itr-methods 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.
Files changed (35) hide show
  1. itr_methods/__init__.py +31 -0
  2. itr_methods/__main__.py +2 -0
  3. itr_methods/_nscf/__init__.py +6 -0
  4. itr_methods/_nscf/api.py +536 -0
  5. itr_methods/_nscf/core/__init__.py +1 -0
  6. itr_methods/_nscf/core/audit_hooks.py +8 -0
  7. itr_methods/_nscf/core/config.py +240 -0
  8. itr_methods/_nscf/core/fusion_solver.py +94 -0
  9. itr_methods/_nscf/core/model.py +132 -0
  10. itr_methods/_nscf/core/penalty.py +100 -0
  11. itr_methods/_nscf/core/refit_selection.py +806 -0
  12. itr_methods/_nscf/core/solver_admm.py +279 -0
  13. itr_methods/_nscf/core/solver_alt.py +881 -0
  14. itr_methods/_nscf/core/trainer.py +309 -0
  15. itr_methods/_nscf/defaults.json +70 -0
  16. itr_methods/_nscf/estimator.py +267 -0
  17. itr_methods/_nscf/exact_prox.py +56 -0
  18. itr_methods/_validation.py +53 -0
  19. itr_methods/doctor.py +35 -0
  20. itr_methods/plotting.py +169 -0
  21. itr_methods/scaf/__init__.py +678 -0
  22. itr_methods/scaf/_solver.py +159 -0
  23. itr_methods-0.1.0.data/data/share/itr_methods/README.md +321 -0
  24. itr_methods-0.1.0.data/data/share/itr_methods/docs/NSCF_TUTORIAL.ipynb +1500 -0
  25. itr_methods-0.1.0.data/data/share/itr_methods/docs/SCAF_TUTORIAL.ipynb +1408 -0
  26. itr_methods-0.1.0.data/data/share/itr_methods/examples/nscf_dendrogram_figure.py +75 -0
  27. itr_methods-0.1.0.data/data/share/itr_methods/examples/quickstart.py +38 -0
  28. itr_methods-0.1.0.data/data/share/itr_methods/examples/scaf_path_figure.py +56 -0
  29. itr_methods-0.1.0.dist-info/METADATA +347 -0
  30. itr_methods-0.1.0.dist-info/RECORD +35 -0
  31. itr_methods-0.1.0.dist-info/WHEEL +5 -0
  32. itr_methods-0.1.0.dist-info/entry_points.txt +2 -0
  33. itr_methods-0.1.0.dist-info/licenses/LICENSE +408 -0
  34. itr_methods-0.1.0.dist-info/licenses/NOTICE.txt +24 -0
  35. itr_methods-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,806 @@
1
+ # refit_selection.py
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import csv
7
+ from pathlib import Path
8
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
9
+
10
+ import numpy as np
11
+
12
+
13
+ ArrayLike = np.ndarray
14
+
15
+
16
+ def _to_numpy(x: Any) -> np.ndarray:
17
+ """
18
+ Convert input to numpy array without forcing a copy when possible.
19
+ """
20
+ if isinstance(x, np.ndarray):
21
+ return x
22
+ return np.asarray(x)
23
+
24
+
25
+ def _safe_float(x: Any) -> float:
26
+ """
27
+ Convert scalar-like object to float.
28
+ Handles python float, numpy scalar, torch scalar, etc.
29
+ """
30
+ try:
31
+ return float(x)
32
+ except Exception:
33
+ if hasattr(x, "item"):
34
+ return float(x.item())
35
+ raise
36
+
37
+
38
+ def _row_close(a: np.ndarray, b: np.ndarray, tol: float) -> bool:
39
+ """
40
+ Compare two 1D vectors using max absolute deviation.
41
+ """
42
+ return np.max(np.abs(a - b)) <= tol
43
+
44
+
45
+ def count_groups_from_group_ids(group_ids: np.ndarray) -> int:
46
+ """
47
+ Return number of unique groups from group id vector.
48
+ """
49
+ group_ids = _to_numpy(group_ids).astype(int)
50
+ if group_ids.size == 0:
51
+ return 0
52
+ return int(group_ids.max()) + 1
53
+
54
+
55
+ def partition_signature(group_ids: np.ndarray) -> Tuple[int, ...]:
56
+ """
57
+ Signature for deduplicating partitions.
58
+ """
59
+ group_ids = _to_numpy(group_ids).astype(int)
60
+ return tuple(group_ids.tolist())
61
+
62
+
63
+ def groups_from_group_ids(group_ids: np.ndarray) -> List[List[int]]:
64
+ """
65
+ Convert group id vector to list of groups.
66
+ Example:
67
+ group_ids = [0,0,1,1,1] -> [[0,1],[2,3,4]]
68
+ """
69
+ group_ids = _to_numpy(group_ids).astype(int)
70
+ if group_ids.ndim != 1:
71
+ raise ValueError(f"group_ids must be 1D, got shape={group_ids.shape}")
72
+
73
+ n_groups = count_groups_from_group_ids(group_ids)
74
+ groups: List[List[int]] = []
75
+ for g in range(n_groups):
76
+ members = np.where(group_ids == g)[0].tolist()
77
+ groups.append(members)
78
+ return groups
79
+
80
+
81
+ def extract_partition_from_Z(
82
+ Z: np.ndarray,
83
+ tol: float = 1e-6,
84
+ round_decimals: int = 6,
85
+ ) -> Tuple[List[List[int]], np.ndarray]:
86
+ """
87
+ Extract partition from fused treatment representation Z.
88
+
89
+ Parameters
90
+ ----------
91
+ Z : np.ndarray, shape (K, r)
92
+ Row k corresponds to treatment k.
93
+ tol : float
94
+ Max absolute difference threshold for saying two rows are same group.
95
+ round_decimals : int
96
+ Optional row rounding before grouping, helps stabilize floating comparisons.
97
+
98
+ Returns
99
+ -------
100
+ groups : list[list[int]]
101
+ Group membership list.
102
+ group_ids : np.ndarray, shape (K,)
103
+ group_ids[k] = group index for treatment k.
104
+ """
105
+ Z = _to_numpy(Z)
106
+ if Z.ndim != 2:
107
+ raise ValueError(f"Z must be 2D, got shape={Z.shape}")
108
+
109
+ Zr = np.round(Z, round_decimals)
110
+ K = Zr.shape[0]
111
+
112
+ unique_rows: List[np.ndarray] = []
113
+ group_ids = np.full(K, -1, dtype=int)
114
+
115
+ for k in range(K):
116
+ row = Zr[k]
117
+ assigned = False
118
+ for g, u in enumerate(unique_rows):
119
+ if _row_close(row, u, tol=tol):
120
+ group_ids[k] = g
121
+ assigned = True
122
+ break
123
+ if not assigned:
124
+ unique_rows.append(row.copy())
125
+ group_ids[k] = len(unique_rows) - 1
126
+
127
+ groups = groups_from_group_ids(group_ids)
128
+ return groups, group_ids
129
+
130
+
131
+ def map_actions_to_groups(A, group_ids):
132
+ """
133
+ Map original treatment/action ids to grouped action ids.
134
+
135
+ If A is a torch tensor, return a torch tensor on the same device.
136
+ If A is a numpy array / list, return a numpy array.
137
+ """
138
+ import numpy as np
139
+
140
+ # torch input -> torch output
141
+ try:
142
+ import torch
143
+ is_torch = torch.is_tensor(A)
144
+ except Exception:
145
+ torch = None
146
+ is_torch = False
147
+
148
+ group_ids_np = np.asarray(group_ids).astype(int)
149
+
150
+ if is_torch:
151
+ A_np = A.detach().cpu().numpy().astype(int)
152
+
153
+ if A_np.ndim != 1:
154
+ raise ValueError(f"A must be 1D, got shape={A_np.shape}")
155
+
156
+ if A_np.size > 0:
157
+ if A_np.min() < 0 or A_np.max() >= len(group_ids_np):
158
+ raise ValueError(
159
+ f"A contains invalid treatment ids. "
160
+ f"Allowed range is [0, {len(group_ids_np)-1}], got [{A_np.min()}, {A_np.max()}]."
161
+ )
162
+
163
+ out_np = group_ids_np[A_np]
164
+ return torch.as_tensor(out_np, device=A.device, dtype=A.dtype)
165
+
166
+ # numpy / list input -> numpy output
167
+ A_np = np.asarray(A).astype(int)
168
+
169
+ if A_np.ndim != 1:
170
+ raise ValueError(f"A must be 1D, got shape={A_np.shape}")
171
+
172
+ if A_np.size > 0:
173
+ if A_np.min() < 0 or A_np.max() >= len(group_ids_np):
174
+ raise ValueError(
175
+ f"A contains invalid treatment ids. "
176
+ f"Allowed range is [0, {len(group_ids_np)-1}], got [{A_np.min()}, {A_np.max()}]."
177
+ )
178
+
179
+ return group_ids_np[A_np]
180
+
181
+
182
+ def remap_group_ids_sequential(group_ids: np.ndarray) -> np.ndarray:
183
+ """
184
+ Ensure group ids are 0,1,...,G-1 in appearance order.
185
+
186
+ Example:
187
+ [2,2,5,5,9] -> [0,0,1,1,2]
188
+ """
189
+ group_ids = _to_numpy(group_ids).astype(int)
190
+ mapping: Dict[int, int] = {}
191
+ new_ids = np.empty_like(group_ids)
192
+
193
+ nxt = 0
194
+ for i, g in enumerate(group_ids):
195
+ if g not in mapping:
196
+ mapping[g] = nxt
197
+ nxt += 1
198
+ new_ids[i] = mapping[g]
199
+ return new_ids
200
+
201
+
202
+ def _copy_matching_module(dst: Any, src: Any, name: str) -> None:
203
+ """
204
+ Copy one submodule state when both models expose it.
205
+ """
206
+ dst_mod = getattr(dst, name, None)
207
+ src_mod = getattr(src, name, None)
208
+ if dst_mod is None or src_mod is None:
209
+ return
210
+ dst_mod.load_state_dict(src_mod.state_dict())
211
+
212
+
213
+ def initialize_grouped_model_from_source(
214
+ target_model: Any,
215
+ source_model: Any,
216
+ group_ids: np.ndarray,
217
+ ) -> None:
218
+ """
219
+ Warm-start a grouped model from a full treatment model.
220
+
221
+ Backbone and baseline are copied directly.
222
+ Group-level gamma rows are initialized by averaging source gamma rows
223
+ within each selected group.
224
+ """
225
+ import torch
226
+
227
+ group_ids = remap_group_ids_sequential(group_ids)
228
+ n_groups = count_groups_from_group_ids(group_ids)
229
+
230
+ with torch.no_grad():
231
+ _copy_matching_module(target_model, source_model, "fc1")
232
+ _copy_matching_module(target_model, source_model, "fc2")
233
+ _copy_matching_module(target_model, source_model, "m_head")
234
+
235
+ src_gamma = source_model.gamma.weight.detach().to(
236
+ device=target_model.gamma.weight.device,
237
+ dtype=target_model.gamma.weight.dtype,
238
+ )
239
+ tgt_gamma = target_model.gamma.weight
240
+
241
+ if tgt_gamma.shape[0] != n_groups:
242
+ raise ValueError(
243
+ f"target grouped gamma has {tgt_gamma.shape[0]} rows but "
244
+ f"group_ids imply {n_groups} groups"
245
+ )
246
+
247
+ for g in range(n_groups):
248
+ members = np.where(group_ids == g)[0]
249
+ if len(members) == 0:
250
+ continue
251
+ idx = torch.as_tensor(
252
+ members.tolist(),
253
+ device=src_gamma.device,
254
+ dtype=torch.long,
255
+ )
256
+ tgt_gamma[g].copy_(src_gamma.index_select(0, idx).mean(dim=0))
257
+
258
+
259
+ def run_grouped_refit(
260
+ *,
261
+ model_class: Callable[..., Any],
262
+ train_fn: Callable[..., Any],
263
+ eval_fn: Callable[..., Any],
264
+ X_train: Any,
265
+ A_train: Any,
266
+ y_train: Any,
267
+ X_val: Any,
268
+ A_val: Any,
269
+ y_val: Any,
270
+ group_ids: np.ndarray,
271
+ model_kwargs: Optional[Dict[str, Any]] = None,
272
+ train_kwargs: Optional[Dict[str, Any]] = None,
273
+ model_n_actions_key: str = "n_actions",
274
+ init_model: Optional[Any] = None,
275
+ ) -> Dict[str, Any]:
276
+ """
277
+ Refit a model under a fixed partition.
278
+
279
+ Parameters
280
+ ----------
281
+ model_class : callable
282
+ Your model constructor, e.g. Net
283
+ train_fn : callable
284
+ Your supervised training function
285
+ Expected use:
286
+ model_out = train_fn(model, X_train, A_train_g, y_train, X_val, A_val_g, y_val, **train_kwargs)
287
+ or
288
+ model, hist = train_fn(...)
289
+ eval_fn : callable
290
+ Your evaluation function returning validation MSE or scalar loss
291
+ Expected use:
292
+ eval_fn(model, X_val, A_val_g, y_val)
293
+ model_n_actions_key : str
294
+ Constructor kwarg name for number of actions/groups. Usually 'n_actions'.
295
+
296
+ Returns
297
+ -------
298
+ dict with keys:
299
+ model, val_mse, n_groups, group_ids, train_output
300
+ """
301
+ model_kwargs = copy.deepcopy(model_kwargs or {})
302
+ train_kwargs = copy.deepcopy(train_kwargs or {})
303
+
304
+ group_ids = remap_group_ids_sequential(group_ids)
305
+ n_groups = count_groups_from_group_ids(group_ids)
306
+
307
+ A_train_g = map_actions_to_groups(A_train, group_ids)
308
+ A_val_g = map_actions_to_groups(A_val, group_ids)
309
+
310
+ model_kwargs[model_n_actions_key] = n_groups
311
+ model = model_class(**model_kwargs)
312
+ if init_model is not None:
313
+ initialize_grouped_model_from_source(model, init_model, group_ids)
314
+
315
+ train_output = train_fn(
316
+ model,
317
+ X_train, A_train_g, y_train,
318
+ X_val, A_val_g, y_val,
319
+ **train_kwargs,
320
+ )
321
+
322
+ # Default: training happens in-place
323
+ trained_model = model
324
+
325
+ # Optional compatibility:
326
+ # if train_fn explicitly returns a model, use it
327
+ try:
328
+ import torch.nn as nn
329
+ if isinstance(train_output, nn.Module):
330
+ trained_model = train_output
331
+ elif isinstance(train_output, tuple) and len(train_output) > 0:
332
+ if isinstance(train_output[0], nn.Module):
333
+ trained_model = train_output[0]
334
+ except Exception:
335
+ pass
336
+
337
+ val_mse = eval_fn(trained_model, X_val, A_val_g, y_val)
338
+
339
+ return {
340
+ "model": trained_model,
341
+ "val_mse": _safe_float(val_mse),
342
+ "n_groups": n_groups,
343
+ "group_ids": group_ids.copy(),
344
+ "train_output": train_output,
345
+ }
346
+
347
+
348
+ def eval_grouped_model_on_original_actions(
349
+ model: Any,
350
+ eval_fn: Callable[..., Any],
351
+ X: Any,
352
+ A: Any,
353
+ y: Any,
354
+ group_ids: np.ndarray,
355
+ ) -> float:
356
+ """
357
+ Evaluate a grouped model on original treatment ids by remapping actions first.
358
+ """
359
+ A_grouped = map_actions_to_groups(A, group_ids)
360
+ return _safe_float(eval_fn(model, X, A_grouped, y))
361
+
362
+
363
+ def evaluate_lambda_path_with_refit(
364
+ *,
365
+ Z_path: np.ndarray,
366
+ lambda_values: Sequence[float],
367
+ model_class: Callable[..., Any],
368
+ train_fn: Callable[..., Any],
369
+ eval_fn: Callable[..., Any],
370
+ X_train: Any,
371
+ A_train: Any,
372
+ y_train: Any,
373
+ X_val: Any,
374
+ A_val: Any,
375
+ y_val: Any,
376
+ model_kwargs: Optional[Dict[str, Any]] = None,
377
+ train_kwargs: Optional[Dict[str, Any]] = None,
378
+ init_model: Optional[Any] = None,
379
+ partition_tol: float = 1e-6,
380
+ round_decimals: int = 6,
381
+ dedup_partitions: bool = True,
382
+ model_n_actions_key: str = "n_actions",
383
+ baseline_mse: Optional[float] = None,
384
+ verbose: bool = True,
385
+ log_fn=print,
386
+ ) -> List[Dict[str, Any]]:
387
+ """
388
+ Evaluate every lambda on the path via grouped refit.
389
+
390
+ Parameters
391
+ ----------
392
+ Z_path : np.ndarray, shape (L, K, r)
393
+ Path of fused representations.
394
+ lambda_values : sequence length L
395
+ dedup_partitions : bool
396
+ If True, identical partitions are refit only once and reused.
397
+
398
+ Returns
399
+ -------
400
+ results : list[dict]
401
+ Each dict contains:
402
+ lambda_idx
403
+ lambda
404
+ groups
405
+ group_ids
406
+ n_groups
407
+ refit_val_mse
408
+ refit_model
409
+ reused_from_idx (optional)
410
+ """
411
+ Z_path = _to_numpy(Z_path)
412
+ if Z_path.ndim != 3:
413
+ raise ValueError(f"Z_path must be 3D (L, K, r), got shape={Z_path.shape}")
414
+
415
+ L = Z_path.shape[0]
416
+ if len(lambda_values) != L:
417
+ raise ValueError(
418
+ f"lambda_values length {len(lambda_values)} does not match Z_path length {L}"
419
+ )
420
+
421
+ results: List[Dict[str, Any]] = []
422
+ cache: Dict[Tuple[int, ...], Dict[str, Any]] = {}
423
+
424
+ for i in range(L):
425
+ lam = _safe_float(lambda_values[i])
426
+ Z = Z_path[i]
427
+
428
+ groups, group_ids = extract_partition_from_Z(
429
+ Z,
430
+ tol=partition_tol,
431
+ round_decimals=round_decimals,
432
+ )
433
+ group_ids = remap_group_ids_sequential(group_ids)
434
+ sig = partition_signature(group_ids)
435
+
436
+ reused_from_idx: Optional[int] = None
437
+
438
+ if dedup_partitions and sig in cache:
439
+ cached = cache[sig]
440
+ refit_model = cached["refit_model"]
441
+ refit_val_mse = cached["refit_val_mse"]
442
+ n_groups = cached["n_groups"]
443
+ reused_from_idx = cached["lambda_idx"]
444
+ else:
445
+ out = run_grouped_refit(
446
+ model_class=model_class,
447
+ train_fn=train_fn,
448
+ eval_fn=eval_fn,
449
+ X_train=X_train,
450
+ A_train=A_train,
451
+ y_train=y_train,
452
+ X_val=X_val,
453
+ A_val=A_val,
454
+ y_val=y_val,
455
+ group_ids=group_ids,
456
+ model_kwargs=model_kwargs,
457
+ train_kwargs=train_kwargs,
458
+ model_n_actions_key=model_n_actions_key,
459
+ init_model=init_model,
460
+ )
461
+ refit_model = out["model"]
462
+ refit_val_mse = out["val_mse"]
463
+ n_groups = out["n_groups"]
464
+
465
+ if dedup_partitions:
466
+ cache[sig] = {
467
+ "lambda_idx": i,
468
+ "refit_model": refit_model,
469
+ "refit_val_mse": refit_val_mse,
470
+ "n_groups": n_groups,
471
+ }
472
+
473
+ row = {
474
+ "lambda_idx": i,
475
+ "lambda": lam,
476
+ "groups": groups,
477
+ "group_ids": group_ids.copy(),
478
+ "n_groups": int(n_groups),
479
+ "refit_val_mse": float(refit_val_mse),
480
+ "delta_vs_baseline": (
481
+ float(refit_val_mse) - float(baseline_mse)
482
+ if baseline_mse is not None else None
483
+ ),
484
+ "refit_model": refit_model,
485
+ "reused_from_idx": reused_from_idx,
486
+ }
487
+ results.append(row)
488
+
489
+ if verbose:
490
+ reuse_msg = f" [reused from {reused_from_idx}]" if reused_from_idx is not None else ""
491
+ log_fn(
492
+ f"[refit] idx={i:03d} lambda={lam:.6g} "
493
+ f"groups={n_groups} val_mse={refit_val_mse:.6f}{reuse_msg}"
494
+ )
495
+
496
+ return results
497
+
498
+
499
+ def pick_lambda_by_refit_min(
500
+ refit_results: Sequence[Dict[str, Any]],
501
+ ) -> int:
502
+ """
503
+ Pick lambda with smallest refit_val_mse.
504
+ Tie-break:
505
+ 1) smaller n_groups
506
+ 2) smaller lambda_idx
507
+ """
508
+ if len(refit_results) == 0:
509
+ raise ValueError("refit_results is empty")
510
+
511
+ best_idx = min(
512
+ range(len(refit_results)),
513
+ key=lambda i: (
514
+ refit_results[i]["refit_val_mse"],
515
+ refit_results[i]["n_groups"],
516
+ refit_results[i]["lambda_idx"],
517
+ ),
518
+ )
519
+ return int(best_idx)
520
+
521
+
522
+ def pick_lambda_by_refit_eps_simplest(
523
+ refit_results: Sequence[Dict[str, Any]],
524
+ eps: float = 0.05,
525
+ ) -> int:
526
+ """
527
+ Pick simplest partition among lambdas whose refit_val_mse is within
528
+ (1 + eps) of the minimum.
529
+
530
+ Rule:
531
+ 1) m* = min refit_val_mse
532
+ 2) candidate if mse <= m*(1+eps)
533
+ 3) among candidates choose smallest n_groups
534
+ 4) tie-break by smaller mse, then smaller lambda_idx
535
+ """
536
+ if len(refit_results) == 0:
537
+ raise ValueError("refit_results is empty")
538
+ if eps < 0:
539
+ raise ValueError(f"eps must be nonnegative, got {eps}")
540
+
541
+ mses = np.array([float(r["refit_val_mse"]) for r in refit_results], dtype=float)
542
+ best_mse = float(mses.min())
543
+ cutoff = best_mse * (1.0 + eps)
544
+
545
+ candidates = [i for i, r in enumerate(refit_results) if float(r["refit_val_mse"]) <= cutoff]
546
+ best_idx = min(
547
+ candidates,
548
+ key=lambda i: (
549
+ refit_results[i]["n_groups"],
550
+ refit_results[i]["refit_val_mse"],
551
+ refit_results[i]["lambda_idx"],
552
+ ),
553
+ )
554
+ return int(best_idx)
555
+
556
+
557
+ def pick_lambda_by_refit_improve_eps_simplest(
558
+ refit_results: Sequence[Dict[str, Any]],
559
+ baseline_mse: float,
560
+ eps: float = 0.05,
561
+ improve_tol: float = 0.0,
562
+ ) -> int:
563
+ """
564
+ Prefer partitions that do not underperform the baseline model.
565
+
566
+ Rule
567
+ ----
568
+ 1) keep lambdas with refit_val_mse <= baseline_mse + improve_tol
569
+ 2) if such candidates exist, among them keep those within (1 + eps) of the
570
+ best candidate mse, then choose the simplest partition
571
+ 3) otherwise fall back to global minimum refit_val_mse
572
+ """
573
+ if len(refit_results) == 0:
574
+ raise ValueError("refit_results is empty")
575
+
576
+ improving = [
577
+ i for i, r in enumerate(refit_results)
578
+ if float(r["refit_val_mse"]) <= float(baseline_mse) + float(improve_tol)
579
+ ]
580
+ if not improving:
581
+ return pick_lambda_by_refit_min(refit_results)
582
+
583
+ best_mse = min(float(refit_results[i]["refit_val_mse"]) for i in improving)
584
+ cutoff = best_mse * (1.0 + float(eps))
585
+ candidates = [
586
+ i for i in improving
587
+ if float(refit_results[i]["refit_val_mse"]) <= cutoff
588
+ ]
589
+ best_idx = min(
590
+ candidates,
591
+ key=lambda i: (
592
+ refit_results[i]["n_groups"],
593
+ refit_results[i]["refit_val_mse"],
594
+ refit_results[i]["lambda_idx"],
595
+ ),
596
+ )
597
+ return int(best_idx)
598
+
599
+
600
+ def pick_lambda_by_refit_improve_eps_prefer_k(
601
+ refit_results: Sequence[Dict[str, Any]],
602
+ baseline_mse: float,
603
+ eps: float = 0.05,
604
+ improve_tol: float = 0.0,
605
+ preferred_n_groups: int = 2,
606
+ ) -> int:
607
+ """
608
+ Legacy compatibility rule.
609
+
610
+ Prefer partitions whose group count is closest to ``preferred_n_groups``
611
+ among candidates that remain competitive in validation MSE.
612
+
613
+ Rule
614
+ ----
615
+ 1) keep lambdas with refit_val_mse <= baseline_mse + improve_tol
616
+ 2) among them keep those within (1 + eps) of the best improving mse
617
+ 3) choose the candidate with n_groups closest to preferred_n_groups
618
+ 4) tie-break by smaller n_groups, then smaller mse, then lambda_idx
619
+ 5) if no improving candidates exist, fall back to global minimum refit_val_mse
620
+ """
621
+ if len(refit_results) == 0:
622
+ raise ValueError("refit_results is empty")
623
+
624
+ improving = [
625
+ i for i, r in enumerate(refit_results)
626
+ if float(r["refit_val_mse"]) <= float(baseline_mse) + float(improve_tol)
627
+ ]
628
+ if not improving:
629
+ return pick_lambda_by_refit_min(refit_results)
630
+
631
+ best_mse = min(float(refit_results[i]["refit_val_mse"]) for i in improving)
632
+ cutoff = best_mse * (1.0 + float(eps))
633
+ candidates = [
634
+ i for i in improving
635
+ if float(refit_results[i]["refit_val_mse"]) <= cutoff
636
+ ]
637
+ best_idx = min(
638
+ candidates,
639
+ key=lambda i: (
640
+ abs(int(refit_results[i]["n_groups"]) - int(preferred_n_groups)),
641
+ int(refit_results[i]["n_groups"]),
642
+ float(refit_results[i]["refit_val_mse"]),
643
+ int(refit_results[i]["lambda_idx"]),
644
+ ),
645
+ )
646
+ return int(best_idx)
647
+
648
+
649
+ def pick_lambda_by_refit_score(
650
+ refit_results: Sequence[Dict[str, Any]],
651
+ alpha: float = 0.0,
652
+ ) -> int:
653
+ """
654
+ Pick lambda minimizing:
655
+ score = refit_val_mse + alpha * n_groups
656
+
657
+ Useful when you want an explicit complexity tradeoff.
658
+ """
659
+ if len(refit_results) == 0:
660
+ raise ValueError("refit_results is empty")
661
+
662
+ best_idx = min(
663
+ range(len(refit_results)),
664
+ key=lambda i: (
665
+ refit_results[i]["refit_val_mse"] + alpha * refit_results[i]["n_groups"],
666
+ refit_results[i]["refit_val_mse"],
667
+ refit_results[i]["n_groups"],
668
+ refit_results[i]["lambda_idx"],
669
+ ),
670
+ )
671
+ return int(best_idx)
672
+
673
+
674
+ def pick_lambda_by_refit(
675
+ refit_results: Sequence[Dict[str, Any]],
676
+ rule: str = "eps_simplest",
677
+ eps: float = 0.05,
678
+ alpha: float = 0.0,
679
+ baseline_mse: Optional[float] = None,
680
+ improve_tol: float = 0.0,
681
+ preferred_n_groups: int = 2,
682
+ ) -> int:
683
+ """
684
+ Unified lambda picker.
685
+
686
+ rule options
687
+ ------------
688
+ "min"
689
+ smallest refit_val_mse
690
+ "eps_simplest"
691
+ within eps of best mse, choose simplest partition
692
+ "score"
693
+ minimize refit_val_mse + alpha * n_groups
694
+ "improve_eps_simplest"
695
+ among partitions no worse than baseline + improve_tol, choose the
696
+ simplest one within eps of the best improving mse; else fall back to min
697
+ "improve_eps_prefer_k"
698
+ legacy compatibility rule; prefer the partition whose group count is
699
+ closest to preferred_n_groups within eps of the best improving mse
700
+ """
701
+ rule = rule.lower().strip()
702
+
703
+ if rule == "min":
704
+ return pick_lambda_by_refit_min(refit_results)
705
+ if rule == "eps_simplest":
706
+ return pick_lambda_by_refit_eps_simplest(refit_results, eps=eps)
707
+ if rule == "score":
708
+ return pick_lambda_by_refit_score(refit_results, alpha=alpha)
709
+ if rule == "improve_eps_simplest":
710
+ if baseline_mse is None:
711
+ raise ValueError("baseline_mse is required for improve_eps_simplest")
712
+ return pick_lambda_by_refit_improve_eps_simplest(
713
+ refit_results,
714
+ baseline_mse=baseline_mse,
715
+ eps=eps,
716
+ improve_tol=improve_tol,
717
+ )
718
+ if rule == "improve_eps_prefer_k":
719
+ if baseline_mse is None:
720
+ raise ValueError("baseline_mse is required for improve_eps_prefer_k")
721
+ return pick_lambda_by_refit_improve_eps_prefer_k(
722
+ refit_results,
723
+ baseline_mse=baseline_mse,
724
+ eps=eps,
725
+ improve_tol=improve_tol,
726
+ preferred_n_groups=preferred_n_groups,
727
+ )
728
+
729
+ raise ValueError(f"Unknown refit selection rule: {rule}")
730
+
731
+
732
+ def summarize_refit_results(
733
+ refit_results: Sequence[Dict[str, Any]]
734
+ ) -> List[Dict[str, Any]]:
735
+ """
736
+ Produce lightweight serializable summary rows.
737
+ """
738
+ rows: List[Dict[str, Any]] = []
739
+ for r in refit_results:
740
+ rows.append({
741
+ "lambda_idx": int(r["lambda_idx"]),
742
+ "lambda": float(r["lambda"]),
743
+ "n_groups": int(r["n_groups"]),
744
+ "refit_val_mse": float(r["refit_val_mse"]),
745
+ "groups": r["groups"],
746
+ "reused_from_idx": r.get("reused_from_idx"),
747
+ })
748
+ return rows
749
+
750
+
751
+ def save_refit_metrics_csv(
752
+ refit_results: Sequence[Dict[str, Any]],
753
+ out_csv: str | Path,
754
+ ) -> None:
755
+ """
756
+ Save compact refit metrics to CSV.
757
+ """
758
+ out_csv = Path(out_csv)
759
+ out_csv.parent.mkdir(parents=True, exist_ok=True)
760
+
761
+ fieldnames = [
762
+ "lambda_idx",
763
+ "lambda",
764
+ "n_groups",
765
+ "refit_val_mse",
766
+ "delta_vs_baseline",
767
+ "groups",
768
+ "group_ids",
769
+ "reused_from_idx",
770
+ ]
771
+
772
+ with out_csv.open("w", newline="", encoding="utf-8") as f:
773
+ writer = csv.DictWriter(f, fieldnames=fieldnames)
774
+ writer.writeheader()
775
+ for r in refit_results:
776
+ writer.writerow({
777
+ "lambda_idx": int(r["lambda_idx"]),
778
+ "lambda": float(r["lambda"]),
779
+ "n_groups": int(r["n_groups"]),
780
+ "refit_val_mse": float(r["refit_val_mse"]),
781
+ "delta_vs_baseline": r.get("delta_vs_baseline"),
782
+ "groups": str(r["groups"]),
783
+ "group_ids": str(_to_numpy(r["group_ids"]).astype(int).tolist()),
784
+ "reused_from_idx": r.get("reused_from_idx"),
785
+ })
786
+
787
+
788
+ def evaluate_test_mse_for_selected_refit(
789
+ *,
790
+ selected_refit_result: Dict[str, Any],
791
+ eval_fn: Callable[..., Any],
792
+ X_test: Any,
793
+ A_test: Any,
794
+ y_test: Any,
795
+ ) -> float:
796
+ """
797
+ Evaluate selected refit model on test set.
798
+
799
+ This uses the selected partition to map original actions to grouped actions.
800
+ """
801
+ group_ids = _to_numpy(selected_refit_result["group_ids"]).astype(int)
802
+ model = selected_refit_result["refit_model"]
803
+
804
+ A_test_g = map_actions_to_groups(A_test, group_ids)
805
+ test_mse = eval_fn(model, X_test, A_test_g, y_test)
806
+ return _safe_float(test_mse)