POPJym 0.1.0__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.
Files changed (55) hide show
  1. popjym-0.1.0/.github/workflows/tests.yml +25 -0
  2. popjym-0.1.0/.gitignore +218 -0
  3. popjym-0.1.0/LICENSE +22 -0
  4. popjym-0.1.0/PKG-INFO +95 -0
  5. popjym-0.1.0/README.md +56 -0
  6. popjym-0.1.0/popjym/__init__.py +41 -0
  7. popjym-0.1.0/popjym/core/__init__.py +27 -0
  8. popjym-0.1.0/popjym/core/deck.py +52 -0
  9. popjym-0.1.0/popjym/core/env.py +99 -0
  10. popjym-0.1.0/popjym/core/maze.py +202 -0
  11. popjym-0.1.0/popjym/core/observability.py +13 -0
  12. popjym-0.1.0/popjym/core/spaces.py +219 -0
  13. popjym-0.1.0/popjym/envs/__init__.py +195 -0
  14. popjym-0.1.0/popjym/envs/autoencode.py +116 -0
  15. popjym-0.1.0/popjym/envs/battleship.py +128 -0
  16. popjym-0.1.0/popjym/envs/concentration.py +158 -0
  17. popjym-0.1.0/popjym/envs/count_recall.py +119 -0
  18. popjym-0.1.0/popjym/envs/higher_lower.py +88 -0
  19. popjym-0.1.0/popjym/envs/labyrinth_escape.py +60 -0
  20. popjym-0.1.0/popjym/envs/labyrinth_explore.py +63 -0
  21. popjym-0.1.0/popjym/envs/minesweeper.py +124 -0
  22. popjym-0.1.0/popjym/envs/multiarmed_bandit.py +75 -0
  23. popjym-0.1.0/popjym/envs/noisy_position_only_cartpole.py +33 -0
  24. popjym-0.1.0/popjym/envs/noisy_position_only_pendulum.py +27 -0
  25. popjym-0.1.0/popjym/envs/position_only_cartpole.py +162 -0
  26. popjym-0.1.0/popjym/envs/position_only_pendulum.py +133 -0
  27. popjym-0.1.0/popjym/envs/repeat_first.py +80 -0
  28. popjym-0.1.0/popjym/envs/repeat_previous.py +99 -0
  29. popjym-0.1.0/popjym/envs/velocity_only_cartpole.py +26 -0
  30. popjym-0.1.0/popjym/registry.py +30 -0
  31. popjym-0.1.0/popjym/wrappers/__init__.py +5 -0
  32. popjym-0.1.0/popjym/wrappers/gymnax.py +190 -0
  33. popjym-0.1.0/pyproject.toml +42 -0
  34. popjym-0.1.0/tests/__init__.py +1 -0
  35. popjym-0.1.0/tests/base_env_test.py +10 -0
  36. popjym-0.1.0/tests/test_autoencode.py +43 -0
  37. popjym-0.1.0/tests/test_battleship.py +22 -0
  38. popjym-0.1.0/tests/test_concentration.py +41 -0
  39. popjym-0.1.0/tests/test_control.py +130 -0
  40. popjym-0.1.0/tests/test_count_recall.py +25 -0
  41. popjym-0.1.0/tests/test_deck.py +14 -0
  42. popjym-0.1.0/tests/test_envs.py +73 -0
  43. popjym-0.1.0/tests/test_gymnax_wrapper.py +90 -0
  44. popjym-0.1.0/tests/test_higher_lower.py +36 -0
  45. popjym-0.1.0/tests/test_jit.py +71 -0
  46. popjym-0.1.0/tests/test_labyrinth_escape.py +53 -0
  47. popjym-0.1.0/tests/test_labyrinth_explore.py +37 -0
  48. popjym-0.1.0/tests/test_maze.py +54 -0
  49. popjym-0.1.0/tests/test_minesweeper.py +21 -0
  50. popjym-0.1.0/tests/test_multiarmed_bandit.py +16 -0
  51. popjym-0.1.0/tests/test_repeat_first.py +20 -0
  52. popjym-0.1.0/tests/test_repeat_previous.py +43 -0
  53. popjym-0.1.0/tests/test_spaces.py +51 -0
  54. popjym-0.1.0/tests/test_upstream_parity.py +243 -0
  55. popjym-0.1.0/uv.lock +2559 -0
@@ -0,0 +1,25 @@
1
+ name: tests
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ pytest:
9
+ runs-on: ubuntu-latest
10
+ strategy:
11
+ matrix:
12
+ dependencies: [core, all]
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: astral-sh/setup-uv@v6
16
+ with:
17
+ enable-cache: true
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.12"
21
+ - if: matrix.dependencies == 'core'
22
+ run: uv sync --locked
23
+ - if: matrix.dependencies == 'all'
24
+ run: uv sync --locked --all-extras
25
+ - run: uv run --no-sync pytest
@@ -0,0 +1,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
popjym-0.1.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zekang Wang and Zhe He
4
+ Copyright (c) 2022 Steven Morad (original POPGym implementation)
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
popjym-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: POPJym
3
+ Version: 0.1.0
4
+ Summary: Pure JAX, JIT-compatible ports of the POPGym environments
5
+ Author: Zekang Wang
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Zekang Wang and Zhe He
9
+ Copyright (c) 2022 Steven Morad (original POPGym implementation)
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ License-File: LICENSE
29
+ Classifier: Development Status :: 3 - Alpha
30
+ Classifier: License :: OSI Approved :: MIT License
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
33
+ Requires-Python: >=3.10
34
+ Requires-Dist: jax>=0.4.30
35
+ Provides-Extra: reference
36
+ Requires-Dist: gymnax>=1.0.0; extra == 'reference'
37
+ Requires-Dist: popgym[navigation]==1.0.7; extra == 'reference'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # POPJym
41
+
42
+ POPJym reimplements the environments from POPGym in pure JAX for experiments on memory in reinforcement learning. It includes 16 task families, each with Easy, Medium, and Hard settings (48 environments). Both `reset` and `step` support `jax.jit` and `jax.vmap`. [Original POPGym implementation](https://github.com/proroklab/popgym/tree/410d5aa626dae8024f498354d8781a0d1870c399)
43
+
44
+ ## Comparison with popjaxrl
45
+
46
+ Chris Lu and colleagues released an earlier JAX implementation of POPGym in popjaxrl. POPJym restores several task rules from the original benchmark. [popjaxrl repository](https://github.com/luchris429/popjaxrl)
47
+
48
+ | Task | Earlier popjaxrl behavior (source) | POPJym behavior |
49
+ | --- | --- | --- |
50
+ | CountRecallEasy | The agent could answer only 0 or 1. [popjaxrl issue #10](https://github.com/luchris429/popjaxrl/issues/10) | The agent can report any count from 0 through 26. |
51
+ | Autoencode | [The agent saw a blank observation for every card during the watch phase.](https://github.com/luchris429/popjaxrl/blob/12e5d42be3a6bde81cce4234f8be4e119e4318b6/envs/environments/popgym_autoencode.py#L71-L77) | The agent sees each suit in order, then recalls the suits in reverse. |
52
+ | RepeatFirstEasy | [A 52-card deck allowed 52 guesses and a perfect return of 52/51.](https://github.com/luchris429/popjaxrl/blob/12e5d42be3a6bde81cce4234f8be4e119e4318b6/envs/environments/popgym_repeat_first.py#L33-L39) | The first card is dealt at reset, leaving 51 guesses and a perfect return of 1. |
53
+ | MineSweeper | [Clearing every safe square in succession left the episode running.](https://github.com/luchris429/popjaxrl/blob/12e5d42be3a6bde81cce4234f8be4e119e4318b6/envs/environments/popgym_minesweeper.py#L39-L53) | Clearing the last safe square ends the episode. |
54
+
55
+ ## Quick start
56
+
57
+ ```bash
58
+ python -m pip install "git+https://github.com/bolt-research/POPJym.git"
59
+ ```
60
+
61
+ ```python
62
+ import jax
63
+ import popjym
64
+
65
+ env = popjym.make("RepeatFirstEasy")
66
+ reset_key, step_key = jax.random.split(jax.random.key(0))
67
+ first_suit, state = env.reset(reset_key)
68
+ obs, state, reward, terminated, truncated, info = jax.jit(env.step)(
69
+ step_key, state, first_suit
70
+ )
71
+ ```
72
+
73
+ ## Citation
74
+
75
+ If you use POPJym in your work, please cite this software and the original POPGym benchmark paper by Morad et al.
76
+
77
+ ```bibtex
78
+ @software{wang2026popjym,
79
+ author = {Wang, Zekang and He, Zhe},
80
+ title = {{POPJym}},
81
+ year = {2026},
82
+ version = {0.1.0},
83
+ url = {https://github.com/bolt-research/POPJym}
84
+ }
85
+ ```
86
+
87
+ ```bibtex
88
+ @inproceedings{morad2023popgym,
89
+ author = {Morad, Steven and Kortvelesy, Ryan and Bettini, Matteo and Liwicki, Stephan and Prorok, Amanda},
90
+ title = {{POPGym}: Benchmarking Partially Observable Reinforcement Learning},
91
+ booktitle = {The Eleventh International Conference on Learning Representations},
92
+ year = {2023},
93
+ url = {https://openreview.net/forum?id=chDrutUTs0K}
94
+ }
95
+ ```
popjym-0.1.0/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # POPJym
2
+
3
+ POPJym reimplements the environments from POPGym in pure JAX for experiments on memory in reinforcement learning. It includes 16 task families, each with Easy, Medium, and Hard settings (48 environments). Both `reset` and `step` support `jax.jit` and `jax.vmap`. [Original POPGym implementation](https://github.com/proroklab/popgym/tree/410d5aa626dae8024f498354d8781a0d1870c399)
4
+
5
+ ## Comparison with popjaxrl
6
+
7
+ Chris Lu and colleagues released an earlier JAX implementation of POPGym in popjaxrl. POPJym restores several task rules from the original benchmark. [popjaxrl repository](https://github.com/luchris429/popjaxrl)
8
+
9
+ | Task | Earlier popjaxrl behavior (source) | POPJym behavior |
10
+ | --- | --- | --- |
11
+ | CountRecallEasy | The agent could answer only 0 or 1. [popjaxrl issue #10](https://github.com/luchris429/popjaxrl/issues/10) | The agent can report any count from 0 through 26. |
12
+ | Autoencode | [The agent saw a blank observation for every card during the watch phase.](https://github.com/luchris429/popjaxrl/blob/12e5d42be3a6bde81cce4234f8be4e119e4318b6/envs/environments/popgym_autoencode.py#L71-L77) | The agent sees each suit in order, then recalls the suits in reverse. |
13
+ | RepeatFirstEasy | [A 52-card deck allowed 52 guesses and a perfect return of 52/51.](https://github.com/luchris429/popjaxrl/blob/12e5d42be3a6bde81cce4234f8be4e119e4318b6/envs/environments/popgym_repeat_first.py#L33-L39) | The first card is dealt at reset, leaving 51 guesses and a perfect return of 1. |
14
+ | MineSweeper | [Clearing every safe square in succession left the episode running.](https://github.com/luchris429/popjaxrl/blob/12e5d42be3a6bde81cce4234f8be4e119e4318b6/envs/environments/popgym_minesweeper.py#L39-L53) | Clearing the last safe square ends the episode. |
15
+
16
+ ## Quick start
17
+
18
+ ```bash
19
+ python -m pip install "git+https://github.com/bolt-research/POPJym.git"
20
+ ```
21
+
22
+ ```python
23
+ import jax
24
+ import popjym
25
+
26
+ env = popjym.make("RepeatFirstEasy")
27
+ reset_key, step_key = jax.random.split(jax.random.key(0))
28
+ first_suit, state = env.reset(reset_key)
29
+ obs, state, reward, terminated, truncated, info = jax.jit(env.step)(
30
+ step_key, state, first_suit
31
+ )
32
+ ```
33
+
34
+ ## Citation
35
+
36
+ If you use POPJym in your work, please cite this software and the original POPGym benchmark paper by Morad et al.
37
+
38
+ ```bibtex
39
+ @software{wang2026popjym,
40
+ author = {Wang, Zekang and He, Zhe},
41
+ title = {{POPJym}},
42
+ year = {2026},
43
+ version = {0.1.0},
44
+ url = {https://github.com/bolt-research/POPJym}
45
+ }
46
+ ```
47
+
48
+ ```bibtex
49
+ @inproceedings{morad2023popgym,
50
+ author = {Morad, Steven and Kortvelesy, Ryan and Bettini, Matteo and Liwicki, Stephan and Prorok, Amanda},
51
+ title = {{POPGym}: Benchmarking Partially Observable Reinforcement Learning},
52
+ booktitle = {The Eleventh International Conference on Learning Representations},
53
+ year = {2023},
54
+ url = {https://openreview.net/forum?id=chDrutUTs0K}
55
+ }
56
+ ```
@@ -0,0 +1,41 @@
1
+ """POPJym: JIT-compatible POPGym environments implemented in JAX."""
2
+
3
+ from popjym import envs
4
+ from popjym.core import (
5
+ Box,
6
+ Discrete,
7
+ MultiBinary,
8
+ MultiDiscrete,
9
+ POPJymEnv,
10
+ Space,
11
+ TupleSpace,
12
+ Observability,
13
+ flatdim,
14
+ flatten,
15
+ )
16
+ from popjym.envs import ALL
17
+ from popjym.registry import ENV_REGISTRY, make, make_gymnax, registered_envs
18
+ from popjym.wrappers import EnvParams, GymnaxWrapper
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ __all__ = [
23
+ "ALL",
24
+ "ENV_REGISTRY",
25
+ "Box",
26
+ "Discrete",
27
+ "EnvParams",
28
+ "GymnaxWrapper",
29
+ "MultiDiscrete",
30
+ "MultiBinary",
31
+ "Space",
32
+ "Observability",
33
+ "flatdim",
34
+ "flatten",
35
+ "POPJymEnv",
36
+ "TupleSpace",
37
+ "envs",
38
+ "make",
39
+ "make_gymnax",
40
+ "registered_envs",
41
+ ]
@@ -0,0 +1,27 @@
1
+ """Reusable JAX modules such as deck, base environment, maze, and spaces."""
2
+
3
+ from popjym.core.env import POPJymEnv
4
+ from popjym.core.spaces import (
5
+ Box,
6
+ Discrete,
7
+ MultiBinary,
8
+ MultiDiscrete,
9
+ Space,
10
+ TupleSpace,
11
+ flatdim,
12
+ flatten,
13
+ )
14
+ from popjym.core.observability import Observability
15
+
16
+ __all__ = [
17
+ "POPJymEnv",
18
+ "Box",
19
+ "Discrete",
20
+ "MultiDiscrete",
21
+ "MultiBinary",
22
+ "Space",
23
+ "TupleSpace",
24
+ "Observability",
25
+ "flatdim",
26
+ "flatten",
27
+ ]
@@ -0,0 +1,52 @@
1
+ """Functional JAX helpers for POPGym's standard 52-card decks.
2
+
3
+ This module mirrors :mod:`popgym.core.deck`, but represents a shuffled deck as
4
+ a JAX integer array so it can live inside an environment PyTree.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import jax
10
+ import jax.numpy as jnp
11
+
12
+ DECK_SIZE = 52
13
+ NUM_SUITS = 4
14
+ NUM_RANKS = 13
15
+ NUM_COLORS = 2
16
+ RANKS = ("a", "2", "3", "4", "5", "6", "7", "8", "9", "10", "j", "q", "k")
17
+ SUITS = ("s", "d", "c", "h")
18
+ COLORS = ("b", "r")
19
+
20
+
21
+ def shuffled_deck(key: jax.Array, num_decks: int) -> jax.Array:
22
+ """Return a shuffled array of unique card indices."""
23
+
24
+ return jax.random.permutation(
25
+ key, jnp.arange(DECK_SIZE * num_decks, dtype=jnp.int32)
26
+ )
27
+
28
+
29
+ def suit(card: jax.Array) -> jax.Array:
30
+ return jnp.mod(card, DECK_SIZE) % NUM_SUITS
31
+
32
+
33
+ def rank(card: jax.Array) -> jax.Array:
34
+ return jnp.mod(card, DECK_SIZE) // NUM_SUITS
35
+
36
+
37
+ def color(card: jax.Array) -> jax.Array:
38
+ return jnp.mod(card, DECK_SIZE) % NUM_COLORS
39
+
40
+
41
+ def feature(card: jax.Array, kind: str) -> jax.Array:
42
+ if kind == "colors":
43
+ return color(card)
44
+ if kind == "suits":
45
+ return suit(card)
46
+ if kind == "ranks":
47
+ return rank(card)
48
+ raise ValueError(f"Unknown card feature: {kind}")
49
+
50
+
51
+ def num_values(kind: str) -> int:
52
+ return {"colors": NUM_COLORS, "suits": NUM_SUITS, "ranks": NUM_RANKS}[kind]
@@ -0,0 +1,99 @@
1
+ """Common protocol for functional POPJym environments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Any, Generic, TypeVar
7
+
8
+ import jax
9
+ import jax.numpy as jnp
10
+
11
+ from popjym.core.observability import Observability
12
+ from popjym.core.spaces import Box, Discrete, MultiDiscrete, flatdim
13
+
14
+ State = TypeVar("State")
15
+
16
+
17
+ class POPJymEnv(ABC, Generic[State]):
18
+ """A stateless environment object whose episode data lives in a PyTree.
19
+
20
+ Environment instances contain configuration only. ``reset`` and ``step``
21
+ are pure functions and can be closed over directly by :func:`jax.jit`.
22
+ """
23
+
24
+ max_episode_length: int
25
+ observation_space: Any
26
+ action_space: Any
27
+ state_space: Any
28
+ observability_level = Observability.PARTIAL
29
+ obs_requires_prev_action = False
30
+ metadata = {"render_modes": []}
31
+ reward_range = (-float("inf"), float("inf"))
32
+
33
+ @property
34
+ def name(self) -> str:
35
+ return type(self).__name__
36
+
37
+ @property
38
+ def unwrapped(self):
39
+ return self
40
+
41
+ @property
42
+ def num_actions(self) -> int:
43
+ if isinstance(self.action_space, Discrete):
44
+ return self.action_space.n
45
+ if isinstance(self.action_space, MultiDiscrete):
46
+ return int(self.action_space.nvec.prod())
47
+ if isinstance(self.action_space, Box):
48
+ return flatdim(self.action_space)
49
+ raise TypeError("num_actions requires a Discrete, MultiDiscrete or Box space")
50
+
51
+ @property
52
+ def observation_size(self) -> int:
53
+ return flatdim(self.observation_space)
54
+
55
+ @abstractmethod
56
+ def get_state(self, state: State) -> Any:
57
+ """POPGym privileged state, distinct from the full simulator PyTree."""
58
+ raise NotImplementedError
59
+
60
+ @abstractmethod
61
+ def get_obs(self, state: State) -> Any:
62
+ """Observation of the current environment state."""
63
+ raise NotImplementedError
64
+
65
+ def last_observation(self, state: State) -> Any:
66
+ """Observation returned by the most recent reset or step."""
67
+ return self.get_obs(state)
68
+
69
+ @abstractmethod
70
+ def elapsed_steps(self, state: State) -> jax.Array:
71
+ raise NotImplementedError
72
+
73
+ @abstractmethod
74
+ def is_terminated(self, state: State) -> jax.Array:
75
+ raise NotImplementedError
76
+
77
+ def is_truncated(self, state: State) -> jax.Array:
78
+ return self.elapsed_steps(state) >= self.max_episode_length
79
+
80
+ def is_terminal(self, state: State) -> jax.Array:
81
+ """Whether the episode has ended for either reason."""
82
+ return self.is_terminated(state) | self.is_truncated(state)
83
+
84
+ def discount(self, state: State) -> jax.Array:
85
+ """Bootstrap through time limits, but not natural terminal states."""
86
+ return (~self.is_terminated(state)).astype(jnp.float32)
87
+
88
+ @abstractmethod
89
+ def reset(self, key: jax.Array) -> tuple[Any, State]:
90
+ raise NotImplementedError
91
+
92
+ @abstractmethod
93
+ def step(
94
+ self, key: jax.Array, state: State, action: Any
95
+ ) -> tuple[Any, State, jax.Array, jax.Array, jax.Array, dict[str, Any]]:
96
+ raise NotImplementedError
97
+
98
+ def sample_action(self, key: jax.Array) -> jax.Array:
99
+ return self.action_space.sample(key)