cuju-engine 0.3.0__py3-none-win_amd64.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 (222) 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/cuju_cpu.dll +0 -0
  34. cuju/cuju_cuda.dll +0 -0
  35. cuju/cuju_render.dll +0 -0
  36. cuju/data/SHA256SUMS +20 -0
  37. cuju/data/animations.bin +0 -0
  38. cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
  39. cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
  40. cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
  41. cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
  42. cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
  43. cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
  44. cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
  45. cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
  46. cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
  47. cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
  48. cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
  49. cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
  50. cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
  51. cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  52. cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  53. cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
  54. cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
  55. cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
  56. cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
  57. cuju/data/digests.json +186 -0
  58. cuju/data/render_digests.json.z +0 -0
  59. cuju/data/scenarios/11_vs_11_competition.py +45 -0
  60. cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
  61. cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
  62. cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
  63. cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
  64. cuju/data/scenarios/1_vs_1_easy.py +25 -0
  65. cuju/data/scenarios/5_vs_5.py +33 -0
  66. cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
  67. cuju/data/scenarios/academy_corner.py +45 -0
  68. cuju/data/scenarios/academy_counterattack_easy.py +45 -0
  69. cuju/data/scenarios/academy_counterattack_hard.py +45 -0
  70. cuju/data/scenarios/academy_empty_goal.py +25 -0
  71. cuju/data/scenarios/academy_empty_goal_close.py +25 -0
  72. cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
  73. cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
  74. cuju/data/scenarios/academy_run_to_score.py +30 -0
  75. cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
  76. cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
  77. cuju/data/scenarios/test_example_multiagent.py +28 -0
  78. cuju/dumps.py +942 -0
  79. cuju/engine_status.py +106 -0
  80. cuju/env.py +1168 -0
  81. cuju/errors.py +108 -0
  82. cuju/gfootball/GRF_SOURCES +86 -0
  83. cuju/gfootball/__init__.py +60 -0
  84. cuju/gfootball/_cv2.py +43 -0
  85. cuju/gfootball/_gym/__init__.py +88 -0
  86. cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
  87. cuju/gfootball/_gym/_vendored/__init__.py +43 -0
  88. cuju/gfootball/_gym/_vendored/core.py +361 -0
  89. cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
  90. cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
  91. cuju/gfootball/_gym/_vendored/error.py +230 -0
  92. cuju/gfootball/_gym/_vendored/logger.py +56 -0
  93. cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
  94. cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
  95. cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
  96. cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
  97. cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
  98. cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
  99. cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
  100. cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
  101. cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
  102. cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
  103. cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
  104. cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
  105. cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
  106. cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
  107. cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
  108. cuju/gfootball/_gym/_vendored/version.py +5 -0
  109. cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
  110. cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
  111. cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
  112. cuju/gfootball/dump_to_txt.py +49 -0
  113. cuju/gfootball/dump_to_video.py +33 -0
  114. cuju/gfootball/env/__init__.py +271 -0
  115. cuju/gfootball/env/config.py +163 -0
  116. cuju/gfootball/env/constants.py +33 -0
  117. cuju/gfootball/env/controller_base.py +114 -0
  118. cuju/gfootball/env/event_queue.py +54 -0
  119. cuju/gfootball/env/football_action_set.py +220 -0
  120. cuju/gfootball/env/football_action_set_test.py +76 -0
  121. cuju/gfootball/env/football_env.py +225 -0
  122. cuju/gfootball/env/football_env_core.py +447 -0
  123. cuju/gfootball/env/football_env_test.py +692 -0
  124. cuju/gfootball/env/gym_test.py +47 -0
  125. cuju/gfootball/env/observation_preprocessing.py +94 -0
  126. cuju/gfootball/env/observation_processor.py +526 -0
  127. cuju/gfootball/env/observation_rotation.py +163 -0
  128. cuju/gfootball/env/observation_rotation_test.py +84 -0
  129. cuju/gfootball/env/player_base.py +46 -0
  130. cuju/gfootball/env/players/__init__.py +16 -0
  131. cuju/gfootball/env/players/agent.py +39 -0
  132. cuju/gfootball/env/players/bot.py +217 -0
  133. cuju/gfootball/env/players/gamepad.py +81 -0
  134. cuju/gfootball/env/players/keyboard.py +72 -0
  135. cuju/gfootball/env/players/lazy.py +31 -0
  136. cuju/gfootball/env/players/ppo2_cnn.py +119 -0
  137. cuju/gfootball/env/players/replay.py +40 -0
  138. cuju/gfootball/env/remote_football_env.py +189 -0
  139. cuju/gfootball/env/scenario_builder.py +125 -0
  140. cuju/gfootball/env/script_helpers.py +130 -0
  141. cuju/gfootball/env/script_helpers_test.py +107 -0
  142. cuju/gfootball/env/wrappers.py +440 -0
  143. cuju/gfootball/env/wrappers_test.py +150 -0
  144. cuju/gfootball/eval_server/__init__.py +17 -0
  145. cuju/gfootball/eval_server/config.py +30 -0
  146. cuju/gfootball/eval_server/example_client.py +107 -0
  147. cuju/gfootball/eval_server/proto/game_server.proto +62 -0
  148. cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
  149. cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
  150. cuju/gfootball/eval_server/proto/master.proto +25 -0
  151. cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
  152. cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
  153. cuju/gfootball/eval_server/utils.py +52 -0
  154. cuju/gfootball/examples/__init__.py +16 -0
  155. cuju/gfootball/examples/models.py +66 -0
  156. cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
  157. cuju/gfootball/examples/run_ppo2.py +123 -0
  158. cuju/gfootball/play_game.py +73 -0
  159. cuju/gfootball/replay.py +43 -0
  160. cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
  161. cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
  162. cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
  163. cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
  164. cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
  165. cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
  166. cuju/gfootball/scenarios/5_vs_5.py +46 -0
  167. cuju/gfootball/scenarios/__init__.py +31 -0
  168. cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
  169. cuju/gfootball/scenarios/academy_corner.py +59 -0
  170. cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
  171. cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
  172. cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
  173. cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
  174. cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
  175. cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
  176. cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
  177. cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
  178. cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
  179. cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
  180. cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
  181. cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
  182. cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
  183. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
  184. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
  185. cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
  186. cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
  187. cuju/gfootball/scenarios/tests/__init__.py +31 -0
  188. cuju/gfootball/scenarios/tests/corner_test.py +38 -0
  189. cuju/gfootball/scenarios/tests/goal_test.py +35 -0
  190. cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
  191. cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
  192. cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
  193. cuju/gfootball/scenarios/tests/offside_test.py +39 -0
  194. cuju/gfootball/scenarios/tests/penalty.py +34 -0
  195. cuju/gfootball/scenarios/tests/second_half.py +33 -0
  196. cuju/gfootball/scenarios/tests/symmetric.py +53 -0
  197. cuju/gfootball_engine/__init__.py +31 -0
  198. cuju/gfootball_engine/_gameplayfootball.py +1624 -0
  199. cuju/gfootball_engine/_native.py +193 -0
  200. cuju/gfootball_engine/_pickle_names.py +114 -0
  201. cuju/gfootball_engine/_render_hooks.py +156 -0
  202. cuju/kaggle.py +425 -0
  203. cuju/multi_device.py +401 -0
  204. cuju/players.py +260 -0
  205. cuju/raw.py +93 -0
  206. cuju/scenarios.py +661 -0
  207. cuju/state.py +211 -0
  208. cuju/wrappers.py +325 -0
  209. cuju_engine-0.3.0.dist-info/METADATA +325 -0
  210. cuju_engine-0.3.0.dist-info/RECORD +222 -0
  211. cuju_engine-0.3.0.dist-info/WHEEL +5 -0
  212. cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
  213. cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
  214. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
  215. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
  216. cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
  217. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
  218. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
  219. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
  220. cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
  221. cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
  222. cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/state.py ADDED
@@ -0,0 +1,211 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Reads single fields of a GRF state, such as the joints of a player or the spin of the ball.
5
+
6
+ `layout` names every field of the match in memory, with its offset, size and type, and `gather`
7
+ loads a state, as `BatchEnvironment.get_state` or GRF's `get_state` return it, and copies chosen
8
+ fields out of it. The guide is in the repository's `docs/states.md`, under Reading fields.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ctypes
14
+ import functools
15
+ import struct
16
+ from collections.abc import Sequence
17
+ from typing import NamedTuple
18
+
19
+ import numpy as np
20
+
21
+ from .errors import ArgumentError, ChoiceError, LibraryError, StateError
22
+
23
+ __all__ = ['FRAMES', 'Field', 'gather', 'layout', 'read']
24
+
25
+ # The frames of `gather`, as the C API numbers them.
26
+ FRAMES = {'rest': 0, 'pitch': 1}
27
+
28
+ # GRF: the state names each type as C++'s `typeid` does, and stores it little-endian.
29
+ _DTYPES = {
30
+ 'f': ('<f4', ()),
31
+ 'i': ('<i4', ()),
32
+ 'j': ('<u4', ()),
33
+ 'b': ('u1', ()),
34
+ 'c': ('i1', ()),
35
+ 'm': ('<u8', ()),
36
+ 'N7blunted7Vector3E': ('<f4', (3,)),
37
+ 'N7blunted10QuaternionE': ('<f4', (4,)),
38
+ }
39
+
40
+
41
+ class Field(NamedTuple):
42
+ """One field of the match in memory.
43
+
44
+ Attributes:
45
+ path: Its name, such as `match.players[3].base.humanoid.nodes[0].rotation`.
46
+ offset: Its offset in bytes from the start of the match in memory.
47
+ size: Its size in bytes.
48
+ type: The type that GRF's state format gives it, such as `f` for a float.
49
+ """
50
+
51
+ path: str
52
+ offset: int
53
+ size: int
54
+ type: str
55
+
56
+
57
+ @functools.cache
58
+ def _library():
59
+ """Returns a loaded library, the CPU one where it loads, else the CUDA one."""
60
+ # Loading imports PyTorch, so it waits for the first state, and `import cuju.state` stays light.
61
+ from ._batch import library as _libraries
62
+
63
+ failures = []
64
+ for device in ('cpu', 'cuda'):
65
+ try:
66
+ library = _libraries._load_library(None, device)
67
+ except Exception as error:
68
+ failures.append(f'{device}: {error}')
69
+ continue
70
+ library.cuju_state_layout.restype = ctypes.c_void_p
71
+ library.cuju_state_layout.argtypes = [ctypes.POINTER(ctypes.c_ulonglong)]
72
+ library.cuju_state_gather.argtypes = [
73
+ ctypes.c_char_p,
74
+ ctypes.c_ulonglong,
75
+ ctypes.c_int,
76
+ ctypes.c_void_p,
77
+ ctypes.c_void_p,
78
+ ctypes.c_int,
79
+ ctypes.c_void_p,
80
+ ]
81
+ return library
82
+ raise LibraryError('expected a library of cuju that loads, found ' + '; '.join(failures))
83
+
84
+
85
+ @functools.cache
86
+ def _fields() -> dict[str, Field]:
87
+ """Returns the fields of `layout`, read once from the library."""
88
+ library = _library()
89
+ size = ctypes.c_ulonglong()
90
+ pointer = library.cuju_state_layout(ctypes.byref(size))
91
+ if not pointer:
92
+ raise LibraryError(library.cuju_last_error().decode())
93
+ fields = {}
94
+ for line in ctypes.string_at(pointer, size.value).decode().splitlines():
95
+ path, offset, length, kind = line.split('\t')
96
+ fields[path] = Field(path, int(offset), int(length), kind)
97
+ return fields
98
+
99
+
100
+ def layout() -> dict[str, Field]:
101
+ """Returns every field of the match in memory, by path, in the order of GRF's state format.
102
+
103
+ Each list covers its whole capacity, so a field such as the eleventh player exists even where a
104
+ state holds fewer, and the offsets hold for every state of every scenario. A field past the
105
+ count of its list holds no value of the match.
106
+
107
+ Returns:
108
+ A new dictionary from each path to its `Field`.
109
+ """
110
+ return dict(_fields())
111
+
112
+
113
+ def _match_bytes(state: bytes) -> bytes:
114
+ """Returns the match of a state, the bytes after its pickle length and its pickle."""
115
+ if len(state) < 4 or not 0 < struct.unpack_from('<i', state)[0] <= len(state) - 4:
116
+ raise StateError(
117
+ f'expected the bytes of a state: a pickle length, the pickle and the match, found '
118
+ f'{len(state)} bytes that hold none'
119
+ )
120
+ (length,) = struct.unpack_from('<i', state)
121
+ return state[4 + length :]
122
+
123
+
124
+ def _resolve(fields: Sequence[str | Field]) -> list[Field]:
125
+ """Returns the `Field` of each path or field, refusing paths that the layout lacks."""
126
+ known = _fields()
127
+ resolved = []
128
+ for field in fields:
129
+ if isinstance(field, Field):
130
+ resolved.append(field)
131
+ elif field in known:
132
+ resolved.append(known[field])
133
+ else:
134
+ raise ArgumentError(f'expected a path of cuju.state.layout(), found {field!r}')
135
+ return resolved
136
+
137
+
138
+ def gather(state: bytes, fields: Sequence[str | Field], frame: str = 'rest') -> bytes:
139
+ """Loads a state and returns the bytes of the chosen fields, one after another.
140
+
141
+ Args:
142
+ state: The bytes of a state, as `BatchEnvironment.get_state` or GRF's `get_state` return
143
+ them.
144
+ fields: Paths of `layout` or its `Field` values, in the order of the result.
145
+ frame: `rest`, where the match is as the engine keeps it and the right team plays mirrored,
146
+ or `pitch`, which turns the right team into the frame of the pitch as GRF's camera
147
+ does, so both teams and the ball share one frame with the left goal at negative x.
148
+
149
+ Returns:
150
+ The bytes of every field in turn, each as long as its `size`.
151
+
152
+ Raises:
153
+ ChoiceError: If `frame` is neither `rest` nor `pitch`. It is a `KeyError` and a
154
+ `ValueError`.
155
+ ArgumentError: If a path is not in `layout`. It is a `ValueError`.
156
+ StateError: If the bytes hold no state. It is a `ValueError` and a `RuntimeError`.
157
+ """
158
+ if frame not in FRAMES:
159
+ raise ChoiceError(f'expected the frame rest or pitch, found {frame!r}')
160
+ match = _match_bytes(state)
161
+ resolved = _resolve(fields)
162
+ offsets = np.array([field.offset for field in resolved], np.uint64)
163
+ sizes = np.array([field.size for field in resolved], np.uint32)
164
+ out = ctypes.create_string_buffer(int(sizes.sum()))
165
+ library = _library()
166
+ if library.cuju_state_gather(
167
+ match,
168
+ len(match),
169
+ FRAMES[frame],
170
+ offsets.ctypes.data,
171
+ sizes.ctypes.data,
172
+ len(resolved),
173
+ ctypes.addressof(out),
174
+ ):
175
+ raise StateError(library.cuju_last_error().decode())
176
+ return out.raw
177
+
178
+
179
+ def read(state: bytes, fields: Sequence[str | Field], frame: str = 'rest') -> list[np.ndarray]:
180
+ """Loads a state and returns the value of each chosen field as a numpy array.
181
+
182
+ A number or an enumeration becomes an array of no dimensions, a vector an array of three floats
183
+ and a quaternion an array of four, x, y, z then w. A field of another type, such as a radian,
184
+ which holds a float, a flag and padding, becomes its raw bytes as `uint8`.
185
+
186
+ Args:
187
+ state: The bytes of a state, as for `gather`.
188
+ fields: Paths of `layout` or its `Field` values.
189
+ frame: `rest` or `pitch`, as for `gather`.
190
+
191
+ Returns:
192
+ One array per field, in the order of `fields`.
193
+
194
+ Raises:
195
+ ChoiceError, ArgumentError, StateError: As `gather` raises them.
196
+ """
197
+ resolved = _resolve(fields)
198
+ data = gather(state, resolved, frame)
199
+ values, position = [], 0
200
+ for field in resolved:
201
+ chunk = data[position : position + field.size]
202
+ position += field.size
203
+ dtype, shape = _DTYPES.get(field.type, (None, ()))
204
+ # GRF: an enumeration is a C++ `enum`, four bytes on every platform it runs on.
205
+ if dtype is None and field.size == 4 and field.type[:1].isdigit():
206
+ dtype = '<i4'
207
+ if dtype is not None and np.dtype(dtype).itemsize * int(np.prod(shape)) == field.size:
208
+ values.append(np.frombuffer(chunk, dtype).reshape(shape).copy())
209
+ else:
210
+ values.append(np.frombuffer(chunk, np.uint8).copy())
211
+ return values
cuju/wrappers.py ADDED
@@ -0,0 +1,325 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """GRF's `MultiAgentToSingleAgent` wrapper, over every environment of a batch.
6
+
7
+ In a scenario that sets `control_all_players`, the policy sees and moves each side's designated
8
+ player, the one that leads the play, and the built-in AI moves the others. The guide is in the
9
+ repository's `docs/migrating-from-grf.md`, under Scripted players and `control_all_players`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ import torch
17
+
18
+ from .dumps import _CORE_ACTIONS
19
+
20
+ __all__ = ['MultiAgentToSingleAgent']
21
+
22
+ _ACTION_COUNTS = {'default': 19, 'v2': 20, 'full': 33}
23
+ # GRF: `football_action_set.action_builtin_ai`, index 19 of `v2` and `full`.
24
+ _BUILTIN_AI = 19
25
+
26
+
27
+ def _select(value, index):
28
+ """Returns `value[environment, index[environment, k]]` for every environment and `k`."""
29
+ rows = torch.arange(index.shape[0], device=index.device)[:, None]
30
+ if isinstance(value, dict):
31
+ return {name: tensor[rows, index] for name, tensor in value.items()}
32
+ return value[rows, index]
33
+
34
+
35
+ def _broadcast(flags, like):
36
+ """Returns `[environment_count]` flags shaped to broadcast over `like`."""
37
+ return flags.view((-1,) + (1,) * (like.dim() - 1))
38
+
39
+
40
+ class MultiAgentToSingleAgent:
41
+ """GRF's `MultiAgentToSingleAgent` over a batch whose scenario sets `control_all_players`.
42
+
43
+ The batch holds an agent for every controllable player of each side the policy plays, and the
44
+ wrapper gives the policy, for each such side, the agent whose active player is the side's
45
+ designated player. Each step moves that agent with the policy's action and every other agent
46
+ with `builtin_ai`, so the batch needs an action set that holds it. `v2` plays GRF's `default`
47
+ set exactly, since `default`'s 19 actions keep their indices in `v2`.
48
+
49
+ The reward is the batch's, `[environment_count, agents]`, as GRF's wrapper passes the reward of
50
+ every agent on. GRF's single-agent wrapper then takes the first agent's, as `squeeze` does here.
51
+
52
+ Attributes:
53
+ batch: The wrapped batch.
54
+ players: The sides the policy plays, 1 or 2, the left one first.
55
+ action_count: The actions of the policy's action set.
56
+ last_actions: The batch's actions of the last step, `[environment_count, agents]`.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ batch: Any,
62
+ left_players: int,
63
+ right_players: int,
64
+ action_set: str | None = None,
65
+ stacked: bool = False,
66
+ squeeze: bool = False,
67
+ _slots: list[int] | None = None,
68
+ ) -> None:
69
+ """Wraps a batch.
70
+
71
+ Args:
72
+ batch: A batch with `with_raw=True` or the raw representation, the action set `v2` or
73
+ `full`, which hold `builtin_ai`, no stack, and on each side either no agent or one
74
+ for every controllable player.
75
+ left_players: 1 if the policy plays the left side, else 0.
76
+ right_players: 1 if the policy plays the right side, else 0.
77
+ action_set: The policy's action set, `default`, `v2` or `full`, or `None` for the
78
+ batch's. `default` needs a batch of `v2` or `full`.
79
+ stacked: Whether the observation stacks the last 4 of the policy's observations, as
80
+ GRF's `FrameStack` over this wrapper does. The designated player changes during
81
+ play, so this differs from the batch's own stack, which stacks each agent's.
82
+ squeeze: Whether the observation drops the axis of the sides, except for `raw`, and the
83
+ reward keeps only the first agent's, as GRF's single-agent wrappers do for one side.
84
+
85
+ Raises:
86
+ ValueError: If the batch lacks the raw arrays or `builtin_ai`, stacks its observations,
87
+ holds agents on a side that the policy does not play or none on one it plays, or if
88
+ `squeeze` meets two sides or `stacked` meets `raw`.
89
+ KeyError: If `action_set` names no known set.
90
+ """
91
+ if left_players not in (0, 1) or right_players not in (0, 1):
92
+ raise ValueError(
93
+ f'expected 0 or 1 left and right players, found {left_players} and {right_players}'
94
+ )
95
+ if batch.action_count < _ACTION_COUNTS['v2']:
96
+ raise ValueError(
97
+ 'expected a batch whose action set holds builtin_ai; create it with '
98
+ "action_set='v2', which plays GRF's default set with the same indices, or 'full'"
99
+ )
100
+ if batch.stacked:
101
+ raise ValueError('expected a batch without a stack; pass stacked=True here instead')
102
+ if getattr(batch, '_raw_fields', None) is None:
103
+ raise ValueError('expected a batch with the raw representation or with_raw=True')
104
+ if stacked and batch._representation == 'raw':
105
+ raise ValueError('expected simple115, simple115v2 or extracted for a stack, found raw')
106
+ # The agents that the policy's sides cover. `create_environment` passes the slots of GRF's
107
+ # `agent` player, and the players of `extra_players` in the other slots act on their own.
108
+ covered = torch.ones(batch.agents, dtype=torch.bool)
109
+ if _slots is not None:
110
+ covered = torch.zeros(batch.agents, dtype=torch.bool)
111
+ covered[list(_slots)] = True
112
+ left = torch.arange(batch.agents) < batch.left_agents[:, None]
113
+ mask = batch.agent_mask & covered
114
+ side_masks = [left & mask, ~left & mask]
115
+ for side, players, agents in (
116
+ ('left', left_players, side_masks[0].sum(1)),
117
+ ('right', right_players, side_masks[1].sum(1)),
118
+ ):
119
+ if bool(((agents > 0) != bool(players)).any()):
120
+ raise ValueError(
121
+ f'expected {"agents" if players else "no agent"} on the {side} side of every '
122
+ f'environment, since the policy {"plays" if players else "does not play"} it'
123
+ )
124
+ self.players = left_players + right_players
125
+ if squeeze and self.players != 1:
126
+ raise ValueError('expected one side to squeeze the axis of the sides')
127
+ if action_set is None:
128
+ self.action_count = batch.action_count
129
+ else:
130
+ if action_set not in _ACTION_COUNTS:
131
+ raise KeyError(f'expected the action set {", ".join(map(repr, _ACTION_COUNTS))}')
132
+ self.action_count = _ACTION_COUNTS[action_set]
133
+ if self.action_count > batch.action_count:
134
+ raise ValueError(
135
+ f'expected a batch with the actions of {action_set!r}, found '
136
+ f'{batch.action_count}'
137
+ )
138
+ self.batch = batch
139
+ self._sides = [side for side, players in ((0, left_players), (1, right_players)) if players]
140
+ self._stacked = stacked
141
+ self._squeeze = squeeze
142
+ device = batch._torch_device
143
+ self._side_masks = [side_mask.to(device) for side_mask in side_masks]
144
+ self._index = None
145
+ self._frames = None
146
+ self._done = None
147
+ self.last_actions = None
148
+
149
+ def _selection(self, raw, only=None):
150
+ """Returns, for each environment, the agent of each side whose active player is designated.
151
+
152
+ Args:
153
+ raw: The raw arrays of the batch.
154
+ only: The environments to check, or `None` for every one. The others get any agent.
155
+
156
+ Raises:
157
+ RuntimeError: If a checked side has no such agent or several, which GRF's wrapper does
158
+ not handle either.
159
+ """
160
+ match = raw['active'] == raw['designated']
161
+ columns = []
162
+ for side in self._sides:
163
+ found = match & self._side_masks[side]
164
+ wrong = found.sum(1) != 1
165
+ if only is not None:
166
+ wrong &= only
167
+ if bool(wrong.any()):
168
+ environment = int(torch.nonzero(wrong)[0, 0])
169
+ raise RuntimeError(
170
+ f'environment {environment} has {int(found[environment].sum())} agents on the '
171
+ f'{("left", "right")[side]} side whose active player is the designated one, '
172
+ 'where the wrapper needs exactly one'
173
+ )
174
+ columns.append(found.int().argmax(1))
175
+ return torch.stack(columns, 1)
176
+
177
+ def _shape(self, observation):
178
+ """Applies `squeeze` to an observation of the policy."""
179
+ if not self._squeeze or isinstance(observation, dict):
180
+ # GRF: the raw observation of one agent keeps its agent axis.
181
+ return observation
182
+ return observation.squeeze(1)
183
+
184
+ def _current(self):
185
+ """Returns the observation of the selected agents in the last outputs of the batch."""
186
+ return _select(self.batch.observation(), self._index)
187
+
188
+ def observation(self) -> Any:
189
+ """Returns the policy's observation of the last `reset` or `step`.
190
+
191
+ It is `[environment_count, players, ...]`, or a dictionary for `raw`, stacked and squeezed
192
+ as the options say.
193
+ """
194
+ if self._index is None:
195
+ raise RuntimeError('reset must be called before the observation')
196
+ observation = torch.cat(self._frames, dim=-1) if self._stacked else self._current()
197
+ return self._shape(observation)
198
+
199
+ def reset(self, *args: Any, **kwargs: Any) -> Any:
200
+ """Resets the batch, with its arguments, and returns the policy's observation."""
201
+ self.batch.reset(*args, **kwargs)
202
+ self._index = self._selection(self.batch.raw())
203
+ if self._stacked:
204
+ self._frames = [self._current()] * 4
205
+ self._done = None
206
+ return self.observation()
207
+
208
+ def _inner_actions(self, actions):
209
+ """Returns the batch's actions, the policy's for the chosen agents and `builtin_ai` else."""
210
+ count = self.action_count
211
+ environments = self.batch.environment_count
212
+ if not isinstance(actions, torch.Tensor):
213
+ actions = torch.as_tensor(actions)
214
+ if actions.is_floating_point() or actions.is_complex():
215
+ raise TypeError(f'expected integer action indices, found {actions.dtype}')
216
+ if self.players == 1 and tuple(actions.shape) == (environments,):
217
+ actions = actions[:, None]
218
+ if tuple(actions.shape) != (environments, self.players):
219
+ raise ValueError(
220
+ f'expected actions of the shape {(environments, self.players)}, found '
221
+ f'{tuple(actions.shape)}'
222
+ )
223
+ # GRF: an action indexes the policy's set, so one outside it raises.
224
+ if actions.device.type == 'cpu' and bool(((actions < -count) | (actions >= count)).any()):
225
+ raise IndexError(f'expected actions from {-count} to {count - 1}')
226
+ actions = actions.to(self._index.device, torch.int64)
227
+ # A negative index counts from the end of the policy's set, not of the batch's.
228
+ actions = torch.where(actions < 0, actions + count, actions)
229
+ inner = torch.full(
230
+ (environments, self.batch.agents), _BUILTIN_AI, dtype=torch.int64, device=actions.device
231
+ )
232
+ inner.scatter_(1, self._index, actions)
233
+ return inner.to(torch.int32)
234
+
235
+ def step(
236
+ self, actions: Any, *, _others: list[tuple[int, int]] | None = None
237
+ ) -> tuple[Any, Any, Any, dict[str, Any]]:
238
+ """Runs one step of the batch.
239
+
240
+ Args:
241
+ actions: `[environment_count, players]` indices into the policy's action set, or
242
+ `[environment_count]` for one side.
243
+
244
+ Returns:
245
+ The policy's observation, the batch's reward `[environment_count, agents]`, or the
246
+ first agent's with `squeeze`, the done flags and the batch's information, whose
247
+ `final_observation` holds the policy's observation of the step that ended each
248
+ episode.
249
+
250
+ Raises:
251
+ RuntimeError: Before the first `reset`, or as `_selection`.
252
+ """
253
+ if self._index is None:
254
+ raise RuntimeError('reset must be called before step')
255
+ self.last_actions = self._inner_actions(actions)
256
+ # The players of `extra_players` that `create_environment` adds act in their own slots.
257
+ for slot, action in _others or []:
258
+ self.last_actions[:, slot] = action
259
+ _, reward, done, information = self.batch.step(self.last_actions)
260
+ ended = done.bool().to(self._index.device)
261
+ final = _select(
262
+ information['final_observation'], self._selection(self.batch.final_raw(), ended)
263
+ )
264
+ self._index = self._selection(self.batch.raw())
265
+ if self._stacked:
266
+ current = self._current()
267
+ # The step that ends an episode stacks its final observation, and an automatic reset
268
+ # then fills the stack with the first observation of the next episode.
269
+ frames = [*self._frames[1:], torch.where(_broadcast(ended, current), final, current)]
270
+ final = torch.cat(frames, dim=-1)
271
+ if self.batch.auto_reset:
272
+ frames = [torch.where(_broadcast(ended, current), current, f) for f in frames]
273
+ self._frames = frames
274
+ self._done = ended
275
+ if self._squeeze:
276
+ reward = reward[:, 0]
277
+ return (
278
+ self.observation(),
279
+ reward,
280
+ done,
281
+ {**information, 'final_observation': self._shape(final)},
282
+ )
283
+
284
+ def reset_done(self) -> None:
285
+ """Resets the environments whose episode ended, as the batch's `reset_done`."""
286
+ if self._index is None:
287
+ raise RuntimeError('reset must be called before reset_done')
288
+ self.batch.reset_done()
289
+ self._index = self._selection(self.batch.raw())
290
+ if self._stacked and self._done is not None:
291
+ current = self._current()
292
+ ended = _broadcast(self._done, current)
293
+ self._frames = [torch.where(ended, current, frame) for frame in self._frames]
294
+ self._done = None
295
+
296
+ def close(self) -> None:
297
+ """Closes the batch."""
298
+ self.batch.close()
299
+
300
+ @staticmethod
301
+ def get_observation(observation: list[dict[str, Any]]) -> list[dict[str, Any]]:
302
+ """Returns the raw observations of one environment whose active player is designated.
303
+
304
+ It is GRF's static method.
305
+ """
306
+ assert 'designated' in observation[0], 'Only raw observations can be converted'
307
+ return [entry for entry in observation if entry['designated'] == entry['active']]
308
+
309
+ @staticmethod
310
+ def get_action(actions: Any, original_observation: list[dict[str, Any]]) -> list[Any]:
311
+ """Returns an action for each raw observation of `original_observation`.
312
+
313
+ It is GRF's static method. Where the active player is the designated one it takes the next
314
+ of `actions`, and elsewhere GRF's `builtin_ai` action.
315
+ """
316
+
317
+ assert 'designated' in original_observation[0], 'Only raw observations can be converted'
318
+ result = [_CORE_ACTIONS['builtin_ai']] * len(original_observation)
319
+ action_index = 0
320
+ for index, entry in enumerate(original_observation):
321
+ if entry['designated'] == entry['active']:
322
+ assert action_index < len(actions)
323
+ result[index] = actions[action_index]
324
+ action_index += 1
325
+ return result