File size: 20,607 Bytes
4636192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
"""Run optimized pipeline with SMOTE + F2 tuning + CatBoost for F1 > 0.5."""

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
    print("โš ๏ธ  SMOTE not installed. Install: pip install imbalanced-learn")

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_optimized(benchmark_dir) -> pd.DataFrame:
    """Build features from marker data (skip missing peak_table.csv)."""
    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)

    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")

    return mfeat


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    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/optimized_pipeline_m2"),
    )
    parser.add_argument(
        "--threshold-steps",
        type=int,
        default=199,
    )
    parser.add_argument(
        "--use-smote",
        type=bool,
        default=True,
        help="Use SMOTE for class imbalance",
    )
    parser.add_argument(
        "--use-catboost",
        type=bool,
        default=True,
        help="Add CatBoost to ensemble",
    )
    parser.add_argument(
        "--use-f2-metric",
        type=bool,
        default=False,
        help="Use F2 instead of F1 for recall optimization (default: F1)",
    )
    parser.add_argument(
        "--use-gpu",
        type=bool,
        default=True,
        help="Use GPU acceleration on Mac (MPS)",
    )
    return parser.parse_args()


def _tune_threshold_f1(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 _tune_threshold_f2(y_true: np.ndarray, prob: np.ndarray, steps: int) -> Tuple[float, float]:
    """Tune threshold for F2 score (emphasize recall)."""
    thresholds = np.linspace(0.01, 0.99, steps)
    best_f2 = -1.0
    best_th = 0.5
    for th in thresholds:
        pred = (prob >= th).astype(int)
        # F2 = 5 * (precision * recall) / (4 * precision + recall)
        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)
        if f2 > best_f2:
            best_f2 = f2
            best_th = float(th)
    return best_th, best_f2


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("๐Ÿš€ OPTIMIZED PIPELINE (SMOTE + F2 + CatBoost)")
    print("=" * 80)
    print(f"SMOTE: {args.use_smote}")
    print(f"CatBoost: {args.use_catboost}")
    print(f"F2 Tuning: {args.use_f2_metric}")
    print(f"Feature Scaling: True")
    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_optimized(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]
            panel_ohe = pd.get_dummies(data["panel"], prefix="panel")
            x_all = pd.concat([data[feature_cols].astype(float), panel_ohe.astype(float)], axis=1)

            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].values
            y_train = y_all[train_idx]
            x_dev = x_all[dev_idx].values
            y_dev = y_all[dev_idx]
            x_test = x_all[test_idx].values
            y_test = y_all[test_idx]

            feature_names = x_all.columns.tolist()

            # ============ STEP 1: SMOTE ============
            if args.use_smote and SMOTE_AVAILABLE:
                smote = SMOTE(random_state=42, k_neighbors=5)
                x_train, y_train = smote.fit_resample(x_train, y_train)
                print(f"SMOTE: {len(y_train)} samples (balanced)", end=" | ")
            else:
                print(f"No SMOTE: {len(y_train)} samples", end=" | ")

            # ============ STEP 2: Feature Scaling ============
            scaler = StandardScaler()
            x_train_scaled = scaler.fit_transform(x_train)
            x_dev_scaled = scaler.transform(x_dev)
            x_test_scaled = scaler.transform(x_test)

            # ============ STEP 3: Model Training ============
            pos = float((y_train == 1).sum())
            neg = float((y_train == 0).sum())
            spw = max(1.0, neg / max(pos, 1.0))

            # LGBM with better regularization
            lgbm = LGBMClassifier(
                n_estimators=1200,
                learning_rate=0.015,
                num_leaves=100,
                subsample=0.85,
                colsample_bytree=0.85,
                min_child_samples=20,
                lambda_l1=1.0,
                lambda_l2=1.0,
                class_weight="balanced",
                random_state=42,
                verbose=-1,
                n_jobs=-1,
            )

            # XGBoost with optimized params
            xgb = XGBClassifier(
                n_estimators=1200,
                learning_rate=0.015,
                max_depth=7,
                min_child_weight=5,
                subsample=0.85,
                colsample_bytree=0.85,
                reg_alpha=1.0,
                reg_lambda=1.0,
                scale_pos_weight=spw,
                eval_metric="logloss",
                random_state=42,
                n_jobs=-1,
                tree_method="hist",
            )

            lgbm.fit(x_train_scaled, y_train)
            xgb.fit(x_train_scaled, y_train)

            p_dev_l = lgbm.predict_proba(x_dev_scaled)[:, 1]
            p_dev_x = xgb.predict_proba(x_dev_scaled)[:, 1]
            p_test_l = lgbm.predict_proba(x_test_scaled)[:, 1]
            p_test_x = xgb.predict_proba(x_test_scaled)[:, 1]

            # ============ STEP 4: CatBoost (Optional) ============
            p_dev_c = None
            p_test_c = None
            if args.use_catboost:
                cb = CatBoostClassifier(
                    iterations=1200,
                    learning_rate=0.015,
                    depth=7,
                    l2_leaf_reg=1.0,
                    scale_pos_weight=spw,
                    random_state=42,
                    verbose=0,
                    task_type="CPU",
                )
                cb.fit(x_train_scaled, y_train)
                p_dev_c = cb.predict_proba(x_dev_scaled)[:, 1]
                p_test_c = cb.predict_proba(x_test_scaled)[:, 1]

            # ============ STEP 5: F2 Threshold Tuning ============
            if args.use_f2_metric:
                th_l, dev_f_l = _tune_threshold_f2(y_dev, p_dev_l, args.threshold_steps)
                th_x, dev_f_x = _tune_threshold_f2(y_dev, p_dev_x, args.threshold_steps)
            else:
                th_l, dev_f_l = _tune_threshold_f1(y_dev, p_dev_l, args.threshold_steps)
                th_x, dev_f_x = _tune_threshold_f1(y_dev, p_dev_x, args.threshold_steps)

            # ============ STEP 6: Ensemble Fusion ============
            best_weight_lx = 0.5
            best_th_lx = 0.5
            best_dev_f_lx = -1.0
            for w in np.linspace(0.0, 1.0, 21):
                p_dev_lx = (w * p_dev_l) + ((1.0 - w) * p_dev_x)
                if args.use_f2_metric:
                    th_lx, dev_f_lx = _tune_threshold_f2(y_dev, p_dev_lx, args.threshold_steps)
                else:
                    th_lx, dev_f_lx = _tune_threshold_f1(y_dev, p_dev_lx, args.threshold_steps)
                if dev_f_lx > best_dev_f_lx:
                    best_dev_f_lx = dev_f_lx
                    best_th_lx = th_lx
                    best_weight_lx = float(w)

            p_test_lx = (best_weight_lx * p_test_l) + ((1.0 - best_weight_lx) * p_test_x)

            # ============ STEP 7: 3-Model Ensemble (with CatBoost) ============
            if args.use_catboost:
                best_weight_3 = [1/3, 1/3, 1/3]
                best_th_3 = 0.5
                best_dev_f_3 = -1.0
                for w_l in np.linspace(0.0, 1.0, 11):
                    for w_x in np.linspace(0.0, 1.0 - w_l, 6):
                        w_c = 1.0 - w_l - w_x
                        p_dev_3 = (w_l * p_dev_l) + (w_x * p_dev_x) + (w_c * p_dev_c)
                        if args.use_f2_metric:
                            th_3, dev_f_3 = _tune_threshold_f2(y_dev, p_dev_3, args.threshold_steps)
                        else:
                            th_3, dev_f_3 = _tune_threshold_f1(y_dev, p_dev_3, args.threshold_steps)
                        if dev_f_3 > best_dev_f_3:
                            best_dev_f_3 = dev_f_3
                            best_th_3 = th_3
                            best_weight_3 = [w_l, w_x, w_c]

                p_test_3 = (best_weight_3[0] * p_test_l) + (best_weight_3[1] * p_test_x) + (best_weight_3[2] * p_test_c)
            else:
                p_test_3 = p_test_lx
                best_th_3 = best_th_lx
                best_dev_f_3 = best_dev_f_lx
                best_weight_3 = [best_weight_lx, 1.0 - best_weight_lx, 0.0]

            model_payload = {
                "lightgbm_best": {
                    "threshold": th_l,
                    "dev_f": dev_f_l,
                    "dev_pr_auc": float(average_precision_score(y_dev, p_dev_l)),
                    "test_prob": p_test_l,
                },
                "xgboost_best": {
                    "threshold": th_x,
                    "dev_f": dev_f_x,
                    "dev_pr_auc": float(average_precision_score(y_dev, p_dev_x)),
                    "test_prob": p_test_x,
                },
                "fusion_lx_best": {
                    "threshold": best_th_lx,
                    "dev_f": best_dev_f_lx,
                    "dev_pr_auc": float(
                        average_precision_score(y_dev, best_weight_lx * p_dev_l + (1.0 - best_weight_lx) * p_dev_x)
                    ),
                    "test_prob": p_test_lx,
                    "weight_lgbm": best_weight_lx,
                },
            }

            if args.use_catboost:
                model_payload["catboost_best"] = {
                    "threshold": np.percentile(p_dev_c, 50),
                    "dev_f": float(f1_score(y_dev, (p_dev_c >= np.percentile(p_dev_c, 50)).astype(int), zero_division=0)),
                    "dev_pr_auc": float(average_precision_score(y_dev, p_dev_c)),
                    "test_prob": p_test_c,
                }
                model_payload["fusion_3_best"] = {
                    "threshold": best_th_3,
                    "dev_f": best_dev_f_3,
                    "dev_pr_auc": float(
                        average_precision_score(
                            y_dev,
                            best_weight_3[0] * p_dev_l + best_weight_3[1] * p_dev_x + best_weight_3[2] * p_dev_c,
                        )
                    ),
                    "test_prob": p_test_3,
                    "weight_lgbm": best_weight_3[0],
                    "weight_xgb": best_weight_3[1],
                    "weight_catboost": best_weight_3[2],
                }

            for model_name, payload in model_payload.items():
                trial_rows.append(
                    {
                        "benchmark": benchmark_name,
                        "split_id": split_id,
                        "model": model_name,
                        "threshold": float(payload["threshold"]),
                        "dev_score": float(payload["dev_f"]),
                        "dev_pr_auc": float(payload["dev_pr_auc"]),
                    }
                )

                m = _metrics(y_test, payload["test_prob"], float(payload["threshold"]))
                per_split_rows.append(
                    {
                        "benchmark": benchmark_name,
                        "split_id": split_id,
                        "model": model_name,
                        "threshold": float(payload["threshold"]),
                        "dev_score": float(payload["dev_f"]),
                        "dev_pr_auc": float(payload["dev_pr_auc"]),
                        "n_train": int((y_train == 1).sum() + (y_train == 0).sum()),
                        "n_dev": int(dev_idx.sum()),
                        "n_test": int(test_idx.sum()),
                        "test_positive_rate": float(y_test.mean()),
                        **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"])
    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"),
            f2_mean=("f2", "mean"),
            f2_std=("f2", "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(args.out_dir / "optimized_pipeline_per_split.csv", index=False)
    summary.to_csv(args.out_dir / "optimized_pipeline_summary.csv", index=False)
    trials.to_csv(args.out_dir / "optimized_pipeline_trials_dev.csv", index=False)
    (args.out_dir / "run_args.json").write_text(
        json.dumps(
            {
                "use_smote": args.use_smote,
                "use_catboost": args.use_catboost,
                "use_f2_metric": args.use_f2_metric,
                "use_gpu": args.use_gpu,
                "pipeline": "LGBM+XGB+CatBoost with SMOTE, F2 tuning, feature scaling, and 3-model ensemble",
            },
            indent=2,
        )
    )

    total_elapsed = time.time() - total_start
    print(f"\n{'=' * 80}")
    print(f"โœ… Total time: {total_elapsed / 60:.1f} minutes")
    print(f"{'=' * 80}\n")

    return per_split, summary


def main() -> None:
    args = _parse_args()
    _, summary = run(args)
    print("\n๐Ÿ“Š SUMMARY RESULTS:")
    print("=" * 80)
    print(summary.to_string(index=False))
    print("=" * 80)

    # Highlight F1 scores > 0.5
    print("\nโœ… F1 SCORES > 0.5 CHECK:")
    f1_cols = [c for c in summary.columns if 'f1_mean' in c]
    for _, row in summary.iterrows():
        f1_score = row['f1_mean']
        status = "โœ… PASS" if f1_score > 0.5 else "โš ๏ธ  BELOW TARGET"
        print(f"  {row['benchmark']:40s} | {row['model']:20s} | F1={f1_score:.4f} | {status}")


if __name__ == "__main__":
    main()