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
229
230
231
232 | def extract_board_features(
board: List[int],
solved_map: Dict[str, dict],
lambda_temp: float = 0.5,
q_temp: float = 1.0,
epsilons: Optional[List[float]] = None,
normalize_to_move: bool = False,
) -> Dict[str, Any]:
"""Extract features for a board.
By default, features are computed on the board as given.
If normalize_to_move=True, we remap pieces so the side-to-move becomes X=1.
Note: Policies and q-values are derived from the original board's solver
output. Normalization only swaps labels 1<->2; legality and q-values align
by construction because moves are on indices, not on piece IDs.
"""
if epsilons is None:
epsilons = [0.1]
to_move = 1 if board.count(1) == board.count(2) else 2
if normalize_to_move and to_move == 2:
# swap X and O labels to make current player X
normalized_board = [0 if v == 0 else (1 if v == 2 else 2) for v in board]
current_player = 1
else:
normalized_board = board[:]
current_player = to_move
x_count, o_count = get_piece_counts(normalized_board)
winner_raw = get_winner(board)
winner_norm = get_winner(normalized_board)
key = serialize_board(board)
norm_key = serialize_board(normalized_board)
reachable = key in solved_map
if reachable:
sol = solved_map[key]
value_current = sol["value"]
plies_to_end = sol["plies_to_end"]
optimal_moves = set(sol["optimal_moves"])
qvals = list(sol["q_values"])
dtt_a = list(sol["dtt_action"])
policy_targets = build_policy_targets(
normalized_board, sol, lambda_temp=lambda_temp, q_temp=q_temp
)
pol_uniform = policy_targets["policy_optimal_uniform"]
pol_soft = policy_targets["policy_soft_dtt"]
pol_soft_q = policy_targets["policy_soft_q"]
eps_policies = {}
for eps in epsilons:
tag = f"{int(round(eps*100)):03d}"
eps_policies[tag] = epsilon_policy_distribution(normalized_board, sol, eps)
pol_entropy = -sum(p * np.log(p + 1e-10) for p in pol_uniform if p > 0)
pol_soft_dtt_entropy = -sum(p * np.log(p + 1e-10) for p in pol_soft if p > 0)
child_tiers = {
"child_wins": sum(1 for v in qvals if v == +1),
"child_draws": sum(1 for v in qvals if v == 0),
"child_losses": sum(1 for v in qvals if v == -1),
}
difficulty = difficulty_score(sol)
# optional: compute reply branching factor as the average number of
# legal replies for the opponent after optimal moves. Keep lightweight
# and deterministic. If no optimal moves, 0.0. Terminal children
# contribute 0 by definition (no replies).
legal_reply_counts: List[int] = []
for mv in optimal_moves:
child = board[:]
child[mv] = 1 if board.count(1) == board.count(2) else 2
if get_winner(child) != 0 or is_draw(child):
legal_reply_counts.append(0)
else:
legal_reply_counts.append(sum(1 for v in child if v == 0))
reply_branching = (
float(sum(legal_reply_counts) / len(legal_reply_counts)) if legal_reply_counts else 0.0
)
else:
value_current = None
plies_to_end = None
optimal_moves = set()
qvals = [None] * 9
dtt_a = [None] * 9
pol_uniform = [None] * 9
pol_soft = [None] * 9
pol_soft_q = [None] * 9
eps_policies = {}
pol_entropy = None
pol_soft_dtt_entropy = None
child_tiers = {"child_wins": 0, "child_draws": 0, "child_losses": 0}
difficulty = 0.0
reply_branching = 0.0
sym = symmetry_info(board)
legal = [normalized_board[i] == 0 for i in range(9)]
best_mask = [(i in optimal_moves) for i in range(9)] if reachable else [False] * 9
cell_pot = calculate_cell_line_potentials(normalized_board)
# Extended positional/strategic features (deterministic and cheap)
# Use the normalized_board for player-relative metrics
x_threats = calculate_line_threats(normalized_board, 1)
o_threats = calculate_line_threats(normalized_board, 2)
x_conn = calculate_connectivity(normalized_board, 1)
o_conn = calculate_connectivity(normalized_board, 2)
control = calculate_control_metrics(normalized_board)
x_patterns = calculate_pattern_strength(normalized_board, 1)
o_patterns = calculate_pattern_strength(normalized_board, 2)
game_phase = calculate_game_phase(normalized_board)
x_two_open = count_two_in_row_open(normalized_board, 1)
o_two_open = count_two_in_row_open(normalized_board, 2)
features: Dict[str, Any] = {
"board_state": key,
"normalized_board_state": norm_key,
"swapped_color": int(normalize_to_move and to_move == 2),
"x_count": x_count,
"o_count": o_count,
"empty_count": normalized_board.count(0),
"move_number": x_count + o_count,
"current_player": current_player,
"is_terminal": winner_raw != 0 or is_draw(board),
"winner": winner_raw,
"winner_normalized": winner_norm,
"is_draw": is_draw(board),
"is_valid": is_valid_state(board),
"reachable_from_start": reachable,
"canonical_form": sym["canonical_form"],
"canonical_op": sym["canonical_op"],
"orbit_size": sym["orbit_size"],
"horizontal_symmetric": sym["horizontal_symmetric"],
"vertical_symmetric": sym["vertical_symmetric"],
"diagonal_symmetric": sym["diagonal_symmetric"],
"rotational_symmetric": sym["rotational_symmetric"],
"any_symmetric": sym["any_symmetric"],
"orbit_index": sym["orbit_index"],
"value_current": value_current,
"plies_to_end": plies_to_end,
"optimal_moves_count": len(optimal_moves),
"optimal_policy_entropy": pol_entropy,
"policy_soft_dtt_entropy": pol_soft_dtt_entropy,
"policy_soft_q_entropy": (
-sum(p * np.log(p + 1e-10) for p in pol_soft_q if p > 0) if reachable else None
),
# Scalar difficulty per state; 0.0 when not reachable
"difficulty_score": difficulty,
"reply_branching_factor": reply_branching,
**child_tiers,
# control metrics (symmetric)
**control,
# player-relative threats/connectivity/patterns
"x_row_threats": x_threats["row_threats"],
"x_col_threats": x_threats["col_threats"],
"x_diag_threats": x_threats["diag_threats"],
"x_total_threats": x_threats["total_threats"],
"o_row_threats": o_threats["row_threats"],
"o_col_threats": o_threats["col_threats"],
"o_diag_threats": o_threats["diag_threats"],
"o_total_threats": o_threats["total_threats"],
"x_connected_pairs": x_conn["connected_pairs"],
"x_total_connections": x_conn["total_connections"],
"x_isolated_pieces": x_conn["isolated_pieces"],
"x_cluster_count": x_conn["cluster_count"],
"x_largest_cluster": x_conn["largest_cluster"],
"o_connected_pairs": o_conn["connected_pairs"],
"o_total_connections": o_conn["total_connections"],
"o_isolated_pieces": o_conn["isolated_pieces"],
"o_cluster_count": o_conn["cluster_count"],
"o_largest_cluster": o_conn["largest_cluster"],
"x_open_lines": x_patterns["open_lines"],
"x_semi_open_lines": x_patterns["semi_open_lines"],
"x_blocked_lines": x_patterns["blocked_lines"],
"x_potential_lines": x_patterns["potential_lines"],
"o_open_lines": o_patterns["open_lines"],
"o_semi_open_lines": o_patterns["semi_open_lines"],
"o_blocked_lines": o_patterns["blocked_lines"],
"o_potential_lines": o_patterns["potential_lines"],
"x_two_in_row_open": x_two_open,
"o_two_in_row_open": o_two_open,
"game_phase": game_phase,
}
for i in range(9):
features[f"cell_{i}"] = normalized_board[i]
features[f"legal_{i}"] = int(legal[i])
features[f"best_{i}"] = int(best_mask[i])
features[f"q_value_{i}"] = qvals[i]
features[f"dtt_action_{i}"] = dtt_a[i]
features[f"canonical_action_map_{i}"] = apply_action_transform(i, sym["canonical_op"])
features[f"policy_uniform_{i}"] = pol_uniform[i] if reachable else None
features[f"policy_soft_{i}"] = pol_soft[i] if reachable else None
features[f"policy_soft_q_{i}"] = pol_soft_q[i] if reachable else None
for tag, pol in eps_policies.items() if reachable else []:
features[f"epsilon_policy_{tag}_{i}"] = pol[i]
features[f"x_cell_open_lines_{i}"] = cell_pot["x_cell_open_lines"][i]
features[f"o_cell_open_lines_{i}"] = cell_pot["o_cell_open_lines"][i]
return features
|