File size: 12,692 Bytes
883e092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build an independent, coverage-qualified reference-arrival table.

The output is derived only from the annotation JSON, waveform-segment SQLite
index, and optional response JSON. It does not read automatic-picker outputs.
C0 requires an exact NSLC segment and a finite sample at the arrival time.
C1--C3 are configuration-dependent and
their window, gap, component, sample-rate, and response requirements are stored
in the output metadata table.
"""

from __future__ import annotations

import argparse
import json
import sqlite3
import sys
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable


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

from scripts.evaluate_picks import WaveformCoverageIndex, parse_utc_to_epoch_seconds


def norm_location(value: Any) -> str:
    text = "" if value is None else str(value).strip()
    return text if text else "--"


def release_path(path: Path | None) -> str | None:
    """Store release-relative paths when inputs are inside the repository."""
    if path is None:
        return None
    resolved = path.expanduser().resolve()
    try:
        return resolved.relative_to(ROOT.resolve()).as_posix()
    except ValueError:
        return str(resolved)


def iter_arrivals(annotation: dict[str, Any]) -> Iterable[dict[str, Any]]:
    for year in annotation["years"].values():
        for day_key, day in year["days"].items():
            period = "2019" if day_key.startswith("2019") else "2021"
            for event_id, event in day["events"].items():
                for station_id, station in event["stations"].items():
                    for pick in station.get("picks", []):
                        yield {
                            "period": period,
                            "event_id": str(event_id),
                            "station_id": str(pick.get("station_id") or station_id),
                            "phase": str(pick.get("phase", "")).upper(),
                            "status": str(pick.get("status", "unknown")),
                            "pick_time": str(pick.get("time")),
                            "pick_time_epoch": parse_utc_to_epoch_seconds(pick.get("time")),
                            "distance_km": pick.get("distance_km"),
                        }


class ResponseIndex:
    def __init__(self, path: Path | None) -> None:
        self.by_key: dict[tuple[str, str, str, str], list[tuple[float, float]]] = defaultdict(list)
        if path is None:
            return
        with path.open() as f:
            payload = json.load(f)
        for item in payload.get("responses", []):
            key = (
                str(item.get("network", "")),
                str(item.get("station", "")),
                norm_location(item.get("location")),
                str(item.get("channel", "")).upper(),
            )
            start = parse_utc_to_epoch_seconds(item.get("epoch_start"))
            end_value = item.get("epoch_end")
            end = (
                parse_utc_to_epoch_seconds(end_value)
                if end_value
                else float("inf")
            )
            self.by_key[key].append((start, end))

    def response_match_count(
        self,
        station_key: str,
        location: str,
        channel: str,
        time_epoch: float,
    ) -> int:
        try:
            network, station = station_key.split(".", 1)
        except ValueError:
            return 0
        key = (network, station, norm_location(location), str(channel).upper())
        return sum(
            1 for start, end in self.by_key.get(key, [])
            if start <= time_epoch < end
        )


def create_output(path: Path) -> sqlite3.Connection:
    if path.exists():
        path.unlink()
    path.parent.mkdir(parents=True, exist_ok=True)
    con = sqlite3.connect(path)
    con.executescript(
        """
        CREATE TABLE metadata (key TEXT PRIMARY KEY, value_json TEXT NOT NULL);
        CREATE TABLE reference_arrivals (
            arrival_id INTEGER PRIMARY KEY,
            period TEXT NOT NULL,
            event_id TEXT NOT NULL,
            station_id TEXT NOT NULL,
            phase TEXT NOT NULL,
            status TEXT NOT NULL,
            pick_time TEXT NOT NULL,
            pick_time_epoch REAL NOT NULL,
            distance_km REAL,
            c0_point_covered INTEGER NOT NULL,
            c1_window_covered INTEGER NOT NULL,
            c2_component_covered INTEGER NOT NULL,
            c3_processing_ready INTEGER NOT NULL,
            matched_location TEXT,
            channel_family TEXT,
            component_count INTEGER NOT NULL,
            channels_json TEXT NOT NULL,
            component_channels_json TEXT NOT NULL,
            component_gap_fractions_json TEXT NOT NULL,
            window_gap_fraction REAL NOT NULL,
            required_component_gap_fraction REAL NOT NULL,
            response_available INTEGER NOT NULL,
            sample_rate_ready INTEGER NOT NULL,
            manual_primary_reference INTEGER NOT NULL
        );
        CREATE INDEX idx_reference_station_phase_time
            ON reference_arrivals(station_id, phase, pick_time_epoch);
        CREATE INDEX idx_reference_period_status_coverage
            ON reference_arrivals(period, status, c0_point_covered);
        CREATE INDEX idx_reference_event ON reference_arrivals(event_id);
        """
    )
    return con


def build(args: argparse.Namespace) -> Counter:
    with args.annotation_json.open() as f:
        annotation = json.load(f)
    coverage = WaveformCoverageIndex(args.waveform_db, args.channel_families)
    responses = ResponseIndex(args.response_json)
    con = create_output(args.output)

    config = {
        "schema": "seismicx-cont-reference-arrivals-v1",
        "sources": {
            "annotation_json": release_path(args.annotation_json),
            "waveform_db": release_path(args.waveform_db),
            "hdf5_waveforms": "h5_file and dataset_path fields in waveform_db",
            "response_json": release_path(args.response_json),
        },
        "coverage": {
            "C0": "exact NSLC point coverage with finite-sample validation",
            "C1": "at least one observed component satisfies the finite-sample window gap threshold",
            "C2": "all declared observed components satisfy the finite-sample window gap threshold",
            "C3": (
                "C2 plus declared sample-rate requirements and, when requested, "
                "exactly one NSLC-and-epoch response match per required component"
            ),
            "channel_families": list(args.channel_families),
            "finite_sample_validation": True,
            "window_before_s": args.window_before_s,
            "window_after_s": args.window_after_s,
            "max_gap_fraction": args.max_gap_fraction,
            "required_components": list(args.required_components),
            "minimum_sample_rate_hz": args.minimum_sample_rate_hz,
            "require_response": args.require_response,
        },
        "reference_settings": {
            "primary": "manual labels satisfying the declared coverage level",
            "expanded": "manual plus operational automatic labels satisfying the declared coverage level",
        },
    }
    con.executemany(
        "INSERT INTO metadata(key, value_json) VALUES (?, ?)",
        [(key, json.dumps(value, sort_keys=True)) for key, value in config.items()],
    )

    sql = """
        INSERT INTO reference_arrivals (
            period, event_id, station_id, phase, status, pick_time,
            pick_time_epoch, distance_km, c0_point_covered, c1_window_covered,
            c2_component_covered, c3_processing_ready, matched_location,
            channel_family, component_count, channels_json,
            component_channels_json, component_gap_fractions_json,
            window_gap_fraction, required_component_gap_fraction,
            response_available, sample_rate_ready, manual_primary_reference
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    """
    counts: Counter = Counter()
    rows: list[tuple[Any, ...]] = []
    for arrival in iter_arrivals(annotation):
        details = coverage.coverage_window_details(
            arrival["station_id"],
            arrival["pick_time_epoch"],
            args.window_before_s,
            args.window_after_s,
            args.max_gap_fraction,
            args.required_components,
        )
        component_channels = details["component_channels"]
        required_channels = [
            component_channels[item]
            for item in args.required_components
            if item in component_channels
        ]
        response_available = bool(required_channels) and len(required_channels) == len(
            args.required_components
        ) and all(
            responses.response_match_count(
                str(details["station_key"]),
                str(details["matched_location"]),
                channel,
                arrival["pick_time_epoch"],
            ) == 1
            for channel in required_channels
        )
        sample_rates = details["component_sample_rates_hz"]
        sample_rate_ready = all(
            component in sample_rates
            and any(rate >= args.minimum_sample_rate_hz for rate in sample_rates[component])
            for component in args.required_components
        )
        c3 = bool(details["component_covered"] and sample_rate_ready)
        if args.require_response:
            c3 = c3 and response_available

        rows.append(
            (
                arrival["period"], arrival["event_id"], arrival["station_id"],
                arrival["phase"], arrival["status"], arrival["pick_time"],
                arrival["pick_time_epoch"], arrival["distance_km"],
                int(details["point_covered"]), int(details["window_covered"]),
                int(details["component_covered"]), int(c3),
                details["matched_location"], details["channel_family"],
                int(details["component_count"]), json.dumps(details["channels"]),
                json.dumps(component_channels, sort_keys=True),
                json.dumps(details["component_gap_fractions"], sort_keys=True),
                float(details["window_gap_fraction"]),
                float(details["required_component_gap_fraction"]),
                int(response_available), int(sample_rate_ready),
                int(arrival["status"] == "manual"),
            )
        )
        counts["arrivals"] += 1
        for level, field in (
            ("C0", "point_covered"),
            ("C1", "window_covered"),
            ("C2", "component_covered"),
        ):
            if details[field]:
                counts[level] += 1
        if c3:
            counts["C3"] += 1
        if len(rows) >= 5000:
            con.executemany(sql, rows)
            rows.clear()
    if rows:
        con.executemany(sql, rows)
    con.execute(
        "INSERT INTO metadata(key, value_json) VALUES (?, ?)",
        ("summary", json.dumps(dict(counts), sort_keys=True)),
    )
    con.commit()
    con.close()
    coverage.close()
    return counts


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--annotation-json",
        type=Path,
        default=ROOT / "data" / "label" / "annotations_for_continuous_hdf5.json",
    )
    parser.add_argument(
        "--waveform-db",
        type=Path,
        default=ROOT / "data" / "index" / "waveform_index.sqlite",
    )
    parser.add_argument(
        "--response-json",
        type=Path,
        default=ROOT / "data" / "response" / "instrument_responses.json",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=ROOT / "data" / "label" / "reference_arrivals.sqlite",
    )
    parser.add_argument("--channel-families", nargs="+", default=["HH", "BH", "EH", "HN"])
    parser.add_argument("--window-before-s", type=float, required=True)
    parser.add_argument("--window-after-s", type=float, required=True)
    parser.add_argument("--max-gap-fraction", type=float, default=0.0)
    parser.add_argument(
        "--required-components", nargs="+", default=["Z", "H1", "H2"]
    )
    parser.add_argument("--minimum-sample-rate-hz", type=float, default=0.0)
    parser.add_argument("--require-response", action="store_true")
    args = parser.parse_args()
    counts = build(args)
    print(json.dumps({"output": str(args.output), "counts": dict(counts)}, indent=2))


if __name__ == "__main__":
    main()