stgfn-repro-code / envs.py
barnabee's picture
Upload folder using huggingface_hub
6e03b1a verified
Raw
History Blame Contribute Delete
10.8 kB
"""Environments for the ST-GFN reproduction, reimplemented from the paper's
Section 4 descriptions (no author code is available for this submission).
Each env exposes a common interface:
- state_dim: int, dimensionality of the one-hot encoding
- n_actions: int, size of the (fixed) action space
- reset() -> state
- valid_actions(state) -> list[int]
- step(state, action) -> (next_state, done)
- reward(terminal_state) -> float (defined only meaningfully at terminal states)
- encode(state) -> np.ndarray[state_dim]
- expected_next_encodings(state, action) -> list[(prob, next_state)] (for envs
with a tractable stochastic kernel, used for the closed-form spectral
expectation E_{s'~P(.|s,a)}[z(s')]; falls back to a single sample otherwise)
"""
from __future__ import annotations
import itertools
import numpy as np
class BitSequenceEnv:
"""BitSequence (Sec 4.2): length-L binary strings, extreme action-failure
stochasticity (Bernoulli p_fail of the appended bit being replaced by a
uniform random bit). Reward is multimodal over a fixed set of target modes.
"""
name = "bitsequence"
def __init__(self, length: int = 8, p_fail: float = 0.9, n_modes: int = 8, seed: int = 0):
self.L = length
self.p_fail = p_fail
rng = np.random.RandomState(seed)
self.modes = [tuple(rng.randint(0, 2, size=length).tolist()) for _ in range(n_modes)]
self.n_actions = 2
self.state_dim = length * 3
def reset(self):
return tuple([-1] * self.L)
def valid_actions(self, state):
if -1 not in state:
return []
return [0, 1]
def step(self, state, action, rng: np.random.RandomState):
pos = state.index(-1)
bit = action if rng.rand() >= self.p_fail else rng.randint(0, 2)
new_state = list(state)
new_state[pos] = bit
done = pos == self.L - 1
return tuple(new_state), done
def expected_next_encodings(self, state, action):
"""Closed-form transition kernel: w.p. (1-p_fail) bit=action, w.p.
p_fail*0.5 bit=0, w.p. p_fail*0.5 bit=1."""
pos = state.index(-1)
outs = []
p_intended = 1.0 - self.p_fail + (self.p_fail * 0.5 if action in (0, 1) else 0.0)
for bit in (0, 1):
p = (1.0 - self.p_fail) * (1.0 if bit == action else 0.0) + self.p_fail * 0.5
if p <= 0:
continue
ns = list(state)
ns[pos] = bit
outs.append((p, tuple(ns)))
return outs
def encode(self, state):
oh = np.zeros((self.L, 3), dtype=np.float32)
for i, b in enumerate(state):
oh[i, b + 1] = 1.0
return oh.flatten()
def reward(self, state):
best = min(sum(a != b for a, b in zip(state, m)) for m in self.modes)
return 0.1 + 10.0 * float(np.exp(-1.2 * best))
def is_mode(self, state, thresh=3.0):
return self.reward(state) >= thresh
class HyperGridEnv:
"""HyperGrid (Sec 4.3): size x size grid, deterministic moves, period-4
reward modes at (x % period == 0, y % period == 0).
State is (x, y, stopped) so the terminating action leads to a *distinct*
terminal node (keeps the generative graph a DAG -- without the flag the
stop action would be a self-loop)."""
name = "hypergrid"
def __init__(self, size: int = 32, period: int = 4, seed: int = 0):
self.size = size
self.period = period
self.n_actions = 3 # 0: +x, 1: +y, 2: stop
self.state_dim = size * 2 + 1
def reset(self):
return (0, 0, 0)
def valid_actions(self, state):
x, y, stopped = state
if stopped:
return []
acts = [2]
if x < self.size - 1:
acts.append(0)
if y < self.size - 1:
acts.append(1)
return acts
def step(self, state, action, rng: np.random.RandomState):
x, y, stopped = state
if action == 2:
return (x, y, 1), True
if action == 0:
x += 1
elif action == 1:
y += 1
if x == self.size - 1 and y == self.size - 1:
return (x, y, 1), True
return (x, y, 0), False
def expected_next_encodings(self, state, action):
ns, _ = self.step(state, action, np.random)
return [(1.0, ns)]
def encode(self, state):
x, y, stopped = state
oh = np.zeros(self.size * 2 + 1, dtype=np.float32)
oh[x] = 1.0
oh[self.size + y] = 1.0
oh[-1] = float(stopped)
return oh
def reward(self, state):
x, y = state[0], state[1]
if x % self.period == 0 and y % self.period == 0:
return 10.0
return 0.1
def mode_id(self, state):
x, y = state[0], state[1]
if x % self.period == 0 and y % self.period == 0:
return (x // self.period, y // self.period)
return None
class TicTacToeEnv:
"""TicTacToe (Sec 4.4): agent (X) vs a minimax opponent (O) that plays
optimally with probability opp_optimal_prob (else a uniform random move).
Reward is derived from the terminal board outcome."""
name = "tictactoe"
LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
def __init__(self, opp_optimal_prob: float = 0.9, seed: int = 0):
self.opp_optimal_prob = opp_optimal_prob
self.n_actions = 9
self.state_dim = 27
self._minimax_cache = {}
def reset(self):
return tuple([0] * 9)
def _winner(self, b):
for a, c, d in self.LINES:
s = b[a] + b[c] + b[d]
if s == 3:
return 1
if s == -3:
return -1
if 0 not in b:
return 0
return None
def _minimax(self, b, player):
key = (b, player)
cached = self._minimax_cache.get(key)
if cached is not None:
return cached
w = self._winner(b)
if w is not None:
self._minimax_cache[key] = (w, None)
return w, None
best_move = None
best_val = -2 * player
for i in range(9):
if b[i] == 0:
nb = list(b)
nb[i] = player
nb = tuple(nb)
val, _ = self._minimax(nb, -player)
if (player == 1 and val > best_val) or (player == -1 and val < best_val):
best_val, best_move = val, i
self._minimax_cache[key] = (best_val, best_move)
return best_val, best_move
def valid_actions(self, state):
if self._winner(state) is not None:
return []
return [i for i in range(9) if state[i] == 0]
def step(self, state, action, rng: np.random.RandomState):
b = list(state)
b[action] = 1
w = self._winner(tuple(b))
if w is not None:
return tuple(b), True
if rng.rand() < self.opp_optimal_prob:
_, move = self._minimax(tuple(b), -1)
else:
empties = [i for i in range(9) if b[i] == 0]
move = empties[rng.randint(len(empties))]
b[move] = -1
w = self._winner(tuple(b))
return tuple(b), w is not None
def expected_next_encodings(self, state, action):
"""Closed form over the opponent's mixed strategy: optimal move w.p.
opp_optimal_prob, uniform among empties w.p. (1-opp_optimal_prob)."""
b = list(state)
b[action] = 1
bt = tuple(b)
w = self._winner(bt)
if w is not None:
return [(1.0, bt)]
_, opt_move = self._minimax(bt, -1)
empties = [i for i in range(9) if b[i] == 0]
probs = {}
if opt_move is not None:
probs[opt_move] = probs.get(opt_move, 0.0) + self.opp_optimal_prob
for m in empties:
probs[m] = probs.get(m, 0.0) + (1 - self.opp_optimal_prob) / len(empties)
outs = []
for m, p in probs.items():
nb = list(b)
nb[m] = -1
outs.append((p, tuple(nb)))
return outs
def encode(self, state):
oh = np.zeros(27, dtype=np.float32)
for i, v in enumerate(state):
oh[i * 3 + (v + 1)] = 1.0
return oh
def reward(self, state):
w = self._winner(state)
if w == 1:
return 5.0
if w == 0:
return 1.0
return 0.05
def is_win(self, state):
return self._winner(state) == 1
class SingleCellProxyEnv:
"""SingleCell (Sec 4.5) TOY PROXY. The real environment needs Perturb-seq
data (Replogle et al. 2022) and a trained response predictor, which is
infeasible within this reproduction's time/compute scope. We substitute a
synthetic combinatorial 'gene selection' task: choose k of n candidate
genes, reward is a synthetic low-rank interaction score. This is a scoped
PROXY for testing whether RKHS smoothness helps generalize over a large
combinatorial action space -- it is NOT a claim about real single-cell
biology. Labeled `toy` throughout the logbook."""
name = "singlecell_proxy"
def __init__(self, n_genes: int = 24, k: int = 3, seed: int = 0):
self.n = n_genes
self.k = k
self.n_actions = n_genes
self.state_dim = n_genes
rng = np.random.RandomState(seed)
rank = 4
A = rng.randn(n_genes, rank)
self.W = (A @ A.T) / rank
self.bias = rng.randn(n_genes) * 0.3
def reset(self):
return tuple()
def valid_actions(self, state):
if len(state) >= self.k:
return []
return [i for i in range(self.n) if i not in state]
def step(self, state, action, rng: np.random.RandomState):
new_state = tuple(sorted(state + (action,)))
done = len(new_state) == self.k
return new_state, done
def expected_next_encodings(self, state, action):
ns = tuple(sorted(state + (action,)))
return [(1.0, ns)]
def encode(self, state):
oh = np.zeros(self.n, dtype=np.float32)
for g in state:
oh[g] = 1.0
return oh
def reward(self, state):
idx = list(state)
sub = self.W[np.ix_(idx, idx)]
score = sub.sum() + self.bias[idx].sum()
return float(np.exp(score / 4.0)) + 0.05
def brute_force_best(self):
best = None
for combo in itertools.combinations(range(self.n), self.k):
r = self.reward(combo)
if best is None or r > best[1]:
best = (combo, r)
return best
ENVS = {
"bitsequence": BitSequenceEnv,
"hypergrid": HyperGridEnv,
"tictactoe": TicTacToeEnv,
"singlecell_proxy": SingleCellProxyEnv,
}