cuju-engine 0.3.0__py3-none-macosx_11_0_arm64.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.
Files changed (221) hide show
  1. cuju/__init__.py +217 -0
  2. cuju/__main__.py +262 -0
  3. cuju/_batch/__init__.py +4 -0
  4. cuju/_batch/allocator.py +52 -0
  5. cuju/_batch/assets.py +68 -0
  6. cuju/_batch/environment.py +1890 -0
  7. cuju/_batch/frame_stack.py +114 -0
  8. cuju/_batch/library.py +190 -0
  9. cuju/_batch/log.py +103 -0
  10. cuju/_batch/memory.py +70 -0
  11. cuju/_batch/operators.py +55 -0
  12. cuju/_batch/pinned.py +39 -0
  13. cuju/_batch/pixels.py +207 -0
  14. cuju/_batch/state.py +77 -0
  15. cuju/_checksums.py +60 -0
  16. cuju/_cli_contract.py +244 -0
  17. cuju/_cli_parsers.py +191 -0
  18. cuju/_completion.py +277 -0
  19. cuju/_dump_to_txt.py +66 -0
  20. cuju/_grf_config.py +331 -0
  21. cuju/_library_path.py +141 -0
  22. cuju/_media.py +113 -0
  23. cuju/_pixels.py +276 -0
  24. cuju/_plugins.py +106 -0
  25. cuju/_python_players.py +224 -0
  26. cuju/_replay_command.py +109 -0
  27. cuju/_replay_player.py +42 -0
  28. cuju/_replays.py +414 -0
  29. cuju/_script_helpers.py +109 -0
  30. cuju/_version.py +6 -0
  31. cuju/action_log.py +371 -0
  32. cuju/check.py +596 -0
  33. cuju/data/SHA256SUMS +20 -0
  34. cuju/data/animations.bin +0 -0
  35. cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
  36. cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
  37. cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
  38. cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
  39. cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
  40. cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
  41. cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
  42. cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
  43. cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
  44. cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
  45. cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
  46. cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
  47. cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
  48. cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  49. cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  50. cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
  51. cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
  52. cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
  53. cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
  54. cuju/data/digests.json +186 -0
  55. cuju/data/render_digests.json.z +0 -0
  56. cuju/data/scenarios/11_vs_11_competition.py +45 -0
  57. cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
  58. cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
  59. cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
  60. cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
  61. cuju/data/scenarios/1_vs_1_easy.py +25 -0
  62. cuju/data/scenarios/5_vs_5.py +33 -0
  63. cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
  64. cuju/data/scenarios/academy_corner.py +45 -0
  65. cuju/data/scenarios/academy_counterattack_easy.py +45 -0
  66. cuju/data/scenarios/academy_counterattack_hard.py +45 -0
  67. cuju/data/scenarios/academy_empty_goal.py +25 -0
  68. cuju/data/scenarios/academy_empty_goal_close.py +25 -0
  69. cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
  70. cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
  71. cuju/data/scenarios/academy_run_to_score.py +30 -0
  72. cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
  73. cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
  74. cuju/data/scenarios/test_example_multiagent.py +28 -0
  75. cuju/dumps.py +942 -0
  76. cuju/engine_status.py +106 -0
  77. cuju/env.py +1168 -0
  78. cuju/errors.py +108 -0
  79. cuju/gfootball/GRF_SOURCES +86 -0
  80. cuju/gfootball/__init__.py +60 -0
  81. cuju/gfootball/_cv2.py +43 -0
  82. cuju/gfootball/_gym/__init__.py +88 -0
  83. cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
  84. cuju/gfootball/_gym/_vendored/__init__.py +43 -0
  85. cuju/gfootball/_gym/_vendored/core.py +361 -0
  86. cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
  87. cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
  88. cuju/gfootball/_gym/_vendored/error.py +230 -0
  89. cuju/gfootball/_gym/_vendored/logger.py +56 -0
  90. cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
  91. cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
  92. cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
  93. cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
  94. cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
  95. cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
  96. cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
  97. cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
  98. cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
  99. cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
  100. cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
  101. cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
  102. cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
  103. cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
  104. cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
  105. cuju/gfootball/_gym/_vendored/version.py +5 -0
  106. cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
  107. cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
  108. cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
  109. cuju/gfootball/dump_to_txt.py +49 -0
  110. cuju/gfootball/dump_to_video.py +33 -0
  111. cuju/gfootball/env/__init__.py +271 -0
  112. cuju/gfootball/env/config.py +163 -0
  113. cuju/gfootball/env/constants.py +33 -0
  114. cuju/gfootball/env/controller_base.py +114 -0
  115. cuju/gfootball/env/event_queue.py +54 -0
  116. cuju/gfootball/env/football_action_set.py +220 -0
  117. cuju/gfootball/env/football_action_set_test.py +76 -0
  118. cuju/gfootball/env/football_env.py +225 -0
  119. cuju/gfootball/env/football_env_core.py +447 -0
  120. cuju/gfootball/env/football_env_test.py +692 -0
  121. cuju/gfootball/env/gym_test.py +47 -0
  122. cuju/gfootball/env/observation_preprocessing.py +94 -0
  123. cuju/gfootball/env/observation_processor.py +526 -0
  124. cuju/gfootball/env/observation_rotation.py +163 -0
  125. cuju/gfootball/env/observation_rotation_test.py +84 -0
  126. cuju/gfootball/env/player_base.py +46 -0
  127. cuju/gfootball/env/players/__init__.py +16 -0
  128. cuju/gfootball/env/players/agent.py +39 -0
  129. cuju/gfootball/env/players/bot.py +217 -0
  130. cuju/gfootball/env/players/gamepad.py +81 -0
  131. cuju/gfootball/env/players/keyboard.py +72 -0
  132. cuju/gfootball/env/players/lazy.py +31 -0
  133. cuju/gfootball/env/players/ppo2_cnn.py +119 -0
  134. cuju/gfootball/env/players/replay.py +40 -0
  135. cuju/gfootball/env/remote_football_env.py +189 -0
  136. cuju/gfootball/env/scenario_builder.py +125 -0
  137. cuju/gfootball/env/script_helpers.py +130 -0
  138. cuju/gfootball/env/script_helpers_test.py +107 -0
  139. cuju/gfootball/env/wrappers.py +440 -0
  140. cuju/gfootball/env/wrappers_test.py +150 -0
  141. cuju/gfootball/eval_server/__init__.py +17 -0
  142. cuju/gfootball/eval_server/config.py +30 -0
  143. cuju/gfootball/eval_server/example_client.py +107 -0
  144. cuju/gfootball/eval_server/proto/game_server.proto +62 -0
  145. cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
  146. cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
  147. cuju/gfootball/eval_server/proto/master.proto +25 -0
  148. cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
  149. cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
  150. cuju/gfootball/eval_server/utils.py +52 -0
  151. cuju/gfootball/examples/__init__.py +16 -0
  152. cuju/gfootball/examples/models.py +66 -0
  153. cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
  154. cuju/gfootball/examples/run_ppo2.py +123 -0
  155. cuju/gfootball/play_game.py +73 -0
  156. cuju/gfootball/replay.py +43 -0
  157. cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
  158. cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
  159. cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
  160. cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
  161. cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
  162. cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
  163. cuju/gfootball/scenarios/5_vs_5.py +46 -0
  164. cuju/gfootball/scenarios/__init__.py +31 -0
  165. cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
  166. cuju/gfootball/scenarios/academy_corner.py +59 -0
  167. cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
  168. cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
  169. cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
  170. cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
  171. cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
  172. cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
  173. cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
  174. cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
  175. cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
  176. cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
  177. cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
  178. cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
  179. cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
  180. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
  181. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
  182. cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
  183. cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
  184. cuju/gfootball/scenarios/tests/__init__.py +31 -0
  185. cuju/gfootball/scenarios/tests/corner_test.py +38 -0
  186. cuju/gfootball/scenarios/tests/goal_test.py +35 -0
  187. cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
  188. cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
  189. cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
  190. cuju/gfootball/scenarios/tests/offside_test.py +39 -0
  191. cuju/gfootball/scenarios/tests/penalty.py +34 -0
  192. cuju/gfootball/scenarios/tests/second_half.py +33 -0
  193. cuju/gfootball/scenarios/tests/symmetric.py +53 -0
  194. cuju/gfootball_engine/__init__.py +31 -0
  195. cuju/gfootball_engine/_gameplayfootball.py +1624 -0
  196. cuju/gfootball_engine/_native.py +193 -0
  197. cuju/gfootball_engine/_pickle_names.py +114 -0
  198. cuju/gfootball_engine/_render_hooks.py +156 -0
  199. cuju/kaggle.py +425 -0
  200. cuju/libcuju_cpu.dylib +0 -0
  201. cuju/libcuju_render.dylib +0 -0
  202. cuju/multi_device.py +401 -0
  203. cuju/players.py +260 -0
  204. cuju/raw.py +93 -0
  205. cuju/scenarios.py +661 -0
  206. cuju/state.py +211 -0
  207. cuju/wrappers.py +325 -0
  208. cuju_engine-0.3.0.dist-info/METADATA +325 -0
  209. cuju_engine-0.3.0.dist-info/RECORD +221 -0
  210. cuju_engine-0.3.0.dist-info/WHEEL +5 -0
  211. cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
  212. cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
  213. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
  214. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
  215. cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
  216. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
  217. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
  218. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
  219. cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
  220. cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
  221. cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/__init__.py ADDED
@@ -0,0 +1,217 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """Batched Google Research Football (GRF) environments on the GPU or the CPU, bit for bit.
6
+
7
+ `BatchEnvironment` steps many environments per call, and its outputs are PyTorch tensors that share
8
+ its buffers. The guide and the reference are in the repository's `docs/` (`index.md`, `api.md`).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import importlib.util
14
+ import sys
15
+ from typing import ClassVar
16
+
17
+ from ._batch.assets import bundled_assets, bundled_scenarios
18
+ from ._version import __version__
19
+ from .errors import (
20
+ ActionRangeError,
21
+ ArgumentError,
22
+ ChoiceError,
23
+ ClosedError,
24
+ ConfigurationError,
25
+ DeviceError,
26
+ EnvironmentIndexError,
27
+ Error,
28
+ LibraryError,
29
+ MissingFileError,
30
+ SignatureError,
31
+ StateError,
32
+ TrackerError,
33
+ UndefinedPathError,
34
+ )
35
+
36
+ __all__ = [
37
+ 'ActionLog',
38
+ 'ActionRangeError',
39
+ 'ArgumentError',
40
+ 'BatchEnvironment',
41
+ 'ChoiceError',
42
+ 'ClosedError',
43
+ 'ConfigurationError',
44
+ 'DeviceError',
45
+ 'Digest',
46
+ 'EnvironmentIndexError',
47
+ 'Error',
48
+ 'LibraryError',
49
+ 'MissingFileError',
50
+ 'MultiDeviceBatch',
51
+ 'SignatureError',
52
+ 'StateError',
53
+ 'TrackerError',
54
+ 'UndefinedPathError',
55
+ '__version__',
56
+ 'bundled_assets',
57
+ 'bundled_scenarios',
58
+ 'digest',
59
+ 'library_path',
60
+ 'memory_estimate',
61
+ 'replay',
62
+ ]
63
+
64
+ # The names keep `cuju` as their module, so that their reprs and pickles name the public path.
65
+ for _name in (bundled_assets, bundled_scenarios):
66
+ _name.__module__ = __name__
67
+ del _name
68
+
69
+ # The names that build on PyTorch load on first use, so that `import cuju` and the commands of the
70
+ # commands that step no batch start without importing PyTorch. Each maps to its module.
71
+ _LAZY = {
72
+ 'BatchEnvironment': '_batch.environment',
73
+ 'memory_estimate': '_batch.environment',
74
+ 'library_path': '_batch.library',
75
+ '_MemoryEstimate': '_batch.memory',
76
+ 'ActionLog': 'action_log',
77
+ 'Digest': 'action_log',
78
+ 'digest': 'action_log',
79
+ 'replay': 'action_log',
80
+ 'MultiDeviceBatch': 'multi_device',
81
+ }
82
+
83
+
84
+ def _load_batch() -> None:
85
+ """Imports the names of `BatchEnvironment` and its helpers, which then name `cuju` their module.
86
+
87
+ The names keep `cuju` as their module, so that their reprs and pickles name the public path.
88
+ """
89
+ from ._batch.environment import BatchEnvironment, memory_estimate
90
+ from ._batch.library import library_path
91
+ from ._batch.memory import _MemoryEstimate
92
+
93
+ loaded = {
94
+ 'BatchEnvironment': BatchEnvironment,
95
+ 'memory_estimate': memory_estimate,
96
+ 'library_path': library_path,
97
+ '_MemoryEstimate': _MemoryEstimate,
98
+ }
99
+ for value in loaded.values():
100
+ value.__module__ = __name__
101
+ globals().update(loaded)
102
+
103
+
104
+ def __getattr__(name: str):
105
+ module = _LAZY.get(name)
106
+ if module is None:
107
+ raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
108
+ if module.startswith('_batch'):
109
+ _load_batch()
110
+ else:
111
+ globals()[name] = getattr(importlib.import_module(f'.{module}', __name__), name)
112
+ return globals()[name]
113
+
114
+
115
+ def __dir__() -> list[str]:
116
+ return sorted(set(globals()) | set(_LAZY))
117
+
118
+
119
+ class _RegisteringLoader:
120
+ """Runs the loader of gymnasium, then registers the ids of `cuju.env` with it."""
121
+
122
+ def __init__(self, loader, name):
123
+ self._loader = loader
124
+ self._name = name
125
+
126
+ def create_module(self, spec):
127
+ return self._loader.create_module(spec)
128
+
129
+ def exec_module(self, module):
130
+ self._loader.exec_module(module)
131
+ _RegistrationFinder.waiting.discard(self._name)
132
+ _register_ids(self._name)
133
+
134
+ def __getattr__(self, name):
135
+ return getattr(self._loader, name)
136
+
137
+
138
+ class _RegistrationFinder:
139
+ """Hands gymnasium, when imported, a loader that then registers the ids of `cuju.env`."""
140
+
141
+ waiting: ClassVar[set[str]] = set()
142
+ # The names being looked up by the other finders, which this one then leaves to them.
143
+ finding: ClassVar[set[str]] = set()
144
+
145
+ def find_spec(self, name, path=None, target=None):
146
+ if name not in self.waiting or name in self.finding:
147
+ return None
148
+ self.finding.add(name)
149
+ try:
150
+ spec = importlib.util.find_spec(name)
151
+ finally:
152
+ self.finding.discard(name)
153
+ if spec is not None and spec.loader is not None:
154
+ spec.loader = _RegisteringLoader(spec.loader, name)
155
+ return spec
156
+
157
+
158
+ def _register_ids(module):
159
+ # A `cuju.env` that is still importing registers the ids itself once it is done.
160
+ try:
161
+ from .env import _register_with
162
+ except ImportError:
163
+ return
164
+ _register_with(module)
165
+
166
+
167
+ def _register_gymnasium_ids():
168
+ """Registers the ids of `cuju.env` with gymnasium once it is imported.
169
+
170
+ gym gets GRF's ids from `cuju.gfootball`, as importing `gfootball` registers them, so that
171
+ `import cuju` imports neither.
172
+ """
173
+ if sys.modules.get('gymnasium') is not None:
174
+ _register_ids('gymnasium')
175
+ else:
176
+ _RegistrationFinder.waiting.add('gymnasium')
177
+ if not any(isinstance(finder, _RegistrationFinder) for finder in sys.meta_path):
178
+ sys.meta_path.insert(0, _RegistrationFinder())
179
+
180
+
181
+ _register_gymnasium_ids()
182
+
183
+
184
+ def _with_portions(path):
185
+ """Returns `path` and, after it, every folder `cuju` that `sys.path` holds elsewhere and that
186
+ is a portion of the package.
187
+
188
+ A package that installs beside cuju puts its files into this folder, and
189
+ an editable install of it keeps them in its own checkout, whose `cuju` folder holds its modules
190
+ and no `__init__.py`. Such a folder joins the package as an absolute path, as
191
+ `pkgutil.extend_path` joins it. A folder `cuju` with an `__init__.py` of its own is a whole
192
+ cuju, such as an older installation or a checkout in the current directory, and stays out, so
193
+ that its modules never stand in for missing ones.
194
+ """
195
+ import os
196
+
197
+ folders = list(path)
198
+ seen = {os.path.normcase(os.path.abspath(folder)) for folder in folders}
199
+ for entry in sys.path:
200
+ if not isinstance(entry, str):
201
+ continue
202
+ folder = os.path.abspath(os.path.join(entry, __name__))
203
+ key = os.path.normcase(folder)
204
+ if key in seen or os.path.isfile(os.path.join(folder, '__init__.py')):
205
+ continue
206
+ if os.path.isdir(folder):
207
+ seen.add(key)
208
+ folders.append(folder)
209
+ return folders
210
+
211
+
212
+ __path__ = _with_portions(__path__)
213
+
214
+ # A module `cuju.<name>` that no package provides names the package that may.
215
+ from . import _plugins # noqa: E402
216
+
217
+ _plugins.install_finder()
cuju/__main__.py ADDED
@@ -0,0 +1,262 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Dispatches the engine tools and installed family commands."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import importlib
10
+ import sys
11
+ from difflib import get_close_matches
12
+ from importlib import metadata
13
+
14
+ from . import _cli_contract as contract
15
+ from . import _cli_parsers as parsers
16
+ from ._version import __version__
17
+
18
+ GROUP = 'cuju.commands'
19
+ ENGINE = 'cuju-engine'
20
+ # These family names have installation hints when their commands are absent.
21
+ FAMILY = {'arena': 'cuju-arena', 'render': 'cuju-render'}
22
+ _MODULES = {'check': '.check', 'replay': '._replay_command', 'dump-to-txt': '._dump_to_txt'}
23
+
24
+
25
+ def _entries() -> dict[str, metadata.EntryPoint]:
26
+ entries = {}
27
+ for entry in metadata.entry_points(group=GROUP):
28
+ if entry.name not in parsers.BUILDERS:
29
+ entries.setdefault(entry.name, entry)
30
+ return dict(sorted(entries.items()))
31
+
32
+
33
+ def version_lines() -> list[str]:
34
+ """Lists the installed distributions of the family."""
35
+ for name in (ENGINE, 'cuju-engine-cpu'):
36
+ try:
37
+ engine = f'{name} {metadata.version(name)}'
38
+ break
39
+ except metadata.PackageNotFoundError:
40
+ continue
41
+ else:
42
+ engine = f'{ENGINE} {__version__}'
43
+
44
+ seen = {ENGINE, 'cuju-engine-cpu', 'cuju'}
45
+ extensions = {}
46
+ for entry in metadata.entry_points(group=GROUP):
47
+ dist = entry.dist
48
+ if dist is not None:
49
+ key = dist.name.lower().replace('_', '-').replace('.', '-')
50
+ if key not in seen:
51
+ extensions[key] = f'{dist.name} {dist.version}'
52
+ lines = [engine, *(extensions[key] for key in sorted(extensions))]
53
+ try:
54
+ lines.append(f'cuju {metadata.version("cuju")}')
55
+ except metadata.PackageNotFoundError:
56
+ pass
57
+ return lines
58
+
59
+
60
+ class _Version(argparse.Action):
61
+ def __init__(self, option_strings, dest, **kwargs):
62
+ super().__init__(option_strings, dest, nargs=0, **kwargs)
63
+
64
+ def __call__(self, parser, namespace, values, option_string=None):
65
+ print('\n'.join(version_lines()))
66
+ parser.exit()
67
+
68
+
69
+ def parser() -> contract.Parser:
70
+ """Builds the parser of the engine without loading any command."""
71
+ root = contract.Parser(
72
+ prog='cuju',
73
+ description='Run the engine tools and the commands of installed packages.',
74
+ epilog=contract.examples('cuju help', 'cuju check', 'cuju completion bash'),
75
+ )
76
+ root.add_argument(
77
+ '-V', '--version', action=_Version, help='print the versions of the installed packages'
78
+ )
79
+ contract.add_globals(root)
80
+ group = root.add_subparsers(dest='command', metavar='NAME')
81
+ for build in parsers.BUILDERS.values():
82
+ build(group)
83
+ return root
84
+
85
+
86
+ def _package_parser(entry: metadata.EntryPoint) -> argparse.ArgumentParser | None:
87
+ module = importlib.import_module(entry.module)
88
+ build = getattr(module, 'parser', None)
89
+ return build() if build is not None else None
90
+
91
+
92
+ def package_parsers(entries):
93
+ """Yields each package with the parser it makes available."""
94
+ for name, entry in entries.items():
95
+ try:
96
+ tree = _package_parser(entry)
97
+ except Exception:
98
+ tree = None
99
+ yield name, entry, tree
100
+
101
+
102
+ def _overview(root: contract.Parser) -> None:
103
+ lines = [root.format_help().rstrip()]
104
+ for name, entry, tree in package_parsers(_entries()):
105
+ dist = entry.dist
106
+ heading = f'{name}, {dist.name} {dist.version}' if dist else name
107
+ lines.extend(('', heading))
108
+ summaries = (
109
+ [
110
+ (choice.dest, choice.help)
111
+ for group in contract.subcommands(tree)
112
+ for choice in group._choices_actions
113
+ ]
114
+ if tree is not None
115
+ else []
116
+ )
117
+ if summaries:
118
+ width = max(len(word) for word, _ in summaries)
119
+ for word, summary in summaries:
120
+ lines.append(f' {word:<{width}} {summary or ""}'.rstrip())
121
+ elif dist and dist.metadata['Summary']:
122
+ lines.append(f' {dist.metadata["Summary"]}')
123
+ print('\n'.join(lines))
124
+
125
+
126
+ def _unknown(name, entries, as_json, help_parser=None) -> int:
127
+ prog = help_parser.prog if help_parser is not None else 'cuju'
128
+ if name in FAMILY:
129
+ return contract.fail(
130
+ prog,
131
+ f'expected a command from {FAMILY[name]}, found the package missing',
132
+ hint=f'pip install {FAMILY[name]}',
133
+ as_json=as_json,
134
+ status=contract.EXIT_ENVIRONMENT,
135
+ error_id='command.package_missing',
136
+ values={'command': name, 'package': FAMILY[name]},
137
+ )
138
+ names = parsers.BUILDERS.keys() | entries.keys() | FAMILY.keys()
139
+ close = get_close_matches(name, sorted(names), n=3)
140
+ hint = 'run cuju help to list the commands.'
141
+ if close:
142
+ hint = f'run cuju help {close[0]}, similar command names are {", ".join(close)}.'
143
+ if help_parser is not None:
144
+ help_parser.print_usage(sys.stderr)
145
+ return contract.fail(
146
+ prog,
147
+ f'no command {name!r}',
148
+ hint=hint,
149
+ as_json=as_json,
150
+ status=contract.EXIT_USAGE,
151
+ error_id='command.unknown',
152
+ values={'command': name},
153
+ )
154
+
155
+
156
+ def _run_entry(entry: metadata.EntryPoint, arguments: list[str]) -> int | None:
157
+ try:
158
+ function = entry.load()
159
+ if not callable(function):
160
+ raise TypeError('expected a callable entry point')
161
+ except BrokenPipeError:
162
+ raise
163
+ except Exception as error:
164
+ dist = entry.dist
165
+ package = dist.name if dist else entry.name
166
+ return contract.fail(
167
+ f'cuju {entry.name}',
168
+ f'could not load the command from {package}, {type(error).__name__}, {error}',
169
+ hint=f'run pip show {package} to check the installation.',
170
+ as_json='--json' in contract.options(arguments),
171
+ status=contract.EXIT_ENVIRONMENT,
172
+ error_id='command.load',
173
+ values={'command': entry.name, 'package': package},
174
+ )
175
+ status = function(arguments)
176
+ return 0 if status is None else int(status)
177
+
178
+
179
+ def _children(tree):
180
+ return {
181
+ name: child for group in contract.subcommands(tree) for name, child in group.choices.items()
182
+ }
183
+
184
+
185
+ def _command_help(root, args):
186
+ name, *words = args.words
187
+ entries = _entries()
188
+ tree = _children(root).get(name)
189
+ if tree is None:
190
+ entry = entries.get(name)
191
+ if entry is None:
192
+ return _unknown(name, entries, False, args._command_parser)
193
+ try:
194
+ tree = _package_parser(entry)
195
+ except BrokenPipeError:
196
+ raise
197
+ except Exception:
198
+ tree = None
199
+ if tree is None:
200
+ return _run_entry(entry, [*words, '--help'])
201
+ path = ['cuju', name]
202
+ for word in words:
203
+ child = _children(tree).get(word)
204
+ if child is None:
205
+ tree.print_usage(sys.stderr)
206
+ prog = ' '.join(path)
207
+ return contract.fail(
208
+ prog,
209
+ f'expected a command below {prog}, found {word!r}',
210
+ hint=f'run {prog} --help to list the commands.',
211
+ status=contract.EXIT_USAGE,
212
+ )
213
+ tree = child
214
+ path.append(word)
215
+ tree.print_help()
216
+ return 0
217
+
218
+
219
+ def _dispatch(arguments: list[str], command_index: int) -> int | None:
220
+ tail = arguments[command_index:]
221
+ if tail and not tail[0].startswith('-') and tail[0] not in parsers.BUILDERS:
222
+ name, *rest = tail
223
+ entries = _entries()
224
+ if name in entries:
225
+ return _run_entry(entries[name], [*arguments[:command_index], *rest])
226
+ return _unknown(name, entries, '--json' in contract.options(rest))
227
+
228
+ root = parser()
229
+ if not tail or tail[0] in ('-h', '--help'):
230
+ _overview(root)
231
+ return 0
232
+ if tail[0].startswith('-') and tail[0] not in ('-V', '--version'):
233
+ root.error(f'expected a root option or a command, found {tail[0]!r}')
234
+ args = root.parse_args(arguments)
235
+ if args.command in _MODULES:
236
+ return importlib.import_module(_MODULES[args.command], __package__)._run(args)
237
+ if args.command == 'help':
238
+ if args.words:
239
+ return _command_help(root, args)
240
+ _overview(root)
241
+ elif args.command == 'completion':
242
+ from . import _completion
243
+
244
+ print(_completion.script(args.shell, root, package_parsers(_entries()), version_lines()))
245
+ return 0
246
+
247
+
248
+ def main(arguments: list[str] | None = None) -> int:
249
+ """Runs the command and returns its exit status."""
250
+ arguments = sys.argv[1:] if arguments is None else arguments
251
+ index = 0
252
+ for flag in arguments:
253
+ if not contract.is_global(flag):
254
+ break
255
+ index += 1
256
+ name = arguments[index] if index < len(arguments) else ''
257
+ prog = f'cuju {name}' if name and not name.startswith('-') else 'cuju'
258
+ return contract.guarded(prog, lambda: _dispatch(arguments, index), arguments)
259
+
260
+
261
+ if __name__ == '__main__':
262
+ sys.exit(main())
@@ -0,0 +1,4 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """The implementation of `BatchEnvironment`, which `cuju` exports."""
@@ -0,0 +1,52 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """The device memory of a batch through PyTorch's caching allocator."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import ctypes
8
+
9
+ import torch
10
+
11
+ # The C signatures of `allocate` and `release` in `cuju_configuration`.
12
+ ALLOCATE = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p)
13
+ RELEASE = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)
14
+
15
+
16
+ class TorchAllocator:
17
+ """The `allocate` and `release` functions that the library calls, over torch's allocator.
18
+
19
+ The memory comes from the default stream of the device, which the library's copies and fills
20
+ use, and the library releases it only once the device is idle, so torch may hand it out again
21
+ at once.
22
+
23
+ Attributes:
24
+ allocate, release: The C functions, which must outlive the batch.
25
+ errors: The exceptions that torch raised in `allocate`, such as `torch.OutOfMemoryError`.
26
+ """
27
+
28
+ def __init__(self, device: torch.device) -> None:
29
+ stream = torch.cuda.default_stream(device)
30
+ errors: list[BaseException] = []
31
+
32
+ def allocate(size, _context):
33
+ try:
34
+ return torch.cuda.caching_allocator_alloc(size, device, stream)
35
+ # An exception cannot cross the library, so the batch raises it after the call.
36
+ except Exception as error:
37
+ errors.append(error)
38
+ return None
39
+
40
+ def release(pointer, _context):
41
+ torch.cuda.caching_allocator_delete(pointer)
42
+
43
+ self.allocate = ALLOCATE(allocate)
44
+ self.release = RELEASE(release)
45
+ self.errors = errors
46
+
47
+ def pointers(self) -> tuple[int, int]:
48
+ """Returns the addresses of `allocate` and `release` for `cuju_configuration`."""
49
+ return (
50
+ ctypes.cast(self.allocate, ctypes.c_void_p).value,
51
+ ctypes.cast(self.release, ctypes.c_void_p).value,
52
+ )
cuju/_batch/assets.py ADDED
@@ -0,0 +1,68 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """The asset bundles that the package ships, and the bundle that a name or path asks for."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import re
10
+
11
+ from ..errors import MissingFileError
12
+
13
+ _DATA_DIRECTORY = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data')
14
+
15
+
16
+ def bundled_assets() -> list[str]:
17
+ """Returns the names of the asset bundles that the package ships, such as `5_vs_5_l4_r0`.
18
+
19
+ `BatchEnvironment` takes such a name `<scenario>_l<left agents>_r<right agents>` in place of a
20
+ path, with any number of agents of a shipped scenario.
21
+ """
22
+ directory = os.path.join(_DATA_DIRECTORY, 'assets')
23
+ if not os.path.isdir(directory):
24
+ return []
25
+ return sorted(name[: -len('.cjb')] for name in os.listdir(directory) if name.endswith('.cjb'))
26
+
27
+
28
+ def _split_name(name):
29
+ """Returns the scenario, left and right agents of `<scenario>_l<left>_r<right>`, or `None`."""
30
+ match = re.fullmatch(r'(.+)_l(\d+)_r(\d+)', name)
31
+ return None if match is None else (match.group(1), int(match.group(2)), int(match.group(3)))
32
+
33
+
34
+ def bundled_scenarios() -> list[str]:
35
+ """Returns the scenarios of the asset bundles that the package ships, such as `5_vs_5`."""
36
+ return sorted({split[0] for split in map(_split_name, bundled_assets()) if split})
37
+
38
+
39
+ def _resolve_asset(asset: str) -> tuple[str, tuple[int, int]]:
40
+ """Returns the bundle path of a path or name, and the agents per side it asks for (-1 keeps)."""
41
+ if callable(asset):
42
+ raise TypeError(
43
+ 'expected the path of a scenario file or of a bundle, found a function; pass the path '
44
+ 'of its file, or build a bundle with cuju.scenarios.build_bundle'
45
+ )
46
+ # GRF: `create_environment` gives a scenario file or a bare name one left agent.
47
+ if os.path.isfile(asset):
48
+ return asset, (1, 0) if asset.endswith('.py') else (-1, -1)
49
+ if asset.endswith(('.py', '.cjb')) or os.sep in asset or '/' in asset:
50
+ raise MissingFileError(f'expected a scenario file or a bundle at {asset!r}, found no file')
51
+ directory = os.path.join(_DATA_DIRECTORY, 'assets')
52
+ shipped = os.path.join(directory, asset + '.cjb')
53
+ if os.path.isfile(shipped):
54
+ return shipped, (-1, -1)
55
+ split = _split_name(asset)
56
+ if split is None and asset in bundled_scenarios():
57
+ split = (asset, 1, 0)
58
+ if split:
59
+ scenario, left, right = split
60
+ # The bundle with the fewest agents serves any counts; the library sets up the agents anew.
61
+ bases = [name for name in bundled_assets() if (_split_name(name) or ('',))[0] == scenario]
62
+ if bases:
63
+ base = min(bases, key=lambda name: sum(_split_name(name)[1:]))
64
+ return os.path.join(directory, base + '.cjb'), (left, right)
65
+ raise MissingFileError(
66
+ f'expected the path of an asset bundle or `<scenario>_l<left>_r<right>` of one of '
67
+ f'{bundled_scenarios()}, found {asset!r}'
68
+ )