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,47 @@
1
+ # coding=utf-8
2
+ # Copyright 2019 Google LLC
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # Modified by the cuju Authors in 2026, in the import lines that ci/port_gfootball.py lists.
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """GFootball environment using OpenAI Gym test."""
19
+
20
+ from __future__ import absolute_import
21
+ from __future__ import division
22
+ from __future__ import print_function
23
+
24
+ import unittest
25
+
26
+ from cuju.gfootball import _gym as gym
27
+ from absl.testing import parameterized
28
+
29
+
30
+ class GymTest(parameterized.TestCase):
31
+
32
+ @parameterized.parameters(('scoring'), ('scoring,checkpoints'))
33
+ def test_environment(self, rewards):
34
+ # Tests it is possible to create and run an environment twice.
35
+ for _ in range(2):
36
+ env = gym.make('cuju.gfootball:GFootball-11_vs_11_easy_stochastic-SMM-v0',
37
+ stacked=True, rewards=rewards)
38
+ env.reset()
39
+ for _ in range(10):
40
+ _, _, done, _ = env.step(env.action_space.sample())
41
+ if done:
42
+ env.reset()
43
+ env.close()
44
+
45
+
46
+ if __name__ == '__main__':
47
+ unittest.main()
@@ -0,0 +1,94 @@
1
+ # coding=utf-8
2
+ # Copyright 2019 Google LLC
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # Modified by the cuju Authors in 2026, in the import lines that ci/port_gfootball.py lists.
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Conversion functions for observations.
19
+ """
20
+
21
+
22
+ from __future__ import absolute_import
23
+ from __future__ import division
24
+ from __future__ import print_function
25
+
26
+ from cuju.gfootball.env import football_action_set
27
+ import numpy as np
28
+ from six.moves import range
29
+
30
+
31
+ SMM_WIDTH = 96
32
+ SMM_HEIGHT = 72
33
+
34
+ SMM_LAYERS = ['left_team', 'right_team', 'ball', 'active']
35
+
36
+ # Normalized minimap coordinates
37
+ MINIMAP_NORM_X_MIN = -1.0
38
+ MINIMAP_NORM_X_MAX = 1.0
39
+ MINIMAP_NORM_Y_MIN = -1.0 / 2.25
40
+ MINIMAP_NORM_Y_MAX = 1.0 / 2.25
41
+
42
+ _MARKER_VALUE = 255
43
+
44
+
45
+ def get_smm_layers(config):
46
+ return SMM_LAYERS
47
+
48
+
49
+ def mark_points(frame, points):
50
+ """Draw dots corresponding to 'points'.
51
+
52
+ Args:
53
+ frame: 2-d matrix representing one SMM channel ([y, x])
54
+ points: a list of (x, y) coordinates to be marked
55
+ """
56
+ for p in range(len(points) // 2):
57
+ x = int((points[p * 2] - MINIMAP_NORM_X_MIN) /
58
+ (MINIMAP_NORM_X_MAX - MINIMAP_NORM_X_MIN) * frame.shape[1])
59
+ y = int((points[p * 2 + 1] - MINIMAP_NORM_Y_MIN) /
60
+ (MINIMAP_NORM_Y_MAX - MINIMAP_NORM_Y_MIN) * frame.shape[0])
61
+ x = max(0, min(frame.shape[1] - 1, x))
62
+ y = max(0, min(frame.shape[0] - 1, y))
63
+ frame[y, x] = _MARKER_VALUE
64
+
65
+
66
+ def generate_smm(observation, config=None,
67
+ channel_dimensions=(SMM_WIDTH, SMM_HEIGHT)):
68
+ """Returns a list of minimap observations given the raw features for each
69
+ active player.
70
+
71
+ Args:
72
+ observation: raw features from the environment
73
+ config: environment config
74
+ channel_dimensions: resolution of SMM to generate
75
+
76
+ Returns:
77
+ (N, H, W, C) - shaped np array representing SMM. N stands for the number of
78
+ players we are controlling.
79
+ """
80
+ frame = np.zeros((len(observation), channel_dimensions[1],
81
+ channel_dimensions[0], len(get_smm_layers(config))),
82
+ dtype=np.uint8)
83
+
84
+ for o_i, o in enumerate(observation):
85
+ for index, layer in enumerate(get_smm_layers(config)):
86
+ assert layer in o
87
+ if layer == 'active':
88
+ if o[layer] == -1:
89
+ continue
90
+ mark_points(frame[o_i, :, :, index],
91
+ np.array(o['left_team'][o[layer]]).reshape(-1))
92
+ else:
93
+ mark_points(frame[o_i, :, :, index], np.array(o[layer]).reshape(-1))
94
+ return frame
@@ -0,0 +1,526 @@
1
+ # coding=utf-8
2
+ # Copyright 2019 Google LLC
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # Modified by the cuju Authors in 2026, in the import lines that ci/port_gfootball.py lists.
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+
18
+ """Observation processor, providing multiple support methods for analyzing observations."""
19
+
20
+ from __future__ import absolute_import
21
+ from __future__ import division
22
+ from __future__ import print_function
23
+
24
+ import collections
25
+ import datetime
26
+ import os
27
+ import shutil
28
+ import tempfile
29
+ import timeit
30
+ import traceback
31
+
32
+ from absl import logging
33
+ from cuju.gfootball.env import constants as const
34
+ from cuju.gfootball.env import football_action_set
35
+ from cuju.gfootball.scenarios import e_PlayerRole_GK
36
+ import numpy as np
37
+ from six.moves import range
38
+ from six.moves import zip
39
+ import six.moves.cPickle
40
+
41
+ # How many past frames are kept around for the dumps to make use of them.
42
+ PAST_STEPS_TRACE_SIZE = 100
43
+
44
+ WRITE_FILES = True
45
+
46
+ try:
47
+ from cuju.gfootball import _cv2 as cv2
48
+ except ImportError:
49
+ from cuju.gfootball import _cv2 as cv2
50
+
51
+
52
+ class DumpConfig(object):
53
+
54
+ def __init__(self,
55
+ max_count=1,
56
+ steps_before=PAST_STEPS_TRACE_SIZE,
57
+ steps_after=0,
58
+ min_frequency=10):
59
+ self._steps_before = steps_before
60
+ self._steps_after = steps_after
61
+ self._max_count = max_count
62
+ # Make sure self._last_dump_time < timeit.default_timer() - min_frequency
63
+ # holds upon startup.
64
+ self._last_dump_time = timeit.default_timer() - 2 * min_frequency
65
+ self._active_dump = None
66
+ self._min_frequency = min_frequency
67
+
68
+
69
+ class TextWriter(object):
70
+
71
+ def __init__(self, frame, x, y=0, field_coords=False, color=(255, 255, 255)):
72
+ self._frame = frame
73
+ if field_coords:
74
+ x = 400 * (x + 1) - 10
75
+ y = 695 * (y + 0.43)
76
+ self._pos_x = int(x)
77
+ self._pos_y = int(y) + 20
78
+ self._color = color
79
+ self._font = cv2.FONT_HERSHEY_SIMPLEX
80
+ self._lineType = 2
81
+ self._arrow_types = ('top', 'top_right', 'right', 'bottom_right', 'bottom',
82
+ 'bottom_left', 'left', 'top_left')
83
+
84
+ def write(self, text, scale_factor=1, color=None):
85
+ textPos = (self._pos_x, self._pos_y)
86
+ fontScale = 0.8 * scale_factor
87
+ cv2.putText(self._frame, text, textPos, self._font, fontScale, color or self._color,
88
+ self._lineType)
89
+ self._pos_y += int(25 * scale_factor)
90
+
91
+ def write_table(self, data, widths, scale_factor=1, offset=0):
92
+ # data is a list of rows. Each row is a list of strings.
93
+ fontScale = 0.5 * scale_factor
94
+ init_x = self._pos_x
95
+ for row in data:
96
+ assert (len(row) == len(widths))
97
+ self._pos_x += offset
98
+ for col, cell in enumerate(row):
99
+ color = self._color
100
+ if isinstance(cell, tuple):
101
+ assert (len(cell) == 2)
102
+ (text, color) = cell
103
+ else:
104
+ assert (isinstance(cell, str))
105
+ text = cell
106
+
107
+ if text in self._arrow_types:
108
+ self.write_arrow(text, scale_factor=scale_factor)
109
+ else:
110
+ textPos = (self._pos_x, self._pos_y)
111
+ cv2.putText(self._frame, text, textPos, self._font, fontScale, color,
112
+ self._lineType)
113
+ self._pos_x += widths[col]
114
+ self._pos_x = init_x
115
+ self._pos_y += int(20 * scale_factor)
116
+ self._pos_x = init_x
117
+
118
+ def write_arrow(self, arrow_type, scale_factor=1):
119
+ assert (arrow_type in self._arrow_types)
120
+ thickness = 1
121
+ arrow_offsets = {
122
+ 'top': (12, 0, 12, -16),
123
+ 'top_right': (4, -4, 16, -16),
124
+ 'right': (0, -10, 20, -10),
125
+ 'bottom_right': (4, -16, 16, -4),
126
+ 'bottom': (10, -16, 10, 0),
127
+ 'bottom_left': (12, -12, 0, 0),
128
+ 'left': (20, -10, 0, -10),
129
+ 'top_left': (16, -4, 4, -16)
130
+ }
131
+ (s_x, s_y, e_x,
132
+ e_y) = tuple(int(v * scale_factor) for v in arrow_offsets[arrow_type])
133
+ start_point = (self._pos_x + s_x, self._pos_y + s_y)
134
+ end_point = (self._pos_x + e_x, self._pos_y + e_y)
135
+ image = cv2.arrowedLine(self._frame, start_point, end_point, self._color,
136
+ thickness)
137
+
138
+
139
+ def write_players_state(writer, players_info):
140
+ table_text = [["PLAYER", "SPRINT", "DRIBBLE", "DIRECTION", "ACTION"]]
141
+ widths = [65, 65, 70, 85, 85]
142
+
143
+ # Sort the players according to the order they appear in observations
144
+ for _, player_info in sorted(players_info.items()):
145
+ table_text.append([
146
+ (player_info['id'], player_info['color']),
147
+ str(player_info.get("sprint", "-")),
148
+ str(player_info.get("dribble", "-")),
149
+ player_info.get("DIRECTION", "O"),
150
+ player_info.get("ACTION", "-")])
151
+ writer.write_table(table_text, widths, scale_factor=1.0, offset=10)
152
+
153
+
154
+ def get_frame(trace):
155
+ if 'frame' in trace._trace['observation']:
156
+ return trace._trace['observation']['frame']
157
+ frame = np.uint8(np.zeros((600, 800, 3)))
158
+ corner1 = (0, 0)
159
+ corner2 = (799, 0)
160
+ corner3 = (799, 599)
161
+ corner4 = (0, 599)
162
+ line_color = (0, 255, 255)
163
+ cv2.line(frame, corner1, corner2, line_color)
164
+ cv2.line(frame, corner2, corner3, line_color)
165
+ cv2.line(frame, corner3, corner4, line_color)
166
+ cv2.line(frame, corner4, corner1, line_color)
167
+ cv2.line(frame, (399, 0), (399, 799), line_color)
168
+ writer = TextWriter(
169
+ frame,
170
+ trace['ball'][0],
171
+ trace['ball'][1],
172
+ field_coords=True,
173
+ color=(248, 244, 236))
174
+ writer.write('B')
175
+ for player_idx, player_coord in enumerate(trace['left_team']):
176
+ writer = TextWriter(
177
+ frame,
178
+ player_coord[0],
179
+ player_coord[1],
180
+ field_coords=True,
181
+ color=(238, 68, 47))
182
+ letter = str(player_idx)
183
+ if trace['left_team_roles'][player_idx] == e_PlayerRole_GK:
184
+ letter = 'G'
185
+ writer.write(letter)
186
+ for player_idx, player_coord in enumerate(trace['right_team']):
187
+ writer = TextWriter(
188
+ frame,
189
+ player_coord[0],
190
+ player_coord[1],
191
+ field_coords=True,
192
+ color=(99, 172, 190))
193
+ letter = str(player_idx)
194
+ if trace['right_team_roles'][player_idx] == e_PlayerRole_GK:
195
+ letter = 'G'
196
+ writer.write(letter)
197
+ return frame
198
+
199
+
200
+ def softmax(x):
201
+ return np.exp(x) / np.sum(np.exp(x), axis=0)
202
+
203
+
204
+ class ActiveDump(object):
205
+
206
+ def __init__(self,
207
+ name,
208
+ finish_step,
209
+ config):
210
+ self._name = name
211
+ self._finish_step = finish_step
212
+ self._config = config
213
+ self._video_fd = None
214
+ self._video_tmp = None
215
+ self._video_writer = None
216
+ self._frame_dim = None
217
+ self._step_cnt = 0
218
+ self._dump_file = None
219
+ if config['write_video']:
220
+ video_format = config['video_format']
221
+ assert video_format in ['avi', 'webm']
222
+ self._video_suffix = '.%s' % video_format
223
+ self._video_fd, self._video_tmp = tempfile.mkstemp(
224
+ suffix=self._video_suffix)
225
+ self._frame_dim = (
226
+ config['render_resolution_x'], config['render_resolution_y'])
227
+ if config['video_quality_level'] not in [1, 2]:
228
+ # Reduce resolution to (800, 450).
229
+ self._frame_dim = min(self._frame_dim, (800, 450))
230
+ if video_format == 'avi':
231
+ if config['video_quality_level'] == 2:
232
+ fcc = cv2.VideoWriter_fourcc('p', 'n', 'g', ' ')
233
+ elif config['video_quality_level'] == 1:
234
+ fcc = cv2.VideoWriter_fourcc(*'MJPG')
235
+ else:
236
+ fcc = cv2.VideoWriter_fourcc(*'XVID')
237
+ else:
238
+ fcc = cv2.VideoWriter_fourcc(*'vp80')
239
+
240
+ self._video_writer = cv2.VideoWriter(
241
+ self._video_tmp, fcc,
242
+ const.PHYSICS_STEPS_PER_SECOND / config['physics_steps_per_frame'],
243
+ self._frame_dim)
244
+ if WRITE_FILES:
245
+ self._dump_file = open(name + '.dump', 'wb')
246
+
247
+ def __del__(self):
248
+ self.finalize()
249
+
250
+ def add_frame(self, frame):
251
+ if self._video_writer:
252
+ frame = frame[..., ::-1]
253
+ frame = cv2.resize(frame, self._frame_dim, interpolation=cv2.INTER_AREA)
254
+ self._video_writer.write(frame)
255
+
256
+ def add_step(self, o):
257
+ # Write video if requested.
258
+ if self._video_writer:
259
+ frame = get_frame(o)
260
+ frame = frame[..., ::-1]
261
+ frame = cv2.resize(frame, self._frame_dim, interpolation=cv2.INTER_AREA)
262
+ writer = TextWriter(frame, self._frame_dim[0] - 300)
263
+ if self._config['custom_display_stats']:
264
+ for line in self._config['custom_display_stats']:
265
+ writer.write(line)
266
+ if self._config['display_game_stats']:
267
+ writer.write('SCORE: %d - %d' % (o['score'][0], o['score'][1]))
268
+ if o['ball_owned_team'] == 0:
269
+ player = 'G' if o['left_team_roles'][
270
+ o['ball_owned_player']] == e_PlayerRole_GK else o[
271
+ 'ball_owned_player']
272
+ writer.write('BALL OWNED: %s' % player, color=(47, 68, 238))
273
+ elif o['ball_owned_team'] == 1:
274
+ player = 'G' if o['right_team_roles'][
275
+ o['ball_owned_player']] == e_PlayerRole_GK else o[
276
+ 'ball_owned_player']
277
+ writer.write('BALL OWNED: %s' % player, color=(190, 172, 99))
278
+ else:
279
+ writer.write('BALL OWNED: ---')
280
+ writer = TextWriter(frame, 0)
281
+ writer.write('STEP: %d' % self._step_cnt)
282
+ sticky_actions = football_action_set.get_sticky_actions(self._config)
283
+
284
+ players_info = {}
285
+ for team in ['left', 'right']:
286
+ player_info = {}
287
+ sticky_actions_field = '%s_agent_sticky_actions' % team
288
+ for player in range(len(o[sticky_actions_field])):
289
+ assert len(sticky_actions) == len(o[sticky_actions_field][player])
290
+ player_idx = o['%s_agent_controlled_player' % team][player]
291
+ player_info = {}
292
+ player_info['color'] = (
293
+ 47, 68, 238) if team == 'left' else (190, 172, 99)
294
+ player_info['id'] = 'G' if o[
295
+ '%s_team_roles' %
296
+ team][player_idx] == e_PlayerRole_GK else str(player_idx)
297
+ active_direction = None
298
+ for i in range(len(sticky_actions)):
299
+ if sticky_actions[i]._directional:
300
+ if o[sticky_actions_field][player][i]:
301
+ active_direction = sticky_actions[i]
302
+ else:
303
+ player_info[sticky_actions[i]._name] = \
304
+ o[sticky_actions_field][player][i]
305
+
306
+ # Info about direction
307
+ player_info['DIRECTION'] = \
308
+ 'O' if active_direction is None else active_direction._name
309
+ if 'action' in o._trace['debug']:
310
+ # Info about action
311
+ player_info['ACTION'] = \
312
+ o['action'][len(players_info)]._name
313
+ players_info[(team, player_idx)] = player_info
314
+
315
+ write_players_state(writer, players_info)
316
+
317
+ if 'baseline' in o._trace['debug']:
318
+ writer.write('BASELINE: %.5f' % o._trace['debug']['baseline'])
319
+ if 'logits' in o._trace['debug']:
320
+ probs = softmax(o._trace['debug']['logits'])
321
+ action_set = football_action_set.get_action_set(self._config)
322
+ for action, prob in zip(action_set, probs):
323
+ writer.write('%s: %.5f' % (action.name, prob), scale_factor=0.5)
324
+ for d in o._debugs:
325
+ writer.write(d)
326
+ self._video_writer.write(frame)
327
+ # Write the dump.
328
+ temp_frame = None
329
+ if 'frame' in o._trace['observation']:
330
+ temp_frame = o._trace['observation']['frame']
331
+ del o._trace['observation']['frame']
332
+
333
+ # Add config to the first frame for our replay tools to use.
334
+ if self._step_cnt == 0:
335
+ o['debug']['config'] = self._config.get_dictionary()
336
+
337
+ six.moves.cPickle.dump(o._trace, self._dump_file)
338
+ if temp_frame is not None:
339
+ o._trace['observation']['frame'] = temp_frame
340
+ self._step_cnt += 1
341
+
342
+ def finalize(self):
343
+ dump_info = {}
344
+ if self._video_writer:
345
+ self._video_writer.release()
346
+ self._video_writer = None
347
+ os.close(self._video_fd)
348
+ try:
349
+ # For some reason sometimes the file is missing, so the code fails.
350
+ if WRITE_FILES:
351
+ shutil.move(self._video_tmp, self._name + self._video_suffix)
352
+ dump_info['video'] = '%s%s' % (self._name, self._video_suffix)
353
+ logging.info('Video written to %s%s', self._name, self._video_suffix)
354
+ except:
355
+ logging.error(traceback.format_exc())
356
+ if self._dump_file:
357
+ self._dump_file.close()
358
+ self._dump_file = None
359
+ if self._step_cnt == 0:
360
+ logging.warning('No data to write to the dump.')
361
+ else:
362
+ dump_info['dump'] = '%s.dump' % self._name
363
+ logging.info('Dump written to %s.dump', self._name)
364
+ return dump_info
365
+
366
+
367
+ class ObservationState(object):
368
+
369
+ def __init__(self, trace):
370
+ # Observations
371
+ self._trace = trace
372
+ self._additional_frames = []
373
+ self._debugs = []
374
+
375
+ def __getitem__(self, key):
376
+ if key in self._trace:
377
+ return self._trace[key]
378
+ if key in self._trace['observation']:
379
+ return self._trace['observation'][key]
380
+ return self._trace['debug'][key]
381
+
382
+ def __contains__(self, key):
383
+ if key in self._trace:
384
+ return True
385
+ if key in self._trace['observation']:
386
+ return True
387
+ return key in self._trace['debug']
388
+
389
+ def _distance(self, o1, o2):
390
+ # We add 'z' dimension if not present, as ball has 3 dimensions, while
391
+ # players have only 2.
392
+ if len(o1) == 2:
393
+ o1 = np.array([o1[0], o1[1], 0])
394
+ if len(o2) == 2:
395
+ o2 = np.array([o2[0], o2[1], 0])
396
+ return np.linalg.norm(o1 - o2)
397
+
398
+ def add_debug(self, text):
399
+ self._debugs.append(text)
400
+
401
+ def add_frame(self, frame):
402
+ self._additional_frames.append(frame)
403
+
404
+
405
+ class ObservationProcessor(object):
406
+
407
+ def __init__(self, config):
408
+ # Const. configuration
409
+ self._ball_takeover_epsilon = 0.03
410
+ self._ball_lost_epsilon = 0.05
411
+ self._frame = 0
412
+ self._dump_config = {}
413
+ self._dump_config['score'] = DumpConfig(
414
+ steps_before=PAST_STEPS_TRACE_SIZE,
415
+ max_count=(100000 if config['dump_scores'] else 0),
416
+ min_frequency=600,
417
+ steps_after=1)
418
+ self._dump_config['lost_score'] = DumpConfig(
419
+ steps_before=PAST_STEPS_TRACE_SIZE,
420
+ max_count=(100000 if config['dump_scores'] else 0),
421
+ min_frequency=600,
422
+ steps_after=1)
423
+ self._dump_config['episode_done'] = DumpConfig(
424
+ steps_before=0,
425
+ # Record entire episode.
426
+ steps_after=10000,
427
+ max_count=(100000 if config['dump_full_episodes'] else 0))
428
+ self._dump_config['shutdown'] = DumpConfig(steps_before=PAST_STEPS_TRACE_SIZE)
429
+ self._dump_directory = None
430
+ self._config = config
431
+ self.clear_state()
432
+
433
+ def clear_state(self):
434
+ self._frame = 0
435
+ self._state = None
436
+ self._trace = collections.deque([], PAST_STEPS_TRACE_SIZE)
437
+
438
+ def reset(self):
439
+ self.clear_state()
440
+
441
+ def len(self):
442
+ return len(self._trace)
443
+
444
+ def __getitem__(self, key):
445
+ return self._trace[key]
446
+
447
+ def add_frame(self, frame):
448
+ if len(self._trace) > 0 and self._config['write_video']:
449
+ self._trace[-1].add_frame(frame)
450
+ for dump in self.pending_dumps():
451
+ dump.add_frame(frame)
452
+
453
+ def update(self, trace):
454
+ self._frame += 1
455
+ frame = trace.get('frame', None)
456
+ if not self._config['write_video'] and 'frame' in trace['observation']:
457
+ # Don't record frame in the trace if we don't write video to save memory.
458
+ no_video_trace = trace
459
+ no_video_trace['observation'] = trace['observation'].copy()
460
+ del no_video_trace['observation']['frame']
461
+ self._state = ObservationState(no_video_trace)
462
+ frame = None
463
+ else:
464
+ self._state = ObservationState(trace)
465
+ self._trace.append(self._state)
466
+ for dump in self.pending_dumps():
467
+ dump.add_step(self._state)
468
+
469
+ def get_last_frame(self):
470
+ if not self._state:
471
+ return []
472
+ return get_frame(self._state)
473
+
474
+ def write_dump(self, name):
475
+ if not name in self._dump_config:
476
+ self._dump_config[name] = DumpConfig()
477
+ config = self._dump_config[name]
478
+ if config._active_dump:
479
+ logging.debug('Dump "%s": already pending', name)
480
+ return
481
+ if config._max_count <= 0:
482
+ logging.debug('Dump "%s": count limit reached / disabled', name)
483
+ return
484
+ if config._last_dump_time > timeit.default_timer() - config._min_frequency:
485
+ logging.debug('Dump "%s": too frequent', name)
486
+ return
487
+ config._max_count -= 1
488
+ config._last_dump_time = timeit.default_timer()
489
+ if self._dump_directory is None:
490
+ self._dump_directory = self._config['tracesdir']
491
+ if WRITE_FILES:
492
+ if not os.path.exists(self._dump_directory):
493
+ os.makedirs(self._dump_directory)
494
+ dump_name = '{2}{3}{0}_{1}'.format(name,
495
+ datetime.datetime.now().strftime('%Y%m%d-%H%M%S%f'),
496
+ self._dump_directory, os.sep)
497
+ config._active_dump = ActiveDump(dump_name,
498
+ self._frame + config._steps_after, self._config)
499
+ for step in list(self._trace)[-config._steps_before:]:
500
+ config._active_dump.add_step(step)
501
+ for frame in step._additional_frames:
502
+ config._active_dump.add_frame(frame)
503
+ if config._steps_after == 0:
504
+ # Synchronously finalize dump, so that crash dump is recorded.
505
+ config._active_dump.finalize()
506
+ config._active_dump = None
507
+ return dump_name
508
+
509
+ def pending_dumps(self):
510
+ dumps = []
511
+ for config in self._dump_config.values():
512
+ if config._active_dump:
513
+ dumps.append(config._active_dump)
514
+ return dumps
515
+
516
+ def process_pending_dumps(self, episode_done=False):
517
+ dumps = []
518
+ for name in self._dump_config:
519
+ config = self._dump_config[name]
520
+ if config._active_dump and (
521
+ episode_done or config._active_dump._finish_step <= self._frame):
522
+ dump_info = config._active_dump.finalize()
523
+ dump_info['name'] = name
524
+ dumps.append(dump_info)
525
+ config._active_dump = None
526
+ return dumps