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/dumps.py ADDED
@@ -0,0 +1,942 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Episodes of a batch as GRF dumps, which GRF's `replay`, `dump_to_txt` and `dump_to_video` read.
4
+
5
+ A `DumpWriter` writes chosen environments of a batch in the format of GRF's
6
+ `observation_processor.py`, one pickle per step, and `read_dump` reads a dump without GRF or numpy.
7
+ The guide is in the repository's `docs/migrating-from-grf.md`, under Dumps from a batch.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import collections
13
+ import ctypes
14
+ import datetime
15
+ import io
16
+ import os
17
+ import pickle
18
+ import re
19
+ import struct
20
+ import timeit
21
+ from typing import Any
22
+
23
+ import torch
24
+
25
+ from .errors import ActionRangeError, ArgumentError, EnvironmentIndexError, LibraryError
26
+
27
+ __all__ = ['DumpWriter', 'read_dump']
28
+
29
+ # GRF's `e_BackendAction`, by value.
30
+ _BACKEND_ACTIONS = (
31
+ 'idle',
32
+ 'left',
33
+ 'top_left',
34
+ 'top',
35
+ 'top_right',
36
+ 'right',
37
+ 'bottom_right',
38
+ 'bottom',
39
+ 'bottom_left',
40
+ 'long_pass',
41
+ 'high_pass',
42
+ 'short_pass',
43
+ 'shot',
44
+ 'keeper_rush',
45
+ 'sliding',
46
+ 'pressure',
47
+ 'team_pressure',
48
+ 'switch',
49
+ 'sprint',
50
+ 'dribble',
51
+ 'release_direction',
52
+ 'release_long_pass',
53
+ 'release_high_pass',
54
+ 'release_short_pass',
55
+ 'release_shot',
56
+ 'release_keeper_rush',
57
+ 'release_sliding',
58
+ 'release_pressure',
59
+ 'release_team_pressure',
60
+ 'release_switch',
61
+ 'release_sprint',
62
+ 'release_dribble',
63
+ 'builtin_ai',
64
+ )
65
+ _DIRECTIONS = (
66
+ 'left',
67
+ 'top_left',
68
+ 'top',
69
+ 'top_right',
70
+ 'right',
71
+ 'bottom_right',
72
+ 'bottom',
73
+ 'bottom_left',
74
+ )
75
+ # GRF: `CoreAction`'s `sticky` and `directional` flags.
76
+ _STICKY = frozenset((*_DIRECTIONS, 'keeper_rush', 'pressure', 'team_pressure', 'sprint', 'dribble'))
77
+ _DIRECTIONAL = frozenset((*_DIRECTIONS, 'release_direction'))
78
+ # GRF: `observation_rotation.flip_single_action` turns a direction by 180 degrees.
79
+ _FLIPPED = {name: _DIRECTIONS[(index + 4) % 8] for index, name in enumerate(_DIRECTIONS)}
80
+ # GRF: `football_action_set.action_set_dict`.
81
+ _DEFAULT_SET = (
82
+ 'idle',
83
+ 'left',
84
+ 'top_left',
85
+ 'top',
86
+ 'top_right',
87
+ 'right',
88
+ 'bottom_right',
89
+ 'bottom',
90
+ 'bottom_left',
91
+ 'long_pass',
92
+ 'high_pass',
93
+ 'short_pass',
94
+ 'shot',
95
+ 'sprint',
96
+ 'release_direction',
97
+ 'release_sprint',
98
+ 'sliding',
99
+ 'dribble',
100
+ 'release_dribble',
101
+ )
102
+ _ACTION_SETS = {
103
+ 'default': _DEFAULT_SET,
104
+ 'v2': (*_DEFAULT_SET, 'builtin_ai'),
105
+ 'full': (
106
+ *_DEFAULT_SET,
107
+ 'builtin_ai',
108
+ 'keeper_rush',
109
+ 'pressure',
110
+ 'team_pressure',
111
+ 'switch',
112
+ 'release_long_pass',
113
+ 'release_high_pass',
114
+ 'release_short_pass',
115
+ 'release_shot',
116
+ 'release_keeper_rush',
117
+ 'release_sliding',
118
+ 'release_pressure',
119
+ 'release_team_pressure',
120
+ 'release_switch',
121
+ ),
122
+ }
123
+ _ACTION_SET_NAMES = {len(actions): name for name, actions in _ACTION_SETS.items()}
124
+ # GRF: `observation_processor.PAST_STEPS_TRACE_SIZE`, the steps before a goal in its dump.
125
+ _STEPS_BEFORE_GOAL = 100
126
+ # The count of values that `cuju_environment_episode` writes.
127
+ _EPISODE_VALUES = 17
128
+
129
+
130
+ class _BackendAction(int):
131
+ """Stands in for GRF's `e_BackendAction` in a pickle."""
132
+
133
+ __slots__ = ()
134
+
135
+
136
+ class _CoreAction:
137
+ """Stands in for GRF's `CoreAction` in a pickle, and serves as it in `cuju.gfootball.env`."""
138
+
139
+ def __init__(self, backend_action, name, sticky=False, directional=False):
140
+ # Exact: the pickle of an action holds these four attributes in GRF's order.
141
+ self._backend_action = backend_action
142
+ self._name = name
143
+ self._sticky = sticky
144
+ self._directional = directional
145
+
146
+ def is_in_actionset(self, config):
147
+ return self._name in _ACTION_SETS[config['action_set']]
148
+
149
+ # GRF: an action compares only with an action, by its name for equality and by its backend
150
+ # action for order.
151
+ def __eq__(self, other):
152
+ assert set(other.__dict__) == set(self.__dict__)
153
+ return self._name == other._name
154
+
155
+ def __ne__(self, other):
156
+ return not self.__eq__(other)
157
+
158
+ def __lt__(self, other):
159
+ assert set(other.__dict__) == set(self.__dict__)
160
+ return self._backend_action < other._backend_action
161
+
162
+ def __le__(self, other):
163
+ assert set(other.__dict__) == set(self.__dict__)
164
+ return self._backend_action <= other._backend_action
165
+
166
+ def __gt__(self, other):
167
+ assert set(other.__dict__) == set(self.__dict__)
168
+ return self._backend_action > other._backend_action
169
+
170
+ def __ge__(self, other):
171
+ assert set(other.__dict__) == set(self.__dict__)
172
+ return self._backend_action >= other._backend_action
173
+
174
+ def __hash__(self):
175
+ return int(self._backend_action)
176
+
177
+ def __repr__(self):
178
+ return self._name
179
+
180
+
181
+ _CORE_ACTIONS = {
182
+ name: _CoreAction(_BackendAction(value), name, name in _STICKY, name in _DIRECTIONAL)
183
+ for value, name in enumerate(_BACKEND_ACTIONS)
184
+ }
185
+
186
+
187
+ # A class, because the pickler saves a function by its own name and a class by `save_global`.
188
+ class _Reconstruct:
189
+ """Stands in for numpy's `_reconstruct` in a pickle."""
190
+
191
+
192
+ class _NumpyArray:
193
+ """Stands in for `numpy.ndarray` in a pickle."""
194
+
195
+
196
+ class _NumpyType:
197
+ """A numpy `dtype` in a pickle, with a `code` such as `f8` and its byte order."""
198
+
199
+ def __init__(self, code, order):
200
+ self.code, self.order = code, order
201
+
202
+ def __reduce__(self):
203
+ return _NumpyType, (self.code, False, True), (3, self.order, None, None, None, -1, -1, 0)
204
+
205
+
206
+ # The numpy types of GRF's observation, each with its struct format.
207
+ _FLOAT64 = (_NumpyType('f8', '<'), 'd')
208
+ _INT64 = (_NumpyType('i8', '<'), 'q')
209
+ _BOOL = (_NumpyType('b1', '|'), '?')
210
+ _UINT8 = (_NumpyType('u1', '|'), 'B')
211
+
212
+
213
+ class _Array:
214
+ """A numpy array in a pickle, which numpy reads as numpy 1 and 2 write it."""
215
+
216
+ def __init__(self, kind, shape, values):
217
+ self.kind, self.shape, self.values = kind, tuple(shape), list(values)
218
+
219
+ def __reduce__(self):
220
+ numpy_type, format_code = self.kind
221
+ data = struct.pack(f'<{len(self.values)}{format_code}', *self.values)
222
+ return _Reconstruct, (_NumpyArray, (0,), b'b'), (1, self.shape, numpy_type, False, data)
223
+
224
+
225
+ # The names under which GRF and numpy find the classes of the stand-ins. The module
226
+ # `numpy.core.multiarray` loads in numpy 1 and 2 alike.
227
+ _GLOBALS = {
228
+ _BackendAction: ('_gameplayfootball', 'e_BackendAction'),
229
+ _CoreAction: ('gfootball.env.football_action_set', 'CoreAction'),
230
+ _Reconstruct: ('numpy.core.multiarray', '_reconstruct'),
231
+ _NumpyArray: ('numpy', 'ndarray'),
232
+ _NumpyType: ('numpy', 'dtype'),
233
+ }
234
+
235
+
236
+ class _Pickler(pickle._Pickler):
237
+ """Pickles the stand-ins as references to GRF's and numpy's classes, without importing them."""
238
+
239
+ def save_global(self, obj, name=None):
240
+ target = _GLOBALS.get(obj)
241
+ if target is None:
242
+ return super().save_global(obj, name)
243
+ module, qualified = target
244
+ self.save(module)
245
+ self.save(qualified)
246
+ self.write(pickle.STACK_GLOBAL)
247
+ self.memoize(obj)
248
+ return None
249
+
250
+
251
+ def _pickle(entry):
252
+ """Returns the pickle of one step, as GRF's `cPickle.dump` writes it."""
253
+ buffer = io.BytesIO()
254
+ _Pickler(buffer, protocol=4).dump(entry)
255
+ return buffer.getvalue()
256
+
257
+
258
+ def _write_file(path, pickles):
259
+ """Writes the pickles of a dump to `path`, which appears only once complete."""
260
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
261
+ temporary = path + '.writing'
262
+ with open(temporary, 'wb') as handle:
263
+ for data in pickles:
264
+ handle.write(data)
265
+ os.replace(temporary, path)
266
+
267
+
268
+ def _difficulty_text(value):
269
+ """Returns a difficulty as part of a module name, `none` for the scenario's, else like `0p5`."""
270
+ return 'none' if value is None else repr(float(value)).replace('.', 'p').replace('-', 'm')
271
+
272
+
273
+ _SCENARIO_FILE = """# A GRF scenario: {base} with the team difficulties of a cuju batch.
274
+ import importlib
275
+
276
+ _BASE = importlib.import_module('gfootball.scenarios.{base}')
277
+
278
+
279
+ def build_scenario(builder):
280
+ _BASE.build_scenario(builder)
281
+ {lines}"""
282
+
283
+
284
+ def _flip_sticky(states, sticky_names):
285
+ """Returns sticky action states for the other side, as GRF's `rotate_sticky_actions`."""
286
+ index = {name: position for position, name in enumerate(sticky_names)}
287
+ return [states[index[_FLIPPED.get(name, name)]] for name in sticky_names]
288
+
289
+
290
+ class _Episode:
291
+ """The steps of one episode of one environment that the writer has read."""
292
+
293
+ def __init__(self, environment, values, config, full, goals):
294
+ self.environment = environment
295
+ self.episode = values[2]
296
+ self.left, self.right = values[9], values[10]
297
+ self.sizes = (values[11], values[12])
298
+ self.config = config
299
+ self.full = full
300
+ self.goals = goals
301
+ self.pickles = []
302
+ self.recent = collections.deque(maxlen=_STEPS_BEFORE_GOAL)
303
+ self.cumulative = 0
304
+ self.frame = 0
305
+ # The time that names the dump of the episode as GRF names it.
306
+ self.stamp = None
307
+
308
+
309
+ def _stamp():
310
+ """Returns the time of now as GRF's dumps name it, such as `20261027-142233123456`."""
311
+ return datetime.datetime.now().strftime('%Y%m%d-%H%M%S%f')
312
+
313
+
314
+ class DumpWriter:
315
+ """Writes the episodes of chosen environments of a batch as GRF dumps.
316
+
317
+ Create it before the batch's `reset`, or right after one, and call `record` after every
318
+ `step` with the actions of that step. An environment that the writer meets in the middle of an
319
+ episode starts with its next episode. An episode that `set_state` or a `reset` cuts is dropped.
320
+
321
+ GRF throttles its dumps by wall-clock time, a full-episode dump at most every 10 seconds and a
322
+ goal dump at most every 10 minutes. The writer writes every episode that `dump_frequency`
323
+ selects, and every goal. An episode whose difficulties differ from its scenario's names its
324
+ level `<scenario>_difficulty_<left>_<right>` and writes that GRF scenario file into `logdir`.
325
+
326
+ Attributes:
327
+ batch: The `BatchEnvironment`.
328
+ logdir: The directory of the dumps, GRF's `logdir`, which each configuration names as
329
+ `tracesdir`.
330
+ environments: The environments that the writer follows.
331
+ write_full_episode_dumps, write_goal_dumps, dump_frequency: GRF's dump options.
332
+ paths: The path of every dump written so far.
333
+ """
334
+
335
+ def __init__(
336
+ self,
337
+ batch: Any,
338
+ logdir: str,
339
+ environments: Any = None,
340
+ write_full_episode_dumps: bool = True,
341
+ write_goal_dumps: bool = False,
342
+ dump_frequency: int = 1,
343
+ ) -> None:
344
+ """Follows `environments` of `batch` from the episodes that its next steps start.
345
+
346
+ Args:
347
+ batch: A `BatchEnvironment`.
348
+ logdir: The directory of the dumps, created when the first is written.
349
+ environments: The indices of the environments to follow, or `None` for every one.
350
+ write_full_episode_dumps: Whether to write each selected episode as
351
+ `episode_done_environment_<index>_episode_<episode>.dump`, as GRF's option.
352
+ write_goal_dumps: Whether to write, at each goal of a selected episode, the steps
353
+ before it, up to 100, and the step that scored, as GRF's `score_...` and
354
+ `lost_score_...` dumps, the latter for a goal of the right team.
355
+ dump_frequency: GRF's option, which selects the first episode of an environment and
356
+ then every `dump_frequency`-th, or every one at 1 or less.
357
+
358
+ Raises:
359
+ EnvironmentIndexError: If an environment lies outside the batch. It is an
360
+ `IndexError` and a `RuntimeError`.
361
+ ClosedError: If the batch is closed. It is a `RuntimeError`.
362
+ LibraryError: If the library of the batch lacks the episode bookkeeping of this
363
+ version. It is a `RuntimeError`.
364
+ """
365
+ batch._handle()
366
+ library = batch._library
367
+ try:
368
+ library.cuju_environment_episode.argtypes = [
369
+ ctypes.c_void_p,
370
+ ctypes.c_int,
371
+ ctypes.c_void_p,
372
+ ctypes.c_void_p,
373
+ ]
374
+ library.cuju_environment_scenario.restype = ctypes.c_char_p
375
+ library.cuju_environment_scenario.argtypes = [ctypes.c_void_p, ctypes.c_int]
376
+ except AttributeError as error:
377
+ raise LibraryError(
378
+ 'the library of the batch lacks cuju_environment_episode; rebuild it'
379
+ ) from error
380
+ count = batch.environment_count
381
+ if environments is None:
382
+ environments = range(count)
383
+ self.environments = list(dict.fromkeys(int(environment) for environment in environments))
384
+ outside = [index for index in self.environments if not 0 <= index < count]
385
+ if outside:
386
+ raise EnvironmentIndexError(
387
+ f'expected environments from 0 to {count - 1}, found {outside}'
388
+ )
389
+ self.batch = batch
390
+ self.logdir = os.fspath(logdir)
391
+ self.write_full_episode_dumps = bool(write_full_episode_dumps)
392
+ self.write_goal_dumps = bool(write_goal_dumps)
393
+ self.dump_frequency = int(dump_frequency)
394
+ self.paths: list[str] = []
395
+ # Whether the dumps take GRF's names, as for the one environment of `create_environment`.
396
+ self._grf_names = False
397
+ self._action_set = _ACTION_SETS[_ACTION_SET_NAMES[batch.action_count]]
398
+ self._sticky = [name for name in self._action_set if name in _STICKY]
399
+ self._index = torch.tensor(self.environments, dtype=torch.long)
400
+ self._episodes: dict[int, _Episode | None] = {}
401
+ self._scenario_files: set[str] = set()
402
+ batch._wait_for_device()
403
+ for environment in self.environments:
404
+ values, _ = self._episode_values(environment)
405
+ # A batch reset and not yet stepped holds each episode at its start.
406
+ self._episodes[environment] = (
407
+ self._open(environment) if values[2] >= 1 and values[5] == -1 else None
408
+ )
409
+
410
+ def _episode_values(self, environment, difficulty=False):
411
+ """Returns an environment's `cuju_environment_episode` values, and difficulties if asked."""
412
+ return _episode_values(self.batch, environment, difficulty)
413
+
414
+ def _level(self, bundle, difficulties):
415
+ """Returns GRF's `level` of an episode, writing a scenario file for its own difficulties."""
416
+ batch = self.batch
417
+ name = batch._library.cuju_environment_scenario(batch._handle(), bundle).decode()
418
+ played, own = difficulties[:2], difficulties[2:]
419
+ pair = [None if value == base else value for value, base in zip(played, own, strict=True)]
420
+ if pair == [None, None]:
421
+ return name
422
+ level = f'{name}_difficulty_{_difficulty_text(pair[0])}_{_difficulty_text(pair[1])}'
423
+ if level not in self._scenario_files:
424
+ lines = ''.join(
425
+ f' builder.config().{side}_team_difficulty = {value!r}\n'
426
+ for side, value in zip(('left', 'right'), pair, strict=True)
427
+ if value is not None
428
+ )
429
+ path = os.path.join(self.logdir, level + '.py')
430
+ os.makedirs(self.logdir, exist_ok=True)
431
+ with open(path, 'w', encoding='utf-8') as handle:
432
+ handle.write(_SCENARIO_FILE.format(base=name, lines=lines))
433
+ self._scenario_files.add(level)
434
+ return level
435
+
436
+ def _config(self, values, difficulties):
437
+ """Returns the configuration of GRF's dump, as `Config.get_dictionary()` holds it."""
438
+ seed, reverse, episode, offset, bundle, _, fixed, deterministic, ticks, left, right = (
439
+ values[:11]
440
+ )
441
+ config = {
442
+ 'action_set': _ACTION_SET_NAMES[self.batch.action_count],
443
+ 'custom_display_stats': None,
444
+ 'display_game_stats': True,
445
+ 'dump_full_episodes': self.write_full_episode_dumps,
446
+ 'dump_scores': self.write_goal_dumps,
447
+ # GRF: a team without agents plays itself, and no agent gives no player.
448
+ 'players': [f'agent:left_players={left},right_players={right}'] if left + right else [],
449
+ 'level': self._level(bundle, difficulties),
450
+ 'physics_steps_per_frame': ticks,
451
+ 'render_resolution_x': 1280,
452
+ 'real_time': False,
453
+ 'tracesdir': self.logdir,
454
+ 'video_format': 'avi',
455
+ 'video_quality_level': 0,
456
+ 'write_video': False,
457
+ 'render_resolution_y': 720,
458
+ }
459
+ # GRF: a seed given as an option precedes the episode number, and a drawn one is a value
460
+ # of the scenario, which `get_dictionary` adds last.
461
+ if fixed >= 0:
462
+ config['game_engine_random_seed'] = seed
463
+ # GRF: the creation of an environment builds the scenario of its first number, and each
464
+ # reset the next, so the first episode is the second. Its parity picks the scenario's form.
465
+ config['episode_number'] = episode + 1 + offset
466
+ if not deterministic:
467
+ config['reverse_team_processing'] = bool(reverse)
468
+ if fixed < 0:
469
+ config['game_engine_random_seed'] = seed
470
+ return config
471
+
472
+ def _open(self, environment):
473
+ """Returns the episode that an environment starts, with the dumps it selects."""
474
+ values, difficulties = self._episode_values(environment, difficulty=True)
475
+ frequency = self.dump_frequency
476
+ # GRF: `PeriodicDumpWriter` counts the resets, the first included.
477
+ selected = frequency <= 1 or (values[2] - 1) % frequency == 0
478
+ return _Episode(
479
+ environment,
480
+ values,
481
+ self._config(values, difficulties),
482
+ selected and self.write_full_episode_dumps,
483
+ selected and self.write_goal_dumps,
484
+ )
485
+
486
+ def _observation(self, rows, episode, designated):
487
+ """Returns GRF's observation of the match from an episode's raw views, or `None`."""
488
+ return _match_observation(rows, episode, designated, self._sticky)
489
+
490
+ def _core_actions(self, episode, row):
491
+ """Returns GRF's `CoreAction`s of one step, with the right agents' directions turned."""
492
+ count = len(self._action_set)
493
+ actions = []
494
+ for agent, index in enumerate(row[: episode.left + episode.right]):
495
+ # GRF: an action indexes a Python list.
496
+ if not -count <= index < count:
497
+ raise ActionRangeError(
498
+ f'expected action indices from {-count} to {count - 1}, found {index} for '
499
+ f'environment {episode.environment}'
500
+ )
501
+ name = self._action_set[index]
502
+ turned = agent >= episode.left
503
+ actions.append(_CORE_ACTIONS[_FLIPPED.get(name, name) if turned else name])
504
+ return actions
505
+
506
+ def _path(self, kind, episode, frame=None, stamp=None):
507
+ """Returns the path of a dump of an episode, and keeps it in `paths`.
508
+
509
+ The writer of one environment of `create_environment` names a dump as GRF does,
510
+ `<logdir>/<kind>_<date>-<time>.dump`, with the time when GRF starts the dump, `stamp` or
511
+ now. Two environments of a batch can start dumps in the same microsecond, so a batch's
512
+ writer names each by its environment, its episode and, for a goal, its step.
513
+ """
514
+ if self._grf_names:
515
+ path = f'{self.logdir}{os.sep}{kind}_{stamp or _stamp()}.dump'
516
+ else:
517
+ name = f'{kind}_environment_{episode.environment}_episode_{episode.episode}'
518
+ if frame is not None:
519
+ name += f'_step_{frame}'
520
+ path = os.path.join(self.logdir, name + '.dump')
521
+ self.paths.append(path)
522
+ return path
523
+
524
+ def _append(self, episode, entry):
525
+ """Adds a step to an episode, and returns the kind and the path of a goal dump it writes."""
526
+ written = []
527
+ reward = entry['reward']
528
+ # GRF: the first step of a dump takes the configuration into the step itself, so a later
529
+ # dump that holds the step holds it too.
530
+ if episode.goals and reward in (1, -1):
531
+ # GRF: the dump of a goal holds the steps before it and the step that scored.
532
+ entries = [*episode.recent, entry]
533
+ entries[0]['debug']['config'] = episode.config
534
+ kind = 'score' if reward == 1 else 'lost_score'
535
+ path = self._path(kind, episode, entry['debug']['frame_cnt'])
536
+ _write_file(path, map(_pickle, entries))
537
+ written.append((kind, path))
538
+ if episode.full:
539
+ if not episode.pickles:
540
+ entry['debug']['config'] = episode.config
541
+ # GRF: the dump of the episode starts, and takes its time, after the first step.
542
+ episode.stamp = _stamp()
543
+ episode.pickles.append(_pickle(entry))
544
+ if episode.goals:
545
+ episode.recent.append(entry)
546
+ return written
547
+
548
+ def _finish(self, episode):
549
+ """Writes the full dump of an episode, if selected, and returns its kind and path."""
550
+ if not episode.full or not episode.pickles:
551
+ return []
552
+ path = self._path('episode_done', episode, stamp=episode.stamp)
553
+ _write_file(path, episode.pickles)
554
+ return [('episode_done', path)]
555
+
556
+ def _rows(self, actions):
557
+ """Returns the followed environments' actions, dones, rewards and raw views on the host."""
558
+ batch = self.batch
559
+ shape = (batch.environment_count, batch.agents)
560
+ _, _, done, _ = batch._outputs()
561
+ index = self._index.to(done.device)
562
+ action_rows = actions.reshape(shape)[index.to(actions.device)].to('cpu').tolist()
563
+ ended = done[index].bool()
564
+ score = batch._buffer('score_reward', (batch.environment_count,), torch.int32)
565
+ reward_rows = score[index].to('cpu').tolist()
566
+ raw_rows = None
567
+ if batch._raw_fields is not None:
568
+ # An ended episode's last observation is in `final_raw`, which an automatic reset
569
+ # keeps.
570
+ current, final = batch._raw('raw'), batch._raw('final_raw')
571
+ raw_rows = {
572
+ name: torch.where(
573
+ ended.reshape(-1, *[1] * (current[name].dim() - 1)),
574
+ final[name][index],
575
+ current[name][index],
576
+ )
577
+ .to('cpu')
578
+ .tolist()
579
+ for name in current
580
+ }
581
+ return action_rows, ended.to('cpu').tolist(), reward_rows, raw_rows
582
+
583
+ def _entry(self, episode, actions, reward, raw, designated):
584
+ """Returns GRF's entry of an episode's next step, and counts the step."""
585
+ episode.cumulative += reward
586
+ entry = {
587
+ 'debug': {
588
+ 'action': self._core_actions(episode, actions),
589
+ 'frame_cnt': episode.frame,
590
+ 'reward': reward,
591
+ 'time': timeit.default_timer(),
592
+ }
593
+ }
594
+ observation = None if raw is None else self._observation(raw, episode, designated)
595
+ if observation is not None:
596
+ entry['observation'] = observation
597
+ entry['reward'] = reward
598
+ entry['cumulative_reward'] = episode.cumulative
599
+ episode.frame += 1
600
+ return entry
601
+
602
+ def record(self, actions: Any) -> list[str]:
603
+ """Reads the step that just ran and writes the dumps it completes.
604
+
605
+ Call it after each `step`, before `reset_done`.
606
+
607
+ Args:
608
+ actions: The actions that the step took, `[environment_count, agents]`, or
609
+ `[environment_count]` for one agent.
610
+
611
+ Returns:
612
+ The paths of the dumps that this call wrote.
613
+
614
+ Raises:
615
+ ArgumentError: If the actions have another shape. It is a `ValueError`.
616
+ ActionRangeError: If an action lies outside the action set. It is an `IndexError`.
617
+ """
618
+ return [path for _, path in self._record(actions)]
619
+
620
+ def _record(self, actions):
621
+ """Does what `record` does, and returns the kind and the path of each dump written."""
622
+ batch = self.batch
623
+ batch._handle()
624
+ actions = torch.as_tensor(actions)
625
+ shape = (batch.environment_count, batch.agents)
626
+ if tuple(actions.shape) != shape and not (
627
+ batch.agents == 1 and tuple(actions.shape) == (batch.environment_count,)
628
+ ):
629
+ raise ArgumentError(
630
+ f'expected the actions of the step, {shape}, found {tuple(actions.shape)}'
631
+ )
632
+ action_rows, done_rows, reward_rows, raw_rows = self._rows(actions)
633
+ batch._wait_for_device()
634
+ auto_reset = batch.auto_reset
635
+ written = []
636
+ for row, environment in enumerate(self.environments):
637
+ values, _ = self._episode_values(environment)
638
+ episodes, step = values[2], values[5]
639
+ episode = self._episodes[environment]
640
+ ended = bool(done_rows[row])
641
+ if ended:
642
+ # A reset in the step leaves the next episode at its start.
643
+ continues = episode is not None and (
644
+ (episodes == episode.episode + 1 and step == -1)
645
+ if auto_reset
646
+ else (episodes == episode.episode and step == episode.frame)
647
+ )
648
+ else:
649
+ # Within an episode the step count goes up by one per step, so another count means
650
+ # a reset or a state set in between.
651
+ if episode is not None and not (
652
+ episodes == episode.episode and step == episode.frame
653
+ ):
654
+ episode = None
655
+ if episode is None and step == 0:
656
+ episode = self._open(environment)
657
+ continues = episode is not None
658
+ if continues:
659
+ raw = None
660
+ if raw_rows is not None:
661
+ raw = [
662
+ {name: raw_rows[name][row][agent] for name in raw_rows}
663
+ for agent in range(batch.agents)
664
+ ]
665
+ # An ended episode's designated players outlive the automatic reset in its slot.
666
+ designated = values[15:17] if ended else values[13:15]
667
+ entry = self._entry(
668
+ episode, action_rows[row], int(reward_rows[row]), raw, designated
669
+ )
670
+ written += self._append(episode, entry)
671
+ if ended:
672
+ written += self._finish(episode)
673
+ if ended:
674
+ episode = self._open(environment) if auto_reset and step == -1 else None
675
+ self._episodes[environment] = episode
676
+ return written
677
+
678
+ def close(self) -> list[str]:
679
+ """Writes each unfinished episode as its dump and stops following the batch.
680
+
681
+ GRF also leaves the dump of an episode that its environment closes in.
682
+
683
+ Returns:
684
+ The paths of the dumps that this call wrote.
685
+ """
686
+ written = []
687
+ for environment, episode in self._episodes.items():
688
+ if episode is not None:
689
+ written += [path for _, path in self._finish(episode)]
690
+ self._episodes[environment] = None
691
+ return written
692
+
693
+ def __enter__(self) -> DumpWriter:
694
+ return self
695
+
696
+ def __exit__(self, *exception: Any) -> None:
697
+ self.close()
698
+
699
+
700
+ def _episode_values(batch, environment, difficulty=False):
701
+ """Returns an environment's `cuju_environment_episode` values, and difficulties if asked."""
702
+ library = batch._library
703
+ library.cuju_environment_episode.argtypes = [
704
+ ctypes.c_void_p,
705
+ ctypes.c_int,
706
+ ctypes.c_void_p,
707
+ ctypes.c_void_p,
708
+ ]
709
+ values = (ctypes.c_longlong * _EPISODE_VALUES)()
710
+ difficulties = (ctypes.c_float * 4)() if difficulty else None
711
+ with batch._on_device():
712
+ batch._check(
713
+ library.cuju_environment_episode(
714
+ batch._handle(),
715
+ environment,
716
+ ctypes.addressof(values),
717
+ None if difficulties is None else ctypes.addressof(difficulties),
718
+ )
719
+ )
720
+ return list(values), None if difficulties is None else list(difficulties)
721
+
722
+
723
+ def _sticky_names(action_count):
724
+ """Returns the names of the sticky actions of the action set of `action_count` actions."""
725
+ return [name for name in _ACTION_SETS[_ACTION_SET_NAMES[action_count]] if name in _STICKY]
726
+
727
+
728
+ def _match_observation(rows, episode, designated, sticky_names):
729
+ """Returns GRF's observation of the match from an episode's raw views, or `None`.
730
+
731
+ It is the dictionary of GRF's `FootballEnvCore.observation()`, which a dump holds, with the
732
+ arrays as `_Array` stand-ins.
733
+
734
+ Args:
735
+ rows: The raw observation of each agent of the environment, as lists.
736
+ episode: The `_Episode`, which gives the agents of each side and the team sizes.
737
+ designated: The designated player of each team.
738
+ sticky_names: The names of the sticky actions of the action set.
739
+ """
740
+ left, right = episode.left, episode.right
741
+ if left + right == 0:
742
+ return None
743
+ # GRF: a right agent, here the first agent without left agents, sees the match turned by
744
+ # 180 degrees with the teams swapped.
745
+ base = rows[0]
746
+ turned = not left
747
+ sign = -1.0 if turned else 1.0
748
+
749
+ def point(values):
750
+ return _Array(_FLOAT64, (3,), [sign * values[0], sign * values[1], values[2]])
751
+
752
+ observation = {
753
+ 'ball': point(base['ball']),
754
+ 'ball_direction': point(base['ball_direction']),
755
+ 'ball_rotation': _Array(_FLOAT64, (3,), base['ball_rotation']),
756
+ }
757
+ for side, chosen, size in zip(('left', 'right'), designated, episode.sizes, strict=True):
758
+ source = side if not turned else ('right' if side == 'left' else 'left')
759
+ positions = [sign * value for pair in base[f'{source}_team'][:size] for value in pair]
760
+ directions = [
761
+ sign * value for pair in base[f'{source}_team_direction'][:size] for value in pair
762
+ ]
763
+ observation[f'{side}_team'] = _Array(_FLOAT64, (size, 2), positions)
764
+ observation[f'{side}_team_direction'] = _Array(_FLOAT64, (size, 2), directions)
765
+ observation[f'{side}_team_tired_factor'] = _Array(
766
+ _FLOAT64, (size,), base[f'{source}_team_tired_factor'][:size]
767
+ )
768
+ observation[f'{side}_team_active'] = _Array(
769
+ _BOOL, (size,), base[f'{source}_team_active'][:size]
770
+ )
771
+ observation[f'{side}_team_yellow_card'] = _Array(
772
+ _BOOL, (size,), base[f'{source}_team_yellow_card'][:size]
773
+ )
774
+ observation[f'{side}_team_roles'] = _Array(
775
+ _INT64, (size,), base[f'{source}_team_roles'][:size]
776
+ )
777
+ # GRF: every team has one, -1 for none, with or without agents.
778
+ observation[f'{side}_team_designated_player'] = chosen
779
+ sticky = len(sticky_names)
780
+ observation['left_agent_sticky_actions'] = [
781
+ _Array(_UINT8, (sticky,), rows[agent]['sticky_actions']) for agent in range(left)
782
+ ]
783
+ observation['left_agent_controlled_player'] = [rows[agent]['active'] for agent in range(left)]
784
+ observation['right_agent_sticky_actions'] = [
785
+ _Array(_UINT8, (sticky,), _flip_sticky(rows[agent]['sticky_actions'], sticky_names))
786
+ for agent in range(left, left + right)
787
+ ]
788
+ observation['right_agent_controlled_player'] = [
789
+ rows[agent]['active'] for agent in range(left, left + right)
790
+ ]
791
+ owned = base['ball_owned_team']
792
+ score = base['score']
793
+ observation['game_mode'] = base['game_mode']
794
+ observation['score'] = [score[1], score[0]] if turned else [score[0], score[1]]
795
+ observation['ball_owned_team'] = (1 - owned if owned > -1 else -1) if turned else owned
796
+ observation['ball_owned_player'] = base['ball_owned_player']
797
+ observation['steps_left'] = base['steps_left']
798
+ return observation
799
+
800
+
801
+ class _ReadAction:
802
+ """GRF's `CoreAction` as `read_dump` loads it."""
803
+
804
+
805
+ class _ReadBackendAction(int):
806
+ """GRF's `e_BackendAction` as `read_dump` loads it."""
807
+
808
+
809
+ class _ReadType:
810
+ """A numpy `dtype` as `read_dump` loads it."""
811
+
812
+ def __init__(self, code, align=False, copy=True):
813
+ self.code, self.order = code, '|'
814
+
815
+ def __setstate__(self, state):
816
+ self.order = state[1]
817
+
818
+
819
+ class _ReadArray:
820
+ """A numpy array as `read_dump` loads it."""
821
+
822
+ def __setstate__(self, state):
823
+ _, self.shape, self.type, _, self.data = state
824
+
825
+
826
+ def _read_reconstruct(cls, shape, code):
827
+ return _ReadArray()
828
+
829
+
830
+ def _read_frombuffer(buffer, numpy_type, shape, order):
831
+ array = _ReadArray()
832
+ array.shape, array.type, array.data = shape, numpy_type, bytes(buffer)
833
+ return array
834
+
835
+
836
+ _READ_TYPES = {
837
+ 'f8': torch.float64,
838
+ 'f4': torch.float32,
839
+ 'i8': torch.int64,
840
+ 'i4': torch.int32,
841
+ 'u1': torch.uint8,
842
+ 'b1': torch.bool,
843
+ }
844
+ _READ_GLOBALS = {
845
+ ('gfootball.env.football_action_set', 'CoreAction'): _ReadAction,
846
+ ('_gameplayfootball', 'e_BackendAction'): _ReadBackendAction,
847
+ ('gfootball_engine', 'e_BackendAction'): _ReadBackendAction,
848
+ # The names of the same classes in the dumps of GRF's Python under `cuju.gfootball`.
849
+ ('cuju.gfootball.env.football_action_set', 'CoreAction'): _ReadAction,
850
+ ('cuju.gfootball_engine._gameplayfootball', 'e_BackendAction'): _ReadBackendAction,
851
+ ('cuju.gfootball_engine', 'e_BackendAction'): _ReadBackendAction,
852
+ ('numpy.core.multiarray', '_reconstruct'): _read_reconstruct,
853
+ ('numpy._core.multiarray', '_reconstruct'): _read_reconstruct,
854
+ ('numpy.core.numeric', '_frombuffer'): _read_frombuffer,
855
+ ('numpy._core.numeric', '_frombuffer'): _read_frombuffer,
856
+ ('numpy', 'ndarray'): _ReadArray,
857
+ ('numpy', 'dtype'): _ReadType,
858
+ }
859
+
860
+
861
+ class _DumpUnpickler(pickle.Unpickler):
862
+ """Reads a dump and resolves only GRF's actions and numpy's arrays."""
863
+
864
+ def find_class(self, module, name):
865
+ target = _READ_GLOBALS.get((module, name))
866
+ if target is None:
867
+ raise pickle.UnpicklingError(f'expected a GRF dump, found `{module}.{name}`')
868
+ return target
869
+
870
+
871
+ def _converted(value):
872
+ """Returns a loaded value with tensors for arrays and names for actions."""
873
+ if isinstance(value, _ReadArray):
874
+ dtype = _READ_TYPES.get(re.sub(r'^[<|=]', '', value.type.code))
875
+ if dtype is None or value.type.order == '>':
876
+ raise pickle.UnpicklingError(f'expected a little-endian array, found {value.type.code}')
877
+ if not value.data:
878
+ return torch.empty(value.shape, dtype=dtype)
879
+ return torch.frombuffer(bytearray(value.data), dtype=dtype).reshape(value.shape)
880
+ if isinstance(value, _ReadAction):
881
+ return value.__dict__['_name']
882
+ if isinstance(value, dict):
883
+ return {key: _converted(item) for key, item in value.items()}
884
+ if isinstance(value, list):
885
+ return [_converted(item) for item in value]
886
+ if isinstance(value, tuple):
887
+ return tuple(_converted(item) for item in value)
888
+ return value
889
+
890
+
891
+ def read_dump(path: str) -> list[dict[str, Any]]:
892
+ """Reads a GRF dump, of this module or of GRF, without GRF or numpy.
893
+
894
+ Each step is a dictionary as GRF wrote it, with CPU tensors in place of numpy arrays and the
895
+ name of each action in place of its `CoreAction`. Only GRF's actions and numpy's arrays load,
896
+ so a dump runs no code of its own.
897
+
898
+ Args:
899
+ path: The path of the dump.
900
+
901
+ Returns:
902
+ The steps of the dump.
903
+
904
+ Raises:
905
+ pickle.UnpicklingError: If the file holds other objects.
906
+ """
907
+ return _read_dump(path, strict=False)
908
+
909
+
910
+ def _read_dump(path: str, *, strict: bool) -> list[dict[str, Any]]:
911
+ steps = []
912
+ with open(path, 'rb') as handle:
913
+ while not strict or handle.peek(1):
914
+ try:
915
+ step = _converted(_DumpUnpickler(handle).load())
916
+ except EOFError:
917
+ if strict:
918
+ raise pickle.UnpicklingError('the final step is incomplete') from None
919
+ return steps
920
+ if strict and not isinstance(step, dict):
921
+ raise pickle.UnpicklingError('expected each step to be a dictionary')
922
+ steps.append(step)
923
+ if not steps:
924
+ raise pickle.UnpicklingError('the dump is empty')
925
+ return steps
926
+
927
+
928
+ def _read_cli_dump(path: str) -> list[dict[str, Any]]:
929
+ """Reads a complete dump for the command line."""
930
+ try:
931
+ return _read_dump(path, strict=True)
932
+ except (
933
+ AttributeError,
934
+ IndexError,
935
+ KeyError,
936
+ OverflowError,
937
+ RuntimeError,
938
+ TypeError,
939
+ ValueError,
940
+ pickle.UnpicklingError,
941
+ ) as error:
942
+ raise ValueError(str(error)) from error