forked from tfius/grm-tcm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrm_tcm_train.py
More file actions
3354 lines (3016 loc) · 169 KB
/
Copy pathgrm_tcm_train.py
File metadata and controls
3354 lines (3016 loc) · 169 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
"""
GRM-TCM trainer / evaluator for the synthetic dataset.
Run sequence:
python grm_tcm_synthetic_generator.py
python grm_tcm_train.py
Expected input:
synthetic_grm_tcm/visits.csv
synthetic_grm_tcm/latent_states.csv
synthetic_grm_tcm/events.csv
Outputs:
grm_tcm_results/grm_visit_embeddings.csv
grm_tcm_results/grm_feature_modes.csv
grm_tcm_results/grm_predictions.csv
grm_tcm_results/grm_metrics.json
"""
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from scipy import sparse
from scipy.linalg import orthogonal_procrustes
from scipy.optimize import minimize_scalar
from scipy.sparse.linalg import eigsh
from sklearn.base import BaseEstimator
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.kernel_ridge import KernelRidge
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import (
accuracy_score, adjusted_mutual_info_score, adjusted_rand_score,
mean_absolute_error, mean_squared_error, normalized_mutual_info_score,
r2_score, roc_auc_score,
)
from sklearn.cluster import KMeans
from sklearn.model_selection import GroupShuffleSplit, KFold
from sklearn.neighbors import NearestNeighbors
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from grm_tcm_persistence import (
canonicalize_eigvec_signs,
save_joblib,
write_manifest,
)
from grm_tcm_projection import nystrom_extend_arrays, surrogate_project
STATIC_SCHEMA_VERSION = "static-v3"
def _sigmoid(z: np.ndarray) -> np.ndarray:
"""Numerically stable sigmoid for arbitrary real-valued inputs."""
out = np.empty_like(z, dtype=float)
pos = z >= 0
neg = ~pos
out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
ez = np.exp(z[neg])
out[neg] = ez / (1.0 + ez)
return out
def _fit_binary_temperature(z: np.ndarray, y: np.ndarray) -> float:
"""Find T > 0 minimizing NLL of sigmoid(z / T) against binary labels y."""
z = np.asarray(z, dtype=float)
y = np.asarray(y, dtype=int)
if z.size == 0 or len(np.unique(y)) < 2:
return 1.0
def nll(t: float) -> float:
t_safe = max(float(t), 1e-3)
s = z / t_safe
# log(sigmoid(s)) and log(1 - sigmoid(s)) via softplus identities
log_p1 = -np.logaddexp(0.0, -s)
log_p0 = -np.logaddexp(0.0, s)
return float(-np.mean(np.where(y == 1, log_p1, log_p0)))
res = minimize_scalar(nll, bounds=(0.05, 10.0), method="bounded")
return float(res.x)
OBSERVATION_NAMES = [
"sleep_quality", "hrv", "resting_hr", "body_temp", "fatigue", "pain",
"appetite", "bowel_quality", "mood_calm", "energy", "heaviness", "cold_hot",
]
# Ordinal observations from the v2 generator (pulse / tongue / complexion-like).
# Stored in visits.csv as integer levels; included as ordinal-as-continuous inputs
# alongside the 12 continuous channels when present and config flag is on.
QUALITATIVE_FEATURE_NAMES = [
"pulse_quality_like", "tongue_state_like", "complexion_like",
]
# Stable per-subject constitution axes (v2 generator). Used as targets for the
# constitution-recovery evaluation, not as input features (they live in subjects.csv).
CONSTITUTION_NAMES = [
"constitution_thermal", "constitution_energy", "constitution_stability",
]
LATENT_NAMES = [
"vitality_depletion", "stress_activation", "inflammatory_load", "digestive_instability",
]
@dataclass
class GRMTrainConfig:
input_dir: str = "synthetic_grm_tcm"
output_dir: str = "grm_tcm_results"
random_seed: int = 42
n_neighbors: int = 12
similarity_sigma: Optional[float] = None
diffusion_alpha: float = 1.0
temporal_edge_weight: float = 0.75
same_subject_edge_weight: float = 0.15
treatment_edge_weight: float = 0.20
subject_similarity_edge_weight: float = 0.25
subject_similarity_neighbors: int = 4
graph_mode: str = "feature_temporal_treatment"
n_modes: int = 8
rho: float = 1.0
use_normalized_laplacian: bool = True
test_size: float = 0.25
target_regression: str = "next_day_score"
target_classification: str = "flare_next_day"
# Secondary classification target: flare ONSET (today=0 -> tomorrow=1).
# Persistence baseline collapses here (it predicts 0 for all flare_today=0 rows),
# so GRM/embedding-based heads should beat it cleanly when there is real signal.
target_classification_onset: str = "flare_onset"
# If True, the GRM heads also see the per-subject lag of the targets
# (score_persistence_today, flare_persistence_today) as additional features.
# This makes the headline "grm" head a fair deployment-style competitor
# against the pure-persistence baseline rather than a strawman.
use_lag_features: bool = True
# If True, include v2 qualitative ordinal channels (pulse/tongue/complexion-like)
# in the observation matrix when present. The wider feature set is also used
# by the raw-RF baseline so the comparison stays apples-to-apples.
include_qualitative_features: bool = True
# Delay-embedding window size for Takens baseline (number of consecutive visits
# concatenated into a single feature vector). Set to 1 to disable (snapshot only).
# Respects subject boundaries; early visits padded with NaN then median-imputed.
delay_embedding_k: int = 3
# Feature source for the visit graph's KNN edges. 'obs' uses raw standardized
# observations (snapshot); 'takens' uses delay-embedded trajectory vectors so
# the graph encodes phase-space similarity (same symptoms AND same velocity).
graph_feature_source: str = "obs"
# Apply Coifman-Lafon density correction (α=1) to KNN edges before adding
# temporal/treatment edges. Reduces sampling-density bias so eigenmodes
# better approximate the Laplace-Beltrami operator geometry.
density_correction: bool = False
# Horizon sweep: evaluate smoothed-delta regression at multiple prediction
# horizons. Persistence predicts Δ=0, so any positive R² is genuine signal.
# Computed inline from global_dysregulation_score; additive diagnostic that
# does not affect the standard h=1 evaluation.
horizon_sweep: Tuple[int, ...] = (1, 3, 7, 14, 21)
horizon_smooth_window: int = 3
# If True, run constitution-recovery evaluation in inductive AND transductive
# modes. Reports visit-GRM aggregates, raw subject aggregates, and a dedicated
# subject-level GRM diagnostic so stable constitution is not forced through a
# visit-only spectral geometry. Skipped silently if subjects.csv lacks
# constitution columns.
evaluate_constitution_recovery: bool = True
# Strict inductive evaluation: split subjects first, fit scaler/KNN/graph/
# eigenbasis ONLY on train subjects, then project test subjects via the
# chosen projection method ('surrogate' or 'nystrom'). Reports honest
# held-out metrics; the persisted model is the train-only fit.
inductive: bool = False
projection: str = "surrogate"
n_neighbors_inductive: int = 12
# Where to look for the matching transductive metrics when generating the
# transductive-vs-inductive comparison plot in inductive mode. Default
# assumes the standard layout: sibling `grm_tcm_results/` dir.
transductive_results_dir: str = "grm_tcm_results"
class GRMTCMTrainer:
def __init__(self, config: GRMTrainConfig):
self.cfg = config
self.input_dir = Path(config.input_dir)
self.output_dir = Path(config.output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
self.obs_preprocessor: Optional[Pipeline] = None
self.nn_index: Optional[NearestNeighbors] = None
self.knn_sigma: Optional[float] = None
self.eigenvalues: Optional[np.ndarray] = None
self.eigenvectors: Optional[np.ndarray] = None
self.eigenvalues_full: Optional[np.ndarray] = None
self.train_degrees: Optional[np.ndarray] = None
self.feature_names: Optional[List[str]] = None
self.ridge_reg: Optional[BaseEstimator] = None
self.logistic_clf: Optional[BaseEstimator] = None
self.embedding_surrogate: Optional[BaseEstimator] = None
self.flare_temperature: Optional[float] = None
self.train_idx: Optional[np.ndarray] = None
self.test_idx: Optional[np.ndarray] = None
self.procrustes_R: Optional[np.ndarray] = None
self._visit_index: Optional[pd.DataFrame] = None
self._X_obs: Optional[np.ndarray] = None
def run(self) -> Dict:
visits, latent, events = self._load_data()
visits = self._prepare_visits(visits)
if self.cfg.inductive:
metrics = self._run_inductive(visits, latent, events)
else:
metrics = self._run_transductive(visits, latent, events)
self._print_evaluation_summary(metrics)
return metrics
@staticmethod
def _print_evaluation_summary(metrics: Dict[str, Any]) -> None:
"""Print a tier-labeled comparison table: GRM vs baselines, with Δ vs best baseline.
Goal: make it impossible to confuse transductive ("diagnostic") and inductive
("deployable") numbers, and surface the apparent gains over the strongest baseline.
"""
tier = metrics.get("evaluation_tier", "unspecified_tier")
tier_label = {
"transductive_diagnostic":
"TRANSDUCTIVE DIAGNOSTIC (graph saw all visits during decomposition)",
"inductive_deployable_prediction":
"INDUCTIVE DEPLOYABLE (test subjects disjoint from training)",
}.get(tier, f"TIER: {tier}")
reg = metrics.get("regression", {})
cls = metrics.get("classification", {})
onset = metrics.get("flare_onset_classification", {})
reg_order = [
"grm_ridge", "grm_plus_lag_ridge", "pca_ridge", "pca_plus_lag_ridge",
"takens_ridge", "takens_plus_lag_ridge",
"takens_pca_ridge", "takens_pca_plus_lag_ridge",
"smooth_rbf_kernel_ridge", "raw_random_forest",
"naive_current_score", "persistence_yesterday_score",
]
cls_order = [
"grm_logistic", "grm_logistic_calibrated", "grm_plus_lag_logistic",
"pca_logistic", "pca_plus_lag_logistic",
"takens_logistic", "takens_plus_lag_logistic",
"takens_pca_logistic", "takens_pca_plus_lag_logistic",
"smooth_rbf_kernel_ridge", "raw_random_forest", "naive_current_score", "persistence_yesterday_flare",
]
onset_order = [
"grm_logistic", "grm_plus_lag_logistic",
"pca_logistic", "pca_plus_lag_logistic",
"takens_logistic", "takens_plus_lag_logistic",
"takens_pca_logistic", "takens_pca_plus_lag_logistic",
"lag_only_logistic",
"raw_random_forest", "naive_marginal",
]
reg_metrics = ["r2", "rmse", "mae"]
cls_metrics = ["roc_auc", "brier", "log_loss"]
def _fmt(v: Any) -> str:
if v is None or (isinstance(v, float) and (np.isnan(v) or not np.isfinite(v))):
return " -"
try:
return f"{float(v):7.4f}"
except (TypeError, ValueError):
return " -"
def _row(name: str, d: Dict[str, Any], cols: List[str]) -> str:
cells = [_fmt(d.get(c)) for c in cols]
return f" {name:<32} " + " ".join(cells)
def _delta_row(grm_d: Dict[str, Any], best_d: Dict[str, Any], cols: List[str], invert: List[bool]) -> str:
cells = []
for c, inv in zip(cols, invert):
try:
g = float(grm_d.get(c)); b = float(best_d.get(c))
d = (b - g) if inv else (g - b)
cells.append(f"{d:+7.4f}")
except (TypeError, ValueError):
cells.append(" -")
return f" {'Δ GRM vs best baseline':<32} " + " ".join(cells)
def _best_baseline(table: Dict[str, Any], baseline_keys: List[str], score_key: str, higher_is_better: bool) -> Dict[str, Any]:
cands = [(k, table[k]) for k in baseline_keys if k in table and table[k]]
if not cands:
return {}
scored = [(k, d, d.get(score_key)) for k, d in cands if d.get(score_key) is not None]
if not scored:
return {}
best = max(scored, key=lambda t: (t[2] if higher_is_better else -t[2]))
return best[1]
bar = "=" * 86
print()
print(bar)
print(f" EVALUATION SUMMARY — {tier_label}")
print(bar)
if reg:
print(f"\n REGRESSION (target=next_day_score)")
print(f" {'predictor':<32} {'R^2':>7} {'RMSE':>7} {'MAE':>7}")
print(f" {'-' * 32} {'-' * 7} {'-' * 7} {'-' * 7}")
for k in reg_order:
if k in reg and reg[k]:
print(_row(k, reg[k], reg_metrics))
best_reg = _best_baseline(
reg, ["pca_ridge", "pca_plus_lag_ridge", "takens_ridge", "takens_plus_lag_ridge", "takens_pca_ridge", "takens_pca_plus_lag_ridge", "smooth_rbf_kernel_ridge", "raw_random_forest", "naive_current_score", "persistence_yesterday_score"],
"r2", higher_is_better=True,
)
headline_reg = reg.get("grm_plus_lag_ridge") or reg.get("grm_ridge")
if headline_reg and best_reg:
print(_delta_row(headline_reg, best_reg, reg_metrics, invert=[False, True, True]))
if cls:
print(f"\n CLASSIFICATION (target=flare_next_day)")
print(f" {'predictor':<32} {'AUC':>7} {'Brier':>7} {'LogLs':>7}")
print(f" {'-' * 32} {'-' * 7} {'-' * 7} {'-' * 7}")
for k in cls_order:
if k in cls and cls[k]:
print(_row(k, cls[k], cls_metrics))
best_cls = _best_baseline(
cls, ["pca_logistic", "pca_plus_lag_logistic", "takens_logistic", "takens_plus_lag_logistic", "takens_pca_logistic", "takens_pca_plus_lag_logistic", "smooth_rbf_kernel_ridge", "raw_random_forest", "naive_current_score", "persistence_yesterday_flare"],
"roc_auc", higher_is_better=True,
)
grm_for_delta = cls.get("grm_plus_lag_logistic") or cls.get("grm_logistic_calibrated") or cls.get("grm_logistic")
if grm_for_delta and best_cls:
print(_delta_row(grm_for_delta, best_cls, cls_metrics, invert=[False, True, True]))
if onset:
n_pos = onset.get("n_test_positive", "?")
n_elig = onset.get("n_test_eligible", "?")
marginal = onset.get("train_marginal")
marginal_str = f"{float(marginal):.3f}" if marginal is not None else "?"
print(f"\n CLASSIFICATION (target=flare_onset; today=0 -> tomorrow=1)")
print(f" full eligible test rows: {n_elig}, positives: {n_pos}, train marginal: {marginal_str}")
print(f" {'predictor':<32} {'AUC':>7} {'Brier':>7} {'LogLs':>7}")
print(f" {'-' * 32} {'-' * 7} {'-' * 7} {'-' * 7}")
for k in onset_order:
if k in onset and isinstance(onset[k], dict) and onset[k]:
print(_row(k, onset[k], cls_metrics))
best_onset = _best_baseline(
onset, ["pca_logistic", "pca_plus_lag_logistic", "takens_logistic", "takens_plus_lag_logistic", "takens_pca_logistic", "takens_pca_plus_lag_logistic", "lag_only_logistic", "raw_random_forest", "naive_marginal"],
"roc_auc", higher_is_better=True,
)
grm_for_delta = onset.get("grm_plus_lag_logistic") or onset.get("grm_logistic")
if grm_for_delta and best_onset:
print(_delta_row(grm_for_delta, best_onset, cls_metrics, invert=[False, True, True]))
hard = onset.get("hard_subset_flare_today_0", {}) or {}
if hard and hard.get("n_test_eligible", 0) > 0:
n_hard = hard.get("n_test_eligible", "?")
n_hard_pos = hard.get("n_test_positive", "?")
print(f"\n HARD SUBSET (flare_today=0 only; the genuinely-predictive task)")
print(f" hard subset rows: {n_hard}, positives: {n_hard_pos}")
print(f" {'predictor':<32} {'AUC':>7} {'Brier':>7} {'LogLs':>7}")
print(f" {'-' * 32} {'-' * 7} {'-' * 7} {'-' * 7}")
for k in onset_order:
if k in hard and isinstance(hard[k], dict) and hard[k]:
print(_row(k, hard[k], cls_metrics))
best_hard = _best_baseline(
hard, ["pca_logistic", "pca_plus_lag_logistic", "takens_logistic", "takens_plus_lag_logistic", "takens_pca_logistic", "takens_pca_plus_lag_logistic", "lag_only_logistic", "raw_random_forest", "naive_marginal"],
"roc_auc", higher_is_better=True,
)
grm_hard = hard.get("grm_plus_lag_logistic") or hard.get("grm_logistic")
if grm_hard and best_hard:
print(_delta_row(grm_hard, best_hard, cls_metrics, invert=[False, True, True]))
aliased = metrics.get("aliased_subset_evaluation", {}) or {}
if aliased and aliased.get("n_eligible", 0) >= 10:
n_a = aliased.get("n_eligible")
print(f"\n ALIASED-PAIR SUBSET (today's obs alias across regimes; futures diverge)")
print(f" eligible test rows: {n_a}")
a_reg = aliased.get("regression", {})
if a_reg:
print(f" REGRESSION (target=next_day_score, aliased subset)")
print(f" {'predictor':<32} {'R^2':>7} {'RMSE':>7} {'MAE':>7}")
print(f" {'-' * 32} {'-' * 7} {'-' * 7} {'-' * 7}")
for k in ["grm_plus_lag_ridge", "pca_plus_lag_ridge", "takens_plus_lag_ridge", "takens_pca_plus_lag_ridge", "raw_random_forest", "naive_current_score", "persistence_yesterday_score"]:
if k in a_reg and a_reg[k]:
print(_row(k, a_reg[k], reg_metrics))
best_a = _best_baseline(
a_reg, ["pca_plus_lag_ridge", "takens_plus_lag_ridge", "takens_pca_plus_lag_ridge", "raw_random_forest", "naive_current_score", "persistence_yesterday_score"],
"r2", higher_is_better=True,
)
grm_a = a_reg.get("grm_plus_lag_ridge")
if grm_a and best_a:
print(_delta_row(grm_a, best_a, reg_metrics, invert=[False, True, True]))
a_cls = aliased.get("classification", {})
if a_cls:
print(f" CLASSIFICATION (target=flare_next_day, aliased subset)")
print(f" {'predictor':<32} {'AUC':>7} {'Brier':>7} {'LogLs':>7}")
print(f" {'-' * 32} {'-' * 7} {'-' * 7} {'-' * 7}")
for k in ["grm_plus_lag_logistic", "pca_plus_lag_logistic", "takens_plus_lag_logistic", "takens_pca_plus_lag_logistic", "raw_random_forest", "naive_current_score", "persistence_yesterday_flare"]:
if k in a_cls and a_cls[k]:
print(_row(k, a_cls[k], cls_metrics))
best_ac = _best_baseline(
a_cls, ["pca_plus_lag_logistic", "takens_plus_lag_logistic", "takens_pca_plus_lag_logistic", "raw_random_forest", "naive_current_score", "persistence_yesterday_flare"],
"roc_auc", higher_is_better=True,
)
grm_ac = a_cls.get("grm_plus_lag_logistic")
if grm_ac and best_ac:
print(_delta_row(grm_ac, best_ac, cls_metrics, invert=[False, True, True]))
const = metrics.get("constitution_recovery", {})
if const and const.get("axes"):
axes = const["axes"]
print(f"\n CONSTITUTION RECOVERY (per-subject aggregates -> stable constitution axes)")
print(f" train subjects: {const.get('n_train_subjects', '?')}, test subjects: {const.get('n_test_subjects', '?')}")
head = " {:<32} ".format("predictor") + " ".join(f"{a.replace('constitution_',''):>10}" for a in axes) + " mean"
print(head)
print(" " + "-" * 32 + " " + " ".join("-" * 10 for _ in axes) + " ------")
for k, label in [
("grm_aggregate_ridge", "visit_grm_aggregate_ridge"),
("subject_graph_grm_ridge", "subject_graph_grm_ridge"),
("raw_aggregate_ridge", "raw_aggregate_ridge"),
]:
row_metrics = const.get(k, {})
if not row_metrics:
continue
cells = []
for a in axes:
r2 = row_metrics.get(a, {}).get("r2")
cells.append(f"{r2:10.4f}" if r2 is not None else f"{'-':>10}")
mean_r2 = const.get("mean_r2", {}).get(k)
mean_s = f"{mean_r2:6.4f}" if mean_r2 is not None else " -"
print(f" {label:<32} " + " ".join(cells) + f" {mean_s}")
grm_mean = const.get("mean_r2", {}).get("grm_aggregate_ridge")
raw_mean = const.get("mean_r2", {}).get("raw_aggregate_ridge")
if grm_mean is not None and raw_mean is not None:
delta = grm_mean - raw_mean
print(f" {'Δ GRM vs raw aggregate (mean R²)':<32} " + " ".join(" " * 10 for _ in axes) + f" {delta:+6.4f}")
tcm = metrics.get("tcm_alignment", {})
if tcm and tcm.get("label_columns"):
print(f"\n TCM ALIGNMENT (GRM clusters vs semantic labels, test set)")
label_cols = tcm["label_columns"]
for k_key in sorted(k for k in tcm if k.startswith("k")):
n_cl = k_key
block = tcm[k_key]
if not block:
continue
print(f" KMeans {k_key}:")
print(f" {'label':<28} {'AMI':>7} {'ARI':>7} {'NMI':>7}")
print(f" {'-' * 28} {'-' * 7} {'-' * 7} {'-' * 7}")
for col in label_cols:
if col in block:
d = block[col]
print(f" {col:<28} {d['ami']:7.4f} {d['ari']:7.4f} {d['nmi']:7.4f}")
regime = metrics.get("regime_prediction", {})
if regime and regime.get("n_test"):
n_cls = regime.get("n_classes", "?")
print(f"\n REGIME PREDICTION (next-day regime, {n_cls} classes)")
model_order = [
"persistence_same_regime",
"grm_logistic", "grm_rf",
"pca_logistic", "takens_logistic", "takens_rf",
"multiscale_logistic", "multiscale+grm_logistic", "multiscale+grm_rf",
"takens+prior_logistic", "takens+prior+grm_logistic", "takens+prior+grm_rf",
]
print(f" {'model':<32} {'top-1 acc':>9}")
print(f" {'-' * 32} {'-' * 9}")
for mk in model_order:
entry = regime.get(mk, {})
acc = entry.get("top1_acc")
if acc is not None:
print(f" {mk:<32} {acc:9.4f}")
change = regime.get("regime_change_subset", {})
if change and change.get("n_transitions"):
n_tr = change["n_transitions"]
print(f"\n REGIME-CHANGE SUBSET (today != tomorrow; {n_tr} transitions)")
print(f" {'model':<32} {'top-1 acc':>9}")
print(f" {'-' * 32} {'-' * 9}")
for mk in model_order:
entry = change.get(mk, {})
acc = entry.get("top1_acc")
if acc is not None:
print(f" {mk:<32} {acc:9.4f}")
tx = metrics.get("treatment_response", {})
if tx and tx.get("n_treatment_visits"):
n_tx = tx["n_treatment_visits"]
print(f"\n TREATMENT RESPONSE STRATIFICATION (clean treatment windows, n={n_tx})")
emb_names = [k for k in tx if isinstance(tx[k], dict) and any(
kk.startswith("delta_") or kk == "regime_change" for kk in tx[k]
)]
if emb_names:
# Show eta² per embedding per horizon.
h_keys = sorted(set(
k for name in emb_names for k in tx[name] if k.startswith("delta_")
))
header = f" {'embedding':<24}" + "".join(f" {'η²_' + k.replace('delta_',''):>8}" for k in h_keys) + f" {'η²_regime':>9}"
print(header)
print(f" {'-' * 24}" + "".join(f" {'-' * 8}" for _ in h_keys) + f" {'-' * 9}")
for name in ["grm", "pca", "takens", "multiscale", "multiscale+grm"]:
if name not in emb_names:
continue
cells = []
for hk in h_keys:
entry = tx[name].get(hk, {})
eta2 = entry.get("eta2")
p = entry.get("p")
s = f"{eta2:8.4f}" if eta2 is not None else " -"
if p is not None and p < 0.05:
s = s.rstrip() + "*"
s = f"{s:>8}"
cells.append(s)
rc = tx[name].get("regime_change", {})
rc_eta = rc.get("eta2")
rc_s = f"{rc_eta:9.4f}" if rc_eta is not None else " -"
if rc.get("p") is not None and rc["p"] < 0.05:
rc_s = rc_s.rstrip() + "*"
rc_s = f"{rc_s:>9}"
print(f" {name:<24}" + " ".join(cells) + f" {rc_s}")
print(f" (* p < 0.05)")
hsweep = metrics.get("horizon_sweep", {})
horizons = hsweep.get("horizons", [])
if horizons:
sw = hsweep.get("smooth_window", "?")
print(f"\n HORIZON SWEEP (smoothed-delta R², MA window={sw}; persistence=Δ0)")
model_keys = [
"persistence_zero", "grm_ridge", "grm_rf",
"pca_ridge", "takens_ridge", "takens_rf",
"takens_pca_ridge", "takens+grm_ridge", "takens+grm_rf",
"multiscale_ridge", "multiscale+grm_ridge",
"takens+prior_ridge", "takens+prior+grm_ridge",
"takens+prior+grm_ssqrt_ridge",
]
header = f" {'model':<24}" + "".join(f" {'h=' + str(h):>8}" for h in horizons)
print(header)
print(f" {'-' * 24}" + "".join(f" {'-' * 8}" for _ in horizons))
for mk in model_keys:
cells = []
for h in horizons:
hdata = hsweep.get(f"h{h}", {})
entry = hdata.get(mk, {})
r2 = entry.get("r2")
cells.append(f"{r2:8.4f}" if r2 is not None else " -")
print(f" {mk:<24}" + " ".join(cells))
sweep = metrics.get("modes_rho_sweep", {})
if sweep and sweep.get("modes_tested"):
modes_tested = sweep["modes_tested"]
rho_tested = sweep["rho_tested"]
horizons_s = sweep.get("horizons", [])
# Print one compact table per horizon.
for h in horizons_s:
hk = f"h{h}"
print(f"\n MODES/ρ SWEEP (smoothed-delta R² at h={h})")
header = f" {'modes \\\\ ρ':<12}" + "".join(f" {r:>6}" for r in rho_tested) + f" {'RF':>6}"
print(header)
print(f" {'-' * 12}" + "".join(f" {'-' * 6}" for _ in rho_tested) + f" {'-' * 6}")
for m in modes_tested:
cells = []
for r in rho_tested:
entry = sweep.get(f"m{m}_rho{r}", {})
val = entry.get(hk)
cells.append(f"{val:6.3f}" if val is not None else " -")
rf_entry = sweep.get(f"m{m}_rho{rho_tested[0]}_rf", {})
rf_val = rf_entry.get(hk)
cells.append(f"{rf_val:6.3f}" if rf_val is not None else " -")
print(f" {m:<12}" + " ".join(cells))
note = metrics.get("tier_note") or metrics.get("interpretation_guardrail")
if note:
print()
print(f" NOTE: {note}")
print(bar)
print()
def _run_transductive(self, visits, latent, events) -> Dict:
self._visit_index = visits[["visit_id", "subject_id", "day"]].copy()
X_obs, feature_names = self._make_observation_matrix(visits)
self._X_obs = X_obs
# Choose feature source for graph KNN edges.
if self.cfg.graph_feature_source == "takens":
X_graph = self._build_delay_embedding(X_obs, visits, self.cfg.delay_embedding_k)
print(f"[graph] KNN edges built from delay-embedded features (k={self.cfg.delay_embedding_k}, dim={X_graph.shape[1]})")
else:
X_graph = X_obs
W = self._build_visit_graph(visits, X_graph, events)
eigenvalues, eigenvectors = self._spectral_decomposition(W)
eigenvectors = canonicalize_eigvec_signs(eigenvectors)
self.eigenvalues = eigenvalues
self.eigenvectors = eigenvectors
embeddings = self._make_grm_embeddings(eigenvalues, eigenvectors)
embeddings_df = self._make_embeddings_df(visits, embeddings)
metrics, predictions_df = self._evaluate(visits, embeddings, latent)
self._fit_embedding_surrogate(X_obs, embeddings)
feature_modes_df = self._feature_mode_correlations(visits, embeddings, feature_names)
self._write_outputs(embeddings_df, feature_modes_df, metrics, predictions_df)
self._save_model()
return metrics
def _run_inductive(self, visits: pd.DataFrame, latent: Optional[pd.DataFrame], events: Optional[pd.DataFrame]) -> Dict:
"""Strict inductive evaluation: split subjects first, fit everything on train-only.
Pipeline:
1. Subject-level split (GroupShuffleSplit semantics; seed-controlled).
2. Fit obs_preprocessor, NN index, visit graph, eigenbasis, embedding surrogate,
ridge head, logistic head, Procrustes R --- all on TRAIN subjects only.
3. Project TEST-subject observations via cfg.projection ('surrogate' | 'nystrom').
4. Score test subjects (regression R², classification AUC, baselines, calibration,
out-of-sample latent recovery).
5. Persist the train-only model with manifest extra {inductive:True, ...} and write
inductive_eval_metrics.json next to the standard CSV outputs.
"""
if self.cfg.projection not in {"surrogate", "nystrom"}:
raise ValueError(f"Unknown projection: {self.cfg.projection!r}; must be 'surrogate' or 'nystrom'.")
# 1. Subject split.
rng = np.random.default_rng(self.cfg.random_seed)
all_subjects = np.array(sorted(visits["subject_id"].unique()))
rng.shuffle(all_subjects)
n_test = max(1, int(round(self.cfg.test_size * len(all_subjects))))
if n_test >= len(all_subjects):
raise ValueError(f"test_size={self.cfg.test_size} leaves no training subjects.")
test_subjects = set(int(s) for s in all_subjects[:n_test])
train_subjects = set(int(s) for s in all_subjects[n_test:])
train_mask = visits["subject_id"].isin(train_subjects).to_numpy()
train_visits = visits[train_mask].sort_values(["subject_id", "day"]).reset_index(drop=True)
test_visits = visits[~train_mask].sort_values(["subject_id", "day"]).reset_index(drop=True)
train_visits["visit_id"] = np.arange(len(train_visits))
test_visits["visit_id"] = np.arange(len(train_visits), len(train_visits) + len(test_visits))
print(
f"[inductive] {len(train_subjects)} train subjects ({len(train_visits)} visits) / "
f"{len(test_subjects)} test subjects ({len(test_visits)} visits)"
)
# 2a. Fit observation preprocessor on train only.
X_train, feature_names = self._make_observation_matrix(train_visits)
self._X_obs = X_train
# 2b. Build train-only graph + eigenbasis.
if self.cfg.graph_feature_source == "takens":
X_train_graph = self._build_delay_embedding(X_train, train_visits, self.cfg.delay_embedding_k)
print(f"[graph] KNN edges built from delay-embedded features (k={self.cfg.delay_embedding_k}, dim={X_train_graph.shape[1]})")
else:
X_train_graph = X_train
W_train = self._build_visit_graph(train_visits, X_train_graph, events)
eigenvalues, eigenvectors = self._spectral_decomposition(W_train)
eigenvectors = canonicalize_eigvec_signs(eigenvectors)
self.eigenvalues = eigenvalues
self.eigenvectors = eigenvectors
train_embeddings = self._make_grm_embeddings(eigenvalues, eigenvectors)
# 2c. Fit heads on ALL train embeddings (no within-graph split needed: the held-out
# set is the disjoint test subjects).
y_reg_train = train_visits[self.cfg.target_regression].to_numpy(float)
y_cls_train = train_visits[self.cfg.target_classification].astype(int).to_numpy()
self.train_idx = np.arange(len(train_visits))
self.test_idx = None # No within-graph test split in inductive mode.
self.ridge_reg = Ridge(alpha=1.0).fit(train_embeddings, y_reg_train)
if len(np.unique(y_cls_train)) >= 2:
self.logistic_clf = LogisticRegression(max_iter=2000, class_weight="balanced").fit(
train_embeddings, y_cls_train
)
else:
self.logistic_clf = None
# 2d. Surrogate + temperature (both train-only).
# When graph was built from delay-embedded features, the surrogate should
# map from X_takens (trajectory) → embeddings, not X_obs (snapshot).
X_train_surr = X_train_graph if self.cfg.graph_feature_source == "takens" else X_train
self._fit_embedding_surrogate(X_train_surr, train_embeddings)
self.flare_temperature = self._fit_flare_temperature(train_embeddings, y_cls_train, self.train_idx)
# 3. Project test observations.
X_test_raw = test_visits[self.feature_names].to_numpy(float)
X_test = self.obs_preprocessor.transform(X_test_raw)
# Match projection input to graph feature source: if graph used X_takens,
# the projection must also use delay-embedded test features so distances
# are in the same space.
if self.cfg.graph_feature_source == "takens":
X_test_proj = self._build_delay_embedding(X_test, test_visits, self.cfg.delay_embedding_k)
else:
X_test_proj = X_test
if self.cfg.projection == "surrogate":
test_embeddings = surrogate_project(self.embedding_surrogate, X_test_proj)
else: # nystrom
if self.nn_index is None:
raise RuntimeError(
f"Nyström projection requires a KNN-based graph_mode; got {self.cfg.graph_mode!r}."
)
test_embeddings = nystrom_extend_arrays(
X_test_proj,
nn_index=self.nn_index,
knn_sigma=float(self.knn_sigma),
eigenvalues=self.eigenvalues,
eigenvectors=self.eigenvectors,
rho=float(self.cfg.rho),
normalized=bool(self.cfg.use_normalized_laplacian),
train_degrees=self.train_degrees,
n_neighbors=int(self.cfg.n_neighbors_inductive),
)
# 4. Score test subjects + baselines.
y_reg_test = test_visits[self.cfg.target_regression].to_numpy(float)
y_cls_test = test_visits[self.cfg.target_classification].astype(int).to_numpy()
pred_grm_reg = self.ridge_reg.predict(test_embeddings)
if self.logistic_clf is not None:
prob_grm_cls = self.logistic_clf.predict_proba(test_embeddings)[:, 1]
pred_grm_cls = (prob_grm_cls >= 0.5).astype(int)
if self.flare_temperature is not None and np.isfinite(self.flare_temperature):
z_test = self.logistic_clf.decision_function(test_embeddings)
prob_grm_cls_cal = _sigmoid(z_test / float(self.flare_temperature))
pred_grm_cls_cal = (prob_grm_cls_cal >= 0.5).astype(int)
else:
prob_grm_cls_cal = None
pred_grm_cls_cal = None
else:
prob_grm_cls = np.full(len(test_visits), 0.5)
pred_grm_cls = np.zeros(len(test_visits), dtype=int)
prob_grm_cls_cal = None
pred_grm_cls_cal = None
# Raw-observation baseline: fit RF on train_raw, predict on test_raw. Both rows
# come through the SAME preprocessor (fit on train) to keep the inductive contract.
# Uses the same feature set the GRM head sees so the comparison is fair.
raw_cols = self.feature_names + ["global_dysregulation_score"]
raw_pipe = Pipeline([("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler())])
train_raw = raw_pipe.fit_transform(train_visits[raw_cols].to_numpy(float))
test_raw = raw_pipe.transform(test_visits[raw_cols].to_numpy(float))
raw_rf_reg = RandomForestRegressor(n_estimators=100, min_samples_leaf=4, random_state=42, n_jobs=-1).fit(
train_raw, y_reg_train
)
pred_raw_reg = raw_rf_reg.predict(test_raw)
if len(np.unique(y_cls_train)) >= 2:
raw_rf_cls = RandomForestClassifier(
n_estimators=100, min_samples_leaf=4, random_state=42, n_jobs=-1, class_weight="balanced"
).fit(train_raw, y_cls_train)
prob_raw_cls = raw_rf_cls.predict_proba(test_raw)[:, 1]
pred_raw_cls = (prob_raw_cls >= 0.5).astype(int)
else:
prob_raw_cls = np.full(len(test_visits), 0.5)
pred_raw_cls = np.zeros(len(test_visits), dtype=int)
pred_smooth_reg, prob_smooth_cls = self._fit_smooth_rbf_baseline(
train_raw, y_reg_train, y_cls_train, test_raw
)
# Naive baseline: just use the current dysregulation score.
pred_naive_reg = test_visits["global_dysregulation_score"].to_numpy(float)
pred_naive_reg = np.nan_to_num(pred_naive_reg, nan=float(np.nanmedian(y_reg_train)))
naive_threshold = float(np.nanmedian(y_reg_train))
pred_naive_cls = (pred_naive_reg >= naive_threshold).astype(int)
prob_naive_cls = np.clip(
pred_naive_reg / max(float(np.nanmax(y_reg_train)), 1e-9), 0, 1
)
persistence = self._persistence_baseline(
test_visits, train_visits,
self.cfg.target_classification, self.cfg.target_regression,
)
# GRM + lag head — fair deployment-style competitor against persistence.
fill_score = float(np.nanmedian(y_reg_train))
fill_flare = float(np.nanmean(y_cls_train))
X_train_grm_lag = self._augment_with_lag(train_embeddings, train_visits, fill_score, fill_flare)
X_test_grm_lag = self._augment_with_lag(test_embeddings, test_visits, fill_score, fill_flare)
ridge_grm_lag = Ridge(alpha=1.0).fit(X_train_grm_lag, y_reg_train)
pred_grm_lag_reg = ridge_grm_lag.predict(X_test_grm_lag)
if len(np.unique(y_cls_train)) >= 2:
log_grm_lag = LogisticRegression(max_iter=2000, class_weight="balanced").fit(X_train_grm_lag, y_cls_train)
prob_grm_lag_cls = log_grm_lag.predict_proba(X_test_grm_lag)[:, 1]
pred_grm_lag_cls = (prob_grm_lag_cls >= 0.5).astype(int)
else:
prob_grm_lag_cls = np.full(len(test_visits), 0.5)
pred_grm_lag_cls = np.zeros(len(test_visits), dtype=int)
# PCA baseline: linear projection into same dimensionality as GRM modes.
# Fit on train_raw only; transform both train and test.
pca = PCA(n_components=min(self.cfg.n_modes, train_raw.shape[1]), random_state=self.cfg.random_seed)
pca_train = pca.fit_transform(train_raw)
pca_test = pca.transform(test_raw)
pca_ridge = Ridge(alpha=1.0).fit(pca_train, y_reg_train)
pred_pca_reg = pca_ridge.predict(pca_test)
if len(np.unique(y_cls_train)) >= 2:
pca_log = LogisticRegression(max_iter=2000, class_weight="balanced").fit(pca_train, y_cls_train)
prob_pca_cls = pca_log.predict_proba(pca_test)[:, 1]
pred_pca_cls = (prob_pca_cls >= 0.5).astype(int)
else:
prob_pca_cls = np.full(len(test_visits), 0.5)
pred_pca_cls = np.zeros(len(test_visits), dtype=int)
X_train_pca_lag = self._augment_with_lag(pca_train, train_visits, fill_score, fill_flare)
X_test_pca_lag = self._augment_with_lag(pca_test, test_visits, fill_score, fill_flare)
pca_lag_ridge = Ridge(alpha=1.0).fit(X_train_pca_lag, y_reg_train)
pred_pca_lag_reg = pca_lag_ridge.predict(X_test_pca_lag)
if len(np.unique(y_cls_train)) >= 2:
pca_lag_log = LogisticRegression(max_iter=2000, class_weight="balanced").fit(X_train_pca_lag, y_cls_train)
prob_pca_lag_cls = pca_lag_log.predict_proba(X_test_pca_lag)[:, 1]
pred_pca_lag_cls = (prob_pca_lag_cls >= 0.5).astype(int)
else:
prob_pca_lag_cls = np.full(len(test_visits), 0.5)
pred_pca_lag_cls = np.zeros(len(test_visits), dtype=int)
# Delay-embedded (Takens) baselines.
takens_train = self._build_delay_embedding(train_raw, train_visits, self.cfg.delay_embedding_k)
takens_test = self._build_delay_embedding(test_raw, test_visits, self.cfg.delay_embedding_k)
takens_ridge_m = Ridge(alpha=1.0).fit(takens_train, y_reg_train)
pred_takens_reg = takens_ridge_m.predict(takens_test)
if len(np.unique(y_cls_train)) >= 2:
takens_log_m = LogisticRegression(max_iter=2000, class_weight="balanced").fit(takens_train, y_cls_train)
prob_takens_cls = takens_log_m.predict_proba(takens_test)[:, 1]
pred_takens_cls = (prob_takens_cls >= 0.5).astype(int)
else:
prob_takens_cls = np.full(len(test_visits), 0.5)
pred_takens_cls = np.zeros(len(test_visits), dtype=int)
X_train_takens_lag = self._augment_with_lag(takens_train, train_visits, fill_score, fill_flare)
X_test_takens_lag = self._augment_with_lag(takens_test, test_visits, fill_score, fill_flare)
takens_lag_ridge_m = Ridge(alpha=1.0).fit(X_train_takens_lag, y_reg_train)
pred_takens_lag_reg = takens_lag_ridge_m.predict(X_test_takens_lag)
if len(np.unique(y_cls_train)) >= 2:
takens_lag_log_m = LogisticRegression(max_iter=2000, class_weight="balanced").fit(X_train_takens_lag, y_cls_train)
prob_takens_lag_cls = takens_lag_log_m.predict_proba(X_test_takens_lag)[:, 1]
pred_takens_lag_cls = (prob_takens_lag_cls >= 0.5).astype(int)
else:
prob_takens_lag_cls = np.full(len(test_visits), 0.5)
pred_takens_lag_cls = np.zeros(len(test_visits), dtype=int)
# Takens-PCA (SSA) in inductive mode.
pca_takens_ind = PCA(n_components=min(self.cfg.n_modes, takens_train.shape[1]), random_state=self.cfg.random_seed)
tpca_train = pca_takens_ind.fit_transform(takens_train)
tpca_test = pca_takens_ind.transform(takens_test)
tpca_ridge_m = Ridge(alpha=1.0).fit(tpca_train, y_reg_train)
pred_tpca_reg = tpca_ridge_m.predict(tpca_test)
if len(np.unique(y_cls_train)) >= 2:
tpca_log_m = LogisticRegression(max_iter=2000, class_weight="balanced").fit(tpca_train, y_cls_train)
prob_tpca_cls = tpca_log_m.predict_proba(tpca_test)[:, 1]
pred_tpca_cls = (prob_tpca_cls >= 0.5).astype(int)
else:
prob_tpca_cls = np.full(len(test_visits), 0.5)
pred_tpca_cls = np.zeros(len(test_visits), dtype=int)
X_train_tpca_lag = self._augment_with_lag(tpca_train, train_visits, fill_score, fill_flare)
X_test_tpca_lag = self._augment_with_lag(tpca_test, test_visits, fill_score, fill_flare)
tpca_lag_ridge_m = Ridge(alpha=1.0).fit(X_train_tpca_lag, y_reg_train)
pred_tpca_lag_reg = tpca_lag_ridge_m.predict(X_test_tpca_lag)
if len(np.unique(y_cls_train)) >= 2:
tpca_lag_log_m = LogisticRegression(max_iter=2000, class_weight="balanced").fit(X_train_tpca_lag, y_cls_train)
prob_tpca_lag_cls = tpca_lag_log_m.predict_proba(X_test_tpca_lag)[:, 1]
pred_tpca_lag_cls = (prob_tpca_lag_cls >= 0.5).astype(int)
else:
prob_tpca_lag_cls = np.full(len(test_visits), 0.5)
pred_tpca_lag_cls = np.zeros(len(test_visits), dtype=int)
# Multi-scale features: k=3 trajectory + 14-day rolling stats.
multi_train = self._build_multiscale_features(train_raw, train_visits)
multi_test = self._build_multiscale_features(test_raw, test_visits)
prior_train = self._build_subject_prior_mean(train_raw, train_visits)
prior_test = self._build_subject_prior_mean(test_raw, test_visits)
# Flare-onset secondary target. Eligible rows = where flare_today is known.
y_onset_train_raw = train_visits[self.cfg.target_classification_onset].astype(float).to_numpy()
y_onset_test_raw = test_visits[self.cfg.target_classification_onset].astype(float).to_numpy()
tr_onset_valid = ~np.isnan(y_onset_train_raw)
te_onset_valid = ~np.isnan(y_onset_test_raw)
y_onset_train = np.where(tr_onset_valid, np.nan_to_num(y_onset_train_raw, nan=0.0), 0).astype(int)
y_onset_test = np.where(te_onset_valid, np.nan_to_num(y_onset_test_raw, nan=0.0), 0).astype(int)
flare_today_test_arr = test_visits["flare_persistence_today"].astype(float).to_numpy()[te_onset_valid]
onset_block = self._fit_and_score_onset(
y_onset_train[tr_onset_valid], y_onset_test[te_onset_valid],
train_embeddings[tr_onset_valid], test_embeddings[te_onset_valid],
X_train_grm_lag[tr_onset_valid], X_test_grm_lag[te_onset_valid],
train_raw[tr_onset_valid], test_raw[te_onset_valid],
flare_today_test_arr,
X_pca_train=pca_train[tr_onset_valid], X_pca_test=pca_test[te_onset_valid],
X_pca_lag_train=X_train_pca_lag[tr_onset_valid], X_pca_lag_test=X_test_pca_lag[te_onset_valid],
X_takens_train=takens_train[tr_onset_valid], X_takens_test=takens_test[te_onset_valid],
X_takens_lag_train=X_train_takens_lag[tr_onset_valid], X_takens_lag_test=X_test_takens_lag[te_onset_valid],
X_tpca_train=tpca_train[tr_onset_valid], X_tpca_test=tpca_test[te_onset_valid],
X_tpca_lag_train=X_train_tpca_lag[tr_onset_valid], X_tpca_lag_test=X_test_tpca_lag[te_onset_valid],
)
# 5. Out-of-sample latent recovery: fit Procrustes on train, apply to test.
latent_recovery = self._latent_recovery_inductive(
train_visits, train_embeddings, test_visits, test_embeddings, latent
)
_ind_combined = pd.concat([train_visits, test_visits], ignore_index=True)
_ind_tr_idx = np.arange(len(train_visits))
_ind_te_idx = np.arange(len(train_visits), len(train_visits) + len(test_visits))
_ind_emb_dict = {
"grm": np.vstack([train_embeddings, test_embeddings]),
"pca": np.vstack([pca_train, pca_test]),
"takens": np.vstack([takens_train, takens_test]),
"takens_pca": np.vstack([tpca_train, tpca_test]),
"takens+grm": np.column_stack([
np.vstack([takens_train, takens_test]),
np.vstack([train_embeddings, test_embeddings]),
]),
"multiscale": np.vstack([multi_train, multi_test]),
"multiscale+grm": np.column_stack([
np.vstack([multi_train, multi_test]),
np.vstack([train_embeddings, test_embeddings]),
]),
"takens+prior": np.column_stack([
np.vstack([takens_train, takens_test]),
np.vstack([prior_train, prior_test]),
]),
"takens+prior+grm": np.column_stack([
np.vstack([takens_train, takens_test]),
np.vstack([prior_train, prior_test]),
np.vstack([train_embeddings, test_embeddings]),
]),
"takens+prior+grm_ssqrt": np.column_stack([
np.vstack([takens_train, takens_test]),
np.vstack([prior_train, prior_test]),
np.vstack([train_embeddings, test_embeddings]),
np.sign(np.vstack([train_embeddings, test_embeddings])) * np.sqrt(np.abs(np.vstack([train_embeddings, test_embeddings]))),
]),
}
metrics: Dict[str, Any] = {
"manifest": "model/manifest.json",
"evaluation_mode": "inductive",
"evaluation_tier": "inductive_deployable_prediction",
"projection": self.cfg.projection,
"n_train_subjects": int(len(train_subjects)),
"n_test_subjects": int(len(test_subjects)),
"n_train_visits": int(len(train_visits)),
"n_test_visits": int(len(test_visits)),
"regression": {
"grm_ridge": self._reg_metrics(y_reg_test, pred_grm_reg),
"grm_plus_lag_ridge": self._reg_metrics(y_reg_test, pred_grm_lag_reg),
"pca_ridge": self._reg_metrics(y_reg_test, pred_pca_reg),
"pca_plus_lag_ridge": self._reg_metrics(y_reg_test, pred_pca_lag_reg),
"takens_ridge": self._reg_metrics(y_reg_test, pred_takens_reg),
"takens_plus_lag_ridge": self._reg_metrics(y_reg_test, pred_takens_lag_reg),
"takens_pca_ridge": self._reg_metrics(y_reg_test, pred_tpca_reg),
"takens_pca_plus_lag_ridge": self._reg_metrics(y_reg_test, pred_tpca_lag_reg),
"smooth_rbf_kernel_ridge": self._reg_metrics(y_reg_test, pred_smooth_reg),
"raw_random_forest": self._reg_metrics(y_reg_test, pred_raw_reg),
"naive_current_score": self._reg_metrics(y_reg_test, pred_naive_reg),
"persistence_yesterday_score": self._reg_metrics(y_reg_test, persistence["score_pred"]),
},
"classification": {
"grm_logistic": self._cls_metrics(y_cls_test, pred_grm_cls, prob_grm_cls),
"grm_logistic_calibrated": (
self._cls_metrics(y_cls_test, pred_grm_cls_cal, prob_grm_cls_cal)
if prob_grm_cls_cal is not None else {}
),
"grm_plus_lag_logistic": self._cls_metrics(y_cls_test, pred_grm_lag_cls, prob_grm_lag_cls),
"pca_logistic": self._cls_metrics(y_cls_test, pred_pca_cls, prob_pca_cls),
"pca_plus_lag_logistic": self._cls_metrics(y_cls_test, pred_pca_lag_cls, prob_pca_lag_cls),
"takens_logistic": self._cls_metrics(y_cls_test, pred_takens_cls, prob_takens_cls),
"takens_plus_lag_logistic": self._cls_metrics(y_cls_test, pred_takens_lag_cls, prob_takens_lag_cls),
"takens_pca_logistic": self._cls_metrics(y_cls_test, pred_tpca_cls, prob_tpca_cls),
"takens_pca_plus_lag_logistic": self._cls_metrics(y_cls_test, pred_tpca_lag_cls, prob_tpca_lag_cls),
"smooth_rbf_kernel_ridge": self._cls_metrics(
y_cls_test, (prob_smooth_cls >= 0.5).astype(int), prob_smooth_cls
),
"raw_random_forest": self._cls_metrics(y_cls_test, pred_raw_cls, prob_raw_cls),
"naive_current_score": self._cls_metrics(y_cls_test, pred_naive_cls, prob_naive_cls),
"persistence_yesterday_flare": self._cls_metrics(
y_cls_test, persistence["flare_pred"], persistence["flare_prob"]
),
},
"flare_onset_classification": onset_block,
"aliased_subset_evaluation": self._evaluate_aliased_subset(
test_visits, y_reg_test, y_cls_test,
pred_grm_lag_reg, prob_grm_lag_cls,
pred_raw_reg, prob_raw_cls,
pred_naive_reg, prob_naive_cls,
persistence,
pred_pca_lag_reg=pred_pca_lag_reg,
prob_pca_lag_cls=prob_pca_lag_cls,
pred_takens_lag_reg=pred_takens_lag_reg,
prob_takens_lag_cls=prob_takens_lag_cls,
pred_tpca_lag_reg=pred_tpca_lag_reg,
prob_tpca_lag_cls=prob_tpca_lag_cls,
),
"constitution_recovery": self._evaluate_constitution_recovery(
train_visits, train_embeddings, test_visits, test_embeddings,
),
"spectral_signal_concentration": self._spectral_signal_concentration(test_visits, test_embeddings),
"tcm_alignment": self._evaluate_tcm_alignment(
pd.concat([train_visits, test_visits], ignore_index=True),
np.vstack([train_embeddings, test_embeddings]),
np.arange(len(train_visits)),
np.arange(len(train_visits), len(train_visits) + len(test_visits)),
),
"horizon_sweep": self._evaluate_horizon_sweep(
_ind_combined, _ind_emb_dict,