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