SeismicX-Cont / essd_scripts /plot_monitoring_regime_characterization.py
cangyeone's picture
Upload essd_scripts/plot_monitoring_regime_characterization.py
90a380e verified
Raw
History Blame Contribute Delete
23.1 kB
#!/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 bisect
import json
import math
import sqlite3
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]
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 quiet 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 merge_intervals(intervals: list[tuple[float, float]]) -> tuple[list[float], list[float]]:
if not intervals:
return [], []
intervals = sorted(intervals)
merged: list[list[float]] = []
for start, end in intervals:
if not merged or start > merged[-1][1] + 1e-6:
merged.append([float(start), float(end)])
else:
merged[-1][1] = max(merged[-1][1], float(end))
starts = [item[0] for item in merged]
ends = [item[1] for item in merged]
return starts, ends
def load_station_coverage(db_path: Path) -> dict[str, tuple[list[float], list[float]]]:
con = sqlite3.connect(db_path)
rows = con.execute(
"""
SELECT station_id, start_epoch, end_epoch
FROM waveform_segments
ORDER BY station_id, start_epoch
"""
)
by_station: dict[str, list[tuple[float, float]]] = defaultdict(list)
for station_id, start_epoch, end_epoch in rows:
by_station[str(station_id)].append((float(start_epoch), float(end_epoch)))
con.close()
return {station_id: merge_intervals(items) for station_id, items in by_station.items()}
def has_coverage(
coverage: dict[str, tuple[list[float], list[float]]],
station_id: str,
epoch: float,
) -> bool:
starts, ends = coverage.get(station_id, ([], []))
idx = bisect.bisect_right(starts, epoch) - 1
return idx >= 0 and epoch <= ends[idx]
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: dict[str, tuple[list[float], list[float]]]):
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=has_coverage(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=False, loc="lower right")
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=False, loc="upper right")
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 = load_station_coverage(args.waveform_db)
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()