File size: 22,125 Bytes
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5f045
90a380e
 
 
 
 
 
 
 
 
 
 
b70b2cc
 
 
2c5f045
b70b2cc
2c5f045
90a380e
 
 
 
 
 
 
 
 
14de170
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5f045
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5f045
 
 
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b70b2cc
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b70b2cc
90a380e
 
 
b70b2cc
 
 
 
 
 
 
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b70b2cc
90a380e
 
b70b2cc
 
 
 
 
 
 
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b70b2cc
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b70b2cc
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c5f045
 
 
90a380e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Plot scientific characterization statistics for SeismicX-Cont monitoring regimes.

The script derives all quantities from the released annotation JSON and SQLite
waveform index. Distance, magnitude, picks-per-event, and inter-event-time
statistics use catalog/annotation fields; overlap fractions and the plotted
arrival distributions use coverage-qualified P/S labels, where coverage is
checked against the SQLite waveform index.
"""

from __future__ import annotations

import argparse
import json
import math
import sys
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Sequence

import matplotlib.pyplot as plt
import numpy as np


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

from evaluate_picks import WaveformCoverageIndex

DEFAULT_LABEL_JSON = ROOT / "data" / "label" / "annotations_for_continuous_hdf5.json"
DEFAULT_MINI_LABEL_JSON = ROOT / "data" / "label" / "annotations_mini_two_hours.json"
DEFAULT_WAVEFORM_DB = ROOT / "data" / "index" / "waveform_index.sqlite"
DEFAULT_OUT = ROOT / "figures" / "monitoring_regime_characterization.pdf"
DEFAULT_SUMMARY_JSON = ROOT / "essd_scripts" / "outputs" / "monitoring_regime_characterization_summary.json"
DEFAULT_SUMMARY_TXT = ROOT / "essd_scripts" / "outputs" / "monitoring_regime_characterization_summary.txt"

PERIOD_LABELS = {
    "2019": "2019 Ridgecrest week",
    "2021": "2021 lower-rate monitoring week",
}
PERIOD_COLORS = {
    "2019": "#9E3D22",
    "2021": "#2C6AA6",
}
PHASE_STYLES = {
    "P": "-",
    "S": "--",
}
OVERLAP_TOLERANCES_S = (10, 15, 30)


@dataclass
class PickRecord:
    period: str
    event_id: str
    event_time_epoch: float
    magnitude: float | None
    station_id: str
    phase: str
    status: str
    pick_time_epoch: float
    distance_km: float
    covered: bool


def parse_epoch(value: str) -> float:
    text = str(value).strip()
    if text.endswith("Z"):
        text = text[:-1]
    return datetime.fromisoformat(text).replace(tzinfo=timezone.utc).timestamp()


def resolve_input_path(path: Path, alternatives: Sequence[Path]) -> Path:
    """Prefer the full-release file name, but allow the mini package layout."""
    if path.exists():
        return path
    for candidate in alternatives:
        if candidate.exists():
            return candidate
    return path


def period_from_day(day_key: str) -> str:
    if day_key.startswith("2019"):
        return "2019"
    if day_key.startswith("2021"):
        return "2021"
    return "other"


def load_annotation(path: Path) -> dict[str, Any]:
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def iter_events(annotation: dict[str, Any]):
    for year in annotation["years"].values():
        for day_key, day in year["days"].items():
            period = period_from_day(day_key)
            for event_id, event in day["events"].items():
                yield period, day_key, event_id, event


def collect_records(annotation: dict[str, Any], coverage: WaveformCoverageIndex):
    picks: list[PickRecord] = []
    event_times: dict[str, list[float]] = defaultdict(list)
    events_by_period: dict[str, set[str]] = defaultdict(set)
    magnitudes_by_event: dict[str, float | None] = {}

    for period, _day_key, event_id, event in iter_events(annotation):
        if period not in PERIOD_LABELS:
            continue
        ev = event.get("event", {})
        event_time = parse_epoch(ev.get("event_time"))
        magnitude = ev.get("magnitude")
        magnitude_value = float(magnitude) if magnitude is not None else None
        event_times[period].append(event_time)
        events_by_period[period].add(event_id)
        magnitudes_by_event[event_id] = magnitude_value

        for station_id, station in event.get("stations", {}).items():
            for pick in station.get("picks", []):
                phase = str(pick.get("phase", "")).upper()
                if phase not in {"P", "S"}:
                    continue
                distance = pick.get("distance_km")
                pick_time = pick.get("time")
                if distance is None or pick_time is None:
                    continue
                pick_epoch = parse_epoch(pick_time)
                picks.append(
                    PickRecord(
                        period=period,
                        event_id=event_id,
                        event_time_epoch=event_time,
                        magnitude=magnitude_value,
                        station_id=str(pick.get("station_id") or station_id),
                        phase=phase,
                        status=str(pick.get("status", "")),
                        pick_time_epoch=pick_epoch,
                        distance_km=float(distance),
                        covered=coverage.has_coverage(
                            str(pick.get("station_id") or station_id), pick_epoch
                        ),
                    )
                )

    return picks, event_times, events_by_period, magnitudes_by_event


def percentile(values: list[float] | np.ndarray, q: float) -> float | None:
    arr = np.asarray(values, dtype=float)
    arr = arr[np.isfinite(arr)]
    if arr.size == 0:
        return None
    return float(np.percentile(arr, q))


def distribution_summary(values: list[float] | np.ndarray) -> dict[str, float | int | None]:
    arr = np.asarray(values, dtype=float)
    arr = arr[np.isfinite(arr)]
    if arr.size == 0:
        return {"n": 0, "p10": None, "median": None, "p90": None, "max": None}
    return {
        "n": int(arr.size),
        "p10": float(np.percentile(arr, 10)),
        "median": float(np.percentile(arr, 50)),
        "p90": float(np.percentile(arr, 90)),
        "max": float(np.max(arr)),
    }


def picks_per_event(picks: list[PickRecord], events_by_period: dict[str, set[str]]):
    counts: dict[str, Counter] = {period: Counter() for period in PERIOD_LABELS}
    for pick in picks:
        if pick.covered:
            counts[pick.period][pick.event_id] += 1
    out: dict[str, list[int]] = {}
    for period, event_ids in events_by_period.items():
        out[period] = [int(counts[period].get(event_id, 0)) for event_id in sorted(event_ids)]
    return out


def inter_event_times(event_times: dict[str, list[float]]) -> dict[str, list[float]]:
    out = {}
    for period, times in event_times.items():
        times = sorted(times)
        out[period] = [b - a for a, b in zip(times, times[1:]) if b > a]
    return out


def overlap_stats(picks: list[PickRecord]) -> dict[str, Any]:
    grouped: dict[tuple[str, str, str], list[float]] = defaultdict(list)
    for pick in picks:
        if pick.covered:
            grouped[(pick.period, pick.station_id, pick.phase)].append(pick.pick_time_epoch)

    totals: dict[str, Counter] = defaultdict(Counter)
    by_phase: dict[str, dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))

    for (period, _station_id, phase), times in grouped.items():
        times = sorted(times)
        n = len(times)
        for i, value in enumerate(times):
            prev_dt = value - times[i - 1] if i > 0 else math.inf
            next_dt = times[i + 1] - value if i < n - 1 else math.inf
            nearest = min(prev_dt, next_dt)
            totals[period]["n"] += 1
            by_phase[period][phase]["n"] += 1
            for tol in OVERLAP_TOLERANCES_S:
                if nearest <= tol:
                    totals[period][f"within_{tol}s"] += 1
                    by_phase[period][phase][f"within_{tol}s"] += 1

    result: dict[str, Any] = {}
    for period in PERIOD_LABELS:
        n = totals[period]["n"]
        result[period] = {
            "all": {
                "n": int(n),
                **{
                    f"within_{tol}s_fraction": (float(totals[period][f"within_{tol}s"]) / n if n else None)
                    for tol in OVERLAP_TOLERANCES_S
                },
            },
            "by_phase": {},
        }
        for phase in ("P", "S"):
            phase_n = by_phase[period][phase]["n"]
            result[period]["by_phase"][phase] = {
                "n": int(phase_n),
                **{
                    f"within_{tol}s_fraction": (
                        float(by_phase[period][phase][f"within_{tol}s"]) / phase_n
                        if phase_n else None
                    )
                    for tol in OVERLAP_TOLERANCES_S
                },
            }
    return result


def build_summary(
    picks: list[PickRecord],
    event_times: dict[str, list[float]],
    events_by_period: dict[str, set[str]],
) -> dict[str, Any]:
    covered = [p for p in picks if p.covered]
    picks_event = picks_per_event(picks, events_by_period)
    inter_times = inter_event_times(event_times)

    distance_by_period_phase = {}
    for period in PERIOD_LABELS:
        distance_by_period_phase[period] = {}
        for phase in ("P", "S"):
            distance_by_period_phase[period][phase] = distribution_summary(
                [p.distance_km for p in covered if p.period == period and p.phase == phase]
            )

    magnitude_distance = {}
    for period in PERIOD_LABELS:
        period_picks = [p for p in covered if p.period == period and p.magnitude is not None]
        small = [p.distance_km for p in period_picks if p.magnitude is not None and p.magnitude < 2.0]
        moderate = [p.distance_km for p in period_picks if p.magnitude is not None and p.magnitude >= 3.0]
        magnitude_distance[period] = {
            "arrival_points": len(period_picks),
            "magnitude_min": percentile([p.magnitude for p in period_picks if p.magnitude is not None], 0),
            "magnitude_median": percentile([p.magnitude for p in period_picks if p.magnitude is not None], 50),
            "magnitude_max": percentile([p.magnitude for p in period_picks if p.magnitude is not None], 100),
            "distance_p90_for_m_lt_2": percentile(small, 90),
            "distance_p90_for_m_ge_3": percentile(moderate, 90),
        }

    status_counts = defaultdict(Counter)
    phase_counts = defaultdict(Counter)
    for p in covered:
        status_counts[p.period][p.status] += 1
        phase_counts[p.period][p.phase] += 1

    return {
        "source_definition": {
            "distance_and_overlap_labels": "coverage-qualified P/S labels from annotations_for_continuous_hdf5.json with station-time coverage checked in waveform_index.sqlite",
            "inter_event_times": "all cataloged events in the annotation JSON, separated by monitoring period",
            "picks_per_event": "coverage-qualified P/S labels counted per cataloged event; events with zero covered arrivals are retained",
        },
        "events": {period: len(events_by_period.get(period, set())) for period in PERIOD_LABELS},
        "coverage_qualified_arrivals": {
            period: {
                "total": int(sum(phase_counts[period].values())),
                "by_phase": dict(phase_counts[period]),
                "by_status": dict(status_counts[period]),
            }
            for period in PERIOD_LABELS
        },
        "distance_km": distance_by_period_phase,
        "magnitude_distance_sampling": magnitude_distance,
        "picks_per_event": {
            period: distribution_summary(values)
            for period, values in picks_event.items()
        },
        "inter_event_time_s": {
            period: {
                **distribution_summary(values),
                "fraction_lt_60s": float(np.mean(np.asarray(values) < 60.0)) if values else None,
                "fraction_lt_300s": float(np.mean(np.asarray(values) < 300.0)) if values else None,
            }
            for period, values in inter_times.items()
        },
        "station_phase_overlap": overlap_stats(picks),
    }


def format_value(value: float | int | None, digits: int = 1) -> str:
    if value is None:
        return "NA"
    if isinstance(value, int):
        return f"{value:,}"
    return f"{value:.{digits}f}"


def format_percent(fraction: float | None) -> str:
    if fraction is None:
        return "NA"
    return f"{100.0 * fraction:.1f}%"


def write_summary_text(summary: dict[str, Any], path: Path) -> None:
    lines = ["Monitoring-regime characterization summary", ""]
    for period, label in PERIOD_LABELS.items():
        lines.append(label)
        lines.append(f"  events: {summary['events'][period]:,}")
        cov = summary["coverage_qualified_arrivals"][period]
        lines.append(
            f"  coverage-qualified arrivals: {cov['total']:,} "
            f"(P={cov['by_phase'].get('P', 0):,}, S={cov['by_phase'].get('S', 0):,})"
        )
        for phase in ("P", "S"):
            dist = summary["distance_km"][period][phase]
            lines.append(
                f"  {phase} distance km: n={dist['n']:,}, "
                f"median={format_value(dist['median'])}, p90={format_value(dist['p90'])}"
            )
        ppe = summary["picks_per_event"][period]
        iet = summary["inter_event_time_s"][period]
        ov = summary["station_phase_overlap"][period]["all"]
        lines.append(
            f"  picks/event: median={format_value(ppe['median'])}, "
            f"p90={format_value(ppe['p90'])}, max={format_value(ppe['max'], 0)}"
        )
        lines.append(
            f"  inter-event time s: median={format_value(iet['median'])}, "
            f"p10={format_value(iet['p10'])}, "
            f"lt60={format_percent(iet['fraction_lt_60s'])}, "
            f"lt300={format_percent(iet['fraction_lt_300s'])}"
        )
        lines.append(
            "  station-phase overlap: "
            + ", ".join(
                f"within {tol}s={format_percent(ov[f'within_{tol}s_fraction'])}"
                for tol in OVERLAP_TOLERANCES_S
            )
        )
        lines.append("")
    path.write_text("\n".join(lines), encoding="utf-8")


def positive_values(values: list[int] | list[float]) -> np.ndarray:
    arr = np.asarray(values, dtype=float)
    return arr[np.isfinite(arr) & (arr > 0)]


def plot_figure(
    picks: list[PickRecord],
    event_times: dict[str, list[float]],
    events_by_period: dict[str, set[str]],
    summary: dict[str, Any],
    out: Path,
    png_out: Path | None = None,
) -> None:
    plt.rcParams.update(
        {
            "font.family": "DejaVu Sans",
            "font.size": 8,
            "axes.labelsize": 8,
            "axes.titlesize": 9,
            "legend.fontsize": 7,
            "xtick.labelsize": 7,
            "ytick.labelsize": 7,
            "pdf.fonttype": 42,
            "ps.fonttype": 42,
        }
    )
    fig = plt.figure(figsize=(7.4, 5.4), constrained_layout=True)
    gs = fig.add_gridspec(2, 3, width_ratios=[1.0, 1.15, 1.0])
    ax_a = fig.add_subplot(gs[0, 0])
    ax_b = fig.add_subplot(gs[0, 1:])
    ax_c = fig.add_subplot(gs[1, 0])
    ax_d = fig.add_subplot(gs[1, 1])
    ax_e = fig.add_subplot(gs[1, 2])

    covered = [p for p in picks if p.covered]
    distances_all = np.asarray([p.distance_km for p in covered], dtype=float)
    x_max = max(100.0, float(np.nanpercentile(distances_all, 99.2)))
    bins_dist = np.linspace(0.0, x_max, 50)
    for period in PERIOD_LABELS:
        for phase in ("P", "S"):
            values = np.asarray(
                [p.distance_km for p in covered if p.period == period and p.phase == phase],
                dtype=float,
            )
            values = values[np.isfinite(values) & (values <= x_max)]
            if values.size:
                ax_a.hist(
                    values,
                    bins=bins_dist,
                    density=True,
                    histtype="step",
                    linewidth=1.35,
                    color=PERIOD_COLORS[period],
                    linestyle=PHASE_STYLES[phase],
                    label=f"{period} {phase}",
                )
    ax_a.set_title("(a) Arrival distance")
    ax_a.set_xlabel("Event-station distance (km)")
    ax_a.set_ylabel("Density")
    ax_a.set_xlim(0, x_max)
    ax_a.legend(frameon=False, ncol=1, loc="upper right")

    rng = np.random.default_rng(20260531)
    for period in PERIOD_LABELS:
        period_points = [
            p for p in covered
            if p.period == period and p.magnitude is not None and p.distance_km > 0
        ]
        if len(period_points) > 60000:
            idx = rng.choice(len(period_points), size=60000, replace=False)
            period_points = [period_points[i] for i in idx]
        ax_b.scatter(
            [p.distance_km for p in period_points],
            [p.magnitude for p in period_points],
            s=4,
            alpha=0.18 if period == "2019" else 0.35,
            color=PERIOD_COLORS[period],
            edgecolors="none",
            rasterized=True,
            label=period,
        )
    ax_b.set_xscale("log")
    ax_b.set_title("(b) Magnitude-distance sampling")
    ax_b.set_xlabel("Event-station distance (km, log scale)")
    ax_b.set_ylabel("Event magnitude")
    ax_b.grid(True, which="major", color="#d9d9d9", linewidth=0.5)
    ax_b.legend(
        frameon=True,
        facecolor="white",
        edgecolor="none",
        framealpha=0.88,
        loc="upper left",
    )

    ppe = picks_per_event(picks, events_by_period)
    max_ppe = max(max(values) for values in ppe.values() if values)
    bins_ppe = np.unique(np.logspace(0, math.log10(max(2, max_ppe)), 32).astype(int))
    for period in PERIOD_LABELS:
        values = positive_values(ppe.get(period, []))
        ax_c.hist(
            values,
            bins=bins_ppe,
            histtype="stepfilled",
            alpha=0.22,
            color=PERIOD_COLORS[period],
        )
        ax_c.hist(
            values,
            bins=bins_ppe,
            histtype="step",
            linewidth=1.2,
            color=PERIOD_COLORS[period],
            label=period,
        )
    ax_c.set_xscale("log")
    ax_c.set_yscale("log")
    ax_c.set_title("(c) Arrivals per event")
    ax_c.set_xlabel("Coverage-qualified P/S arrivals")
    ax_c.set_ylabel("Events")
    ax_c.legend(
        frameon=True,
        facecolor="white",
        edgecolor="none",
        framealpha=0.88,
        loc="upper left",
    )

    iet = inter_event_times(event_times)
    all_dt_min = positive_values([dt / 60.0 for values in iet.values() for dt in values])
    bins_dt = np.logspace(
        math.log10(max(1e-2, np.nanmin(all_dt_min))),
        math.log10(max(1.0, np.nanmax(all_dt_min))),
        36,
    )
    for period in PERIOD_LABELS:
        values = positive_values([dt / 60.0 for dt in iet.get(period, [])])
        ax_d.hist(
            values,
            bins=bins_dt,
            histtype="stepfilled",
            alpha=0.22,
            color=PERIOD_COLORS[period],
        )
        ax_d.hist(
            values,
            bins=bins_dt,
            histtype="step",
            linewidth=1.2,
            color=PERIOD_COLORS[period],
            label=period,
        )
    ax_d.set_xscale("log")
    ax_d.set_yscale("log")
    ax_d.set_title("(d) Inter-event time")
    ax_d.set_xlabel("Time to next event (min, log scale)")
    ax_d.set_ylabel("Event pairs")

    x = np.arange(len(OVERLAP_TOLERANCES_S))
    width = 0.36
    for offset, period in zip((-width / 2, width / 2), PERIOD_LABELS):
        values = [
            100.0 * (summary["station_phase_overlap"][period]["all"][f"within_{tol}s_fraction"] or 0.0)
            for tol in OVERLAP_TOLERANCES_S
        ]
        ax_e.bar(
            x + offset,
            values,
            width=width,
            color=PERIOD_COLORS[period],
            label=period,
            alpha=0.86,
        )
    ax_e.set_xticks(x, [f"+/-{tol} s" for tol in OVERLAP_TOLERANCES_S])
    ax_e.set_ylim(0, 100)
    ax_e.set_title("(e) Station-phase overlap")
    ax_e.set_xlabel("Time window")
    ax_e.set_ylabel("Arrivals with neighbor (%)")
    ax_e.legend(frameon=False, loc="upper left")

    for ax in (ax_a, ax_c, ax_d, ax_e):
        ax.grid(True, axis="y", color="#e1e1e1", linewidth=0.45)
    for ax in (ax_a, ax_b, ax_c, ax_d, ax_e):
        for spine in ("top", "right"):
            ax.spines[spine].set_visible(False)

    out.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(out, bbox_inches="tight")
    if png_out is not None:
        fig.savefig(png_out, dpi=240, bbox_inches="tight")
    plt.close(fig)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--label-json", type=Path, default=DEFAULT_LABEL_JSON)
    parser.add_argument("--waveform-db", type=Path, default=DEFAULT_WAVEFORM_DB)
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    parser.add_argument("--png-out", type=Path, default=None)
    parser.add_argument("--summary-json", type=Path, default=DEFAULT_SUMMARY_JSON)
    parser.add_argument("--summary-txt", type=Path, default=DEFAULT_SUMMARY_TXT)
    args = parser.parse_args()

    args.label_json = resolve_input_path(args.label_json, [DEFAULT_MINI_LABEL_JSON])
    annotation = load_annotation(args.label_json)
    coverage = WaveformCoverageIndex(
        args.waveform_db, channel_families=("HH", "BH", "EH", "HN")
    )
    picks, event_times, events_by_period, _magnitudes = collect_records(annotation, coverage)
    summary = build_summary(picks, event_times, events_by_period)

    args.summary_json.parent.mkdir(parents=True, exist_ok=True)
    args.summary_json.write_text(json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8")
    write_summary_text(summary, args.summary_txt)

    png_out = args.png_out
    if png_out is None and args.out.suffix.lower() == ".pdf":
        png_out = args.out.with_suffix(".png")
    plot_figure(picks, event_times, events_by_period, summary, args.out, png_out=png_out)
    print(f"[OK] wrote {args.out}")
    print(f"[OK] wrote {args.summary_json}")
    print(f"[OK] wrote {args.summary_txt}")


if __name__ == "__main__":
    main()