File size: 26,973 Bytes
a2d1ad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd
from sklearn.metrics import pairwise_distances
from sklearn.preprocessing import StandardScaler


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Run the CB-Telemetry time-matched retrieval protocol on released feature tables."
    )
    parser.add_argument("--root", default=".", help="CB-Telemetry dataset root.")
    parser.add_argument("--feature-table", required=True, help="Anchor feature table used to define rows and slots.")
    parser.add_argument("--output-dir", required=True, help="Directory for retrieval outputs.")
    parser.add_argument("--max-slot-gap", type=int, default=1, help="Maximum neighboring-slot gap.")
    parser.add_argument("--min-dates-per-pair", type=int, default=12, help="Minimum dates required per slot pair.")
    parser.add_argument("--bootstrap-samples", type=int, default=2000, help="Bootstrap resamples for intervals.")
    parser.add_argument("--bootstrap-seed", type=int, default=42, help="Bootstrap random seed.")
    parser.add_argument("--random-seed", type=int, default=42, help="Random seed for the permuted-control baseline.")
    parser.add_argument(
        "--archive-scope",
        choices=["global", "same_archive_only"],
        default="global",
        help="Candidate pool: all target rows, or rows from the same archive only.",
    )
    parser.add_argument(
        "--representation",
        action="append",
        default=[],
        help="Repeat as name=feature_table_path. Paths are resolved relative to --root unless absolute.",
    )
    parser.add_argument(
        "--include-metadata-controls",
        action="store_true",
        help="Add metadata_basic, metadata_calendar, and random_permuted_continuous controls.",
    )
    return parser.parse_args()


def resolve_path(root: Path, raw_path: str) -> Path:
    path = Path(raw_path).expanduser()
    if not path.is_absolute():
        path = (root / path).resolve()
    return path


def release_path(root: Path, path: Path) -> str:
    try:
        return path.resolve().relative_to(root).as_posix()
    except ValueError:
        return path.as_posix()


def build_key(df: pd.DataFrame) -> pd.Series:
    return (
        df["archive"].astype(str).str.strip()
        + "||"
        + df["date"].astype(str).str.strip()
        + "||"
        + df["filename"].astype(str).str.strip()
    )


def add_slot_metadata(df: pd.DataFrame) -> pd.DataFrame:
    result = df.copy()
    result["timestamp_dt"] = pd.to_datetime(result["timestamp"], errors="raise")
    result["date"] = result["date"].astype(str)
    result["archive"] = result["archive"].astype(str)
    result["filename"] = result["filename"].astype(str)
    result["key"] = build_key(result)
    result["dawn_slot_id"] = 0
    result["slot_count_on_date"] = 0
    result["slot_hour_signature"] = ""
    for date_str, group in result.groupby("date", sort=True):
        ordered = group.sort_values(["timestamp_dt", "filename"]).copy()
        slot_ids = np.arange(1, len(ordered) + 1, dtype=np.int32)
        result.loc[ordered.index, "dawn_slot_id"] = slot_ids
        result.loc[ordered.index, "slot_count_on_date"] = int(len(ordered))
        signature = "-".join(str(int(item)) for item in ordered["hour"].tolist())
        result.loc[ordered.index, "slot_hour_signature"] = signature
    result["dawn_slot_id"] = result["dawn_slot_id"].astype(int)
    result["slot_count_on_date"] = result["slot_count_on_date"].astype(int)
    return result


def feature_columns(df: pd.DataFrame) -> list[str]:
    columns = [col for col in df.columns if col.startswith("f_")]
    if not columns:
        raise RuntimeError("No f_* feature columns were found.")
    return columns


def standardize(matrix: np.ndarray) -> np.ndarray:
    return StandardScaler().fit_transform(matrix.astype(np.float32, copy=False)).astype(np.float32)


def load_representation_matrix(root: Path, path_text: str, anchor_df: pd.DataFrame) -> np.ndarray:
    path = resolve_path(root, path_text)
    df = pd.read_csv(path, low_memory=False).copy()
    df["date"] = df["date"].astype(str)
    df["archive"] = df["archive"].astype(str)
    df["filename"] = df["filename"].astype(str)
    df["key"] = build_key(df)
    columns = feature_columns(df)
    indexed = df.set_index("key")
    keys = anchor_df["key"].tolist()
    missing = [key for key in keys if key not in indexed.index]
    if missing:
        raise RuntimeError(f"{path} is missing {len(missing)} anchor rows.")
    matrix = indexed.loc[keys, columns].to_numpy(dtype=np.float32)
    return standardize(matrix)


def parse_representations(items: list[str]) -> list[tuple[str, str]]:
    if not items:
        raise ValueError("At least one --representation name=path is required.")
    result: list[tuple[str, str]] = []
    for item in items:
        if "=" not in item:
            raise ValueError(f"Invalid representation argument: {item}")
        name, raw_path = item.split("=", 1)
        result.append((name.strip(), raw_path.strip()))
    return result


def build_metadata_matrix(anchor_df: pd.DataFrame, include_calendar: bool) -> np.ndarray:
    archive_dummies = pd.get_dummies(anchor_df["archive"].astype(str), prefix="archive", dtype=np.float32)
    slot_dummies = pd.get_dummies(anchor_df["dawn_slot_id"].astype(int), prefix="slot", dtype=np.float32)
    blocks = [
        anchor_df["hour"].astype(np.float32).to_numpy()[:, None],
        archive_dummies.to_numpy(dtype=np.float32),
        slot_dummies.to_numpy(dtype=np.float32),
    ]
    if include_calendar:
        date_dt = pd.to_datetime(anchor_df["date"].astype(str), format="%Y%m%d", errors="raise")
        month_angle = 2.0 * np.pi * (date_dt.dt.month.to_numpy(dtype=np.float32) - 1.0) / 12.0
        year_offset = date_dt.dt.year.to_numpy(dtype=np.float32) - float(date_dt.dt.year.min())
        blocks.extend(
            [
                np.sin(month_angle).astype(np.float32)[:, None],
                np.cos(month_angle).astype(np.float32)[:, None],
                year_offset.astype(np.float32)[:, None],
            ]
        )
    return standardize(np.column_stack(blocks).astype(np.float32))


def cosine_rank_indices(query_matrix: np.ndarray, target_matrix: np.ndarray) -> np.ndarray:
    distances = pairwise_distances(query_matrix, target_matrix, metric="cosine")
    return np.argsort(distances, axis=1)


def reciprocal_rank(rank_index_zero_based: int) -> float:
    return 1.0 / float(rank_index_zero_based + 1)


def summarize_query_rows(query_df: pd.DataFrame) -> dict[str, float]:
    rank_positions = query_df["rank_position"].to_numpy(dtype=np.float32)
    return {
        "top1_hit_rate": float(query_df["top1_hit"].mean()),
        "top5_hit_rate": float(query_df["top5_hit"].mean()),
        "mrr": float(query_df["reciprocal_rank"].mean()),
        "median_rank": float(np.median(rank_positions)),
        "mean_rank": float(np.mean(rank_positions)),
    }


def evaluate_pair_subset(
    matrix: np.ndarray,
    pair_df: pd.DataFrame,
    query_slot: int,
    target_slot: int,
    archive_label: str,
) -> dict[str, Any]:
    eligible_dates = pair_df.groupby("date")["dawn_slot_id"].nunique().reset_index(name="slot_count")
    eligible_dates = eligible_dates[eligible_dates["slot_count"] == 2]["date"].astype(str).tolist()
    pair_df = pair_df[pair_df["date"].isin(eligible_dates)].copy()
    query_df = pair_df[pair_df["dawn_slot_id"] == query_slot].copy().sort_values("date").reset_index(drop=True)
    target_df = pair_df[pair_df["dawn_slot_id"] == target_slot].copy().sort_values("date").reset_index(drop=True)

    if query_df.empty or target_df.empty:
        raise RuntimeError(f"slot_pair {query_slot}->{target_slot} has no valid rows.")
    if query_df["date"].tolist() != target_df["date"].tolist():
        raise RuntimeError(f"slot_pair {query_slot}->{target_slot} query and target dates are not aligned.")

    query_matrix = matrix[query_df["anchor_row_index"].to_numpy()]
    target_matrix = matrix[target_df["anchor_row_index"].to_numpy()]
    ranks = cosine_rank_indices(query_matrix, target_matrix)

    positive_dates = query_df["date"].tolist()
    target_dates = target_df["date"].tolist()
    query_rows: list[dict[str, Any]] = []
    for row_idx, expected_date in enumerate(positive_dates):
        ranked_dates = [target_dates[item] for item in ranks[row_idx].tolist()]
        positive_rank = ranked_dates.index(expected_date)
        query_rows.append(
            {
                "date": str(expected_date),
                "query_slot": int(query_slot),
                "target_slot": int(target_slot),
                "archive_scope_label": archive_label,
                "candidate_size_per_query": int(len(target_df)),
                "chance_top1": 1.0 / float(len(target_df)),
                "rank_position": int(positive_rank + 1),
                "top1_hit": 1.0 if positive_rank == 0 else 0.0,
                "top5_hit": 1.0 if positive_rank < min(5, len(ranked_dates)) else 0.0,
                "reciprocal_rank": reciprocal_rank(positive_rank),
            }
        )

    query_result_df = pd.DataFrame(query_rows)
    metrics = summarize_query_rows(query_result_df)
    return {
        "query_slot": int(query_slot),
        "target_slot": int(target_slot),
        "archive_scope_label": archive_label,
        "query_rows": int(len(query_df)),
        "candidate_rows": int(len(target_df)),
        "candidate_size_per_query": int(len(target_df)),
        "chance_top1": 1.0 / float(len(target_df)),
        "top1_hit_rate": metrics["top1_hit_rate"],
        "top5_hit_rate": metrics["top5_hit_rate"],
        "mrr": metrics["mrr"],
        "median_rank": metrics["median_rank"],
        "mean_rank": metrics["mean_rank"],
        "date_examples": positive_dates[:5],
        "query_details": query_rows,
    }


def evaluate_slot_pair(
    matrix: np.ndarray,
    anchor_df: pd.DataFrame,
    query_slot: int,
    target_slot: int,
    archive_scope: str,
    min_dates_per_pair: int,
) -> list[dict[str, Any]]:
    pair_df = anchor_df[anchor_df["dawn_slot_id"].isin([query_slot, target_slot])].copy()
    if archive_scope == "global":
        return [
            evaluate_pair_subset(
                matrix,
                pair_df=pair_df,
                query_slot=query_slot,
                target_slot=target_slot,
                archive_label="all",
            )
        ]

    rows: list[dict[str, Any]] = []
    for archive_name, archive_df in pair_df.groupby("archive", sort=True):
        if archive_df["dawn_slot_id"].nunique() < 2:
            continue
        eligible_dates = archive_df.groupby("date")["dawn_slot_id"].nunique().reset_index(name="slot_count")
        eligible_dates = eligible_dates[eligible_dates["slot_count"] == 2]
        if int(len(eligible_dates)) < min_dates_per_pair:
            continue
        rows.append(
            evaluate_pair_subset(
                matrix,
                pair_df=archive_df.copy(),
                query_slot=query_slot,
                target_slot=target_slot,
                archive_label=str(archive_name),
            )
        )
    return rows


def build_slot_pairs(
    anchor_df: pd.DataFrame,
    max_slot_gap: int,
    min_dates_per_pair: int,
    archive_scope: str,
) -> list[tuple[int, int]]:
    max_slot_id = int(anchor_df["dawn_slot_id"].max())
    pairs: list[tuple[int, int]] = []
    for query_slot in range(1, max_slot_id + 1):
        for target_slot in range(1, max_slot_id + 1):
            if query_slot == target_slot:
                continue
            if abs(query_slot - target_slot) > max_slot_gap:
                continue
            pair_df = anchor_df[anchor_df["dawn_slot_id"].isin([query_slot, target_slot])].copy()
            if archive_scope == "global":
                eligible_dates = pair_df.groupby("date")["dawn_slot_id"].nunique().reset_index(name="slot_count")
                eligible_dates = eligible_dates[eligible_dates["slot_count"] == 2]
                if int(len(eligible_dates)) >= min_dates_per_pair:
                    pairs.append((query_slot, target_slot))
                continue

            archive_has_valid_pair = False
            for _, archive_df in pair_df.groupby("archive", sort=True):
                if archive_df["dawn_slot_id"].nunique() < 2:
                    continue
                eligible_dates = archive_df.groupby("date")["dawn_slot_id"].nunique().reset_index(name="slot_count")
                eligible_dates = eligible_dates[eligible_dates["slot_count"] == 2]
                if int(len(eligible_dates)) >= min_dates_per_pair:
                    archive_has_valid_pair = True
                    break
            if archive_has_valid_pair:
                pairs.append((query_slot, target_slot))
    if not pairs:
        raise RuntimeError("No valid slot pairs satisfy min_dates_per_pair.")
    return sorted(pairs)


def aggregate_pair_rows(method_name: str, pair_df: pd.DataFrame) -> dict[str, float | str]:
    return {
        "method": method_name,
        "mean_top1_hit_rate": float(pair_df["top1_hit_rate"].mean()),
        "mean_top5_hit_rate": float(pair_df["top5_hit_rate"].mean()),
        "mean_mrr": float(pair_df["mrr"].mean()),
        "mean_median_rank": float(pair_df["median_rank"].mean()),
        "mean_candidate_size": float(pair_df["candidate_size_per_query"].mean()),
        "mean_chance_top1": float(pair_df["chance_top1"].mean()),
    }


def evaluate_representation(
    method_name: str,
    matrix: np.ndarray,
    anchor_df: pd.DataFrame,
    slot_pairs: list[tuple[int, int]],
    archive_scope: str,
    min_dates_per_pair: int,
) -> dict[str, Any]:
    pair_rows: list[dict[str, Any]] = []
    query_rows: list[dict[str, Any]] = []
    for query_slot, target_slot in slot_pairs:
        rows = evaluate_slot_pair(
            matrix,
            anchor_df,
            query_slot=query_slot,
            target_slot=target_slot,
            archive_scope=archive_scope,
            min_dates_per_pair=min_dates_per_pair,
        )
        for row in rows:
            raw_query_details = row.pop("query_details")
            row["method"] = method_name
            pair_rows.append(row)
            for query_detail in raw_query_details:
                query_detail["method"] = method_name
                query_rows.append(query_detail)
    if not pair_rows:
        raise RuntimeError(f"method={method_name} has no valid pair rows.")
    aggregate = aggregate_pair_rows(method_name, pd.DataFrame(pair_rows))
    return {"aggregate": aggregate, "pairs": pair_rows, "queries": query_rows}


def percentile_interval(samples: list[float]) -> tuple[float, float]:
    values = np.asarray(samples, dtype=np.float64)
    return float(np.percentile(values, 2.5)), float(np.percentile(values, 97.5))


def bootstrap_pair_level(
    method_name: str,
    pair_df: pd.DataFrame,
    bootstrap_samples: int,
    rng: np.random.Generator,
) -> dict[str, Any]:
    metric_names = ["top1_hit_rate", "mrr", "top5_hit_rate"]
    point_estimates = {metric: float(pair_df[metric].mean()) for metric in metric_names}
    boot_values = {metric: [] for metric in metric_names}
    pair_count = len(pair_df)
    for _ in range(bootstrap_samples):
        sampled_indices = rng.integers(0, pair_count, size=pair_count)
        sampled = pair_df.iloc[sampled_indices]
        for metric in metric_names:
            boot_values[metric].append(float(sampled[metric].mean()))

    result: dict[str, Any] = {
        "method": method_name,
        "bootstrap_unit": "pair",
        "bootstrap_samples": int(bootstrap_samples),
        "group_count": int(pair_count),
    }
    for metric in metric_names:
        ci_low, ci_high = percentile_interval(boot_values[metric])
        result[f"{metric}_point_estimate"] = point_estimates[metric]
        result[f"{metric}_ci_low"] = ci_low
        result[f"{metric}_ci_high"] = ci_high
    return result


def bootstrap_date_level(
    method_name: str,
    query_df: pd.DataFrame,
    bootstrap_samples: int,
    rng: np.random.Generator,
) -> dict[str, Any]:
    grouped_queries = {
        group_key: group.copy().reset_index(drop=True)
        for group_key, group in query_df.groupby(["query_slot", "target_slot", "archive_scope_label"], sort=True)
    }
    point_pair_rows: list[dict[str, float | str]] = []
    for group_key, group in grouped_queries.items():
        metrics = summarize_query_rows(group)
        point_pair_rows.append(
            {
                "group_key": str(group_key),
                "top1_hit_rate": metrics["top1_hit_rate"],
                "mrr": metrics["mrr"],
                "top5_hit_rate": metrics["top5_hit_rate"],
            }
        )
    point_pair_df = pd.DataFrame(point_pair_rows)
    point_estimates = {
        "top1_hit_rate": float(point_pair_df["top1_hit_rate"].mean()),
        "mrr": float(point_pair_df["mrr"].mean()),
        "top5_hit_rate": float(point_pair_df["top5_hit_rate"].mean()),
    }
    boot_values = {"top1_hit_rate": [], "mrr": [], "top5_hit_rate": []}
    for _ in range(bootstrap_samples):
        sampled_pair_rows: list[dict[str, float | str]] = []
        for group_key, group in grouped_queries.items():
            sampled_indices = rng.integers(0, len(group), size=len(group))
            sampled_group = group.iloc[sampled_indices].reset_index(drop=True)
            metrics = summarize_query_rows(sampled_group)
            sampled_pair_rows.append(
                {
                    "group_key": str(group_key),
                    "top1_hit_rate": metrics["top1_hit_rate"],
                    "mrr": metrics["mrr"],
                    "top5_hit_rate": metrics["top5_hit_rate"],
                }
            )
        sampled_pair_df = pd.DataFrame(sampled_pair_rows)
        boot_values["top1_hit_rate"].append(float(sampled_pair_df["top1_hit_rate"].mean()))
        boot_values["mrr"].append(float(sampled_pair_df["mrr"].mean()))
        boot_values["top5_hit_rate"].append(float(sampled_pair_df["top5_hit_rate"].mean()))

    result: dict[str, Any] = {
        "method": method_name,
        "bootstrap_unit": "date",
        "bootstrap_samples": int(bootstrap_samples),
        "group_count": int(len(grouped_queries)),
        "query_row_count": int(len(query_df)),
    }
    for metric in ["top1_hit_rate", "mrr", "top5_hit_rate"]:
        ci_low, ci_high = percentile_interval(boot_values[metric])
        result[f"{metric}_point_estimate"] = point_estimates[metric]
        result[f"{metric}_ci_low"] = ci_low
        result[f"{metric}_ci_high"] = ci_high
    return result


def bootstrap_rows(
    method_name: str,
    pair_df: pd.DataFrame,
    query_df: pd.DataFrame,
    bootstrap_samples: int,
    bootstrap_seed: int,
) -> list[dict[str, Any]]:
    pair_rng = np.random.default_rng(bootstrap_seed)
    date_rng = np.random.default_rng(bootstrap_seed + 1000)
    return [
        bootstrap_date_level(method_name, query_df, bootstrap_samples=bootstrap_samples, rng=date_rng),
        bootstrap_pair_level(method_name, pair_df, bootstrap_samples=bootstrap_samples, rng=pair_rng),
    ]


def write_markdown(output_path: Path, summary: dict[str, Any]) -> None:
    lines = [
        "# CB-Telemetry Time-Matched Retrieval",
        "",
        f"- feature_table: `{summary['feature_table']}`",
        f"- max_slot_gap: `{summary['max_slot_gap']}`",
        f"- min_dates_per_pair: `{summary['min_dates_per_pair']}`",
        f"- archive_scope: `{summary['archive_scope']}`",
        f"- bootstrap_samples: `{summary['bootstrap_samples']}`",
        f"- slot_pairs: `{summary['slot_pairs']}`",
        "",
        "## Aggregate",
        "",
        "| method | top1 | chance_top1 | mrr | top5 | mean_candidate_size |",
        "| --- | --- | --- | --- | --- | --- |",
    ]
    for row in summary["aggregate_rows"]:
        lines.append(
            f"| {row['method']} | {row['mean_top1_hit_rate']:.4f} | {row['mean_chance_top1']:.4f} | "
            f"{row['mean_mrr']:.4f} | {row['mean_top5_hit_rate']:.4f} | {row['mean_candidate_size']:.1f} |"
        )
    lines.extend(["", "## Bootstrap 95% CI", "", "| method | unit | top1 | mrr | top5 |", "| --- | --- | --- | --- | --- |"])
    for row in summary["bootstrap_rows"]:
        lines.append(
            f"| {row['method']} | {row['bootstrap_unit']} | "
            f"{row['top1_hit_rate_point_estimate']:.4f} [{row['top1_hit_rate_ci_low']:.4f}, {row['top1_hit_rate_ci_high']:.4f}] | "
            f"{row['mrr_point_estimate']:.4f} [{row['mrr_ci_low']:.4f}, {row['mrr_ci_high']:.4f}] | "
            f"{row['top5_hit_rate_point_estimate']:.4f} [{row['top5_hit_rate_ci_low']:.4f}, {row['top5_hit_rate_ci_high']:.4f}] |"
        )
    output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def main() -> None:
    args = parse_args()
    root = Path(args.root).expanduser().resolve()
    output_dir = resolve_path(root, args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    feature_table_path = resolve_path(root, args.feature_table)
    anchor_df = add_slot_metadata(pd.read_csv(feature_table_path, low_memory=False))
    anchor_df = anchor_df.sort_values(["date", "timestamp_dt", "filename"]).reset_index(drop=True)
    anchor_df["anchor_row_index"] = np.arange(len(anchor_df), dtype=np.int32)
    slot_pairs = build_slot_pairs(
        anchor_df,
        max_slot_gap=args.max_slot_gap,
        min_dates_per_pair=args.min_dates_per_pair,
        archive_scope=args.archive_scope,
    )

    representation_matrices: list[tuple[str, np.ndarray, str]] = []
    for method_name, raw_path in parse_representations(args.representation):
        representation_matrices.append((method_name, load_representation_matrix(root, raw_path, anchor_df), raw_path))

    if args.include_metadata_controls:
        representation_matrices.append(("metadata_basic", build_metadata_matrix(anchor_df, include_calendar=False), "generated"))
        representation_matrices.append(("metadata_calendar", build_metadata_matrix(anchor_df, include_calendar=True), "generated"))
        continuous_columns = feature_columns(anchor_df)
        continuous_matrix = anchor_df[continuous_columns].to_numpy(dtype=np.float32)
        rng = np.random.default_rng(args.random_seed)
        permuted = continuous_matrix[rng.permutation(len(anchor_df))]
        representation_matrices.append(("random_permuted_continuous", standardize(permuted), "generated"))

    aggregate_rows: list[dict[str, Any]] = []
    pair_rows: list[dict[str, Any]] = []
    query_rows: list[dict[str, Any]] = []
    all_bootstrap_rows: list[dict[str, Any]] = []
    detailed_results: dict[str, Any] = {}

    for method_name, matrix, source_path in representation_matrices:
        result = evaluate_representation(
            method_name=method_name,
            matrix=matrix,
            anchor_df=anchor_df,
            slot_pairs=slot_pairs,
            archive_scope=args.archive_scope,
            min_dates_per_pair=args.min_dates_per_pair,
        )
        aggregate_rows.append(result["aggregate"])
        pair_rows.extend(result["pairs"])
        query_rows.extend(result["queries"])
        method_pair_df = pd.DataFrame(result["pairs"])
        method_query_df = pd.DataFrame(result["queries"])
        method_bootstrap_rows = bootstrap_rows(
            method_name=method_name,
            pair_df=method_pair_df,
            query_df=method_query_df,
            bootstrap_samples=args.bootstrap_samples,
            bootstrap_seed=args.bootstrap_seed,
        )
        all_bootstrap_rows.extend(method_bootstrap_rows)
        detailed_results[method_name] = {
            "feature_table": source_path,
            "aggregate": result["aggregate"],
            "bootstrap": method_bootstrap_rows,
        }

    aggregate_df = pd.DataFrame(aggregate_rows).sort_values(
        ["mean_top1_hit_rate", "mean_mrr", "mean_top5_hit_rate"],
        ascending=False,
    ).reset_index(drop=True)
    pair_df = pd.DataFrame(pair_rows).sort_values(["method", "query_slot", "target_slot"]).reset_index(drop=True)
    query_df = pd.DataFrame(query_rows).sort_values(
        ["method", "query_slot", "target_slot", "archive_scope_label", "date"]
    ).reset_index(drop=True)
    bootstrap_df = pd.DataFrame(all_bootstrap_rows).sort_values(
        ["bootstrap_unit", "top1_hit_rate_point_estimate", "mrr_point_estimate", "top5_hit_rate_point_estimate"],
        ascending=[True, False, False, False],
    ).reset_index(drop=True)

    aggregate_df.to_csv(output_dir / "aggregate_summary.csv", index=False)
    pair_df.to_csv(output_dir / "pair_summary.csv", index=False)
    query_df.to_csv(output_dir / "query_summary.csv", index=False)
    bootstrap_df.to_csv(output_dir / "bootstrap_summary.csv", index=False)

    summary: dict[str, Any] = {
        "feature_table": release_path(root, feature_table_path),
        "output_dir": release_path(root, output_dir),
        "files": {
            "aggregate_summary_csv": release_path(root, output_dir / "aggregate_summary.csv"),
            "pair_summary_csv": release_path(root, output_dir / "pair_summary.csv"),
            "query_summary_csv": release_path(root, output_dir / "query_summary.csv"),
            "bootstrap_summary_csv": release_path(root, output_dir / "bootstrap_summary.csv"),
        },
        "max_slot_gap": int(args.max_slot_gap),
        "min_dates_per_pair": int(args.min_dates_per_pair),
        "archive_scope": args.archive_scope,
        "bootstrap_samples": int(args.bootstrap_samples),
        "bootstrap_seed": int(args.bootstrap_seed),
        "slot_pairs": [f"{src}->{dst}" for src, dst in slot_pairs],
        "rows": int(len(anchor_df)),
        "date_count": int(anchor_df["date"].nunique()),
        "slot_count_distribution": {
            str(key): int(value)
            for key, value in anchor_df.groupby("date")["dawn_slot_id"].max().value_counts().sort_index().to_dict().items()
        },
        "aggregate_rows": aggregate_df.to_dict(orient="records"),
        "bootstrap_rows": bootstrap_df.to_dict(orient="records"),
        "pair_rows": pair_df.to_dict(orient="records"),
        "detailed_results": detailed_results,
    }
    (output_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
    write_markdown(output_dir / "summary.md", summary)
    print(
        json.dumps(
            {
                "output_dir": summary["output_dir"],
                "archive_scope": summary["archive_scope"],
                "max_slot_gap": summary["max_slot_gap"],
                "aggregate_rows": summary["aggregate_rows"],
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()