"""Run baseline unknown-present experiments with LightGBM and XGBoost.""" from __future__ import annotations import argparse import json from dataclasses import dataclass from pathlib import Path from typing import Dict, Iterable, List, Tuple import numpy as np import pandas as pd from lightgbm import LGBMClassifier from sklearn.metrics import ( accuracy_score, average_precision_score, confusion_matrix, f1_score, precision_score, recall_score, roc_auc_score, ) from xgboost import XGBClassifier EPS = 1e-9 @dataclass class ModelTrial: model_name: str params: Dict[str, float] threshold: float dev_f1: float dev_pr_auc: float estimator: object def _parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--benchmark-root", type=Path, default=Path("data/processed"), help="Root folder containing benchmark directories.", ) parser.add_argument( "--benchmarks", nargs="+", default=["rd14-fullref-50_multisplit_v2", "rd12-fullref-61_multisplit_v2"], help="Benchmark directory names to evaluate.", ) parser.add_argument( "--out-dir", type=Path, default=Path("outputs/benchmarks/unknown_detection_full"), help="Output directory for metrics and artifacts.", ) parser.add_argument( "--threshold-steps", type=int, default=99, help="Number of threshold points in [0.01, 0.99] for dev tuning.", ) parser.add_argument( "--full-search", action="store_true", help="Enable a larger hyperparameter grid for stronger results.", ) return parser.parse_args() def _agg_numeric( frame: pd.DataFrame, key: str, value_cols: Iterable[str], prefix: str, ) -> pd.DataFrame: grouped = frame.groupby(key, sort=False)[list(value_cols)] agg = grouped.agg(["mean", "std", "min", "max", "median"]) agg.columns = [f"{prefix}_{col}_{stat}" for col, stat in agg.columns] agg = agg.reset_index() for col in agg.columns: if col != key: agg[col] = agg[col].fillna(0.0) return agg def _build_features(benchmark_dir: Path) -> pd.DataFrame: marker_path = benchmark_dir / "marker_table.csv" peak_path = benchmark_dir / "peak_table.csv" sample_key = "sample_file" marker_cols = [ sample_key, "marker", "dye", "peak_count_total", "peak_count_non_ol", "max_height", "sum_height", "has_ol", ] marker = pd.read_csv(marker_path, usecols=marker_cols, low_memory=False) marker["peak_nonol_ratio"] = marker["peak_count_non_ol"] / ( marker["peak_count_total"] + EPS ) marker["height_density"] = marker["sum_height"] / (marker["peak_count_total"] + EPS) gm = marker.groupby(sample_key, sort=False) mfeat = pd.DataFrame( { sample_key: gm.size().index, "marker_rows": gm.size().values, "marker_unique_count": gm["marker"].nunique().values, "marker_has_ol_rate": gm["has_ol"].mean().values, "marker_peak_total_sum": gm["peak_count_total"].sum().values, "marker_peak_nonol_sum": gm["peak_count_non_ol"].sum().values, "marker_peak_nonol_ratio_mean": gm["peak_nonol_ratio"].mean().values, "marker_height_density_mean": gm["height_density"].mean().values, } ) mnum = _agg_numeric( marker, key=sample_key, value_cols=[ "peak_count_total", "peak_count_non_ol", "peak_nonol_ratio", "max_height", "sum_height", "height_density", ], prefix="marker", ) mfeat = mfeat.merge(mnum, on=sample_key, how="left") dye_sum = marker.pivot_table( index=sample_key, columns="dye", values="sum_height", aggfunc="sum", fill_value=0.0, ) dye_sum.columns = [f"marker_sum_height_dye_{c}" for c in dye_sum.columns] mfeat = mfeat.merge(dye_sum.reset_index(), on=sample_key, how="left") peak_cols = [sample_key, "marker", "dye", "height", "size", "is_ol", "allele_label_norm"] peak = pd.read_csv(peak_path, usecols=peak_cols, low_memory=False) gp = peak.groupby(sample_key, sort=False) pfeat = pd.DataFrame( { sample_key: gp.size().index, "peak_rows": gp.size().values, "peak_ol_count": gp["is_ol"].sum().values, "peak_unique_markers": gp["marker"].nunique().values, "peak_unique_dyes": gp["dye"].nunique().values, } ) pfeat["peak_nonol_count"] = pfeat["peak_rows"] - pfeat["peak_ol_count"] pfeat["peak_ol_rate"] = pfeat["peak_ol_count"] / (pfeat["peak_rows"] + EPS) pfeat["peak_nonol_per_marker"] = pfeat["peak_nonol_count"] / ( pfeat["peak_unique_markers"] + EPS ) pnum = _agg_numeric( peak, key=sample_key, value_cols=["height", "size"], prefix="peak", ) pfeat = pfeat.merge(pnum, on=sample_key, how="left") non_ol = peak[peak["is_ol"] == 0].copy() if len(non_ol) == 0: non_ol = peak.copy() pnum_non_ol = _agg_numeric( non_ol, key=sample_key, value_cols=["height", "size"], prefix="peak_nonol", ) pfeat = pfeat.merge(pnum_non_ol, on=sample_key, how="left") for thr in [30, 50, 100, 200, 500, 1000]: c = ( non_ol.assign(high=(non_ol["height"] >= thr).astype(int)) .groupby(sample_key, sort=False)["high"] .sum() .rename(f"peak_nonol_height_ge_{thr}") ) pfeat = pfeat.merge(c.reset_index(), on=sample_key, how="left") uniq_non_ol = ( non_ol.groupby(sample_key, sort=False)["allele_label_norm"] .nunique() .rename("peak_nonol_unique_alleles") ) pfeat = pfeat.merge(uniq_non_ol.reset_index(), on=sample_key, how="left") features = mfeat.merge(pfeat, on=sample_key, how="inner") for col in features.columns: if col != sample_key: features[col] = features[col].replace([np.inf, -np.inf], 0.0).fillna(0.0) return features def _fit_trial( model_name: str, params: Dict[str, float], x_train: pd.DataFrame, y_train: np.ndarray, x_dev: pd.DataFrame, y_dev: np.ndarray, threshold_steps: int, ) -> ModelTrial: if model_name == "lightgbm": estimator = LGBMClassifier(**params) elif model_name == "xgboost": estimator = XGBClassifier(**params) else: raise ValueError(f"Unsupported model: {model_name}") estimator.fit(x_train, y_train) dev_prob = estimator.predict_proba(x_dev)[:, 1] ths = np.linspace(0.01, 0.99, threshold_steps) best_f1 = -1.0 best_th = 0.5 for th in ths: pred = (dev_prob >= th).astype(int) score = f1_score(y_dev, pred, zero_division=0) if score > best_f1: best_f1 = float(score) best_th = float(th) dev_pr = float(average_precision_score(y_dev, dev_prob)) return ModelTrial( model_name=model_name, params=params, threshold=best_th, dev_f1=best_f1, dev_pr_auc=dev_pr, estimator=estimator, ) def _metrics(y_true: np.ndarray, prob: np.ndarray, threshold: float) -> Dict[str, float]: pred = (prob >= threshold).astype(int) tn, fp, fn, tp = confusion_matrix(y_true, pred, labels=[0, 1]).ravel() specificity = tn / (tn + fp + EPS) return { "roc_auc": float(roc_auc_score(y_true, prob)), "pr_auc": float(average_precision_score(y_true, prob)), "f1": float(f1_score(y_true, pred, zero_division=0)), "precision": float(precision_score(y_true, pred, zero_division=0)), "recall": float(recall_score(y_true, pred, zero_division=0)), "specificity": float(specificity), "accuracy": float(accuracy_score(y_true, pred)), "tp": int(tp), "fp": int(fp), "tn": int(tn), "fn": int(fn), } def _model_grids( scale_pos_weight: float, full_search: bool = False ) -> Dict[str, List[Dict[str, float]]]: if full_search: return { "lightgbm": [ { "n_estimators": 500, "learning_rate": 0.05, "num_leaves": 63, "subsample": 0.9, "colsample_bytree": 0.9, "class_weight": "balanced", "random_state": 42, "verbose": -1, }, { "n_estimators": 800, "learning_rate": 0.03, "num_leaves": 127, "subsample": 0.9, "colsample_bytree": 0.9, "class_weight": "balanced", "random_state": 42, "verbose": -1, }, { "n_estimators": 1100, "learning_rate": 0.02, "num_leaves": 127, "subsample": 0.95, "colsample_bytree": 0.95, "class_weight": "balanced", "random_state": 42, "verbose": -1, }, ], "xgboost": [ { "n_estimators": 500, "learning_rate": 0.05, "max_depth": 6, "subsample": 0.9, "colsample_bytree": 0.9, "scale_pos_weight": scale_pos_weight, "eval_metric": "logloss", "random_state": 42, "n_jobs": 4, }, { "n_estimators": 800, "learning_rate": 0.03, "max_depth": 8, "subsample": 0.9, "colsample_bytree": 0.9, "scale_pos_weight": scale_pos_weight, "eval_metric": "logloss", "random_state": 42, "n_jobs": 4, }, { "n_estimators": 1100, "learning_rate": 0.02, "max_depth": 8, "subsample": 0.95, "colsample_bytree": 0.95, "scale_pos_weight": scale_pos_weight, "eval_metric": "logloss", "random_state": 42, "n_jobs": 4, }, ], } return { "lightgbm": [ { "n_estimators": 350, "learning_rate": 0.05, "num_leaves": 63, "subsample": 0.9, "colsample_bytree": 0.9, "class_weight": "balanced", "random_state": 42, "verbose": -1, }, ], "xgboost": [ { "n_estimators": 350, "learning_rate": 0.05, "max_depth": 6, "subsample": 0.9, "colsample_bytree": 0.9, "scale_pos_weight": scale_pos_weight, "eval_metric": "logloss", "random_state": 42, "n_jobs": 4, }, ], } def run(args: argparse.Namespace) -> Tuple[pd.DataFrame, pd.DataFrame]: out_dir = args.out_dir out_dir.mkdir(parents=True, exist_ok=True) all_rows: List[Dict[str, float]] = [] trial_rows: List[Dict[str, float]] = [] for benchmark_name in args.benchmarks: benchmark_dir = args.benchmark_root / benchmark_name labels = pd.read_csv(benchmark_dir / "sample_labels_all_splits.csv", low_memory=False) features = _build_features(benchmark_dir) for split_id in sorted(labels["split_id"].unique()): split_df = labels[labels["split_id"] == split_id].copy() data = split_df.merge(features, on="sample_file", how="inner") feature_cols = [ c for c in data.columns if c not in { "benchmark_id", "split_id", "partition", "study_id", "panel", "sample_file", "sample_family_id", "true_contributors", "known_contributors_true", "unknown_contributors_true", "num_known_in_sample", "num_unknown_in_sample", "unknown_present", "total_contributors", } ] panel_ohe = pd.get_dummies(data["panel"], prefix="panel") x_base = pd.concat([data[feature_cols].astype(float), panel_ohe.astype(float)], axis=1) y = data["unknown_present"].astype(int).values partition = data["partition"].values train_idx = partition == "train" dev_idx = partition == "dev" test_idx = partition == "test" x_train, y_train = x_base[train_idx], y[train_idx] x_dev, y_dev = x_base[dev_idx], y[dev_idx] x_test, y_test = x_base[test_idx], y[test_idx] pos = float(y_train.sum()) neg = float(len(y_train) - y_train.sum()) scale_pos_weight = max(1.0, neg / max(pos, 1.0)) grids = _model_grids( scale_pos_weight=scale_pos_weight, full_search=args.full_search ) for model_name, candidates in grids.items(): best: ModelTrial | None = None for candidate in candidates: trial = _fit_trial( model_name=model_name, params=candidate, x_train=x_train, y_train=y_train, x_dev=x_dev, y_dev=y_dev, threshold_steps=args.threshold_steps, ) trial_rows.append( { "benchmark": benchmark_name, "split_id": split_id, "model": model_name, "dev_f1": trial.dev_f1, "dev_pr_auc": trial.dev_pr_auc, "threshold": trial.threshold, "params": json.dumps(candidate, sort_keys=True), } ) if best is None or trial.dev_f1 > best.dev_f1: best = trial assert best is not None test_prob = best.estimator.predict_proba(x_test)[:, 1] metrics = _metrics(y_test, test_prob, best.threshold) all_rows.append( { "benchmark": benchmark_name, "split_id": split_id, "model": model_name, "threshold": best.threshold, "best_dev_f1": best.dev_f1, "best_dev_pr_auc": best.dev_pr_auc, "n_train": int(train_idx.sum()), "n_dev": int(dev_idx.sum()), "n_test": int(test_idx.sum()), "test_positive_rate": float(y_test.mean()), **metrics, } ) per_split = pd.DataFrame(all_rows).sort_values(["benchmark", "model", "split_id"]) trials = pd.DataFrame(trial_rows).sort_values(["benchmark", "model", "split_id"]) summary = ( per_split.groupby(["benchmark", "model"], as_index=False) .agg( roc_auc_mean=("roc_auc", "mean"), roc_auc_std=("roc_auc", "std"), pr_auc_mean=("pr_auc", "mean"), pr_auc_std=("pr_auc", "std"), f1_mean=("f1", "mean"), f1_std=("f1", "std"), precision_mean=("precision", "mean"), recall_mean=("recall", "mean"), specificity_mean=("specificity", "mean"), accuracy_mean=("accuracy", "mean"), ) .sort_values(["benchmark", "model"]) ) per_split.to_csv(out_dir / "unknown_detection_per_split.csv", index=False) summary.to_csv(out_dir / "unknown_detection_summary.csv", index=False) trials.to_csv(out_dir / "unknown_detection_trials_dev.csv", index=False) (out_dir / "run_args.json").write_text( json.dumps( { "benchmark_root": str(args.benchmark_root), "benchmarks": args.benchmarks, "threshold_steps": args.threshold_steps, "full_search": args.full_search, }, indent=2, ) ) return per_split, summary def main() -> None: args = _parse_args() _, summary = run(args) print(summary.to_string(index=False)) if __name__ == "__main__": main()