File size: 23,101 Bytes
1f3a62d
28d4175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f3a62d
 
 
 
28d4175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f3a62d
 
 
 
 
 
 
 
 
 
28d4175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f3a62d
28d4175
1f3a62d
 
 
28d4175
1f3a62d
28d4175
 
 
 
 
 
1f3a62d
28d4175
 
 
 
 
 
1f3a62d
 
28d4175
 
 
 
1f3a62d
28d4175
 
 
 
1f3a62d
 
28d4175
 
 
 
1f3a62d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d4175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f3a62d
28d4175
 
1f3a62d
 
 
28d4175
 
 
1f3a62d
 
28d4175
1f3a62d
28d4175
 
 
 
 
 
 
 
 
 
 
 
1f3a62d
28d4175
1f3a62d
28d4175
 
 
 
 
 
 
 
 
 
 
 
 
 
1f3a62d
28d4175
 
 
 
1f3a62d
28d4175
1f3a62d
28d4175
 
 
 
 
 
 
 
 
1f3a62d
 
 
 
 
 
 
 
 
 
28d4175
 
 
 
1f3a62d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28d4175
 
 
 
 
1f3a62d
28d4175
 
 
 
 
1f3a62d
 
 
 
 
 
28d4175
 
 
 
 
 
 
 
 
 
1f3a62d
 
 
 
28d4175
1f3a62d
 
 
 
 
28d4175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Train leak-free 3-class (Blazar / Pulsar / Other) and binary Fermi-LAT 4FGL-DR4 Random Forests and export to skops + ONNX."""

from __future__ import annotations

import argparse
import hashlib
import json
from datetime import datetime, timezone
from importlib import metadata
from pathlib import Path
from typing import Any

import numpy as np
import onnxruntime as ort
import pandas as pd
import skops.io as sio
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import (
    average_precision_score,
    balanced_accuracy_score,
    confusion_matrix,
    f1_score,
    precision_score,
    recall_score,
    roc_auc_score,
)
from sklearn.model_selection import StratifiedKFold, cross_val_predict

# Leak-free gamma-ray features: is_plec (PLSuperExpCutoff) is omitted because 4FGL-DR4
# assigns it almost exclusively to bright, confirmed pulsars (269/320) vs 0/2,563 unassociated.
FEATS_GAMMA_FULL = ["pl_index", "log_var", "log_eflux", "abs_b", "is_curved", "sig"]
FEATS_GAMMA_BLIND = ["pl_index", "log_var", "log_eflux", "is_curved", "sig"]
FEATS_MW_EXTRA = [
    "has_radio_95",
    "log_radio_s14",
    "log_radio_to_gamma",
    "has_radio_alpha",
    "radio_alpha_filled",
    "is_steep_radio",
    "has_wise_strip_95",
    "has_radio_wise_strip_95",
    "wise_w1_w2_filled",
    "wise_w2_w3_filled",
    "wise_strip_dist_filled",
    "has_xray_95",
    "log_xray_flux",
    "log_fx_fg",
    "xray_hr_filled",
]
FEATS_MW_FULL = FEATS_GAMMA_FULL + FEATS_MW_EXTRA
FEATS_MW_BLIND = FEATS_GAMMA_BLIND + FEATS_MW_EXTRA

CLASSES_3 = {"0": "blazar", "1": "pulsar", "2": "other"}
CLASSES_2 = {"0": "blazar", "1": "pulsar"}

MODEL_SPECS: list[tuple[str, str, list[str], str]] = [
    ("rf_3class_gamma_6feat", "3class", FEATS_GAMMA_FULL, "Leak-free 6-feature gamma-only 3-class Random Forest (Blazar/Pulsar/Other)"),
    ("rf_3class_mw_21feat", "3class", FEATS_MW_FULL, "Flagship leak-free 21-feature multi-wavelength 3-class Random Forest (Blazar/Pulsar/Other)"),
    ("rf_3class_mw_sky_blind_20feat", "3class", FEATS_MW_BLIND, "Leak-free 20-feature sky-blind multi-wavelength 3-class ablation (no abs_b)"),
    ("rf_binary_gamma_6feat", "binary", FEATS_GAMMA_FULL, "Leak-free 6-feature gamma-only binary Random Forest (Blazar/Pulsar)"),
    ("rf_binary_mw_21feat", "binary", FEATS_MW_FULL, "Leak-free 21-feature multi-wavelength binary Random Forest (Blazar/Pulsar)"),
    ("rf_binary_mw_sky_blind_20feat", "binary", FEATS_MW_BLIND, "Leak-free 20-feature sky-blind multi-wavelength binary ablation (no abs_b)"),
]


def _sha256(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def _make_rf() -> RandomForestClassifier:
    return RandomForestClassifier(
        n_estimators=300,
        max_depth=10,
        min_samples_leaf=4,
        class_weight="balanced",
        random_state=42,
        n_jobs=-1,
    )


def build_features(f4: pd.DataFrame, mw: pd.DataFrame) -> pd.DataFrame:
    """Merge 4FGL gamma-ray properties with depth-harmonized multi-wavelength features."""
    df = f4.copy()
    df["src_id"] = df["name"].astype(str).str.strip()
    df = df.merge(
        mw.drop(columns=[c for c in ["ra", "dec", "lii", "bii"] if c in mw.columns]),
        on="src_id",
        how="left",
    )

    spec = df["spectrum_type"].fillna("").astype(str).str.strip()
    df["log_var"] = np.log10(np.clip(df["variability_index"].fillna(1.0).to_numpy(dtype=float), 0.1, None))
    df["log_eflux"] = np.log10(np.clip(df["energy_flux"].to_numpy(dtype=float), 1e-16, None))
    df["abs_b"] = np.abs(df["bii"].fillna(0.0).to_numpy(dtype=float))
    df["is_curved"] = spec.isin(["LogParabola", "PLSuperExpCutoff"]).astype(float)
    df["sig"] = df["detection_significance"].fillna(0.0).to_numpy(dtype=float)

    s14 = df["best_radio_s14_mjy"].to_numpy(dtype=float)
    has_r_uni = (df["has_radio_95_unif2p5"].fillna(0).to_numpy(dtype=float) > 0.5) & np.isfinite(s14) & (s14 >= 2.5)
    df["has_radio_95"] = has_r_uni.astype(float)
    df["log_radio_s14"] = np.where(has_r_uni, np.log10(np.clip(s14, 0.1, None)), -1.0)
    df["log_radio_to_gamma"] = np.where(
        has_r_uni,
        np.log10(np.clip(s14, 0.1, None)) - (df["log_eflux"].to_numpy(dtype=float) + 12.0),
        -3.0,
    )

    ralpha = df["radio_alpha"].to_numpy(dtype=float)
    has_alpha = np.isfinite(ralpha) & has_r_uni
    df["has_radio_alpha"] = has_alpha.astype(float)
    df["radio_alpha_filled"] = np.where(has_alpha, np.clip(ralpha, -3.5, 2.5), 0.0)
    df["is_steep_radio"] = (has_alpha & (ralpha < -1.1)).astype(float)

    df["has_wise_strip_95"] = (df["has_wise_strip_95"].fillna(0).to_numpy(dtype=float) > 0.5).astype(float)
    df["has_radio_wise_strip_95"] = (df["has_radio_wise_strip_95"].fillna(0).to_numpy(dtype=float) > 0.5).astype(float)

    rw12 = df["radio_wise_w1_w2"].to_numpy(dtype=float)
    dw12 = df["direct_wise_w1_w2"].to_numpy(dtype=float)
    w12 = np.where(np.isfinite(rw12), rw12, dw12)
    rw23 = df["radio_wise_w2_w3"].to_numpy(dtype=float)
    dw23 = df["direct_wise_w2_w3"].to_numpy(dtype=float)
    w23 = np.where(np.isfinite(rw23), rw23, dw23)

    df["wise_w1_w2_filled"] = np.where(np.isfinite(w12), np.clip(w12, -1.0, 3.0), 0.0)
    df["wise_w2_w3_filled"] = np.where(np.isfinite(w23), np.clip(w23, -1.0, 6.0), 0.0)
    df["wise_strip_dist_filled"] = np.where(
        np.isfinite(df["wise_strip_dist"].to_numpy(dtype=float)),
        np.clip(df["wise_strip_dist"].to_numpy(dtype=float), 0.0, 5.0),
        5.0,
    )

    xf = df["best_xray_flux"].to_numpy(dtype=float)
    is_rxs = df["best_xray_survey"].fillna("").astype(str) == "rass2rxs"
    xf = np.where(is_rxs & np.isfinite(xf), np.clip(xf, 1e-15, 1e-10), xf)
    has_x = (df["has_xray_95"].fillna(0).to_numpy(dtype=float) > 0.5) & np.isfinite(xf) & (xf > 0.0)
    df["has_xray_95"] = has_x.astype(float)
    df["log_xray_flux"] = np.where(has_x, np.log10(np.clip(xf, 1e-16, 1e-9)), -15.5)
    df["log_fx_fg"] = np.where(
        has_x,
        np.clip(np.log10(np.clip(xf, 1e-16, 1e-9)) - df["log_eflux"].to_numpy(dtype=float), -4.5, 2.5),
        -4.5,
    )
    xhr = df["best_xray_hr"].to_numpy(dtype=float)
    df["xray_hr_filled"] = np.where(has_x & np.isfinite(xhr), np.clip(xhr, -1.0, 1.0), 0.0)
    return df


def _export_and_verify(
    name: str,
    clf: RandomForestClassifier,
    X_ref: np.ndarray,
    n_classes: int,
    models_dir: Path,
) -> tuple[Path, Path, dict[str, float]]:
    skops_path = models_dir / f"{name}.skops"
    sio.dump(clf, skops_path)

    onnx_path = models_dir / f"{name}.onnx"
    onnx_model = convert_sklearn(
        clf,
        initial_types=[("float_input", FloatTensorType([None, X_ref.shape[1]]))],
        options={id(clf): {"zipmap": False}},
    )
    onnx_path.write_bytes(onnx_model.SerializeToString())

    untrusted = sio.get_untrusted_types(file=skops_path)
    clf_skops = sio.load(skops_path, trusted=untrusted)
    probs_ref = clf.predict_proba(X_ref)
    probs_skops = clf_skops.predict_proba(X_ref)
    skops_max_diff = float(np.max(np.abs(probs_ref - probs_skops)))
    if skops_max_diff >= 1e-12:
        raise RuntimeError(f"{name}: skops round-trip diff {skops_max_diff} >= 1e-12")

    X32 = X_ref.astype(np.float32)
    probs_ref32 = clf.predict_proba(X32)
    sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
    input_name = sess.get_inputs()[0].name
    _, probs_onnx = sess.run(None, {input_name: X32})
    if probs_onnx.shape != (len(X32), n_classes):
        raise RuntimeError(f"{name}: ONNX output shape {probs_onnx.shape} != {(len(X32), n_classes)}")
    onnx_max_diff = float(np.max(np.abs(probs_ref32 - probs_onnx)))
    if onnx_max_diff >= 1e-5:
        raise RuntimeError(f"{name}: ONNX round-trip diff {onnx_max_diff} >= 1e-5")

    return skops_path, onnx_path, {
        "skops_max_abs_diff": skops_max_diff,
        "onnx_float32_max_abs_diff": onnx_max_diff,
    }


def _eval_3class(
    name: str,
    description: str,
    feats: list[str],
    train_df: pd.DataFrame,
    y_train: np.ndarray,
    unid_df: pd.DataFrame,
    models_dir: Path,
) -> tuple[dict[str, Any], np.ndarray]:
    X = train_df[feats].to_numpy(dtype=float)
    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
    oof = cross_val_predict(_make_rf(), X, y_train, cv=skf, method="predict_proba")

    macro_roc = float(roc_auc_score(y_train, oof, multi_class="ovr", average="macro"))
    per_class_roc = {
        cname: float(roc_auc_score((y_train == int(cid)).astype(int), oof[:, int(cid)]))
        for cid, cname in CLASSES_3.items()
    }
    per_class_pr = {
        cname: float(average_precision_score((y_train == int(cid)).astype(int), oof[:, int(cid)]))
        for cid, cname in CLASSES_3.items()
    }
    pred_argmax = oof.argmax(axis=1)
    bal_acc = float(balanced_accuracy_score(y_train, pred_argmax))
    cm = confusion_matrix(y_train, pred_argmax).tolist()

    thresh_metrics: dict[str, Any] = {}
    for th in (0.50, 0.60, 0.70):
        key = f"threshold_{th:.2f}".replace(".", "p")
        per_c = {}
        for cid, cname in CLASSES_3.items():
            c = int(cid)
            sel = oof[:, c] >= th
            tp = int(((y_train == c) & sel).sum())
            n_pred = int(sel.sum())
            n_true = int((y_train == c).sum())
            per_c[cname] = {
                "precision": float(tp / n_pred) if n_pred else 0.0,
                "recall": float(tp / n_true) if n_true else 0.0,
                "n_predicted": n_pred,
                "n_true_positives": tp,
            }
        thresh_metrics[key] = per_c

    clf = _make_rf().fit(X, y_train)
    skops_path, onnx_path, parity = _export_and_verify(name, clf, X, 3, models_dir)

    p_unid = clf.predict_proba(unid_df[feats].to_numpy(dtype=float))
    unid_counts = {}
    for th in (0.50, 0.60, 0.70):
        key = f"at_{th:.2f}".replace(".", "p")
        unid_counts[key] = {
            "blazar": int((p_unid[:, 0] >= th).sum()),
            "pulsar": int((p_unid[:, 1] >= th).sum()),
            "other": int((p_unid[:, 2] >= th).sum()),
            "ambiguous": int((p_unid.max(axis=1) < th).sum()),
        }

    print(
        f"[{name}] MacroROC={macro_roc:.4f} (Blz={per_class_roc['blazar']:.4f}, "
        f"Psr={per_class_roc['pulsar']:.4f}, Oth={per_class_roc['other']:.4f}) | "
        f"PR=({per_class_pr['blazar']:.4f}/{per_class_pr['pulsar']:.4f}/{per_class_pr['other']:.4f}) | "
        f"Unassoc>=0.60: {unid_counts['at_0p60']['blazar']}/{unid_counts['at_0p60']['pulsar']}/{unid_counts['at_0p60']['other']} | "
        f"skops={parity['skops_max_abs_diff']:.2e} onnx={parity['onnx_float32_max_abs_diff']:.2e}"
    )

    meta = {
        "task": "3class",
        "classes": CLASSES_3,
        "description": description,
        "skops_path": f"models/{skops_path.name}",
        "onnx_path": f"models/{onnx_path.name}",
        "sha256": {"skops": _sha256(skops_path), "onnx": _sha256(onnx_path)},
        "size_bytes": {"skops": skops_path.stat().st_size, "onnx": onnx_path.stat().st_size},
        "features": feats,
        "n_train": int(len(y_train)),
        "cv_metrics": {
            "macro_ovr_roc_auc": macro_roc,
            "per_class_ovr_roc_auc": per_class_roc,
            "per_class_pr_auc": per_class_pr,
            "balanced_accuracy_argmax": bal_acc,
            "confusion_matrix_argmax_blazar_pulsar_other": cm,
            **thresh_metrics,
        },
        "unassociated_counts": unid_counts,
        "parity_check": parity,
    }
    return meta, p_unid


def _eval_binary(
    name: str,
    description: str,
    feats: list[str],
    train_df: pd.DataFrame,
    y_train: np.ndarray,
    unid_df: pd.DataFrame,
    models_dir: Path,
) -> tuple[dict[str, Any], np.ndarray]:
    X = train_df[feats].to_numpy(dtype=float)
    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
    oof = cross_val_predict(_make_rf(), X, y_train, cv=skf, method="predict_proba")[:, 1]

    def _m(t: float) -> dict[str, Any]:
        yp = (oof >= t).astype(int)
        return {
            "threshold": t,
            "balanced_accuracy": float(balanced_accuracy_score(y_train, yp)),
            "pulsar_precision": float(precision_score(y_train, yp, zero_division=0)),
            "pulsar_recall": float(recall_score(y_train, yp, zero_division=0)),
            "pulsar_f1": float(f1_score(y_train, yp, zero_division=0)),
            "confusion_matrix_blazar0_pulsar1": confusion_matrix(y_train, yp).tolist(),
        }

    clf = _make_rf().fit(X, y_train)
    skops_path, onnx_path, parity = _export_and_verify(name, clf, X, 2, models_dir)

    p_unid = clf.predict_proba(unid_df[feats].to_numpy(dtype=float))[:, 1]
    unid_counts = {
        "pulsar_ge_0p70": int((p_unid >= 0.70).sum()),
        "blazar_le_0p30": int((p_unid <= 0.30).sum()),
        "ambiguous": int(((p_unid > 0.30) & (p_unid < 0.70)).sum()),
    }

    m50 = _m(0.50)
    m70 = _m(0.70)
    roc = float(roc_auc_score(y_train, oof))
    pr = float(average_precision_score(y_train, oof))

    print(
        f"[{name}] ROC-AUC={roc:.4f} PR-AUC={pr:.4f} | "
        f"P>=0.70 Prec={m70['pulsar_precision']:.4f} Rec={m70['pulsar_recall']:.4f} | "
        f"Unassoc P>=0.70={unid_counts['pulsar_ge_0p70']} P<=0.30={unid_counts['blazar_le_0p30']} | "
        f"skops={parity['skops_max_abs_diff']:.2e} onnx={parity['onnx_float32_max_abs_diff']:.2e}"
    )

    meta = {
        "task": "binary",
        "classes": CLASSES_2,
        "description": description,
        "skops_path": f"models/{skops_path.name}",
        "onnx_path": f"models/{onnx_path.name}",
        "sha256": {"skops": _sha256(skops_path), "onnx": _sha256(onnx_path)},
        "size_bytes": {"skops": skops_path.stat().st_size, "onnx": onnx_path.stat().st_size},
        "features": feats,
        "n_train": int(len(y_train)),
        "cv_metrics": {
            "roc_auc": roc,
            "pr_auc_pulsar": pr,
            "balanced_accuracy_0p50": m50["balanced_accuracy"],
            "pulsar_precision_0p50": m50["pulsar_precision"],
            "pulsar_recall_0p50": m50["pulsar_recall"],
            "pulsar_precision_0p70": m70["pulsar_precision"],
            "pulsar_recall_0p70": m70["pulsar_recall"],
            "metrics_at_0p50": m50,
            "metrics_at_0p70": m70,
        },
        "unassociated_counts": unid_counts,
        "parity_check": parity,
    }
    return meta, p_unid


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--data-dir",
        type=Path,
        default=Path("/home/binx/Projects/sky-watcher/data/processed"),
        help="Directory containing fermi_4fgl.csv and mw_4fgl_matches.csv",
    )
    parser.add_argument(
        "--out-dir",
        type=Path,
        default=Path(__file__).resolve().parent.parent,
        help="Repository root where models/, data/, and config.json will be written",
    )
    args = parser.parse_args()

    models_dir = args.out_dir / "models"
    data_out_dir = args.out_dir / "data"
    models_dir.mkdir(parents=True, exist_ok=True)
    data_out_dir.mkdir(parents=True, exist_ok=True)

    f4 = pd.read_csv(args.data_dir / "fermi_4fgl.csv").dropna(subset=["ra", "dec", "pl_index", "energy_flux"]).copy()
    mw = pd.read_csv(args.data_dir / "mw_4fgl_matches.csv")
    df = build_features(f4, mw)

    st = df["source_type"].fillna("").astype(str).str.strip().str.lower()
    is_blaz = st.isin(["bll", "fsrq", "bcu"])
    is_psr = st.isin(["psr", "msp"])
    is_unid = st.isin(["", "nan", "unid", "unk"])
    is_spp = st == "spp"
    is_other_conf = (~is_blaz) & (~is_psr) & (~is_unid) & (~is_spp)

    mask_3c = is_blaz | is_psr | is_other_conf
    train_3c = df[mask_3c].copy().reset_index(drop=True)
    y_3c = np.where(is_psr[mask_3c], 1, np.where(is_other_conf[mask_3c], 2, 0))

    mask_2c = is_blaz | is_psr
    train_2c = df[mask_2c].copy().reset_index(drop=True)
    y_2c = is_psr[mask_2c].astype(int).to_numpy()

    unid_df = df[is_unid].copy().reset_index(drop=True)

    models_meta: dict[str, Any] = {}
    unid_probs: dict[str, np.ndarray] = {}

    for name, task, feats, desc in MODEL_SPECS:
        if task == "3class":
            meta, p_unid = _eval_3class(name, desc, feats, train_3c, y_3c, unid_df, models_dir)
        else:
            meta, p_unid = _eval_binary(name, desc, feats, train_2c, y_2c, unid_df, models_dir)
        models_meta[name] = meta
        unid_probs[name] = p_unid

    # Export standardized 2,563-row unassociated predictions CSV
    p3_g = unid_probs["rf_3class_gamma_6feat"]
    p3_mw = unid_probs["rf_3class_mw_21feat"]
    p3_mwb = unid_probs["rf_3class_mw_sky_blind_20feat"]
    p2_g = unid_probs["rf_binary_gamma_6feat"]
    p2_mw = unid_probs["rf_binary_mw_21feat"]
    p2_mwb = unid_probs["rf_binary_mw_sky_blind_20feat"]

    def _lbl3(p: np.ndarray, th: float) -> np.ndarray:
        cls = np.array(["Blazar_Cand", "Pulsar_Cand", "Other_Cand"])
        top = p.argmax(axis=1)
        return np.where(p.max(axis=1) >= th, cls[top], "Ambiguous")

    unid_df["p_blazar_3c_gamma"] = p3_g[:, 0]
    unid_df["p_pulsar_3c_gamma"] = p3_g[:, 1]
    unid_df["p_other_3c_gamma"] = p3_g[:, 2]
    unid_df["p_blazar_3c_mw"] = p3_mw[:, 0]
    unid_df["p_pulsar_3c_mw"] = p3_mw[:, 1]
    unid_df["p_other_3c_mw"] = p3_mw[:, 2]
    unid_df["p_blazar_3c_mw_sky_blind"] = p3_mwb[:, 0]
    unid_df["p_pulsar_3c_mw_sky_blind"] = p3_mwb[:, 1]
    unid_df["p_other_3c_mw_sky_blind"] = p3_mwb[:, 2]
    unid_df["p_pulsar_bin_gamma"] = p2_g
    unid_df["p_pulsar_bin_mw"] = p2_mw
    unid_df["p_pulsar_bin_mw_sky_blind"] = p2_mwb
    unid_df["label_3c_mw_0p60"] = _lbl3(p3_mw, 0.60)
    unid_df["label_3c_mw_0p70"] = _lbl3(p3_mw, 0.70)

    export_cols = [
        "name",
        "ra",
        "dec",
        "lii",
        "bii",
        "spectrum_type",
        "pl_index",
        "variability_index",
        "energy_flux",
        "detection_significance",
        "has_radio_95",
        "best_radio_s14_mjy",
        "best_radio_survey",
        "radio_alpha",
        "has_wise_strip_95",
        "has_radio_wise_strip_95",
        "has_xray_95",
        "best_xray_flux",
        "best_xray_survey",
        "p_blazar_3c_gamma",
        "p_pulsar_3c_gamma",
        "p_other_3c_gamma",
        "p_blazar_3c_mw",
        "p_pulsar_3c_mw",
        "p_other_3c_mw",
        "p_blazar_3c_mw_sky_blind",
        "p_pulsar_3c_mw_sky_blind",
        "p_other_3c_mw_sky_blind",
        "p_pulsar_bin_gamma",
        "p_pulsar_bin_mw",
        "p_pulsar_bin_mw_sky_blind",
        "label_3c_mw_0p60",
        "label_3c_mw_0p70",
    ]
    pred_csv = data_out_dir / "fermi_4fgl_3class_predictions.csv"
    unid_df[export_cols].sort_values("p_pulsar_3c_mw", ascending=False).to_csv(pred_csv, index=False)
    print("Wrote", pred_csv)

    pkgs = ["scikit-learn", "skops", "skl2onnx", "onnxruntime", "numpy", "pandas"]
    lib_versions = {p: metadata.version(p) for p in pkgs}

    config = {
        "schema_version": "2.0.0",
        "created_at": datetime.now(timezone.utc).isoformat(),
        "library_versions": lib_versions,
        "dataset": {
            "catalog": "NASA Fermi-LAT 4FGL-DR4 + depth-harmonized radio/WISE/X-ray counterparts",
            "n_total_valid": int(len(df)),
            "n_train_3class": int(len(train_3c)),
            "n_train_binary": int(len(train_2c)),
            "n_blazars": int((y_3c == 0).sum()),
            "n_pulsars": int((y_3c == 1).sum()),
            "n_other_confirmed": int((y_3c == 2).sum()),
            "n_excluded_spp": int(is_spp.sum()),
            "n_unassociated": int(len(unid_df)),
        },
        "hyperparameters": {
            "estimator": "RandomForestClassifier",
            "n_estimators": 300,
            "max_depth": 10,
            "min_samples_leaf": 4,
            "class_weight": "balanced",
            "random_state": 42,
        },
        "leakage_fixes": {
            "removed_is_plec": "PLSuperExpCutoff is assigned to 269/320 confirmed pulsars vs 0/2,563 unassociated sources; dropped from all v2 models.",
            "added_confirmed_other_class": "246 confirmed non-blazar, non-pulsar sources (SNR, PWN, globular cluster, radio galaxy, binary, nova, etc.); 132 unconfirmed spp coincidences kept out of training.",
        },
        "operating_thresholds": {
            "3class_recommended": 0.60,
            "3class_strict": 0.70,
            "binary_blazar_high_conf_max": 0.30,
            "binary_balanced": 0.50,
            "binary_pulsar_high_conf_min": 0.70,
        },
        "preprocessing": {
            "gamma_features": {
                "pl_index": "4FGL photon spectral index",
                "log_var": "log10(clip(variability_index.fillna(1.0), 0.1, None))",
                "log_eflux": "log10(clip(energy_flux, 1e-16, None))",
                "abs_b": "abs(bii.fillna(0.0))",
                "is_curved": "1.0 if spectrum_type in {'LogParabola', 'PLSuperExpCutoff'} else 0.0",
                "sig": "detection_significance.fillna(0.0)",
            },
            "multiwavelength_sentinel_fills_and_clips": {
                "has_radio_95": "1.0 if S_1.4eq >= 2.5 mJy inside r_ell_95 <= 1.0 else 0.0",
                "log_radio_s14": "log10(clip(S_1.4eq, 0.1, None)) if has_radio_95 else -1.0",
                "log_radio_to_gamma": "log10(clip(S_1.4eq, 0.1, None)) - (log_eflux + 12.0) if has_radio_95 else -3.0",
                "has_radio_alpha": "1.0 if finite radio_alpha and has_radio_95 else 0.0",
                "radio_alpha_filled": "clip(radio_alpha, -3.5, 2.5) if has_radio_alpha else 0.0",
                "is_steep_radio": "1.0 if has_radio_alpha and radio_alpha < -1.1 else 0.0",
                "has_wise_strip_95": "1.0 if AllWISE source in D'Abrusco strip inside 95% ellipse else 0.0",
                "has_radio_wise_strip_95": "1.0 if Radio+WISE strip counterpart inside 95% ellipse else 0.0",
                "wise_w1_w2_filled": "clip(w1_w2, -1.0, 3.0) if finite else 0.0",
                "wise_w2_w3_filled": "clip(w2_w3, -1.0, 6.0) if finite else 0.0",
                "wise_strip_dist_filled": "clip(wise_strip_dist, 0.0, 5.0) if finite else 5.0",
                "has_xray_95": "1.0 if X-ray counterpart (eROSITA DR2/DR1 or ROSAT 2RXS clipped 1e-15..1e-10) inside 95% ellipse else 0.0",
                "log_xray_flux": "log10(clip(xray_flux, 1e-16, 1e-9)) if has_xray_95 else -15.5",
                "log_fx_fg": "clip(log10(clip(xray_flux, 1e-16, 1e-9)) - log_eflux, -4.5, 2.5) if has_xray_95 else -4.5",
                "xray_hr_filled": "clip(xray_hr, -1.0, 1.0) if has_xray_95 and finite else 0.0",
            },
        },
        "models": models_meta,
    }

    cfg_path = args.out_dir / "config.json"
    cfg_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
    print("Wrote", cfg_path)


if __name__ == "__main__":
    main()