File size: 8,336 Bytes
f7e2ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
688c130
 
f7e2ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""Core KantBench environment implementing the OpenEnv Environment interface."""
from __future__ import annotations

import uuid
from typing import Any, Callable, Optional

from openenv.core.env_server.interfaces import Environment
from env.models import GameAction, GameObservation, GameState, RoundResult
from common.games import GameConfig, get_game, GAMES
from common.strategies import get_strategy, STRATEGIES, OpponentStrategy
from constant_definitions.game_constants import DEFAULT_NUM_ROUNDS

_ONE = int(bool(True))
_ZERO_F = float()


class KantEnvironment(Environment[GameObservation, GameAction, GameState]):
    """Game-theory environment hosting multiple classic games.

    The agent plays against a built-in opponent strategy or another agent
    function. The opponent's move is computed automatically inside ``step()``
    via the selected strategy or the provided ``opponent_fn``.
    """

    SUPPORTS_CONCURRENT_SESSIONS = True

    def __init__(self) -> None:
        super().__init__()
        self._game: Optional[GameConfig] = None
        self._strategy: Optional[OpponentStrategy] = None
        self._strategy_name: str = ""
        self._opponent_fn: Optional[Callable[[GameObservation], GameAction]] = None
        self._state: GameState = GameState()

    # ------------------------------------------------------------------
    # OpenEnv interface
    # ------------------------------------------------------------------

    def reset(
        self,
        seed: Optional[int] = None,
        episode_id: Optional[str] = None,
        **kwargs: Any,
    ) -> GameObservation:
        game_name: str = kwargs.get("game", "prisoners_dilemma")
        strategy_name: str = kwargs.get("strategy", "tit_for_tat")
        num_rounds: Optional[int] = kwargs.get("num_rounds")
        opponent_fn: Optional[Callable[[GameObservation], GameAction]] = kwargs.get(
            "opponent_fn",
        )

        self._game = get_game(game_name)
        self._opponent_fn = opponent_fn
        if opponent_fn is not None:
            self._strategy = None
            self._strategy_name = "agent"
        else:
            self._strategy = get_strategy(strategy_name)
            self._strategy_name = strategy_name

        rounds = num_rounds if num_rounds is not None else self._game.default_rounds

        self._state = GameState(
            episode_id=episode_id or str(uuid.uuid4()),
            game_name=game_name,
            opponent_strategy=strategy_name,
            total_rounds=rounds,
        )

        return self._build_observation()

    def step(
        self,
        action: GameAction,
        **kwargs: Any,
    ) -> GameObservation:
        if self._game is None:
            raise RuntimeError("Call reset() before step().")
        if self._state.is_done:
            raise RuntimeError("Episode already finished. Call reset().")
        if action.action not in self._game.actions:
            raise ValueError(
                f"Invalid action '{action.action}'. "
                f"Choose from: {self._game.actions}"
            )

        player_action = action.action
        opponent_action = self._auto_play_opponent(player_action)

        p_pay, o_pay = self._game.payoff_fn(player_action, opponent_action)

        new_round = len(self._state.history) + _ONE
        result = RoundResult(
            round_number=new_round,
            player_action=player_action,
            opponent_action=opponent_action,
            player_payoff=p_pay,
            opponent_payoff=o_pay,
        )

        history = list(self._state.history) + [result]
        p_score = self._state.player_score + p_pay
        o_score = self._state.opponent_score + o_pay
        done = new_round >= self._state.total_rounds

        self._state = GameState(
            episode_id=self._state.episode_id,
            step_count=self._state.step_count + _ONE,
            game_name=self._state.game_name,
            opponent_strategy=self._state.opponent_strategy,
            current_round=new_round,
            total_rounds=self._state.total_rounds,
            player_score=p_score,
            opponent_score=o_score,
            history=history,
            is_done=done,
        )

        return self._build_observation(reward=p_pay, last_round=result, done=done)

    @property
    def state(self) -> GameState:
        return self._state

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    def _auto_play_opponent(self, player_action: str) -> str:
        assert self._game is not None

        if self._opponent_fn is not None:
            opp_obs = self._build_opponent_observation()
            opp_action = self._opponent_fn(opp_obs)
            opp_actions = self._opponent_actions()
            if opp_action.action not in opp_actions:
                raise ValueError(
                    f"Opponent returned invalid action '{opp_action.action}'. "
                    f"Choose from: {opp_actions}"
                )
            return opp_action.action

        assert self._strategy is not None
        hist = [
            {
                "player_action": r.player_action,
                "opponent_action": r.opponent_action,
            }
            for r in self._state.history
        ]
        opp_actions = self._opponent_actions()
        return self._strategy.choose_action(
            self._game.game_type, opp_actions, hist,
        )

    def _opponent_actions(self) -> list[str]:
        assert self._game is not None
        if self._game.opponent_actions is not None:
            return list(self._game.opponent_actions)
        gt = self._game.game_type
        if gt == "ultimatum":
            return ["accept", "reject"]
        if gt == "trust":
            return _trust_return_actions()
        # matrix, public_goods, auction, commons, dictator, centipede,
        # stackelberg, and all generated games share action space
        return list(self._game.actions)

    def _build_opponent_observation(self) -> GameObservation:
        """Build a GameObservation from the opponent's perspective.

        Swaps player/opponent in history, scores, and payoffs so the opponent
        agent sees itself as the "player".
        """
        assert self._game is not None
        flipped_history = [
            RoundResult(
                round_number=r.round_number,
                player_action=r.opponent_action,
                opponent_action=r.player_action,
                player_payoff=r.opponent_payoff,
                opponent_payoff=r.player_payoff,
            )
            for r in self._state.history
        ]
        opp_actions = self._opponent_actions()
        return GameObservation(
            done=False,
            reward=_ZERO_F,
            game_name=self._state.game_name,
            game_description=self._game.description,
            available_actions=opp_actions,
            current_round=self._state.current_round,
            total_rounds=self._state.total_rounds,
            history=flipped_history,
            player_score=self._state.opponent_score,
            opponent_score=self._state.player_score,
            opponent_strategy="agent",
        )

    def _build_observation(
        self,
        reward: float = _ZERO_F,
        last_round: Optional[RoundResult] = None,
        done: bool = False,
    ) -> GameObservation:
        assert self._game is not None
        return GameObservation(
            done=done,
            reward=reward,
            game_name=self._state.game_name,
            game_description=self._game.description,
            available_actions=list(self._game.actions),
            current_round=self._state.current_round,
            total_rounds=self._state.total_rounds,
            history=list(self._state.history),
            player_score=self._state.player_score,
            opponent_score=self._state.opponent_score,
            opponent_strategy=self._strategy_name,
            last_round=last_round,
        )


def _trust_return_actions() -> list[str]:
    from constant_definitions.game_constants import TRUST_ENDOWMENT, TRUST_MULTIPLIER
    cap = TRUST_ENDOWMENT * TRUST_MULTIPLIER
    return [f"return_{i}" for i in range(cap + _ONE)]