Repository navigation
Expand file tree
/
Copy pathanalysis.py
More file actions
2182 lines (1991 loc) · 84.6 KB
/
Copy pathanalysis.py
File metadata and controls
2182 lines (1991 loc) · 84.6 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
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import math
import os
import re
import subprocess
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
try:
import yaml
except Exception: # pragma: no cover - optional for CSV-only mode
yaml = None
CHILD_ID_PATTERN = re.compile(r"Submitted batch job (\d+)")
REPO_ROOT = Path(__file__).resolve().parent
@dataclass(frozen=True)
class ChildJob:
job_id: str
case_name: str | None
parent_case_id: str | None
config_path: str | None
profile: str | None
model_type: str | None
scaler: str | None
split_mode: str | None
split_strategy: str | None
scientific_config_id: str | None
execution_label: str | None
state: str
exit_code: str
elapsed: str
failure_reason: str | None
log_path: str | None = None
execution_manifest_path: str | None = None
@dataclass(frozen=True)
class GeneralizationRecord:
case_name: str
model_type: str | None
split_mode: str | None
split_strategy: str | None
feature_input: str | None
metric_name: str
train_value: float
test_value: float
val_value: float | None
gap_train_minus_test: float
gap_train_minus_test_std: float | None
overfit_flag: bool
underfit_flag: bool
config_path: str | None
run_dir: str | None
scaler: str | None = None
parent_case_id: str | None = None
scientific_config_id: str | None = None
execution_label: str | None = None
state: str | None = None
failure_reason: str | None = None
slice_count: int = 1
metric_slices_used: int = 1
completed_slices: int = 1
failed_slices: int = 0
config_paths: tuple[str, ...] = ()
run_dirs: tuple[str, ...] = ()
METRIC_FIELDS = [
"r2",
"mae",
"rmse",
"mse",
"auc",
"auprc",
"accuracy",
"f1",
"train_r2",
"test_r2",
"val_r2",
"train_mae",
"test_mae",
"val_mae",
"train_rmse",
"test_rmse",
"val_rmse",
"train_mse",
"test_mse",
"val_mse",
"train_auc",
"test_auc",
"val_auc",
"train_auprc",
"test_auprc",
"val_auprc",
"train_accuracy",
"test_accuracy",
"val_accuracy",
"train_f1",
"test_f1",
"val_f1",
]
# Time-series (Adaptive NVAR) horizon RMSE columns. Emitted alongside the
# tabular metrics so DOE analysis CSVs surface per-horizon rollout error for
# train/val/test. Purely additive: non-time-series runs leave these blank.
HORIZON_RMSE_FIELDS = [
f"{segment}_rmse_h{h}"
for segment in ("train", "val", "test")
for h in (25, 50, 75, 100)
]
RUN_METRIC_CSV_FIELDS = [
"case_name",
"group_index",
"parent_case_id",
"scientific_config_id",
"job_id",
"state",
"failure_reason",
"profile",
"model_type",
"scaler",
"feature_input",
"split_mode",
"split_strategy",
"execution_label",
"slice_count",
"completed_slices",
"failed_slices",
"elapsed",
"config_path",
"config_paths",
"run_dir",
"run_dirs",
"metrics_path",
"metrics_paths",
] + METRIC_FIELDS + [f"{field}_std" for field in METRIC_FIELDS] + HORIZON_RMSE_FIELDS
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Analyze CheMLFlow DOE runs from Slurm job logs + sacct or from local "
"run_status.json files, then write summary reports (JSON/CSV)."
)
)
parser.add_argument(
"--backend",
choices=("slurm", "local"),
default="slurm",
help="Execution backend to analyze. Use local for manifest/run_status-based DOE runs.",
)
parser.add_argument(
"--orchestrator-job-id",
default="",
help="Slurm orchestrator job ID (for example: 2307731).",
)
parser.add_argument(
"--logs-dir",
default="/mnt/home/f0113398/logs",
help="Directory containing <orchestrator-log-prefix>-<jobid>.out/err logs.",
)
parser.add_argument(
"--orchestrator-log-prefix",
default="ysi_doe",
help=(
"Prefix used for orchestrator log filenames in --logs-dir "
"(default: ysi_doe; example for PAH: pah_doe)."
),
)
parser.add_argument(
"--doe-dir",
default="/mnt/home/f0113398/ysi_doe",
help="DOE output directory containing manifest.jsonl and generated case YAMLs.",
)
parser.add_argument(
"--execution-manifest",
default="",
help=(
"Optional backend-neutral execution attempt manifest. "
"Default for --backend local: <doe-dir>/execution_manifest.jsonl when present."
),
)
parser.add_argument(
"--output-dir",
default="",
help=(
"Output directory for reports. "
"Default: <doe-dir>/analysis_<orchestrator-job-id>."
),
)
parser.add_argument(
"--sacct-bin",
default="sacct",
help="Path/name of sacct executable.",
)
parser.add_argument(
"--all-runs-csv",
default="",
help=(
"Optional shortcut mode: path to an existing all_runs_metrics.csv. "
"When set, analysis runs in CSV-only plotting mode."
),
)
parser.add_argument(
"--overfit-threshold",
type=float,
default=0.15,
help="Threshold on train-test metric gap to flag overfitting (default: 0.15).",
)
parser.add_argument(
"--underfit-threshold-r2",
type=float,
default=0.20,
help="Regression underfit threshold on train r2 (default: 0.20).",
)
parser.add_argument(
"--underfit-threshold-auc",
type=float,
default=0.65,
help="Classification underfit threshold on train auc (default: 0.65).",
)
return parser.parse_args()
def _read_text(path: Path) -> str:
return path.read_text(encoding="utf-8")
def _parse_child_job_ids(orchestrator_out: Path) -> list[str]:
text = _read_text(orchestrator_out)
ids = [m.group(1) for m in CHILD_ID_PATTERN.finditer(text)]
# Keep original order, drop duplicates.
deduped: list[str] = []
seen: set[str] = set()
for job_id in ids:
if job_id in seen:
continue
seen.add(job_id)
deduped.append(job_id)
return deduped
def _load_valid_manifest_records(manifest_path: Path) -> list[dict[str, Any]]:
valid: list[dict[str, Any]] = []
for line in _read_text(manifest_path).splitlines():
line = line.strip()
if not line:
continue
rec = json.loads(line)
if str(rec.get("status", "")).lower() != "valid":
continue
record_type = str(rec.get("record_type", "execution_child")).strip().lower()
if record_type == "parent":
continue
cfg = rec.get("config_path")
if cfg:
valid.append(rec)
return valid
def _load_execution_attempt_records(path: Path | None) -> list[dict[str, Any]]:
if path is None or not path.exists():
return []
records: list[dict[str, Any]] = []
for line in _read_text(path).splitlines():
line = line.strip()
if not line:
continue
record = json.loads(line)
record_type = str(record.get("record_type", "")).strip().lower()
if record_type and record_type != "execution_attempt":
continue
records.append(record)
return records
def _normalize_path_key(value: Any, doe_dir: Path) -> str:
text = str(value or "").strip()
if not text:
return ""
path = Path(text)
if path.is_absolute():
return str(path)
for candidate in (Path.cwd() / path, REPO_ROOT / path, doe_dir / path):
if candidate.exists():
return str(candidate)
return str((Path.cwd() / path).absolute())
def _index_execution_attempts(
attempts: list[dict[str, Any]],
doe_dir: Path,
) -> tuple[dict[str, dict[str, Any]], dict[str, dict[str, Any]]]:
by_case_id: dict[str, dict[str, Any]] = {}
by_config_path: dict[str, dict[str, Any]] = {}
for attempt in attempts:
case_id = str(attempt.get("case_id", "")).strip()
if case_id:
by_case_id[case_id] = attempt
config_key = _normalize_path_key(attempt.get("config_path"), doe_dir)
if config_key:
by_config_path[config_key] = attempt
return by_case_id, by_config_path
def _run_sacct(sacct_bin: str, child_ids: list[str]) -> list[dict[str, str]]:
if not child_ids:
return []
job_arg = ",".join(child_ids)
cmd = [
sacct_bin,
"-n",
"-P",
"-j",
job_arg,
"--format",
"JobIDRaw,JobID,JobName,State,ExitCode,Elapsed",
]
completed = subprocess.run(cmd, capture_output=True, text=True, check=True)
rows: list[dict[str, str]] = []
for raw_line in completed.stdout.splitlines():
line = raw_line.strip()
if not line:
continue
parts = line.split("|")
if len(parts) != 6:
continue
rows.append(
{
"job_id_raw": parts[0],
"job_id": parts[1],
"job_name": parts[2],
"state": parts[3],
"exit_code": parts[4],
"elapsed": parts[5],
}
)
return rows
def _resolve_manifest_config_path(config_path: str | None, doe_dir: Path) -> Path | None:
if not config_path:
return None
path = Path(str(config_path))
if path.is_absolute():
return path
candidates = [Path.cwd() / path, REPO_ROOT / path, doe_dir / path]
for candidate in candidates:
if candidate.exists():
return candidate
return candidates[0]
def _load_yaml_config(path: Path | None) -> dict[str, Any]:
if path is None or yaml is None or not path.exists():
return {}
try:
loaded = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
except Exception:
return {}
return loaded if isinstance(loaded, dict) else {}
def _run_dir_from_config(config: dict[str, Any]) -> Path | None:
global_cfg = config.get("global") if isinstance(config.get("global"), dict) else {}
run_dir = str(global_cfg.get("run_dir", "")).strip()
return Path(run_dir) if run_dir else None
def _parse_status_time(value: Any) -> datetime | None:
text = str(value or "").strip()
if not text:
return None
try:
if text.endswith("Z"):
text = f"{text[:-1]}+00:00"
parsed = datetime.fromisoformat(text)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed
except ValueError:
return None
def _elapsed_from_run_status(run_status: dict[str, Any] | None) -> str:
if not run_status:
return ""
start = _parse_status_time(run_status.get("start_time"))
end = _parse_status_time(run_status.get("end_time"))
if start is None or end is None:
return ""
return str(max(0, int((end - start).total_seconds())))
def _local_failure_reason(run_status: dict[str, Any] | None, status: str) -> str | None:
normalized = status.strip().lower()
if normalized == "success":
return None
if run_status is None:
return "missing_run_status"
if normalized == "running":
return "running"
if normalized == "failed":
failed_node = str(run_status.get("failed_node", "")).strip()
exception_type = str(run_status.get("exception_type", "")).strip()
if failed_node and exception_type:
return f"{failed_node}:{exception_type}"
return exception_type or failed_node or "failed"
return f"run_status_{normalized or 'unknown'}"
def _local_state_from_run_status(run_status: dict[str, Any] | None) -> tuple[str, str, str | None]:
if run_status is None:
return "UNKNOWN", "", "missing_run_status"
status = str(run_status.get("status", "")).strip().lower()
if status == "success":
return "COMPLETED", "0", None
if status == "failed":
return "FAILED", "1", _local_failure_reason(run_status, status)
if status == "running":
return "RUNNING", "", _local_failure_reason(run_status, status)
return "UNKNOWN", "", _local_failure_reason(run_status, status)
def _failure_reason_from_attempt(attempt: dict[str, Any] | None) -> str | None:
if not attempt:
return None
reason = str(attempt.get("failure_reason", "")).strip()
if reason:
return reason
return_code = attempt.get("return_code")
if return_code not in {None, "", 0, "0"}:
return "nonzero_return_code"
state = str(attempt.get("state", "")).strip().upper()
if state in {"FAILED", "CANCELLED", "TIMEOUT"}:
return state.lower()
if state == "DRY_RUN":
return "dry_run"
return None
def _merge_local_state(
*,
run_status: dict[str, Any] | None,
attempt: dict[str, Any] | None,
) -> tuple[str, str, str | None]:
status_state, status_exit_code, status_failure = _local_state_from_run_status(run_status)
if not attempt:
return status_state, status_exit_code, status_failure
attempt_state = str(attempt.get("state", "")).strip().upper()
attempt_return_code = attempt.get("return_code")
attempt_exit_code = "" if attempt_return_code in {None, ""} else str(attempt_return_code)
attempt_failure = _failure_reason_from_attempt(attempt)
if attempt_state in {"FAILED", "CANCELLED", "TIMEOUT"} or attempt_return_code not in {
None,
"",
0,
"0",
}:
return "FAILED", attempt_exit_code or status_exit_code, attempt_failure or status_failure
if attempt_state == "DRY_RUN":
return "DRY_RUN", "", attempt_failure
if attempt_state == "SKIPPED":
if status_state == "COMPLETED":
return "COMPLETED", "0", None
return "SKIPPED", attempt_exit_code, attempt_failure or status_failure
if attempt_state == "COMPLETED":
if status_state in {"COMPLETED", "UNKNOWN"}:
return "COMPLETED", attempt_exit_code or "0", None
return status_state, attempt_exit_code or status_exit_code, status_failure
return status_state, attempt_exit_code or status_exit_code, status_failure or attempt_failure
def _build_local_jobs(
valid_manifest_records: list[dict[str, Any]],
doe_dir: Path,
execution_attempts: list[dict[str, Any]] | None = None,
execution_manifest_path: Path | None = None,
) -> list[ChildJob]:
attempts_by_case_id, attempts_by_config_path = _index_execution_attempts(
execution_attempts or [],
doe_dir,
)
jobs: list[ChildJob] = []
for idx, record in enumerate(valid_manifest_records, start=1):
cfg_path = _resolve_manifest_config_path(record.get("config_path"), doe_dir)
cfg = _load_yaml_config(cfg_path)
run_dir = _run_dir_from_config(cfg)
run_status = _load_json(run_dir / "run_status.json") if run_dir else None
case_id = str(record.get("case_id", "")).strip()
cfg_key = _normalize_path_key(cfg_path, doe_dir)
attempt = attempts_by_case_id.get(case_id) or attempts_by_config_path.get(cfg_key)
state, exit_code, failure_reason = _merge_local_state(
run_status=run_status,
attempt=attempt,
)
case_name = _parse_case_name(str(cfg_path) if cfg_path else record.get("config_path"))
profile, parsed_model_type, parsed_split_mode, parsed_split_strategy = _extract_case_fields(case_name)
train_cfg = cfg.get("train") if isinstance(cfg.get("train"), dict) else {}
train_model_cfg = train_cfg.get("model") if isinstance(train_cfg.get("model"), dict) else {}
model_type = str(train_model_cfg.get("type", "")).strip() or parsed_model_type
split_mode = str(_get_dotted(cfg, "split.mode", parsed_split_mode or "")).strip() or None
split_strategy = str(_get_dotted(cfg, "split.strategy", parsed_split_strategy or "")).strip() or None
scaler = _infer_scaler(cfg) if cfg else None
jobs.append(
ChildJob(
job_id=f"local_{idx:05d}",
case_name=case_name,
parent_case_id=str(record.get("parent_case_id", "")).strip() or None,
config_path=str(cfg_path) if cfg_path else record.get("config_path"),
profile=profile,
model_type=model_type,
scaler=scaler,
split_mode=split_mode,
split_strategy=split_strategy,
scientific_config_id=str(record.get("scientific_config_id", "")).strip() or None,
execution_label=str(record.get("execution_label", "")).strip() or None,
state=state,
exit_code=exit_code,
elapsed=str(attempt.get("elapsed_seconds", "")).strip()
if attempt and str(attempt.get("elapsed_seconds", "")).strip()
else _elapsed_from_run_status(run_status),
failure_reason=failure_reason,
log_path=str(attempt.get("log_path", "")).strip() if attempt else None,
execution_manifest_path=str(execution_manifest_path) if execution_manifest_path else None,
)
)
return jobs
def _parse_case_name(case_config_path: str | None) -> str | None:
if not case_config_path:
return None
return Path(case_config_path).stem
def _extract_case_fields(case_name: str | None) -> tuple[str | None, str | None, str | None, str | None]:
if not case_name:
return None, None, None, None
parts = case_name.split("__")
if len(parts) < 5:
return None, None, None, None
return parts[1], parts[2], parts[3], parts[4]
def _derive_failure_reason(job_state: str, step_states: list[str]) -> str | None:
state = (job_state or "").upper()
step_upper = [s.upper() for s in step_states]
if state == "COMPLETED":
return None
if "OUT_OF_MEMORY" in state or any("OUT_OF_MEMORY" in s for s in step_upper):
return "out_of_memory"
if "TIMEOUT" in state:
return "timeout"
if "CANCELLED" in state:
return "cancelled"
if "FAILED" in state:
return "failed_other"
if "PENDING" in state:
return "pending"
if "RUNNING" in state:
return "running"
return "other"
def _safe_float(value: Any) -> float | None:
if value is None:
return None
s = str(value).strip()
if not s:
return None
try:
return float(s)
except (TypeError, ValueError):
return None
def _parse_case_index(case_name: str) -> int | None:
m = re.match(r"^case_(\d+)", case_name or "")
if not m:
return None
try:
return int(m.group(1))
except ValueError:
return None
def _load_all_runs_metrics_csv(path: Path) -> list[dict[str, str]]:
rows: list[dict[str, str]] = []
if not path.exists():
return rows
with path.open("r", encoding="utf-8", newline="") as fh:
reader = csv.DictReader(fh)
for row in reader:
rows.append({k: (v if v is not None else "") for k, v in row.items()})
return rows
def _stable_hash(payload: Any) -> str:
body = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(body.encode("utf-8")).hexdigest()
def _get_dotted(container: dict[str, Any], dotted: str, default: Any = None) -> Any:
current: Any = container
for part in [p for p in dotted.split(".") if p]:
if not isinstance(current, dict) or part not in current:
return default
current = current[part]
return current
def _pop_dotted(container: dict[str, Any], dotted: str) -> None:
parts = [p for p in dotted.split(".") if p]
if not parts:
return
parents: list[tuple[dict[str, Any], str]] = []
current: Any = container
for part in parts[:-1]:
if not isinstance(current, dict) or part not in current:
return
parents.append((current, part))
current = current[part]
if not isinstance(current, dict):
return
current.pop(parts[-1], None)
while parents:
parent, key = parents.pop()
child = parent.get(key)
if isinstance(child, dict) and not child:
parent.pop(key, None)
else:
break
def _infer_feature_input(config: dict[str, Any]) -> str | None:
nodes = ((config.get("pipeline") or {}).get("nodes") if isinstance(config.get("pipeline"), dict) else None) or []
if "featurize.ecfp4_rdkit" in nodes:
return "featurize.ecfp4_rdkit"
if "featurize.morgan" in nodes:
return "featurize.morgan"
if "featurize.rdkit_labeled" in nodes:
return "featurize.rdkit_labeled"
if "featurize.rdkit" in nodes:
return "featurize.rdkit"
if "featurize.none" in nodes or "use.curated_features" in nodes:
return "featurize.none"
pipeline_cfg = config.get("pipeline")
if isinstance(pipeline_cfg, dict):
configured = str(pipeline_cfg.get("feature_input", "")).strip()
if configured:
if configured == "use.curated_features":
return "featurize.none"
return configured
model_type = str((((config.get("train") or {}).get("model") or {}).get("type", ""))).strip().lower()
if _is_chemprop_like_model_type(model_type):
return "smiles_native"
return "none" if "train" in nodes else None
def _infer_scaler(config: dict[str, Any]) -> str | None:
scaler = str(_get_dotted(config, "preprocess.scaler", "")).strip()
return scaler or None
def _infer_scaler_from_config_path(config_path: str | None) -> str | None:
if not config_path or yaml is None:
return None
path = Path(config_path)
if not path.exists():
return None
try:
cfg = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
except Exception:
return None
if not isinstance(cfg, dict):
return None
return _infer_scaler(cfg)
def _is_chemprop_like_model_type(model_type: str) -> bool:
return str(model_type).strip().lower() in {"chemprop", "chemeleon"}
def _scientific_config_payload(config: dict[str, Any]) -> dict[str, Any]:
payload = json.loads(json.dumps(config))
global_cfg = payload.get("global")
if isinstance(global_cfg, dict):
global_cfg.pop("base_dir", None)
global_cfg.pop("run_dir", None)
global_cfg.pop("artifact_retention", None)
runs_cfg = global_cfg.get("runs")
if isinstance(runs_cfg, dict):
runs_cfg.pop("id", None)
split_mode = str(_get_dotted(payload, "split.mode", "")).strip().lower()
if split_mode == "cv":
_pop_dotted(payload, "split.cv.fold_index")
_pop_dotted(payload, "split.cv.repeat_index")
elif split_mode == "nested_holdout_cv":
_pop_dotted(payload, "split.inner.fold_index")
_pop_dotted(payload, "split.inner.repeat_index")
return payload
def _scientific_config_id(config: dict[str, Any]) -> str:
return _stable_hash(_scientific_config_payload(config))
def _execution_label(config: dict[str, Any]) -> str:
split_mode = str(_get_dotted(config, "split.mode", "holdout")).strip().lower() or "holdout"
if split_mode == "cv":
fold_index = int(_get_dotted(config, "split.cv.fold_index", 0))
repeat_index = int(_get_dotted(config, "split.cv.repeat_index", 0))
return f"rep{repeat_index}_fold{fold_index}"
if split_mode == "nested_holdout_cv":
stage = str(_get_dotted(config, "split.stage", "inner")).strip().lower() or "inner"
if stage == "inner":
fold_index = int(_get_dotted(config, "split.inner.fold_index", 0))
repeat_index = int(_get_dotted(config, "split.inner.repeat_index", 0))
return f"{stage}_rep{repeat_index}_fold{fold_index}"
return stage
return split_mode
def _mean(values: list[float]) -> float:
return sum(values) / len(values) if values else 0.0
def _std(values: list[float]) -> float:
if len(values) <= 1:
return 0.0
mu = _mean(values)
variance = sum((v - mu) ** 2 for v in values) / len(values)
return math.sqrt(variance)
def _join_unique(values: list[str]) -> str:
out: list[str] = []
seen: set[str] = set()
for value in values:
text = str(value).strip()
if not text or text in seen:
continue
seen.add(text)
out.append(text)
return ";".join(out)
def _failure_summary(rows: list[dict[str, Any]]) -> str:
counts = Counter(str(r.get("failure_reason", "")).strip() for r in rows if str(r.get("failure_reason", "")).strip())
if not counts:
return ""
return ",".join(f"{reason}={count}" for reason, count in sorted(counts.items()))
def _load_json(path: Path) -> dict[str, Any] | None:
if not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return None
def _resolve_metrics_path(run_dir: Path, model_type: str) -> Path:
if _is_chemprop_like_model_type(model_type):
return run_dir / "chemprop_metrics.json"
return run_dir / f"{model_type}_metrics.json"
def _resolve_split_metrics(
model_type: str,
run_dir: Path,
metrics_payload: dict[str, Any] | None,
) -> dict[str, Any] | None:
if metrics_payload:
split_metrics_path = metrics_payload.get("split_metrics_path")
if split_metrics_path:
path = Path(str(split_metrics_path))
payload = _load_json(path)
if payload is not None:
return payload
if _is_chemprop_like_model_type(model_type):
fallback = run_dir / "chemprop_split_metrics.json"
else:
fallback = run_dir / f"{model_type}_split_metrics.json"
return _load_json(fallback)
def _append_failure_reason(existing: str | None, reason: str) -> str:
current = str(existing or "").strip()
if not current:
return reason
if reason in {chunk.strip() for chunk in current.split(";")}:
return current
return f"{current}; {reason}"
def _job_missing_expected_metrics(job: ChildJob) -> bool:
if job.state != "COMPLETED" or not job.config_path:
return False
cfg_path = Path(job.config_path)
cfg = _load_yaml_config(cfg_path)
if not cfg:
return False
run_dir = _run_dir_from_config(cfg)
train_cfg = cfg.get("train") if isinstance(cfg.get("train"), dict) else {}
train_model_cfg = train_cfg.get("model") if isinstance(train_cfg.get("model"), dict) else {}
model_type = job.model_type or str(train_model_cfg.get("type", "")).strip()
if not run_dir or not model_type:
return False
metrics_path = _resolve_metrics_path(run_dir, model_type)
return _load_json(metrics_path) is None
def _job_missing_split_metrics(job: ChildJob) -> bool:
if job.state != "COMPLETED" or not job.config_path:
return False
cfg_path = Path(job.config_path)
cfg = _load_yaml_config(cfg_path)
if not cfg:
return False
run_dir = _run_dir_from_config(cfg)
train_cfg = cfg.get("train") if isinstance(cfg.get("train"), dict) else {}
train_model_cfg = train_cfg.get("model") if isinstance(train_cfg.get("model"), dict) else {}
model_type = job.model_type or str(train_model_cfg.get("type", "")).strip()
if not run_dir or not model_type:
return False
metrics_path = _resolve_metrics_path(run_dir, model_type)
metrics_payload = _load_json(metrics_path)
if metrics_payload is None:
return False
split_metrics = _resolve_split_metrics(
model_type=model_type,
run_dir=run_dir,
metrics_payload=metrics_payload,
)
if not isinstance(split_metrics, dict):
return True
return _extract_primary_metric(split_metrics) is None
def _job_has_top_level_metric(job: ChildJob) -> bool:
if job.state != "COMPLETED" or not job.config_path:
return False
cfg_path = Path(job.config_path)
cfg = _load_yaml_config(cfg_path)
if not cfg:
return False
run_dir = _run_dir_from_config(cfg)
train_cfg = cfg.get("train") if isinstance(cfg.get("train"), dict) else {}
train_model_cfg = train_cfg.get("model") if isinstance(train_cfg.get("model"), dict) else {}
model_type = job.model_type or str(train_model_cfg.get("type", "")).strip()
if not run_dir or not model_type:
return False
metrics_path = _resolve_metrics_path(run_dir, model_type)
metrics_payload = _load_json(metrics_path)
if not isinstance(metrics_payload, dict):
return False
for metric in ("auc", "r2", "mae", "rmse", "accuracy", "f1", "auprc"):
if _safe_float(metrics_payload.get(metric)) is not None:
return True
return False
def _summarize_metric_artifacts(jobs: list[ChildJob]) -> dict[str, Any]:
completed_jobs = [job for job in jobs if job.state == "COMPLETED"]
missing_metrics = sum(1 for job in completed_jobs if _job_missing_expected_metrics(job))
missing_split_metrics = sum(1 for job in completed_jobs if _job_missing_split_metrics(job))
top_level_metric_jobs = sum(1 for job in completed_jobs if _job_has_top_level_metric(job))
return {
"completed_jobs": len(completed_jobs),
"missing_metrics": missing_metrics,
"top_level_metric_jobs": top_level_metric_jobs,
"split_metric_jobs": len(completed_jobs) - missing_split_metrics,
"missing_split_metrics": missing_split_metrics,
"primary_metric_complete": missing_metrics == 0,
"split_diagnostics_complete": missing_split_metrics == 0,
}
def _mark_missing_metric_jobs(jobs: list[ChildJob]) -> list[ChildJob]:
updated: list[ChildJob] = []
for job in jobs:
if _job_missing_expected_metrics(job):
updated.append(
replace(
job,
state="PARTIAL",
failure_reason=_append_failure_reason(job.failure_reason, "missing_metrics"),
)
)
else:
updated.append(job)
return updated
def _eval_segment_metrics(split_metrics: dict[str, Any]) -> tuple[dict[str, Any], str] | tuple[None, None]:
"""Return (eval_dict, segment_name) for split-based model comparison.
Time-series runs may set ``selection_segment`` to ``val`` so DOE/Optuna
comparisons match the notebooks: hyperparameters are selected on validation
RMSE, and the test split remains held out for the final fixed configuration.
Older metrics without this field keep the historical test-then-val fallback.
"""
preferred = str(split_metrics.get("selection_segment", "")).strip().lower()
if preferred in {"val", "test"}:
chosen = split_metrics.get(preferred)
if isinstance(chosen, dict) and chosen:
return chosen, preferred
test = split_metrics.get("test")
if isinstance(test, dict) and test:
return test, "test"
val = split_metrics.get("val")
if isinstance(val, dict) and val:
return val, "val"
return None, None
def _extract_primary_metric(split_metrics: dict[str, Any]) -> str | None:
train = split_metrics.get("train")
if not isinstance(train, dict):
return None
# Evaluation segment is the trainer's selection segment when provided,
# otherwise test if present, else val.
eval_metrics, _segment = _eval_segment_metrics(split_metrics)
if eval_metrics is None:
return None
# Prefer "higher-is-better" metrics for a clean generalization gap signal.
for candidate in ("r2", "auc", "auprc", "accuracy", "f1"):
if candidate in train and candidate in eval_metrics:
if _safe_float(train.get(candidate)) is not None and _safe_float(eval_metrics.get(candidate)) is not None:
return candidate
# Time-series (Adaptive NVAR) workflows emit horizon-specific RMSE
# (rmse_h25, rmse_h50, ...) and/or a plain rmse, rather than the tabular
# classification/regression metrics above. These are lower-is-better, but
# for the purpose of "does this run have usable split metrics?" any one of
# them present in both train and the eval segment is sufficient. Prefer the
# largest horizon (the headline forecast metric), then smaller horizons,
# then a bare rmse, mirroring the trainer's own primary-metric choice.
horizon_candidates = sorted(
(
key
for key in train
if key.startswith("rmse_h") and key in eval_metrics
),
key=lambda k: _horizon_sort_key(k),
reverse=True,
)
for candidate in (*horizon_candidates, "rmse"):
if candidate in train and candidate in eval_metrics:
if _safe_float(train.get(candidate)) is not None and _safe_float(eval_metrics.get(candidate)) is not None:
return candidate
return None
def _horizon_sort_key(key: str) -> int:
"""Sort key for 'rmse_h<N>' metric names; non-numeric suffixes sort last."""
try:
return int(key.split("rmse_h", 1)[1])
except (IndexError, ValueError):
return -1
def _build_generalization_records(
jobs: list[ChildJob],
overfit_threshold: float,
underfit_threshold_r2: float,
underfit_threshold_auc: float,
) -> list[GeneralizationRecord]:
records: list[GeneralizationRecord] = []
for job in jobs:
if job.state != "COMPLETED":
continue
if not job.config_path:
continue
cfg_path = Path(job.config_path)
if not cfg_path.exists():
continue
if yaml is None:
continue