Download scripts/validate_leave_one_output_precision_proxy.py from cangyeone/SeismicX-Cont: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/datasets/cangyeone/SeismicX-Cont/resolve/main/scripts/validate_leave_one_output_precision_proxy.py
- Command line
-
hf download hf://datasets/cangyeone/SeismicX-Cont/scripts/validate_leave_one_output_precision_proxy.py
-
curl -L -o validate_leave_one_output_precision_proxy.py https://huggingface.co/datasets/cangyeone/SeismicX-Cont/resolve/main/scripts/validate_leave_one_output_precision_proxy.py
15.4 kB
| #!/usr/bin/env python3 | |
| """Evaluate the eligible cross-output precision proxy leave one output out. | |
| For each assessed output, its source picks are removed and the remaining picks | |
| are reclustered with the released strict-span rule. Assessed picks and external | |
| candidates are then assigned one-to-one within ``delta``. Eligibility is | |
| queried at the assessed-pick time. An optional station-day circular time-shift | |
| null is calculated for one declared output without changing its daily pick | |
| count. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import math | |
| import sqlite3 | |
| import sys | |
| import zlib | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| import numba | |
| import numpy as np | |
| import orjson | |
| import zstandard as zstd | |
| ROOT = Path(__file__).resolve().parents[1] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from scripts.build_all_model_phase_catalog import cluster_group | |
| DAY_US = 86_400_000_000 | |
| PERIODS = { | |
| "2019": (1_561_939_200_000_000, 1_562_544_000_000_000), | |
| "2021": (1_636_329_600_000_000, 1_636_934_400_000_000), | |
| } | |
| def assign_sorted_one_to_one( | |
| assessed: np.ndarray, | |
| candidates: np.ndarray, | |
| tolerance_us: int, | |
| ) -> np.ndarray: | |
| """Return candidate indices using deterministic earliest-feasible matching.""" | |
| assigned = np.full(len(assessed), -1, dtype=np.int64) | |
| i = 0 | |
| j = 0 | |
| while i < len(assessed) and j < len(candidates): | |
| if candidates[j] < assessed[i] - tolerance_us: | |
| j += 1 | |
| elif assessed[i] < candidates[j] - tolerance_us: | |
| i += 1 | |
| else: | |
| assigned[i] = j | |
| i += 1 | |
| j += 1 | |
| return assigned | |
| def period_for_time(time_us: int) -> str | None: | |
| for period, (left, right) in PERIODS.items(): | |
| if left <= time_us < right: | |
| return period | |
| return None | |
| def load_eligibility( | |
| path: Path, | |
| ) -> tuple[dict[tuple[str, str, int], tuple[np.ndarray, np.ndarray]], dict[int, str]]: | |
| con = sqlite3.connect(path) | |
| names = { | |
| int(output_id): str(output_name) | |
| for output_id, output_name in con.execute( | |
| "SELECT output_id, output_name FROM outputs ORDER BY output_id" | |
| ) | |
| } | |
| grouped: dict[tuple[str, str, int], list[tuple[int, int]]] = defaultdict(list) | |
| for station, output_id, left, right, phase_mask in con.execute( | |
| """ | |
| SELECT station_id, output_id, processed_start_us, processed_end_us, | |
| phase_mask | |
| FROM eligibility_intervals | |
| WHERE valid_input=1 | |
| ORDER BY station_id, output_id, processed_start_us, processed_end_us | |
| """ | |
| ): | |
| if int(phase_mask) & 1: | |
| grouped[(str(station), "P", int(output_id))].append((int(left), int(right))) | |
| if int(phase_mask) & 2: | |
| grouped[(str(station), "S", int(output_id))].append((int(left), int(right))) | |
| con.close() | |
| result = { | |
| key: ( | |
| np.asarray([left for left, _ in values], dtype=np.int64), | |
| np.asarray([right for _, right in values], dtype=np.int64), | |
| ) | |
| for key, values in grouped.items() | |
| } | |
| return result, names | |
| def eligibility_count( | |
| times: np.ndarray, | |
| station: str, | |
| phase: str, | |
| excluded_output: int, | |
| intervals: dict[tuple[str, str, int], tuple[np.ndarray, np.ndarray]], | |
| output_count: int, | |
| ) -> np.ndarray: | |
| counts = np.zeros(len(times), dtype=np.uint8) | |
| for output_id in range(output_count): | |
| if output_id == excluded_output: | |
| continue | |
| item = intervals.get((station, phase, output_id)) | |
| if item is None: | |
| continue | |
| starts, ends = item | |
| indices = np.searchsorted(starts, times, side="right") - 1 | |
| valid = indices >= 0 | |
| safe = np.maximum(indices, 0) | |
| valid &= ends[safe] >= times | |
| counts += valid.astype(np.uint8) | |
| return counts | |
| def shifted_station_day_times( | |
| times: np.ndarray, | |
| station: str, | |
| replicate: int, | |
| ) -> np.ndarray: | |
| shifted = np.empty_like(times) | |
| days = times // DAY_US | |
| for day in np.unique(days): | |
| mask = days == day | |
| seed = zlib.crc32(f"{station}:{int(day)}:{replicate}".encode("utf-8")) | |
| offset_s = 60 + seed % 541 | |
| day_start = int(day) * DAY_US | |
| shifted[mask] = day_start + ( | |
| (times[mask] - day_start + offset_s * 1_000_000) % DAY_US | |
| ) | |
| shifted.sort() | |
| return shifted | |
| def iter_station_phase_groups(path: Path) -> Iterable[tuple[str, str, np.ndarray, np.ndarray]]: | |
| current_key: tuple[str, str] | None = None | |
| times: list[int] = [] | |
| models: list[int] = [] | |
| with path.open("rb") as raw: | |
| with zstd.ZstdDecompressor().stream_reader(raw) as reader: | |
| buffer = b"" | |
| while True: | |
| chunk = reader.read(8 * 1024 * 1024) | |
| if not chunk: | |
| break | |
| buffer += chunk | |
| lines = buffer.split(b"\n") | |
| buffer = lines.pop() | |
| for line in lines: | |
| if not line: | |
| continue | |
| record = orjson.loads(line) | |
| key = (str(record["s"]), str(record["p"])) | |
| if current_key is not None and key != current_key: | |
| if len(times) > 1 and any(a > b for a, b in zip(times, times[1:])): | |
| order = np.argsort(np.asarray(times), kind="stable") | |
| times = [times[index] for index in order] | |
| models = [models[index] for index in order] | |
| yield ( | |
| current_key[0], current_key[1], | |
| np.asarray(times, dtype=np.int64), | |
| np.asarray(models, dtype=np.uint8), | |
| ) | |
| times = [] | |
| models = [] | |
| current_key = key | |
| base = int(record["t"]) | |
| for member in record["x"]: | |
| models.append(int(member[0])) | |
| times.append(base + int(member[2])) | |
| if buffer.strip(): | |
| record = orjson.loads(buffer) | |
| key = (str(record["s"]), str(record["p"])) | |
| if current_key is not None and key != current_key: | |
| if len(times) > 1 and any(a > b for a, b in zip(times, times[1:])): | |
| order = np.argsort(np.asarray(times), kind="stable") | |
| times = [times[index] for index in order] | |
| models = [models[index] for index in order] | |
| yield ( | |
| current_key[0], current_key[1], | |
| np.asarray(times, dtype=np.int64), | |
| np.asarray(models, dtype=np.uint8), | |
| ) | |
| times = [] | |
| models = [] | |
| current_key = key | |
| base = int(record["t"]) | |
| for member in record["x"]: | |
| models.append(int(member[0])) | |
| times.append(base + int(member[2])) | |
| if current_key is not None: | |
| if len(times) > 1 and any(a > b for a, b in zip(times, times[1:])): | |
| order = np.argsort(np.asarray(times), kind="stable") | |
| times = [times[index] for index in order] | |
| models = [models[index] for index in order] | |
| yield ( | |
| current_key[0], current_key[1], | |
| np.asarray(times, dtype=np.int64), | |
| np.asarray(models, dtype=np.uint8), | |
| ) | |
| def accumulate( | |
| counters: dict[tuple[Any, ...], list[int]], | |
| key_prefix: tuple[Any, ...], | |
| assessed: np.ndarray, | |
| external_times: np.ndarray, | |
| external_support: np.ndarray, | |
| eligible_m: np.ndarray, | |
| delta_us: int, | |
| q0: float, | |
| m0: int, | |
| ) -> None: | |
| assignments = assign_sorted_one_to_one(assessed, external_times, delta_us) | |
| for period in PERIODS: | |
| left, right = PERIODS[period] | |
| mask = (assessed >= left) & (assessed < right) | |
| if not np.any(mask): | |
| continue | |
| m = eligible_m[mask] | |
| assigned = assignments[mask] | |
| denominator = m >= m0 | |
| matched = assigned >= 0 | |
| k = np.zeros(len(assigned), dtype=np.uint8) | |
| k[matched] = external_support[assigned[matched]] | |
| corroborated = denominator & matched & (k / np.maximum(m, 1) >= q0) | |
| values = counters.setdefault((*key_prefix, period), [0, 0, 0]) | |
| values[0] += int(mask.sum()) | |
| values[1] += int(denominator.sum()) | |
| values[2] += int(corroborated.sum()) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--candidates", type=Path, | |
| default=ROOT / "data/label/all_model_phase_picks.jsonl.zst", | |
| ) | |
| parser.add_argument( | |
| "--eligibility", type=Path, | |
| default=ROOT / "data/label/output_eligibility.sqlite", | |
| ) | |
| parser.add_argument( | |
| "--output-tsv", type=Path, | |
| default=ROOT / "data/validation/leave_one_output_precision_proxy.tsv", | |
| ) | |
| parser.add_argument( | |
| "--output-json", type=Path, | |
| default=ROOT / "data/validation/leave_one_output_precision_proxy.json", | |
| ) | |
| parser.add_argument("--cluster-span-s", type=float, default=1.5) | |
| parser.add_argument("--delta-s", type=float, default=0.5) | |
| parser.add_argument("--q0", type=float, default=0.5) | |
| parser.add_argument("--m0", type=int, default=6) | |
| parser.add_argument("--null-output", default="seismicxm.01") | |
| parser.add_argument("--null-replicates", type=int, default=20) | |
| args = parser.parse_args() | |
| intervals, output_names = load_eligibility(args.eligibility) | |
| name_to_id = {name: output_id for output_id, name in output_names.items()} | |
| if args.null_output not in name_to_id: | |
| raise KeyError(f"null output is absent from registry: {args.null_output}") | |
| null_output = name_to_id[args.null_output] | |
| model_count = len(output_names) | |
| cluster_us = int(round(args.cluster_span_s * 1_000_000)) | |
| delta_us = int(round(args.delta_s * 1_000_000)) | |
| observed: dict[tuple[Any, ...], list[int]] = {} | |
| null: dict[tuple[Any, ...], list[int]] = {} | |
| source_pick_count = 0 | |
| for group_index, (station, phase, times, models) in enumerate( | |
| iter_station_phase_groups(args.candidates), 1 | |
| ): | |
| source_pick_count += len(times) | |
| for assessed_output in range(model_count): | |
| assessed_mask = models == assessed_output | |
| if not np.any(assessed_mask): | |
| continue | |
| assessed = times[assessed_mask] | |
| external_times_raw = times[~assessed_mask] | |
| external_models = models[~assessed_mask] | |
| _, _, candidate_times, _, candidate_support, _ = cluster_group( | |
| external_times_raw, external_models, cluster_us, model_count | |
| ) | |
| eligible_m = eligibility_count( | |
| assessed, station, phase, assessed_output, intervals, model_count | |
| ) | |
| accumulate( | |
| observed, (assessed_output, phase), assessed, candidate_times, | |
| candidate_support, eligible_m, delta_us, args.q0, args.m0, | |
| ) | |
| if assessed_output == null_output: | |
| for replicate in range(args.null_replicates): | |
| shifted = shifted_station_day_times(assessed, station, replicate) | |
| shifted_m = eligibility_count( | |
| shifted, station, phase, assessed_output, intervals, model_count | |
| ) | |
| accumulate( | |
| null, (replicate, phase), shifted, candidate_times, | |
| candidate_support, shifted_m, delta_us, args.q0, args.m0, | |
| ) | |
| if group_index % 100 == 0: | |
| print( | |
| f"[LOO] groups={group_index:,} source_picks={source_pick_count:,}", | |
| flush=True, | |
| ) | |
| rows = [] | |
| for (output_id, phase, period), (reported, eligible, corroborated) in sorted(observed.items()): | |
| rows.append( | |
| { | |
| "output_id": output_id, | |
| "output_name": output_names[output_id], | |
| "period": period, | |
| "phase": phase, | |
| "reported_pick_count": reported, | |
| "eligible_denominator": eligible, | |
| "corroborated_count": corroborated, | |
| "cross_output_precision_proxy": ( | |
| corroborated / eligible if eligible else None | |
| ), | |
| } | |
| ) | |
| null_rows = [] | |
| for phase in ("P", "S"): | |
| for period in PERIODS: | |
| fractions = [] | |
| denominators = [] | |
| for replicate in range(args.null_replicates): | |
| _, eligible, corroborated = null.get((replicate, phase, period), [0, 0, 0]) | |
| if eligible: | |
| fractions.append(corroborated / eligible) | |
| denominators.append(eligible) | |
| null_rows.append( | |
| { | |
| "output_id": null_output, | |
| "output_name": output_names[null_output], | |
| "period": period, | |
| "phase": phase, | |
| "replicates": len(fractions), | |
| "mean_eligible_denominator": float(np.mean(denominators)) if denominators else None, | |
| "mean_null_fraction": float(np.mean(fractions)) if fractions else None, | |
| "null_fraction_p05": float(np.quantile(fractions, 0.05)) if fractions else None, | |
| "null_fraction_p95": float(np.quantile(fractions, 0.95)) if fractions else None, | |
| } | |
| ) | |
| payload = { | |
| "schema": "seismicx-cont-leave-one-output-precision-proxy-v1", | |
| "candidate_file": args.candidates.relative_to(ROOT).as_posix(), | |
| "eligibility_file": args.eligibility.relative_to(ROOT).as_posix(), | |
| "source_pick_count": source_pick_count, | |
| "parameters": { | |
| "cluster_strict_span_s": args.cluster_span_s, | |
| "assignment_tolerance_delta_s": args.delta_s, | |
| "normalized_support_threshold_q0": args.q0, | |
| "minimum_external_eligibility_m0": args.m0, | |
| "assignment": "deterministic earliest-feasible one-to-one assignment on sorted times", | |
| "eligibility_query_time": "assessed-pick time", | |
| }, | |
| "rows": rows, | |
| "station_day_time_shift_null": { | |
| "output": args.null_output, | |
| "replicates": args.null_replicates, | |
| "offset_s": "deterministic uniform integer in [60, 600] per station-day-replicate", | |
| "daily_pick_count_preserved": True, | |
| "rows": null_rows, | |
| }, | |
| } | |
| args.output_json.parent.mkdir(parents=True, exist_ok=True) | |
| args.output_json.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") | |
| with args.output_tsv.open("w", newline="") as stream: | |
| writer = csv.DictWriter(stream, fieldnames=list(rows[0]), delimiter="\t") | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| print(json.dumps({"rows": len(rows), "source_pick_count": source_pick_count}, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |