-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalign_stack.py
More file actions
3450 lines (3091 loc) · 125 KB
/
Copy pathalign_stack.py
File metadata and controls
3450 lines (3091 loc) · 125 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 openpyxl.styles import Alignment, Font, PatternFill
from typing import cast
from matplotlib.lines import Line2D
from pathlib import Path
from datetime import datetime, timezone
import time
import json
import re
import subprocess
from obspy import UTCDateTime, Stream, Trace
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,
get_component_selection,
load_event_metadata,
load_station_lookup,
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 = 2, 8 # 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'
# 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
use_json_event_location = False
event_lat_override: float | None = None
event_lon_override: float | None = None
event_depth_override: float | None = None
event_alignment_reference = "CI_40353472"
event_stack_alignment_max_shift_sec = 0.2
use_event_static_correction = False # True: catalog shifts; False: measure event-stack residuals
event_progress_say_rate = 130
trace_peak_to_pre_p_median_min: float | None = 10.0
STATION_STATIC_MODES = frozenset({"none", "tabulated", "cross_correlation"})
station_static_mode = "cross_correlation"
station_static_file = info_root / "stations.xlsx"
station_static_column = "station static s"
_station_static_cache: dict[str, 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 resolve_station_static_mode(cfg: dict, default_mode: str) -> str:
"""Return the configured station-static mode, accepting the legacy Boolean."""
if "station_static_mode" in cfg:
mode = str(cfg["station_static_mode"]).strip().lower()
if mode not in STATION_STATIC_MODES:
raise ValueError(
"station_static_mode must be one of "
f"{sorted(STATION_STATIC_MODES)}; got {cfg['station_static_mode']!r}"
)
return mode
if "use_station_static_correction" in cfg:
return "tabulated" if bool(cfg["use_station_static_correction"]) else "cross_correlation"
if default_mode not in STATION_STATIC_MODES:
raise ValueError(f"Invalid default station-static mode: {default_mode!r}")
return default_mode
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
global data_path, event, events
global analysis_hz, input_mode
global snippets_root
global use_json_event_location
global event_lat_override, event_lon_override, event_depth_override
global event_alignment_reference
global event_stack_alignment_max_shift_sec
global use_event_static_correction
global event_progress_say_rate, trace_peak_to_pre_p_median_min
global station_static_mode, station_static_file, station_static_column
global _station_static_cache
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))
configured_trace_ratio = cfg.get(
"trace_peak_to_pre_p_median_min",
cfg.get("trace_peak_to_pre_p_median_max", trace_peak_to_pre_p_median_min),
)
trace_peak_to_pre_p_median_min = (
None if configured_trace_ratio is None else float(configured_trace_ratio)
)
if (
trace_peak_to_pre_p_median_min is not None
and trace_peak_to_pre_p_median_min < 1.0
):
raise ValueError(
"trace_peak_to_pre_p_median_min must be at least 1.0 or null; "
f"got {trace_peak_to_pre_p_median_min}"
)
all_channels = bool(cfg.get("all_channels", all_channels))
component = str(cfg.get("component", component))
align_phase = str(cfg.get("align_phase", align_phase))
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]
event_alignment_reference = str(
cfg.get("event_alignment_reference", event_alignment_reference)
)
event_stack_alignment_max_shift_sec = float(
cfg.get("event_stack_alignment_max_shift_sec", event_stack_alignment_max_shift_sec)
)
if event_stack_alignment_max_shift_sec <= 0.0:
raise ValueError(
"event_stack_alignment_max_shift_sec must be positive; "
f"got {event_stack_alignment_max_shift_sec}"
)
use_event_static_correction = bool(
cfg.get("use_event_static_correction", use_event_static_correction)
)
station_static_mode = resolve_station_static_mode(cfg, station_static_mode)
station_static_file = Path(cfg.get("station_static_file", station_static_file))
station_static_column = str(
cfg.get("station_static_column", station_static_column)
)
_station_static_cache = None
event_progress_say_rate = int(
cfg.get("event_progress_say_rate", event_progress_say_rate)
)
if event_progress_say_rate <= 0:
raise ValueError(
"event_progress_say_rate must be positive; "
f"got {event_progress_say_rate}"
)
use_json_event_location = bool(
cfg.get("use_json_event_location", use_json_event_location)
)
if use_json_event_location:
required_location = ("event_lat", "event_lon", "event_depth")
missing_location = [key for key in required_location if key not in cfg]
if missing_location:
raise ValueError(
"use_json_event_location requires "
f"{', '.join(required_location)}; missing {', '.join(missing_location)}"
)
event_lat_override = float(cfg["event_lat"])
event_lon_override = float(cfg["event_lon"])
event_depth_override = float(cfg["event_depth"])
if not -90.0 <= event_lat_override <= 90.0:
raise ValueError(f"event_lat must be between -90 and 90; got {event_lat_override}")
if not -180.0 <= event_lon_override <= 180.0:
raise ValueError(f"event_lon must be between -180 and 180; got {event_lon_override}")
if event_depth_override < 0.0:
raise ValueError(f"event_depth must be non-negative; got {event_depth_override}")
else:
event_lat_override = None
event_lon_override = None
event_depth_override = None
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 the latest JSON snapshot of run parameters for reproducibility."""
output_dir = Path(output_dir)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-2]
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,
"trace_peak_to_pre_p_median_min": trace_peak_to_pre_p_median_min,
"move_limit_sec": move_limit_sec,
"all_channels": all_channels,
"component": component,
"align_phase": align_phase,
"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_alignment_reference": event_alignment_reference,
"event_stack_alignment_max_shift_sec": event_stack_alignment_max_shift_sec,
"use_event_static_correction": use_event_static_correction,
"event_progress_say_rate": event_progress_say_rate,
"station_static_mode": station_static_mode,
"station_static_file": _snapshot_path(station_static_file),
"station_static_column": station_static_column,
"use_json_event_location": use_json_event_location,
"event_lat": event_lat_override,
"event_lon": event_lon_override,
"event_depth": event_depth_override,
"show_individual_seismograms": show_individual_seismograms,
"show_record_section_plot": show_record_section_plot,
}
snapshot_path = output_dir / "rp_latest.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 the shared align_stack output directory."""
global RUN_OUTPUT_DIR
RUN_OUTPUT_DIR = base_output_root
RUN_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"align_stack 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) / "stack_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 write_screening_failure_counts(
rows: list[dict],
run_output_dir: Path,
) -> Path:
"""Write per-event/component screening counts for the active run."""
out_file = run_output_dir / "screening_failure_counts.xlsx"
columns = [
"event_id",
"component",
"total_traces",
"accepted_traces",
"failed_any_threshold",
"failed_correlation_threshold",
"failed_noise_ratio_threshold",
"correlation_threshold_min",
"noise_ratio_threshold_min",
]
sheet_name = "Screening counts"
frame = pd.DataFrame(rows, columns=columns)
with pd.ExcelWriter(out_file, engine="openpyxl") as writer:
frame.to_excel(writer, index=False, sheet_name=sheet_name)
worksheet = writer.sheets[sheet_name]
worksheet.freeze_panes = "A2"
worksheet.auto_filter.ref = worksheet.dimensions
worksheet.row_dimensions[1].height = 34
header_fill = PatternFill("solid", fgColor="1F4E78")
for cell in worksheet[1]:
cell.font = Font(color="FFFFFF", bold=True)
cell.fill = header_fill
cell.alignment = Alignment(
horizontal="center",
vertical="center",
wrap_text=True,
)
column_widths = (16, 12, 14, 16, 20, 28, 28, 26, 26)
for column_cells, width in zip(worksheet.columns, column_widths):
worksheet.column_dimensions[column_cells[0].column_letter].width = width
for row in worksheet.iter_rows(min_row=2, min_col=3, max_col=7):
for cell in row:
cell.number_format = "0"
for row in worksheet.iter_rows(min_row=2, min_col=8, max_col=9):
for cell in row:
cell.number_format = "0.00"
print(f"Screening failure counts saved to: {out_file}")
return out_file
def event_has_zero_catalog_skip(eve_id: str) -> bool:
"""Return True only when the event's catalog skip value is numerically zero."""
if catalog_local is None or not {"evid", "skip"}.issubset(catalog_local.columns):
return False
event_rows = catalog_local.loc[
catalog_local["evid"].astype(str) == str(eve_id),
"skip",
]
if event_rows.empty:
return False
skip_value = pd.to_numeric(event_rows.iloc[0], errors="coerce")
return bool(pd.notna(skip_value) and float(skip_value) == 0.0)
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:
"""Write station residual shifts for one event/component to the statics directory."""
catalog_shift_column = catalog_time_shift_column()
catalog_shift_component_by_column = {
"time shift": "R",
"time shift T": "T",
}
catalog_shift_component = catalog_shift_component_by_column.get(catalog_shift_column)
if catalog_shift_component is None:
raise ValueError(
"Cannot derive the legacy R/T statics label from catalog column "
f"{catalog_shift_column!r}"
)
stations = sorted(set(station_shifts) & set(calc_shifts), key=lambda station: int(station))
if not stations:
print(f"[WARN] No station shifts available to write for {eve_id} {plot_comp} {align_phase_name}.")
return None
rows = []
for station in stations:
measured_shift = float(station_shifts[station]["lag_seconds"])
predicted_shift = float(calc_shifts[station])
rows.append(
{
"event_id": eve_id,
"station": station,
"component": plot_comp,
"catalog_shift_component": catalog_shift_component,
"catalog_time_shift_column": catalog_shift_column,
"phase": align_phase_name,
"frequency_min_hz": float(min_freq_hz),
"frequency_max_hz": float(max_freq_hz),
"sample_rate_hz": float(sample_rate),
"measured_shift_seconds": measured_shift,
"predicted_shift_seconds": predicted_shift,
"shift_relative_to_predicted_seconds": measured_shift - predicted_shift,
"lag_samples": int(station_shifts[station]["lag_samples"]),
"station_correlation": float(station_corr.get(station, np.nan)),
"passed_window_correlation": station in pass_window_ids,
"source_output_dir": str(save_dir),
}
)
statics_dir = Path(path_prefix) / "stack_output" / "Statics"
statics_dir.mkdir(parents=True, exist_ok=True)
frequency_label = f"{min_freq_hz:g}-{max_freq_hz:g}Hz"
out_file = statics_dir / (
f"{eve_id}_{plot_comp}_{align_phase_name}_{frequency_label}_"
f"shift{catalog_shift_component}_xcorr_statics.xlsx"
)
pd.DataFrame(rows).to_excel(out_file, index=False)
print(f"✓ Station residual shifts saved to: {out_file}")
return out_file
def apply_event_location_override(
event_depth: float,
eve_lat: float,
eve_lon: float,
) -> tuple[float, float, float]:
"""Return JSON event location when enabled; otherwise retain catalog metadata."""
if not use_json_event_location:
return event_depth, eve_lat, eve_lon
if (
event_lat_override is None
or event_lon_override is None
or event_depth_override is None
):
raise RuntimeError(
"use_json_event_location is enabled, but the JSON event location is unavailable"
)
print(
"Using JSON event location override: "
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
def catalog_time_shift_column() -> str:
"""Return the event-time-shift column shared by all waveform components."""
return "time shift"
def apply_event_origin_time_shift(eve_id: str, origin: UTCDateTime) -> UTCDateTime:
"""Apply the shared catalog event static when configured to use it."""
if not use_event_static_correction:
return origin
if catalog_local is None:
raise RuntimeError("Catalog is unavailable; cannot apply the event time shift")
shift_column = catalog_time_shift_column()
if shift_column not in catalog_local.columns:
raise RuntimeError(f'Catalog is missing the required "{shift_column}" column')
matching_rows = catalog_local.loc[catalog_local["evid"] == eve_id, shift_column]
if matching_rows.empty:
raise RuntimeError(f"Event {eve_id} is missing from the catalog time-shift table")
time_shift = float(matching_rows.iloc[0])
if not np.isfinite(time_shift):
raise RuntimeError(f"Event {eve_id} has no finite catalog time shift")
adjusted_origin = origin + time_shift
print(
f"Using catalog {shift_column}: "
f"{eve_id} origin shifted by {time_shift:+.6f} s"
)
return adjusted_origin
def event_time_shift_for_plot(eve_id: str) -> float:
"""Return the catalog event shift actually applied by this run."""
if not use_event_static_correction:
return 0.0
if catalog_local is None:
return 0.0
shift_column = catalog_time_shift_column()
if shift_column not in catalog_local.columns:
return 0.0
matching_rows = catalog_local.loc[catalog_local["evid"] == eve_id, shift_column]
if matching_rows.empty:
return 0.0
time_shift = float(matching_rows.iloc[0])
return time_shift if np.isfinite(time_shift) else 0.0
def imposed_station_shifts_for_stream(
st_comp: Stream,
ref_station_id: str,
) -> dict[str, float] | None:
"""Load station statics and express them relative to the selected reference station."""
global _station_static_cache
if station_static_mode != "tabulated":
return None
if _station_static_cache is None:
if not station_static_file.exists():
raise FileNotFoundError(f"Station static file not found: {station_static_file}")
station_df = pd.read_excel(station_static_file, dtype={"station": str})
required = {"station", station_static_column}
missing = required - set(station_df.columns)
if missing:
raise ValueError(
f"{station_static_file} is missing required columns: {sorted(missing)}"
)
station_df = station_df[["station", station_static_column]].copy()
station_df["station"] = station_df["station"].astype(str).str.zfill(5)
station_df[station_static_column] = pd.to_numeric(
station_df[station_static_column], errors="coerce"
)
station_df = station_df.dropna(subset=[station_static_column])
_station_static_cache = dict(
zip(station_df["station"], station_df[station_static_column], strict=True)
)
station_ids = {str(trace.stats.station).zfill(5) for trace in st_comp}
missing_station_ids = sorted(station_ids - set(_station_static_cache))
if missing_station_ids:
raise ValueError(
f"Station statics are missing for {len(missing_station_ids)} processed stations, "
f"including {', '.join(missing_station_ids[:10])}"
)
normalized_ref = str(ref_station_id).zfill(5)
ref_static = _station_static_cache[normalized_ref]
imposed = {
station_id: _station_static_cache[station_id] - ref_static
for station_id in station_ids
}
print(
f"Using imposed station statics from {station_static_file.name} "
f"column {station_static_column!r}; reference {normalized_ref} is set to 0 s"
)
return imposed
# ===================== 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="g", 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="tab:blue", 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):
plot_mask = mask
plot_start = start_time
plot_end = end_time
if not np.any(plot_mask):
print(
"[WARN] Requested plotting window has no samples; "
"using full available time range for 3-comp envelope."
)
plot_mask = np.ones_like(t_abs, dtype=bool)
plot_start = float(t_abs[0])
plot_end = float(t_abs[-1])
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[plot_mask], log_env[plot_mask], color="k", lw=1.5)
ax_env.set_xlim(plot_start, plot_end)
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, plot_start, plot_end)
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:
plot_mask = mask
plot_start = start_time
plot_end = end_time
if not np.any(plot_mask):
print(
"[WARN] Requested plotting window has no samples; "
"using full available time range for single-trace envelope."
)
plot_mask = np.ones_like(t_abs, dtype=bool)
plot_start = float(t_abs[0])
plot_end = float(t_abs[-1])
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[plot_mask], log_env[plot_mask], color="k", lw=1.5)
ax_env.set_xlim(plot_start, plot_end)
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, plot_start, plot_end)
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 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),
)