RoutingGraphEnv 0.0.1__tar.gz
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.
- routinggraphenv-0.0.1/.github/workflows/publish-pypi.yml +65 -0
- routinggraphenv-0.0.1/.gitignore +179 -0
- routinggraphenv-0.0.1/.pre-commit-config.yaml +11 -0
- routinggraphenv-0.0.1/LICENSE +21 -0
- routinggraphenv-0.0.1/PKG-INFO +78 -0
- routinggraphenv-0.0.1/README.md +54 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/__init__.py +6 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/envs/__init__.py +4 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/envs/openstreetmap_services.py +88 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/envs/routing_graph.py +276 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/wrappers/__init__.py +4 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/wrappers/clip_reward.py +13 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/wrappers/discrete_actions.py +12 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/wrappers/reacher_weighted_reward.py +16 -0
- routinggraphenv-0.0.1/RoutingGraphEnv/wrappers/relative_position.py +12 -0
- routinggraphenv-0.0.1/pyproject.toml +44 -0
- routinggraphenv-0.0.1/requirements.txt +3 -0
- routinggraphenv-0.0.1/test.py +47 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
pull_request:
|
|
5
|
+
branches:
|
|
6
|
+
- main
|
|
7
|
+
types:
|
|
8
|
+
- closed
|
|
9
|
+
|
|
10
|
+
concurrency:
|
|
11
|
+
group: publish-pypi
|
|
12
|
+
cancel-in-progress: false
|
|
13
|
+
|
|
14
|
+
jobs:
|
|
15
|
+
build:
|
|
16
|
+
if: github.event.pull_request.merged == true
|
|
17
|
+
runs-on: ubuntu-latest
|
|
18
|
+
permissions:
|
|
19
|
+
contents: read
|
|
20
|
+
|
|
21
|
+
steps:
|
|
22
|
+
- name: Check out merged commit
|
|
23
|
+
uses: actions/checkout@v4
|
|
24
|
+
with:
|
|
25
|
+
ref: ${{ github.event.pull_request.merge_commit_sha }}
|
|
26
|
+
|
|
27
|
+
- name: Set up Python
|
|
28
|
+
uses: actions/setup-python@v5
|
|
29
|
+
with:
|
|
30
|
+
python-version: "3.12"
|
|
31
|
+
|
|
32
|
+
- name: Install build tools
|
|
33
|
+
run: python -m pip install --upgrade build twine
|
|
34
|
+
|
|
35
|
+
- name: Build distributions
|
|
36
|
+
run: python -m build
|
|
37
|
+
|
|
38
|
+
- name: Check distributions
|
|
39
|
+
run: python -m twine check dist/*
|
|
40
|
+
|
|
41
|
+
- name: Upload distributions
|
|
42
|
+
uses: actions/upload-artifact@v4
|
|
43
|
+
with:
|
|
44
|
+
name: python-distributions
|
|
45
|
+
path: dist/
|
|
46
|
+
if-no-files-found: error
|
|
47
|
+
|
|
48
|
+
publish:
|
|
49
|
+
needs: build
|
|
50
|
+
runs-on: ubuntu-latest
|
|
51
|
+
environment:
|
|
52
|
+
name: pypi
|
|
53
|
+
url: https://pypi.org/p/RoutingGraphEnv
|
|
54
|
+
permissions:
|
|
55
|
+
id-token: write
|
|
56
|
+
|
|
57
|
+
steps:
|
|
58
|
+
- name: Download distributions
|
|
59
|
+
uses: actions/download-artifact@v4
|
|
60
|
+
with:
|
|
61
|
+
name: python-distributions
|
|
62
|
+
path: dist/
|
|
63
|
+
|
|
64
|
+
- name: Publish distributions to PyPI
|
|
65
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# Created by https://www.toptal.com/developers/gitignore/api/python
|
|
2
|
+
# Edit at https://www.toptal.com/developers/gitignore?templates=python
|
|
3
|
+
|
|
4
|
+
### Python ###
|
|
5
|
+
# Byte-compiled / optimized / DLL files
|
|
6
|
+
__pycache__/
|
|
7
|
+
*.py[cod]
|
|
8
|
+
*$py.class
|
|
9
|
+
|
|
10
|
+
# C extensions
|
|
11
|
+
*.so
|
|
12
|
+
|
|
13
|
+
# Distribution / packaging
|
|
14
|
+
.Python
|
|
15
|
+
build/
|
|
16
|
+
develop-eggs/
|
|
17
|
+
dist/
|
|
18
|
+
downloads/
|
|
19
|
+
eggs/
|
|
20
|
+
.eggs/
|
|
21
|
+
lib/
|
|
22
|
+
lib64/
|
|
23
|
+
parts/
|
|
24
|
+
sdist/
|
|
25
|
+
var/
|
|
26
|
+
wheels/
|
|
27
|
+
share/python-wheels/
|
|
28
|
+
*.egg-info/
|
|
29
|
+
.installed.cfg
|
|
30
|
+
*.egg
|
|
31
|
+
MANIFEST
|
|
32
|
+
|
|
33
|
+
# PyInstaller
|
|
34
|
+
# Usually these files are written by a python script from a template
|
|
35
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
36
|
+
*.manifest
|
|
37
|
+
*.spec
|
|
38
|
+
|
|
39
|
+
# Installer logs
|
|
40
|
+
pip-log.txt
|
|
41
|
+
pip-delete-this-directory.txt
|
|
42
|
+
|
|
43
|
+
# Unit test / coverage reports
|
|
44
|
+
htmlcov/
|
|
45
|
+
.tox/
|
|
46
|
+
.nox/
|
|
47
|
+
.coverage
|
|
48
|
+
.coverage.*
|
|
49
|
+
.cache
|
|
50
|
+
nosetests.xml
|
|
51
|
+
coverage.xml
|
|
52
|
+
*.cover
|
|
53
|
+
*.py,cover
|
|
54
|
+
.hypothesis/
|
|
55
|
+
.pytest_cache/
|
|
56
|
+
cover/
|
|
57
|
+
|
|
58
|
+
# Translations
|
|
59
|
+
*.mo
|
|
60
|
+
*.pot
|
|
61
|
+
|
|
62
|
+
# Django stuff:
|
|
63
|
+
*.log
|
|
64
|
+
local_settings.py
|
|
65
|
+
db.sqlite3
|
|
66
|
+
db.sqlite3-journal
|
|
67
|
+
|
|
68
|
+
# Flask stuff:
|
|
69
|
+
instance/
|
|
70
|
+
.webassets-cache
|
|
71
|
+
|
|
72
|
+
# Scrapy stuff:
|
|
73
|
+
.scrapy
|
|
74
|
+
|
|
75
|
+
# Sphinx documentation
|
|
76
|
+
docs/_build/
|
|
77
|
+
|
|
78
|
+
# PyBuilder
|
|
79
|
+
.pybuilder/
|
|
80
|
+
target/
|
|
81
|
+
|
|
82
|
+
# Jupyter Notebook
|
|
83
|
+
.ipynb_checkpoints
|
|
84
|
+
|
|
85
|
+
# IPython
|
|
86
|
+
profile_default/
|
|
87
|
+
ipython_config.py
|
|
88
|
+
|
|
89
|
+
# pyenv
|
|
90
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
91
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
92
|
+
# .python-version
|
|
93
|
+
|
|
94
|
+
# pipenv
|
|
95
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
96
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
97
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
98
|
+
# install all needed dependencies.
|
|
99
|
+
#Pipfile.lock
|
|
100
|
+
|
|
101
|
+
# poetry
|
|
102
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
103
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
104
|
+
# commonly ignored for libraries.
|
|
105
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
106
|
+
#poetry.lock
|
|
107
|
+
|
|
108
|
+
# pdm
|
|
109
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
110
|
+
#pdm.lock
|
|
111
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
112
|
+
# in version control.
|
|
113
|
+
# https://pdm.fming.dev/#use-with-ide
|
|
114
|
+
.pdm.toml
|
|
115
|
+
|
|
116
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
117
|
+
__pypackages__/
|
|
118
|
+
|
|
119
|
+
# Celery stuff
|
|
120
|
+
celerybeat-schedule
|
|
121
|
+
celerybeat.pid
|
|
122
|
+
|
|
123
|
+
# SageMath parsed files
|
|
124
|
+
*.sage.py
|
|
125
|
+
|
|
126
|
+
# Environments
|
|
127
|
+
.env
|
|
128
|
+
.venv
|
|
129
|
+
env/
|
|
130
|
+
venv/
|
|
131
|
+
ENV/
|
|
132
|
+
env.bak/
|
|
133
|
+
venv.bak/
|
|
134
|
+
|
|
135
|
+
# Spyder project settings
|
|
136
|
+
.spyderproject
|
|
137
|
+
.spyproject
|
|
138
|
+
|
|
139
|
+
# Rope project settings
|
|
140
|
+
.ropeproject
|
|
141
|
+
|
|
142
|
+
# mkdocs documentation
|
|
143
|
+
/site
|
|
144
|
+
|
|
145
|
+
# mypy
|
|
146
|
+
.mypy_cache/
|
|
147
|
+
.dmypy.json
|
|
148
|
+
dmypy.json
|
|
149
|
+
|
|
150
|
+
# Pyre type checker
|
|
151
|
+
.pyre/
|
|
152
|
+
|
|
153
|
+
# pytype static type analyzer
|
|
154
|
+
.pytype/
|
|
155
|
+
|
|
156
|
+
# Cython debug symbols
|
|
157
|
+
cython_debug/
|
|
158
|
+
|
|
159
|
+
# PyCharm
|
|
160
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
161
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
162
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
163
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
164
|
+
#.idea/
|
|
165
|
+
|
|
166
|
+
### Python Patch ###
|
|
167
|
+
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
|
168
|
+
poetry.toml
|
|
169
|
+
|
|
170
|
+
# ruff
|
|
171
|
+
.ruff_cache/
|
|
172
|
+
|
|
173
|
+
# LSP config files
|
|
174
|
+
pyrightconfig.json
|
|
175
|
+
|
|
176
|
+
# End of https://www.toptal.com/developers/gitignore/api/python
|
|
177
|
+
|
|
178
|
+
cache/
|
|
179
|
+
|
|
@@ -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.
|
|
@@ -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,54 @@
|
|
|
1
|
+
# Gymnasium Examples
|
|
2
|
+
Some simple examples of Gymnasium environments and wrappers.
|
|
3
|
+
For some explanations of these examples, see the [Gymnasium documentation](https://gymnasium.farama.org).
|
|
4
|
+
|
|
5
|
+
### Environments
|
|
6
|
+
This repository hosts the examples that are shown [on the environment creation documentation](https://gymnasium.farama.org/tutorials/gymnasium_basics/environment_creation/).
|
|
7
|
+
- `GridWorldEnv`: Simplistic implementation of gridworld environment
|
|
8
|
+
|
|
9
|
+
### Wrappers
|
|
10
|
+
This repository hosts the examples that are shown [on wrapper documentation](https://gymnasium.farama.org/api/wrappers/).
|
|
11
|
+
- `ClipReward`: A `RewardWrapper` that clips immediate rewards to a valid range
|
|
12
|
+
- `DiscreteActions`: An `ActionWrapper` that restricts the action space to a finite subset
|
|
13
|
+
- `RelativePosition`: An `ObservationWrapper` that computes the relative position between an agent and a target
|
|
14
|
+
- `ReacherRewardWrapper`: Allow us to weight the reward terms for the reacher environment
|
|
15
|
+
|
|
16
|
+
### Contributing
|
|
17
|
+
If you would like to contribute, follow these steps:
|
|
18
|
+
- Fork this repository
|
|
19
|
+
- Clone your fork
|
|
20
|
+
- Set up pre-commit via `pre-commit install`
|
|
21
|
+
|
|
22
|
+
PRs may require accompanying PRs in [the documentation repo](https://github.com/Farama-Foundation/Gymnasium/tree/main/docs).
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
To install your new environment, run the following commands:
|
|
28
|
+
|
|
29
|
+
```{shell}
|
|
30
|
+
cd RoutingGraphEnv
|
|
31
|
+
pip install -e .
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Upload to pypi.org
|
|
35
|
+
|
|
36
|
+
Chạy tại thư mục project:
|
|
37
|
+
|
|
38
|
+
```shell
|
|
39
|
+
python3 -m build
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Lệnh sẽ tạo thư mục `dist/` chứa file `.whl` và `.tar.gz`.
|
|
43
|
+
|
|
44
|
+
Nếu chưa có module `build`:
|
|
45
|
+
|
|
46
|
+
```shell
|
|
47
|
+
python3 -m pip install build
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Sau đó:
|
|
51
|
+
|
|
52
|
+
```shell
|
|
53
|
+
python3 -m twine upload dist/*
|
|
54
|
+
```
|
|
@@ -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,44 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[tool.hatch.build.targets.wheel]
|
|
6
|
+
packages = ["RoutingGraphEnv"]
|
|
7
|
+
|
|
8
|
+
[project]
|
|
9
|
+
name = "RoutingGraphEnv"
|
|
10
|
+
version = "0.0.1"
|
|
11
|
+
description = "A Gymnasium environment for route optimization on OpenStreetMap road networks"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.11"
|
|
14
|
+
license = "MIT"
|
|
15
|
+
license-files = ["LICENSE"]
|
|
16
|
+
authors = [
|
|
17
|
+
{ name = "Trương Hải Đăng" },
|
|
18
|
+
]
|
|
19
|
+
keywords = [
|
|
20
|
+
"gymnasium",
|
|
21
|
+
"openstreetmap",
|
|
22
|
+
"reinforcement-learning",
|
|
23
|
+
"route-optimization",
|
|
24
|
+
"routing",
|
|
25
|
+
]
|
|
26
|
+
classifiers = [
|
|
27
|
+
"Development Status :: 3 - Alpha",
|
|
28
|
+
"Intended Audience :: Developers",
|
|
29
|
+
"Intended Audience :: Science/Research",
|
|
30
|
+
"Operating System :: OS Independent",
|
|
31
|
+
"Programming Language :: Python :: 3",
|
|
32
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
33
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
34
|
+
]
|
|
35
|
+
dependencies = [
|
|
36
|
+
"gymnasium",
|
|
37
|
+
"osmnx",
|
|
38
|
+
"pygame>=2.1.3",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://github.com/TruongHaiDang/routing-graph"
|
|
43
|
+
Repository = "https://github.com/TruongHaiDang/routing-graph.git"
|
|
44
|
+
Issues = "https://github.com/TruongHaiDang/routing-graph/issues"
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import gymnasium as gym
|
|
2
|
+
import RoutingGraphEnv # Registers the environment with Gymnasium.
|
|
3
|
+
from time import sleep
|
|
4
|
+
from pprint import pprint
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
env = gym.make(
|
|
8
|
+
"RoutingGraphEnv/RoutingGraph-v0",
|
|
9
|
+
place_name="Tan Binh District, Ho Chi Minh City, Vietnam",
|
|
10
|
+
num_nodes=10,
|
|
11
|
+
render_mode="human"
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
observation, info = env.reset(seed=42)
|
|
15
|
+
|
|
16
|
+
terminated = False
|
|
17
|
+
truncated = False
|
|
18
|
+
|
|
19
|
+
while not terminated and not truncated:
|
|
20
|
+
action = env.action_space.sample(mask=env.unwrapped.action_masks())
|
|
21
|
+
|
|
22
|
+
observation, reward, terminated, truncated, info = env.step(action)
|
|
23
|
+
print("observation")
|
|
24
|
+
pprint(observation)
|
|
25
|
+
print("reward")
|
|
26
|
+
pprint(reward)
|
|
27
|
+
print("terminated")
|
|
28
|
+
pprint(terminated)
|
|
29
|
+
print("truncated")
|
|
30
|
+
pprint(truncated)
|
|
31
|
+
print("info")
|
|
32
|
+
pprint(info)
|
|
33
|
+
|
|
34
|
+
print(
|
|
35
|
+
{
|
|
36
|
+
"action": action,
|
|
37
|
+
"reward": reward,
|
|
38
|
+
"terminated": terminated,
|
|
39
|
+
"truncated": truncated,
|
|
40
|
+
"observation": observation,
|
|
41
|
+
"info": info,
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
print("-"*100)
|
|
45
|
+
sleep(1)
|
|
46
|
+
|
|
47
|
+
env.close()
|