|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +import torch |
| 4 | + |
| 5 | +from tensordict.tensordict import TensorDict |
| 6 | +from torchrl.data import ( |
| 7 | + BoundedTensorSpec, |
| 8 | + CompositeSpec, |
| 9 | + UnboundedContinuousTensorSpec, |
| 10 | + UnboundedDiscreteTensorSpec, |
| 11 | +) |
| 12 | + |
| 13 | +from rl4co.envs.common.base import RL4COEnvBase |
| 14 | +from rl4co.utils.ops import gather_by_index, get_tour_length |
| 15 | +from rl4co.utils.pylogger import get_pylogger |
| 16 | + |
| 17 | +from .generator import SHPPGenerator |
| 18 | +from .render import render |
| 19 | + |
| 20 | +log = get_pylogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class SHPPEnv(RL4COEnvBase): |
| 24 | + """ |
| 25 | + Shortest Hamiltonian Path Problem (SHPP) |
| 26 | + SHPP is referred to the open-loop Traveling Salesman Problem (TSP) in the literature. |
| 27 | + The goal of the SHPP is to find the shortest Hamiltonian path in a given graph with |
| 28 | + given fixed starting/terminating nodes (they can be different nodes). A Hamiltonian |
| 29 | + path visits all other nodes exactly once. At each step, the agent chooses a city to visit. |
| 30 | + The reward is 0 unless the agent visits all the cities. In that case, the reward is |
| 31 | + (-)length of the path: maximizing the reward is equivalent to minimizing the path length. |
| 32 | +
|
| 33 | + Observation: |
| 34 | + - locations of each customer |
| 35 | + - starting node and terminating node |
| 36 | + - the current location of the vehicle |
| 37 | +
|
| 38 | + Constraints: |
| 39 | + - the first node is the starting node |
| 40 | + - the last node is the terminating node |
| 41 | + - each node is visited exactly once |
| 42 | +
|
| 43 | + Finish condition: |
| 44 | + - the agent has visited all the customers and reached the terminating node |
| 45 | +
|
| 46 | + Reward: |
| 47 | + - (minus) the length of the path |
| 48 | +
|
| 49 | + Args: |
| 50 | + generator: SHPPGenerator instance as the generator |
| 51 | + generator_params: parameters for the generator |
| 52 | + """ |
| 53 | + |
| 54 | + name = "shpp" |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, |
| 58 | + generator: SHPPGenerator = None, |
| 59 | + generator_params: dict = {}, |
| 60 | + **kwargs, |
| 61 | + ): |
| 62 | + super().__init__(**kwargs) |
| 63 | + if generator is None: |
| 64 | + generator = SHPPGenerator(**generator_params) |
| 65 | + self.generator = generator |
| 66 | + self._make_spec(self.generator) |
| 67 | + |
| 68 | + @staticmethod |
| 69 | + def _step(td: TensorDict) -> TensorDict: |
| 70 | + current_node = td["action"] |
| 71 | + first_node = current_node if td["i"].all() == 0 else td["first_node"] |
| 72 | + |
| 73 | + # Set not visited to 0 (i.e., we visited the node) |
| 74 | + available = td["available"].scatter( |
| 75 | + -1, current_node.unsqueeze(-1).expand_as(td["action_mask"]), 0 |
| 76 | + ) |
| 77 | + |
| 78 | + # If all other nodes are visited, the terminating node will be available |
| 79 | + action_mask = available.clone() |
| 80 | + action_mask[..., -1] = ~available[..., :-1].any(dim=-1) |
| 81 | + |
| 82 | + # We are done there are no unvisited locations |
| 83 | + done = torch.sum(available, dim=-1) == 0 |
| 84 | + |
| 85 | + # The reward is calculated outside via get_reward for efficiency, so we set it to 0 here |
| 86 | + reward = torch.zeros_like(done) |
| 87 | + |
| 88 | + td.update( |
| 89 | + { |
| 90 | + "first_node": first_node, |
| 91 | + "current_node": current_node, |
| 92 | + "i": td["i"] + 1, |
| 93 | + "available": available, |
| 94 | + "action_mask": action_mask, |
| 95 | + "reward": reward, |
| 96 | + "done": done, |
| 97 | + }, |
| 98 | + ) |
| 99 | + return td |
| 100 | + |
| 101 | + def _reset(self, td: Optional[TensorDict] = None, batch_size=None) -> TensorDict: |
| 102 | + """Note: the first node is the starting node; the last node is the terminating node""" |
| 103 | + device = td.device |
| 104 | + locs = td["locs"] |
| 105 | + |
| 106 | + # We do not enforce loading from self for flexibility |
| 107 | + num_loc = locs.shape[-2] |
| 108 | + |
| 109 | + # Other variables |
| 110 | + current_node = torch.zeros((batch_size), dtype=torch.int64, device=device) |
| 111 | + last_node = torch.full( |
| 112 | + (batch_size), num_loc - 1, dtype=torch.int64, device=device |
| 113 | + ) |
| 114 | + available = torch.ones( |
| 115 | + (*batch_size, num_loc), dtype=torch.bool, device=device |
| 116 | + ) # 1 means not visited, i.e. action is allowed |
| 117 | + action_mask = torch.zeros((*batch_size, num_loc), dtype=torch.bool, device=device) |
| 118 | + action_mask[..., 0] = 1 # Only the start point is availabe at the beginning |
| 119 | + i = torch.zeros((*batch_size, 1), dtype=torch.int64, device=device) |
| 120 | + |
| 121 | + return TensorDict( |
| 122 | + { |
| 123 | + "locs": locs, |
| 124 | + "first_node": current_node, |
| 125 | + "last_node": last_node, |
| 126 | + "current_node": current_node, |
| 127 | + "i": i, |
| 128 | + "available": available, |
| 129 | + "action_mask": action_mask, |
| 130 | + "reward": torch.zeros((*batch_size, 1), dtype=torch.float32), |
| 131 | + }, |
| 132 | + batch_size=batch_size, |
| 133 | + ) |
| 134 | + |
| 135 | + def _get_reward(self, td, actions) -> TensorDict: |
| 136 | + # Gather locations in order of tour and return distance between them (i.e., -reward) |
| 137 | + locs_ordered = gather_by_index(td["locs"], actions) |
| 138 | + return -get_tour_length(locs_ordered) |
| 139 | + |
| 140 | + @staticmethod |
| 141 | + def check_solution_validity(td: TensorDict, actions: torch.Tensor): |
| 142 | + """Check that solution is valid: nodes are visited exactly once""" |
| 143 | + assert ( |
| 144 | + torch.arange(actions.size(1), out=actions.data.new()) |
| 145 | + .view(1, -1) |
| 146 | + .expand_as(actions) |
| 147 | + == actions.data.sort(1)[0] |
| 148 | + ).all(), "Invalid tour" |
| 149 | + |
| 150 | + @staticmethod |
| 151 | + def render(td: TensorDict, actions: torch.Tensor = None, ax=None): |
| 152 | + return render(td, actions, ax) |
| 153 | + |
| 154 | + def _make_spec(self, generator): |
| 155 | + """Make the observation and action specs from the parameters""" |
| 156 | + self.observation_spec = CompositeSpec( |
| 157 | + locs=BoundedTensorSpec( |
| 158 | + low=generator.min_loc, |
| 159 | + high=generator.max_loc, |
| 160 | + shape=(generator.num_loc, 2), |
| 161 | + dtype=torch.float32, |
| 162 | + ), |
| 163 | + first_node=UnboundedDiscreteTensorSpec( |
| 164 | + shape=(1), |
| 165 | + dtype=torch.int64, |
| 166 | + ), |
| 167 | + current_node=UnboundedDiscreteTensorSpec( |
| 168 | + shape=(1), |
| 169 | + dtype=torch.int64, |
| 170 | + ), |
| 171 | + i=UnboundedDiscreteTensorSpec( |
| 172 | + shape=(1), |
| 173 | + dtype=torch.int64, |
| 174 | + ), |
| 175 | + action_mask=UnboundedDiscreteTensorSpec( |
| 176 | + shape=(generator.num_loc), |
| 177 | + dtype=torch.bool, |
| 178 | + ), |
| 179 | + shape=(), |
| 180 | + ) |
| 181 | + self.action_spec = BoundedTensorSpec( |
| 182 | + shape=(1,), |
| 183 | + dtype=torch.int64, |
| 184 | + low=0, |
| 185 | + high=generator.num_loc, |
| 186 | + ) |
| 187 | + self.reward_spec = UnboundedContinuousTensorSpec(shape=(1,)) |
| 188 | + self.done_spec = UnboundedDiscreteTensorSpec(shape=(1,), dtype=torch.bool) |
0 commit comments