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
@@ -0,0 +1,109 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """`cuju replay`, GRF's script `replay` without rendering, which plays a dump again and checks it.
6
+
7
+ cuju replay --trace_file=/tmp/dumps/episode_done_20261026-120000000000.dump
8
+
9
+ It replays cuju's and GRF's dumps alike and compares every step with the dump's bit for bit, apart
10
+ from the wall-clock time. It prints the first difference and exits 1 if there is one, and
11
+ `check(trace_file)` does the same from Python.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import sys
18
+ from typing import Any
19
+
20
+ from . import _cli_contract as contract
21
+ from . import _cli_parsers, _replays, dumps
22
+ from ._library_path import _backend
23
+ from .errors import ChoiceError, DeviceError, LibraryError, MissingFileError
24
+
25
+ __all__ = ['check', 'main']
26
+
27
+
28
+ def check(trace_file: str, device: Any = 'cpu', threads: int = 1) -> _replays.ReplayResult:
29
+ """Plays a dump again and compares every step with the dump's.
30
+
31
+ Args:
32
+ trace_file: A dump that starts at the start of its episode.
33
+ device: The device that plays the replay. Every device plays the same match.
34
+ threads: The CPU threads of the replay.
35
+
36
+ Returns:
37
+ `(steps, ended, difference)`, the steps found equal, whether the replay's episode ended
38
+ with the dump's last step, and the first difference as a text, or `None` if the replay
39
+ equals the dump.
40
+
41
+ Raises:
42
+ ValueError: If the dump holds no configuration, does not start at the start of its
43
+ episode, or holds an action outside its action set.
44
+ """
45
+ return _replays.replay(trace_file, device=device, threads=threads)
46
+
47
+
48
+ def _run(arguments: argparse.Namespace) -> int:
49
+ path = arguments.trace_file
50
+ try:
51
+ if arguments.device != 'auto':
52
+ _backend(arguments.device)
53
+ except ChoiceError:
54
+ arguments._command_parser.error(
55
+ f'expected --device to be cpu, cuda, cuda:N or auto, found {arguments.device!r}'
56
+ )
57
+ try:
58
+ steps = dumps._read_cli_dump(path)
59
+ if arguments.fps is not None:
60
+ ticks = steps[0]['debug']['config']['physics_steps_per_frame']
61
+ fps = arguments.fps
62
+ if fps <= 0 or fps != ticks or 100 // fps != ticks:
63
+ arguments._command_parser.error(
64
+ f'expected a frame rate for the dump of {ticks} ticks a step, found {fps}'
65
+ )
66
+ result = _replays._replay_steps(steps, path, device=arguments.device)
67
+ except (DeviceError, LibraryError, MissingFileError) as error:
68
+ expected = str(error).partition(';')[0]
69
+ return contract.fail(
70
+ 'cuju replay',
71
+ expected,
72
+ hint=f'run cuju replay --trace_file {contract.quote_path(path)} --device cpu.'
73
+ if arguments.device != 'cpu'
74
+ else 'run cuju check --device cpu to check the installation.',
75
+ as_json=arguments.json,
76
+ status=contract.EXIT_ENVIRONMENT,
77
+ error_id='replay.backend_unavailable',
78
+ values={'device': arguments.device},
79
+ )
80
+ except (OSError, ValueError, KeyError, TypeError, IndexError, AttributeError) as error:
81
+ detail = (error.strerror or str(error)).lower() if isinstance(error, OSError) else error
82
+ return contract.fail(
83
+ 'cuju replay',
84
+ f'expected a replayable dump at {contract.quote_path(path)}, found {detail}',
85
+ hint='run cuju replay --trace_file FILE with a dump from the start of an episode.',
86
+ as_json=arguments.json,
87
+ error_id='replay.dump',
88
+ values={'file': path},
89
+ )
90
+ if arguments.json:
91
+ contract.emit(
92
+ 'engine.replay/1',
93
+ {'steps': result.steps, 'ended': result.ended, 'difference': result.difference},
94
+ )
95
+ return contract.EXIT_NO if result.difference is not None else 0
96
+ if result.difference is not None:
97
+ print(f'The replay differs from the dump at {result.difference}')
98
+ return 1
99
+ ending = 'and ends the episode there' if result.ended else 'before the end of the episode'
100
+ print(f"The replay equals the dump's {result.steps} steps, {ending}.")
101
+ return 0
102
+
103
+
104
+ def main(argv: list[str] | None = None) -> int:
105
+ return contract.run_command(_cli_parsers.replay(), _run, argv)
106
+
107
+
108
+ if __name__ == '__main__':
109
+ sys.exit(main())
cuju/_replay_player.py ADDED
@@ -0,0 +1,42 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """GRF's player `replay` for `cuju.env`, whose actions come from a dump, as `replay:path=<dump>`.
6
+
7
+ As in GRF, the player takes the actions of the dump from position `index`, the position of its
8
+ definition among the players, and ends the process once the dump has no step left. It reads the
9
+ dump with `cuju.dumps.read_dump`, which runs no code from it, so dumps of GRF, of `cuju.env` and of
10
+ a batch play alike.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import sys
16
+ from typing import Any
17
+
18
+ from . import dumps
19
+ from .gfootball.env import player_base
20
+
21
+ __all__ = ['Player']
22
+
23
+
24
+ class Player(player_base.PlayerBase):
25
+ """Player with actions coming from specific game replay."""
26
+
27
+ def __init__(self, player_config: dict[str, Any], env_config: Any) -> None:
28
+ player_base.PlayerBase.__init__(self, player_config)
29
+ self._can_play_right = True
30
+ self._replay = dumps.read_dump(player_config['path'])
31
+ self._step = 0
32
+ self._player = player_config['index']
33
+
34
+ def take_action(self, observations: list[dict[str, Any]]) -> list[Any]:
35
+ if self._step == len(self._replay):
36
+ print('Replay finished.')
37
+ sys.exit(0)
38
+ names = self._replay[self._step]['debug']['action'][
39
+ self._player : self.num_controlled_players() + self._player
40
+ ]
41
+ self._step += 1
42
+ return [dumps._CORE_ACTIONS[name] for name in names]
cuju/_replays.py ADDED
@@ -0,0 +1,414 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Plays the steps of an episode again in a new batch, for GRF's `write_dump` and its replays.
5
+
6
+ A batch of one environment plays an episode from GRF's configuration of it, the start of the episode
7
+ or a state, and the actions of its steps. Each step reads as `cuju.dumps` writes it, so an
8
+ environment can write the last steps of its episode on demand, and a dump can be checked against
9
+ the match that its actions play.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import datetime
15
+ import io
16
+ import os
17
+ import re
18
+ import tempfile
19
+ from typing import Any, NamedTuple
20
+
21
+ import torch
22
+
23
+ from . import BatchEnvironment, dumps
24
+
25
+ # GRF: `observation_processor.PAST_STEPS_TRACE_SIZE`, the steps that a dump on demand holds.
26
+ _TRACE_SIZE = 100
27
+ # GRF: the dumps that the options of an environment write, which `write_dump` does not start.
28
+ _OPTION_DUMPS = frozenset({'episode_done', 'score', 'lost_score'})
29
+ # The name that `DumpWriter` gives a scenario with team difficulties of its own.
30
+ _DIFFICULTY_LEVEL = re.compile(r'(.+)_difficulty_([0-9a-z]+)_([0-9a-z]+)')
31
+ # GRF: the values that its replay sets over `config_update`.
32
+ _REPLAY_VALUES = frozenset({'physics_steps_per_frame', 'real_time', 'tracesdir', 'write_video'})
33
+ # The keys that differ between two plays of one match, the wall-clock time, the configuration that
34
+ # a dump adds to some steps, and a rendered frame.
35
+ _UNCOMPARED = frozenset({'time', 'config', 'frame'})
36
+
37
+
38
+ def _difficulty(text):
39
+ """Returns the difficulty that `dumps._difficulty_text` wrote as `text`."""
40
+ return None if text == 'none' else float(text.replace('p', '.').replace('m', '-'))
41
+
42
+
43
+ def agent_counts(players: list[str]) -> tuple[int, int]:
44
+ """Returns the left and right players of GRF's player definitions, as its replay counts them."""
45
+ from ._grf_config import count_left_players, count_right_players
46
+
47
+ return (
48
+ sum(count_left_players(player) for player in players),
49
+ sum(count_right_players(player) for player in players),
50
+ )
51
+
52
+
53
+ def batch_for(
54
+ config: dict[str, Any], level: str | None = None, device: Any = 'cpu', threads: int = 1
55
+ ) -> BatchEnvironment:
56
+ """Returns a batch of one environment that plays the episode of a GRF configuration.
57
+
58
+ Args:
59
+ config: GRF's configuration of the episode, as the first step of a dump holds it.
60
+ level: The scenario to play, or `None` for the configuration's `level`.
61
+ device: The device of the batch.
62
+ threads: The CPU threads of the batch.
63
+ """
64
+ level = config['level'] if level is None else level
65
+ difficulty = None
66
+ match = _DIFFICULTY_LEVEL.fullmatch(level)
67
+ if match is not None and not os.path.isfile(level):
68
+ try:
69
+ difficulty = [(_difficulty(match.group(2)), _difficulty(match.group(3)))]
70
+ level = match.group(1)
71
+ except ValueError:
72
+ difficulty = None
73
+ left, right = agent_counts(config['players'])
74
+ return BatchEnvironment(
75
+ level,
76
+ environment_count=1,
77
+ representation='raw',
78
+ action_set=config['action_set'],
79
+ auto_reset=False,
80
+ device=device,
81
+ threads=threads,
82
+ physics_steps_per_frame=config['physics_steps_per_frame'],
83
+ game_engine_random_seed=config['game_engine_random_seed'],
84
+ agent_counts=[(left, right)],
85
+ difficulty=difficulty,
86
+ # The first reset of a batch plays the episode after the one after `episode_number`, and
87
+ # only its parity reaches the bundle.
88
+ episode_number=(config['episode_number'] - 2) % 2,
89
+ )
90
+
91
+
92
+ def start(batch: BatchEnvironment, config: dict[str, Any]) -> None:
93
+ """Resets a batch from `batch_for` to the start of the configuration's episode."""
94
+ reverse = config.get('reverse_team_processing')
95
+ batch.reset(reverse=None if reverse is None else int(bool(reverse)))
96
+
97
+
98
+ class Player:
99
+ """Steps a batch of one environment and reads each step as a dump step."""
100
+
101
+ def __init__(self, batch: BatchEnvironment) -> None:
102
+ self.batch = batch
103
+ # Created before the batch's reset, the writer follows no episode and writes nothing.
104
+ self.writer = dumps.DumpWriter(
105
+ batch, tempfile.gettempdir(), environments=[0], write_full_episode_dumps=False
106
+ )
107
+ self.episode = None
108
+
109
+ def begin(self, frame: int | None = None, cumulative: int = 0) -> None:
110
+ """Starts counting the steps of the episode that the batch now holds.
111
+
112
+ Args:
113
+ frame: The frame count of the next step, or `None` for the one after the batch's step.
114
+ cumulative: The scoring reward that the episode has collected so far.
115
+ """
116
+ values, _ = self.writer._episode_values(0)
117
+ self.episode = dumps._Episode(0, values, None, False, False)
118
+ # The batch's step count is the frame count of the step that it last played.
119
+ self.episode.frame = values[5] + 1 if frame is None else frame
120
+ self.episode.cumulative = cumulative
121
+
122
+ def step(self, row: Any, entry: bool = True) -> tuple[dict[str, Any] | None, int, bool]:
123
+ """Plays one step.
124
+
125
+ Args:
126
+ row: The actions of the batch's agents.
127
+ entry: Whether to return the step as a dump step.
128
+
129
+ Returns:
130
+ The dump step or `None`, the scoring reward, and whether the episode ended.
131
+ """
132
+ batch = self.batch
133
+ actions = torch.as_tensor(row, dtype=torch.int32).reshape(1, batch.agents).cpu()
134
+ _, _, done, information = batch.step(actions.to(batch.torch_device))
135
+ if not entry:
136
+ reward = int(information['score_reward'][0])
137
+ self.episode.cumulative += reward
138
+ self.episode.frame += 1
139
+ return None, reward, bool(done[0])
140
+ action_rows, done_rows, reward_rows, raw_rows = self.writer._rows(actions)
141
+ values, _ = self.writer._episode_values(0)
142
+ ended = bool(done_rows[0])
143
+ raw = [
144
+ {name: raw_rows[name][0][agent] for name in raw_rows} for agent in range(batch.agents)
145
+ ]
146
+ designated = values[15:17] if ended else values[13:15]
147
+ reward = int(reward_rows[0])
148
+ entry = self.writer._entry(self.episode, action_rows[0], reward, raw, designated)
149
+ return entry, reward, ended
150
+
151
+
152
+ class EpisodeSteps:
153
+ """The batch actions of each step of an environment's episode, and GRF's dumps on demand.
154
+
155
+ GRF's environment keeps the last 100 steps of the episode for its dumps. This keeps only the
156
+ actions, from the reset or each loaded state, and plays them again when a dump is written.
157
+ """
158
+
159
+ def __init__(self) -> None:
160
+ self.reset()
161
+
162
+ def reset(self) -> list[Any]:
163
+ """Starts a new episode, and returns the list that takes the actions of its steps."""
164
+ self.segments: list[tuple[bytes | None, list[Any]]] = [(None, [])]
165
+ # GRF: the trace of the dumps starts again with each episode.
166
+ self.first = 0
167
+ self.names: set[str] = set()
168
+ self.configs: dict[int, dict[str, Any]] = {}
169
+ return self.segments[-1][1]
170
+
171
+ def set_state(self, state: bytes, ended: bool) -> list[Any]:
172
+ """Continues from a loaded state, and returns the list that takes its steps' actions."""
173
+ self.segments.append((state, []))
174
+ if ended:
175
+ # GRF: an ended episode has no trace, and loading a state starts a new one.
176
+ self.first = len(self.segments) - 1
177
+ self.names = set()
178
+ self.configs = {}
179
+ return self.segments[-1][1]
180
+
181
+ def _play(self, environment, config):
182
+ """Replays the episode, returning the trace's last 100 dump steps and goals by position."""
183
+ level = environment._settings['level']
184
+ batch = batch_for(config, level, environment.batch.torch_device, 1)
185
+ try:
186
+ player = Player(batch)
187
+ cumulative = 0
188
+ trace_length = sum(len(rows) for _, rows in self.segments[self.first :])
189
+ kept = trace_length - min(trace_length, _TRACE_SIZE)
190
+ played, entries, goals = 0, [], []
191
+ for index, (state, rows) in enumerate(self.segments):
192
+ if state is None:
193
+ start(batch, config)
194
+ player.begin(0, cumulative)
195
+ else:
196
+ batch.set_state(0, state)
197
+ player.begin(None, cumulative)
198
+ traced = index >= self.first
199
+ for row in rows:
200
+ wanted = traced and played >= kept
201
+ entry, reward, _ = player.step(row, wanted)
202
+ if wanted:
203
+ entries.append((played, entry))
204
+ if traced:
205
+ if reward in (1, -1):
206
+ goals.append(played)
207
+ played += 1
208
+ cumulative = player.episode.cumulative
209
+ finally:
210
+ batch.close()
211
+ return entries, goals
212
+
213
+ def write_dump(self, environment: Any, name: str) -> str | None:
214
+ """Writes the last steps of the environment's episode as GRF's `write_dump(name)` does.
215
+
216
+ Returns:
217
+ The path without `.dump`, or `None` where GRF writes none.
218
+ """
219
+
220
+ if environment._done:
221
+ raise RuntimeError(
222
+ "the episode ended, and GRF's environment keeps no steps to dump until reset()"
223
+ )
224
+ # GRF: the options start these dumps, and a name dumps once an episode.
225
+ if name in _OPTION_DUMPS or name in self.names:
226
+ return None
227
+ self.names.add(name)
228
+ # GRF: the configuration of a dump is the environment's, with the episode's values.
229
+ config = environment._config.get_dictionary()
230
+ batch = environment.batch
231
+ writer = dumps.DumpWriter(
232
+ batch, os.curdir, environments=[0], write_full_episode_dumps=False
233
+ )
234
+ values, _ = writer._episode_values(0)
235
+ played = dict(config)
236
+ played.update(
237
+ {
238
+ 'action_set': dumps._ACTION_SET_NAMES[batch.action_count],
239
+ 'game_engine_random_seed': values[0],
240
+ 'reverse_team_processing': bool(values[1]),
241
+ 'episode_number': values[2] + 1 + values[3],
242
+ 'physics_steps_per_frame': values[8],
243
+ }
244
+ )
245
+ entries, goals = self._play(environment, played)
246
+ # The steps that hold the configuration, by their positions in the trace.
247
+ configs = self.configs
248
+ if entries:
249
+ configs[entries[0][0]] = config
250
+ # GRF: the first step of each dump of the options takes the configuration as well.
251
+ own = environment._dumps
252
+ current = own._writer._episodes.get(0) if own is not None else None
253
+ if current is not None and len(self.segments) == 1:
254
+ if current.full:
255
+ configs.setdefault(0, config)
256
+ if current.goals:
257
+ for position in goals:
258
+ configs.setdefault(max(0, position - _TRACE_SIZE), config)
259
+ for position, entry in entries:
260
+ if position in configs:
261
+ entry['debug']['config'] = configs[position]
262
+ # GRF writes into `tracesdir`, the `logdir` of `create_environment`. An empty one is the
263
+ # working directory, as for cuju's other dumps.
264
+ directory = config['tracesdir'] or os.curdir
265
+ os.makedirs(directory, exist_ok=True)
266
+ stamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S%f')
267
+ path = f'{directory}{os.sep}{name}_{stamp}'
268
+ dumps._write_file(path + '.dump', (dumps._pickle(entry) for _, entry in entries))
269
+ return path
270
+
271
+
272
+ class ReplayResult(NamedTuple):
273
+ """What a replay of a dump found.
274
+
275
+ Attributes:
276
+ steps: The steps of the dump that the replay played and found equal.
277
+ ended: Whether the replay's episode ended at the dump's last step.
278
+ difference: The first difference, or `None` if the replay equals the dump.
279
+ """
280
+
281
+ steps: int
282
+ ended: bool
283
+ difference: str | None
284
+
285
+
286
+ def _bits(tensor):
287
+ return tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8)
288
+
289
+
290
+ def _shown(value):
291
+ """Returns a short text of a value of a dump step."""
292
+ if isinstance(value, torch.Tensor):
293
+ if value.numel() <= 6:
294
+ return f'{value.tolist()}'
295
+ return f'a {value.dtype} tensor of the shape {tuple(value.shape)}'
296
+ return repr(value)
297
+
298
+
299
+ def difference(replayed: Any, stored: Any, where: str) -> str | None:
300
+ """Returns where a replayed dump step differs from the stored one, bit for bit, or `None`.
301
+
302
+ Only the stored step's keys count, apart from the wall-clock time, the configuration and a
303
+ rendered frame.
304
+ """
305
+ if isinstance(stored, torch.Tensor):
306
+ if (
307
+ not isinstance(replayed, torch.Tensor)
308
+ or replayed.dtype != stored.dtype
309
+ or replayed.shape != stored.shape
310
+ or not torch.equal(_bits(replayed), _bits(stored))
311
+ ):
312
+ return f'{where}: the replay gives {_shown(replayed)}, the dump holds {_shown(stored)}'
313
+ return None
314
+ if isinstance(stored, dict):
315
+ if not isinstance(replayed, dict):
316
+ return f'{where}: the replay gives {_shown(replayed)}, the dump holds a dictionary'
317
+ for key, value in stored.items():
318
+ if key in _UNCOMPARED:
319
+ continue
320
+ if key not in replayed:
321
+ return f'{where}.{key}: the replay lacks it'
322
+ found = difference(replayed[key], value, f'{where}.{key}')
323
+ if found is not None:
324
+ return found
325
+ return None
326
+ if isinstance(stored, (list, tuple)):
327
+ if type(replayed) is not type(stored) or len(replayed) != len(stored):
328
+ return f'{where}: the replay gives {_shown(replayed)}, the dump holds {_shown(stored)}'
329
+ for index, (first, second) in enumerate(zip(replayed, stored, strict=True)):
330
+ found = difference(first, second, f'{where}[{index}]')
331
+ if found is not None:
332
+ return found
333
+ return None
334
+ if type(replayed) is not type(stored) or replayed != stored:
335
+ return f'{where}: the replay gives {_shown(replayed)}, the dump holds {_shown(stored)}'
336
+ return None
337
+
338
+
339
+ def loaded(entry: dict[str, Any]) -> dict[str, Any]:
340
+ """Returns a dump step as `read_dump` reads it back."""
341
+ return dumps._converted(dumps._DumpUnpickler(io.BytesIO(dumps._pickle(entry))).load())
342
+
343
+
344
+ def replay(
345
+ path: str,
346
+ device: Any = 'cpu',
347
+ threads: int = 1,
348
+ overrides: dict[str, Any] | None = None,
349
+ ) -> ReplayResult:
350
+ """Plays a dump's actions again from its configuration and compares every step with the dump.
351
+
352
+ Args:
353
+ path: A dump that starts at the start of its episode, of cuju or of GRF.
354
+ device: The device of the batch that plays it.
355
+ threads: The CPU threads of that batch.
356
+ overrides: Values that replace those of the dump's configuration, as GRF's
357
+ `config_update`, apart from the ones that GRF's replay sets itself.
358
+
359
+ Returns:
360
+ The steps found equal, whether the replay's episode ended with the dump, and the first
361
+ difference, if any.
362
+
363
+ Raises:
364
+ ValueError: If the dump holds no configuration, does not start at the start of its
365
+ episode, or holds an action outside its action set.
366
+ """
367
+ return _replay_steps(dumps.read_dump(path), path, device, threads, overrides)
368
+
369
+
370
+ def _replay_steps(steps, path, device='cpu', threads=1, overrides=None) -> ReplayResult:
371
+ if not steps or 'config' not in steps[0].get('debug', {}):
372
+ raise ValueError(f'expected a dump whose first step holds the configuration in {path}')
373
+ if steps[0]['debug']['frame_cnt'] != 0:
374
+ # GRF: `ScriptHelpers.replay` asserts the same.
375
+ raise ValueError(
376
+ 'the dump does not start from the beginning of its episode, so it cannot be replayed'
377
+ )
378
+ config = dict(steps[0]['debug']['config'])
379
+ config.update(
380
+ (key, value) for key, value in (overrides or {}).items() if key not in _REPLAY_VALUES
381
+ )
382
+ names = dumps._ACTION_SETS[config['action_set']]
383
+ left, _ = agent_counts(config['players'])
384
+ batch = batch_for(config, device=device, threads=threads)
385
+ try:
386
+ start(batch, config)
387
+ player = Player(batch)
388
+ player.begin(0)
389
+ ended = False
390
+ for index, step in enumerate(steps):
391
+ if ended:
392
+ return ReplayResult(
393
+ index,
394
+ True,
395
+ f'step {index}: the replay ended its episode at step {index - 1}, and the dump '
396
+ f'holds {len(steps)} steps',
397
+ )
398
+ row = []
399
+ for agent, name in enumerate(step['debug']['action']):
400
+ turned = dumps._FLIPPED.get(name, name) if agent >= left else name
401
+ if turned not in names:
402
+ raise ValueError(
403
+ f'step {index} holds the action {name!r}, outside the action set '
404
+ f'{config["action_set"]!r}'
405
+ )
406
+ row.append(names.index(turned))
407
+ row += [0] * (batch.agents - len(row))
408
+ entry, _, ended = player.step(row)
409
+ found = difference(loaded(entry), step, f'step {index}')
410
+ if found is not None:
411
+ return ReplayResult(index, ended, found)
412
+ return ReplayResult(len(steps), ended, None)
413
+ finally:
414
+ batch.close()
@@ -0,0 +1,109 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """The `load_dump` and `dump_to_txt` of GRF's `ScriptHelpers` for cuju's commands for dumps.
6
+
7
+ `load_dump` reads a dump without running its code and gives GRF's numpy arrays and `CoreAction`s,
8
+ so `dump_to_txt` writes GRF's text. `replay(dump, render=False)` plays a dump again and checks
9
+ every step bit for bit. GRF's own `ScriptHelpers`, with `dump_to_video`, is in `cuju.gfootball`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ import torch
17
+
18
+ from . import _replays, dumps
19
+
20
+ __all__ = ['ScriptHelpers']
21
+
22
+
23
+ def _grf_value(value: Any) -> Any:
24
+ """Returns a value of `read_dump` with numpy arrays for tensors, as GRF's pickle holds it."""
25
+ if isinstance(value, torch.Tensor):
26
+ return value.numpy()
27
+ if isinstance(value, dict):
28
+ return {key: _grf_value(item) for key, item in value.items()}
29
+ if isinstance(value, list):
30
+ return [_grf_value(item) for item in value]
31
+ if isinstance(value, tuple):
32
+ return tuple(_grf_value(item) for item in value)
33
+ return value
34
+
35
+
36
+ def _grf_steps(steps):
37
+ converted = [_grf_value(step) for step in steps]
38
+ for step in converted:
39
+ debug = step.get('debug')
40
+ # GRF puts actions in the debug information.
41
+ if isinstance(debug, dict) and 'action' in debug:
42
+ debug['action'] = [dumps._CORE_ACTIONS[name] for name in debug['action']]
43
+ return converted
44
+
45
+
46
+ def _dump_text(steps, include_debug):
47
+ if not include_debug:
48
+ for step in steps:
49
+ step.pop('debug', None)
50
+ return str(steps)
51
+
52
+
53
+ class ScriptHelpers:
54
+ """The methods of GRF's `ScriptHelpers` that need no rendering."""
55
+
56
+ def load_dump(self, dump_file: str) -> list[dict[str, Any]]:
57
+ """Returns the steps of a dump as GRF's method, with numpy arrays and `CoreAction`s."""
58
+ return _grf_steps(dumps.read_dump(dump_file))
59
+
60
+ def dump_to_txt(self, dump_file: str, output: str, include_debug: bool) -> None:
61
+ """Writes the steps of a dump to `output` as text, as GRF's method."""
62
+ text = _dump_text(self.load_dump(dump_file), include_debug)
63
+ with open(output, 'w') as handle:
64
+ handle.write(text)
65
+
66
+ def replay(
67
+ self,
68
+ dump: str,
69
+ fps: int = 10,
70
+ config_update: dict[str, Any] | None = None,
71
+ directory: str | None = None,
72
+ render: bool = True,
73
+ ) -> None:
74
+ """Plays a dump again and checks it, as GRF's replay without rendering.
75
+
76
+ The replay plays the dump's actions in a new environment of the dump's configuration, as
77
+ GRF's replay players do, and compares each step with the dump's, every observation, action
78
+ and reward bit for bit, apart from the wall-clock time.
79
+
80
+ Args:
81
+ dump: A dump that starts at the start of its episode.
82
+ fps: GRF's frame rate of the replay. Only 10 plays the match of a dump of 10 ticks a
83
+ step. GRF's other rates add idle steps or change the ticks, another match.
84
+ config_update: Values that replace those of the dump's configuration.
85
+ directory: Where GRF's replay writes its own dumps and video. cuju writes neither, so
86
+ it is ignored.
87
+ render: Must be `False`, since cuju renders nothing.
88
+
89
+ Raises:
90
+ ValueError: If `render` is set, `fps` plays another match than the dump's, the dump
91
+ cannot be replayed, or a step of the replay differs from the dump's, naming the
92
+ first such step and value.
93
+ """
94
+ if render:
95
+ raise ValueError('cuju renders nothing, so it replays with render=False only')
96
+ steps = dumps.read_dump(dump)
97
+ if not steps or 'config' not in steps[0].get('debug', {}):
98
+ raise ValueError(f'expected a dump whose first step holds the configuration in {dump}')
99
+ ticks = steps[0]['debug']['config']['physics_steps_per_frame']
100
+ # GRF: `__modify_trace` adds idle steps unless the rate equals the dump's, and the replay
101
+ # plays steps of 100 / fps ticks.
102
+ if fps != ticks or 100 // fps != ticks:
103
+ raise ValueError(
104
+ f"at {fps} frames per second GRF's replay plays another match than the dump of "
105
+ f'{ticks} ticks a step, and only 10 replays a dump of 10 ticks a step'
106
+ )
107
+ result = _replays.replay(dump, overrides=config_update)
108
+ if result.difference is not None:
109
+ raise ValueError(f'the replay differs from the dump at {result.difference}')
cuju/_version.py ADDED
@@ -0,0 +1,6 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """The version of cuju, which the package metadata and the CMake build read from this file."""
5
+
6
+ __version__ = '0.3.0'