"""Advanced feature engineering pipeline with synthetic features.""" from __future__ import annotations import argparse import json import sys import time from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pandas as pd from catboost import CatBoostClassifier 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 sklearn.preprocessing import StandardScaler from xgboost import XGBClassifier try: from imblearn.over_sampling import SMOTE SMOTE_AVAILABLE = True except ImportError: SMOTE_AVAILABLE = False ROOT = Path(__file__).resolve().parents[2] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) EPS = 1e-9 def _agg_numeric(frame: pd.DataFrame, key: str, value_cols, prefix: str) -> pd.DataFrame: """Aggregate numeric features.""" 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_with_engineering(benchmark_dir: Path) -> pd.DataFrame: """Build features with advanced synthetic feature engineering.""" marker_path = benchmark_dir / "marker_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) marker["max_ratio"] = marker["max_height"] / (marker["sum_height"] + EPS) # ===== BASE FEATURES ===== 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", "max_ratio", ], prefix="marker", ) mfeat = mfeat.merge(mnum, on=sample_key, how="left") # ===== DYE FEATURES ===== 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") # ===== ADVANCED SYNTHETIC FEATURES ===== print(" ✨ Engineering synthetic features...") # 1. Marker quality features mfeat["marker_avg_peak_count"] = mfeat["marker_peak_total_sum"] / (mfeat["marker_unique_count"] + EPS) mfeat["marker_nonol_ratio"] = mfeat["marker_peak_nonol_sum"] / (mfeat["marker_peak_total_sum"] + EPS) # 2. Height-based features (from aggregated marker features) if "marker_sum_height_std" in mfeat.columns: mfeat["marker_height_coefficient_of_variation"] = ( mfeat["marker_sum_height_std"] / (mfeat["marker_sum_height_mean"] + EPS) ) if "marker_sum_height_max" in mfeat.columns and "marker_sum_height_min" in mfeat.columns: mfeat["marker_height_range"] = mfeat["marker_sum_height_max"] - mfeat["marker_sum_height_min"] # 3. Variance features if "marker_peak_count_total_std" in mfeat.columns: mfeat["marker_peak_variance"] = mfeat["marker_peak_count_total_std"] # 4. Dye balance features dye_cols = [c for c in mfeat.columns if c.startswith("marker_sum_height_dye_")] if dye_cols and len(dye_cols) > 1: dye_values = mfeat[dye_cols].fillna(0).values mfeat["dye_count"] = (dye_values > 0).sum(axis=1) dye_sums = dye_values.sum(axis=1, keepdims=True) + EPS dye_norm = dye_values / dye_sums mfeat["dye_balance_entropy"] = -np.sum(dye_norm * np.log(dye_norm + EPS), axis=1) mfeat["dye_dominant_ratio"] = dye_values.max(axis=1) / (dye_values.sum(axis=1) + EPS) mfeat["dye_magnitude_range"] = dye_values.max(axis=1) - dye_values.min(axis=1) # 5. Outlier features mfeat["marker_ol_severity"] = mfeat["marker_has_ol_rate"] * mfeat["marker_rows"] mfeat["marker_nonol_density"] = ( mfeat["marker_peak_nonol_sum"] / (mfeat["marker_rows"] + EPS) ) # 6. Distribution features (if available) if "marker_sum_height_max" in mfeat.columns and "marker_sum_height_min" in mfeat.columns: mfeat["marker_min_max_ratio"] = ( mfeat["marker_sum_height_min"] / (mfeat["marker_sum_height_max"] + EPS) ) if "marker_sum_height_median" in mfeat.columns and "marker_sum_height_mean" in mfeat.columns: mfeat["marker_median_mean_ratio"] = ( mfeat["marker_sum_height_median"] / (mfeat["marker_sum_height_mean"] + EPS) ) # 7. Interaction features mfeat["marker_complexity"] = ( mfeat["marker_unique_count"] * mfeat["marker_rows"] * mfeat["marker_has_ol_rate"] ) mfeat["marker_quality_score"] = ( mfeat["marker_nonol_ratio"] * (1 - mfeat["marker_has_ol_rate"]) * mfeat["marker_peak_nonol_ratio_mean"] ) # 8. Robustness features if "marker_peak_count_total_std" in mfeat.columns and "marker_peak_count_total_mean" in mfeat.columns: mfeat["marker_consistency"] = ( 1 - (mfeat["marker_peak_count_total_std"] / (mfeat["marker_peak_count_total_mean"] + EPS)) ).clip(0, 1) # Fill NaN values mfeat = mfeat.fillna(0) mfeat = mfeat.replace([np.inf, -np.inf], 0) return mfeat def _tune_threshold(y_true: np.ndarray, prob: np.ndarray, steps: int) -> Tuple[float, float]: """Tune threshold for F1 score.""" thresholds = np.linspace(0.01, 0.99, steps) best_f1 = -1.0 best_th = 0.5 for th in thresholds: pred = (prob >= th).astype(int) score = f1_score(y_true, pred, zero_division=0) if score > best_f1: best_f1 = float(score) best_th = float(th) return best_th, best_f1 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) precision = precision_score(y_true, pred, zero_division=0) recall = recall_score(y_true, pred, zero_division=0) f2 = (5 * precision * recall) / (4 * precision + recall + 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)), "f2": float(f2), "precision": float(precision), "recall": float(recall), "specificity": float(specificity), "accuracy": float(accuracy_score(y_true, pred)), "tp": int(tp), "fp": int(fp), "tn": int(tn), "fn": int(fn), } def run(args: argparse.Namespace) -> Tuple[pd.DataFrame, pd.DataFrame]: args.out_dir.mkdir(parents=True, exist_ok=True) print("=" * 80) print("šŸš€ ADVANCED FEATURE ENGINEERING PIPELINE") print("=" * 80) per_split_rows: List[Dict[str, object]] = [] trial_rows: List[Dict[str, object]] = [] total_start = time.time() for benchmark_name in args.benchmarks: print(f"\nšŸ“Š Processing benchmark: {benchmark_name}") benchmark_dir = args.benchmark_root / benchmark_name labels = pd.read_csv(benchmark_dir / "sample_labels_all_splits.csv", low_memory=False) features = _build_features_with_engineering(benchmark_dir) for split_idx, split_id in enumerate(sorted(labels["split_id"].unique())): print(f" Split {split_idx + 1}/{len(labels['split_id'].unique())}: {split_id}", end=" ") split_start = time.time() split_df = labels[labels["split_id"] == split_id].copy() data = split_df.merge(features, on="sample_file", how="inner") drop_cols = { "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", } feature_cols = [c for c in data.columns if c not in drop_cols] x_all = data[feature_cols].astype(float).values y_all = data["unknown_present"].astype(int).values partition = data["partition"].values train_idx = partition == "train" dev_idx = partition == "dev" test_idx = partition == "test" x_train = x_all[train_idx] y_train = y_all[train_idx] x_dev = x_all[dev_idx] y_dev = y_all[dev_idx] x_test = x_all[test_idx] y_test = y_all[test_idx] # SMOTE if SMOTE_AVAILABLE: smote = SMOTE(random_state=42, k_neighbors=5) x_train, y_train = smote.fit_resample(x_train, y_train) # Feature scaling scaler = StandardScaler() x_train = scaler.fit_transform(x_train) x_dev = scaler.transform(x_dev) x_test = scaler.transform(x_test) # Training pos = float((y_train == 1).sum()) neg = float((y_train == 0).sum()) spw = max(1.0, neg / max(pos, 1.0)) lgbm = LGBMClassifier( n_estimators=1500, learning_rate=0.01, num_leaves=80, subsample=0.80, colsample_bytree=0.80, min_child_samples=25, lambda_l1=2.0, lambda_l2=2.0, class_weight="balanced", random_state=42, verbose=-1, n_jobs=-1, ) xgb = XGBClassifier( n_estimators=1500, learning_rate=0.01, max_depth=6, min_child_weight=7, subsample=0.80, colsample_bytree=0.80, reg_alpha=2.0, reg_lambda=2.0, scale_pos_weight=spw, eval_metric="logloss", random_state=42, n_jobs=-1, ) lgbm.fit(x_train, y_train) xgb.fit(x_train, y_train) p_dev_l = lgbm.predict_proba(x_dev)[:, 1] p_dev_x = xgb.predict_proba(x_dev)[:, 1] p_test_l = lgbm.predict_proba(x_test)[:, 1] p_test_x = xgb.predict_proba(x_test)[:, 1] # Threshold tuning (F1) th_l, dev_f1_l = _tune_threshold(y_dev, p_dev_l, args.threshold_steps) th_x, dev_f1_x = _tune_threshold(y_dev, p_dev_x, args.threshold_steps) # 2-Model ensemble best_weight = 0.5 best_th = 0.5 best_f1 = -1.0 for w in np.linspace(0.0, 1.0, 21): p_dev = (w * p_dev_l) + ((1.0 - w) * p_dev_x) th, dev_f1 = _tune_threshold(y_dev, p_dev, args.threshold_steps) if dev_f1 > best_f1: best_f1 = dev_f1 best_th = th best_weight = float(w) p_test = (best_weight * p_test_l) + ((1.0 - best_weight) * p_test_x) model_payload = { "lightgbm": { "threshold": th_l, "dev_f1": dev_f1_l, "test_prob": p_test_l, }, "xgboost": { "threshold": th_x, "dev_f1": dev_f1_x, "test_prob": p_test_x, }, "fusion": { "threshold": best_th, "dev_f1": best_f1, "test_prob": p_test, "weight": best_weight, }, } for model_name, payload in model_payload.items(): m = _metrics(y_test, payload["test_prob"], float(payload["threshold"])) per_split_rows.append( { "benchmark": benchmark_name, "split_id": split_id, "model": model_name, **m, } ) split_elapsed = time.time() - split_start print(f"āœ… {split_elapsed:.1f}s") per_split = pd.DataFrame(per_split_rows).sort_values(["benchmark", "model", "split_id"]) summary = ( per_split.groupby(["benchmark", "model"], as_index=False) .agg( f1_mean=("f1", "mean"), f1_std=("f1", "std"), precision_mean=("precision", "mean"), recall_mean=("recall", "mean"), roc_auc_mean=("roc_auc", "mean"), ) .sort_values(["benchmark", "model"]) ) per_split.to_csv(args.out_dir / "advanced_features_per_split.csv", index=False) summary.to_csv(args.out_dir / "advanced_features_summary.csv", index=False) total_elapsed = time.time() - total_start print(f"\n{'=' * 80}") print(f"āœ… Total time: {total_elapsed / 60:.1f} minutes") print(f"Features: {len(feature_cols)} total") print(f"{'=' * 80}\n") return per_split, summary def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--benchmark-root", type=Path, default=Path("data/processed")) parser.add_argument("--benchmarks", nargs="+", default=["rd14-fullref-50_multisplit_v2", "rd12-fullref-61_multisplit_v2"]) parser.add_argument("--out-dir", type=Path, default=Path("outputs/benchmarks/advanced_features")) parser.add_argument("--threshold-steps", type=int, default=199) args = parser.parse_args() _, summary = run(args) print("\nšŸ“Š RESULTS:") print(summary.to_string(index=False)) if __name__ == "__main__": main()