Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
3293 lines (2971 loc) · 126 KB
/
Copy pathmain.py
File metadata and controls
3293 lines (2971 loc) · 126 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
# an example workflow that uses ChemBL bioactivty data
import csv
import glob
import hashlib
import json
import logging
import os
import subprocess
import sys
import time
import traceback
from datetime import datetime, timezone
import yaml
import pandas as pd
import joblib
import numpy as np
from contracts import (
ANALYZE_EDA_INPUT_2CLASS_CONTRACT,
ANALYZE_EDA_INPUT_3CLASS_CONTRACT,
ANALYZE_EDA_GENERIC_INPUT_CONTRACT,
ANALYZE_EDA_OUTPUT_CONTRACT,
ANALYZE_STATS_INPUT_CONTRACT,
ANALYZE_STATS_OUTPUT_CONTRACT,
CURATE_INPUT_CONTRACT,
CURATE_OUTPUT_CONTRACT,
FEATURIZE_RDKIT_INPUT_CONTRACT,
FEATURIZE_RDKIT_OUTPUT_CONTRACT,
FEATURIZE_RDKIT_LABELED_INPUT_CONTRACT,
FEATURIZE_RDKIT_LABELED_OUTPUT_LABELS_CONTRACT,
FEATURIZE_MORGAN_INPUT_CONTRACT,
FEATURIZE_MORGAN_OUTPUT_CONTRACT,
PREPROCESS_FEATURES_INPUT_CONTRACT,
PREPROCESS_FEATURES_OUTPUT_CONTRACT,
PREPROCESS_ARTIFACTS_CONTRACT,
SELECT_FEATURES_INPUT_FEATURES_CONTRACT,
SELECT_FEATURES_OUTPUT_CONTRACT,
SELECT_FEATURES_LIST_CONTRACT,
EXPLAIN_INPUT_MODEL_CONTRACT,
EXPLAIN_OUTPUT_CONTRACT,
GET_DATA_INPUT_CONTRACT,
GET_DATA_OUTPUT_CONTRACT,
DESCRIPTORS_CONTRACT,
IC50_INPUT_CONTRACT,
LABEL_IC50_INPUT_CONTRACT,
LABEL_IC50_OUTPUT_2CLASS_CONTRACT,
LABEL_IC50_OUTPUT_3CLASS_CONTRACT,
MODEL_LABELS_CONTRACT,
PIC50_2CLASS_CONTRACT,
PIC50_3CLASS_CONTRACT,
PREPROCESSED_CONTRACT,
TRAIN_INPUT_FEATURES_CONTRACT,
TRAIN_INPUT_LABELS_CONTRACT,
TRAIN_OUTPUT_CONTRACT,
ContractSpec,
bind_output_path,
make_target_column_contract,
validate_contract,
)
from MLModels import data_preprocessing
from MLModels import train_models
from utilities import splitters
from utilities.config_validation import validate_config_strict
_EXPLICIT_FEATURE_INPUT_NODES = {
"featurize.none",
"use.curated_features",
"featurize.rdkit",
"featurize.rdkit_labeled",
"featurize.morgan",
"featurize.ecfp4_rdkit",
}
def build_paths(base_dir: str) -> dict[str, str]:
return {
"raw": os.path.join(base_dir, "raw.csv"),
"raw_sample": os.path.join(base_dir, "raw_sample.csv"),
"raw_sample_meta": os.path.join(base_dir, "raw_sample.meta.json"),
"preprocessed": os.path.join(base_dir, "preprocessed.csv"),
"curated": os.path.join(base_dir, "curated.csv"),
"curated_labeled": os.path.join(base_dir, "curated_labeled.csv"),
"curated_smiles": os.path.join(base_dir, "curated_smiles.csv"),
"pic50_3class": os.path.join(base_dir, "bioactivity_3class_pIC50.csv"),
"pic50_2class": os.path.join(base_dir, "bioactivity_2class_pIC50.csv"),
"rdkit_descriptors": os.path.join(base_dir, "rdkit_descriptors.csv"),
"rdkit_labeled": os.path.join(base_dir, "rdkit_descriptors_labeled.csv"),
"morgan_fingerprints": os.path.join(base_dir, "morgan_fingerprints.csv"),
"morgan_labeled": os.path.join(base_dir, "morgan_fingerprints_labeled.csv"),
"morgan_meta": os.path.join(base_dir, "morgan_meta.json"),
"ecfp4_rdkit_features": os.path.join(base_dir, "ecfp4_rdkit_features.csv"),
"ecfp4_rdkit_labeled": os.path.join(base_dir, "ecfp4_rdkit_labeled.csv"),
"ecfp4_rdkit_meta": os.path.join(base_dir, "ecfp4_rdkit_meta.json"),
"preprocessed_features": os.path.join(base_dir, "preprocessed_features.csv"),
"preprocessed_labels": os.path.join(base_dir, "preprocessed_labels.csv"),
"selected_features": os.path.join(base_dir, "selected_features.csv"),
"selected_features_list": os.path.join(base_dir, "selected_features.txt"),
"preprocess_artifacts": os.path.join(base_dir, "preprocess_artifacts.joblib"),
"split_dir": os.path.join(base_dir, "splits"),
}
def load_config(path: str) -> dict:
with open(path, "r", encoding="utf-8") as f:
if path.endswith((".yaml", ".yml")):
return yaml.safe_load(f)
return json.load(f)
def sample_csv(input_path: str, output_path: str, max_rows: int) -> None:
with open(input_path, "r", encoding="utf-8") as infile, open(
output_path, "w", encoding="utf-8", newline=""
) as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for idx, row in enumerate(reader):
writer.writerow(row)
if idx >= max_rows:
break
_DATASET_SAMPLE_STRATEGIES = {"random", "stratified"}
_DATASET_SAMPLE_KEYS = {"fraction", "seed", "strategy", "stratify_column"}
def _sample_row_count(total_rows: int, fraction: float) -> int:
if total_rows <= 0:
return 0
return min(total_rows, max(1, int(total_rows * fraction + 0.5)))
def _resolve_sample_fraction(value: object) -> float:
if isinstance(value, bool):
raise ValueError("get_data.sample.fraction must be a number in the interval (0, 1].")
try:
fraction = float(value)
except (TypeError, ValueError) as exc:
raise ValueError("get_data.sample.fraction must be a number in the interval (0, 1].") from exc
if not 0 < fraction <= 1:
raise ValueError("get_data.sample.fraction must be a number in the interval (0, 1].")
return fraction
def _resolve_sample_seed(value: object, *, default_seed: int) -> int:
if value is None:
return int(default_seed)
if isinstance(value, bool):
raise ValueError("get_data.sample.seed must be an integer.")
if isinstance(value, int):
return value
if isinstance(value, float):
if value.is_integer():
return int(value)
raise ValueError("get_data.sample.seed must be an integer.")
if isinstance(value, str):
text = value.strip()
if text and text.lstrip("+-").isdigit():
return int(text)
raise ValueError("get_data.sample.seed must be an integer.")
def _resolve_sample_strategy(value: object) -> str:
strategy = str(value or "random").strip().lower()
if strategy not in _DATASET_SAMPLE_STRATEGIES:
allowed = ", ".join(sorted(_DATASET_SAMPLE_STRATEGIES))
raise ValueError(f"get_data.sample.strategy must be one of: {allowed}.")
return strategy
def _random_sample_frame(df: pd.DataFrame, *, fraction: float, seed: int) -> pd.DataFrame:
sample_size = _sample_row_count(len(df), fraction)
if sample_size == len(df):
return df.copy()
return df.sample(n=sample_size, random_state=seed).sort_index()
def _allocate_stratified_counts(group_sizes: list[int], desired_count: int) -> list[int]:
total_rows = sum(group_sizes)
if total_rows <= 0 or desired_count <= 0:
return [0 for _ in group_sizes]
desired_count = min(total_rows, desired_count)
nonempty_group_count = sum(1 for size in group_sizes if size > 0)
if desired_count == total_rows:
return list(group_sizes)
if desired_count < nonempty_group_count:
return [1 if size > 0 else 0 for size in group_sizes]
quotas = [size * desired_count / total_rows for size in group_sizes]
counts = [
min(size, max(1, int(quota)))
if size > 0
else 0
for size, quota in zip(group_sizes, quotas)
]
while sum(counts) > desired_count:
candidates = [idx for idx, count in enumerate(counts) if count > 1]
if not candidates:
break
idx = max(candidates, key=lambda candidate: (counts[candidate] - quotas[candidate], counts[candidate]))
counts[idx] -= 1
while sum(counts) < desired_count:
candidates = [idx for idx, (count, size) in enumerate(zip(counts, group_sizes)) if count < size]
if not candidates:
break
idx = max(candidates, key=lambda candidate: (quotas[candidate] - counts[candidate], group_sizes[candidate]))
counts[idx] += 1
return counts
def _stratified_sample_frame(
df: pd.DataFrame,
*,
fraction: float,
seed: int,
stratify_column: str,
) -> pd.DataFrame:
if df.empty:
return df.copy()
rng = np.random.default_rng(seed)
sampled_groups = []
groups = [group for _, group in df.groupby(stratify_column, sort=False, dropna=False)]
desired_count = _sample_row_count(len(df), fraction)
group_sizes = [len(group) for group in groups]
group_sample_sizes = _allocate_stratified_counts(group_sizes, desired_count)
if sum(group_sample_sizes) > desired_count:
logging.warning(
"get_data.sample.strategy=stratified requested %d rows but found %d classes; "
"sampling one row per class (%d rows total).",
desired_count,
len(groups),
sum(group_sample_sizes),
)
for group, sample_size in zip(groups, group_sample_sizes):
if sample_size <= 0:
continue
if sample_size == len(group):
sampled_groups.append(group.copy())
continue
group_seed = int(rng.integers(0, 2**32 - 1))
sampled_groups.append(group.sample(n=sample_size, random_state=group_seed))
if not sampled_groups:
return df.iloc[0:0].copy()
return pd.concat(sampled_groups).sort_index()
def _stringify_sample_group(value: object) -> str:
if pd.isna(value):
return "<NA>"
return str(value)
def _sample_group_counts(df: pd.DataFrame, column: str) -> dict[str, int]:
counts: dict[str, int] = {}
if column not in df.columns:
return counts
for value, count in df.groupby(column, sort=False, dropna=False).size().items():
key = _stringify_sample_group(value)
counts[key] = counts.get(key, 0) + int(count)
return counts
def _resolve_sample_stratify_column(context: dict, sample_config: dict) -> str:
candidates = [
sample_config.get("stratify_column"),
(context.get("label_config") or {}).get("source_column")
if isinstance(context.get("label_config"), dict)
else None,
(context.get("curate_config") or {}).get("label_column")
if isinstance(context.get("curate_config"), dict)
else None,
context.get("target_column"),
]
for candidate in candidates:
text = str(candidate or "").strip()
if text:
return text
return ""
def _apply_raw_dataset_sample(context: dict, raw_data_file: str) -> str:
get_data_config = context.get("get_data_config", {})
sample_config = get_data_config.get("sample") if isinstance(get_data_config, dict) else None
if sample_config is None:
return raw_data_file
if not isinstance(sample_config, dict):
raise ValueError("get_data.sample must be a mapping with fraction, seed, and strategy fields.")
unknown_keys = sorted(set(sample_config) - _DATASET_SAMPLE_KEYS)
if unknown_keys:
raise ValueError(
"get_data.sample contains unknown key(s): " + ", ".join(unknown_keys)
)
fraction = _resolve_sample_fraction(sample_config.get("fraction"))
seed = _resolve_sample_seed(
sample_config.get("seed"),
default_seed=int(context.get("global_random_state", 42)),
)
requested_strategy = _resolve_sample_strategy(sample_config.get("strategy"))
effective_strategy = requested_strategy
target_column = str(context.get("target_column", "")).strip()
stratify_column = _resolve_sample_stratify_column(context, sample_config)
task_type = str(context.get("task_type", "regression")).strip().lower()
df = pd.read_csv(raw_data_file)
if requested_strategy == "stratified":
if task_type != "classification":
logging.warning(
"get_data.sample.strategy=stratified is only class-stratified for "
"classification; falling back to random sampling for task_type=%r.",
task_type,
)
effective_strategy = "random"
elif stratify_column not in df.columns:
logging.warning(
"get_data.sample.strategy=stratified requested target column %r, "
"but it is missing from the raw dataset; falling back to random sampling.",
stratify_column,
)
effective_strategy = "random"
if effective_strategy == "stratified":
sampled_df = _stratified_sample_frame(
df,
fraction=fraction,
seed=seed,
stratify_column=stratify_column,
)
else:
sampled_df = _random_sample_frame(df, fraction=fraction, seed=seed)
sampled_path = context["paths"]["raw_sample"]
sampled_df.to_csv(sampled_path, index=False)
metadata = {
"source_path": raw_data_file,
"sampled_path": sampled_path,
"source_rows": int(len(df)),
"sampled_rows": int(len(sampled_df)),
"fraction": fraction,
"seed": seed,
"strategy": requested_strategy,
"effective_strategy": effective_strategy,
"task_type": task_type,
"target_column": target_column,
"stratify_column": stratify_column if effective_strategy == "stratified" else None,
"actual_fraction": float(len(sampled_df) / len(df)) if len(df) else 0.0,
}
if effective_strategy == "stratified" and stratify_column in df.columns:
metadata["source_strata_counts"] = _sample_group_counts(df, stratify_column)
metadata["sampled_strata_counts"] = _sample_group_counts(sampled_df, stratify_column)
metadata_path = context["paths"].get("raw_sample_meta", f"{sampled_path}.meta.json")
_write_json_atomic(metadata_path, metadata)
context["raw_sample_metadata"] = metadata
logging.info(
"Applied dataset sample: %d/%d rows using %s strategy (fraction=%s, seed=%s).",
len(sampled_df),
len(df),
effective_strategy,
fraction,
seed,
)
return sampled_path
def resolve_run_dir(config: dict) -> str:
global_config = config.get("global", {})
run_dir = global_config.get("run_dir")
if run_dir:
return run_dir
runs = global_config.get("runs", {})
if runs.get("enabled"):
run_id = runs.get("id")
if not run_id:
run_id = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
return os.path.join("runs", run_id)
return "results"
def _as_bool(value: object) -> bool:
if isinstance(value, bool):
return value
if value is None:
return False
if isinstance(value, str):
return value.strip().lower() in {"1", "true", "yes", "on"}
return bool(value)
def _resolve_log_level(global_config: dict) -> int:
configured = global_config.get("log_level")
if configured is not None:
if isinstance(configured, int):
return configured
if isinstance(configured, str):
level = getattr(logging, configured.strip().upper(), None)
if isinstance(level, int):
return level
if _as_bool(global_config.get("debug", False)):
return logging.DEBUG
return logging.INFO
def _resolve_seed(global_seed: int, override: object | None = None) -> int:
if override is None:
return int(global_seed)
return int(override)
def _resolve_artifact_retention(global_config: dict) -> str:
retention = str(
global_config.get("artifact_retention", _ARTIFACT_RETENTION_FULL)
).strip().lower()
if not retention:
return _ARTIFACT_RETENTION_FULL
if retention not in _SUPPORTED_ARTIFACT_RETENTION:
supported = ", ".join(sorted(_SUPPORTED_ARTIFACT_RETENTION))
raise ValueError(f"global.artifact_retention must be one of: {supported}")
return retention
def _track_heavy_artifact(context: dict, path: str) -> None:
if not isinstance(path, str):
return
clean = path.strip()
if not clean:
return
heavy = context.setdefault("_heavy_artifacts", set())
if not isinstance(heavy, set):
return
heavy.add(os.path.abspath(clean))
def _track_heavy_artifact_glob(context: dict, pattern: str) -> None:
if not isinstance(pattern, str):
return
clean = pattern.strip()
if not clean:
return
globs = context.setdefault("_heavy_artifact_globs", set())
if not isinstance(globs, set):
return
globs.add(os.path.abspath(clean))
def _path_is_within(path: str, roots: list[str]) -> bool:
abs_path = os.path.abspath(path)
for root in roots:
try:
if os.path.commonpath([abs_path, root]) == root:
return True
except ValueError:
continue
return False
def _apply_artifact_retention(context: dict, *, run_status: str) -> None:
retention = str(
context.get("artifact_retention", _ARTIFACT_RETENTION_FULL)
).strip().lower()
summary = {
"retention": retention,
"run_status": run_status,
"candidate_count": 0,
"deleted_count": 0,
"skipped_preexisting_count": 0,
"failed_delete_count": 0,
"failed_deletes": [],
}
if retention != _ARTIFACT_RETENTION_AUDIT_LIGHT:
context["artifact_retention_summary"] = summary
return
run_dir = str(context.get("run_dir", "")).strip()
base_dir = str(context.get("base_dir", "")).strip()
run_start_epoch: float | None
try:
run_start_epoch = float(context.get("run_start_epoch")) # type: ignore[arg-type]
except (TypeError, ValueError):
run_start_epoch = None
allowed_roots = [
os.path.abspath(root)
for root in (base_dir, run_dir)
if isinstance(root, str) and root.strip()
]
heavy_paths = context.get("_heavy_artifacts", set())
heavy_globs = context.get("_heavy_artifact_globs", set())
candidate_paths: set[str] = set()
if isinstance(heavy_paths, set):
candidate_paths.update(path for path in heavy_paths if isinstance(path, str) and path.strip())
if isinstance(heavy_globs, set):
for pattern in heavy_globs:
if not isinstance(pattern, str) or not pattern.strip():
continue
candidate_paths.update(glob.glob(pattern, recursive=True))
deleted_count = 0
skipped_preexisting_count = 0
failed_deletes: list[dict[str, str]] = []
summary["candidate_count"] = len(candidate_paths)
for path in sorted(candidate_paths):
if not os.path.isfile(path):
continue
if allowed_roots and not _path_is_within(path, allowed_roots):
failed_deletes.append({"path": path, "reason": "outside_allowed_roots"})
continue
if run_start_epoch is not None:
try:
if os.path.getmtime(path) + 1e-6 < run_start_epoch:
skipped_preexisting_count += 1
continue
except OSError as exc:
failed_deletes.append({"path": path, "reason": str(exc)})
continue
try:
os.remove(path)
deleted_count += 1
except OSError as exc:
failed_deletes.append({"path": path, "reason": str(exc)})
summary["deleted_count"] = deleted_count
summary["skipped_preexisting_count"] = skipped_preexisting_count
summary["failed_delete_count"] = len(failed_deletes)
summary["failed_deletes"] = failed_deletes
logging.info(
"Artifact retention '%s' applied after %s run: removed %d heavy artifact files.",
retention,
run_status,
deleted_count,
)
for failure in failed_deletes:
logging.warning(
"artifact retention could not remove '%s': %s",
failure["path"],
failure["reason"],
)
context["artifact_retention_summary"] = summary
def _configure_logging(run_dir: str, level: int = logging.INFO) -> None:
"""Configure root logger to emit to stdout and to <run_dir>/run.log.
This must be defined before any pipeline runner calls it.
"""
log_path = os.path.join(run_dir, "run.log")
logger = logging.getLogger()
logger.setLevel(level)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
if not any(
isinstance(h, logging.StreamHandler) and not isinstance(h, logging.FileHandler)
for h in logger.handlers
):
stream_handler = logging.StreamHandler()
stream_handler.setLevel(level)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
if not any(
isinstance(h, logging.FileHandler) and getattr(h, "baseFilename", "") == log_path
for h in logger.handlers
):
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
for handler in logger.handlers:
handler.setLevel(level)
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _stable_hash(payload: object) -> str:
body = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(body.encode("utf-8")).hexdigest()
def _hashable_config_payload(config: dict) -> dict:
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)
return payload
_PIPELINE_NODE_ALIASES = {
"use.curated_features": "featurize.none",
}
_CHEMPROP_LIKE_MODELS = {"chemprop", "chemeleon"}
_ARTIFACT_RETENTION_FULL = "full"
_ARTIFACT_RETENTION_AUDIT_LIGHT = "audit_light"
_SUPPORTED_ARTIFACT_RETENTION = {
_ARTIFACT_RETENTION_FULL,
_ARTIFACT_RETENTION_AUDIT_LIGHT,
}
def _canonicalize_pipeline_nodes(nodes: list[str]) -> list[str]:
return [_PIPELINE_NODE_ALIASES.get(str(node), str(node)) for node in nodes]
def _is_chemprop_like_model(model_type: object) -> bool:
return str(model_type or "").strip().lower() in _CHEMPROP_LIKE_MODELS
def _normalize_runtime_config(config: dict, nodes: list[str]) -> dict:
payload = json.loads(json.dumps(config))
pipeline_cfg = payload.get("pipeline")
if isinstance(pipeline_cfg, dict):
pipeline_cfg["nodes"] = list(nodes)
else:
payload["pipeline"] = {"nodes": list(nodes)}
return payload
def _git_sha() -> str | None:
try:
result = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
check=True,
capture_output=True,
text=True,
)
return result.stdout.strip() or None
except Exception:
return None
def _write_json_atomic(path: str, payload: dict) -> None:
directory = os.path.dirname(path) or "."
os.makedirs(directory, exist_ok=True)
temp_path = f"{path}.tmp.{os.getpid()}"
with open(temp_path, "w", encoding="utf-8") as fh:
json.dump(payload, fh, indent=2)
os.replace(temp_path, path)
def _run_subprocess(cmd: list[str], *, cwd: str | None = None) -> subprocess.CompletedProcess[str]:
"""Run a child process and raise with captured output on failure."""
result = subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
command = " ".join(str(part) for part in cmd)
stderr = (result.stderr or "").strip()
stdout = (result.stdout or "").strip()
details: list[str] = [
f"Command failed with exit code {result.returncode}: {command}",
]
if stdout:
details.append(f"stdout:\n{stdout}")
if stderr:
details.append(f"stderr:\n{stderr}")
raise RuntimeError("\n".join(details))
return result
def run_node_get_data(context: dict) -> None:
validate_contract(
bind_output_path(GET_DATA_INPUT_CONTRACT, context["config_path"]),
warn_only=False,
)
script_path = os.path.join("GetData", "get_data.py")
output_file = context["paths"]["raw"]
_run_subprocess([sys.executable, script_path, output_file, "--config", context["config_path"]])
validate_contract(bind_output_path(GET_DATA_OUTPUT_CONTRACT, output_file), warn_only=True)
sampled_file = _apply_raw_dataset_sample(context, output_file)
if sampled_file != output_file:
context["paths"]["raw_full"] = output_file
context["paths"]["raw"] = sampled_file
validate_contract(bind_output_path(GET_DATA_OUTPUT_CONTRACT, sampled_file), warn_only=True)
def run_node_curate(context: dict) -> None:
validate_contract(
bind_output_path(CURATE_INPUT_CONTRACT, context["paths"]["raw"]),
warn_only=False,
)
raw_data_file = context["paths"]["raw"]
pipeline_type = context["pipeline_type"]
get_data_config = context.get("get_data_config", {})
if pipeline_type == "qm9" and isinstance(get_data_config, dict) and "sample" not in get_data_config:
max_rows = get_data_config.get("max_rows")
if max_rows:
sampled_path = context["paths"]["raw_sample"]
sample_csv(raw_data_file, sampled_path, int(max_rows))
raw_data_file = sampled_path
curate_config = context["curate_config"]
target_column = context["target_column"]
properties_items = _as_str_list(curate_config.get("properties"))
if not properties_items:
if pipeline_type == "qm9" or context.get("task_type") == "classification":
properties_items = _as_str_list(target_column)
else:
properties_items = _as_str_list("standard_value")
properties = ",".join(properties_items)
script_path = os.path.join("utilities", "prepareActivityData.py")
preprocessed_file = context["paths"]["preprocessed"]
curated_file = context["paths"]["curated"]
curated_smiles_output = context["paths"]["curated_smiles"]
cmd = [
sys.executable,
script_path,
raw_data_file,
preprocessed_file,
curated_file,
curated_smiles_output,
"--active_threshold",
str(context["active_threshold"]),
"--inactive_threshold",
str(context["inactive_threshold"]),
"--properties",
properties,
]
smiles_column = curate_config.get("smiles_column")
if smiles_column:
cmd.extend(["--smiles_column", smiles_column])
cmd.extend(["--target_column", str(target_column)])
dedupe_strategy = curate_config.get("dedupe_strategy")
if dedupe_strategy:
cmd.extend(["--dedupe_strategy", dedupe_strategy])
label_column = curate_config.get("label_column")
if not label_column and context.get("task_type") == "classification":
label_column = context["target_column"]
if label_column:
cmd.extend(["--label_column", label_column])
if curate_config.get("require_neutral_charge"):
cmd.append("--require_neutral_charge")
if "prefer_largest_fragment" in curate_config:
if curate_config.get("prefer_largest_fragment"):
cmd.append("--prefer_largest_fragment")
else:
cmd.append("--no_prefer_largest_fragment")
if context["keep_all_columns"]:
cmd.append("--keep_all_columns")
if "drop_missing_smiles" in curate_config:
if _as_bool(curate_config.get("drop_missing_smiles", True)):
cmd.append("--drop_missing_smiles")
else:
cmd.append("--no_drop_missing_smiles")
if "drop_invalid_smiles" in curate_config:
if _as_bool(curate_config.get("drop_invalid_smiles", True)):
cmd.append("--drop_invalid_smiles")
else:
cmd.append("--no_drop_invalid_smiles")
if "drop_missing_target" in curate_config:
if _as_bool(curate_config.get("drop_missing_target", True)):
cmd.append("--drop_missing_target")
else:
cmd.append("--no_drop_missing_target")
required_non_null_columns = _as_str_list(curate_config.get("required_non_null_columns", []))
if required_non_null_columns:
cmd.extend(["--required_non_null_columns", ",".join(required_non_null_columns)])
row_filters = curate_config.get("row_filters", {})
if isinstance(row_filters, dict) and row_filters:
cmd.extend(["--row_filters", json.dumps(row_filters, separators=(",", ":"))])
_run_subprocess(cmd)
validate_contract(bind_output_path(PREPROCESSED_CONTRACT, preprocessed_file), warn_only=True)
validate_contract(bind_output_path(CURATE_OUTPUT_CONTRACT, curated_file), warn_only=True)
# Establish the canonical dataset path for downstream nodes.
context["curated_path"] = curated_file
def run_node_featurize_none(context: dict) -> None:
curated_path = context.get("curated_path", context["paths"]["curated"])
validate_contract(
bind_output_path(
make_target_column_contract(
name="featurize_none_input",
target_column=context["target_column"],
output_path=curated_path,
),
curated_path,
),
warn_only=False,
)
context["feature_matrix"] = curated_path
context["labels_matrix"] = curated_path
context["feature_method"] = "none"
def run_node_label_ic50(context: dict) -> None:
input_file = context.get("curated_path", context["paths"]["curated"])
validate_contract(
bind_output_path(LABEL_IC50_INPUT_CONTRACT, input_file),
warn_only=False,
)
script_path = os.path.join("utilities", "IC50_pIC50.py")
output_file_3class = context["paths"]["pic50_3class"]
output_file_2class = context["paths"]["pic50_2class"]
_run_subprocess(
[sys.executable, script_path, input_file, output_file_3class, output_file_2class]
)
validate_contract(
bind_output_path(LABEL_IC50_OUTPUT_3CLASS_CONTRACT, output_file_3class),
warn_only=True,
)
validate_contract(
bind_output_path(LABEL_IC50_OUTPUT_2CLASS_CONTRACT, output_file_2class),
warn_only=True,
)
context["labels_matrix"] = output_file_3class
# Treat the labeled pIC50 output as the canonical dataset for downstream nodes.
context["curated_path"] = output_file_3class
def run_node_analyze_stats(context: dict) -> None:
validate_contract(
bind_output_path(ANALYZE_STATS_INPUT_CONTRACT, context["paths"]["pic50_2class"]),
warn_only=False,
)
script_path = os.path.join("utilities", "stat_tests.py")
input_file = context["paths"]["pic50_2class"]
output_dir = context["base_dir"]
descriptor = context["target_column"]
tests = ["mannwhitney", "ttest"]
try:
stats_df = pd.read_csv(input_file)
if descriptor in stats_df.columns and stats_df[descriptor].nunique(dropna=True) <= 20:
tests.append("chi2")
else:
logging.info(
"Skipping chi2 for descriptor '%s' due to high cardinality/continuous values.",
descriptor,
)
except Exception as exc:
logging.warning("Could not inspect stats input for chi2 guard (%s). Running without chi2.", exc)
for test in tests:
_run_subprocess([sys.executable, script_path, input_file, output_dir, test, descriptor])
validate_contract(
bind_output_path(ANALYZE_STATS_OUTPUT_CONTRACT, output_dir),
warn_only=True,
)
def run_node_analyze_eda(context: dict) -> None:
from utilities.generic_eda import run_generic_eda
input_file = context.get("curated_path", context["paths"]["raw"])
validate_contract(
bind_output_path(ANALYZE_EDA_GENERIC_INPUT_CONTRACT, input_file),
warn_only=False,
)
analyze_cfg = context.get("analyze_config", {}) or {}
eda_cfg = analyze_cfg.get("eda", {}) if isinstance(analyze_cfg, dict) else {}
output_dir = str((eda_cfg or {}).get("output_dir") or os.path.join(context["run_dir"], "eda"))
run_generic_eda(
input_path=input_file,
output_dir=output_dir,
task_type=context.get("task_type"),
target_column=context.get("target_column"),
config=eda_cfg,
)
validate_contract(
bind_output_path(ANALYZE_EDA_OUTPUT_CONTRACT, output_dir),
warn_only=True,
)
def run_node_analyze_molecular_eda(context: dict) -> None:
"""Run the opt-in, dataset-scoped molecular EDA bundle."""
from utilities.molecular_analysis import run_molecular_eda_node
run_molecular_eda_node(context)
def run_node_analyze_publication_figures(context: dict) -> None:
"""Render only the publication figures explicitly selected in the config."""
from utilities.molecular_analysis import run_publication_figures_node
run_publication_figures_node(context)
def run_node_featurize_rdkit(context: dict) -> None:
validate_contract(
bind_output_path(
FEATURIZE_RDKIT_INPUT_CONTRACT,
context.get("curated_path", context["paths"]["curated"]),
),
warn_only=False,
)
# Use labeled descriptors so features and target live in a single canonical file.
script_path = os.path.join("GenDescriptors", "RDKit_descriptors_labeled.py")
input_file = context.get("curated_path", context["paths"]["curated"])
output_file = context["paths"]["rdkit_descriptors"]
labeled_output_file = context["paths"]["rdkit_labeled"]
_track_heavy_artifact(context, output_file)
_track_heavy_artifact(context, labeled_output_file)
_run_subprocess(
[
sys.executable,
script_path,
input_file,
output_file,
"--labeled-output-file",
labeled_output_file,
"--property-columns",
context["target_column"],
]
)
validate_contract(
bind_output_path(FEATURIZE_RDKIT_OUTPUT_CONTRACT, output_file),
warn_only=True,
)
validate_contract(
bind_output_path(FEATURIZE_RDKIT_LABELED_OUTPUT_LABELS_CONTRACT, labeled_output_file),
warn_only=True,
)
context["feature_matrix"] = labeled_output_file
context["labels_matrix"] = labeled_output_file
context["feature_method"] = "rdkit"
def run_node_featurize_rdkit_labeled(context: dict) -> None:
# Backward-compatible alias: use the same implementation as featurize.rdkit.
run_node_featurize_rdkit(context)
def run_node_featurize_morgan(context: dict) -> None:
validate_contract(
bind_output_path(
FEATURIZE_MORGAN_INPUT_CONTRACT,
context.get("curated_path", context["paths"]["curated"]),
),
warn_only=False,
)
script_path = os.path.join("GenDescriptors", "Morgan_fingerprints.py")
input_file = context.get("curated_path", context["paths"]["curated"])
output_file = context["paths"]["morgan_fingerprints"]
labeled_output = context["paths"]["morgan_labeled"]
_track_heavy_artifact(context, output_file)
_track_heavy_artifact(context, labeled_output)
featurize_config = context.get("featurize_config", {})
radius = featurize_config.get("radius", 2)
n_bits = featurize_config.get("n_bits", 2048)
cmd = [
sys.executable,
script_path,
input_file,
output_file,
"--radius",
str(radius),
"--n_bits",
str(n_bits),
"--labeled-output-file",
labeled_output,
"--property-columns",
context["target_column"],
]
_run_subprocess(cmd)
with open(context["paths"]["morgan_meta"], "w", encoding="utf-8") as meta_out:
json.dump(
{"radius": radius, "n_bits": n_bits},
meta_out,
indent=2,
)
validate_contract(
bind_output_path(FEATURIZE_MORGAN_OUTPUT_CONTRACT, output_file),
warn_only=True,
)
validate_contract(
make_target_column_contract(
name="featurize_morgan_labeled_output",
target_column=context["target_column"],
output_path=labeled_output,
),
warn_only=True,
)
context["feature_matrix"] = labeled_output
context["labels_matrix"] = labeled_output
context["feature_method"] = "morgan"
def run_node_featurize_ecfp4_rdkit(context: dict) -> None:
validate_contract(
bind_output_path(
FEATURIZE_MORGAN_INPUT_CONTRACT,
context.get("curated_path", context["paths"]["curated"]),
),
warn_only=False,
)
script_path = os.path.join("GenDescriptors", "ECFP4_RDKit_descriptors.py")
input_file = context.get("curated_path", context["paths"]["curated"])
output_file = context["paths"]["ecfp4_rdkit_features"]
labeled_output = context["paths"]["ecfp4_rdkit_labeled"]
metadata_output = context["paths"]["ecfp4_rdkit_meta"]
_track_heavy_artifact(context, output_file)