POPJym 0.1.0__py3-none-any.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.
- popjym/__init__.py +41 -0
- popjym/core/__init__.py +27 -0
- popjym/core/deck.py +52 -0
- popjym/core/env.py +99 -0
- popjym/core/maze.py +202 -0
- popjym/core/observability.py +13 -0
- popjym/core/spaces.py +219 -0
- popjym/envs/__init__.py +195 -0
- popjym/envs/autoencode.py +116 -0
- popjym/envs/battleship.py +128 -0
- popjym/envs/concentration.py +158 -0
- popjym/envs/count_recall.py +119 -0
- popjym/envs/higher_lower.py +88 -0
- popjym/envs/labyrinth_escape.py +60 -0
- popjym/envs/labyrinth_explore.py +63 -0
- popjym/envs/minesweeper.py +124 -0
- popjym/envs/multiarmed_bandit.py +75 -0
- popjym/envs/noisy_position_only_cartpole.py +33 -0
- popjym/envs/noisy_position_only_pendulum.py +27 -0
- popjym/envs/position_only_cartpole.py +162 -0
- popjym/envs/position_only_pendulum.py +133 -0
- popjym/envs/repeat_first.py +80 -0
- popjym/envs/repeat_previous.py +99 -0
- popjym/envs/velocity_only_cartpole.py +26 -0
- popjym/registry.py +30 -0
- popjym/wrappers/__init__.py +5 -0
- popjym/wrappers/gymnax.py +190 -0
- popjym-0.1.0.dist-info/METADATA +95 -0
- popjym-0.1.0.dist-info/RECORD +31 -0
- popjym-0.1.0.dist-info/WHEEL +4 -0
- popjym-0.1.0.dist-info/licenses/LICENSE +22 -0
popjym/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""POPJym: JIT-compatible POPGym environments implemented in JAX."""
|
|
2
|
+
|
|
3
|
+
from popjym import envs
|
|
4
|
+
from popjym.core import (
|
|
5
|
+
Box,
|
|
6
|
+
Discrete,
|
|
7
|
+
MultiBinary,
|
|
8
|
+
MultiDiscrete,
|
|
9
|
+
POPJymEnv,
|
|
10
|
+
Space,
|
|
11
|
+
TupleSpace,
|
|
12
|
+
Observability,
|
|
13
|
+
flatdim,
|
|
14
|
+
flatten,
|
|
15
|
+
)
|
|
16
|
+
from popjym.envs import ALL
|
|
17
|
+
from popjym.registry import ENV_REGISTRY, make, make_gymnax, registered_envs
|
|
18
|
+
from popjym.wrappers import EnvParams, GymnaxWrapper
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"ALL",
|
|
24
|
+
"ENV_REGISTRY",
|
|
25
|
+
"Box",
|
|
26
|
+
"Discrete",
|
|
27
|
+
"EnvParams",
|
|
28
|
+
"GymnaxWrapper",
|
|
29
|
+
"MultiDiscrete",
|
|
30
|
+
"MultiBinary",
|
|
31
|
+
"Space",
|
|
32
|
+
"Observability",
|
|
33
|
+
"flatdim",
|
|
34
|
+
"flatten",
|
|
35
|
+
"POPJymEnv",
|
|
36
|
+
"TupleSpace",
|
|
37
|
+
"envs",
|
|
38
|
+
"make",
|
|
39
|
+
"make_gymnax",
|
|
40
|
+
"registered_envs",
|
|
41
|
+
]
|
popjym/core/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Reusable JAX modules such as deck, base environment, maze, and spaces."""
|
|
2
|
+
|
|
3
|
+
from popjym.core.env import POPJymEnv
|
|
4
|
+
from popjym.core.spaces import (
|
|
5
|
+
Box,
|
|
6
|
+
Discrete,
|
|
7
|
+
MultiBinary,
|
|
8
|
+
MultiDiscrete,
|
|
9
|
+
Space,
|
|
10
|
+
TupleSpace,
|
|
11
|
+
flatdim,
|
|
12
|
+
flatten,
|
|
13
|
+
)
|
|
14
|
+
from popjym.core.observability import Observability
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"POPJymEnv",
|
|
18
|
+
"Box",
|
|
19
|
+
"Discrete",
|
|
20
|
+
"MultiDiscrete",
|
|
21
|
+
"MultiBinary",
|
|
22
|
+
"Space",
|
|
23
|
+
"TupleSpace",
|
|
24
|
+
"Observability",
|
|
25
|
+
"flatdim",
|
|
26
|
+
"flatten",
|
|
27
|
+
]
|
popjym/core/deck.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Functional JAX helpers for POPGym's standard 52-card decks.
|
|
2
|
+
|
|
3
|
+
This module mirrors :mod:`popgym.core.deck`, but represents a shuffled deck as
|
|
4
|
+
a JAX integer array so it can live inside an environment PyTree.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import jax
|
|
10
|
+
import jax.numpy as jnp
|
|
11
|
+
|
|
12
|
+
DECK_SIZE = 52
|
|
13
|
+
NUM_SUITS = 4
|
|
14
|
+
NUM_RANKS = 13
|
|
15
|
+
NUM_COLORS = 2
|
|
16
|
+
RANKS = ("a", "2", "3", "4", "5", "6", "7", "8", "9", "10", "j", "q", "k")
|
|
17
|
+
SUITS = ("s", "d", "c", "h")
|
|
18
|
+
COLORS = ("b", "r")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def shuffled_deck(key: jax.Array, num_decks: int) -> jax.Array:
|
|
22
|
+
"""Return a shuffled array of unique card indices."""
|
|
23
|
+
|
|
24
|
+
return jax.random.permutation(
|
|
25
|
+
key, jnp.arange(DECK_SIZE * num_decks, dtype=jnp.int32)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def suit(card: jax.Array) -> jax.Array:
|
|
30
|
+
return jnp.mod(card, DECK_SIZE) % NUM_SUITS
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def rank(card: jax.Array) -> jax.Array:
|
|
34
|
+
return jnp.mod(card, DECK_SIZE) // NUM_SUITS
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def color(card: jax.Array) -> jax.Array:
|
|
38
|
+
return jnp.mod(card, DECK_SIZE) % NUM_COLORS
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def feature(card: jax.Array, kind: str) -> jax.Array:
|
|
42
|
+
if kind == "colors":
|
|
43
|
+
return color(card)
|
|
44
|
+
if kind == "suits":
|
|
45
|
+
return suit(card)
|
|
46
|
+
if kind == "ranks":
|
|
47
|
+
return rank(card)
|
|
48
|
+
raise ValueError(f"Unknown card feature: {kind}")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def num_values(kind: str) -> int:
|
|
52
|
+
return {"colors": NUM_COLORS, "suits": NUM_SUITS, "ranks": NUM_RANKS}[kind]
|
popjym/core/env.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Common protocol for functional POPJym environments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from typing import Any, Generic, TypeVar
|
|
7
|
+
|
|
8
|
+
import jax
|
|
9
|
+
import jax.numpy as jnp
|
|
10
|
+
|
|
11
|
+
from popjym.core.observability import Observability
|
|
12
|
+
from popjym.core.spaces import Box, Discrete, MultiDiscrete, flatdim
|
|
13
|
+
|
|
14
|
+
State = TypeVar("State")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class POPJymEnv(ABC, Generic[State]):
|
|
18
|
+
"""A stateless environment object whose episode data lives in a PyTree.
|
|
19
|
+
|
|
20
|
+
Environment instances contain configuration only. ``reset`` and ``step``
|
|
21
|
+
are pure functions and can be closed over directly by :func:`jax.jit`.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
max_episode_length: int
|
|
25
|
+
observation_space: Any
|
|
26
|
+
action_space: Any
|
|
27
|
+
state_space: Any
|
|
28
|
+
observability_level = Observability.PARTIAL
|
|
29
|
+
obs_requires_prev_action = False
|
|
30
|
+
metadata = {"render_modes": []}
|
|
31
|
+
reward_range = (-float("inf"), float("inf"))
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def name(self) -> str:
|
|
35
|
+
return type(self).__name__
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def unwrapped(self):
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def num_actions(self) -> int:
|
|
43
|
+
if isinstance(self.action_space, Discrete):
|
|
44
|
+
return self.action_space.n
|
|
45
|
+
if isinstance(self.action_space, MultiDiscrete):
|
|
46
|
+
return int(self.action_space.nvec.prod())
|
|
47
|
+
if isinstance(self.action_space, Box):
|
|
48
|
+
return flatdim(self.action_space)
|
|
49
|
+
raise TypeError("num_actions requires a Discrete, MultiDiscrete or Box space")
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def observation_size(self) -> int:
|
|
53
|
+
return flatdim(self.observation_space)
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def get_state(self, state: State) -> Any:
|
|
57
|
+
"""POPGym privileged state, distinct from the full simulator PyTree."""
|
|
58
|
+
raise NotImplementedError
|
|
59
|
+
|
|
60
|
+
@abstractmethod
|
|
61
|
+
def get_obs(self, state: State) -> Any:
|
|
62
|
+
"""Observation of the current environment state."""
|
|
63
|
+
raise NotImplementedError
|
|
64
|
+
|
|
65
|
+
def last_observation(self, state: State) -> Any:
|
|
66
|
+
"""Observation returned by the most recent reset or step."""
|
|
67
|
+
return self.get_obs(state)
|
|
68
|
+
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def elapsed_steps(self, state: State) -> jax.Array:
|
|
71
|
+
raise NotImplementedError
|
|
72
|
+
|
|
73
|
+
@abstractmethod
|
|
74
|
+
def is_terminated(self, state: State) -> jax.Array:
|
|
75
|
+
raise NotImplementedError
|
|
76
|
+
|
|
77
|
+
def is_truncated(self, state: State) -> jax.Array:
|
|
78
|
+
return self.elapsed_steps(state) >= self.max_episode_length
|
|
79
|
+
|
|
80
|
+
def is_terminal(self, state: State) -> jax.Array:
|
|
81
|
+
"""Whether the episode has ended for either reason."""
|
|
82
|
+
return self.is_terminated(state) | self.is_truncated(state)
|
|
83
|
+
|
|
84
|
+
def discount(self, state: State) -> jax.Array:
|
|
85
|
+
"""Bootstrap through time limits, but not natural terminal states."""
|
|
86
|
+
return (~self.is_terminated(state)).astype(jnp.float32)
|
|
87
|
+
|
|
88
|
+
@abstractmethod
|
|
89
|
+
def reset(self, key: jax.Array) -> tuple[Any, State]:
|
|
90
|
+
raise NotImplementedError
|
|
91
|
+
|
|
92
|
+
@abstractmethod
|
|
93
|
+
def step(
|
|
94
|
+
self, key: jax.Array, state: State, action: Any
|
|
95
|
+
) -> tuple[Any, State, jax.Array, jax.Array, jax.Array, dict[str, Any]]:
|
|
96
|
+
raise NotImplementedError
|
|
97
|
+
|
|
98
|
+
def sample_action(self, key: jax.Array) -> jax.Array:
|
|
99
|
+
return self.action_space.sample(key)
|
popjym/core/maze.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Shared JAX maze generation and movement logic for navigation tasks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import IntEnum
|
|
6
|
+
from typing import NamedTuple
|
|
7
|
+
|
|
8
|
+
import jax
|
|
9
|
+
import jax.numpy as jnp
|
|
10
|
+
|
|
11
|
+
from popjym.core.env import POPJymEnv
|
|
12
|
+
from popjym.core.spaces import Discrete, MultiDiscrete
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Explored(IntEnum):
|
|
16
|
+
NO = 0
|
|
17
|
+
YES = 1
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Cell(IntEnum):
|
|
21
|
+
FREE = 0
|
|
22
|
+
OBSTACLE = 1
|
|
23
|
+
START = 2
|
|
24
|
+
GOAL = 3
|
|
25
|
+
HIDDEN = 4
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Actions(IntEnum):
|
|
29
|
+
LEFT = 0
|
|
30
|
+
RIGHT = 1
|
|
31
|
+
UP = 2
|
|
32
|
+
DOWN = 3
|
|
33
|
+
NONE = 4
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# Integer aliases keep the JAX expressions concise while preserving the
|
|
37
|
+
# upstream enum-based public API.
|
|
38
|
+
FREE = int(Cell.FREE)
|
|
39
|
+
OBSTACLE = int(Cell.OBSTACLE)
|
|
40
|
+
START = int(Cell.START)
|
|
41
|
+
GOAL = int(Cell.GOAL)
|
|
42
|
+
HIDDEN = int(Cell.HIDDEN)
|
|
43
|
+
NONE = int(Actions.NONE)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class MazeState(NamedTuple):
|
|
47
|
+
grid: jax.Array
|
|
48
|
+
explored: jax.Array
|
|
49
|
+
position: jax.Array
|
|
50
|
+
curr_step: jax.Array
|
|
51
|
+
last_action: jax.Array
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def generate_maze(key: jax.Array, logical_height: int, logical_width: int):
|
|
55
|
+
"""Port mazelib's default random Hunt-and-Kill algorithm to JAX.
|
|
56
|
+
|
|
57
|
+
Random hunts start walks only from visited cells. Like mazelib, at most
|
|
58
|
+
height * width hunts are attempted; finished mazes can exit early.
|
|
59
|
+
"""
|
|
60
|
+
height, width = 2 * logical_height + 1, 2 * logical_width + 1
|
|
61
|
+
num_cells = logical_height * logical_width
|
|
62
|
+
key, start_key = jax.random.split(key)
|
|
63
|
+
start = jax.random.randint(start_key, (), 0, num_cells, dtype=jnp.int32)
|
|
64
|
+
position = jnp.array(
|
|
65
|
+
[2 * (start // logical_width) + 1, 2 * (start % logical_width) + 1], jnp.int32
|
|
66
|
+
)
|
|
67
|
+
grid = jnp.ones((height, width), jnp.int32).at[position[0], position[1]].set(FREE)
|
|
68
|
+
deltas = jnp.array([[-2, 0], [2, 0], [0, -2], [0, 2]], jnp.int32)
|
|
69
|
+
|
|
70
|
+
def neighbors(grid, position):
|
|
71
|
+
candidates = position + deltas
|
|
72
|
+
valid = jnp.all(
|
|
73
|
+
(candidates > 0) & (candidates < jnp.array([height - 1, width - 1])), axis=1
|
|
74
|
+
)
|
|
75
|
+
safe = jnp.clip(candidates, 0, jnp.array([height - 1, width - 1]))
|
|
76
|
+
return candidates, valid & (grid[safe[:, 0], safe[:, 1]] == OBSTACLE)
|
|
77
|
+
|
|
78
|
+
def walk_cond(carry):
|
|
79
|
+
_, grid, position = carry
|
|
80
|
+
return (grid[position[0], position[1]] == FREE) & jnp.any(
|
|
81
|
+
neighbors(grid, position)[1]
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def walk_body(carry):
|
|
85
|
+
key, grid, position = carry
|
|
86
|
+
key, choice_key = jax.random.split(key)
|
|
87
|
+
candidates, valid = neighbors(grid, position)
|
|
88
|
+
logits = jnp.where(valid, jnp.float32(0), -jnp.inf)
|
|
89
|
+
choice = jax.random.categorical(choice_key, logits)
|
|
90
|
+
target = candidates[choice]
|
|
91
|
+
wall = (position + target) // 2
|
|
92
|
+
grid = grid.at[target[0], target[1]].set(FREE).at[wall[0], wall[1]].set(FREE)
|
|
93
|
+
return key, grid, target
|
|
94
|
+
|
|
95
|
+
def hunt_cond(carry):
|
|
96
|
+
_, grid, _, count = carry
|
|
97
|
+
return (count <= height * width) & jnp.any(grid[1::2, 1::2] == OBSTACLE)
|
|
98
|
+
|
|
99
|
+
def hunt_body(carry):
|
|
100
|
+
key, grid, position, count = carry
|
|
101
|
+
key, grid, _ = jax.lax.while_loop(walk_cond, walk_body, (key, grid, position))
|
|
102
|
+
key, hunt_key = jax.random.split(key)
|
|
103
|
+
cell = jax.random.randint(hunt_key, (), 0, num_cells, dtype=jnp.int32)
|
|
104
|
+
position = jnp.array(
|
|
105
|
+
[2 * (cell // logical_width) + 1, 2 * (cell % logical_width) + 1], jnp.int32
|
|
106
|
+
)
|
|
107
|
+
return key, grid, position, count + 1
|
|
108
|
+
|
|
109
|
+
key, grid, _, _ = jax.lax.while_loop(
|
|
110
|
+
hunt_cond, hunt_body, (key, grid, position, jnp.int32(0))
|
|
111
|
+
)
|
|
112
|
+
key, side_key, start_index_key, goal_index_key = jax.random.split(key, 4)
|
|
113
|
+
side = jax.random.randint(side_key, (), 0, 4, dtype=jnp.int32)
|
|
114
|
+
|
|
115
|
+
def border_position(which_side, index_key):
|
|
116
|
+
row = jax.random.randint(index_key, (), 0, logical_height, dtype=jnp.int32)
|
|
117
|
+
col = jax.random.randint(
|
|
118
|
+
jax.random.fold_in(index_key, 1), (), 0, logical_width, dtype=jnp.int32
|
|
119
|
+
)
|
|
120
|
+
branches = (
|
|
121
|
+
lambda _: jnp.array([0, 2 * col + 1], jnp.int32),
|
|
122
|
+
lambda _: jnp.array([2 * row + 1, width - 1], jnp.int32),
|
|
123
|
+
lambda _: jnp.array([height - 1, 2 * col + 1], jnp.int32),
|
|
124
|
+
lambda _: jnp.array([2 * row + 1, 0], jnp.int32),
|
|
125
|
+
)
|
|
126
|
+
return jax.lax.switch(which_side, branches, operand=None)
|
|
127
|
+
|
|
128
|
+
start = border_position(side, start_index_key)
|
|
129
|
+
goal = border_position((side + 2) % 4, goal_index_key)
|
|
130
|
+
grid = grid.at[start[0], start[1]].set(START)
|
|
131
|
+
grid = grid.at[goal[0], goal[1]].set(GOAL)
|
|
132
|
+
return grid, start, goal
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class MazeEnv(POPJymEnv[MazeState]):
|
|
136
|
+
"""Base class shared by POPGym's two navigation environments."""
|
|
137
|
+
|
|
138
|
+
obs_requires_prev_action = True
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self, maze_dims: tuple[int, int] = (10, 10), episode_length: int = 1024
|
|
142
|
+
):
|
|
143
|
+
if any(d < 6 or d % 2 for d in maze_dims):
|
|
144
|
+
raise ValueError(
|
|
145
|
+
"Maze dimensions must be even and at least 6 (as in mazelib)"
|
|
146
|
+
)
|
|
147
|
+
self.input_dims = tuple(maze_dims)
|
|
148
|
+
self.logical_dims = (maze_dims[0] // 2, maze_dims[1] // 2)
|
|
149
|
+
self.maze_dims = self.logical_dims
|
|
150
|
+
self.grid_shape = (maze_dims[0] + 1, maze_dims[1] + 1)
|
|
151
|
+
self.max_episode_length = episode_length
|
|
152
|
+
self.action_space = Discrete(4)
|
|
153
|
+
self.observation_space = MultiDiscrete(tuple([5] * 9 + [5]))
|
|
154
|
+
self.state_space = MultiDiscrete(
|
|
155
|
+
((5,) * self.grid_shape[1],) * self.grid_shape[0]
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def get_obs(self, state):
|
|
159
|
+
return self._observation(state, state.last_action)
|
|
160
|
+
|
|
161
|
+
def elapsed_steps(self, state):
|
|
162
|
+
return state.curr_step
|
|
163
|
+
|
|
164
|
+
def is_truncated(self, state):
|
|
165
|
+
# POPGym checks equality after incrementing the counter in step().
|
|
166
|
+
return (state.curr_step > 0) & (state.curr_step == self.max_episode_length - 1)
|
|
167
|
+
|
|
168
|
+
def _reset_maze(self, key: jax.Array):
|
|
169
|
+
grid, start, _ = generate_maze(key, *self.logical_dims)
|
|
170
|
+
explored = jnp.zeros(self.grid_shape, dtype=jnp.bool_)
|
|
171
|
+
explored = explored.at[start[0], start[1]].set(True)
|
|
172
|
+
return MazeState(grid, explored, start, jnp.int32(0), jnp.int32(NONE))
|
|
173
|
+
|
|
174
|
+
def _move(self, state: MazeState, action) -> jax.Array:
|
|
175
|
+
deltas = jnp.array([[0, -1], [0, 1], [-1, 0], [1, 0]], dtype=jnp.int32)
|
|
176
|
+
candidate = state.position + deltas[jnp.asarray(action, dtype=jnp.int32)]
|
|
177
|
+
candidate = jnp.clip(candidate, 0, jnp.asarray(self.grid_shape, jnp.int32) - 1)
|
|
178
|
+
return jnp.where(
|
|
179
|
+
state.grid[candidate[0], candidate[1]] == OBSTACLE,
|
|
180
|
+
state.position,
|
|
181
|
+
candidate,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def _observation(self, state: MazeState, action) -> jax.Array:
|
|
185
|
+
# POPGym caps the inclusive row end at the width and the column end
|
|
186
|
+
# at the height. The padded grid handles the slice's actual boundaries.
|
|
187
|
+
start = jnp.maximum(state.position - 1, 0)
|
|
188
|
+
end = jnp.minimum(
|
|
189
|
+
state.position + 1, jnp.asarray(self.grid_shape[::-1], jnp.int32)
|
|
190
|
+
)
|
|
191
|
+
padded = jnp.pad(state.grid, ((0, 2), (0, 2)), constant_values=OBSTACLE)
|
|
192
|
+
view = jax.lax.dynamic_slice(padded, (start[0], start[1]), (3, 3))
|
|
193
|
+
valid = (jnp.arange(3)[:, None] <= end[0] - start[0]) & (
|
|
194
|
+
jnp.arange(3)[None, :] <= end[1] - start[1]
|
|
195
|
+
)
|
|
196
|
+
view = jnp.where(valid, view, OBSTACLE)
|
|
197
|
+
return jnp.concatenate(
|
|
198
|
+
[view.reshape(-1), jnp.asarray([action], dtype=jnp.int32)]
|
|
199
|
+
).astype(jnp.int32)
|
|
200
|
+
|
|
201
|
+
def get_state(self, state: MazeState) -> jax.Array:
|
|
202
|
+
return jnp.where(state.explored, state.grid, HIDDEN)
|
popjym/core/spaces.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""JAX-native spaces and categorical flattening, without a Gym dependency."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from math import prod
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import jax
|
|
10
|
+
import jax.numpy as jnp
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Space:
|
|
15
|
+
"""Static specification with pure, JIT/vmap-compatible operations."""
|
|
16
|
+
|
|
17
|
+
def sample(self, key):
|
|
18
|
+
raise NotImplementedError
|
|
19
|
+
|
|
20
|
+
def contains(self, value):
|
|
21
|
+
raise NotImplementedError
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def flat_dim(self):
|
|
25
|
+
return flatdim(self)
|
|
26
|
+
|
|
27
|
+
def flatten(self, value):
|
|
28
|
+
return flatten(self, value)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Discrete(Space):
|
|
33
|
+
n: int
|
|
34
|
+
dtype: Any = jnp.int32
|
|
35
|
+
|
|
36
|
+
def __post_init__(self):
|
|
37
|
+
if not isinstance(self.n, (int, np.integer)) or self.n <= 0:
|
|
38
|
+
raise ValueError("n must be a positive integer")
|
|
39
|
+
if not np.issubdtype(self.dtype, np.integer):
|
|
40
|
+
raise ValueError("Discrete requires an integer dtype")
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def shape(self):
|
|
44
|
+
return ()
|
|
45
|
+
|
|
46
|
+
def sample(self, key):
|
|
47
|
+
return jax.random.randint(key, (), 0, self.n, dtype=self.dtype)
|
|
48
|
+
|
|
49
|
+
def contains(self, value):
|
|
50
|
+
value = jnp.asarray(value)
|
|
51
|
+
if value.shape != () or not jnp.issubdtype(value.dtype, jnp.integer):
|
|
52
|
+
return jnp.bool_(False)
|
|
53
|
+
return (value >= 0) & (value < self.n)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, eq=False)
|
|
57
|
+
class MultiDiscrete(Space):
|
|
58
|
+
nvec: Any
|
|
59
|
+
dtype: Any = jnp.int32
|
|
60
|
+
|
|
61
|
+
def __post_init__(self):
|
|
62
|
+
nvec = np.asarray(self.nvec)
|
|
63
|
+
if not np.issubdtype(nvec.dtype, np.integer) or np.any(nvec <= 0):
|
|
64
|
+
raise ValueError("nvec must contain positive integers")
|
|
65
|
+
if not np.issubdtype(self.dtype, np.integer):
|
|
66
|
+
raise ValueError("MultiDiscrete requires an integer dtype")
|
|
67
|
+
nvec = np.array(nvec, dtype=self.dtype, copy=True)
|
|
68
|
+
nvec.flags.writeable = False
|
|
69
|
+
object.__setattr__(self, "nvec", nvec)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def shape(self):
|
|
73
|
+
return self.nvec.shape
|
|
74
|
+
|
|
75
|
+
def sample(self, key):
|
|
76
|
+
return jax.random.randint(
|
|
77
|
+
key, self.shape, 0, jnp.asarray(self.nvec), dtype=self.dtype
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
def contains(self, value):
|
|
81
|
+
value = jnp.asarray(value)
|
|
82
|
+
if value.shape != self.shape or not jnp.issubdtype(value.dtype, jnp.integer):
|
|
83
|
+
return jnp.bool_(False)
|
|
84
|
+
return jnp.all((value >= 0) & (value < jnp.asarray(self.nvec)))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class MultiBinary(Space):
|
|
89
|
+
n: int | tuple[int, ...]
|
|
90
|
+
dtype: Any = jnp.int8
|
|
91
|
+
|
|
92
|
+
def __post_init__(self):
|
|
93
|
+
if any(d <= 0 for d in self.shape):
|
|
94
|
+
raise ValueError("MultiBinary dimensions must be positive")
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def shape(self):
|
|
98
|
+
return (self.n,) if isinstance(self.n, int) else tuple(self.n)
|
|
99
|
+
|
|
100
|
+
def sample(self, key):
|
|
101
|
+
return jax.random.bernoulli(key, shape=self.shape).astype(self.dtype)
|
|
102
|
+
|
|
103
|
+
def contains(self, value):
|
|
104
|
+
value = jnp.asarray(value)
|
|
105
|
+
if value.shape != self.shape:
|
|
106
|
+
return jnp.bool_(False)
|
|
107
|
+
return jnp.all((value == 0) | (value == 1))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True, eq=False)
|
|
111
|
+
class Box(Space):
|
|
112
|
+
low: Any
|
|
113
|
+
high: Any
|
|
114
|
+
shape: tuple[int, ...] | None = None
|
|
115
|
+
dtype: Any = jnp.float32
|
|
116
|
+
|
|
117
|
+
def __post_init__(self):
|
|
118
|
+
shape = self.shape
|
|
119
|
+
if shape is None:
|
|
120
|
+
shape = np.broadcast_shapes(np.shape(self.low), np.shape(self.high))
|
|
121
|
+
shape = tuple(shape)
|
|
122
|
+
low = np.array(np.broadcast_to(self.low, shape), dtype=self.dtype, copy=True)
|
|
123
|
+
high = np.array(np.broadcast_to(self.high, shape), dtype=self.dtype, copy=True)
|
|
124
|
+
if np.any(np.isnan(low) | np.isnan(high) | (low > high)):
|
|
125
|
+
raise ValueError("Box bounds must satisfy low <= high and cannot be NaN")
|
|
126
|
+
low.flags.writeable = high.flags.writeable = False
|
|
127
|
+
object.__setattr__(self, "low", low)
|
|
128
|
+
object.__setattr__(self, "high", high)
|
|
129
|
+
object.__setattr__(self, "shape", shape)
|
|
130
|
+
|
|
131
|
+
def sample(self, key):
|
|
132
|
+
low, high = jnp.asarray(self.low), jnp.asarray(self.high)
|
|
133
|
+
if jnp.issubdtype(self.dtype, jnp.integer):
|
|
134
|
+
return jax.random.randint(key, self.shape, low, high + 1, dtype=self.dtype)
|
|
135
|
+
uk, nk, ek = jax.random.split(key, 3)
|
|
136
|
+
bounded_low, bounded_high = jnp.isfinite(low), jnp.isfinite(high)
|
|
137
|
+
safe_low, safe_high = (
|
|
138
|
+
jnp.where(bounded_low, low, 0),
|
|
139
|
+
jnp.where(bounded_high, high, 1),
|
|
140
|
+
)
|
|
141
|
+
uniform = safe_low + jax.random.uniform(uk, self.shape, dtype=self.dtype) * (
|
|
142
|
+
safe_high - safe_low
|
|
143
|
+
)
|
|
144
|
+
normal = jax.random.normal(nk, self.shape, dtype=self.dtype)
|
|
145
|
+
exponential = jax.random.exponential(ek, self.shape, dtype=self.dtype)
|
|
146
|
+
return jnp.where(
|
|
147
|
+
bounded_low & bounded_high,
|
|
148
|
+
uniform,
|
|
149
|
+
jnp.where(
|
|
150
|
+
bounded_low,
|
|
151
|
+
safe_low + exponential,
|
|
152
|
+
jnp.where(bounded_high, safe_high - exponential, normal),
|
|
153
|
+
),
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def contains(self, value):
|
|
157
|
+
value = jnp.asarray(value)
|
|
158
|
+
if value.shape != self.shape:
|
|
159
|
+
return jnp.bool_(False)
|
|
160
|
+
if np.issubdtype(self.dtype, np.integer) and not jnp.issubdtype(
|
|
161
|
+
value.dtype, jnp.integer
|
|
162
|
+
):
|
|
163
|
+
return jnp.bool_(False)
|
|
164
|
+
return jnp.all(
|
|
165
|
+
(value >= jnp.asarray(self.low)) & (value <= jnp.asarray(self.high))
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass(frozen=True)
|
|
170
|
+
class TupleSpace(Space):
|
|
171
|
+
spaces: tuple[Space, ...]
|
|
172
|
+
shape = None
|
|
173
|
+
dtype = None
|
|
174
|
+
|
|
175
|
+
def __len__(self):
|
|
176
|
+
return len(self.spaces)
|
|
177
|
+
|
|
178
|
+
def __getitem__(self, index):
|
|
179
|
+
return self.spaces[index]
|
|
180
|
+
|
|
181
|
+
def sample(self, key):
|
|
182
|
+
keys = jax.random.split(key, len(self.spaces))
|
|
183
|
+
return tuple(space.sample(k) for space, k in zip(self.spaces, keys))
|
|
184
|
+
|
|
185
|
+
def contains(self, value):
|
|
186
|
+
if not isinstance(value, tuple) or len(value) != len(self.spaces):
|
|
187
|
+
return jnp.bool_(False)
|
|
188
|
+
return jnp.all(jnp.asarray([s.contains(x) for s, x in zip(self.spaces, value)]))
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def flatdim(space: Space) -> int:
|
|
192
|
+
"""Size of a flat encoding; categorical components are one-hot encoded."""
|
|
193
|
+
if isinstance(space, Discrete):
|
|
194
|
+
return int(space.n)
|
|
195
|
+
if isinstance(space, MultiDiscrete):
|
|
196
|
+
return int(space.nvec.sum())
|
|
197
|
+
if isinstance(space, (Box, MultiBinary)):
|
|
198
|
+
return prod(space.shape)
|
|
199
|
+
if isinstance(space, TupleSpace):
|
|
200
|
+
return sum(flatdim(s) for s in space.spaces)
|
|
201
|
+
raise TypeError(f"Unsupported space: {type(space).__name__}")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def flatten(space: Space, value: Any) -> jax.Array:
|
|
205
|
+
"""Encode one observation/action as a float32 feature vector."""
|
|
206
|
+
if isinstance(space, Discrete):
|
|
207
|
+
return jax.nn.one_hot(value, space.n, dtype=jnp.float32)
|
|
208
|
+
if isinstance(space, MultiDiscrete):
|
|
209
|
+
if space.nvec.size == 0:
|
|
210
|
+
return jnp.empty((0,), dtype=jnp.float32)
|
|
211
|
+
values = jnp.asarray(value).reshape(-1)
|
|
212
|
+
return jnp.concatenate(
|
|
213
|
+
[jax.nn.one_hot(values[i], int(n)) for i, n in enumerate(space.nvec.flat)]
|
|
214
|
+
)
|
|
215
|
+
if isinstance(space, (Box, MultiBinary)):
|
|
216
|
+
return jnp.asarray(value, dtype=jnp.float32).reshape(-1)
|
|
217
|
+
if isinstance(space, TupleSpace):
|
|
218
|
+
return jnp.concatenate([flatten(s, x) for s, x in zip(space.spaces, value)])
|
|
219
|
+
raise TypeError(f"Unsupported space: {type(space).__name__}")
|