-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalign_stack.py
More file actions
2642 lines (2351 loc) · 91.8 KB
/
Copy pathalign_stack.py
File metadata and controls
2642 lines (2351 loc) · 91.8 KB
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# code by John Vidale and codex
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from typing import cast
from matplotlib.lines import Line2D
from pathlib import Path
from datetime import datetime, timezone
import time
import json
import re
from obspy import UTCDateTime, Stream, Trace
from obspy.geodetics import gps2dist_azimuth
from obspy.taup import TauPyModel
from scipy.signal import hilbert
from scipy.signal.windows import gaussian
from align_utils import (
add_catalog_event_lines,
add_stage_timing,
add_utc_time_axis,
build_alignment_products_payload,
build_component_output_payload,
compute_phase_travel_times,
compute_stage1_aligned_stack,
compute_stage2_screened_stack,
compute_stage3_finalized_rows,
compute_taup_station_shifts,
compute_time_axis_and_stack,
correlation_time_bounds,
draw_correlation_markers,
ensure_utc_datetime,
get_component_selection,
load_event_metadata,
load_station_lookup,
make_event_output_dir,
compute_alignment_setup,
normalize_traces_in_window,
report_timing_once,
read_waveforms_for_event,
rotate_horizontals_to_component,
resolve_component_key,
select_reference_trace,
print_reference_summary,
preprocess_traces_bandpass,
set_figure_title,
TimingState,
write_component_stack_mseeds,
)
min_freq, max_freq = 3.0, 10.0 # Bandpass filter (Hz)
start_time, end_time = -10.0, 20 # Plotting time window (seconds since origin)
# start_time, end_time = -1990.0, 3690.0 # Plotting time window (seconds since origin)
# start_time, end_time = -1990.0, 15000 # Plotting time window (seconds since origin)
win_pre, win_post = 0.5, 0.5 # Correlation window parameters (seconds)
r_window_min = 0.6 # Minimum correlation coefficient for trace selection
move_limit_sec = 0.05 # Maximum allowed shift (seconds) searched in compute_lag
# Run modes
all_channels = True # If True to process all channels
component = "R" # Component selection: 'Z', 'R', or 'T'
align_phase = "S" # Alignment phase 'P' or 'S'
verbose = False # If True, print detailed processing info
# Paths
path_prefix = "/Users/jvidale/Documents/Research/FaultScanR/"
info_root = Path(path_prefix + "event_sta_info")
analysis_hz = 100
input_mode = "snippets" # options: "long" or "snippets"
data_path = Path(path_prefix + f"Sgrams/20220930_{analysis_hz}Hz")
snippets_root = Path(path_prefix + f"Sgrams/Snippets_{analysis_hz}Hz")
event = "CI_40353544" # Single run selection (used when the corresponding "all_*" is False)
# event = "CI_40353664" # Single run selection (used when the corresponding "all_*" is False)
events = [event] # Allows for future modification to process multiple events
event_lat_override: float | None = None
event_lon_override: float | None = None
event_depth_override: float | None = None
# plotting options (user-facing)
show_individual_seismograms = False # Plot individual seismograms (20 traces/plot, 5 panels/figure)
show_record_section_plot = False # Show aligned record sections (single + 3-comp)
INPUT_CONFIG_FILE = Path(__file__).resolve().with_name("rp_input.json")
RUN_OUTPUT_DIR: Path | None = None
def apply_input_config(config_file: Path) -> None:
"""Load optional JSON run-parameter input file and override defaults."""
global min_freq, max_freq, start_time, end_time
global win_pre, win_post, r_window_min, move_limit_sec
global all_channels, component, align_phase, verbose
global data_path, event, events
global analysis_hz, input_mode
global snippets_root
global event_lat_override, event_lon_override, event_depth_override
global show_individual_seismograms, show_record_section_plot
def parse_sampling_hz(value, default_hz: int) -> int:
allowed = (50, 100, 250)
if value is None:
return default_hz
if isinstance(value, (int, float)):
hz = int(value)
if hz in allowed:
return hz
raise ValueError(f"analysis_hz must be one of {allowed}; got {value!r}")
if isinstance(value, str):
m = re.fullmatch(r"\s*(50|100|250)\s*(?:Hz)?\s*", value)
if m:
return int(m.group(1))
raise ValueError(f"analysis_hz must be one of {allowed}; got {value!r}")
raise ValueError(f"analysis_hz must be one of {allowed}; got {value!r}")
if not config_file.exists():
print(f"[INFO] Input config not found, using in-file defaults: {config_file}")
return
try:
with config_file.open("r", encoding="utf-8") as f:
cfg = json.load(f)
except Exception as e:
print(f"[WARN] Failed to read input config: {config_file} ({e})")
return
min_freq = float(cfg.get("min_freq", min_freq))
max_freq = float(cfg.get("max_freq", max_freq))
start_time = float(cfg.get("start_time", start_time))
end_time = float(cfg.get("end_time", end_time))
win_pre = float(cfg.get("win_pre", win_pre))
win_post = float(cfg.get("win_post", win_post))
r_window_min = float(cfg.get("r_window_min", r_window_min))
move_limit_sec = float(cfg.get("move_limit_sec", move_limit_sec))
all_channels = bool(cfg.get("all_channels", all_channels))
component = str(cfg.get("component", component))
align_phase = str(cfg.get("align_phase", align_phase))
verbose = bool(cfg.get("verbose", verbose))
analysis_hz = parse_sampling_hz(cfg.get("analysis_hz", analysis_hz), analysis_hz)
mode_cfg = str(cfg.get("input_mode", input_mode)).lower()
input_mode = mode_cfg if mode_cfg in ("long", "snippets") else input_mode
if "events" in cfg and isinstance(cfg["events"], list):
events = [str(x) for x in cfg["events"]]
elif "event" in cfg:
events = [str(cfg["event"])]
if events:
event = events[0]
lat_cfg = cfg.get("event_lat")
lon_cfg = cfg.get("event_lon")
depth_cfg = cfg.get("event_depth")
if lat_cfg is not None or lon_cfg is not None or depth_cfg is not None:
if lat_cfg is None or lon_cfg is None or depth_cfg is None:
print(
"[WARN] Event location override requires event_lat, event_lon, "
"and event_depth; using catalog location."
)
event_lat_override = None
event_lon_override = None
event_depth_override = None
else:
event_lat_override = float(lat_cfg)
event_lon_override = float(lon_cfg)
event_depth_override = float(depth_cfg)
data_path = Path(path_prefix + f"Sgrams/20220930_{analysis_hz}Hz")
snippets_root = Path(path_prefix + f"Sgrams/Snippets_{analysis_hz}Hz")
show_individual_seismograms = bool(cfg.get("show_individual_seismograms", show_individual_seismograms))
show_record_section_plot = bool(cfg.get("show_record_section_plot", show_record_section_plot))
print(f"Loaded input config: {config_file}")
apply_input_config(INPUT_CONFIG_FILE)
# Timing (cpu and wall)
timing_state = TimingState()
catalog_local = None
try:
catalog_local_file = info_root / "catalog_local_hand.xlsx"
catalog_local = pd.read_excel(catalog_local_file)
print(f"Loaded catalog: {catalog_local_file}")
except Exception as e:
print(f"[WARN] Failed to read catalog in {info_root} ({e})")
# Travel-time model
model = TauPyModel(model="iasp91")
def write_run_parameter_snapshot(output_dir: Path | str) -> Path:
"""Write a timestamped JSON snapshot of run parameters for reproducibility."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-2]
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
root_path = Path(path_prefix)
def _snapshot_path(p: Path) -> str:
"""Prefer root-relative paths in snapshots to avoid repeating hardwired prefix."""
try:
return str(p.relative_to(root_path))
except Exception:
return str(p)
snapshot = {
"timestamp": timestamp,
"min_freq": min_freq,
"max_freq": max_freq,
"start_time": start_time,
"end_time": end_time,
"win_pre": win_pre,
"win_post": win_post,
"r_window_min": r_window_min,
"move_limit_sec": move_limit_sec,
"all_channels": all_channels,
"component": component,
"align_phase": align_phase,
"verbose": verbose,
"info_root": _snapshot_path(info_root),
"input_mode": input_mode,
"analysis_hz": analysis_hz,
"data_path": _snapshot_path(data_path),
"snippets_root": _snapshot_path(snippets_root),
"events": list(events),
"event_lat_override": event_lat_override,
"event_lon_override": event_lon_override,
"event_depth_override": event_depth_override,
"show_individual_seismograms": show_individual_seismograms,
"show_record_section_plot": show_record_section_plot,
}
snapshot_path = output_dir / f"rp_{timestamp}.json"
with snapshot_path.open("w", encoding="utf-8") as f:
json.dump(snapshot, f, indent=2)
print(f"Saved run parameter snapshot: {snapshot_path}")
return snapshot_path
def initialize_run_output_dir(base_output_root: Path) -> Path:
"""Create and return a timestamped directory for one pipeline run."""
global RUN_OUTPUT_DIR
run_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-2]
RUN_OUTPUT_DIR = base_output_root / run_timestamp
RUN_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"Run output directory: {RUN_OUTPUT_DIR}")
return RUN_OUTPUT_DIR
def get_run_event_output_dir(eve_id: str) -> Path:
"""Return per-event output directory under the active run directory."""
if RUN_OUTPUT_DIR is None:
fallback_root = Path(path_prefix + "output")
initialize_run_output_dir(fallback_root)
event_dir = RUN_OUTPUT_DIR / eve_id # type: ignore[union-attr]
event_dir.mkdir(parents=True, exist_ok=True)
return event_dir
def apply_event_location_override(
event_depth: float,
eve_lat: float,
eve_lon: float,
) -> tuple[float, float, float]:
"""Return configured event lat/lon/depth overrides when all are supplied."""
if (
event_lat_override is None
or event_lon_override is None
or event_depth_override is None
):
return event_depth, eve_lat, eve_lon
print(
"Using event location override from rp_input.json: "
f"lat={event_lat_override:.6f}, lon={event_lon_override:.6f}, "
f"depth={event_depth_override:.3f} km"
)
return event_depth_override, event_lat_override, event_lon_override
# ===================== Helper functions =====================
def plot_stage_stacks(
eve_id: str,
plot_comp: str,
align_phase_name: str,
t_abs: np.ndarray,
mask: np.ndarray,
aligned_stack: np.ndarray,
selected_aligned_stack: np.ndarray,
stack_vec: np.ndarray,
save_dir: Path,
) -> None:
"""Plot and save Stage-1/Stage-2/Final stacks for single-component runs."""
fig_stk, ax_stk = plt.subplots(1, 1, figsize=(10, 3.8))
set_figure_title(fig_stk, f"{eve_id} {plot_comp} stage stacks")
ax_stk.plot(t_abs[mask], aligned_stack[mask], color="C0", lw=2, label="Stage 1: aligned_stack")
ax_stk.plot(
t_abs[mask],
selected_aligned_stack[mask],
color="C1",
lw=2,
label="Stage 2: selected_aligned_stack",
)
ax_stk.plot(t_abs[mask], stack_vec[mask], color="C3", lw=2.2, label="Final stack")
ax_stk.axhline(0.0, color="k", lw=0.6, alpha=0.6)
ax_stk.set_xlim(start_time, end_time)
ax_stk.set_ylim(-1.1, 1.1)
ax_stk.grid(alpha=0.2)
ax_stk.set_xlabel("Time since origin (s)")
ax_stk.set_ylabel("Stack (norm.)")
ax_stk.set_title(f"Event {eve_id} {plot_comp}: Stage-1/Stage-2/Final stacks")
ax_stk.legend(loc="upper right", fontsize=9)
plt.tight_layout()
stack_file = save_dir / f"{eve_id}_{plot_comp}_stage_stacks_{align_phase_name}.png"
fig_stk.savefig(stack_file, dpi=300, bbox_inches="tight")
print(f"✓ Stage stacks plot saved to: {stack_file}")
def plot_record_section_and_stack(
show_record: bool,
eve_id: str,
plot_comp: str,
align_phase_name: str,
selected_rows: list,
rejected_rows: list,
t_abs: np.ndarray,
mask: np.ndarray,
sample_rate: float,
t_ref,
win_start: int,
win_end: int,
move_sec: float,
npts: int,
n_pass_window: int,
stack_vec: np.ndarray,
save_dir: Path,
):
"""Plot and save record section (top) plus normalized stack (bottom)."""
if not show_record:
return None
fig, (ax, ax2) = plt.subplots(
2,
1,
figsize=(10, 9),
sharex=False,
gridspec_kw={"height_ratios": [3, 1]},
)
set_figure_title(fig, f"{eve_id} {plot_comp} aligned record section")
all_rows = selected_rows + rejected_rows
all_rows.sort(key=lambda t: t[0])
t_masked = t_abs[mask]
if len(all_rows) > 0 and np.any(mask):
A = np.vstack([row[2][mask] for row in all_rows])
dvec = np.array([row[0] for row in all_rows], dtype=float)
# y-edges for irregular station spacing
if len(dvec) == 1:
y_edges = np.array([dvec[0] - 0.5, dvec[0] + 0.5])
else:
mids = 0.5 * (dvec[1:] + dvec[:-1])
y_edges = np.empty(len(dvec) + 1)
y_edges[1:-1] = mids
y_edges[0] = dvec[0] - (mids[0] - dvec[0])
y_edges[-1] = dvec[-1] + (dvec[-1] - mids[-1])
# t-edges for pcolormesh
if len(t_masked) == 1:
t_edges = np.array(
[t_masked[0] - 0.5 / sample_rate, t_masked[0] + 0.5 / sample_rate]
)
else:
tmids = 0.5 * (t_masked[1:] + t_masked[:-1])
t_edges = np.empty(len(t_masked) + 1)
t_edges[1:-1] = tmids
t_edges[0] = t_masked[0] - (tmids[0] - t_masked[0])
t_edges[-1] = t_masked[-1] + (t_masked[-1] - tmids[-1])
ax.pcolormesh(
t_edges,
y_edges,
A,
cmap="gray",
shading="auto",
vmin=-1.0,
vmax=1.0,
)
ax.set_xlim(start_time, end_time)
ax.set_xlabel("Time since origin (s)")
ax.set_ylabel("Epicentral distance (km)")
ax.set_title(f"Aligned {align_phase_name} waveforms Event {eve_id} comp = {plot_comp}")
ax.grid(alpha=0.2)
# Theoretical arrival time (reference station) as a vertical reference line
try:
if t_ref is not None:
for axi in (ax, ax2):
axi.axvline(x=t_ref, color="k", lw=3, alpha=0.5, zorder=6)
except Exception as e:
print(f" [WARN] Failed to draw vertical reference arrival for {align_phase_name}: {e}")
# Correlation window and search bounds
try:
for axi in (ax, ax2):
draw_correlation_markers(
axi,
start_time,
win_start,
win_end,
sample_rate,
move_sec,
npts,
)
except Exception as e:
print(f" [WARN] Failed to draw correlation window bounds: {e}")
try:
legend_handles = [
Line2D([0], [0], color="y", lw=2, label="Correlation window"),
Line2D([0], [0], color="g", lw=2, label="Correlation search (±move_limit_sec)"),
Line2D([0], [0], color="none", label=f"Pass r_win: {n_pass_window}"),
]
ax.legend(
handles=legend_handles,
loc="upper left",
bbox_to_anchor=(1.02, 1.0),
borderaxespad=0.0,
fontsize=9,
)
except Exception as e:
print(f" [WARN] Failed to add legend: {e}")
# Bottom panel: normalized stack
ax2.plot(t_abs[mask], stack_vec[mask], color="C3", lw=1.5)
ax2.axhline(0.0, color="k", lw=0.6)
ax2.set_xlim(start_time, end_time)
ax2.set_xlabel("Time since origin (s)")
ax2.set_ylabel("Stack (norm.)")
ax2.set_ylim(-1.1, 1.1)
ax2.set_title("Final stack uses ALL traces (no screening)")
ax2.grid(alpha=0.2)
plt.tight_layout()
record_file = save_dir / f"{eve_id}_{plot_comp}_{align_phase_name}.png"
fig.savefig(record_file, dpi=300, bbox_inches="tight")
print(f"✓ Record-section plot saved to: {record_file}")
return fig
def plot_three_component_log_envelope(
comp_order: list,
stack_by_comp: dict,
sample_rate_env: float,
t_abs: np.ndarray,
mask: np.ndarray,
start_time: float,
end_time: float,
eve_id: str,
align_phase_name: str,
save_dir: Path,
origin_env,
catalog_df,
) -> None:
"""Plot and save log10 RMS envelope for combined three-component stacks."""
try:
if all(comp in stack_by_comp for comp in comp_order):
z = stack_by_comp["DPZ"]
r = stack_by_comp["R"]
t = stack_by_comp["T"]
env_z = np.abs(cast(np.ndarray, hilbert(z)))
env_r = np.abs(cast(np.ndarray, hilbert(r)))
env_t = np.abs(cast(np.ndarray, hilbert(t)))
env_rms = np.sqrt((env_z ** 2 + env_r ** 2 + env_t ** 2) / 3.0)
std_sec = 1.0
std_samples = max(1.0, float(sample_rate_env) * std_sec)
win_samples = max(3, int(round(6.0 * std_samples)))
gauss = gaussian(win_samples, std_samples)
gauss = gauss / np.sum(gauss)
env_rms_smooth = np.convolve(env_rms, gauss, mode="same")
log_env = np.log10(np.maximum(env_rms_smooth, 1e-12))
fig_env, ax_env = plt.subplots(figsize=(12, 4.5))
set_figure_title(fig_env, f"{eve_id} 3-comp log10 envelope")
ax_env.plot(t_abs[mask], log_env[mask], color="k", lw=1.5)
ax_env.set_xlim(start_time, end_time)
ax_env.set_xlabel("Time since origin (s)", fontsize=11)
ax_env.set_ylabel("log10 envelope", fontsize=11)
ax_env.set_title(
f"Event {eve_id} - log10 RMS envelope of 3-component stack",
fontsize=12,
fontweight="bold",
)
ax_env.grid(alpha=0.2)
add_catalog_event_lines(ax_env, origin_env, catalog_df, start_time, end_time)
fig_env.subplots_adjust(bottom=0.28)
if origin_env is not None:
try:
add_utc_time_axis(ax_env, origin_env)
except Exception as e:
print(f"[WARN] Failed to add UTC time axis (envelope): {e}")
env_file = save_dir / f"{eve_id}_3comp_log10_envelope_{align_phase_name}.png"
fig_env.savefig(env_file, dpi=300, bbox_inches="tight")
print(f"✓ Log10 envelope plot saved to: {env_file}")
except Exception as e:
print(f"[WARN] Failed to create log10 envelope plot: {e}")
def plot_single_trace_log_envelope(
num_traces: int,
stack_vec: np.ndarray,
sample_rate: float,
t_abs: np.ndarray,
mask: np.ndarray,
start_time: float,
end_time: float,
eve_id: str,
plot_comp: str,
align_phase_name: str,
save_dir: Path,
origin,
catalog_df,
) -> None:
"""Plot and save log10 envelope when there is a single trace."""
if num_traces != 1:
return
try:
env = np.abs(cast(np.ndarray, hilbert(stack_vec)))
std_sec = 1.0
std_samples = max(1.0, float(sample_rate) * std_sec)
win_samples = max(3, int(round(6.0 * std_samples)))
gauss = gaussian(win_samples, std_samples)
gauss = gauss / np.sum(gauss)
env_smooth = np.convolve(env, gauss, mode="same")
log_env = np.log10(np.maximum(env_smooth, 1e-12))
fig_env, ax_env = plt.subplots(figsize=(12, 4.5))
set_figure_title(fig_env, f"{eve_id} {plot_comp} log10 envelope")
ax_env.plot(t_abs[mask], log_env[mask], color="k", lw=1.5)
ax_env.set_xlim(start_time, end_time)
ax_env.set_xlabel("Time since origin (s)", fontsize=11)
ax_env.set_ylabel("log10 envelope", fontsize=11)
ax_env.set_title(
f"Event {eve_id} - log10 envelope ({plot_comp})",
fontsize=12,
fontweight="bold",
)
ax_env.grid(alpha=0.2)
add_catalog_event_lines(ax_env, origin, catalog_df, start_time, end_time)
fig_env.subplots_adjust(bottom=0.28)
if origin is not None:
try:
add_utc_time_axis(ax_env, origin)
except Exception as e:
print(f"[WARN] Failed to add UTC time axis (single envelope): {e}")
env_file = save_dir / f"{eve_id}_{plot_comp}_log10_envelope_{align_phase_name}.png"
fig_env.savefig(env_file, dpi=300, bbox_inches="tight")
print(f"✓ Log10 envelope plot saved to: {env_file}")
except Exception as e:
print(f"[WARN] Failed to create log10 envelope plot (single trace): {e}")
def plot_estimated_vs_calculated_shifts(
calc_shifts: dict,
station_shifts: dict,
pass_window_ids: set,
eve_id: str,
plot_comp: str,
align_phase_name: str,
save_dir: Path,
) -> None:
"""Plot estimated shift versus TauP-calculated shift for stations with both values."""
common_sta = set(calc_shifts.keys()) & set(station_shifts.keys())
if len(common_sta) == 0:
print("[WARN] No stations with both estimated and calculated shifts for comparison.")
return
stations = sorted(common_sta, key=lambda s: int(s))
est_shift = np.array([station_shifts[s]["lag_seconds"] for s in stations], dtype=float)
calc_shift = np.array([calc_shifts[s] for s in stations], dtype=float)
pass_set = set(pass_window_ids)
pass_mask = np.array([s in pass_set for s in stations], dtype=bool)
fail_mask = ~pass_mask
fig_ec, ax_ec = plt.subplots(1, 1, figsize=(6.2, 5.2))
set_figure_title(fig_ec, f"{eve_id} {plot_comp} est vs calc shifts")
if np.any(pass_mask):
ax_ec.scatter(calc_shift[pass_mask], est_shift[pass_mask], s=20, alpha=0.6, c="k", label="Pass r_win")
if np.any(fail_mask):
ax_ec.scatter(calc_shift[fail_mask], est_shift[fail_mask], s=22, alpha=0.8, c="red", label="Fail r_win")
minv = float(min(np.min(calc_shift), np.min(est_shift)))
maxv = float(max(np.max(calc_shift), np.max(est_shift)))
ax_ec.plot([minv, maxv], [minv, maxv], "r--", lw=1.2, alpha=0.7, label="1:1 line")
ax_ec.set_xlabel("Calculated shift (s)")
ax_ec.set_ylabel("Estimated shift (s)")
ax_ec.set_title(f"Event {eve_id} {plot_comp}: Estimated vs Calculated shifts")
ax_ec.grid(alpha=0.3)
ax_ec.legend(loc="upper left", fontsize=9)
plt.tight_layout()
estcalc_file = save_dir / f"{eve_id}_{plot_comp}_est_vs_calc_shift_{align_phase_name}.png"
fig_ec.savefig(estcalc_file, dpi=300, bbox_inches="tight")
print(f"✓ Estimated vs calculated shift plot saved to: {estcalc_file}")
def write_component_phase_time_shifts(
save_dir: Path,
eve_id: str,
plot_comp: str,
align_phase_name: str,
station_shifts: dict,
calc_shifts: dict,
station_corr: dict,
pass_window_ids: set,
sample_rate: float,
min_freq_hz: float,
max_freq_hz: float,
) -> Path | None:
"""Save component/phase cross-correlation shifts relative to predicted arrivals."""
component_name = plot_comp.upper()
phase_name = align_phase_name.upper()
def station_sort_key(station_id: str):
try:
return (0, int(station_id))
except ValueError:
return (1, station_id)
rows = []
for station_id in sorted(station_shifts.keys(), key=station_sort_key):
station_shift = station_shifts[station_id]
if isinstance(station_shift, dict):
measured_shift = float(station_shift["lag_seconds"])
lag_samples = station_shift.get("lag_samples", np.nan)
else:
measured_shift = float(station_shift)
lag_samples = np.nan
predicted_shift = calc_shifts.get(station_id)
predicted_shift = float(predicted_shift) if predicted_shift is not None else np.nan
residual_shift = measured_shift - predicted_shift if np.isfinite(predicted_shift) else np.nan
rows.append(
{
"event_id": eve_id,
"station": station_id,
"component": component_name,
"phase": phase_name,
"sample_rate_hz": float(sample_rate),
"lag_samples": int(lag_samples) if np.isfinite(lag_samples) else np.nan,
"xcorr_shift_seconds": measured_shift,
"predicted_shift_seconds": predicted_shift,
"shift_relative_to_predicted_seconds": residual_shift,
"window_correlation": float(station_corr.get(station_id, np.nan)),
"passed_window_correlation": station_id in pass_window_ids,
}
)
if not rows:
print(f"[WARN] No {component_name} {phase_name}-wave station shifts available to save.")
return None
statics_dir = Path(path_prefix + "output") / "Statics"
statics_dir.mkdir(parents=True, exist_ok=True)
freq_label = f"{min_freq_hz:g}-{max_freq_hz:g}Hz".replace(".", "p")
out_file = statics_dir / f"{eve_id}_{component_name}_{phase_name}_{freq_label}_xcorr_statics.xlsx"
pd.DataFrame(rows).to_excel(out_file, index=False)
print(f"✓ {component_name} {phase_name}-wave statics saved to: {out_file}")
return out_file
def write_radial_s_wave_time_shifts(*args, **kwargs) -> Path | None:
"""Backward-compatible wrapper for component/phase statics export."""
return write_component_phase_time_shifts(*args, **kwargs)
def plot_snippet_comparison(
start_time: float,
win_start: int,
win_end: int,
sample_rate: float,
ref_window: np.ndarray,
pass_window_ids: set,
snippet_by_station: dict,
eve_id: str,
plot_comp: str,
align_phase_name: str,
save_dir: Path,
) -> None:
"""Plot pass/fail correlation-window snippets against the reference window."""
try:
t_win = start_time + (np.arange(win_start, win_end) / sample_rate)
pass_list = sorted(list(pass_window_ids), key=lambda s: int(s))
fail_list = sorted(
[s for s in snippet_by_station.keys() if s not in pass_window_ids],
key=lambda s: int(s),
)
n_show = 10
pass_show = pass_list[:n_show]
fail_show = fail_list[:n_show]
fig_snip, (axp, axf) = plt.subplots(1, 2, figsize=(10, 3.8), sharey=True)
set_figure_title(fig_snip, f"{eve_id} {plot_comp} correlation snippets")
for sid in pass_show:
axp.plot(t_win, snippet_by_station[sid], color="k", alpha=0.4, lw=1)
axp.plot(t_win, ref_window, color="C3", lw=2, label="Ref window")
axp.set_title(f"Pass r_win (N={len(pass_list)})")
axp.set_xlabel("Time since origin (s)")
axp.grid(alpha=0.3)
for sid in fail_show:
axf.plot(t_win, snippet_by_station[sid], color="k", alpha=0.4, lw=1)
axf.plot(t_win, ref_window, color="C3", lw=2, label="Ref window")
axf.set_title(f"Fail r_win (N={len(fail_list)})")
axf.set_xlabel("Time since origin (s)")
axf.grid(alpha=0.3)
axp.set_ylabel("Normalized amplitude")
axf.legend(loc="upper right", fontsize=8)
fig_snip.suptitle(
f"Event {eve_id} {plot_comp}: correlation-window snippets",
fontsize=12,
fontweight="bold",
)
plt.tight_layout()
snip_file = save_dir / f"{eve_id}_{plot_comp}_snippet_compare_{align_phase_name}.png"
fig_snip.savefig(snip_file, dpi=300, bbox_inches="tight")
print(f"✓ Snippet comparison plot saved to: {snip_file}")
except Exception as e:
print(f"[WARN] Failed to create snippet comparison plot: {e}")
def plot_station_pass_map(
aligned_traces_by_station: dict,
pass_window_ids: set,
name2ll: dict,
eve_id: str,
plot_comp: str,
align_phase_name: str,
save_dir: Path,
) -> None:
"""Plot station locations colored by pass/fail screening status."""
try:
all_stations = sorted(aligned_traces_by_station.keys(), key=lambda s: int(s))
pass_win = set(pass_window_ids)
fig_map, axm = plt.subplots(1, 1, figsize=(6.5, 5.5))
set_figure_title(fig_map, f"{eve_id} {plot_comp} station pass map")
pass_lats = [name2ll[s][0] for s in all_stations if s in pass_win]
pass_lons = [name2ll[s][1] for s in all_stations if s in pass_win]
fail_lats = [name2ll[s][0] for s in all_stations if s not in pass_win]
fail_lons = [name2ll[s][1] for s in all_stations if s not in pass_win]
if len(fail_lons) > 0:
axm.scatter(fail_lons, fail_lats, s=18, c="0.7", label="Fail")
if len(pass_lons) > 0:
axm.scatter(pass_lons, pass_lats, s=22, c="C3", label="Pass")
axm.set_title("Pass r_win", fontsize=11, fontweight="bold")
axm.grid(alpha=0.3)
axm.set_xlabel("Longitude")
axm.set_ylabel("Latitude")
axm.legend(loc="upper right", fontsize=9)
fig_map.suptitle(
f"Event {eve_id} {plot_comp}: stations passing thresholds",
fontsize=13,
fontweight="bold",
)
plt.tight_layout()
map_file = save_dir / f"{eve_id}_{plot_comp}_station_pass_map_{align_phase_name}.png"
fig_map.savefig(map_file, dpi=300, bbox_inches="tight")
print(f"✓ Station pass/fail map saved to: {map_file}")
except Exception as e:
print(f"[WARN] Failed to create station pass/fail maps: {e}")
def plot_individual_seismograms_single_component(
show_individual_seismograms: bool,
selected_rows: list,
rejected_rows: list,
pass_window_ids: set,
t_abs: np.ndarray,
mask: np.ndarray,
stack_vec: np.ndarray,
start_time: float,
win_start: int,
win_end: int,
sample_rate: float,
move_limit_sec: float,
npts: int,
eve_id: str,
plot_comp: str,
align_phase_name: str,
save_dir: Path,
) -> None:
"""Plot individual seismograms in paged panels for single-component mode."""
if not show_individual_seismograms:
return
try:
all_rows = selected_rows + rejected_rows
all_rows.sort(key=lambda t: int(t[1]))
n_traces = len(all_rows)
if n_traces <= 0:
return
n_per = 20
panels_per_fig = 5
n_panels = int(np.ceil(n_traces / n_per))
n_figs = int(np.ceil(n_panels / panels_per_fig))
for fig_idx in range(n_figs):
panel_start = fig_idx * panels_per_fig
panel_end = min((fig_idx + 1) * panels_per_fig, n_panels)
panels_in_fig = panel_end - panel_start
fig_ind, axes_ind = plt.subplots(
panels_in_fig,
1,
figsize=(10, 2.2 * panels_in_fig),
sharex=True,
sharey=False,
)
set_figure_title(
fig_ind,
f"{eve_id} {plot_comp} individual seismograms fig {fig_idx + 1}",
)
if panels_in_fig == 1:
axes_ind = [axes_ind]
for p in range(panels_in_fig):
axp = axes_ind[p]
global_panel = panel_start + p
start_idx = global_panel * n_per
end_idx = min((global_panel + 1) * n_per, n_traces)
subset = all_rows[start_idx:end_idx]
t_win_start = start_time + (win_start / sample_rate)
t_win_end = start_time + (win_end / sample_rate)
t_explore_start = max(start_time, t_win_start - move_limit_sec)
t_explore_end = min(start_time + (npts / sample_rate), t_win_end + move_limit_sec)
axp.axvline(x=t_win_start, color="y", lw=1.2, alpha=0.9)
axp.axvline(x=t_win_end, color="y", lw=1.2, alpha=0.9)
axp.axvline(x=t_explore_start, color="g", lw=1.2, alpha=0.9)
axp.axvline(x=t_explore_end, color="g", lw=1.2, alpha=0.9)
for idx_in_subset, (_, station_id, y) in enumerate(subset):
i = (len(subset) - 1) - idx_in_subset
passed_win = station_id in pass_window_ids
trace_color = "k" if passed_win else "red"
axp.plot(
t_abs[mask],
y[mask] + i,
color=trace_color,
lw=0.7,
)
axp.text(
t_abs[mask][0],
i,
station_id,
fontsize=6,
va="center",
)
ref_offset = len(subset) + 1
axp.plot(
t_abs[mask],
stack_vec[mask] + ref_offset,
color="C3",
lw=1.2,
)
axp.set_ylim(-1, len(subset) + 2)
axp.grid(alpha=0.2)
axp.set_ylabel("Trace index")
axes_ind[-1].set_xlabel("Time since origin (s)")
fig_ind.suptitle(
f"Event {eve_id} {plot_comp}: individual seismograms "
f"(20 per panel, fig {fig_idx + 1}/{n_figs})",
fontsize=12,
fontweight="bold",
)
plt.tight_layout()
ind_file = save_dir / (
f"{eve_id}_{plot_comp}_individual_seismograms_{align_phase_name}_fig{fig_idx + 1}.png"
)
fig_ind.savefig(ind_file, dpi=300, bbox_inches="tight")
print(f"✓ Individual seismograms plot saved to: {ind_file}")
except Exception as e:
print(f"[WARN] Failed to create individual seismograms plot: {e}")
def plot_three_component_stack_compare(
all_component_data: dict,
eve_id: str,
align_phase_name: str,
save_dir: Path,
) -> None:
"""Plot black/red stack comparison for Z/R/T components and save figure."""
print("Creating stack comparison plot (all aligned vs r_min-selected)...")
fig_cmp, axes_cmp = plt.subplots(3, 1, figsize=(9, 12), sharex=True, sharey=True)
set_figure_title(fig_cmp, f"{eve_id} stack compare")
comp_order = ["DPZ", "R", "T"]
comp_titles_cmp = ["Z stack", "R stack", "T stack"]
utc_tz = timezone.utc
for j, comp_name in enumerate(comp_order):
axc = axes_cmp[j]
if comp_name not in all_component_data:
axc.set_axis_off()
continue
data = all_component_data[comp_name]
t_abs = data["t_abs"]
mask = data["mask"]
start_time = data["start_time"]
end_time = data["end_time"]
p_time = data.get("p_traveltime")
s_time = data.get("s_traveltime")
tr_map = data.get("aligned_traces_by_station", {})
all_stations = sorted(tr_map.keys(), key=lambda s: int(s))
stack_black = np.zeros_like(t_abs)
if len(all_stations) > 0:
bank_all = [tr_map[sta] for sta in all_stations]
stack_black = np.mean(np.vstack(bank_all), axis=0)
ms = np.max(np.abs(stack_black)) or 1.0
stack_black = stack_black / ms
sel_ids = data.get("selected_ids", [])
sel_ids = [s for s in sel_ids if s in tr_map]
n_pass_window = int(data.get("n_pass_window", len(sel_ids)))
stack_red = stack_black
if len(sel_ids) > 0:
bank_sel = [tr_map[sta] for sta in sel_ids]
stack_red = np.mean(np.vstack(bank_sel), axis=0)
ms = np.max(np.abs(stack_red)) or 1.0
stack_red = stack_red / ms
axc.plot(t_abs[mask], stack_black[mask], color="k", lw=2, label="All aligned traces")
axc.plot(
t_abs[mask],
stack_red[mask],
color="r",
lw=2,
label=f"Pass r_win N={n_pass_window}",
)
axc.axhline(0.0, color="k", lw=0.6, alpha=0.6)
if p_time is not None:
axc.axvline(x=p_time, color="b", lw=1.5, alpha=0.7, linestyle="--", label="P arrival")
if s_time is not None:
axc.axvline(x=s_time, color="g", lw=1.5, alpha=0.7, linestyle="--", label="S arrival")
axc.set_xlim(start_time, end_time)
axc.set_ylim(-1.1, 1.1)
axc.grid(alpha=0.2)
axc.set_title(comp_titles_cmp[j], fontsize=12, fontweight="bold")
axc.set_xlabel("Time since origin (s)", fontsize=11)
if j != 2:
axc.set_xlabel("")
if j == 0:
axc.set_ylabel("Stack (norm.)", fontsize=11)
axc.legend(loc="upper right", fontsize=9)
if j == 2:
try:
origin_utc = data.get("origin")
if origin_utc is not None:
add_utc_time_axis(axc, origin_utc, tick_tz=utc_tz)
except Exception as e:
print(f"[WARN] Failed to add UTC time axis: {e}")
fig_cmp.suptitle(
f"Event {eve_id} - Stack compare (black: all aligned; red: pass r_min thresholds)",