Skip to content

Commit 602e4be

Browse files
authored
add survo env (#461)
* add survo env * add survo curriculum * add survo tests
1 parent 0159b1b commit 602e4be

File tree

3 files changed

+344
-3
lines changed

3 files changed

+344
-3
lines changed

reasoning_gym/games/__init__.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from .rush_hour import RushHourConfig, RushHourCurriculum, RushHourDataset
2121
from .sokoban import SokobanConfig, SokobanCurriculum, SokobanDataset
2222
from .sudoku import SudokuConfig, SudokuCurriculum, SudokuDataset
23+
from .survo import SurvoConfig, SurvoCurriculum, SurvoDataset
2324
from .tower_of_hanoi import HanoiConfig, HanoiCurriculum, HanoiDataset
2425
from .tsumego import TsumegoConfig, TsumegoCurriculum, TsumegoDataset
2526

@@ -45,12 +46,15 @@
4546
"Puzzle24Config",
4647
"Puzzle24Dataset",
4748
"Puzzle24Curriculum",
48-
"SudokuConfig",
49-
"SudokuCurriculum",
50-
"SudokuDataset",
5149
"SokobanConfig",
5250
"SokobanCurriculum",
5351
"SokobanDataset",
52+
"SudokuConfig",
53+
"SudokuCurriculum",
54+
"SudokuDataset",
55+
"SurvoConfig",
56+
"SurvoCurriculum",
57+
"SurvoDataset",
5458
"RushHourConfig",
5559
"RushHourCurriculum",
5660
"RushHourDataset",

reasoning_gym/games/survo.py

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
"""
2+
Survo dataset, adapted for Reasoning Gym from SynthRL: https://github.com/MiniMax-AI/SynLogic/tree/main/games/tasks/survo
3+
"""
4+
5+
from dataclasses import dataclass
6+
from random import Random
7+
from typing import Any, Optional
8+
9+
import numpy as np
10+
11+
from ..coaching import BaseCurriculum, RangeAttributeDefinition
12+
from ..factory import ProceduralDataset, register_dataset
13+
14+
DATASET_NAME = "survo"
15+
16+
PROMPT_TEMPLATES = [
17+
"Given a {n}*{n} matrix where the last element of each row and column equals the sum of the other elements in that row or column. The matrix is:\n{matrix}\nwhere some elements are replaced with 0. You have a set of numbers {numbers} that can be filled into the 0 positions to satisfy the rules. Please fill in the matrix. Each number can only be used once.",
18+
"You have a {n}*{n} matrix with some positions already filled with numbers and others marked with 0. The matrix is:\n{matrix}\nThe last number in each row and column represents the sum of all other numbers in that row or column. You need to fill in the 0 positions using the numbers {numbers} to satisfy these conditions. Each number can only be used once.",
19+
"Complete the following Survo puzzle. In this {n}*{n} matrix:\n{matrix}\nthe cells marked with 0 need to be filled with numbers. The last number in each row and column equals the sum of all other numbers in that row or column. You can use the following numbers: {numbers}. Each number can only be used once.",
20+
"In this {n}*{n} Survo matrix puzzle:\n{matrix}\nthe 0 cells need to be filled with numbers from the set {numbers}. The last element in each row and column is the sum of all other elements in that row or column. Each number can only be used once. Provide the completed matrix.",
21+
"Solve this {n}*{n} matrix puzzle:\n{matrix}\nwhere 0 represents empty cells that need to be filled. The last number in each row and column equals the sum of all other numbers in that row or column. You have the numbers {numbers} to place in the empty cells. Each number can only be used once.",
22+
]
23+
24+
25+
@dataclass
26+
class SurvoConfig:
27+
min_board_size: int = 4
28+
max_board_size: int = 5
29+
min_empty: int = 3
30+
max_empty: int = 5
31+
min_num: int = 1
32+
max_num: int = 9
33+
seed: Optional[int] = None
34+
size: int = 500 # Virtual dataset size
35+
36+
def validate(self):
37+
"""Validate configuration parameters"""
38+
assert self.min_board_size > 3, "min_board_size must be greater than 3"
39+
assert self.max_board_size >= self.min_board_size, "max_board_size must be >= min_board_size"
40+
assert self.min_empty > 0, "min_empty must be > 0"
41+
assert self.max_empty <= (self.min_board_size - 1) * (
42+
self.min_board_size - 1
43+
), f"max_empty must be <= {(self.min_board_size - 1) * (self.min_board_size - 1)}"
44+
assert self.min_empty <= self.max_empty, "min_empty must be <= max_empty"
45+
assert self.min_num > 0, "min_num must be > 0"
46+
assert self.min_num < self.max_num, "min_num must be less than max_num"
47+
48+
49+
class SurvoDataset(ProceduralDataset):
50+
def __init__(self, config: SurvoConfig):
51+
super().__init__(config=config, seed=config.seed, size=config.size)
52+
53+
def __len__(self) -> int:
54+
return self.config.size
55+
56+
def __iter__(self):
57+
self._current_idx = 0
58+
return self
59+
60+
def __next__(self):
61+
if self._current_idx >= self.config.size:
62+
raise StopIteration
63+
item = self[self._current_idx]
64+
self._current_idx += 1
65+
return item
66+
67+
def __getitem__(self, idx: int) -> dict:
68+
rng = Random(self.config.seed + idx)
69+
70+
board_size = rng.randint(self.config.min_board_size, self.config.max_board_size)
71+
num_empty = rng.randint(self.config.min_empty, self.config.max_empty)
72+
73+
filled_matrix, puzzle, candidate_numbers = self._generate_valid_matrix(
74+
rng, board_size, num_empty, self.config.min_num, self.config.max_num
75+
)
76+
77+
puzzle_str = "\n".join(" ".join(str(x) for x in row) for row in puzzle)
78+
solution_str = "\n".join(" ".join(str(x) for x in row) for row in filled_matrix)
79+
80+
question = rng.choice(PROMPT_TEMPLATES).format(n=board_size, matrix=puzzle_str, numbers=candidate_numbers)
81+
82+
return {
83+
"question": question,
84+
"answer": solution_str,
85+
"metadata": {
86+
"source_dataset": DATASET_NAME,
87+
"source_idx": idx,
88+
"puzzle": puzzle.tolist(),
89+
"solution": filled_matrix.tolist(),
90+
"candidate_numbers": candidate_numbers,
91+
"board_size": board_size,
92+
"num_empty": num_empty,
93+
"min_num": self.config.min_num,
94+
"max_num": self.config.max_num,
95+
"difficulty": {
96+
"board_size": (self.config.min_board_size, self.config.max_board_size),
97+
"empty": (self.config.min_empty, self.config.max_empty),
98+
},
99+
},
100+
}
101+
102+
def _generate_valid_matrix(
103+
self, rng: Random, n: int, num_empty: int, min_num: int, max_num: int
104+
) -> tuple[np.ndarray, np.ndarray, list[int]]:
105+
matrix = np.zeros((n, n), dtype=int)
106+
107+
for i in range(n - 1):
108+
for j in range(n - 1):
109+
matrix[i, j] = rng.randint(min_num, max_num)
110+
111+
for i in range(n - 1):
112+
row_sum = sum(matrix[i, 0 : n - 1])
113+
matrix[i, n - 1] = row_sum
114+
115+
col_sum = sum(matrix[0 : n - 1, i])
116+
matrix[n - 1, i] = col_sum
117+
118+
matrix[n - 1, n - 1] = sum(matrix[0 : n - 1, n - 1])
119+
120+
filled_matrix = matrix.copy()
121+
122+
positions = [(i, j) for i in range(n - 1) for j in range(n - 1)]
123+
selected_positions = rng.sample(positions, num_empty)
124+
125+
candidate_numbers = []
126+
for i, j in selected_positions:
127+
candidate_numbers.append(int(matrix[i, j]))
128+
matrix[i, j] = 0
129+
130+
return filled_matrix, matrix, candidate_numbers
131+
132+
def score_answer(self, answer: Optional[str], entry: dict[str, Any]) -> float:
133+
if not isinstance(answer, str):
134+
return 0.0
135+
136+
board_size = entry["metadata"]["board_size"]
137+
grid = self._parse_grid(answer)
138+
true_grid = entry["metadata"]["solution"]
139+
140+
if len(grid) != board_size or any(len(row) != board_size for row in grid):
141+
return 0.0
142+
143+
for i in range(board_size):
144+
for j in range(board_size):
145+
if grid[i][j] != true_grid[i][j]:
146+
return 0.0
147+
148+
return 1.0
149+
150+
def _parse_grid(self, answer: str) -> list[list[str]]:
151+
grid = []
152+
for line in answer.strip().split("\n"):
153+
row = []
154+
for c in line.strip().split():
155+
try:
156+
row.append(int(c))
157+
except ValueError:
158+
continue # Ignore non-integer values
159+
if row:
160+
grid.append(row)
161+
return grid
162+
163+
164+
class SurvoCurriculum(BaseCurriculum):
165+
def __init__(self):
166+
super().__init__(SurvoCurriculum.__name__, SurvoConfig)
167+
168+
self._define_attributes(
169+
RangeAttributeDefinition(
170+
name="board_size",
171+
levels=[4, 5, 6, 7],
172+
description="Board size (n x n)",
173+
lower_field_name="min_board_size",
174+
upper_field_name="max_board_size",
175+
),
176+
RangeAttributeDefinition(
177+
name="empty",
178+
levels=[4, 9, 16, 25],
179+
description="Number of empty cells",
180+
lower_field_name="min_empty",
181+
upper_field_name="max_empty",
182+
),
183+
)
184+
185+
186+
register_dataset(DATASET_NAME, SurvoDataset, SurvoConfig, SurvoCurriculum)

tests/test_survo.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import numpy as np
2+
import pytest
3+
4+
from reasoning_gym.coaching.base_curriculum import DefaultCurriculumContext, RangeAttributeMode
5+
from reasoning_gym.games import SurvoConfig, SurvoCurriculum, SurvoDataset
6+
7+
8+
def test_survo_config_validation():
9+
"""Bad configs should raise."""
10+
# min_board_size must be > 3
11+
with pytest.raises(AssertionError):
12+
SurvoConfig(min_board_size=3).validate()
13+
14+
# max_board_size must be ≥ min_board_size
15+
with pytest.raises(AssertionError):
16+
SurvoConfig(min_board_size=6, max_board_size=5).validate()
17+
18+
# min_empty ≤ max_empty and within board-area limits
19+
with pytest.raises(AssertionError):
20+
SurvoConfig(min_empty=6, max_empty=5).validate()
21+
22+
# min_num < max_num
23+
with pytest.raises(AssertionError):
24+
SurvoConfig(min_num=5, max_num=5).validate()
25+
26+
27+
def test_survo_deterministic():
28+
"""Same seed ⇒ identical items."""
29+
cfg = SurvoConfig(seed=123, size=15, min_board_size=4, max_board_size=5, min_empty=3, max_empty=5)
30+
ds1, ds2 = SurvoDataset(cfg), SurvoDataset(cfg)
31+
32+
for i in range(len(ds1)):
33+
assert ds1[i] == ds2[i]
34+
35+
36+
def test_survo_items():
37+
"""Generated items have expected structure and metadata."""
38+
cfg = SurvoConfig(seed=99, size=20, min_board_size=4, max_board_size=5, min_empty=3, max_empty=5)
39+
ds = SurvoDataset(cfg)
40+
41+
for itm in ds:
42+
md = itm["metadata"]
43+
44+
# Basic keys
45+
assert set(itm.keys()) == {"question", "answer", "metadata"}
46+
assert "puzzle" in md and "solution" in md and "candidate_numbers" in md
47+
48+
orig = np.array(md["puzzle"])
49+
full = np.array(md["solution"])
50+
51+
# Dimensions
52+
n = full.shape[0]
53+
assert cfg.min_board_size <= n <= cfg.max_board_size
54+
assert orig.shape == full.shape == (n, n)
55+
56+
# Number of empties
57+
empties = np.count_nonzero(orig == 0)
58+
assert empties == md["num_empty"]
59+
assert cfg.min_empty <= empties <= cfg.max_empty
60+
61+
# Candidate numbers should match removed values (order disregarded)
62+
removed_values = full[orig == 0].tolist()
63+
assert sorted(removed_values) == sorted(md["candidate_numbers"])
64+
65+
66+
def test_survo_solution_validity():
67+
"""Solution must satisfy Survo row/column-sum rules."""
68+
cfg = SurvoConfig(seed=321, size=10, min_board_size=4, max_board_size=5, min_empty=3, max_empty=5)
69+
ds = SurvoDataset(cfg)
70+
71+
for itm in ds:
72+
m = np.array(itm["metadata"]["solution"])
73+
n = m.shape[0]
74+
75+
# Row sums (exclude last row)
76+
for r in range(n - 1):
77+
assert m[r, : n - 1].sum() == m[r, n - 1]
78+
79+
# Column sums (exclude last col)
80+
for c in range(n - 1):
81+
assert m[: n - 1, c].sum() == m[n - 1, c]
82+
83+
# Grand total cell
84+
assert m[n - 1, n - 1] == m[: n - 1, n - 1].sum()
85+
86+
87+
def test_survo_difficulty_levels():
88+
"""More allowed empties ⇒ puzzles have, on average, more blank cells."""
89+
seed, n_items, board = 777, 8, 5
90+
91+
def avg_empties(min_empty, max_empty):
92+
cfg = SurvoConfig(
93+
seed=seed,
94+
size=n_items,
95+
min_board_size=board,
96+
max_board_size=board,
97+
min_empty=min_empty,
98+
max_empty=max_empty,
99+
)
100+
ds = SurvoDataset(cfg)
101+
return np.mean([np.count_nonzero(np.array(itm["metadata"]["puzzle"]) == 0) for itm in ds])
102+
103+
low = avg_empties(3, 3)
104+
mid = avg_empties(6, 6)
105+
high = avg_empties(10, 10)
106+
107+
assert low < mid < high
108+
109+
110+
def test_survo_answer_scoring():
111+
"""Correct answer ⇒ 1.0; variations score lower."""
112+
cfg = SurvoConfig(seed=42, size=5, min_board_size=4, max_board_size=4, min_empty=3, max_empty=3)
113+
ds = SurvoDataset(cfg)
114+
115+
for itm in ds:
116+
correct = itm["answer"]
117+
assert ds.score_answer(correct, itm) == 1.0
118+
119+
# Tamper with a single cell
120+
candidate_numbers = itm["metadata"]["candidate_numbers"]
121+
wrong = correct.replace(str(candidate_numbers[0]), str(max(candidate_numbers) + 1), 1)
122+
assert ds.score_answer(wrong, itm) < 1.0
123+
124+
# Bad type / empty
125+
assert ds.score_answer(None, itm) == 0.0
126+
assert ds.score_answer("", itm) == 0.0
127+
128+
129+
def test_survo_curriculum():
130+
"""SurvoCurriculum controls board size and empties as advertised."""
131+
cur = SurvoCurriculum()
132+
base_val = {"size": 100, "seed": 1}
133+
ctx = DefaultCurriculumContext(mode=RangeAttributeMode.UPPER_BOUND)
134+
135+
# Level 0
136+
cfg0: SurvoConfig = cur.generate_configuration(base_val, context=ctx)
137+
assert cfg0.min_board_size == cfg0.max_board_size == 4
138+
assert cfg0.min_empty == cfg0.max_empty == 4
139+
140+
# Increment levels
141+
cur.increment_attr_level("board_size")
142+
cur.increment_attr_level("empty")
143+
cfg1: SurvoConfig = cur.generate_configuration(base_val, context=ctx)
144+
assert cfg1.min_board_size == cfg1.max_board_size == 5
145+
assert cfg1.min_empty == cfg1.max_empty == 9
146+
147+
# Global progression
148+
cur.set_global_level(3)
149+
cfg_max: SurvoConfig = cur.generate_configuration(base_val, context=ctx)
150+
assert cfg_max.min_board_size == cfg_max.max_board_size == 7
151+
assert cfg_max.min_empty == cfg_max.max_empty == 25

0 commit comments

Comments
 (0)