cangyeone commited on
Commit
e1fdcb4
·
verified ·
1 Parent(s): dfb3947

Sync canonical release scripts and config

Browse files
Files changed (1) hide show
  1. scripts/plot_dataset_overview.py +673 -0
scripts/plot_dataset_overview.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Dataset Overview Figure
5
+ =======================
6
+ A comprehensive visualization of the continuous seismic waveform dataset,
7
+ contrasting the 2019 Ridgecrest earthquake sequence with a quiet 2021 period.
8
+
9
+ Usage
10
+ -----
11
+ python essd_scripts/plot_dataset_overview.py \
12
+ --label-json data/label/annotations_for_continuous_hdf5.json \
13
+ --waveform-db data/index/waveform_index.sqlite \
14
+ --h5-dir data/hdf5 \
15
+ --out figures/dataset_overview.pdf
16
+
17
+ Dependencies
18
+ ------------
19
+ numpy, matplotlib, h5py, scipy (optional, for envelope)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import math
27
+ import sqlite3
28
+ from collections import defaultdict
29
+ from datetime import datetime, timezone
30
+ from pathlib import Path
31
+ from typing import Dict, List, Optional, Tuple
32
+
33
+ import h5py
34
+ import numpy as np
35
+ import matplotlib
36
+ import matplotlib.pyplot as plt
37
+ import matplotlib.gridspec as gridspec
38
+ import matplotlib.patches as mpatches
39
+ import matplotlib.ticker as mticker
40
+ from matplotlib.lines import Line2D
41
+
42
+ # ──────────────────────────────────────────────────────────────────────────────
43
+ # Global style
44
+ # ──────────────────────────────────────────────────────────────────────────────
45
+
46
+ RIDGECREST_COLOR = "#C0392B" # deep red – 2019 Ridgecrest sequence
47
+ QUIET_COLOR = "#2471A3" # steel blue – 2021 quiet period
48
+ NET_COLORS = {"CI": "#1F618D", "BK": "#196F3D", "NC": "#B7770D"}
49
+ NET_LABELS = {"CI": "CI – Southern California", "BK": "BK – Berkeley", "NC": "NC – Northern California"}
50
+ P_COLOR = "#1A5276"
51
+ S_COLOR = "#922B21"
52
+ ACCENT = "#F39C12"
53
+
54
+ FONT_TITLE = dict(fontsize=14, fontweight="bold", color="#1C2833")
55
+ FONT_LABEL = dict(fontsize=12, color="#2C3E50")
56
+ FONT_ANNOT = dict(fontsize=10, color="#555555")
57
+
58
+
59
+ # ──────────────────────────────────────────────────────────────────────────────
60
+ # Data helpers
61
+ # ──────────────────────────────────────────────────────────────────────────────
62
+
63
+ def load_stations(db_path: Path) -> List[Dict]:
64
+ conn = sqlite3.connect(str(db_path))
65
+ rows = conn.execute("""
66
+ SELECT station_key, network, station,
67
+ AVG(latitude) as lat, AVG(longitude) as lon,
68
+ COUNT(DISTINCT DATE(datetime(start_epoch,'unixepoch'))) as n_days
69
+ FROM waveform_segments
70
+ WHERE latitude IS NOT NULL AND ABS(latitude) > 0.1
71
+ GROUP BY station_key
72
+ """).fetchall()
73
+ conn.close()
74
+ return [{"key": r[0], "net": r[1], "sta": r[2],
75
+ "lat": r[3], "lon": r[4], "n_days": r[5]} for r in rows]
76
+
77
+
78
+ def load_events(label_json: Path) -> List[Dict]:
79
+ with open(label_json, encoding="utf-8") as f:
80
+ data = json.load(f)
81
+ events = []
82
+ for yr in data.get("years", {}).values():
83
+ for day_obj in yr.get("days", {}).values():
84
+ for ev in day_obj.get("events", {}).values():
85
+ evd = ev.get("event", {})
86
+ t = evd.get("event_time", "")
87
+ mag = evd.get("magnitude")
88
+ if not t or mag is None:
89
+ continue
90
+ events.append({
91
+ "time": t, "day": t[:10],
92
+ "mag": float(mag),
93
+ "lat": evd.get("latitude"),
94
+ "lon": evd.get("longitude"),
95
+ "dep": evd.get("depth_km"),
96
+ "picks": ev.get("counts", {}).get("pick_count", 0),
97
+ })
98
+ return events
99
+
100
+
101
+ def load_station_picks(label_json: Path, station_id: str, date_str: str) -> List[Dict]:
102
+ with open(label_json, encoding="utf-8") as f:
103
+ data = json.load(f)
104
+ picks = []
105
+ for yr in data.get("years", {}).values():
106
+ for day_obj in yr.get("days", {}).values():
107
+ for ev in day_obj.get("events", {}).values():
108
+ for sid0, sobj in ev.get("stations", {}).items():
109
+ for p in sobj.get("picks", []):
110
+ sid = p.get("station_id") or sid0
111
+ t = p.get("time", "")
112
+ if sid == station_id and t.startswith(date_str):
113
+ picks.append({"time": t, "phase": p.get("phase", "?"),
114
+ "status": p.get("status", "")})
115
+ return picks
116
+
117
+ def select_best_station_day(
118
+ label_json: Path,
119
+ waveform_db: Path,
120
+ year_prefix: str = "2019",
121
+ min_picks: int = 50,
122
+ max_picks: int = 300,
123
+ preferred_channels: Tuple[str, ...] = ("HHZ", "BHZ", "EHZ", "HNZ"),
124
+ ) -> Optional[Tuple[str, str, str, int]]:
125
+ """
126
+ Select station-day with the largest number of reference picks
127
+ and available waveform in the database.
128
+
129
+ Returns
130
+ -------
131
+ (station_id, channel, date_str, n_picks)
132
+ """
133
+ with open(label_json, encoding="utf-8") as f:
134
+ data = json.load(f)
135
+
136
+ counter = defaultdict(int)
137
+
138
+ for yr in data.get("years", {}).values():
139
+ for day_obj in yr.get("days", {}).values():
140
+ for ev in day_obj.get("events", {}).values():
141
+ for sid0, sobj in ev.get("stations", {}).items():
142
+ for p in sobj.get("picks", []):
143
+ sid = p.get("station_id") or sid0
144
+ t = p.get("time", "")
145
+ if sid and t.startswith(year_prefix):
146
+ counter[(sid, t[:10])] += 1
147
+
148
+ if not counter:
149
+ return None
150
+
151
+ conn = sqlite3.connect(str(waveform_db))
152
+
153
+ candidates = [
154
+ ((sid, date_str), n_picks)
155
+ for (sid, date_str), n_picks in counter.items()
156
+ if min_picks <= n_picks <= max_picks
157
+ ]
158
+
159
+ candidates = sorted(candidates, key=lambda kv: kv[1], reverse=True)
160
+ for (sid, date_str), n_picks in candidates:
161
+ for ch in preferred_channels:
162
+ row = conn.execute("""
163
+ SELECT channel
164
+ FROM waveform_segments
165
+ WHERE station_id=?
166
+ AND channel=?
167
+ AND DATE(datetime(start_epoch,'unixepoch'))=?
168
+ ORDER BY npts DESC
169
+ LIMIT 1
170
+ """, (sid, ch, date_str)).fetchone()
171
+
172
+ if row is not None:
173
+ conn.close()
174
+ return sid, ch, date_str, n_picks
175
+
176
+ conn.close()
177
+ return None
178
+
179
+ def query_waveform(db_path: Path, station_id: str, channel: str, date_str: str) -> Optional[Dict]:
180
+ conn = sqlite3.connect(str(db_path))
181
+ row = conn.execute("""
182
+ SELECT dataset_path, h5_file, npts, sampling_rate, start_epoch, latitude, longitude
183
+ FROM waveform_segments
184
+ WHERE station_id=? AND channel=?
185
+ AND DATE(datetime(start_epoch,'unixepoch'))=?
186
+ ORDER BY npts DESC LIMIT 1
187
+ """, (station_id, channel, date_str)).fetchone()
188
+ conn.close()
189
+ if row is None:
190
+ return None
191
+ return {"path": row[0], "h5_file": row[1], "npts": row[2],
192
+ "sr": row[3], "t0": row[4],
193
+ "lat": row[5], "lon": row[6]}
194
+
195
+
196
+ def read_waveform_downsampled(info: Dict, h5_dir: Optional[Path] = None,
197
+ target_hz: float = 1.0) -> Tuple[np.ndarray, np.ndarray]:
198
+ """Read waveform and downsample to target_hz via RMS in each window."""
199
+ h5_path = info["h5_file"]
200
+ if h5_dir is not None:
201
+ h5_path = str(h5_dir / Path(h5_path).name)
202
+ with h5py.File(h5_path, "r") as h5:
203
+ raw = h5[info["path"]][:]
204
+ raw = raw.astype(np.float32)
205
+
206
+ sr = float(info["sr"])
207
+ win = max(1, int(sr / target_hz))
208
+ n_wins = len(raw) // win
209
+ data = raw[: n_wins * win].reshape(n_wins, win)
210
+
211
+ # RMS envelope for display
212
+ envelope = np.sqrt(np.mean(data ** 2, axis=1))
213
+
214
+ t0 = float(info["t0"])
215
+ times = np.arange(n_wins) / target_hz # seconds from midnight
216
+ return times, envelope
217
+
218
+
219
+ def iso_to_epoch(s: str) -> float:
220
+ s = s.strip()
221
+ if s.endswith("Z"):
222
+ s = s[:-1] + "+00:00"
223
+ dt = datetime.fromisoformat(s)
224
+ if dt.tzinfo is None:
225
+ dt = dt.replace(tzinfo=timezone.utc)
226
+ return dt.timestamp()
227
+
228
+
229
+ # ──────────────────────────────────────────────────────────────────────────────
230
+ # Individual panel drawers
231
+ # ──────────────────────────────────────────────────────────────────────────────
232
+
233
+ def draw_station_map(ax: plt.Axes, stations: List[Dict], events: List[Dict]) -> None:
234
+ """Panel A – station map with network colours and Ridgecrest epicentres."""
235
+
236
+ # Background colour
237
+ ax.set_facecolor("#EBF5FB")
238
+
239
+ # Plot stations per network
240
+ for net, color in NET_COLORS.items():
241
+ sub = [s for s in stations if s["net"] == net]
242
+ lons = [s["lon"] for s in sub]
243
+ lats = [s["lat"] for s in sub]
244
+ ax.scatter(lons, lats, c=color, s=22, alpha=0.75, linewidths=0,
245
+ label=f"{net} ({len(sub)} stations)", zorder=3)
246
+
247
+ # Ridgecrest main shocks
248
+ ridgecrest = [
249
+ (35.705, -117.504, "M6.4\n2019-07-04"),
250
+ (35.770, -117.599, "M7.1\n2019-07-06"),
251
+ ]
252
+ for lat, lon, lbl in ridgecrest:
253
+ ax.scatter(lon, lat, marker="*", c=RIDGECREST_COLOR, s=420,
254
+ zorder=6, edgecolors="white", linewidths=0.7)
255
+ ax.annotate(lbl, (lon, lat), xytext=(5, 5), textcoords="offset points",
256
+ fontsize=9, color=RIDGECREST_COLOR, fontweight="bold", zorder=7)
257
+
258
+ # Mark the two showcase stations
259
+ showcase = [
260
+ ("CI.ADO.--", 34.550, -117.434, "CI.ADO\n(Ridgecrest\ncase)", "left"),
261
+ ("CI.CSH.--", 33.644, -116.596, "CI.CSH\n(Quiet\ncase)", "right"),
262
+ ]
263
+ for sid, lat, lon, lbl, ha in showcase:
264
+ ax.scatter(lon, lat, marker="^", c=ACCENT, s=120, zorder=5,
265
+ edgecolors="white", linewidths=0.8)
266
+ xoff = 6 if ha == "left" else -6
267
+ ax.annotate(lbl, (lon, lat), xytext=(xoff, 7), textcoords="offset points",
268
+ ha=ha, fontsize=9.5, color="#6E2F1A", fontweight="bold",
269
+ bbox=dict(boxstyle="round,pad=0.2", fc="white", alpha=0.7, lw=0),
270
+ zorder=7)
271
+
272
+ # Legend entries for epicentres and stations
273
+ leg_extra = [
274
+ Line2D([0], [0], marker="*", color="w", markerfacecolor=RIDGECREST_COLOR,
275
+ markersize=7, label="Ridgecrest epicentre"),
276
+ Line2D([0], [0], marker="^", color="w", markerfacecolor=ACCENT,
277
+ markersize=5, label="Showcase station"),
278
+ ]
279
+ handles, labels = ax.get_legend_handles_labels()
280
+ ax.legend(handles + leg_extra, labels + [h.get_label() for h in leg_extra],
281
+ fontsize=7, loc="upper left",
282
+ framealpha=0.88, edgecolor="#AAAAAA", labelspacing=0.3,
283
+ handlelength=1.2, handletextpad=0.4, borderpad=0.4)
284
+
285
+ # Map extent & labels
286
+ ax.set_xlim(-124.6, -113.8)
287
+ ax.set_ylim(32.2, 43.2)
288
+ ax.set_xlabel("Longitude", **FONT_LABEL)
289
+ ax.set_ylabel("Latitude", **FONT_LABEL)
290
+ ax.tick_params(labelsize=10)
291
+
292
+ # Simple graticule
293
+ ax.xaxis.set_major_locator(mticker.MultipleLocator(2))
294
+ ax.yaxis.set_major_locator(mticker.MultipleLocator(2))
295
+ ax.grid(True, lw=0.4, color="white", alpha=0.7)
296
+
297
+ # Panel label
298
+ ax.set_title("A · Seismic Network Coverage", loc="left", **FONT_TITLE, pad=6)
299
+
300
+ # Dataset overview inset (text box)
301
+ n_ci = sum(1 for s in stations if s["net"] == "CI")
302
+ n_bk = sum(1 for s in stations if s["net"] == "BK")
303
+ n_nc = sum(1 for s in stations if s["net"] == "NC")
304
+ total_picks = sum(e["picks"] for e in events)
305
+ summary = (
306
+ f"Networks: CI·BK·NC\n"
307
+ f"Stations: {len(stations):,} total\n"
308
+ f"Days: 14 (7 + 7)\n"
309
+ f"Events: {len(events):,}\n"
310
+ f"Total P/S picks: {total_picks:,}"
311
+ )
312
+ ax.text(0.975, 0.97, summary,
313
+ transform=ax.transAxes, fontsize=8.5,
314
+ va="top", ha="right", family="monospace",
315
+ bbox=dict(boxstyle="round,pad=0.6", fc="white", alpha=0.88,
316
+ ec="#AAAAAA", lw=0.8))
317
+
318
+
319
+ def draw_activity_timeline(ax: plt.Axes, events: List[Dict]) -> None:
320
+ """Panel B – events & picks per day with broken x-axis feel."""
321
+
322
+ daily_ev = defaultdict(int)
323
+ daily_pk = defaultdict(int)
324
+ for e in events:
325
+ daily_ev[e["day"]] += 1
326
+ daily_pk[e["day"]] += e["picks"]
327
+
328
+ days_2019 = sorted(d for d in daily_ev if d.startswith("2019"))
329
+ days_2021 = sorted(d for d in daily_ev if d.startswith("2021"))
330
+ all_days = days_2019 + ["gap"] + days_2021
331
+
332
+ # X positions with a visual gap
333
+ pos = {}
334
+ x = 0
335
+ for d in days_2019:
336
+ pos[d] = x; x += 1
337
+ x += 1.2 # gap
338
+ for d in days_2021:
339
+ pos[d] = x; x += 1
340
+
341
+ # Bars: events (left y), picks (right y)
342
+ ax2 = ax.twinx()
343
+
344
+ bar_w = 0.38
345
+ for d in days_2019 + days_2021:
346
+ col = RIDGECREST_COLOR if d.startswith("2019") else QUIET_COLOR
347
+ x_ = pos[d]
348
+ ax.bar(x_ - bar_w/2, max(daily_ev[d], 1), width=bar_w,
349
+ color=col, alpha=0.90, zorder=3)
350
+ ax2.bar(x_ + bar_w/2, max(daily_pk[d], 1), width=bar_w,
351
+ color=col, alpha=0.45, zorder=2)
352
+
353
+ # X tick labels
354
+ xticks = [pos[d] for d in days_2019 + days_2021]
355
+ xlbls = [d[5:] for d in days_2019 + days_2021] # MM-DD
356
+ ax.set_xticks(xticks)
357
+ ax.set_xticklabels(xlbls, rotation=40, ha="right", fontsize=10)
358
+
359
+ # Log scale on both y-axes
360
+ ax.set_yscale("log")
361
+ ax2.set_yscale("log")
362
+ ax.set_ylim(bottom=0.7)
363
+ ax2.set_ylim(bottom=0.7)
364
+
365
+ # Gap annotation – place at a fixed log-scale-friendly y
366
+ gap_x = (pos[days_2019[-1]] + pos[days_2021[0]]) / 2
367
+ ax.text(gap_x, 2.5, "╌╌ ~2 yrs ╌╌",
368
+ ha="center", va="bottom", fontsize=9.5, color="#888888")
369
+
370
+ # Axes styling – use compact 10^n tick labels
371
+ ax.yaxis.set_major_formatter(mticker.LogFormatterSciNotation(labelOnlyBase=True))
372
+ ax2.yaxis.set_major_formatter(mticker.LogFormatterSciNotation(labelOnlyBase=True))
373
+ ax.set_ylabel("Events / day", **FONT_LABEL)
374
+ ax2.set_ylabel("Picks / day", labelpad=0, fontsize=12, color="#666666")
375
+ ax.tick_params(axis="y", labelsize=10)
376
+ ax2.tick_params(axis="y", labelsize=10, labelcolor="#888888")
377
+ ax.set_xlim(-0.7, pos[days_2021[-1]] + 0.7)
378
+
379
+ # Legend
380
+ handles = [
381
+ mpatches.Patch(color=RIDGECREST_COLOR, alpha=0.9, label="Events (2019)"),
382
+ mpatches.Patch(color=QUIET_COLOR, alpha=0.9, label="Events (2021)"),
383
+ mpatches.Patch(color=RIDGECREST_COLOR, alpha=0.4, label="Picks (2019)"),
384
+ mpatches.Patch(color=QUIET_COLOR, alpha=0.4, label="Picks (2021)"),
385
+ ]
386
+ ax.legend(handles=handles, fontsize=10, loc="upper left",
387
+ framealpha=0.85, edgecolor="#AAAAAA", ncol=2, labelspacing=0.4)
388
+ ax.set_title("B · Daily Seismic Activity", loc="left", **FONT_TITLE, pad=6)
389
+ ax.spines[["top", "right"]].set_visible(False)
390
+ ax2.spines[["top", "left"]].set_visible(False)
391
+ ax.grid(axis="y", lw=0.4, alpha=0.5, zorder=0)
392
+ box = ax.get_position()
393
+ dx = 0.02
394
+ ax.set_position([box.x0 - dx, box.y0, box.width, box.height])
395
+
396
+
397
+ def draw_magnitude_distribution(ax: plt.Axes, events: List[Dict]) -> None:
398
+ """Panel C – cumulative magnitude-frequency plot for both periods."""
399
+
400
+ ev_2019 = sorted([e["mag"] for e in events if e["day"].startswith("2019")])
401
+ ev_2021 = sorted([e["mag"] for e in events if e["day"].startswith("2021")])
402
+
403
+ def cdf(mags):
404
+ m = np.array(sorted(mags))
405
+ n = np.arange(len(m), 0, -1) # cumulative from right
406
+ return m, n
407
+
408
+ m19, n19 = cdf(ev_2019)
409
+ m21, n21 = cdf(ev_2021)
410
+
411
+ ax.semilogy(m19, n19, color=RIDGECREST_COLOR, lw=1.8,
412
+ label=f"2019 (N={len(ev_2019):,})")
413
+ ax.semilogy(m21, n21, color=QUIET_COLOR, lw=1.8,
414
+ label=f"2021 (N={len(ev_2021):,})")
415
+
416
+ ax.fill_betweenx(n19, m19, alpha=0.10, color=RIDGECREST_COLOR)
417
+ ax.fill_betweenx(n21, m21, alpha=0.10, color=QUIET_COLOR)
418
+
419
+ # Mark main shocks
420
+ for idx, mag, lbl in [(0, 7.1, "M7.1"), (1, 6.4, "M6.4")]:
421
+ ax.axvline(mag, lw=1.2, ls="--", color=RIDGECREST_COLOR, alpha=0.7)
422
+ ax.text(mag + 0.07, n19.max() * (idx*2+4)*0.1, lbl,
423
+ fontsize=9.5, color=RIDGECREST_COLOR, va="top", fontweight="bold")
424
+
425
+ ax.set_xlabel("Magnitude", **FONT_LABEL)
426
+ ax.set_ylabel("Cumul. # events ≥ M", labelpad=0, **FONT_LABEL)
427
+ ax.yaxis.set_major_formatter(mticker.LogFormatterSciNotation(labelOnlyBase=True))
428
+ ax.tick_params(labelsize=10)
429
+ ax.legend(fontsize=10, framealpha=0.85, edgecolor="#AAAAAA")
430
+ ax.set_title("C · Magnitude–Frequency", loc="left", **FONT_TITLE, pad=6)
431
+ ax.spines[["top", "right"]].set_visible(False)
432
+ ax.grid(lw=0.4, alpha=0.4)
433
+
434
+
435
+ def draw_waveform(ax: plt.Axes,
436
+ times: np.ndarray,
437
+ envelope: np.ndarray,
438
+ picks: List[Dict],
439
+ t0_epoch: float,
440
+ date_str: str,
441
+ station: str,
442
+ channel: str,
443
+ period_label: str,
444
+ color: str) -> None:
445
+ """Panel D / E – single-day waveform envelope with pick markers."""
446
+
447
+ # Normalise envelope for display
448
+ env_norm = envelope / (np.percentile(envelope, 99) + 1e-9)
449
+ env_norm = np.clip(env_norm, 0, 8)
450
+
451
+ # Shade fill
452
+ ax.fill_between(times / 3600, env_norm, alpha=0.35, color=color, lw=0)
453
+ ax.plot(times / 3600, env_norm, lw=0.5, color=color, alpha=0.8)
454
+
455
+ # Pick markers
456
+ p_times = [p for p in picks if p["phase"] == "P"]
457
+ s_times = [p for p in picks if p["phase"] == "S"]
458
+ for group, col, yoff, lbl in [
459
+ (p_times, P_COLOR, 0.92, "P"),
460
+ (s_times, S_COLOR, 0.62, "S"),
461
+ ]:
462
+ for p in group:
463
+ try:
464
+ t_epoch = iso_to_epoch(p["time"])
465
+ t_sec = t_epoch - t0_epoch
466
+ t_hr = t_sec / 3600
467
+ ax.axvline(t_hr, lw=0.7, color=col, alpha=0.65, zorder=4)
468
+ except Exception:
469
+ continue
470
+ if group:
471
+ ax.text(
472
+ 0.99, yoff,
473
+ f"{lbl} ({len(group)})",
474
+ transform=ax.transAxes,
475
+ ha="right",
476
+ va="top",
477
+ fontsize=10,
478
+ color=col,
479
+ fontweight="bold",
480
+ zorder=20,
481
+ bbox=dict(
482
+ boxstyle="round,pad=0.25",
483
+ facecolor="white",
484
+ edgecolor="#CCCCCC",
485
+ linewidth=0.4,
486
+ alpha=0.85,
487
+ ),
488
+ )
489
+
490
+ # Axes
491
+ ax.set_xlim(0, 24)
492
+ ax.set_xticks(range(0, 25, 3))
493
+ ax.set_xticklabels([f"{h:02d}:00" for h in range(0, 25, 3)], fontsize=10)
494
+ ax.set_ylabel("Norm. amplitude", **FONT_LABEL)
495
+ ax.tick_params(axis="y", labelsize=10)
496
+ ax.spines[["top", "right"]].set_visible(False)
497
+
498
+ # Title
499
+ title = (f"{period_label} · {station} {channel} · {date_str}")
500
+ ax.set_title(title, loc="left", **FONT_TITLE, pad=5)
501
+
502
+ # Annotation box
503
+ n_picks = len(picks)
504
+
505
+ ax.text(
506
+ 0.01, 0.97, # 更靠上
507
+ f"Reference picks: {n_picks}",
508
+ transform=ax.transAxes,
509
+ fontsize=10,
510
+ color="#333333",
511
+ va="top",
512
+ zorder=10, # 🔴 关键:压到最上层
513
+ bbox=dict(
514
+ boxstyle="round,pad=0.35",
515
+ facecolor="white", # 比 fc 更规范
516
+ edgecolor="none",
517
+ alpha=0.85 # 稍微更实一点
518
+ )
519
+ )
520
+
521
+
522
+ # ──────────────────────────────────────────────────────────────────────────────
523
+ # Main figure assembly
524
+ # ──────────────────────────────────────────────────────────────────────────────
525
+
526
+ def build_figure(label_json: Path, waveform_db: Path, h5_dir: Path,
527
+ out_path: Path) -> None:
528
+
529
+ print("[1/6] Loading stations …")
530
+ stations = load_stations(waveform_db)
531
+
532
+ print("[2/6] Loading events & picks …")
533
+ events = load_events(label_json)
534
+
535
+ print("[3/6] Loading waveforms …")
536
+ best_2019 = select_best_station_day(
537
+ label_json=label_json,
538
+ waveform_db=waveform_db,
539
+ year_prefix="2019",
540
+ max_picks=500,
541
+ preferred_channels=("HHZ", "BHZ", "EHZ", "HNZ"),
542
+ )
543
+
544
+
545
+ if best_2019 is None:
546
+ print(" [WARN] No valid 2019 station-day found. Fall back to CI.ADO.--")
547
+ ridge_sid, ridge_ch, ridge_date = "CI.ADO.--", "HHZ", "2019-07-05"
548
+ else:
549
+ ridge_sid, ridge_ch, ridge_date, ridge_npicks = best_2019
550
+ print(
551
+ f" Best 2019 station-day: {ridge_sid} {ridge_ch} "
552
+ f"{ridge_date} with {ridge_npicks} reference picks"
553
+ )
554
+
555
+
556
+ wf_cfg = [
557
+ ("ridgecrest", ridge_sid, ridge_ch, ridge_date, RIDGECREST_COLOR),
558
+ ("quiet", "CI.CSH.--", "HHZ", "2021-11-14", QUIET_COLOR),
559
+ ]
560
+ waveforms = {}
561
+ picks_wf = {}
562
+ for label, sid, ch, date_str, col in wf_cfg:
563
+ info = query_waveform(waveform_db, sid, ch, date_str)
564
+ if info is None:
565
+ print(f" [WARN] waveform not found: {sid} {ch} {date_str}")
566
+ continue
567
+ print(f" Reading {sid} {ch} {date_str} npts={info['npts']:,} …")
568
+ t, env = read_waveform_downsampled(info, h5_dir=h5_dir, target_hz=1.0)
569
+ waveforms[label] = (t, env, info, col, sid, ch, date_str)
570
+ picks_wf[label] = load_station_picks(label_json, sid, date_str)
571
+ print(f" {len(picks_wf[label])} picks found for {sid} on {date_str}")
572
+
573
+ # ── Layout ────────────────────────────────────────────────────────────────
574
+ print("[4/6] Building figure …")
575
+ fig = plt.figure(figsize=(12, 7.15), dpi=150)
576
+ fig.patch.set_facecolor("white")
577
+
578
+ gs_outer = gridspec.GridSpec(
579
+ 3, 1,
580
+ hspace=0.52,
581
+ #wspace=0.55,
582
+ height_ratios=[4.2, 1.55, 1.55],
583
+ left=0.07, right=0.97, top=0.97, bottom=0.08,
584
+ )
585
+
586
+ # Row 0: map + timeline + magnitude
587
+ gs_top = gridspec.GridSpecFromSubplotSpec(
588
+ 1, 3, subplot_spec=gs_outer[0],
589
+ width_ratios=[1.35, 1.50, 1.15], wspace=0.30,
590
+ )
591
+ ax_map = fig.add_subplot(gs_top[0])
592
+ ax_time = fig.add_subplot(gs_top[1])
593
+ ax_mag = fig.add_subplot(gs_top[2])
594
+
595
+ # Rows 1–2: waveforms
596
+ ax_wf = {}
597
+ for row_i, key in enumerate(["ridgecrest", "quiet"]):
598
+ ax_wf[key] = fig.add_subplot(gs_outer[row_i + 1])
599
+
600
+ # ── Draw panels ───────────────────────────────────────────────────────────
601
+ print("[5/6] Drawing panels …")
602
+
603
+ draw_station_map(ax_map, stations, events)
604
+ draw_activity_timeline(ax_time, events)
605
+ draw_magnitude_distribution(ax_mag, events)
606
+
607
+ for label, col, period_lbl in [
608
+ ("ridgecrest", RIDGECREST_COLOR,
609
+ "D · Dense Ridgecrest Aftershock Sequence"),
610
+ ("quiet", QUIET_COLOR,
611
+ "E · Quiet Period"),
612
+ ]:
613
+ ax = ax_wf[label]
614
+ if label in waveforms:
615
+ t, env, info, c, sid, ch, date_str = waveforms[label]
616
+ draw_waveform(
617
+ ax, t, env,
618
+ picks_wf.get(label, []),
619
+ t0_epoch=info["t0"],
620
+ date_str=date_str,
621
+ station=sid, channel=ch,
622
+ period_label=period_lbl,
623
+ color=c,
624
+ )
625
+ else:
626
+ ax.text(0.5, 0.5, "Waveform not available",
627
+ ha="center", va="center", transform=ax.transAxes,
628
+ fontsize=9, color="#888888")
629
+ ax.set_title(period_lbl, loc="left", **FONT_TITLE, pad=5)
630
+ ax.set_xlabel("Time (UTC)", **FONT_LABEL)
631
+
632
+ # ── Title ──────────────────────────��──────────────────────────────────────
633
+ # suptitle removed per user request; panel titles (A–E) are retained.
634
+
635
+ # ── Save ──────────────────────────────────────────────────────────────────
636
+ print(f"[6/6] Saving → {out_path} …")
637
+ out_path.parent.mkdir(parents=True, exist_ok=True)
638
+ fig.savefig(out_path, dpi=200, bbox_inches="tight", facecolor="white")
639
+ plt.close(fig)
640
+ print(f"Done. {out_path}")
641
+
642
+
643
+ # ──────────────────────────────────────────────────────────────────────────────
644
+ # CLI
645
+ # ──────────────────────────────────────────────────────────────────────────────
646
+
647
+ def main() -> None:
648
+ parser = argparse.ArgumentParser(description="Dataset overview figure.")
649
+ parser.add_argument("--label-json", type=Path,
650
+ default=Path("data/label/annotations_for_continuous_hdf5.json"))
651
+ parser.add_argument("--waveform-db", type=Path,
652
+ default=Path("data/index/waveform_index.sqlite"))
653
+ parser.add_argument("--h5-dir", type=Path,
654
+ default=Path("data/hdf5"))
655
+ parser.add_argument("--out", type=Path,
656
+ default=Path("figures/dataset_overview.pdf"))
657
+ parser.add_argument("--dpi", type=int, default=200)
658
+ args = parser.parse_args()
659
+ if not args.label_json.exists():
660
+ mini_label = Path("data/label/annotations_mini_two_hours.json")
661
+ if mini_label.exists():
662
+ args.label_json = mini_label
663
+
664
+ build_figure(
665
+ label_json = args.label_json,
666
+ waveform_db = args.waveform_db,
667
+ h5_dir = args.h5_dir,
668
+ out_path = args.out,
669
+ )
670
+
671
+
672
+ if __name__ == "__main__":
673
+ main()