File size: 9,275 Bytes
b4a9114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Calculate precision proxy 1 and its reference-window sensitivity.

The script extracts one declared output from the compact multi-output catalogue,
intersects merged manual-reference windows with that output's eligibility
domain, and performs deterministic one-to-one station-phase-time matching.
"""

from __future__ import annotations

import argparse
import csv
import json
import sqlite3
import sys
from collections import defaultdict
from pathlib import Path
from typing import Iterable

import numpy as np

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from scripts.validate_leave_one_output_precision_proxy import (
    PERIODS,
    assign_sorted_one_to_one,
    iter_station_phase_groups,
    load_eligibility,
)


def load_manual_references(
    path: Path,
) -> dict[tuple[str, str, str], np.ndarray]:
    con = sqlite3.connect(path)
    grouped: dict[tuple[str, str, str], list[int]] = defaultdict(list)
    for period, station, phase, epoch in con.execute(
        """
        SELECT period, station_id, phase, pick_time_epoch
        FROM evaluation_references
        WHERE has_manual_reference=1 AND c0_point_covered=1
        ORDER BY period, station_id, phase, pick_time_epoch
        """
    ):
        grouped[(str(period), str(station), str(phase))].append(
            int(round(float(epoch) * 1_000_000))
        )
    con.close()
    return {key: np.asarray(values, dtype=np.int64) for key, values in grouped.items()}


def merge_windows(times: np.ndarray, half_width_us: int) -> list[tuple[int, int]]:
    merged: list[tuple[int, int]] = []
    for value in times:
        left = int(value) - half_width_us
        right = int(value) + half_width_us
        if merged and left <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], right))
        else:
            merged.append((left, right))
    return merged


def intersect_windows(
    left: list[tuple[int, int]],
    right_starts: np.ndarray,
    right_ends: np.ndarray,
) -> list[tuple[int, int]]:
    result: list[tuple[int, int]] = []
    i = 0
    j = 0
    while i < len(left) and j < len(right_starts):
        start = max(left[i][0], int(right_starts[j]))
        end = min(left[i][1], int(right_ends[j]))
        if start <= end:
            if result and start <= result[-1][1]:
                result[-1] = (result[-1][0], max(result[-1][1], end))
            else:
                result.append((start, end))
        if left[i][1] <= right_ends[j]:
            i += 1
        else:
            j += 1
    return result


def select_in_windows(times: np.ndarray, windows: list[tuple[int, int]]) -> np.ndarray:
    selected: list[np.ndarray] = []
    for left, right in windows:
        begin = int(np.searchsorted(times, left, side="left"))
        end = int(np.searchsorted(times, right, side="right"))
        if end > begin:
            selected.append(times[begin:end])
    return np.concatenate(selected) if selected else np.empty(0, dtype=np.int64)


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(
        "--references", type=Path,
        default=ROOT / "data/label/reference_arrivals.sqlite",
    )
    parser.add_argument(
        "--eligibility", type=Path,
        default=ROOT / "data/label/output_eligibility.sqlite",
    )
    parser.add_argument("--output-name", default="seismicxm.01")
    parser.add_argument("--epsilon-s", type=float, default=0.5)
    parser.add_argument("--window-s", type=float, action="append")
    parser.add_argument(
        "--output-tsv", type=Path,
        default=ROOT / "data/validation/reference_window_precision_proxy_sensitivity.tsv",
    )
    parser.add_argument(
        "--output-json", type=Path,
        default=ROOT / "data/validation/reference_window_precision_proxy_sensitivity.json",
    )
    args = parser.parse_args()
    windows_s = args.window_s or [1.0, 5.0, 10.0, 30.0]
    if any(value < args.epsilon_s for value in windows_s):
        raise ValueError("every T must be at least epsilon")

    references = load_manual_references(args.references)
    reference_totals: dict[tuple[str, str], int] = defaultdict(int)
    for (period, _, phase), values in references.items():
        reference_totals[(period, phase)] += len(values)
    eligibility, output_names = load_eligibility(args.eligibility)
    name_to_id = {name: output_id for output_id, name in output_names.items()}
    if args.output_name not in name_to_id:
        raise KeyError(f"output is absent from registry: {args.output_name}")
    output_id = name_to_id[args.output_name]
    epsilon_us = int(round(args.epsilon_s * 1_000_000))
    counters: dict[tuple[str, str, float], list[int]] = defaultdict(
        lambda: [0, 0, 0, 0, 0]
    )

    def process_group(station: str, phase: str, assessed: np.ndarray) -> None:
        domain = eligibility.get((station, phase, output_id))
        if domain is None:
            return
        domain_starts, domain_ends = domain
        for period in PERIODS:
            refs = references.get((period, station, phase))
            if refs is None or not len(refs):
                continue
            ref_indices = np.searchsorted(domain_starts, refs, side="right") - 1
            valid = ref_indices >= 0
            valid &= domain_ends[np.maximum(ref_indices, 0)] >= refs
            eligible_refs = refs[valid]
            if not len(eligible_refs):
                continue
            for window_s in windows_s:
                raw_windows = merge_windows(
                    eligible_refs, int(round(window_s * 1_000_000))
                )
                effective = intersect_windows(raw_windows, domain_starts, domain_ends)
                selected_picks = select_in_windows(assessed, effective)
                assignments = assign_sorted_one_to_one(
                    eligible_refs, selected_picks, epsilon_us
                )
                matched = int(np.sum(assignments >= 0))
                values = counters[(period, phase, float(window_s))]
                values[0] += len(refs)
                values[1] += len(eligible_refs)
                values[2] += len(effective)
                values[3] += int(sum(right - left for left, right in effective))
                values[4] += len(selected_picks)
                if len(values) == 5:
                    values.append(0)
                values[5] += matched

    seen_groups: set[tuple[str, str]] = set()
    for group_index, (station, phase, times, models) in enumerate(
        iter_station_phase_groups(args.candidates), 1
    ):
        seen_groups.add((station, phase))
        assessed = times[models == output_id]
        process_group(station, phase, assessed)
        if group_index % 100 == 0:
            print(f"[PROXY1] groups={group_index:,}", flush=True)

    for _, station, phase in references:
        if (station, phase) not in seen_groups:
            process_group(station, phase, np.empty(0, dtype=np.int64))
            seen_groups.add((station, phase))

    rows = []
    for (period, phase, window_s), values in sorted(counters.items()):
        _, eligible_refs, n_windows, duration_us, picks, matched = values
        rows.append(
            {
                "output_id": output_id,
                "output_name": args.output_name,
                "period": period,
                "phase": phase,
                "window_half_width_T_s": window_s,
                "matching_tolerance_epsilon_s": args.epsilon_s,
                "c0_manual_reference_count": reference_totals[(period, phase)],
                "workflow_eligible_reference_count": eligible_refs,
                "effective_window_count": n_windows,
                "effective_window_duration_s": duration_us / 1_000_000,
                "reported_pick_count_in_effective_windows": picks,
                "matched_pick_count": matched,
                "catalogue_conditioned_precision_proxy": matched / picks if picks else None,
            }
        )
    payload = {
        "schema": "seismicx-cont-reference-window-precision-proxy-v1",
        "candidate_file": args.candidates.relative_to(ROOT).as_posix(),
        "reference_file": args.references.relative_to(ROOT).as_posix(),
        "eligibility_file": args.eligibility.relative_to(ROOT).as_posix(),
        "reference_definition": (
            "canonical C0-covered station-location-phase-time references with "
            "at least one manual source reading"
        ),
        "assignment": "deterministic earliest-feasible one-to-one station-phase-time matching",
        "rows": 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), "output": args.output_name}, indent=2))


if __name__ == "__main__":
    main()