RoutingGraphEnv 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ from gymnasium.envs.registration import register
2
+
3
+ register(
4
+ id="RoutingGraphEnv/RoutingGraph-v0",
5
+ entry_point="RoutingGraphEnv.envs:RoutingGraphEnv",
6
+ )
@@ -0,0 +1,4 @@
1
+ from RoutingGraphEnv.envs.openstreetmap_services import OpenStreetMapService
2
+ from RoutingGraphEnv.envs.routing_graph import RoutingGraphEnv
3
+
4
+ __all__ = ["OpenStreetMapService", "RoutingGraphEnv"]
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+
5
+ import networkx as nx
6
+ import numpy as np
7
+ import osmnx as ox
8
+ from networkx import MultiDiGraph
9
+
10
+
11
+ class OpenStreetMapService:
12
+ """Load road networks and select reproducible routing nodes."""
13
+
14
+ @staticmethod
15
+ def load_drive_graph(
16
+ place_name: str,
17
+ simplify: bool = True,
18
+ ) -> MultiDiGraph:
19
+ graph = ox.graph_from_place(
20
+ place_name,
21
+ network_type="drive",
22
+ simplify=simplify,
23
+ )
24
+
25
+ return ox.truncate.largest_component(
26
+ graph,
27
+ strongly=True,
28
+ )
29
+
30
+ @staticmethod
31
+ def generate_random_road_nodes(
32
+ graph: MultiDiGraph,
33
+ count: int,
34
+ seed: int | None = None,
35
+ ) -> list[dict]:
36
+ if count < 2:
37
+ raise ValueError("count must be at least 2")
38
+
39
+ node_ids = list(graph.nodes)
40
+ if count > len(node_ids):
41
+ raise ValueError(
42
+ f"Requested {count} nodes but graph only has {len(node_ids)} nodes."
43
+ )
44
+
45
+ selected = random.Random(seed).sample(node_ids, count)
46
+ return [
47
+ {
48
+ "id": index,
49
+ "osm_node_id": node_id,
50
+ "latitude": graph.nodes[node_id]["y"],
51
+ "longitude": graph.nodes[node_id]["x"],
52
+ }
53
+ for index, node_id in enumerate(selected)
54
+ ]
55
+
56
+ @classmethod
57
+ def generate_random_points_on_roads(
58
+ cls,
59
+ place_name: str,
60
+ count: int,
61
+ seed: int | None = None,
62
+ ) -> tuple[MultiDiGraph, list[dict]]:
63
+ graph = cls.load_drive_graph(place_name)
64
+ return graph, cls.generate_random_road_nodes(graph, count, seed)
65
+
66
+ @staticmethod
67
+ def distance_matrix(
68
+ graph: MultiDiGraph,
69
+ nodes: list[dict],
70
+ ) -> np.ndarray:
71
+ """Compute selected-node distances with one Dijkstra run per source."""
72
+ node_ids = [node["osm_node_id"] for node in nodes]
73
+ matrix = np.full((len(node_ids), len(node_ids)), np.inf, dtype=np.float32)
74
+ np.fill_diagonal(matrix, 0.0)
75
+
76
+ for source_index, source_id in enumerate(node_ids):
77
+ lengths = nx.single_source_dijkstra_path_length(
78
+ graph,
79
+ source_id,
80
+ weight="length",
81
+ )
82
+ for target_index, target_id in enumerate(node_ids):
83
+ if source_index != target_index:
84
+ matrix[source_index, target_index] = lengths.get(
85
+ target_id, float("inf")
86
+ )
87
+
88
+ return matrix
@@ -0,0 +1,276 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import gymnasium as gym
6
+ import numpy as np
7
+ from gymnasium import spaces
8
+ from networkx import MultiDiGraph
9
+
10
+ from RoutingGraphEnv.envs.openstreetmap_services import OpenStreetMapService
11
+
12
+
13
+ class RoutingGraphEnv(gym.Env):
14
+ """Gymnasium environment for finding a short round trip through road nodes."""
15
+
16
+ metadata = {"render_modes": ["human", "rgb_array"], "render_fps": 4}
17
+
18
+ def __init__(
19
+ self,
20
+ render_mode: str | None = None,
21
+ num_nodes: int = 5,
22
+ place_name: str = "Tan Binh District, Ho Chi Minh City, Vietnam",
23
+ graph: MultiDiGraph | None = None,
24
+ nodes: list[dict[str, Any]] | None = None,
25
+ ) -> None:
26
+ if num_nodes < 2:
27
+ raise ValueError("num_nodes must be at least 2")
28
+ if render_mode not in (None, *self.metadata["render_modes"]):
29
+ raise ValueError(f"Unsupported render mode: {render_mode}")
30
+ if (graph is None) != (nodes is None):
31
+ raise ValueError("graph and nodes must be provided together")
32
+
33
+ self.render_mode = render_mode
34
+ self.num_nodes = num_nodes
35
+ self.place_name = place_name
36
+ self.window_size = 720
37
+ self.window = None
38
+ self.clock = None
39
+ self._render_font = None
40
+ self._render_small_font = None
41
+
42
+ if graph is None:
43
+ graph, nodes = OpenStreetMapService.generate_random_points_on_roads(
44
+ place_name=place_name,
45
+ count=num_nodes,
46
+ seed=42,
47
+ )
48
+ elif len(nodes) != num_nodes:
49
+ raise ValueError("len(nodes) must equal num_nodes")
50
+
51
+ self.graph = graph
52
+ self.nodes = nodes
53
+ self.distance_matrix = OpenStreetMapService.distance_matrix(graph, nodes)
54
+ if not np.isfinite(self.distance_matrix).all():
55
+ raise ValueError("Selected road nodes are not mutually reachable")
56
+
57
+ self.observation_space = spaces.Dict(
58
+ {
59
+ "visit_order": spaces.Box(
60
+ low=-1,
61
+ high=num_nodes - 1,
62
+ shape=(num_nodes,),
63
+ dtype=np.int32,
64
+ ),
65
+ "visited": spaces.MultiBinary(num_nodes),
66
+ "current_node": spaces.Discrete(num_nodes),
67
+ }
68
+ )
69
+ self.action_space = spaces.Discrete(num_nodes)
70
+
71
+ self._visit_order = np.full(num_nodes, -1, dtype=np.int32)
72
+ self._visited = np.zeros(num_nodes, dtype=np.int8)
73
+ self._current_node = 0
74
+ self._step_count = 0
75
+ self._total_distance = 0.0
76
+ self._render_positions: np.ndarray | None = None
77
+
78
+ def _get_obs(self) -> dict[str, np.ndarray | int]:
79
+ return {
80
+ "visit_order": self._visit_order.copy(),
81
+ "visited": self._visited.copy(),
82
+ "current_node": self._current_node,
83
+ }
84
+
85
+ def _get_info(self) -> dict[str, float]:
86
+ return {"total_distance": self._total_distance}
87
+
88
+ def action_masks(self) -> np.ndarray:
89
+ return np.logical_not(self._visited).astype(dtype=np.int8)
90
+
91
+ def reset(
92
+ self,
93
+ seed: int | None = None,
94
+ options: dict[str, Any] | None = None,
95
+ ) -> tuple[dict[str, np.ndarray | int], dict[str, float]]:
96
+ super().reset(seed=seed)
97
+ start_node = 0 if options is None else int(options.get("start_node", 0))
98
+ if not self.action_space.contains(start_node):
99
+ raise ValueError("start_node is outside the action space")
100
+
101
+ self._visit_order.fill(-1)
102
+ self._visited.fill(0)
103
+ self._visit_order[0] = start_node
104
+ self._visited[start_node] = 1
105
+ self._current_node = start_node
106
+ self._step_count = 1
107
+ self._total_distance = 0.0
108
+
109
+ if self.render_mode == "human":
110
+ self._render_frame()
111
+ return self._get_obs(), self._get_info()
112
+
113
+ def step(
114
+ self,
115
+ action: int,
116
+ ) -> tuple[dict[str, np.ndarray | int], float, bool, bool, dict[str, float]]:
117
+ if not self.action_space.contains(action):
118
+ raise ValueError(f"Invalid action: {action}")
119
+ action = int(action)
120
+ if self._visited[action]:
121
+ return self._get_obs(), -1.0, False, False, {
122
+ **self._get_info(),
123
+ "invalid_action": True,
124
+ }
125
+
126
+ distance = float(self.distance_matrix[self._current_node, action])
127
+ self._total_distance += distance
128
+ self._current_node = action
129
+ self._visit_order[self._step_count] = action
130
+ self._visited[action] = 1
131
+ self._step_count += 1
132
+
133
+ terminated = self._step_count == self.num_nodes
134
+ if terminated:
135
+ return_distance = float(self.distance_matrix[action, self._visit_order[0]])
136
+ distance += return_distance
137
+ self._total_distance += return_distance
138
+
139
+ if self.render_mode == "human":
140
+ self._render_frame()
141
+ return self._get_obs(), -distance, terminated, False, self._get_info()
142
+
143
+ def render(self) -> np.ndarray | None:
144
+ if self.render_mode == "rgb_array":
145
+ return self._render_frame()
146
+ return None
147
+
148
+ def _render_frame(self) -> np.ndarray | None:
149
+ import pygame
150
+ import pygame._freetype as freetype
151
+
152
+ if self.window is None and self.render_mode == "human":
153
+ pygame.init()
154
+ pygame.display.init()
155
+ self.window = pygame.display.set_mode((self.window_size, self.window_size))
156
+ pygame.display.set_caption("Routing Graph Environment")
157
+ self.clock = pygame.time.Clock()
158
+ if not freetype.get_init():
159
+ freetype.init()
160
+ if self._render_font is None:
161
+ self._render_font = freetype.Font(None, 22)
162
+ self._render_small_font = freetype.Font(None, 16)
163
+
164
+ canvas = pygame.Surface((self.window_size, self.window_size))
165
+ canvas.fill((238, 242, 247))
166
+
167
+ map_rect = pygame.Rect(28, 92, self.window_size - 56, self.window_size - 156)
168
+ pygame.draw.rect(canvas, (220, 231, 220), map_rect, border_radius=18)
169
+ pygame.draw.rect(canvas, (133, 158, 136), map_rect, width=2, border_radius=18)
170
+
171
+ title = self._render_font.render(self.place_name, (30, 41, 59))[0]
172
+ canvas.blit(title, (28, 22))
173
+ status = self._render_small_font.render(
174
+ f"Visited: {self._step_count}/{self.num_nodes} "
175
+ f"Distance: {self._total_distance / 1000:.2f} km",
176
+ (71, 85, 105),
177
+ )[0]
178
+ canvas.blit(status, (28, 56))
179
+
180
+ if self._render_positions is None:
181
+ coordinates = np.asarray(
182
+ [[node["longitude"], node["latitude"]] for node in self.nodes],
183
+ dtype=np.float64,
184
+ )
185
+ minimum = coordinates.min(axis=0)
186
+ span = np.maximum(coordinates.max(axis=0) - minimum, 1e-12)
187
+ inner_margin = 46
188
+ self._render_positions = (
189
+ np.asarray([map_rect.left, map_rect.top])
190
+ + inner_margin
191
+ + (coordinates - minimum)
192
+ / span
193
+ * np.asarray(
194
+ [
195
+ map_rect.width - 2 * inner_margin,
196
+ map_rect.height - 2 * inner_margin,
197
+ ]
198
+ )
199
+ )
200
+ self._render_positions[:, 1] = map_rect.bottom - (
201
+ self._render_positions[:, 1] - map_rect.top
202
+ )
203
+ positions = self._render_positions
204
+
205
+ visited = self._visit_order[: self._step_count]
206
+ for source, target in zip(visited, visited[1:]):
207
+ pygame.draw.line(
208
+ canvas,
209
+ (45, 108, 223),
210
+ positions[source],
211
+ positions[target],
212
+ 5,
213
+ )
214
+ if self._step_count == self.num_nodes:
215
+ pygame.draw.line(
216
+ canvas,
217
+ (45, 108, 223),
218
+ positions[visited[-1]],
219
+ positions[visited[0]],
220
+ 5,
221
+ )
222
+
223
+ for index, position in enumerate(positions):
224
+ if index == self._current_node:
225
+ color = (245, 158, 11)
226
+ radius = 16
227
+ elif index == visited[0]:
228
+ color = (22, 163, 74)
229
+ radius = 14
230
+ elif self._visited[index]:
231
+ color = (45, 108, 223)
232
+ radius = 13
233
+ else:
234
+ color = (255, 255, 255)
235
+ radius = 13
236
+
237
+ pygame.draw.circle(canvas, (255, 255, 255), position, radius + 4)
238
+ pygame.draw.circle(canvas, color, position, radius)
239
+ pygame.draw.circle(canvas, (55, 65, 81), position, radius, width=2)
240
+ label_color = (255, 255, 255) if self._visited[index] else (55, 65, 81)
241
+ label = self._render_small_font.render(str(index), label_color)[0]
242
+ canvas.blit(label, label.get_rect(center=position))
243
+
244
+ legend_y = self.window_size - 42
245
+ legend_items = (
246
+ ((22, 163, 74), "Start"),
247
+ ((245, 158, 11), "Current"),
248
+ ((45, 108, 223), "Visited"),
249
+ ((255, 255, 255), "Unvisited"),
250
+ )
251
+ legend_x = 28
252
+ for color, text in legend_items:
253
+ pygame.draw.circle(canvas, color, (legend_x + 7, legend_y), 7)
254
+ pygame.draw.circle(canvas, (55, 65, 81), (legend_x + 7, legend_y), 7, 1)
255
+ legend = self._render_small_font.render(text, (55, 65, 81))[0]
256
+ canvas.blit(legend, (legend_x + 19, legend_y - 9))
257
+ legend_x += legend.get_width() + 48
258
+
259
+ if self.render_mode == "human":
260
+ self.window.blit(canvas, (0, 0))
261
+ pygame.event.pump()
262
+ pygame.display.update()
263
+ self.clock.tick(self.metadata["render_fps"])
264
+ return None
265
+ return np.transpose(pygame.surfarray.array3d(canvas), (1, 0, 2))
266
+
267
+ def close(self) -> None:
268
+ if self.window is not None:
269
+ import pygame
270
+
271
+ pygame.display.quit()
272
+ pygame.quit()
273
+ self.window = None
274
+ self.clock = None
275
+ self._render_font = None
276
+ self._render_small_font = None
@@ -0,0 +1,4 @@
1
+ from RoutingGraphEnv.wrappers.clip_reward import ClipReward
2
+ from RoutingGraphEnv.wrappers.discrete_actions import DiscreteActions
3
+ from RoutingGraphEnv.wrappers.reacher_weighted_reward import ReacherRewardWrapper
4
+ from RoutingGraphEnv.wrappers.relative_position import RelativePosition
@@ -0,0 +1,13 @@
1
+ import gymnasium as gym
2
+ import numpy as np
3
+
4
+
5
+ class ClipReward(gym.RewardWrapper):
6
+ def __init__(self, env, min_reward, max_reward):
7
+ super().__init__(env)
8
+ self.min_reward = min_reward
9
+ self.max_reward = max_reward
10
+ self.reward_range = (min_reward, max_reward)
11
+
12
+ def reward(self, reward):
13
+ return np.clip(reward, self.min_reward, self.max_reward)
@@ -0,0 +1,12 @@
1
+ import gymnasium as gym
2
+ from gymnasium.spaces import Discrete
3
+
4
+
5
+ class DiscreteActions(gym.ActionWrapper):
6
+ def __init__(self, env, disc_to_cont):
7
+ super().__init__(env)
8
+ self.disc_to_cont = disc_to_cont
9
+ self.action_space = Discrete(len(disc_to_cont))
10
+
11
+ def action(self, act):
12
+ return self.disc_to_cont[act]
@@ -0,0 +1,16 @@
1
+ import gymnasium as gym
2
+
3
+
4
+ class ReacherRewardWrapper(gym.Wrapper):
5
+ def __init__(self, env, reward_dist_weight, reward_ctrl_weight):
6
+ super().__init__(env)
7
+ self.reward_dist_weight = reward_dist_weight
8
+ self.reward_ctrl_weight = reward_ctrl_weight
9
+
10
+ def step(self, action):
11
+ obs, _, terminated, truncated, info = self.env.step(action)
12
+ reward = (
13
+ self.reward_dist_weight * info["reward_dist"]
14
+ + self.reward_ctrl_weight * info["reward_ctrl"]
15
+ )
16
+ return obs, reward, terminated, truncated, info
@@ -0,0 +1,12 @@
1
+ import gymnasium as gym
2
+ from gymnasium.spaces import Box
3
+ import numpy as np
4
+
5
+
6
+ class RelativePosition(gym.ObservationWrapper):
7
+ def __init__(self, env):
8
+ super().__init__(env)
9
+ self.observation_space = Box(shape=(2,), low=-np.inf, high=np.inf)
10
+
11
+ def observation(self, obs):
12
+ return obs["target"] - obs["agent"]
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: RoutingGraphEnv
3
+ Version: 0.0.1
4
+ Summary: A Gymnasium environment for route optimization on OpenStreetMap road networks
5
+ Project-URL: Homepage, https://github.com/TruongHaiDang/routing-graph
6
+ Project-URL: Repository, https://github.com/TruongHaiDang/routing-graph.git
7
+ Project-URL: Issues, https://github.com/TruongHaiDang/routing-graph/issues
8
+ Author: Trương Hải Đăng
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: gymnasium,openstreetmap,reinforcement-learning,route-optimization,routing
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: gymnasium
21
+ Requires-Dist: osmnx
22
+ Requires-Dist: pygame>=2.1.3
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Gymnasium Examples
26
+ Some simple examples of Gymnasium environments and wrappers.
27
+ For some explanations of these examples, see the [Gymnasium documentation](https://gymnasium.farama.org).
28
+
29
+ ### Environments
30
+ This repository hosts the examples that are shown [on the environment creation documentation](https://gymnasium.farama.org/tutorials/gymnasium_basics/environment_creation/).
31
+ - `GridWorldEnv`: Simplistic implementation of gridworld environment
32
+
33
+ ### Wrappers
34
+ This repository hosts the examples that are shown [on wrapper documentation](https://gymnasium.farama.org/api/wrappers/).
35
+ - `ClipReward`: A `RewardWrapper` that clips immediate rewards to a valid range
36
+ - `DiscreteActions`: An `ActionWrapper` that restricts the action space to a finite subset
37
+ - `RelativePosition`: An `ObservationWrapper` that computes the relative position between an agent and a target
38
+ - `ReacherRewardWrapper`: Allow us to weight the reward terms for the reacher environment
39
+
40
+ ### Contributing
41
+ If you would like to contribute, follow these steps:
42
+ - Fork this repository
43
+ - Clone your fork
44
+ - Set up pre-commit via `pre-commit install`
45
+
46
+ PRs may require accompanying PRs in [the documentation repo](https://github.com/Farama-Foundation/Gymnasium/tree/main/docs).
47
+
48
+
49
+ ## Installation
50
+
51
+ To install your new environment, run the following commands:
52
+
53
+ ```{shell}
54
+ cd RoutingGraphEnv
55
+ pip install -e .
56
+ ```
57
+
58
+ ## Upload to pypi.org
59
+
60
+ Chạy tại thư mục project:
61
+
62
+ ```shell
63
+ python3 -m build
64
+ ```
65
+
66
+ Lệnh sẽ tạo thư mục `dist/` chứa file `.whl` và `.tar.gz`.
67
+
68
+ Nếu chưa có module `build`:
69
+
70
+ ```shell
71
+ python3 -m pip install build
72
+ ```
73
+
74
+ Sau đó:
75
+
76
+ ```shell
77
+ python3 -m twine upload dist/*
78
+ ```
@@ -0,0 +1,13 @@
1
+ RoutingGraphEnv/__init__.py,sha256=KgF0s__Vh2csHg35E9IYPJ1UIQKSrmA94Xn-UYdFUwk,160
2
+ RoutingGraphEnv/envs/__init__.py,sha256=v8G1BgOS-ofiUYGS8LqRDHh93D0EpJwMcsJgrVpahyc,195
3
+ RoutingGraphEnv/envs/openstreetmap_services.py,sha256=4UKyNbLnx3L6ko9LWFQ9P-tCgeKOaAtoVM9RjKsBtAA,2587
4
+ RoutingGraphEnv/envs/routing_graph.py,sha256=3nPNNP9QqEJtGIHsIqlxsuX6CzYvOBjUpOjGd8ZcNiI,10240
5
+ RoutingGraphEnv/wrappers/__init__.py,sha256=3PYxSCZ4lH1hzJfYrKTmoGUUBrIo7bVCTL7EncazT94,284
6
+ RoutingGraphEnv/wrappers/clip_reward.py,sha256=bzJ1-WQMEHnmJomeIHA6Hp6gJ7Z2Gzob8VKanmo5B5w,388
7
+ RoutingGraphEnv/wrappers/discrete_actions.py,sha256=da-6KuUtACdmF9JZHQNw60Y5pIoNl7c8WddW32zQTTI,342
8
+ RoutingGraphEnv/wrappers/reacher_weighted_reward.py,sha256=Nz0dz6a7s33fiVjbJ1p-i0Gz7SlOlIWsmsH0REwqdOk,572
9
+ RoutingGraphEnv/wrappers/relative_position.py,sha256=woiefV57IiBCGnTZ2zD30gnZw_mLmJJ-EdUEFybvwmI,337
10
+ routinggraphenv-0.0.1.dist-info/METADATA,sha256=66hDMq-y5lxeOPqahppgfVYkP1vDfMt8Q26QIQ_6t0g,2692
11
+ routinggraphenv-0.0.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
12
+ routinggraphenv-0.0.1.dist-info/licenses/LICENSE,sha256=_eBqWuxye5a0YySC8StPown-mJRIkM547tf5P_A1T1g,1078
13
+ routinggraphenv-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2023 Farama Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.