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.
- cuju/__init__.py +217 -0
- cuju/__main__.py +262 -0
- cuju/_batch/__init__.py +4 -0
- cuju/_batch/allocator.py +52 -0
- cuju/_batch/assets.py +68 -0
- cuju/_batch/environment.py +1890 -0
- cuju/_batch/frame_stack.py +114 -0
- cuju/_batch/library.py +190 -0
- cuju/_batch/log.py +103 -0
- cuju/_batch/memory.py +70 -0
- cuju/_batch/operators.py +55 -0
- cuju/_batch/pinned.py +39 -0
- cuju/_batch/pixels.py +207 -0
- cuju/_batch/state.py +77 -0
- cuju/_checksums.py +60 -0
- cuju/_cli_contract.py +244 -0
- cuju/_cli_parsers.py +191 -0
- cuju/_completion.py +277 -0
- cuju/_dump_to_txt.py +66 -0
- cuju/_grf_config.py +331 -0
- cuju/_library_path.py +141 -0
- cuju/_media.py +113 -0
- cuju/_pixels.py +276 -0
- cuju/_plugins.py +106 -0
- cuju/_python_players.py +224 -0
- cuju/_replay_command.py +109 -0
- cuju/_replay_player.py +42 -0
- cuju/_replays.py +414 -0
- cuju/_script_helpers.py +109 -0
- cuju/_version.py +6 -0
- cuju/action_log.py +371 -0
- cuju/check.py +596 -0
- cuju/cuju_cpu.dll +0 -0
- cuju/cuju_cuda.dll +0 -0
- cuju/cuju_render.dll +0 -0
- cuju/data/SHA256SUMS +20 -0
- cuju/data/animations.bin +0 -0
- cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
- cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
- cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
- cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
- cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
- cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
- cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
- cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
- cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
- cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
- cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
- cuju/data/digests.json +186 -0
- cuju/data/render_digests.json.z +0 -0
- cuju/data/scenarios/11_vs_11_competition.py +45 -0
- cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
- cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
- cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
- cuju/data/scenarios/1_vs_1_easy.py +25 -0
- cuju/data/scenarios/5_vs_5.py +33 -0
- cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
- cuju/data/scenarios/academy_corner.py +45 -0
- cuju/data/scenarios/academy_counterattack_easy.py +45 -0
- cuju/data/scenarios/academy_counterattack_hard.py +45 -0
- cuju/data/scenarios/academy_empty_goal.py +25 -0
- cuju/data/scenarios/academy_empty_goal_close.py +25 -0
- cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
- cuju/data/scenarios/academy_run_to_score.py +30 -0
- cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
- cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
- cuju/data/scenarios/test_example_multiagent.py +28 -0
- cuju/dumps.py +942 -0
- cuju/engine_status.py +106 -0
- cuju/env.py +1168 -0
- cuju/errors.py +108 -0
- cuju/gfootball/GRF_SOURCES +86 -0
- cuju/gfootball/__init__.py +60 -0
- cuju/gfootball/_cv2.py +43 -0
- cuju/gfootball/_gym/__init__.py +88 -0
- cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
- cuju/gfootball/_gym/_vendored/__init__.py +43 -0
- cuju/gfootball/_gym/_vendored/core.py +361 -0
- cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
- cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
- cuju/gfootball/_gym/_vendored/error.py +230 -0
- cuju/gfootball/_gym/_vendored/logger.py +56 -0
- cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
- cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
- cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
- cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
- cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
- cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
- cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
- cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
- cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
- cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
- cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
- cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
- cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
- cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
- cuju/gfootball/_gym/_vendored/version.py +5 -0
- cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
- cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
- cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
- cuju/gfootball/dump_to_txt.py +49 -0
- cuju/gfootball/dump_to_video.py +33 -0
- cuju/gfootball/env/__init__.py +271 -0
- cuju/gfootball/env/config.py +163 -0
- cuju/gfootball/env/constants.py +33 -0
- cuju/gfootball/env/controller_base.py +114 -0
- cuju/gfootball/env/event_queue.py +54 -0
- cuju/gfootball/env/football_action_set.py +220 -0
- cuju/gfootball/env/football_action_set_test.py +76 -0
- cuju/gfootball/env/football_env.py +225 -0
- cuju/gfootball/env/football_env_core.py +447 -0
- cuju/gfootball/env/football_env_test.py +692 -0
- cuju/gfootball/env/gym_test.py +47 -0
- cuju/gfootball/env/observation_preprocessing.py +94 -0
- cuju/gfootball/env/observation_processor.py +526 -0
- cuju/gfootball/env/observation_rotation.py +163 -0
- cuju/gfootball/env/observation_rotation_test.py +84 -0
- cuju/gfootball/env/player_base.py +46 -0
- cuju/gfootball/env/players/__init__.py +16 -0
- cuju/gfootball/env/players/agent.py +39 -0
- cuju/gfootball/env/players/bot.py +217 -0
- cuju/gfootball/env/players/gamepad.py +81 -0
- cuju/gfootball/env/players/keyboard.py +72 -0
- cuju/gfootball/env/players/lazy.py +31 -0
- cuju/gfootball/env/players/ppo2_cnn.py +119 -0
- cuju/gfootball/env/players/replay.py +40 -0
- cuju/gfootball/env/remote_football_env.py +189 -0
- cuju/gfootball/env/scenario_builder.py +125 -0
- cuju/gfootball/env/script_helpers.py +130 -0
- cuju/gfootball/env/script_helpers_test.py +107 -0
- cuju/gfootball/env/wrappers.py +440 -0
- cuju/gfootball/env/wrappers_test.py +150 -0
- cuju/gfootball/eval_server/__init__.py +17 -0
- cuju/gfootball/eval_server/config.py +30 -0
- cuju/gfootball/eval_server/example_client.py +107 -0
- cuju/gfootball/eval_server/proto/game_server.proto +62 -0
- cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
- cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
- cuju/gfootball/eval_server/proto/master.proto +25 -0
- cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
- cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
- cuju/gfootball/eval_server/utils.py +52 -0
- cuju/gfootball/examples/__init__.py +16 -0
- cuju/gfootball/examples/models.py +66 -0
- cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
- cuju/gfootball/examples/run_ppo2.py +123 -0
- cuju/gfootball/play_game.py +73 -0
- cuju/gfootball/replay.py +43 -0
- cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
- cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
- cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
- cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
- cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
- cuju/gfootball/scenarios/5_vs_5.py +46 -0
- cuju/gfootball/scenarios/__init__.py +31 -0
- cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
- cuju/gfootball/scenarios/academy_corner.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
- cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
- cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
- cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
- cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
- cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
- cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
- cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
- cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
- cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
- cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
- cuju/gfootball/scenarios/tests/__init__.py +31 -0
- cuju/gfootball/scenarios/tests/corner_test.py +38 -0
- cuju/gfootball/scenarios/tests/goal_test.py +35 -0
- cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
- cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
- cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
- cuju/gfootball/scenarios/tests/offside_test.py +39 -0
- cuju/gfootball/scenarios/tests/penalty.py +34 -0
- cuju/gfootball/scenarios/tests/second_half.py +33 -0
- cuju/gfootball/scenarios/tests/symmetric.py +53 -0
- cuju/gfootball_engine/__init__.py +31 -0
- cuju/gfootball_engine/_gameplayfootball.py +1624 -0
- cuju/gfootball_engine/_native.py +193 -0
- cuju/gfootball_engine/_pickle_names.py +114 -0
- cuju/gfootball_engine/_render_hooks.py +156 -0
- cuju/kaggle.py +425 -0
- cuju/multi_device.py +401 -0
- cuju/players.py +260 -0
- cuju/raw.py +93 -0
- cuju/scenarios.py +661 -0
- cuju/state.py +211 -0
- cuju/wrappers.py +325 -0
- cuju_engine-0.3.0.dist-info/METADATA +325 -0
- cuju_engine-0.3.0.dist-info/RECORD +222 -0
- cuju_engine-0.3.0.dist-info/WHEEL +5 -0
- cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
- cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
- cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/env.py
ADDED
|
@@ -0,0 +1,1168 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# Copyright 2019 Google LLC
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
"""GRF's `create_environment` and gymnasium ids, each environment a batch of one.
|
|
6
|
+
|
|
7
|
+
`create_environment` takes GRF's arguments with GRF's defaults and returns GRF's gym interface,
|
|
8
|
+
or gymnasium's with `api='gymnasium'`. It draws the seed of every episode from Python's `random` as
|
|
9
|
+
GRF does, so after the same `random.seed(...)` it plays GRF's matches. Importing `cuju` registers
|
|
10
|
+
the ids `GFootball-<scenario>-<representation>-v0` with gymnasium, for `gymnasium.make`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import collections
|
|
16
|
+
import importlib
|
|
17
|
+
import importlib.metadata
|
|
18
|
+
import importlib.util
|
|
19
|
+
import io
|
|
20
|
+
import os
|
|
21
|
+
import pickle
|
|
22
|
+
import platform
|
|
23
|
+
import random
|
|
24
|
+
import re
|
|
25
|
+
import struct
|
|
26
|
+
import sys
|
|
27
|
+
import warnings
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
import gymnasium as _gym
|
|
34
|
+
except ImportError:
|
|
35
|
+
try:
|
|
36
|
+
import gym as _gym
|
|
37
|
+
except ImportError:
|
|
38
|
+
raise ImportError(
|
|
39
|
+
"cuju.env needs gymnasium, from pip install 'cuju-engine[spaces]', or GRF's gym"
|
|
40
|
+
) from None
|
|
41
|
+
|
|
42
|
+
from . import BatchEnvironment, _replays, bundled_scenarios
|
|
43
|
+
from ._batch import frame_stack as _frame_stack
|
|
44
|
+
from ._batch.state import _pickle_episode, _StateUnpickler
|
|
45
|
+
from .errors import ChoiceError, StateError
|
|
46
|
+
from .players import Bot, Lazy
|
|
47
|
+
from .raw import grf_observation, grf_observations
|
|
48
|
+
from .wrappers import MultiAgentToSingleAgent
|
|
49
|
+
|
|
50
|
+
__all__ = ['FootballEnvironment', 'create_environment', 'grf_observation', 'register_environments']
|
|
51
|
+
|
|
52
|
+
# The interfaces of `create_environment`, GRF's gym one first.
|
|
53
|
+
_APIS = ('gym', 'gymnasium')
|
|
54
|
+
|
|
55
|
+
# GRF: `observation_preprocessing.SMM_WIDTH` and `SMM_HEIGHT`.
|
|
56
|
+
_SMM_SIZE = (96, 72)
|
|
57
|
+
# GRF: every scenario that `scenario_builder` builds draws `random.randint(0, 2000000000)`.
|
|
58
|
+
_SEED_LIMIT = 2000000000
|
|
59
|
+
# GRF: the core actions in the order of the `full` set. The `default` and `v2` sets take the
|
|
60
|
+
# first 19 and 20.
|
|
61
|
+
_ACTION_NAMES = (
|
|
62
|
+
'idle',
|
|
63
|
+
'left',
|
|
64
|
+
'top_left',
|
|
65
|
+
'top',
|
|
66
|
+
'top_right',
|
|
67
|
+
'right',
|
|
68
|
+
'bottom_right',
|
|
69
|
+
'bottom',
|
|
70
|
+
'bottom_left',
|
|
71
|
+
'long_pass',
|
|
72
|
+
'high_pass',
|
|
73
|
+
'short_pass',
|
|
74
|
+
'shot',
|
|
75
|
+
'sprint',
|
|
76
|
+
'release_direction',
|
|
77
|
+
'release_sprint',
|
|
78
|
+
'sliding',
|
|
79
|
+
'dribble',
|
|
80
|
+
'release_dribble',
|
|
81
|
+
'builtin_ai',
|
|
82
|
+
'keeper_rush',
|
|
83
|
+
'pressure',
|
|
84
|
+
'team_pressure',
|
|
85
|
+
'switch',
|
|
86
|
+
'release_long_pass',
|
|
87
|
+
'release_high_pass',
|
|
88
|
+
'release_short_pass',
|
|
89
|
+
'release_shot',
|
|
90
|
+
'release_keeper_rush',
|
|
91
|
+
'release_sliding',
|
|
92
|
+
'release_pressure',
|
|
93
|
+
'release_team_pressure',
|
|
94
|
+
'release_switch',
|
|
95
|
+
)
|
|
96
|
+
_ACTION_COUNTS = {'default': 19, 'v2': 20, 'full': 33}
|
|
97
|
+
# GRF: options of `Config` that only rendering reads, so without it they change nothing.
|
|
98
|
+
_DISPLAY_OPTIONS = frozenset(
|
|
99
|
+
{
|
|
100
|
+
'custom_display_stats',
|
|
101
|
+
'display_game_stats',
|
|
102
|
+
'real_time',
|
|
103
|
+
'render_resolution_x',
|
|
104
|
+
'render_resolution_y',
|
|
105
|
+
'video_format',
|
|
106
|
+
'video_quality_level',
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
_OPTIONS = _DISPLAY_OPTIONS | {
|
|
110
|
+
'action_set',
|
|
111
|
+
'dump_full_episodes',
|
|
112
|
+
'dump_scores',
|
|
113
|
+
'episode_number',
|
|
114
|
+
'game_engine_random_seed',
|
|
115
|
+
'level',
|
|
116
|
+
'physics_steps_per_frame',
|
|
117
|
+
'players',
|
|
118
|
+
'reverse_team_processing',
|
|
119
|
+
'tracesdir',
|
|
120
|
+
'write_video',
|
|
121
|
+
}
|
|
122
|
+
# The players of GRF's `gfootball/env/players` that a batch can play.
|
|
123
|
+
_PLAYERS = ('agent', 'bot', 'lazy')
|
|
124
|
+
# GRF: any other player is a module of `gfootball.env.players`, here one so named or a module path.
|
|
125
|
+
_PLAYER_MODULE = re.compile(r'\w+(\.\w+)*')
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _numpy(tensor):
|
|
129
|
+
"""Returns a host copy of a tensor as a numpy array."""
|
|
130
|
+
return tensor.detach().cpu().numpy().copy()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _parse_player(definition):
|
|
134
|
+
"""Returns the name, left players, right players and parameters of a player definition.
|
|
135
|
+
|
|
136
|
+
GRF: `config.parse_player_definition`, which gives a player without counts one left player.
|
|
137
|
+
"""
|
|
138
|
+
name, parameters = definition, {}
|
|
139
|
+
if ':' in definition:
|
|
140
|
+
# GRF: on Windows the path of a replay may hold a colon.
|
|
141
|
+
if (
|
|
142
|
+
platform.system() == 'Windows'
|
|
143
|
+
and definition.startswith('replay:')
|
|
144
|
+
and len(definition.split(':')) > 2
|
|
145
|
+
):
|
|
146
|
+
name, text = 'replay', definition.split('replay:')[-1]
|
|
147
|
+
else:
|
|
148
|
+
name, text = definition.split(':')
|
|
149
|
+
for parameter in text.split(','):
|
|
150
|
+
key, value = parameter.split('=')
|
|
151
|
+
parameters[key] = value
|
|
152
|
+
counted = 'left_players' in parameters or 'right_players' in parameters
|
|
153
|
+
left = int(parameters.pop('left_players', 0))
|
|
154
|
+
right = int(parameters.pop('right_players', 0))
|
|
155
|
+
return name, left if counted else 1, right, parameters
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _scenario_facts(asset):
|
|
159
|
+
"""Returns whether a scenario is deterministic and the controllable players of each side.
|
|
160
|
+
|
|
161
|
+
The first is `None` where only the bundle knows, and the second is `None` unless the scenario
|
|
162
|
+
sets `control_all_players`.
|
|
163
|
+
"""
|
|
164
|
+
if isinstance(asset, str) and asset.endswith('.py') and os.path.isfile(asset):
|
|
165
|
+
from . import scenarios
|
|
166
|
+
|
|
167
|
+
# GRF: `create_environment` reads the scenario of episode 1, the odd form.
|
|
168
|
+
odd = scenarios.describe(asset)[1]
|
|
169
|
+
control = None
|
|
170
|
+
if odd['values']['control_all_players']:
|
|
171
|
+
control = tuple(
|
|
172
|
+
sum(1 for player in odd[side] if player[4]) for side in ('left', 'right')
|
|
173
|
+
)
|
|
174
|
+
return bool(odd['values']['deterministic']), control
|
|
175
|
+
if isinstance(asset, str) and not asset.endswith('.cjb') and os.sep not in asset:
|
|
176
|
+
# GRF: no shipped scenario is deterministic or sets `control_all_players`.
|
|
177
|
+
return False, None
|
|
178
|
+
return None, None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _numpy_values(value):
|
|
182
|
+
"""Returns a value of GRF's observation of the match with each array stand-in as numpy's."""
|
|
183
|
+
from . import dumps
|
|
184
|
+
|
|
185
|
+
if isinstance(value, dumps._Array):
|
|
186
|
+
numpy_type, _ = value.kind
|
|
187
|
+
return np.array(value.values, dtype=np.dtype(numpy_type.order + numpy_type.code)).reshape(
|
|
188
|
+
value.shape
|
|
189
|
+
)
|
|
190
|
+
if isinstance(value, dict):
|
|
191
|
+
return {key: _numpy_values(item) for key, item in value.items()}
|
|
192
|
+
if isinstance(value, list):
|
|
193
|
+
return [_numpy_values(item) for item in value]
|
|
194
|
+
return value
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _space_shape(base, agents, single, stacked):
|
|
198
|
+
"""Returns the shape of GRF's observation space for `agents` agents of the player."""
|
|
199
|
+
# GRF: the representation wrappers size the agent axis from the action space, which is a
|
|
200
|
+
# `Discrete` that counts as one agent for fewer than two agents.
|
|
201
|
+
shape = (agents if agents > 1 else 1, *base)
|
|
202
|
+
if single:
|
|
203
|
+
shape = shape[1:]
|
|
204
|
+
if stacked:
|
|
205
|
+
shape = (*shape[:-1], shape[-1] * 4)
|
|
206
|
+
return shape
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class _Dumps:
|
|
210
|
+
"""GRF's dump options, which `cuju.dumps.DumpWriter` writes after each step, outside `step`.
|
|
211
|
+
|
|
212
|
+
Each reset takes the dump options of the configuration for the episode that it starts. With a
|
|
213
|
+
`frequency` above 1, only the first reset and then one in every `frequency` keep them, as GRF's
|
|
214
|
+
`PeriodicDumpWriter` counts the resets of the environment.
|
|
215
|
+
"""
|
|
216
|
+
|
|
217
|
+
def __init__(self, batch, full_episodes, goals, frequency, directory):
|
|
218
|
+
try:
|
|
219
|
+
from . import dumps
|
|
220
|
+
except ImportError:
|
|
221
|
+
raise NotImplementedError(
|
|
222
|
+
"GRF's dump options write through cuju.dumps, which this installation lacks"
|
|
223
|
+
) from None
|
|
224
|
+
self._frequency = frequency
|
|
225
|
+
self._resets = 0
|
|
226
|
+
# GRF: an empty `logdir` writes the dumps in the working directory.
|
|
227
|
+
self._writer = dumps.DumpWriter(
|
|
228
|
+
batch,
|
|
229
|
+
directory or os.curdir,
|
|
230
|
+
environments=[0],
|
|
231
|
+
write_full_episode_dumps=bool(full_episodes),
|
|
232
|
+
write_goal_dumps=bool(goals),
|
|
233
|
+
)
|
|
234
|
+
# GRF: one environment names its dumps by their kind and the time they start.
|
|
235
|
+
self._writer._grf_names = True
|
|
236
|
+
|
|
237
|
+
def after_step(self, actions):
|
|
238
|
+
"""Records the step that the batch's `actions` played and returns the dumps it wrote.
|
|
239
|
+
|
|
240
|
+
GRF: `info['dumps']` lists a dictionary for each dump that the step finished, with the
|
|
241
|
+
path of the dump and the name of its kind, as `ObservationProcessor` gives it.
|
|
242
|
+
"""
|
|
243
|
+
return [{'dump': path, 'name': kind} for kind, path in self._writer._record(actions)]
|
|
244
|
+
|
|
245
|
+
def follow(self, config):
|
|
246
|
+
"""Takes the dump options of GRF's `Config` for the episode that a reset starts."""
|
|
247
|
+
# GRF: `create_environment` applies `PeriodicDumpWriter` only for a frequency above 1.
|
|
248
|
+
kept = self._frequency <= 1 or self._resets % self._frequency == 0
|
|
249
|
+
self._resets += 1
|
|
250
|
+
self._writer.write_full_episode_dumps = kept and bool(config['dump_full_episodes'])
|
|
251
|
+
self._writer.write_goal_dumps = kept and bool(config['dump_scores'])
|
|
252
|
+
|
|
253
|
+
def close(self):
|
|
254
|
+
self._writer.close()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# GRF: the keys of a state's pickle, of the episode logic and of the wrappers that keep states.
|
|
258
|
+
_CORE, _CHECKPOINTS, _FRAMES = 'FootballEnvCore', 'CheckpointRewardWrapper', 'FrameStack'
|
|
259
|
+
# GRF: the attributes of `EnvState`, the episode logic.
|
|
260
|
+
_LOGIC = ('previous_score_diff', 'previous_game_mode', 'prev_ball_owned_team')
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _split_state(state):
|
|
264
|
+
"""Returns the pickled entries of a state in GRF's byte format and its match bytes.
|
|
265
|
+
|
|
266
|
+
The entries hold the episode logic under `FootballEnvCore` and those of GRF's wrappers, such
|
|
267
|
+
as the counts of `CheckpointRewardWrapper` and the frames of `FrameStack`.
|
|
268
|
+
|
|
269
|
+
Raises:
|
|
270
|
+
StateError: If the bytes hold no pickle of the episode logic or it does not load.
|
|
271
|
+
"""
|
|
272
|
+
if len(state) < 4 or not 0 < struct.unpack_from('<i', state)[0] <= len(state) - 4:
|
|
273
|
+
raise StateError(
|
|
274
|
+
'expected the bytes of a state: a pickle length, the pickle and the match, '
|
|
275
|
+
f'found {len(state)} bytes that hold none'
|
|
276
|
+
)
|
|
277
|
+
(length,) = struct.unpack_from('<i', state)
|
|
278
|
+
unpickler = _StateUnpickler(io.BytesIO(state[4 : 4 + length]))
|
|
279
|
+
# The frames of `FrameStack` are numpy arrays in a deque.
|
|
280
|
+
unpickler.stacked = True
|
|
281
|
+
try:
|
|
282
|
+
entries = unpickler.load()
|
|
283
|
+
[vars(entries[_CORE])[name] for name in _LOGIC]
|
|
284
|
+
except (pickle.UnpicklingError, KeyError, TypeError, EOFError) as error:
|
|
285
|
+
raise StateError(
|
|
286
|
+
f'expected the pickle of the episode logic in the state, found {error!r}'
|
|
287
|
+
) from error
|
|
288
|
+
return entries, state[4 + length :]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _pickled(value):
|
|
292
|
+
"""Returns the pickle of `value` without its protocol and stop opcodes."""
|
|
293
|
+
return pickle.dumps(value, protocol=2)[2:-1]
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _own_frame(frame):
|
|
297
|
+
"""Returns a numeric frame as an array of its own with numpy's own dtype, else the frame.
|
|
298
|
+
|
|
299
|
+
A batch's stack holds such arrays, which pickle writes in full with one dtype for all, while
|
|
300
|
+
the frames of a loaded state share the dtypes that the pickle built.
|
|
301
|
+
"""
|
|
302
|
+
if not isinstance(frame, np.ndarray) or frame.dtype.kind not in 'biufc':
|
|
303
|
+
return frame
|
|
304
|
+
return frame.astype(np.dtype(frame.dtype.str))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _join_state(entries, match):
|
|
308
|
+
"""Returns the state in GRF's byte format of pickled entries and match bytes.
|
|
309
|
+
|
|
310
|
+
The episode logic, the checkpoint counts and the frames are written as a batch writes them, so
|
|
311
|
+
equal entries give equal bytes, and every other entry follows as pickle writes it.
|
|
312
|
+
"""
|
|
313
|
+
episode = [vars(entries[_CORE])[name] for name in _LOGIC]
|
|
314
|
+
collected = None
|
|
315
|
+
if _CHECKPOINTS in entries:
|
|
316
|
+
counts = entries[_CHECKPOINTS]
|
|
317
|
+
collected = [counts.get(agent, 0) for agent in range(max(counts, default=-1) + 1)]
|
|
318
|
+
frames = None
|
|
319
|
+
if _FRAMES in entries:
|
|
320
|
+
stack = entries[_FRAMES]
|
|
321
|
+
frames = _pickled(
|
|
322
|
+
collections.deque(map(_own_frame, stack), maxlen=getattr(stack, 'maxlen', None))
|
|
323
|
+
)
|
|
324
|
+
data = _pickle_episode(episode, collected, frames)
|
|
325
|
+
others = b''.join(
|
|
326
|
+
_pickled(key) + _pickled(value)
|
|
327
|
+
for key, value in entries.items()
|
|
328
|
+
if key not in (_CORE, _CHECKPOINTS, _FRAMES)
|
|
329
|
+
)
|
|
330
|
+
# The other entries join the dictionary before its last `SETITEMS` and `STOP`.
|
|
331
|
+
data = data[:-2] + others + data[-2:]
|
|
332
|
+
return struct.pack('<i', len(data)) + data + match
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class FootballEnvironment(_gym.Env):
|
|
336
|
+
"""One GRF environment, from `create_environment`.
|
|
337
|
+
|
|
338
|
+
The observation, the reward, the termination and the information of each step equal those of
|
|
339
|
+
the environment that GRF's `create_environment` returns for the same arguments, bit for bit,
|
|
340
|
+
after the same `random.seed(...)`. With GRF's gym interface, the default, `reset` returns the
|
|
341
|
+
observation and `step` returns `(observation, reward, done, info)`. With gymnasium's, `reset`
|
|
342
|
+
returns `(observation, info)` and `step` returns `(observation, reward, terminated, truncated,
|
|
343
|
+
info)`, with `truncated` always `False`, as GRF's episodes end only by termination.
|
|
344
|
+
|
|
345
|
+
Attributes:
|
|
346
|
+
batch: The batch of one environment that plays the match.
|
|
347
|
+
observation_space, action_space: GRF's spaces for the same arguments. The raw
|
|
348
|
+
representation has no observation space, as in GRF, so its `observation_space` is
|
|
349
|
+
`None`.
|
|
350
|
+
_config: GRF's `Config` of the environment, of the private module `cuju._grf_config`, which
|
|
351
|
+
counts the episodes and holds the seed of each as GRF's does.
|
|
352
|
+
_num_actions: The number of actions of the action set, as GRF's attribute.
|
|
353
|
+
reward_range: The bounds of the reward, unbounded, as gym's `Env` gives GRF's.
|
|
354
|
+
"""
|
|
355
|
+
|
|
356
|
+
# GRF: gym's `Env`, whose rewards are unbounded.
|
|
357
|
+
reward_range = (-float('inf'), float('inf'))
|
|
358
|
+
|
|
359
|
+
def __init__(self, batch, settings):
|
|
360
|
+
self.batch = batch
|
|
361
|
+
self._settings = settings
|
|
362
|
+
self._config = settings['config']
|
|
363
|
+
self._slots = settings['slots']
|
|
364
|
+
# GRF: a configuration without an `agent` player steps with `step([])`, and its observation
|
|
365
|
+
# is the match's own.
|
|
366
|
+
self._agent = settings.get('agent', True)
|
|
367
|
+
# GRF: the single-agent wrappers follow the agent counts of the arguments.
|
|
368
|
+
self._single = settings['single']
|
|
369
|
+
self._representation = settings['representation']
|
|
370
|
+
self._fixed = settings['fixed_seed'] is not None
|
|
371
|
+
self._done = False
|
|
372
|
+
self._gymnasium = settings['api'] == 'gymnasium'
|
|
373
|
+
self._dumps = settings['dumps']
|
|
374
|
+
self._wrapper = settings['wrapper']
|
|
375
|
+
# GRF: the scripted players of `extra_players`, which act on their own observations.
|
|
376
|
+
self._scripted = [
|
|
377
|
+
(
|
|
378
|
+
Bot(batch, slots[0])
|
|
379
|
+
if name == 'bot'
|
|
380
|
+
else Lazy(batch, slots)
|
|
381
|
+
if name == 'lazy'
|
|
382
|
+
else name.bind(batch),
|
|
383
|
+
slots,
|
|
384
|
+
)
|
|
385
|
+
for name, slots in settings['scripted']
|
|
386
|
+
]
|
|
387
|
+
self._python_players = settings.get('python_players')
|
|
388
|
+
# GRF: the steps of the episode that `write_dump` writes.
|
|
389
|
+
self._episode_steps = _replays.EpisodeSteps()
|
|
390
|
+
self._played = self._episode_steps.reset()
|
|
391
|
+
count = settings['action_count']
|
|
392
|
+
agents = len(self._slots) if self._wrapper is None else self._wrapper.players
|
|
393
|
+
# GRF's gym interface takes gym's spaces where an older gym is installed.
|
|
394
|
+
spaces = (_legacy_gym() or _gym).spaces if settings['api'] == 'gym' else _gym.spaces
|
|
395
|
+
self.action_space = (
|
|
396
|
+
spaces.MultiDiscrete([count] * agents) if agents > 1 else spaces.Discrete(count)
|
|
397
|
+
)
|
|
398
|
+
width, height = settings['channel_dimensions']
|
|
399
|
+
stacked = settings['stacked']
|
|
400
|
+
if self._representation == 'extracted':
|
|
401
|
+
shape = _space_shape((height, width, 4), agents, self._single, stacked)
|
|
402
|
+
self.observation_space = spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8)
|
|
403
|
+
elif self._representation != 'raw':
|
|
404
|
+
shape = _space_shape((115,), agents, self._single, stacked)
|
|
405
|
+
self.observation_space = spaces.Box(
|
|
406
|
+
low=-np.inf, high=np.inf, shape=shape, dtype=np.float32
|
|
407
|
+
)
|
|
408
|
+
else:
|
|
409
|
+
# GRF: the raw representation has no space, and gymnasium's `Env` declares none.
|
|
410
|
+
self.observation_space = None
|
|
411
|
+
|
|
412
|
+
@property
|
|
413
|
+
def _num_actions(self) -> int:
|
|
414
|
+
"""The number of actions of the action set, as GRF's `FootballEnv._num_actions`."""
|
|
415
|
+
return self._settings['action_count']
|
|
416
|
+
|
|
417
|
+
def _observe(self):
|
|
418
|
+
"""Returns the agent's observation of the current step, as GRF's wrappers give it."""
|
|
419
|
+
if self._wrapper is not None:
|
|
420
|
+
if self._representation == 'raw':
|
|
421
|
+
return self._raw(self._wrapper._index[0].tolist())
|
|
422
|
+
array = _numpy(self._wrapper.observation()[0])
|
|
423
|
+
elif self._representation == 'raw':
|
|
424
|
+
return self.observation()
|
|
425
|
+
else:
|
|
426
|
+
array = _numpy(self.batch.observation()[0, self._slots])
|
|
427
|
+
return array[0] if self._single else array
|
|
428
|
+
|
|
429
|
+
def _raw(self, slots):
|
|
430
|
+
"""Returns GRF's raw observation of each agent of `slots`."""
|
|
431
|
+
return grf_observations(self.batch, 0, slots)
|
|
432
|
+
|
|
433
|
+
def observation(self) -> list[dict[str, Any]] | dict[str, Any] | None:
|
|
434
|
+
"""Returns the raw observation of each of the agent's players, as GRF's unwrapped one.
|
|
435
|
+
|
|
436
|
+
Without an `agent` player it is GRF's observation of the match, the dictionary that GRF's
|
|
437
|
+
dumps hold, read from the players that the configuration holds. With no player at all the
|
|
438
|
+
batch holds no raw observation to read, so it is `None`.
|
|
439
|
+
"""
|
|
440
|
+
if not self._agent:
|
|
441
|
+
return self._match_observation()
|
|
442
|
+
return self._raw(self._slots)
|
|
443
|
+
|
|
444
|
+
def _match_observation(self):
|
|
445
|
+
"""Returns GRF's observation of the match, `FootballEnvCore.observation()`, or `None`."""
|
|
446
|
+
from . import dumps
|
|
447
|
+
|
|
448
|
+
batch = self.batch
|
|
449
|
+
if batch.agents == 0:
|
|
450
|
+
return None
|
|
451
|
+
raw = batch.raw()
|
|
452
|
+
rows = [
|
|
453
|
+
{name: tensor[0, agent].tolist() for name, tensor in raw.items()}
|
|
454
|
+
for agent in range(batch.agents)
|
|
455
|
+
]
|
|
456
|
+
values, _ = dumps._episode_values(batch, 0)
|
|
457
|
+
# An ended episode keeps the designated players of its last step apart.
|
|
458
|
+
designated = values[15:17] if self._done else values[13:15]
|
|
459
|
+
episode = dumps._Episode(0, values, None, False, False)
|
|
460
|
+
sticky = dumps._sticky_names(batch.action_count)
|
|
461
|
+
return _numpy_values(dumps._match_observation(rows, episode, designated, sticky))
|
|
462
|
+
|
|
463
|
+
def _actions(self, action):
|
|
464
|
+
"""Returns the agent's actions and those of the scripted players for the agent's `action`.
|
|
465
|
+
|
|
466
|
+
The first are the actions of the batch's agents with those of the scripted players in
|
|
467
|
+
their slots, or under `MultiAgentToSingleAgent` the policy's actions, one a side, which the
|
|
468
|
+
wrapper places. The second lists each scripted player's slot with its action.
|
|
469
|
+
"""
|
|
470
|
+
# GRF: `FootballEnv._action_to_list`, then one action per player of the agent.
|
|
471
|
+
if isinstance(action, np.ndarray):
|
|
472
|
+
action = action.tolist()
|
|
473
|
+
if not isinstance(action, list):
|
|
474
|
+
action = [action]
|
|
475
|
+
count = len(self._slots) if self._wrapper is None else self._wrapper.players
|
|
476
|
+
if len(action) != count:
|
|
477
|
+
if not self._agent:
|
|
478
|
+
# GRF: `FootballEnv.step` without an agent asserts that it gets no action.
|
|
479
|
+
raise ValueError(f'step() received {len(action)} actions, but no agent is playing')
|
|
480
|
+
raise ValueError(
|
|
481
|
+
f'expected {count} actions, one for each player of the agent, found {len(action)}'
|
|
482
|
+
)
|
|
483
|
+
names = _ACTION_NAMES[: self._settings['action_count']]
|
|
484
|
+
values = []
|
|
485
|
+
for value in action:
|
|
486
|
+
if hasattr(value, '_name') and hasattr(value, '_backend_action'):
|
|
487
|
+
# GRF: a `CoreAction` stands for itself.
|
|
488
|
+
if value._name not in names:
|
|
489
|
+
raise ValueError(
|
|
490
|
+
f'expected an action of the set {self._settings["action_set"]!r}, found '
|
|
491
|
+
f'{value._name!r}; create the environment with that set'
|
|
492
|
+
)
|
|
493
|
+
value = names.index(value._name)
|
|
494
|
+
elif isinstance(value, (bool, int, np.int32, np.int64)):
|
|
495
|
+
value = int(value)
|
|
496
|
+
else:
|
|
497
|
+
raise TypeError(f'expected an integer action, found {value!r}')
|
|
498
|
+
values.append(value)
|
|
499
|
+
scripted = [
|
|
500
|
+
(slot, value)
|
|
501
|
+
for player, slots in self._scripted
|
|
502
|
+
for slot, value in zip(slots, player.act().reshape(-1).tolist(), strict=True)
|
|
503
|
+
]
|
|
504
|
+
if self._wrapper is not None:
|
|
505
|
+
return values, scripted
|
|
506
|
+
actions = [0] * self.batch.agents
|
|
507
|
+
for slot, value in [*zip(self._slots, values, strict=True), *scripted]:
|
|
508
|
+
actions[slot] = value
|
|
509
|
+
return actions, scripted
|
|
510
|
+
|
|
511
|
+
def reset(self, *, seed: int | None = None, options: dict[str, Any] | None = None) -> Any:
|
|
512
|
+
"""Starts the next episode, with a seed drawn from Python's `random` as GRF draws it.
|
|
513
|
+
|
|
514
|
+
Args:
|
|
515
|
+
seed: Seeds `np_random`, as the reset of GRF's gymnasium port does. The match does not
|
|
516
|
+
depend on it.
|
|
517
|
+
options: Ignored, as in GRF.
|
|
518
|
+
|
|
519
|
+
Returns:
|
|
520
|
+
The observation, and with gymnasium's interface an empty information dictionary after
|
|
521
|
+
it.
|
|
522
|
+
"""
|
|
523
|
+
if seed is not None:
|
|
524
|
+
# GRF: gym 0.21 takes no seed in `reset`, so only gymnasium's base class seeds.
|
|
525
|
+
super().reset(seed=seed)
|
|
526
|
+
target = self.batch if self._wrapper is None else self._wrapper
|
|
527
|
+
if self._dumps is not None:
|
|
528
|
+
# GRF: the dump options of the configuration, which `PeriodicDumpWriter` sets before
|
|
529
|
+
# the reset, hold for the episode that the reset starts.
|
|
530
|
+
self._dumps.follow(self._config)
|
|
531
|
+
episode_seed = None if self._fixed else random.randint(0, _SEED_LIMIT)
|
|
532
|
+
if episode_seed is None:
|
|
533
|
+
target.reset()
|
|
534
|
+
else:
|
|
535
|
+
target.reset(seeds=episode_seed)
|
|
536
|
+
# GRF: each reset builds the scenario of the next episode number with the seed it drew.
|
|
537
|
+
self._config._new_scenario(1, episode_seed)
|
|
538
|
+
if self._python_players is not None:
|
|
539
|
+
self._python_players.reset()
|
|
540
|
+
self._played = self._episode_steps.reset()
|
|
541
|
+
self._done = False
|
|
542
|
+
if self._gymnasium:
|
|
543
|
+
return self._observe(), {}
|
|
544
|
+
return self._observe()
|
|
545
|
+
|
|
546
|
+
def step(self, action: Any) -> tuple[Any, ...]:
|
|
547
|
+
"""Runs one step.
|
|
548
|
+
|
|
549
|
+
Args:
|
|
550
|
+
action: An action index, or a list or numpy array of one per player of the agent.
|
|
551
|
+
|
|
552
|
+
Returns:
|
|
553
|
+
The observation, the `float32` reward, a scalar for one player or without an agent,
|
|
554
|
+
whether the episode ended and `{'score_reward': ...}`. With GRF's dump options, the
|
|
555
|
+
information also holds `dumps`, as GRF's, a dictionary for each dump that the step
|
|
556
|
+
finished, which maps `dump` to its path and `name` to its kind, such as
|
|
557
|
+
`episode_done`. Gymnasium's interface puts `False` for truncation before the
|
|
558
|
+
information.
|
|
559
|
+
|
|
560
|
+
Raises:
|
|
561
|
+
RuntimeError: If the episode ended, until `reset`.
|
|
562
|
+
ValueError: If the number of actions is not the number of the agent's players.
|
|
563
|
+
"""
|
|
564
|
+
if self._done:
|
|
565
|
+
raise RuntimeError("can't call step() once the episode finished; call reset() first")
|
|
566
|
+
actions, scripted = self._actions(action)
|
|
567
|
+
if self._wrapper is None:
|
|
568
|
+
_, reward, done, information = self.batch.step([actions])
|
|
569
|
+
played = [actions]
|
|
570
|
+
else:
|
|
571
|
+
_, reward, done, information = self._wrapper.step([actions], _others=scripted)
|
|
572
|
+
played = self._wrapper.last_actions
|
|
573
|
+
# GRF: the reward of each of the agent's players, which `MultiAgentToSingleAgent` passes
|
|
574
|
+
# on for every player that the agent controls.
|
|
575
|
+
reward = _numpy(reward[0, self._slots])
|
|
576
|
+
self._played.append(played)
|
|
577
|
+
self._done = bool(done[0])
|
|
578
|
+
score_reward = int(information['score_reward'][0])
|
|
579
|
+
info = {'score_reward': score_reward}
|
|
580
|
+
if self._dumps is not None:
|
|
581
|
+
# GRF: the information lists the dumps that the step finished.
|
|
582
|
+
written = self._dumps.after_step(played)
|
|
583
|
+
if written:
|
|
584
|
+
info['dumps'] = written
|
|
585
|
+
observation = self._observe()
|
|
586
|
+
if not self._agent:
|
|
587
|
+
# GRF: without an agent the reward is the scoring reward itself.
|
|
588
|
+
reward = np.array(score_reward, dtype=np.float32)
|
|
589
|
+
elif self._single:
|
|
590
|
+
reward = reward[0]
|
|
591
|
+
if self._gymnasium:
|
|
592
|
+
return observation, reward, self._done, False, info
|
|
593
|
+
return observation, reward, self._done, info
|
|
594
|
+
|
|
595
|
+
def seed(self, seed: int | None = None) -> None:
|
|
596
|
+
"""Does nothing and returns `None`, as gym's `Env.seed` under GRF's environment does.
|
|
597
|
+
|
|
598
|
+
The match follows Python's `random`, or `game_engine_random_seed`, as GRF's does.
|
|
599
|
+
"""
|
|
600
|
+
return None
|
|
601
|
+
|
|
602
|
+
def disable_render(self) -> None:
|
|
603
|
+
"""Does nothing, since cuju renders nothing. GRF's turns its renderer off."""
|
|
604
|
+
|
|
605
|
+
def _refuse_wrapper_state(self):
|
|
606
|
+
"""Raises `ValueError` under GRF's `MultiAgentToSingleAgent`, which refuses states too."""
|
|
607
|
+
if self._wrapper is not None:
|
|
608
|
+
raise ValueError(
|
|
609
|
+
"GRF's MultiAgentToSingleAgent supports no states, so a scenario with "
|
|
610
|
+
'control_all_players played by one player a side has none'
|
|
611
|
+
)
|
|
612
|
+
|
|
613
|
+
def get_state(self, to_pickle: dict[str, Any] | None = None) -> bytes:
|
|
614
|
+
"""Returns the state of the match in GRF's byte format, as GRF's `get_state(to_pickle)`.
|
|
615
|
+
|
|
616
|
+
Args:
|
|
617
|
+
to_pickle: The entries of GRF's wrappers over the environment, such as the counts of
|
|
618
|
+
`CheckpointRewardWrapper` and the frames of `FrameStack`, which the state holds
|
|
619
|
+
beside the match. The entries of `rewards='scoring,checkpoints'` and
|
|
620
|
+
`stacked=True` replace those of the same keys, as GRF's innermost wrapper writes
|
|
621
|
+
its entry last.
|
|
622
|
+
|
|
623
|
+
Returns:
|
|
624
|
+
The bytes, which `set_state` here or in GRF reads. Equal entries give equal bytes,
|
|
625
|
+
whether the options of `create_environment` or GRF's wrappers wrote them.
|
|
626
|
+
"""
|
|
627
|
+
self._refuse_wrapper_state()
|
|
628
|
+
batch = self.batch
|
|
629
|
+
entries, match = _split_state(batch.get_state(0, stacked=batch.stacked))
|
|
630
|
+
own = {_CORE: entries[_CORE]}
|
|
631
|
+
if _CHECKPOINTS in entries:
|
|
632
|
+
# GRF: the counts go by the agent's players, which play the batch's slots.
|
|
633
|
+
counts = entries[_CHECKPOINTS]
|
|
634
|
+
own[_CHECKPOINTS] = {
|
|
635
|
+
index: counts[slot] for index, slot in enumerate(self._slots) if slot in counts
|
|
636
|
+
}
|
|
637
|
+
if batch.stacked:
|
|
638
|
+
# GRF: `FrameStack` holds the observations of the agent's players.
|
|
639
|
+
stack = batch.observation()[0, self._slots].cpu()
|
|
640
|
+
own[_FRAMES] = collections.deque(
|
|
641
|
+
_frame_stack.frames_of(stack, len(self._slots)), maxlen=_frame_stack.FRAMES
|
|
642
|
+
)
|
|
643
|
+
return _join_state({**(to_pickle or {}), **own}, match)
|
|
644
|
+
|
|
645
|
+
def set_state(self, state: bytes) -> dict[str, Any]:
|
|
646
|
+
"""Loads a state in GRF's byte format, as GRF's `set_state(state)`.
|
|
647
|
+
|
|
648
|
+
Returns:
|
|
649
|
+
The pickled entries of the state, as GRF's returns them, from which GRF's wrappers over
|
|
650
|
+
the environment take theirs, such as the counts of `CheckpointRewardWrapper` and the
|
|
651
|
+
frames of `FrameStack`.
|
|
652
|
+
|
|
653
|
+
Raises:
|
|
654
|
+
StateError: If the bytes hold no state that loads, or lack the counts of
|
|
655
|
+
`rewards='scoring,checkpoints'` or the frames of `stacked=True`. It is a
|
|
656
|
+
`ValueError` and a `RuntimeError`.
|
|
657
|
+
"""
|
|
658
|
+
self._refuse_wrapper_state()
|
|
659
|
+
batch = self.batch
|
|
660
|
+
entries, match = _split_state(state)
|
|
661
|
+
core = {_CORE: entries[_CORE]}
|
|
662
|
+
own = dict(core)
|
|
663
|
+
if batch._checkpoints and _CHECKPOINTS in entries:
|
|
664
|
+
counts = entries[_CHECKPOINTS]
|
|
665
|
+
own[_CHECKPOINTS] = {
|
|
666
|
+
slot: counts[index] for index, slot in enumerate(self._slots) if index in counts
|
|
667
|
+
}
|
|
668
|
+
if batch.stacked and _FRAMES in entries:
|
|
669
|
+
own[_FRAMES] = self._batch_frames(entries[_FRAMES])
|
|
670
|
+
batch.set_state(0, _join_state(own, match), stacked=batch.stacked)
|
|
671
|
+
# The replay of `write_dump` plays the match in a batch of raw observations.
|
|
672
|
+
self._played = self._episode_steps.set_state(_join_state(core, match), self._done)
|
|
673
|
+
self._done = False
|
|
674
|
+
return entries
|
|
675
|
+
|
|
676
|
+
def _batch_frames(self, frames):
|
|
677
|
+
"""Returns the frames of a state's `FrameStack` for every agent of the batch.
|
|
678
|
+
|
|
679
|
+
GRF's `FrameStack` holds the observations of the agent's players, and the batch stacks
|
|
680
|
+
those of the scripted players too. Their frames stay as the batch holds them, since only
|
|
681
|
+
the agent sees a stack.
|
|
682
|
+
|
|
683
|
+
Raises:
|
|
684
|
+
StateError: If the frames are not four observations of the agent's players.
|
|
685
|
+
"""
|
|
686
|
+
batch = self.batch
|
|
687
|
+
agents = batch.agents
|
|
688
|
+
if list(self._slots) == list(range(agents)):
|
|
689
|
+
return frames
|
|
690
|
+
own = list(frames) if isinstance(frames, (collections.deque, list, tuple)) else []
|
|
691
|
+
current = _frame_stack.frames_of(batch.observation()[0, :agents].cpu(), agents)
|
|
692
|
+
if len(own) != _frame_stack.FRAMES:
|
|
693
|
+
raise StateError(
|
|
694
|
+
f"expected the {_frame_stack.FRAMES} frames of GRF's FrameStack in the state"
|
|
695
|
+
)
|
|
696
|
+
shape = current[0].shape[1:]
|
|
697
|
+
expected = shape if len(self._slots) == 1 else (len(self._slots), *shape)
|
|
698
|
+
stack = []
|
|
699
|
+
for frame, mine in zip(current, own, strict=True):
|
|
700
|
+
mine = np.asarray(mine)
|
|
701
|
+
if mine.shape != expected or mine.dtype != frame.dtype:
|
|
702
|
+
raise StateError(
|
|
703
|
+
f'expected frames of the shape {expected} and the type {frame.dtype} in the '
|
|
704
|
+
f'state, found {mine.shape} and {mine.dtype}'
|
|
705
|
+
)
|
|
706
|
+
frame = frame.copy()
|
|
707
|
+
frame[self._slots] = mine.reshape((len(self._slots), *shape))
|
|
708
|
+
stack.append(frame)
|
|
709
|
+
return collections.deque(stack, maxlen=_frame_stack.FRAMES)
|
|
710
|
+
|
|
711
|
+
def write_dump(self, name: str) -> str | None:
|
|
712
|
+
"""Writes the last steps of the episode as a dump, as GRF's `write_dump(name)`.
|
|
713
|
+
|
|
714
|
+
The dump `<logdir>/<name>_<date>-<time>.dump` holds the last 100 steps of the episode at
|
|
715
|
+
most, the first with the configuration, as GRF writes it. Each name writes once an episode.
|
|
716
|
+
The steps play again in a new batch of one environment, from the reset and each state
|
|
717
|
+
loaded since, so a long episode takes a moment.
|
|
718
|
+
|
|
719
|
+
Args:
|
|
720
|
+
name: The name of the dump. GRF's options write `episode_done`, `score` and
|
|
721
|
+
`lost_score`, so those names write nothing here.
|
|
722
|
+
|
|
723
|
+
Returns:
|
|
724
|
+
The path of the dump without `.dump`, as GRF returns it, or `None` if it writes none.
|
|
725
|
+
|
|
726
|
+
Raises:
|
|
727
|
+
RuntimeError: If the episode ended, until `reset`, where GRF's has no steps to dump.
|
|
728
|
+
"""
|
|
729
|
+
return self._episode_steps.write_dump(self, name)
|
|
730
|
+
|
|
731
|
+
def close(self) -> None:
|
|
732
|
+
"""Frees the batch."""
|
|
733
|
+
if self._dumps is not None:
|
|
734
|
+
self._dumps.close()
|
|
735
|
+
self._dumps = None
|
|
736
|
+
self.batch.close()
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def create_environment(
|
|
740
|
+
env_name: str = '',
|
|
741
|
+
stacked: bool = False,
|
|
742
|
+
representation: str = 'extracted',
|
|
743
|
+
rewards: str = 'scoring',
|
|
744
|
+
write_goal_dumps: bool = False,
|
|
745
|
+
write_full_episode_dumps: bool = False,
|
|
746
|
+
render: bool = False,
|
|
747
|
+
write_video: bool = False,
|
|
748
|
+
dump_frequency: int = 1,
|
|
749
|
+
logdir: str = '',
|
|
750
|
+
extra_players: list[str] | None = None,
|
|
751
|
+
number_of_left_players_agent_controls: int = 1,
|
|
752
|
+
number_of_right_players_agent_controls: int = 0,
|
|
753
|
+
channel_dimensions: tuple[int, int] = _SMM_SIZE,
|
|
754
|
+
other_config_options: dict[str, Any] | None = None,
|
|
755
|
+
*,
|
|
756
|
+
device: str = 'cpu',
|
|
757
|
+
threads: int = 1,
|
|
758
|
+
api: str = 'gym',
|
|
759
|
+
) -> FootballEnvironment:
|
|
760
|
+
"""Creates one GRF environment, as `gfootball.env.create_environment` with the same arguments.
|
|
761
|
+
|
|
762
|
+
Args:
|
|
763
|
+
env_name: A shipped scenario such as `11_vs_11_stochastic`, a GRF scenario file or a bundle.
|
|
764
|
+
stacked: Whether the observation stacks the last 4, as GRF's `stacked`.
|
|
765
|
+
representation: `extracted` for the SMM, `simple115`, `simple115v2` or `raw`.
|
|
766
|
+
rewards: `scoring`, or `scoring,checkpoints`.
|
|
767
|
+
write_goal_dumps: GRF's dumps of the frames before each goal, through `cuju.dumps`.
|
|
768
|
+
write_full_episode_dumps: GRF's dumps of every episode, through `cuju.dumps`.
|
|
769
|
+
render: Must stay `False`, since cuju renders nothing.
|
|
770
|
+
write_video: Must stay `False`, for the same reason.
|
|
771
|
+
dump_frequency: Keep the dump options for the first reset and then for one reset in
|
|
772
|
+
every `dump_frequency`, as GRF's option.
|
|
773
|
+
logdir: The directory of the dumps.
|
|
774
|
+
extra_players: Further players, each a definition such as GRF's
|
|
775
|
+
`'agent:left_players=1'`.
|
|
776
|
+
number_of_left_players_agent_controls: The left players that the agent controls.
|
|
777
|
+
number_of_right_players_agent_controls: The right players that the agent controls.
|
|
778
|
+
channel_dimensions: The width and the height of the SMM.
|
|
779
|
+
other_config_options: GRF's other `Config` values, which are `action_set`,
|
|
780
|
+
`game_engine_random_seed`, `reverse_team_processing`, `episode_number`,
|
|
781
|
+
`physics_steps_per_frame`, `players`, `level`, the dump settings, and the rendering
|
|
782
|
+
settings, which change nothing here.
|
|
783
|
+
device: Where the batch of one environment runs, `cpu` or `cuda`. Not a GRF argument.
|
|
784
|
+
threads: The CPU threads of that batch. Not a GRF argument.
|
|
785
|
+
api: `gym` for GRF's interface, where `reset` returns the observation and `step` four
|
|
786
|
+
values, or `gymnasium` for gymnasium's, where `reset` returns two and `step` five. Not
|
|
787
|
+
a GRF argument.
|
|
788
|
+
|
|
789
|
+
Returns:
|
|
790
|
+
The environment.
|
|
791
|
+
|
|
792
|
+
Raises:
|
|
793
|
+
ValueError: If `api` names neither interface, `env_name` is empty, `render` or
|
|
794
|
+
`write_video` is set, a player definition names a player that cuju lacks or a second
|
|
795
|
+
agent, or another argument is refused by `BatchEnvironment`, which raises `KeyError`
|
|
796
|
+
for an unknown representation or action set.
|
|
797
|
+
NotImplementedError: If a dump option is set and `cuju.dumps` is missing.
|
|
798
|
+
"""
|
|
799
|
+
if api not in _APIS:
|
|
800
|
+
raise ValueError(f'expected api {" or ".join(map(repr, _APIS))}, found {api!r}')
|
|
801
|
+
if not env_name:
|
|
802
|
+
raise ValueError('expected the name of a scenario in env_name')
|
|
803
|
+
if render or write_video:
|
|
804
|
+
raise ValueError('cuju renders nothing, so it supports neither render nor write_video')
|
|
805
|
+
if representation in ('pixels', 'pixels_gray'):
|
|
806
|
+
# GRF: these need its render switch, which `cuju.gfootball` plays as GRF does.
|
|
807
|
+
raise ChoiceError(
|
|
808
|
+
f"cuju.env renders nothing, so it has no representation {representation!r}; GRF's "
|
|
809
|
+
'pixels come from cuju.gfootball, and a BatchEnvironment draws them for its episodes'
|
|
810
|
+
)
|
|
811
|
+
options = dict(other_config_options or {})
|
|
812
|
+
unknown = sorted(set(options) - _OPTIONS)
|
|
813
|
+
if unknown:
|
|
814
|
+
warnings.warn(
|
|
815
|
+
f'other_config_options holds {unknown}, which GRF keeps and ignores, as cuju does',
|
|
816
|
+
stacklevel=2,
|
|
817
|
+
)
|
|
818
|
+
left_agents = number_of_left_players_agent_controls
|
|
819
|
+
right_agents = number_of_right_players_agent_controls
|
|
820
|
+
players = [f'agent:left_players={left_agents},right_players={right_agents}']
|
|
821
|
+
facts = _scenario_facts(env_name)
|
|
822
|
+
control = facts[1]
|
|
823
|
+
# GRF: a scenario that sets `control_all_players` gives the agent every controllable player
|
|
824
|
+
# of its sides, and `MultiAgentToSingleAgent` lets the policy play one a side.
|
|
825
|
+
single_players = control is not None and left_agents in (0, 1) and right_agents in (0, 1)
|
|
826
|
+
if single_players:
|
|
827
|
+
if 'players' in options or not left_agents + right_agents:
|
|
828
|
+
raise ValueError(
|
|
829
|
+
'expected one player on one or both sides, and the players of extra_players '
|
|
830
|
+
'rather than of other_config_options, for a scenario with control_all_players'
|
|
831
|
+
)
|
|
832
|
+
players = [
|
|
833
|
+
f'agent:left_players={control[0] if left_agents else 0},'
|
|
834
|
+
f'right_players={control[1] if right_agents else 0}'
|
|
835
|
+
]
|
|
836
|
+
if extra_players is not None:
|
|
837
|
+
players.extend(extra_players)
|
|
838
|
+
# GRF: the values of the environment's `Config`, which `other_config_options` updates.
|
|
839
|
+
values = {
|
|
840
|
+
'dump_full_episodes': write_full_episode_dumps,
|
|
841
|
+
'dump_scores': write_goal_dumps,
|
|
842
|
+
'players': players,
|
|
843
|
+
'level': env_name,
|
|
844
|
+
'tracesdir': logdir,
|
|
845
|
+
'write_video': write_video,
|
|
846
|
+
**options,
|
|
847
|
+
}
|
|
848
|
+
batch, settings = _create(
|
|
849
|
+
values,
|
|
850
|
+
env_name,
|
|
851
|
+
facts,
|
|
852
|
+
config=None,
|
|
853
|
+
representation=representation,
|
|
854
|
+
rewards=rewards,
|
|
855
|
+
stacked=stacked,
|
|
856
|
+
channel_dimensions=channel_dimensions,
|
|
857
|
+
dump_frequency=dump_frequency,
|
|
858
|
+
sides=(left_agents, right_agents) if single_players else None,
|
|
859
|
+
single=left_agents + right_agents == 1,
|
|
860
|
+
device=device,
|
|
861
|
+
threads=threads,
|
|
862
|
+
api=api,
|
|
863
|
+
)
|
|
864
|
+
legacy = _legacy_gym() if api == 'gym' else None
|
|
865
|
+
if legacy is None:
|
|
866
|
+
return FootballEnvironment(batch, settings)
|
|
867
|
+
return _legacy_class(legacy)(batch, settings)
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
def _legacy_gym():
|
|
871
|
+
"""Returns gym where a gym before 0.26 is installed beside gymnasium, else `None`.
|
|
872
|
+
|
|
873
|
+
GRF's gym interface is that of gym 0.21, so code written for GRF checks gym's classes.
|
|
874
|
+
"""
|
|
875
|
+
if _gym.__name__ == 'gym' or not _gym_before_026():
|
|
876
|
+
return None
|
|
877
|
+
try:
|
|
878
|
+
return importlib.import_module('gym')
|
|
879
|
+
except Exception:
|
|
880
|
+
return None
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
_LEGACY_CLASSES: dict[str, type] = {}
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def _legacy_class(gym) -> type:
|
|
887
|
+
"""Returns `FootballEnvironment` that is also gym's `Env`, for GRF's gym interface."""
|
|
888
|
+
cls = _LEGACY_CLASSES.get(gym.__version__)
|
|
889
|
+
if cls is None:
|
|
890
|
+
cls = type('FootballEnvironment', (FootballEnvironment, gym.Env), {})
|
|
891
|
+
cls.__module__ = __name__
|
|
892
|
+
cls.__doc__ = FootballEnvironment.__doc__
|
|
893
|
+
_LEGACY_CLASSES[gym.__version__] = cls
|
|
894
|
+
return cls
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def _create(
|
|
898
|
+
values,
|
|
899
|
+
env_name,
|
|
900
|
+
facts,
|
|
901
|
+
*,
|
|
902
|
+
config,
|
|
903
|
+
representation,
|
|
904
|
+
rewards,
|
|
905
|
+
stacked,
|
|
906
|
+
channel_dimensions,
|
|
907
|
+
dump_frequency,
|
|
908
|
+
sides,
|
|
909
|
+
single,
|
|
910
|
+
device,
|
|
911
|
+
threads,
|
|
912
|
+
api,
|
|
913
|
+
):
|
|
914
|
+
"""Returns the batch and the settings of the environment of GRF's configuration values.
|
|
915
|
+
|
|
916
|
+
Args:
|
|
917
|
+
values: The values of GRF's `Config` before its scenario numbers the first episode, with
|
|
918
|
+
the episode number of the options.
|
|
919
|
+
env_name, facts: A scenario and its `_scenario_facts`, which spare reading them again when
|
|
920
|
+
the level is that scenario.
|
|
921
|
+
config: The `Config` that GRF's `FootballEnv` takes, which drew the seed of the first
|
|
922
|
+
episode, or `None` to build the configuration as `create_environment` does.
|
|
923
|
+
sides: The policy's sides for `MultiAgentToSingleAgent`, or `None` without it.
|
|
924
|
+
single: Whether the agent controls one player, as GRF's single-agent wrappers check.
|
|
925
|
+
representation, rewards, stacked, channel_dimensions, dump_frequency, device, threads, api:
|
|
926
|
+
As `create_environment`.
|
|
927
|
+
"""
|
|
928
|
+
single_players = sides is not None
|
|
929
|
+
players = list(values['players'])
|
|
930
|
+
level = values['level']
|
|
931
|
+
action_set = values.get('action_set', 'default')
|
|
932
|
+
if action_set not in _ACTION_COUNTS:
|
|
933
|
+
raise KeyError(f'expected the action set {", ".join(map(repr, _ACTION_COUNTS))}')
|
|
934
|
+
# GRF: each player controls the next positions of each side, in the order of the list.
|
|
935
|
+
parsed, left, right, slots, scripted = [], 0, 0, None, []
|
|
936
|
+
for definition in players:
|
|
937
|
+
name, player_left, player_right, parameters = _parse_player(definition)
|
|
938
|
+
# GRF: another name is a module of players, which loads with the players, below.
|
|
939
|
+
if name not in _PLAYERS and not _PLAYER_MODULE.fullmatch(name):
|
|
940
|
+
raise ValueError(
|
|
941
|
+
f'expected the players {", ".join(_PLAYERS)}, or a module that defines the player, '
|
|
942
|
+
f'in {definition!r}'
|
|
943
|
+
)
|
|
944
|
+
if name == 'bot' and player_left + player_right != 1:
|
|
945
|
+
raise ValueError(f"GRF's bot controls one player, found {definition!r}")
|
|
946
|
+
# GRF: the bot asserts the `full` action set.
|
|
947
|
+
if name == 'bot' and action_set != 'full':
|
|
948
|
+
raise ValueError("GRF's bot needs other_config_options={'action_set': 'full'}")
|
|
949
|
+
parsed.append((name, left, player_left, right, player_right, parameters))
|
|
950
|
+
left += player_left
|
|
951
|
+
right += player_right
|
|
952
|
+
for name, left_start, player_left, right_start, player_right, _ in parsed:
|
|
953
|
+
positions = list(range(left_start, left_start + player_left)) + [
|
|
954
|
+
left + position for position in range(right_start, right_start + player_right)
|
|
955
|
+
]
|
|
956
|
+
if name == 'agent':
|
|
957
|
+
if slots is not None:
|
|
958
|
+
raise ValueError("expected one 'agent' player, as GRF allows")
|
|
959
|
+
slots = positions
|
|
960
|
+
elif positions or name not in _PLAYERS:
|
|
961
|
+
scripted.append((name, positions))
|
|
962
|
+
# GRF: `FootballEnv` plays without an agent too, stepping with `step([])`.
|
|
963
|
+
agent = slots is not None
|
|
964
|
+
slots = slots or []
|
|
965
|
+
if config is None:
|
|
966
|
+
# GRF: `create_environment` builds a configuration that reads the scenario, which draws a
|
|
967
|
+
# seed whatever the options say.
|
|
968
|
+
random.randint(0, _SEED_LIMIT)
|
|
969
|
+
fixed_seed = values.get('game_engine_random_seed')
|
|
970
|
+
if fixed_seed is not None and not 0 <= fixed_seed < 2**32:
|
|
971
|
+
raise ValueError(
|
|
972
|
+
f'expected a game_engine_random_seed from 0 to 2**32 - 1, found {fixed_seed}'
|
|
973
|
+
)
|
|
974
|
+
reverse = values.get('reverse_team_processing')
|
|
975
|
+
episode_number = values.get('episode_number', 0)
|
|
976
|
+
deterministic = (facts if level == env_name else _scenario_facts(level))[0]
|
|
977
|
+
# GRF: without a fixed seed, the configuration of the environment draws the seed whose parity
|
|
978
|
+
# sets the team order, and the reset inside the creation of the core draws the seed of the
|
|
979
|
+
# episode that a step before the first `reset` plays. `FootballEnv` takes a configuration
|
|
980
|
+
# that drew the first already.
|
|
981
|
+
creation = None
|
|
982
|
+
if fixed_seed is None:
|
|
983
|
+
first = (
|
|
984
|
+
random.randint(0, _SEED_LIMIT) if config is None else config['game_engine_random_seed']
|
|
985
|
+
)
|
|
986
|
+
creation = [first]
|
|
987
|
+
python_players = None
|
|
988
|
+
if any(name not in _PLAYERS for name, _ in scripted):
|
|
989
|
+
from ._python_players import PythonPlayers
|
|
990
|
+
|
|
991
|
+
# GRF: `FootballEnv` builds its players between the configuration and the core.
|
|
992
|
+
config = _grf_config_values(values, config, deterministic, fixed_seed, creation)
|
|
993
|
+
python_players = PythonPlayers(players, parsed, scripted, config, action_set)
|
|
994
|
+
scripted = python_players.scripted
|
|
995
|
+
if creation is not None:
|
|
996
|
+
creation.append(random.randint(0, _SEED_LIMIT))
|
|
997
|
+
numpy_legacy = int(np.__version__.split('.')[0]) < 2
|
|
998
|
+
batch = BatchEnvironment(
|
|
999
|
+
level,
|
|
1000
|
+
environment_count=1,
|
|
1001
|
+
representation=representation,
|
|
1002
|
+
rewards=rewards,
|
|
1003
|
+
# `v2` plays `default` with `builtin_ai` for the agents that the policy does not move.
|
|
1004
|
+
action_set='v2' if single_players and action_set == 'default' else action_set,
|
|
1005
|
+
numpy_legacy=numpy_legacy,
|
|
1006
|
+
auto_reset=False,
|
|
1007
|
+
with_raw=True,
|
|
1008
|
+
device=device,
|
|
1009
|
+
threads=threads,
|
|
1010
|
+
physics_steps_per_frame=values.get('physics_steps_per_frame', 10),
|
|
1011
|
+
channel_dimensions=tuple(channel_dimensions),
|
|
1012
|
+
stacked=stacked and not single_players,
|
|
1013
|
+
game_engine_random_seed=fixed_seed,
|
|
1014
|
+
agent_counts=[(left, right)],
|
|
1015
|
+
# Only the parity of the episode number reaches a bundle. The creation plays the episode
|
|
1016
|
+
# before the first, and one more reset sets the team order where only the bundle knows
|
|
1017
|
+
# whether the scenario is deterministic.
|
|
1018
|
+
episode_number=(episode_number + (0 if creation and deterministic is None else 1)) % 2,
|
|
1019
|
+
)
|
|
1020
|
+
try:
|
|
1021
|
+
if creation is None:
|
|
1022
|
+
batch.reset(reverse=None if reverse is None else int(bool(reverse)))
|
|
1023
|
+
elif deterministic is None:
|
|
1024
|
+
# The library sets the team order from the seed as GRF does, deterministic or not.
|
|
1025
|
+
batch.reset(seeds=creation[0], reverse=None if reverse is None else int(bool(reverse)))
|
|
1026
|
+
batch.reset(seeds=creation[1])
|
|
1027
|
+
else:
|
|
1028
|
+
if reverse is None:
|
|
1029
|
+
reverse = 0 if deterministic else creation[0] % 2
|
|
1030
|
+
batch.reset(seeds=creation[1], reverse=int(bool(reverse)))
|
|
1031
|
+
dumps = None
|
|
1032
|
+
dump_full = values.get('dump_full_episodes', False)
|
|
1033
|
+
dump_goals = values.get('dump_scores', False)
|
|
1034
|
+
if values.get('write_video', False):
|
|
1035
|
+
raise ValueError('cuju renders nothing, so it writes no video')
|
|
1036
|
+
if dump_full or dump_goals:
|
|
1037
|
+
dumps = _Dumps(
|
|
1038
|
+
batch, dump_full, dump_goals, dump_frequency, values.get('tracesdir', '')
|
|
1039
|
+
)
|
|
1040
|
+
wrapper = None
|
|
1041
|
+
if single_players:
|
|
1042
|
+
# GRF: the wrapper covers the agent's players, and the players of `extra_players`
|
|
1043
|
+
# play their own actions.
|
|
1044
|
+
wrapper = MultiAgentToSingleAgent(
|
|
1045
|
+
batch, *sides, action_set=action_set, stacked=stacked, _slots=slots
|
|
1046
|
+
)
|
|
1047
|
+
config = _grf_config(values, config, deterministic, fixed_seed, creation)
|
|
1048
|
+
except BaseException:
|
|
1049
|
+
batch.close()
|
|
1050
|
+
raise
|
|
1051
|
+
settings = {
|
|
1052
|
+
'config': config,
|
|
1053
|
+
'agent': agent,
|
|
1054
|
+
'slots': slots,
|
|
1055
|
+
'single': single,
|
|
1056
|
+
'wrapper': wrapper,
|
|
1057
|
+
'scripted': scripted,
|
|
1058
|
+
'representation': representation,
|
|
1059
|
+
'fixed_seed': fixed_seed,
|
|
1060
|
+
'action_set': action_set,
|
|
1061
|
+
'action_count': _ACTION_COUNTS[action_set],
|
|
1062
|
+
'channel_dimensions': tuple(channel_dimensions),
|
|
1063
|
+
'stacked': stacked,
|
|
1064
|
+
'dumps': dumps,
|
|
1065
|
+
'api': api,
|
|
1066
|
+
'python_players': python_players,
|
|
1067
|
+
'level': level,
|
|
1068
|
+
}
|
|
1069
|
+
return batch, settings
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def _grf_config(values, config, deterministic, fixed_seed, creation):
|
|
1073
|
+
"""Returns GRF's `Config` of an environment as its creation leaves it.
|
|
1074
|
+
|
|
1075
|
+
Args:
|
|
1076
|
+
values, config: As `_create`.
|
|
1077
|
+
deterministic: Whether the scenario is deterministic, `None` where only its bundle knows.
|
|
1078
|
+
fixed_seed: The seed of the options, or `None`.
|
|
1079
|
+
creation: The seeds that the creation drew, or `None` with a fixed seed.
|
|
1080
|
+
"""
|
|
1081
|
+
config = _grf_config_values(values, config, deterministic, fixed_seed, creation)
|
|
1082
|
+
# GRF: the creation of the core builds the scenario again with the same number and a new seed.
|
|
1083
|
+
config._new_scenario(0, None if creation is None else creation[1])
|
|
1084
|
+
return config
|
|
1085
|
+
|
|
1086
|
+
|
|
1087
|
+
def _grf_config_values(values, config, deterministic, fixed_seed, creation):
|
|
1088
|
+
"""Returns GRF's `Config` of an environment before the core's first reset, for `_grf_config`."""
|
|
1089
|
+
from . import _grf_config as grf_config
|
|
1090
|
+
|
|
1091
|
+
if config is None:
|
|
1092
|
+
values = dict(values)
|
|
1093
|
+
# GRF: the `Config` numbers the scenario that it builds, and a scenario that is not
|
|
1094
|
+
# deterministic takes the team order from the parity of its seed unless the values hold one.
|
|
1095
|
+
values['episode_number'] = values.get('episode_number', 0) + 1
|
|
1096
|
+
if deterministic is False and 'reverse_team_processing' not in values:
|
|
1097
|
+
seed = fixed_seed if creation is None else creation[0]
|
|
1098
|
+
values['reverse_team_processing'] = bool(seed % 2)
|
|
1099
|
+
config = grf_config._without_draw(values)
|
|
1100
|
+
if creation is not None:
|
|
1101
|
+
# GRF: the seed that the configuration drew is a value of its scenario.
|
|
1102
|
+
config.set_scenario_value('game_engine_random_seed', creation[0])
|
|
1103
|
+
return config
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
# GRF: the ids of `gfootball/__init__.py`, by the suffix of each representation.
|
|
1107
|
+
_GYM_REPRESENTATIONS = (
|
|
1108
|
+
('SMM', 'extracted'),
|
|
1109
|
+
('Pixels', 'pixels'),
|
|
1110
|
+
('simple115', 'simple115'),
|
|
1111
|
+
('simple115v2', 'simple115v2'),
|
|
1112
|
+
)
|
|
1113
|
+
_ENTRY_POINT = 'cuju.env:create_environment'
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
def _gym_version() -> tuple[int, int] | None:
|
|
1117
|
+
"""Returns the major and minor version of the installed gym, or `None` without one."""
|
|
1118
|
+
try:
|
|
1119
|
+
version = importlib.metadata.version('gym')
|
|
1120
|
+
except importlib.metadata.PackageNotFoundError:
|
|
1121
|
+
return None
|
|
1122
|
+
match = re.match(r'(\d+)\.(\d+)', version)
|
|
1123
|
+
return (int(match[1]), int(match[2])) if match else None
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
def _gym_before_026() -> bool:
|
|
1127
|
+
"""Returns whether the installed gym precedes 0.26, which took gymnasium's interface."""
|
|
1128
|
+
version = _gym_version()
|
|
1129
|
+
return version is not None and version < (0, 26)
|
|
1130
|
+
|
|
1131
|
+
|
|
1132
|
+
def register_environments() -> None:
|
|
1133
|
+
"""Registers GRF's ids `GFootball-<scenario>-<representation>-v0` for the shipped scenarios.
|
|
1134
|
+
|
|
1135
|
+
It registers them with gymnasium, where installed, with gymnasium's interface. `import cuju`
|
|
1136
|
+
imports no gymnasium, and registers the ids as soon as it is imported. gym gets GRF's own
|
|
1137
|
+
environments under the same ids from `import cuju.gfootball`, as importing `gfootball`
|
|
1138
|
+
registers them in GRF. The `Pixels` ids are registered as in GRF, and making one raises, since
|
|
1139
|
+
cuju renders nothing.
|
|
1140
|
+
"""
|
|
1141
|
+
if importlib.util.find_spec('gymnasium') is not None:
|
|
1142
|
+
_register_with('gymnasium')
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
def _register_with(module: str) -> None:
|
|
1146
|
+
"""Registers GRF's ids with `gymnasium`, as `register_environments` does."""
|
|
1147
|
+
if module != 'gymnasium':
|
|
1148
|
+
return
|
|
1149
|
+
registration = importlib.import_module(f'{module}.envs.registration')
|
|
1150
|
+
registry = registration.registry
|
|
1151
|
+
specs = registry if isinstance(registry, dict) else registry.env_specs
|
|
1152
|
+
for scenario in bundled_scenarios():
|
|
1153
|
+
for suffix, representation in _GYM_REPRESENTATIONS:
|
|
1154
|
+
name = f'GFootball-{scenario}-{suffix}-v0'
|
|
1155
|
+
spec = specs[name] if name in specs else None
|
|
1156
|
+
if spec is not None and spec.entry_point == _ENTRY_POINT:
|
|
1157
|
+
continue
|
|
1158
|
+
registration.register(
|
|
1159
|
+
id=name,
|
|
1160
|
+
entry_point=_ENTRY_POINT,
|
|
1161
|
+
kwargs={'env_name': scenario, 'representation': representation, 'api': module},
|
|
1162
|
+
)
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
# A gymnasium that this module's own imports brought in gets the ids here, since `cuju` cannot
|
|
1166
|
+
# take them from a module that is still importing.
|
|
1167
|
+
if sys.modules.get('gymnasium') is not None:
|
|
1168
|
+
_register_with('gymnasium')
|