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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Mass_models.py Grouped-CV training with calibration & thresholding on tRNA profiles.
# Supports:
#   - train_mode: supervised / pu / both
#   - weight_mode: normal / weighted / both
#   - models: RF / XGB / ET (ExtraTrees)
#   - metrics: F1 / PR_AUC / FB
#
# Input: ndjson train/test with 64-log + GC + tetra_norm (full row from ndjson).
# Labels: positives are assemblies present in Supp2 (NOT treated as certain ALT, only candidates).
# Weighted mode: assigns confidence weights ONLY to Supp2 genomes using Supp1 expected vs inferred,
# with gentle GC gating.
#
# NEW FIXES:
#   - Proper sample_weight routing into sklearn Pipeline: clf__sample_weight
#   - PU classifier marked as classifier for sklearn calibration (_estimator_type + classifier tags)
#   - Optional calibration auto-disabled for PU by default (still possible with --force_calibration_pu)
#   - Skip already-trained model variants based on existing artifacts in results_models/
#   - Crash-safe: each run saved immediately, and metrics_summary.csv updated after each run
#
# NOTE:
#   - For PU, calibration can be extremely expensive (cv * n_bags refits). Default: off for PU unless forced.

import argparse, json, os, re, time, glob
from pathlib import Path
from collections import Counter

import numpy as np
import pandas as pd

from sklearn.model_selection import StratifiedGroupKFold
from sklearn.metrics import (
    f1_score, confusion_matrix, accuracy_score, precision_score, recall_score,
    fbeta_score, roc_auc_score, average_precision_score, precision_recall_curve
)
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.impute import SimpleImputer
from sklearn.calibration import CalibratedClassifierCV
from sklearn.base import BaseEstimator, ClassifierMixin, clone

import joblib

try:
    from xgboost import XGBClassifier
    _HAS_XGB = True
except Exception:
    _HAS_XGB = False

import optuna
from optuna.pruners import MedianPruner

ANTICODONS64 = [a+b+c for a in "ACGT" for b in "ACGT" for c in "ACGT"]
TETRA_KEYS   = [a+b+c+d for a in "ACGT" for b in "ACGT" for c in "ACGT" for d in "ACGT"]

AA_SET = set(list("ACDEFGHIKLMNPQRSTVWY"))
STAR = "*"
QMARK = "?"

# =========================
# Helpers: crash-safe fit with sample_weight
# =========================
def fit_pipeline(model, X, y, sample_weight=None):
    """
    Fit helper that correctly routes sample_weight into Pipeline
    (to the 'clf' step) and also supports plain estimators.
    """
    if sample_weight is None:
        return model.fit(X, y)

    sw = np.asarray(sample_weight)

    # sklearn Pipeline cannot accept sample_weight directly
    if isinstance(model, Pipeline):
        return model.fit(X, y, clf__sample_weight=sw)

    # many estimators accept sample_weight directly
    try:
        return model.fit(X, y, sample_weight=sw)
    except TypeError:
        return model.fit(X, y)

# =========================
# PU Bagging Meta-Estimator
# =========================
class PUBaggingClassifier(BaseEstimator, ClassifierMixin):
    """
    PU-learning via bagging:
      - y==1: positives (P)  [assemblies from Supp2]
      - y==0: unlabeled (U)  [everything else]
    For each bag:
      - train on all P + sampled subset of U as pseudo-negative
    predict_proba: average over bags.

    sklearn calibration fix:
      - _estimator_type='classifier'
      - get tags / is_classifier compatibility
    """
    _estimator_type = "classifier"

    def __init__(self, base_estimator, n_bags=15, u_ratio=3.0, random_state=42):
        self.base_estimator = base_estimator
        self.n_bags = int(n_bags)
        self.u_ratio = float(u_ratio)
        self.random_state = int(random_state)
        self.models_ = None
        self.classes_ = np.array([0, 1], dtype=int)

    def _more_tags(self):
        # Helps sklearn treat this as classifier with predict_proba.
        return {"requires_y": True, "binary_only": True}

    def fit(self, X, y, sample_weight=None):
        y = np.asarray(y).astype(int)
        self.classes_ = np.array([0, 1], dtype=int)

        pos_idx = np.where(y == 1)[0]
        unl_idx = np.where(y == 0)[0]

        if pos_idx.size == 0:
            raise ValueError("PU training requires at least one positive sample (y==1).")

        rng = np.random.RandomState(self.random_state)
        self.models_ = []

        # if no unlabeled, just fit once
        if unl_idx.size == 0:
            m = clone(self.base_estimator)
            fit_pipeline(m, X, y, sample_weight)
            self.models_.append(m)
            return self

        k_u = int(min(unl_idx.size, max(1, round(self.u_ratio * pos_idx.size))))

        for _ in range(self.n_bags):
            if k_u <= unl_idx.size:
                u_b = rng.choice(unl_idx, size=k_u, replace=False)
            else:
                u_b = rng.choice(unl_idx, size=k_u, replace=True)

            idx_b = np.concatenate([pos_idx, u_b])

            X_b = X.iloc[idx_b] if hasattr(X, "iloc") else X[idx_b]
            y_b = y[idx_b]

            sw_b = None
            if sample_weight is not None:
                sw_b = np.asarray(sample_weight)[idx_b]

            m = clone(self.base_estimator)
            fit_pipeline(m, X_b, y_b, sw_b)
            self.models_.append(m)

        return self

    def predict_proba(self, X):
        if not self.models_:
            raise RuntimeError("PUBaggingClassifier not fitted")
        probs = [m.predict_proba(X) for m in self.models_]
        return np.mean(np.stack(probs, axis=0), axis=0)

    def predict(self, X):
        return (self.predict_proba(X)[:, 1] >= 0.5).astype(int)

# =========================
# Helpers: IDs, NDJSON features
# =========================
def extract_acc_base(acc: str) -> str:
    m = re.match(r'^(G[CF]A_\d+)', str(acc))
    return m.group(1) if m else str(acc).split('.')[0]

def load_alt_list_from_supp2(supp2_xlsx: str) -> set:
    df = pd.read_excel(supp2_xlsx, header=None, usecols=[3])
    alt = df.iloc[:, 0].dropna().astype(str).unique().tolist()
    return set(extract_acc_base(x) for x in alt)

def label_from_supp2(meta: pd.DataFrame, supp2_xlsx: str) -> pd.Series:
    alt = load_alt_list_from_supp2(supp2_xlsx)
    return meta["acc_base"].map(lambda a: 1 if a in alt else 0).astype(int)

def parse_anticodon_from_label(label_tail: str) -> str:
    if "_" in label_tail:
        return label_tail.split("_", 1)[1].upper().replace("U","T")
    return label_tail.upper().replace("U","T")

def build_vec64_from_record(rec: dict) -> np.ndarray:
    counter = Counter()
    for t in rec.get("trna_type_per_acc", []):
        c = int(t.get("count", 0) or 0)
        tail = str(t.get("label", "")).split("_genome_")[-1]
        ac = parse_anticodon_from_label(tail)
        if len(ac) == 3 and set(ac) <= {"A","C","G","T"}:
            counter[ac] += c
    return np.array([counter.get(k, 0) for k in ANTICODONS64], dtype=float)

def build_feature_matrices(ndjson_path: str, include_gc_len_tetra: bool = True):
    rows = []
    with open(ndjson_path, "r") as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            try:
                rows.append(json.loads(line))
            except Exception:
                continue

    feat_rows, meta_rows = [], []
    for rec in rows:
        acc = rec.get("acc")
        if not acc:
            continue
        acc_base = extract_acc_base(acc)
        gc = rec.get("gc", {})
        tetra = rec.get("tetra_norm", {})

        v64 = build_vec64_from_record(rec)
        vals = np.log1p(v64)
        cols = [f"ac_{k}" for k in ANTICODONS64]
        trna_dict = {c: float(v) for c, v in zip(cols, vals)}

        extra = {}
        if include_gc_len_tetra:
            extra["gc_percent"] = float(gc.get("percent", np.nan))
            extra["genome_length"] = int(gc.get("length", 0) or 0)
            for k in TETRA_KEYS:
                extra[f"tetra_{k}"] = float(tetra.get(k, np.nan))

        feat_rows.append({**trna_dict, **extra})
        meta_rows.append({"acc": acc, "acc_base": acc_base})

    X = pd.DataFrame(feat_rows)
    meta = pd.DataFrame(meta_rows)
    return X, meta

def _count_lines(path: Path) -> int:
    try:
        return sum(1 for _ in open(path, 'r'))
    except Exception:
        return -1

def _load_train_test(path_str: str, supp2_path: str):
    p = Path(path_str)
    if not p.is_dir():
        raise FileNotFoundError(f"--ndjson must be a directory containing train.jsonl and test.jsonl: {p}")
    tr = p / "train.jsonl"
    te = p / "test.jsonl"
    if not tr.exists() or not te.exists():
        raise FileNotFoundError(f"{p} must contain train.jsonl and test.jsonl")

    print(f"[LOAD] train: {tr} (lines≈{_count_lines(tr)})")
    Xtr, mtr = build_feature_matrices(str(tr), True)
    print(f"[LOAD]  test: {te} (lines≈{_count_lines(te)})")
    Xte, mte = build_feature_matrices(str(te), True)

    ytr = label_from_supp2(mtr, supp2_path)  # P=1 (Supp2), U=0 otherwise
    yte = label_from_supp2(mte, supp2_path)

    gtr = mtr["acc_base"].tolist()
    gte = mte["acc_base"].tolist()
    return Xtr, ytr, gtr, mtr, Xte, yte, gte, mte

def make_preprocess_pipeline(X: pd.DataFrame) -> ColumnTransformer:
    num_cols = list(X.columns)
    pre_num = Pipeline([
        ("imputer", SimpleImputer(strategy="median")),
        ("scaler", StandardScaler(with_mean=True, with_std=True))
    ])
    return ColumnTransformer(
        [("num", pre_num, num_cols)],
        remainder="drop",
        verbose_feature_names_out=False
    )

# =========================
# Supp1 parsing -> weights for Supp2 only
# =========================
def _norm_code_str(x) -> str:
    if pd.isna(x):
        return ""
    return str(x).replace(",", "").replace(" ", "").strip().upper()

def _analyze_expected_inferred(expected: str, inferred: str):
    """
    Return counts:
      aa_aa: AA<->AA different
      aa_q : AA<->?
      stop_aa: *<->AA
      stop_q : *<->?
      total_q: positions with '?' in either string
      valid: both length 64
    """
    e = _norm_code_str(expected)
    i = _norm_code_str(inferred)
    if len(e) != 64 or len(i) != 64:
        return dict(valid=False, aa_aa=0, aa_q=0, stop_aa=0, stop_q=0, total_q=0)

    aa_aa = aa_q = stop_aa = stop_q = total_q = 0

    for a, b in zip(e, i):
        if a == QMARK or b == QMARK:
            total_q += 1

        if a == b:
            continue

        a_is_aa = a in AA_SET
        b_is_aa = b in AA_SET
        a_is_q  = a == QMARK
        b_is_q  = b == QMARK
        a_is_s  = a == STAR
        b_is_s  = b == STAR

        if a_is_aa and b_is_aa:
            aa_aa += 1
        elif (a_is_aa and b_is_q) or (a_is_q and b_is_aa):
            aa_q += 1
        elif (a_is_s and b_is_aa) or (a_is_aa and b_is_s):
            stop_aa += 1
        elif (a_is_s and b_is_q) or (a_is_q and b_is_s):
            stop_q += 1
        else:
            pass

    return dict(valid=True, aa_aa=aa_aa, aa_q=aa_q, stop_aa=stop_aa, stop_q=stop_q, total_q=total_q)

def load_supp1_code_map(supp1_csv: str):
    """
    Returns dict base_assembly -> (expected_str, inferred_str)
    Uses columns:
      - assembly
      - expected genetic code
      - Codetta inferred genetic code
    """
    df = pd.read_csv(supp1_csv)
    cols = {c.lower(): c for c in df.columns}

    def pick(key_sub):
        for k in cols:
            if k == key_sub:
                return cols[k]
        for k in cols:
            if key_sub in k:
                return cols[k]
        return None

    asm_col = pick("assembly")
    exp_col = pick("expected genetic code")
    inf_col = pick("codetta inferred genetic code")

    if not (asm_col and exp_col and inf_col):
        raise ValueError(f"[ERROR] Supp1.csv missing required columns. Found: {list(df.columns)}")

    out = {}
    for _, row in df.iterrows():
        asm = str(row[asm_col])
        base = extract_acc_base(asm)
        out[base] = (row[exp_col], row[inf_col])
    return out

def gentle_gc_penalty(gc_val, gc_median, gc_iqr):
    """
    Very gentle penalty: near 1.0 for most of the range.
    Uses robust z = |gc - median| / IQR.
    Returns in [0.90, 1.00] (delicate gating).
    """
    if not np.isfinite(gc_val) or gc_iqr <= 1e-9 or not np.isfinite(gc_median):
        return 1.0
    z = abs(float(gc_val) - float(gc_median)) / float(gc_iqr)
    pen = float(np.exp(-0.08 * z))
    return float(min(1.0, max(0.90, pen)))

def weight_for_supp2_genome(base, gc_percent, supp1_map, gc_median, gc_iqr):
    """
    Weight only for genomes in Supp2:
      - STOP<->AA => very confident ALT signal (1.0)
      - AA<->AA => confident, but apply gentle GC penalty (close to 1.0)
      - STOP<->? treated like AA<->AA (your requirement)
      - AA<->? => less confident (downweights with total_q)
    If Supp1 missing or invalid: return 0.85 (still candidate but less trusted)
    """
    if base not in supp1_map:
        return 0.85

    exp, inf = supp1_map[base]
    a = _analyze_expected_inferred(exp, inf)
    if not a["valid"]:
        return 0.85

    aa_aa = a["aa_aa"]
    aa_q = a["aa_q"]
    stop_aa = a["stop_aa"]
    stop_q = a["stop_q"]
    total_q = a["total_q"]

    gc_pen = gentle_gc_penalty(gc_percent, gc_median, gc_iqr)

    if stop_aa > 0:
        w = 1.00 * gc_pen
        return float(max(0.90, min(1.00, w)))

    # treat STOP<->? like AA<->AA
    aa_like = aa_aa + stop_q

    if aa_like > 0 and aa_q == 0:
        w = 0.98 * gc_pen
        return float(max(0.90, min(1.00, w)))

    if aa_like > 0 and aa_q > 0:
        w = 0.95 * (0.97 ** max(total_q, 0)) * gc_pen
        return float(max(0.75, min(0.98, w)))

    if aa_like == 0 and aa_q > 0:
        w = 0.70 * (0.95 ** max(total_q, 0)) * gc_pen
        return float(max(0.35, min(0.75, w)))

    w = 0.80 * gc_pen
    return float(max(0.50, min(0.90, w)))

def build_sample_weights_for_dataset(meta_df, X_df, y_series, supp2_set, supp1_map):
    """
    Returns np.array weights (len == n_samples).
    Only genomes in Supp2 get graded weights; others -> 1.0.
    """
    gc_vals = X_df["gc_percent"].astype(float).values if "gc_percent" in X_df.columns else np.full(len(X_df), np.nan)

    gc_clean = gc_vals[np.isfinite(gc_vals)]
    if gc_clean.size >= 10:
        gc_median = float(np.median(gc_clean))
        q1 = float(np.quantile(gc_clean, 0.25))
        q3 = float(np.quantile(gc_clean, 0.75))
        gc_iqr = float(max(1e-6, q3 - q1))
    else:
        gc_median, gc_iqr = float("nan"), 1.0

    weights = np.ones(len(X_df), dtype=float)
    bases = meta_df["acc_base"].astype(str).tolist()

    for i, base in enumerate(bases):
        if base in supp2_set:
            gc = gc_vals[i]
            weights[i] = weight_for_supp2_genome(base, gc, supp1_map, gc_median, gc_iqr)
        else:
            weights[i] = 1.0
    return weights

# =========================
# Metrics utilities
# =========================
def metrics_from_pred(y_true, y_pred, y_proba=None):
    y_true = np.asarray(y_true); y_pred = np.asarray(y_pred)
    cm = confusion_matrix(y_true, y_pred, labels=[0,1])
    tn, fp, fn, tp = int(cm[0,0]), int(cm[0,1]), int(cm[1,0]), int(cm[1,1])
    row = dict(tn=tn, fp=fp, fn=fn, tp=tp)
    row["n"] = int(len(y_true)); row["positives"] = int(y_true.sum())
    row["accuracy"] = float(accuracy_score(y_true, y_pred))
    row["precision"] = float(precision_score(y_true, y_pred, pos_label=1, zero_division=0))
    row["recall"] = float(recall_score(y_true, y_pred, pos_label=1, zero_division=0))
    row["specificity"] = float(tn / (tn + fp)) if (tn + fp) > 0 else 0.0
    row["f1"] = float(f1_score(y_true, y_pred, pos_label=1, zero_division=0))
    if y_proba is not None and not np.isnan(y_proba).all():
        try: row["roc_auc"] = float(roc_auc_score(y_true, y_proba))
        except Exception: row["roc_auc"] = float("nan")
        try: row["pr_auc"] = float(average_precision_score(y_true, y_proba))
        except Exception: row["pr_auc"] = float("nan")
    else:
        row["roc_auc"] = float("nan"); row["pr_auc"] = float("nan")
    return row

def best_threshold_f1(y_true, y_score):
    p, r, t = precision_recall_curve(y_true, y_score)
    f1 = (2*p*r) / np.maximum(p+r, 1e-12)
    idx = int(np.nanargmax(f1))
    return float(t[max(0, idx-1)]) if idx == len(t) else float(t[idx])

def best_threshold_fbeta(y_true, y_score, beta=2.0):
    p, r, t = precision_recall_curve(y_true, y_score)
    if t.size == 0:
        return float(np.median(y_score))
    p = p[1:].astype(float)
    r = r[1:].astype(float)
    t = t.astype(float)
    valid = np.isfinite(p) & np.isfinite(r) & np.isfinite(t)
    p, r, t = p[valid], r[valid], t[valid]
    if t.size == 0:
        return float(np.median(y_score))
    fbeta_vals = (1.0 + beta**2) * p * r / np.maximum(beta**2 * p + r, 1e-12)
    j = int(np.nanargmax(fbeta_vals))
    return float(t[j])

# =========================
# Optuna objective
# =========================
def make_objective(model_type: str,
                   train_mode: str,
                   X: pd.DataFrame, y: pd.Series, groups,
                   metric_obj: str,
                   n_splits: int, seed: int, threads: int,
                   pu_bags: int, pu_u_ratio: float,
                   fb_beta: float,
                   sample_weight: np.ndarray | None):
    sgkf = StratifiedGroupKFold(n_splits=n_splits, shuffle=True, random_state=seed)
    pre = make_preprocess_pipeline(X)

    def build_base_estimator(trial):
        if model_type == "RF":
            params = dict(
                n_estimators = trial.suggest_int("n_estimators", 400, 1400),
                max_depth    = trial.suggest_int("max_depth", 6, 16),
                min_samples_split = trial.suggest_int("min_samples_split", 2, 20),
                min_samples_leaf  = trial.suggest_int("min_samples_leaf", 2, 12),
                max_features = trial.suggest_categorical("max_features", ["sqrt"]),
                class_weight = trial.suggest_categorical("class_weight", [None, "balanced", "balanced_subsample"]),
                n_jobs = threads,
                random_state = seed,
            )
            return RandomForestClassifier(**params)

        if model_type == "ET":
            params = dict(
                n_estimators = trial.suggest_int("n_estimators", 600, 2000),
                max_depth    = trial.suggest_int("max_depth", 6, 18),
                min_samples_split = trial.suggest_int("min_samples_split", 2, 20),
                min_samples_leaf  = trial.suggest_int("min_samples_leaf", 2, 12),
                max_features = trial.suggest_categorical("max_features", ["sqrt"]),
                class_weight = trial.suggest_categorical("class_weight", [None, "balanced"]),
                n_jobs = threads,
                random_state = seed,
            )
            return ExtraTreesClassifier(**params)

        if not _HAS_XGB:
            raise RuntimeError("xgboost not installed")
        params = dict(
            n_estimators = trial.suggest_int("n_estimators", 400, 2000),
            max_depth    = trial.suggest_int("max_depth", 3, 9),
            learning_rate= trial.suggest_float("learning_rate", 1e-3, 0.15, log=True),
            subsample    = trial.suggest_float("subsample", 0.6, 1.0),
            colsample_bytree = trial.suggest_float("colsample_bytree", 0.5, 1.0),
            reg_alpha    = trial.suggest_float("reg_alpha", 1e-4, 10.0, log=True),
            reg_lambda   = trial.suggest_float("reg_lambda", 1e-3, 10.0, log=True),
            gamma        = trial.suggest_float("gamma", 0.0, 5.0),
            min_child_weight = trial.suggest_float("min_child_weight", 1e-3, 10.0, log=True),
            n_jobs = threads,
            random_state = seed,
            tree_method = trial.suggest_categorical("tree_method", ["hist", "approx"]),
            objective = "binary:logistic",
            eval_metric = "logloss",
        )
        return XGBClassifier(**params)

    def objective(trial):
        clf = build_base_estimator(trial)
        base_pipe = Pipeline([("pre", pre), ("clf", clf)])

        if train_mode == "pu":
            model = PUBaggingClassifier(
                base_estimator=base_pipe,
                n_bags=pu_bags,
                u_ratio=pu_u_ratio,
                random_state=seed
            )
        else:
            model = base_pipe

        y_true_all = []
        proba_all = []
        f_scores = []

        for tr_idx, va_idx in sgkf.split(X, y, groups):
            Xtr, Xva = X.iloc[tr_idx], X.iloc[va_idx]
            ytr, yva = y.iloc[tr_idx], y.iloc[va_idx]

            sw_tr = None
            if sample_weight is not None:
                sw_tr = np.asarray(sample_weight)[tr_idx]

            model_fold = clone(model)
            fit_pipeline(model_fold, Xtr, ytr, sw_tr)

            proba = model_fold.predict_proba(Xva)[:, 1]
            y_true_all.append(yva.values)
            proba_all.append(proba)

            if metric_obj == "F1":
                thr = best_threshold_f1(yva.values, proba)
                yhat = (proba >= thr).astype(int)
                f_scores.append(f1_score(yva.values, yhat, zero_division=0))

        y_true_all = np.concatenate(y_true_all)
        proba_all = np.concatenate(proba_all)

        if metric_obj == "F1":
            return float(np.mean(f_scores))
        if metric_obj == "PR_AUC":
            return float(average_precision_score(y_true_all, proba_all))
        if metric_obj == "FB":
            thr = best_threshold_fbeta(y_true_all, proba_all, beta=fb_beta)
            yhat = (proba_all >= thr).astype(int)
            return float(fbeta_score(y_true_all, yhat, beta=fb_beta, zero_division=0))

        raise ValueError("metric_obj must be one of: F1, PR_AUC, FB")

    return objective, pre

# =========================
# Fit best model + calibration + threshold + test metrics
# =========================
def fit_best_model(model_type: str,
                   train_mode: str,
                   weight_mode: str,
                   metric_obj: str,
                   X: pd.DataFrame, y: pd.Series, groups,
                   seed: int, timeout: int, n_trials: int, outdir: Path, tag: str,
                   X_test: pd.DataFrame = None, y_test: pd.Series = None,
                   threads: int = 1,
                   pu_bags: int = 15, pu_u_ratio: float = 3.0,
                   fb_beta: float = 2.0,
                   calibrate: bool = True,
                   sample_weight: np.ndarray | None = None,
                   cv_folds: int = 5):

    t0 = time.time()

    def _make_eta_cb(t0, timeout, n_trials):
        def _cb(study, trial):
            try:
                elapsed = time.time() - t0
                done = trial.number + 1
                avg = elapsed / max(1, done)
                rem_trials = max(0, (n_trials or 0) - done)
                eta_trials = rem_trials * avg if n_trials else float('inf')
                eta_timeout = max(0.0, (timeout or 0) - elapsed) if timeout else float('inf')
                eta = min(eta_trials, eta_timeout)
                print(f"[TRIAL] #{trial.number:03d} value={trial.value:.5f} | best={study.best_value:.5f} | elapsed={elapsed/60:.1f}m | ETA~{eta/60:.1f}m")
            except Exception:
                print(f"[TRIAL] #{trial.number:03d} done")
        return _cb

    study = optuna.create_study(
        direction="maximize",
        pruner=MedianPruner(n_startup_trials=8, n_warmup_steps=2),
        study_name=f"{model_type}_{train_mode}_{weight_mode}_{metric_obj}_{tag}"
    )

    objective, pre = make_objective(
        model_type=model_type,
        train_mode=train_mode,
        X=X, y=y, groups=groups,
        metric_obj=metric_obj,
        n_splits=cv_folds,
        seed=seed, threads=threads,
        pu_bags=pu_bags, pu_u_ratio=pu_u_ratio,
        fb_beta=fb_beta,
        sample_weight=sample_weight
    )

    study.optimize(
        objective,
        timeout=timeout,
        n_trials=n_trials,
        gc_after_trial=True,
        callbacks=[_make_eta_cb(t0, timeout, n_trials)]
    )

    best_params = dict(study.best_params)

    # rebuild best estimator
    if model_type == "RF":
        clf = RandomForestClassifier(**{**best_params, "n_jobs": threads, "random_state": seed})
    elif model_type == "ET":
        clf = ExtraTreesClassifier(**{**best_params, "n_jobs": threads, "random_state": seed})
    else:
        if not _HAS_XGB:
            raise RuntimeError("xgboost not installed")
        clf = XGBClassifier(**{
            **best_params,
            "n_jobs": threads,
            "random_state": seed,
            "objective": "binary:logistic",
            "eval_metric": "logloss",
        })

    base_pipe = Pipeline([("pre", pre), ("clf", clf)])

    if train_mode == "pu":
        model = PUBaggingClassifier(
            base_estimator=base_pipe,
            n_bags=pu_bags,
            u_ratio=pu_u_ratio,
            random_state=seed
        )
    else:
        model = base_pipe

    # fit final model (weighted or not)
    fit_pipeline(model, X, y, sample_weight)

    # optional calibration
    final_model = model
    if calibrate:
        # CalibratedClassifierCV will refit the estimator cv times; for PU this is heavy.
        try:
            calib = CalibratedClassifierCV(estimator=model, method="isotonic", cv=cv_folds)
        except TypeError:
            calib = CalibratedClassifierCV(base_estimator=model, method="isotonic", cv=cv_folds)

        # We avoid passing weights here for robustness across sklearn versions.
        calib.fit(X, y)
        final_model = calib

    # threshold selection on train
    proba_tr = final_model.predict_proba(X)[:, 1]
    if metric_obj == "F1":
        tau = best_threshold_f1(y.values, proba_tr)
    elif metric_obj == "FB":
        tau = best_threshold_fbeta(y.values, proba_tr, beta=fb_beta)
    else:
        tau = best_threshold_f1(y.values, proba_tr)

    yhat_tr = (proba_tr >= tau).astype(int)
    train_row = metrics_from_pred(y.values, yhat_tr, proba_tr)
    train_row = {f"train_{k}": v for k, v in train_row.items()}

    metrics = dict(
        threshold_used=float(tau),
        study_best=float(study.best_value),
        model_type=model_type,
        train_mode=train_mode,
        weight_mode=weight_mode,
        metric_obj=metric_obj,
        fb_beta=float(fb_beta),
        pu_bags=int(pu_bags),
        pu_u_ratio=float(pu_u_ratio),
        calibrated=bool(calibrate),
        **train_row
    )

    # test metrics (always)
    if X_test is not None and y_test is not None:
        X_te = X_test.reindex(columns=list(X.columns))
        proba_te = final_model.predict_proba(X_te)[:, 1]
        yhat_te = (proba_te >= tau).astype(int)
        test_row = metrics_from_pred(y_test.values, yhat_te, proba_te)
        metrics.update({f"test_{k}": v for k, v in test_row.items()})

    return final_model, best_params, metrics, study

# =========================
# Results folder detection / skipping already trained variants
# =========================
def model_run_id(model_type, train_mode, weight_mode, metric_obj, tag):
    return f"{model_type}_{train_mode}_{weight_mode}_{metric_obj}_{tag}"

def artifact_paths(results_dir: Path, run_id: str):
    return {
        "model":   results_dir / f"model_{run_id}.joblib",
        "params":  results_dir / f"best_params_{run_id}.json",
        "metrics": results_dir / f"metrics_{run_id}.json",
    }

def is_run_complete(results_dir: Path, run_id: str) -> bool:
    p = artifact_paths(results_dir, run_id)
    return p["model"].exists() and p["metrics"].exists() and p["params"].exists()

def load_existing_metrics(results_dir: Path) -> list:
    rows = []
    for mf in sorted(results_dir.glob("metrics_*.json")):
        try:
            d = json.loads(mf.read_text())
            rows.append(d)
        except Exception:
            continue
    return rows

def append_metrics_summary(results_dir: Path, rows: list):
    if not rows:
        return
    df = pd.DataFrame(rows)
    df.to_csv(results_dir / "metrics_summary.csv", index=False)

# =========================
# Main
# =========================
def main():
    ap = argparse.ArgumentParser(description="Train RF/XGB/ET with grouped CV. supervised + PU. normal + weighted.")
    ap.add_argument("--ndjson", required=True, help="Folder with train.jsonl and test.jsonl")
    ap.add_argument("--supp2", required=True, help="Supp2.xlsx (positives list for PU; label=1)")
    ap.add_argument("--supp1", required=False, default=None, help="Supp1.csv (for weighted grading of Supp2 genomes)")
    ap.add_argument("--outdir", required=True, help="Output directory root (will create results_models/)")

    ap.add_argument("--train_mode", choices=["supervised","pu","both"], default="both",
                    help="Training mode: classic supervised vs PU-bagging vs both")

    ap.add_argument("--weight_mode", choices=["normal","weighted","both"], default="both",
                    help="normal: all weights=1; weighted: grade only Supp2 genomes via Supp1 expected/inferred; both: run both")

    ap.add_argument("--model", choices=["RF","XGB","ET","all"], default="all",
                    help="Model(s): RF, XGB, ET (ExtraTrees baseline), or all")

    ap.add_argument("--metric", choices=["F1","PR_AUC","FB","all"], default="all",
                    help="Optuna objective metric")

    ap.add_argument("--fb_beta", type=float, default=2.0, help="Beta for F-beta metric (FB objective)")

    ap.add_argument("--timeout", type=int, default=3600, help="Optuna time budget per run (seconds)")
    ap.add_argument("--n_trials", type=int, default=60, help="Upper limit of trials if timeout not reached")
    ap.add_argument("--threads", type=int, default=0, help="Threads (0=auto cpu_count()-4)")
    ap.add_argument("--seed", type=int, default=42, help="Random seed")

    ap.add_argument("--pu_bags", type=int, default=15, help="PU bagging: number of bags")
    ap.add_argument("--pu_u_ratio", type=float, default=3.0, help="PU bagging: U sampled per bag = ratio * |P|")

    ap.add_argument("--no_calibration", action="store_true",
                    help="Disable isotonic calibration (use raw predict_proba from base model / PU ensemble).")

    ap.add_argument("--force_calibration_pu", action="store_true",
                    help="Force calibration even for PU (can be extremely slow: cv_folds * pu_bags fits).")

    ap.add_argument("--cv", type=int, default=5, help="Grouped CV folds for objective & calibration")
    ap.add_argument("--overwrite", action="store_true",
                    help="Re-train even if artifacts already exist for a run_id (otherwise skipped).")

    args = ap.parse_args()

    cpu_total = os.cpu_count() or 8
    eff_threads = max(1, cpu_total - 4) if args.threads in (None, 0, -1) else max(1, args.threads)
    print(f"[CPU ] total={cpu_total} using={eff_threads} (flag={args.threads})")

    os.environ['OMP_NUM_THREADS'] = str(eff_threads)
    os.environ['OPENBLAS_NUM_THREADS'] = str(eff_threads)
    os.environ['MKL_NUM_THREADS'] = str(eff_threads)
    os.environ['VECLIB_MAXIMUM_THREADS'] = str(eff_threads)
    os.environ['NUMEXPR_NUM_THREADS'] = str(eff_threads)

    out_root = Path(args.outdir)
    out_root.mkdir(parents=True, exist_ok=True)

    results_dir = out_root / "results_models"
    results_dir.mkdir(parents=True, exist_ok=True)

    # load once
    Xtr, ytr, gtr, mtr, Xte, yte, gte, mte = _load_train_test(args.ndjson, args.supp2)
    tag = "64log_gc_tetra"

    supp2_set = load_alt_list_from_supp2(args.supp2)

    # weights (only if needed)
    supp1_map = {}
    if args.supp1:
        print("[LOAD] Supp1 mapping for weights:", args.supp1)
        supp1_map = load_supp1_code_map(args.supp1)

    weights_train_weighted = None
    weights_test_weighted = None
    if args.weight_mode in ("weighted", "both"):
        if not args.supp1:
            raise ValueError("--weight_mode weighted/both requires --supp1 Supp1.csv")
        weights_train_weighted = build_sample_weights_for_dataset(mtr, Xtr, ytr, supp2_set, supp1_map)
        weights_test_weighted  = build_sample_weights_for_dataset(mte, Xte, yte, supp2_set, supp1_map)

        # snapshot for debugging
        snap_tr = pd.DataFrame({
            "acc_base": mtr["acc_base"].astype(str).values,
            "y": ytr.astype(int).values,
            "gc_percent": Xtr["gc_percent"].astype(float).values,
            "weight": weights_train_weighted
        })
        snap_te = pd.DataFrame({
            "acc_base": mte["acc_base"].astype(str).values,
            "y": yte.astype(int).values,
            "gc_percent": Xte["gc_percent"].astype(float).values,
            "weight": weights_test_weighted
        })
        snap_tr.to_csv(results_dir / "weights_snapshot_train.tsv", sep="\t", index=False)
        snap_te.to_csv(results_dir / "weights_snapshot_test.tsv", sep="\t", index=False)
        print("[WRITE] weights_snapshot_train.tsv / weights_snapshot_test.tsv")

        wP = weights_train_weighted[ytr.values == 1]
        if wP.size:
            print(f"[WEIGHTS] Supp2(P) weights: n={wP.size} mean={wP.mean():.3f} sd={wP.std():.3f} min={wP.min():.3f} max={wP.max():.3f}")

    print("\n" + "="*72)
    print(f"[DATA] train={Xtr.shape} P(from Supp2)={int(ytr.sum())} ({100.0*float(ytr.mean()):.3f}%)")
    print(f"[DATA]  test={Xte.shape} P(from Supp2)={int(yte.sum())} ({100.0*float(yte.mean()):.3f}%)")
    print("="*72)

    train_modes = ["supervised","pu"] if args.train_mode == "both" else [args.train_mode]
    weight_modes = ["normal","weighted"] if args.weight_mode == "both" else [args.weight_mode]
    models = ["RF","XGB","ET"] if args.model == "all" else [args.model]
    metrics = ["F1","PR_AUC","FB"] if args.metric == "all" else [args.metric]

    # Load any already-existing metrics into summary rows
    global_rows = load_existing_metrics(results_dir)
    if global_rows:
        append_metrics_summary(results_dir, global_rows)
        print(f"[INFO] Found existing metrics: {len(global_rows)} runs. metrics_summary.csv refreshed.")

    for tm in train_modes:
        for wm in weight_modes:
            for met in metrics:
                for mdl in models:
                    run_id = model_run_id(mdl, tm, wm, met, tag)

                    # Decide calibration: PU default off unless forced
                    calibrate = (not args.no_calibration)
                    if tm == "pu" and calibrate and not args.force_calibration_pu:
                        print(f"[INFO] Auto-disabling calibration for PU run {run_id} (use --force_calibration_pu to override).")
                        calibrate = False

                    # Skip if complete and not overwrite
                    if (not args.overwrite) and is_run_complete(results_dir, run_id):
                        print(f"[SKIP] already exists: {run_id}")
                        continue

                    print("\n" + "-"*72)
                    print(f"[RUN ] mode={tm} | weights={wm} | metric={met} | model={mdl} | timeout={args.timeout}s | trials={args.n_trials}")
                    print(f"[RUN ] run_id={run_id} | calibrate={calibrate}")
                    print("-"*72)

                    # pick weights
                    if wm == "weighted":
                        sw_tr = weights_train_weighted
                        sw_te = weights_test_weighted
                    else:
                        sw_tr = None
                        sw_te = None

                    t0 = time.time()
                    final_model, best_params, met_dict, study = fit_best_model(
                        model_type=mdl,
                        train_mode=tm,
                        weight_mode=wm,
                        metric_obj=met,
                        X=Xtr, y=ytr, groups=gtr,
                        seed=args.seed,
                        timeout=args.timeout,
                        n_trials=args.n_trials,
                        outdir=results_dir,
                        tag=tag,
                        X_test=Xte,
                        y_test=yte,
                        threads=eff_threads,
                        pu_bags=args.pu_bags,
                        pu_u_ratio=args.pu_u_ratio,
                        fb_beta=args.fb_beta,
                        calibrate=calibrate,
                        sample_weight=sw_tr,
                        cv_folds=args.cv
                    )

                    dt = time.time() - t0
                    print(f"[DONE] {mdl} | {tm} | {wm} | {met} in {dt/60:.1f} min best={study.best_value:.5f}")

                    # crash-safe save immediately
                    model_path   = results_dir / f"model_{run_id}.joblib"
                    params_path  = results_dir / f"best_params_{run_id}.json"
                    metrics_path = results_dir / f"metrics_{run_id}.json"
                    cols_path    = results_dir / f"feature_columns_{tag}.json"

                    joblib.dump(final_model, model_path)
                    params_path.write_text(json.dumps(best_params, indent=2))
                    metrics_path.write_text(json.dumps(met_dict, indent=2))
                    if not cols_path.exists():
                        cols_path.write_text(json.dumps(list(Xtr.columns), indent=2))

                    # Update in-memory summary list:
                    # remove previous row with same run_id if overwrite
                    global_rows = [r for r in global_rows if not (
                        r.get("model_type")==mdl and r.get("train_mode")==tm and r.get("weight_mode")==wm
                        and r.get("metric_obj")==met
                    )]
                    met_row = dict(met_dict)
                    met_row["elapsed_min"] = float(dt/60.0)
                    global_rows.append(met_row)

                    append_metrics_summary(results_dir, global_rows)
                    print("[WRITE] metrics_summary.csv updated")

    print("[DONE] Saved artifacts to", results_dir.resolve())

if __name__ == "__main__":
    main()