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/kaggle.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
# Copyright 2026 The cuju Authors
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""Kaggle's GRF competition protocol, with `players_raw` from a batch and Kaggle agents in a batch.
|
|
5
|
+
|
|
6
|
+
`KaggleAgent` runs a Kaggle agent function, such as a `submission.py` agent or a public rule-based
|
|
7
|
+
bot, as one agent of every environment of a batch, and `evaluate` plays whole matches with it.
|
|
8
|
+
`AgentRunner` calls such a function as Kaggle does and checks its answer, for a program that builds
|
|
9
|
+
the observations itself. The guide is in the repository's `docs/recipes.md`, under Train for the
|
|
10
|
+
Kaggle competition.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import inspect
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import torch
|
|
20
|
+
|
|
21
|
+
from . import BatchEnvironment
|
|
22
|
+
from .raw import grf_observation, team_sizes
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
'AgentRunner',
|
|
26
|
+
'KaggleAgent',
|
|
27
|
+
'accepts_configuration',
|
|
28
|
+
'action_index',
|
|
29
|
+
'action_indices',
|
|
30
|
+
'evaluate',
|
|
31
|
+
'observation',
|
|
32
|
+
'players_raw',
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
# Kaggle: the time an agent may overrun across a match, in seconds, which every observation holds.
|
|
36
|
+
_OVERAGE_TIME = 60
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _Struct(dict):
|
|
40
|
+
"""A dictionary whose keys are also attributes, as Kaggle's `Struct` that agents receive."""
|
|
41
|
+
|
|
42
|
+
def __getattr__(self, name):
|
|
43
|
+
try:
|
|
44
|
+
return self[name]
|
|
45
|
+
except KeyError:
|
|
46
|
+
raise AttributeError(name) from None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _lists(entry):
|
|
50
|
+
"""Returns a GRF raw dictionary with its numpy arrays as lists, as Kaggle's JSON makes them."""
|
|
51
|
+
return {
|
|
52
|
+
name: value.tolist() if isinstance(value, np.ndarray) else value
|
|
53
|
+
for name, value in entry.items()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def players_raw(
|
|
58
|
+
batch: Any, environment: int, agent: int, final: bool = False
|
|
59
|
+
) -> list[dict[str, Any]]:
|
|
60
|
+
"""Returns `obs['players_raw']` of a Kaggle agent that plays an agent of a batch.
|
|
61
|
+
|
|
62
|
+
The list holds one dictionary, GRF's raw observation of the agent's player, with lists for
|
|
63
|
+
GRF's numpy arrays, Python floats for its `float64` values, as Kaggle's agents receive it after
|
|
64
|
+
JSON. A right agent sees the match turned, with its own team as `left_team`, as in Kaggle.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
batch: A batch with the raw representation or `with_raw=True`.
|
|
68
|
+
environment: The index of the environment.
|
|
69
|
+
agent: The index of the agent.
|
|
70
|
+
final: Whether to read the step that ended the last episode, `final_raw()`.
|
|
71
|
+
"""
|
|
72
|
+
raw = batch.final_raw() if final else batch.raw()
|
|
73
|
+
return [
|
|
74
|
+
_lists(grf_observation(raw, environment, agent, *team_sizes(batch, environment, agent)))
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def observation(
|
|
79
|
+
batch: Any,
|
|
80
|
+
environment: int,
|
|
81
|
+
agent: int | list[int],
|
|
82
|
+
step: int = 0,
|
|
83
|
+
final: bool = False,
|
|
84
|
+
raw: dict[str, Any] | None = None,
|
|
85
|
+
) -> _Struct:
|
|
86
|
+
"""Returns a Kaggle agent's observation, a dictionary whose keys are also attributes.
|
|
87
|
+
|
|
88
|
+
It holds `players_raw`, `controlled_players`, and Kaggle's `step` and `remainingOverageTime`.
|
|
89
|
+
A list of agents gives Kaggle's multi-agent form, one entry of `players_raw` per agent in the
|
|
90
|
+
order of the list, and `controlled_players` their count.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
batch: A batch with the raw representation or `with_raw=True`.
|
|
94
|
+
environment: The index of the environment.
|
|
95
|
+
agent: The index of the agent, or a list of the agents that one function plays.
|
|
96
|
+
step: The steps of the episode so far, which Kaggle counts from 0.
|
|
97
|
+
final: Whether to read the step that ended the last episode.
|
|
98
|
+
raw: The raw arrays to read in place of the batch's, such as one copy of `batch.raw()` on
|
|
99
|
+
the host that the observations of several agents share. `final` then has no effect.
|
|
100
|
+
"""
|
|
101
|
+
several = isinstance(agent, (list, tuple))
|
|
102
|
+
agents = [int(index) for index in agent] if several else [int(agent)]
|
|
103
|
+
if raw is None:
|
|
104
|
+
raw = batch.final_raw() if final else batch.raw()
|
|
105
|
+
return _Struct(
|
|
106
|
+
players_raw=[
|
|
107
|
+
_lists(grf_observation(raw, environment, index, *team_sizes(batch, environment, index)))
|
|
108
|
+
for index in agents
|
|
109
|
+
],
|
|
110
|
+
controlled_players=len(agents),
|
|
111
|
+
step=step,
|
|
112
|
+
remainingOverageTime=_OVERAGE_TIME,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def accepts_configuration(function: Any) -> bool:
|
|
117
|
+
"""Returns whether an agent function takes a configuration, as Kaggle decides it.
|
|
118
|
+
|
|
119
|
+
Kaggle passes the configuration as a second argument to a function with at least two
|
|
120
|
+
positional parameters, or with `*args`, and calls any other function with the observation
|
|
121
|
+
alone.
|
|
122
|
+
"""
|
|
123
|
+
try:
|
|
124
|
+
parameters = inspect.signature(function).parameters.values()
|
|
125
|
+
except (TypeError, ValueError):
|
|
126
|
+
return False
|
|
127
|
+
positional = [
|
|
128
|
+
parameter
|
|
129
|
+
for parameter in parameters
|
|
130
|
+
if parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD)
|
|
131
|
+
]
|
|
132
|
+
return len(positional) >= 2 or any(
|
|
133
|
+
parameter.kind == parameter.VAR_POSITIONAL for parameter in parameters
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def action_index(value: Any, count: int) -> int:
|
|
138
|
+
"""Returns the action index of a Kaggle agent's answer for one controlled player.
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
value: The answer, `[action]` as Kaggle's agents return it, an integer, a one-element
|
|
142
|
+
array or an enum whose value is the index, such as `Action` of Kaggle's helpers.
|
|
143
|
+
count: The actions of the action set, and an index from `-count` to `count - 1` counts
|
|
144
|
+
from the end for a negative one, as in GRF.
|
|
145
|
+
|
|
146
|
+
Raises:
|
|
147
|
+
ValueError: If a list holds other than one action.
|
|
148
|
+
TypeError: If the action is not an integer.
|
|
149
|
+
IndexError: If the action lies outside the action set.
|
|
150
|
+
"""
|
|
151
|
+
if isinstance(value, (list, tuple)):
|
|
152
|
+
if len(value) != 1:
|
|
153
|
+
raise ValueError(f'expected one action for the one controlled player, found {value!r}')
|
|
154
|
+
value = value[0]
|
|
155
|
+
return _index(value, count)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def action_indices(value: Any, count: int, players: int) -> list[int]:
|
|
159
|
+
"""Returns the action indices of an answer for `players` controlled players, one each.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
value: The answer, a list, tuple or array with one action per controlled player, each in
|
|
163
|
+
a form that `action_index` takes.
|
|
164
|
+
count: The actions of the action set.
|
|
165
|
+
players: The controlled players.
|
|
166
|
+
|
|
167
|
+
Raises:
|
|
168
|
+
ValueError: If the answer holds other than one action per player.
|
|
169
|
+
TypeError, IndexError: As `action_index` raises them for an action.
|
|
170
|
+
"""
|
|
171
|
+
if isinstance(value, np.ndarray):
|
|
172
|
+
value = value.reshape(-1).tolist()
|
|
173
|
+
if not isinstance(value, (list, tuple)) or len(value) != players:
|
|
174
|
+
raise ValueError(
|
|
175
|
+
f'expected one action for each of the {players} controlled players, found {value!r}'
|
|
176
|
+
)
|
|
177
|
+
return [_index(item, count) for item in value]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _index(value, count):
|
|
181
|
+
"""Returns one action index, from an integer, a one-element array or an enum."""
|
|
182
|
+
if isinstance(value, np.ndarray) and value.size == 1:
|
|
183
|
+
value = value.item()
|
|
184
|
+
# Kaggle: the `Action` enum of the football helpers holds the index as its value.
|
|
185
|
+
if not isinstance(value, (int, np.integer)) and isinstance(getattr(value, 'value', None), int):
|
|
186
|
+
value = value.value
|
|
187
|
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
|
|
188
|
+
raise TypeError(f'expected an integer action from the agent, found {value!r}')
|
|
189
|
+
# GRF: an action indexes a Python list, so it may count from the end.
|
|
190
|
+
if not -count <= int(value) < count:
|
|
191
|
+
raise IndexError(f'expected an action from {-count} to {count - 1}, found {value}')
|
|
192
|
+
return int(value)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# The names before 0.2.1, which the renderer of cuju 0.2.0 imports.
|
|
196
|
+
_accepts_configuration = accepts_configuration
|
|
197
|
+
_action = action_index
|
|
198
|
+
_actions = action_indices
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class AgentRunner:
|
|
202
|
+
"""Calls a Kaggle agent function as Kaggle does, and checks its answer against an action set.
|
|
203
|
+
|
|
204
|
+
The runner suits a program that builds the observations itself, such as one that plays a
|
|
205
|
+
match step by step, and `KaggleAgent` covers the agents of a batch.
|
|
206
|
+
|
|
207
|
+
Attributes:
|
|
208
|
+
function: The agent function.
|
|
209
|
+
configuration: What a function that takes a configuration receives second.
|
|
210
|
+
accepts_configuration: Whether the function takes a configuration.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
def __init__(self, function: Any, configuration: dict[str, Any] | None = None) -> None:
|
|
214
|
+
"""Binds a Kaggle agent function.
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
function: `agent(obs)` or `agent(obs, configuration)`, as `accepts_configuration`
|
|
218
|
+
tells them apart.
|
|
219
|
+
configuration: The configuration of Kaggle's environment that the function reads, as
|
|
220
|
+
a dictionary, and `None` passes an empty one.
|
|
221
|
+
"""
|
|
222
|
+
self.function = function
|
|
223
|
+
self.configuration = _Struct(configuration or {})
|
|
224
|
+
self.accepts_configuration = accepts_configuration(function)
|
|
225
|
+
|
|
226
|
+
def __call__(self, obs: Any) -> Any:
|
|
227
|
+
"""Calls the function with an observation, and the configuration if it takes one, and
|
|
228
|
+
returns its answer as it is."""
|
|
229
|
+
if self.accepts_configuration:
|
|
230
|
+
return self.function(obs, self.configuration)
|
|
231
|
+
return self.function(obs)
|
|
232
|
+
|
|
233
|
+
def act(self, obs: Any, count: int) -> list[int]:
|
|
234
|
+
"""Calls the function and returns one action index per controlled player.
|
|
235
|
+
|
|
236
|
+
One controlled player may answer in Kaggle's single form, as `action_index` takes it, and
|
|
237
|
+
several answer with one action each, in the order of `obs['players_raw']`.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
obs: The observation, as `observation` returns it.
|
|
241
|
+
count: The actions of the action set.
|
|
242
|
+
|
|
243
|
+
Raises:
|
|
244
|
+
TypeError, ValueError, IndexError: As `action_index` and `action_indices` raise them,
|
|
245
|
+
and whatever the function raises.
|
|
246
|
+
"""
|
|
247
|
+
players = len(obs['players_raw'])
|
|
248
|
+
answer = self(obs)
|
|
249
|
+
if players == 1:
|
|
250
|
+
return [action_index(answer, count)]
|
|
251
|
+
return action_indices(answer, count, players)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
class KaggleAgent:
|
|
255
|
+
"""Runs a Kaggle agent function as one agent, or several, of every environment of a batch.
|
|
256
|
+
|
|
257
|
+
Each call of `act` builds the Kaggle observation of the agent in every environment from the
|
|
258
|
+
batch's current raw observation, calls the function once per environment, and returns the
|
|
259
|
+
actions. It counts Kaggle's `step` per environment from the first observation of each episode.
|
|
260
|
+
|
|
261
|
+
A function that controls several players receives Kaggle's multi-agent form, one raw
|
|
262
|
+
observation per controlled player in `obs['players_raw']`, in the order of `agents`, with
|
|
263
|
+
`controlled_players` their count, and returns one action per player in the same order.
|
|
264
|
+
|
|
265
|
+
Attributes:
|
|
266
|
+
function: The agent function.
|
|
267
|
+
batch: The batch.
|
|
268
|
+
agent: The first agent that the function plays.
|
|
269
|
+
agents: Every agent that the function plays, `[agent]` for one.
|
|
270
|
+
configuration: What a function that takes two arguments receives second.
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
def __init__(
|
|
274
|
+
self,
|
|
275
|
+
function: Any,
|
|
276
|
+
batch: Any,
|
|
277
|
+
agent: int,
|
|
278
|
+
configuration: dict[str, Any] | None = None,
|
|
279
|
+
agents: list[int] | None = None,
|
|
280
|
+
) -> None:
|
|
281
|
+
"""Binds a Kaggle agent function to an agent of a batch.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
function: `agent(obs)` or `agent(obs, configuration)`, which reads
|
|
285
|
+
`obs['players_raw'][0]` and returns `[action]`, an index of the action set.
|
|
286
|
+
batch: A batch with the raw representation or `with_raw=True`.
|
|
287
|
+
agent: The index of the agent, which must exist in every environment.
|
|
288
|
+
configuration: The configuration of Kaggle's environment that the function reads, if
|
|
289
|
+
any, as a dictionary, and `None` passes an empty one.
|
|
290
|
+
agents: The agents of a function that controls several players, in the order of its
|
|
291
|
+
observations and actions, or `None` for `agent` alone. With a list, `act` returns
|
|
292
|
+
one column per agent.
|
|
293
|
+
|
|
294
|
+
Raises:
|
|
295
|
+
ValueError: If the batch has no raw arrays or an agent is missing somewhere.
|
|
296
|
+
"""
|
|
297
|
+
if getattr(batch, '_raw_fields', None) is None:
|
|
298
|
+
raise ValueError('expected a batch with the raw representation or with_raw=True')
|
|
299
|
+
self.agents = [agent] if agents is None else [int(index) for index in agents]
|
|
300
|
+
if not self.agents or len(set(self.agents)) != len(self.agents):
|
|
301
|
+
raise ValueError(f'expected distinct agents, found {agents!r}')
|
|
302
|
+
for index in self.agents:
|
|
303
|
+
if not 0 <= index < batch.agents or not bool(batch.agent_mask[:, index].all()):
|
|
304
|
+
raise ValueError(f'expected an agent of every environment, found {index}')
|
|
305
|
+
self._several = agents is not None
|
|
306
|
+
self.function = function
|
|
307
|
+
self.batch = batch
|
|
308
|
+
self.agent = self.agents[0]
|
|
309
|
+
self.configuration = _Struct(configuration or {})
|
|
310
|
+
self._two_arguments = accepts_configuration(function)
|
|
311
|
+
self._steps = [0] * batch.environment_count
|
|
312
|
+
|
|
313
|
+
def reset(self, mask: Any = None) -> None:
|
|
314
|
+
"""Counts Kaggle's `step` from 0 again, in the environments of `mask` or in all."""
|
|
315
|
+
for environment in range(self.batch.environment_count):
|
|
316
|
+
if mask is None or bool(mask[environment]):
|
|
317
|
+
self._steps[environment] = 0
|
|
318
|
+
|
|
319
|
+
def act(self, done: Any = None, skip: Any = None) -> torch.Tensor:
|
|
320
|
+
"""Returns the agent's actions, `[environment_count]` `int32` indices on the batch's device.
|
|
321
|
+
|
|
322
|
+
A function given a list of `agents` returns `[environment_count, len(agents)]`.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
done: The done flags of the step before, where an automatic reset started a new
|
|
326
|
+
episode, whose `step` counts from 0 again, or `None` if no episode ended.
|
|
327
|
+
skip: Flags of the environments where the function is not called and the action is
|
|
328
|
+
`idle`, such as those whose match is over.
|
|
329
|
+
|
|
330
|
+
Raises:
|
|
331
|
+
TypeError, ValueError, IndexError: If the function's answer is not one action of the
|
|
332
|
+
batch's action set.
|
|
333
|
+
"""
|
|
334
|
+
if done is not None:
|
|
335
|
+
self.reset(torch.as_tensor(done).bool().cpu())
|
|
336
|
+
skip = None if skip is None else torch.as_tensor(skip).bool().cpu()
|
|
337
|
+
# One copy of the raw arrays to the host serves every environment.
|
|
338
|
+
raw = {name: tensor.cpu() for name, tensor in self.batch.raw().items()}
|
|
339
|
+
actions = []
|
|
340
|
+
players = len(self.agents)
|
|
341
|
+
for environment in range(self.batch.environment_count):
|
|
342
|
+
if skip is not None and bool(skip[environment]):
|
|
343
|
+
actions.append([0] * players if self._several else 0)
|
|
344
|
+
continue
|
|
345
|
+
entries = [
|
|
346
|
+
_lists(
|
|
347
|
+
grf_observation(
|
|
348
|
+
raw, environment, agent, *team_sizes(self.batch, environment, agent)
|
|
349
|
+
)
|
|
350
|
+
)
|
|
351
|
+
for agent in self.agents
|
|
352
|
+
]
|
|
353
|
+
obs = _Struct(
|
|
354
|
+
players_raw=entries,
|
|
355
|
+
controlled_players=players,
|
|
356
|
+
step=self._steps[environment],
|
|
357
|
+
remainingOverageTime=_OVERAGE_TIME,
|
|
358
|
+
)
|
|
359
|
+
answer = (
|
|
360
|
+
self.function(obs, self.configuration)
|
|
361
|
+
if self._two_arguments
|
|
362
|
+
else self.function(obs)
|
|
363
|
+
)
|
|
364
|
+
if self._several:
|
|
365
|
+
actions.append(action_indices(answer, self.batch.action_count, players))
|
|
366
|
+
else:
|
|
367
|
+
actions.append(action_index(answer, self.batch.action_count))
|
|
368
|
+
self._steps[environment] += 1
|
|
369
|
+
return torch.tensor(actions, dtype=torch.int32, device=self.batch._torch_device)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def evaluate(
|
|
373
|
+
left: Any,
|
|
374
|
+
right: Any = None,
|
|
375
|
+
episodes: int = 1,
|
|
376
|
+
scenario: str = '11_vs_11_kaggle',
|
|
377
|
+
seed: int = 0,
|
|
378
|
+
device: str = 'cpu',
|
|
379
|
+
threads: int = 0,
|
|
380
|
+
configuration: dict[str, Any] | None = None,
|
|
381
|
+
) -> list[tuple[int, int]]:
|
|
382
|
+
"""Plays matches of Kaggle agents, one per environment, and returns their final scores.
|
|
383
|
+
|
|
384
|
+
Each environment plays its first episode only, as Kaggle plays every match in a newly created
|
|
385
|
+
GRF environment, so with the even form of the scenario and its own team order.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
left: The Kaggle agent function of the left team.
|
|
389
|
+
right: The function of the right team, or `None` for GRF's built-in AI.
|
|
390
|
+
episodes: The number of matches, one per environment.
|
|
391
|
+
scenario: A shipped scenario or a GRF scenario file.
|
|
392
|
+
seed: The seed of the batch, and match `k` is environment `k` of the seed rule.
|
|
393
|
+
|
|
394
|
+
device: `cpu` or `cuda`.
|
|
395
|
+
threads: The CPU threads.
|
|
396
|
+
configuration: What a function that takes two arguments receives second.
|
|
397
|
+
|
|
398
|
+
Returns:
|
|
399
|
+
The goals of the left and of the right team in each match.
|
|
400
|
+
"""
|
|
401
|
+
batch = BatchEnvironment(
|
|
402
|
+
scenario,
|
|
403
|
+
environment_count=episodes,
|
|
404
|
+
representation='raw',
|
|
405
|
+
seed=seed,
|
|
406
|
+
auto_reset=False,
|
|
407
|
+
device=device,
|
|
408
|
+
threads=threads,
|
|
409
|
+
agent_counts=[(1, 0 if right is None else 1)],
|
|
410
|
+
)
|
|
411
|
+
try:
|
|
412
|
+
players = [KaggleAgent(left, batch, 0, configuration)]
|
|
413
|
+
if right is not None:
|
|
414
|
+
players.append(KaggleAgent(right, batch, 1, configuration))
|
|
415
|
+
batch.reset()
|
|
416
|
+
finished = torch.zeros(episodes, dtype=torch.bool)
|
|
417
|
+
while not bool(finished.all()):
|
|
418
|
+
actions = torch.stack([player.act(skip=finished) for player in players], 1)
|
|
419
|
+
_, _, done, _ = batch.step(actions)
|
|
420
|
+
finished |= done.bool().cpu()
|
|
421
|
+
# The left agent sees its own goals first.
|
|
422
|
+
scores = batch.raw()['score'][:, 0].cpu().tolist()
|
|
423
|
+
finally:
|
|
424
|
+
batch.close()
|
|
425
|
+
return [(int(own), int(other)) for own, other in scores]
|