cangyeone commited on
Commit
d0abb68
·
verified ·
1 Parent(s): 2c2052d

Upload mini dataset utility files

Browse files
utils/hdf5_waveform_dataset.py ADDED
@@ -0,0 +1,2038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import glob
5
+ import json
6
+ import os
7
+ import warnings
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from pathlib import Path
10
+
11
+ # Disable HDF5 POSIX file locking before h5py initialises.
12
+ # Must be set before the first h5py import / H5open() call.
13
+ # Prevents h5py.File() from blocking indefinitely on lock acquisition
14
+ # (e.g. due to Spotlight, Time Machine, NFS, or a crashed prior run).
15
+ os.environ.setdefault("HDF5_USE_FILE_LOCKING", "FALSE")
16
+
17
+ import h5py
18
+ import numpy as np
19
+ import torch
20
+ from torch.utils.data import Dataset, DataLoader
21
+ from obspy import Trace, UTCDateTime
22
+ from obspy.core.inventory import Channel, Inventory, Network, Site, Station
23
+ from obspy.core.inventory.response import (
24
+ CoefficientsTypeResponseStage,
25
+ FIRResponseStage,
26
+ InstrumentSensitivity,
27
+ PolesZerosResponseStage,
28
+ PolynomialResponseStage,
29
+ Response,
30
+ ResponseStage,
31
+ )
32
+
33
+
34
+ DEFAULT_LOCATION = "--"
35
+
36
+
37
+ def parse_time(t):
38
+ return UTCDateTime(str(t))
39
+
40
+
41
+ def decode_attr(value):
42
+ if isinstance(value, bytes):
43
+ return value.decode("utf-8", errors="ignore")
44
+ if isinstance(value, np.bytes_):
45
+ return value.decode("utf-8", errors="ignore")
46
+ return value
47
+
48
+
49
+ def normalize_location(location, default=DEFAULT_LOCATION):
50
+ location = decode_attr(location)
51
+ if location is None:
52
+ return default
53
+ location = str(location).strip()
54
+ return location if location else default
55
+
56
+
57
+ def channel_suffix(channel):
58
+ return str(channel)[-1].upper()
59
+
60
+
61
+ def channel_prefix(channel):
62
+ ch = str(channel).upper()
63
+ if len(ch) >= 3:
64
+ return ch[:2]
65
+ return ch[:-1]
66
+
67
+
68
+ def component_rank(channel):
69
+ order = {
70
+ "E": 0,
71
+ "1": 0,
72
+ "N": 1,
73
+ "2": 1,
74
+ "Z": 2,
75
+ "3": 2,
76
+ }
77
+ return order.get(channel_suffix(channel), 99)
78
+
79
+
80
+ def has_three_components(channels):
81
+ suffixes = {channel_suffix(ch) for ch in channels}
82
+ return {"E", "N", "Z"}.issubset(suffixes) or {"1", "2", "3"}.issubset(suffixes)
83
+
84
+
85
+ def is_z_only_channels(channels):
86
+ suffixes = {channel_suffix(ch) for ch in channels}
87
+ return len(channels) == 1 and suffixes == {"Z"}
88
+
89
+
90
+ def get_attr(obj, name, default=None):
91
+ if name in obj.attrs:
92
+ return decode_attr(obj.attrs[name])
93
+ return default
94
+
95
+
96
+ def get_float_attr(obj, name, default=np.nan):
97
+ try:
98
+ return float(get_attr(obj, name, default))
99
+ except Exception:
100
+ return float(default)
101
+
102
+
103
+ def get_bool_attr(obj, name, default=False):
104
+ value = get_attr(obj, name, default)
105
+
106
+ if isinstance(value, (bool, np.bool_)):
107
+ return bool(value)
108
+ if isinstance(value, (int, np.integer)):
109
+ return bool(value)
110
+ if isinstance(value, str):
111
+ return value.lower() in ["true", "1", "yes"]
112
+
113
+ return bool(value)
114
+
115
+
116
+ def resolve_h5_files(h5_input):
117
+ if isinstance(h5_input, (list, tuple)):
118
+ files = []
119
+ for item in h5_input:
120
+ files.extend(resolve_h5_files(item))
121
+ return sorted(set(files))
122
+
123
+ h5_input = str(h5_input)
124
+ p = Path(h5_input)
125
+
126
+ if p.is_file():
127
+ return [str(p)]
128
+
129
+ if p.is_dir():
130
+ files = sorted(str(x) for x in p.glob("*.h5"))
131
+ files += sorted(str(x) for x in p.glob("*.hdf5"))
132
+ return files
133
+
134
+ files = sorted(glob.glob(h5_input))
135
+ if files:
136
+ return files
137
+
138
+ raise FileNotFoundError(f"No HDF5 files found from input: {h5_input}")
139
+
140
+
141
+ def make_sample_key_from_index_item(item):
142
+ """Build a stable sample key from index metadata only."""
143
+ channels = item.get("channels", [])
144
+ if not channels and item.get("channel", ""):
145
+ channels = [item.get("channel", "")]
146
+ channels = ",".join(str(x) for x in channels)
147
+
148
+ return "|".join([
149
+ str(item.get("h5_file", "")),
150
+ str(item.get("year_id", "")),
151
+ str(item.get("day_id", "")),
152
+ str(item.get("station_id", "")),
153
+ str(item.get("channel_family", item.get("channel", ""))),
154
+ channels,
155
+ ])
156
+
157
+
158
+ def make_sample_key_from_record(record):
159
+ """Build the same sample key from one output JSONL record.
160
+
161
+ Must produce a key identical to make_sample_key_from_index_item so that
162
+ the resume scanner can match written records back to index entries.
163
+
164
+ Two known pitfalls:
165
+ 1. station_id: the pick record stores it inside station_info (and now also
166
+ at the top level after the station_id fix). We try both places.
167
+ 2. Z-only replicated channels: _getitem_three stores ["EHZ","EHZ","EHZ"]
168
+ in channels_out when replicate_z_only=True, but the index entry stores
169
+ the raw ["EHZ"] list. Deduplicate before joining to match the index key.
170
+ """
171
+ channels = record.get("channels") or [] # handle None / missing
172
+ # Deduplicate for Z-only replicated samples so the key matches the index
173
+ # entry, which was built from the raw (non-replicated) channel list.
174
+ if record.get("z_only_replicated", False):
175
+ seen: set = set()
176
+ channels = [ch for ch in channels if not (ch in seen or seen.add(ch))]
177
+ channels = ",".join(str(x) for x in channels)
178
+
179
+ station_info = record.get("station_info", {}) or {}
180
+ station_id = station_info.get("station_id", record.get("station_id", ""))
181
+
182
+ return "|".join([
183
+ str(record.get("h5_file", "")),
184
+ str(record.get("year_id", "")),
185
+ str(record.get("day_id", "")),
186
+ str(station_id),
187
+ str(record.get("channel_family", record.get("channel", ""))),
188
+ channels,
189
+ ])
190
+
191
+
192
+ def _parse_jsonl_chunk(path, start_byte, end_byte, record_type):
193
+ """Parse one byte-range chunk of a JSONL file and return finished sample keys.
194
+
195
+ Called from load_finished_sample_keys via ThreadPoolExecutor. Python's
196
+ built-in json.loads (C extension) releases the GIL during parsing, so
197
+ multiple threads genuinely run in parallel for large files.
198
+
199
+ Both ``phase_pick`` and ``error`` records are treated as "finished" so that
200
+ samples which errored on a previous run are skipped on resume rather than
201
+ retried indefinitely. Error records store the pre-built key in the
202
+ ``sample_key`` field; phase_pick records reconstruct the key from individual
203
+ fields via make_sample_key_from_record.
204
+ """
205
+ keys = set()
206
+ total = 0
207
+ bad = 0
208
+ with open(path, "rb") as f:
209
+ f.seek(start_byte)
210
+ if start_byte > 0:
211
+ f.readline() # discard partial line at chunk boundary
212
+ while f.tell() < end_byte:
213
+ raw = f.readline()
214
+ if not raw:
215
+ break
216
+ line = raw.decode("utf-8", errors="ignore").strip()
217
+ if not line:
218
+ continue
219
+ total += 1
220
+ try:
221
+ record = json.loads(line)
222
+ except Exception:
223
+ bad += 1
224
+ continue
225
+ rt = record.get("record_type", "")
226
+ # Accept phase_pick records (primary output), error records
227
+ # (inference failures), and no_pick records (successful runs
228
+ # with zero detections above min_confidence). All three mean
229
+ # the station-day was fully processed and should be skipped on
230
+ # resume. error and no_pick records carry a pre-built
231
+ # sample_key field; phase_pick records are reconstructed below.
232
+ if rt in ("error", "no_pick"):
233
+ key = record.get("sample_key", "")
234
+ if key and key.strip("|"):
235
+ keys.add(key)
236
+ continue
237
+ if record_type and rt != record_type:
238
+ continue
239
+ try:
240
+ key = make_sample_key_from_record(record)
241
+ if key.strip("|"):
242
+ keys.add(key)
243
+ except Exception:
244
+ bad += 1
245
+ continue
246
+ return keys, total, bad
247
+
248
+
249
+ def load_finished_sample_keys(jsonl_file, record_type="phase_pick", num_threads=4):
250
+ """Return (finished_keys_set, total_lines, bad_lines) for resume filtering.
251
+
252
+ The JSONL file is split into ``num_threads`` byte-range chunks and parsed
253
+ concurrently via ThreadPoolExecutor. Python's json.loads (C extension)
254
+ releases the GIL during parsing, so multiple threads genuinely overlap.
255
+
256
+ Sample keys are reconstructed directly from JSONL record fields (h5_file,
257
+ year_id, day_id, station_id, channel_family, channels) — no companion
258
+ index file is needed.
259
+ """
260
+ jsonl_file = Path(jsonl_file)
261
+ finished = set()
262
+
263
+ if not jsonl_file.exists():
264
+ return finished, 0, 0
265
+
266
+ file_size = jsonl_file.stat().st_size
267
+ if file_size == 0:
268
+ return finished, 0, 0
269
+
270
+ # Don't spin up more threads than make sense for small files.
271
+ n = max(1, min(num_threads, file_size // (256 * 1024)))
272
+ chunk_size = file_size // n
273
+ chunks = [
274
+ (i * chunk_size, (i + 1) * chunk_size if i < n - 1 else file_size)
275
+ for i in range(n)
276
+ ]
277
+
278
+ def _parse(args):
279
+ return _parse_jsonl_chunk(str(jsonl_file), args[0], args[1], record_type)
280
+
281
+ if n == 1:
282
+ results = [_parse(chunks[0])]
283
+ else:
284
+ with ThreadPoolExecutor(max_workers=n) as pool:
285
+ results = list(pool.map(_parse, chunks))
286
+
287
+ total_lines = 0
288
+ bad_lines = 0
289
+ for keys, count, bad in results:
290
+ finished.update(keys)
291
+ total_lines += count
292
+ bad_lines += bad
293
+
294
+ return finished, total_lines, bad_lines
295
+
296
+
297
+ def fill_segments_to_array(
298
+ segments,
299
+ fill_value=0.0,
300
+ dtype=np.float32,
301
+ use_overlap_mask=True,
302
+ max_duration_sec=90000.0,
303
+ ):
304
+ if len(segments) == 0:
305
+ return None, None, None, None
306
+
307
+ segments = sorted(segments, key=lambda x: x["starttime"])
308
+
309
+ sampling_rate = float(segments[0]["sampling_rate"])
310
+ global_start = min(s["starttime"] for s in segments)
311
+ global_end = max(s["endtime"] for s in segments)
312
+
313
+ duration_sec = float(global_end - global_start)
314
+ npts = int(round(duration_sec * sampling_rate)) + 1
315
+
316
+ if (not np.isfinite(sampling_rate)) or sampling_rate <= 0:
317
+ raise ValueError(f"Invalid sampling_rate={sampling_rate}")
318
+ if npts <= 0:
319
+ raise ValueError(
320
+ f"Invalid npts={npts}, start={global_start}, end={global_end}, sr={sampling_rate}"
321
+ )
322
+ if max_duration_sec and max_duration_sec > 0 and duration_sec > float(max_duration_sec):
323
+ raise ValueError(
324
+ f"Abnormal segment time span: duration={duration_sec:.3f}s, "
325
+ f"npts={npts}, sr={sampling_rate}, start={global_start}, end={global_end}"
326
+ )
327
+
328
+ data = np.full(npts, fill_value, dtype=dtype)
329
+ filled = np.zeros(npts, dtype=bool) if use_overlap_mask else None
330
+
331
+ for seg in segments:
332
+ seg_data = seg["data"].astype(dtype, copy=False)
333
+
334
+ i0 = int(round((seg["starttime"] - global_start) * sampling_rate))
335
+ i1 = i0 + len(seg_data)
336
+
337
+ if i0 < 0:
338
+ seg_data = seg_data[-i0:]
339
+ i0 = 0
340
+
341
+ if i1 > npts:
342
+ seg_data = seg_data[: npts - i0]
343
+ i1 = npts
344
+
345
+ if i0 >= i1:
346
+ continue
347
+
348
+ target = slice(i0, i1)
349
+ seg_data = seg_data[: i1 - i0]
350
+
351
+ if use_overlap_mask:
352
+ mask = ~filled[target]
353
+ data_view = data[target]
354
+ data_view[mask] = seg_data[mask]
355
+ filled[target][mask] = True
356
+ else:
357
+ data[target] = seg_data
358
+
359
+ return data, global_start, global_end, sampling_rate
360
+
361
+
362
+ def resample_1d_array(x, original_sr, target_sr=None, dtype=np.float32):
363
+ """
364
+ 线性插值重采样,不依赖 scipy。
365
+
366
+ x: [T]
367
+ original_sr: 原始采样率
368
+ target_sr: 目标采样率;None 表示不重采样
369
+ """
370
+ if x is None:
371
+ return x, original_sr
372
+
373
+ x = np.asarray(x, dtype=dtype)
374
+
375
+ if target_sr is None:
376
+ return x, float(original_sr)
377
+
378
+ original_sr = float(original_sr)
379
+ target_sr = float(target_sr)
380
+
381
+ if not np.isfinite(original_sr) or original_sr <= 0:
382
+ return x, original_sr
383
+
384
+ if abs(original_sr - target_sr) < 1e-6:
385
+ return x, original_sr
386
+
387
+ if len(x) <= 1:
388
+ return x.astype(dtype, copy=False), target_sr
389
+
390
+ duration = (len(x) - 1) / original_sr
391
+ new_npts = int(round(duration * target_sr)) + 1
392
+
393
+ old_t = np.arange(len(x), dtype=np.float64) / original_sr
394
+ new_t = np.arange(new_npts, dtype=np.float64) / target_sr
395
+
396
+ y = np.interp(new_t, old_t, x).astype(dtype)
397
+
398
+ return y, target_sr
399
+
400
+
401
+ def resample_2d_array(x, original_sr, target_sr=None, dtype=np.float32):
402
+ """
403
+ x: [T, C]
404
+ """
405
+ x = np.asarray(x, dtype=dtype)
406
+
407
+ if target_sr is None:
408
+ return x, float(original_sr)
409
+
410
+ if x.ndim != 2:
411
+ raise ValueError(f"Expected 2D array [T, C], got shape={x.shape}")
412
+
413
+ ys = []
414
+ current_sr = original_sr
415
+
416
+ for i in range(x.shape[1]):
417
+ y, current_sr = resample_1d_array(
418
+ x[:, i],
419
+ original_sr=original_sr,
420
+ target_sr=target_sr,
421
+ dtype=dtype,
422
+ )
423
+ ys.append(y)
424
+
425
+ min_len = min(len(y) for y in ys)
426
+ ys = [y[:min_len] for y in ys]
427
+
428
+ return np.stack(ys, axis=1).astype(dtype), current_sr
429
+
430
+
431
+ def utc_or_none(value):
432
+ if value is None:
433
+ return None
434
+ value = decode_attr(value)
435
+ value = "" if value is None else str(value).strip()
436
+ if not value or value.lower() in {"none", "null", "nan"}:
437
+ return None
438
+ try:
439
+ return UTCDateTime(value)
440
+ except Exception:
441
+ return None
442
+
443
+
444
+ def finite_float_or_none(value):
445
+ try:
446
+ value = float(value)
447
+ except Exception:
448
+ return None
449
+ if not np.isfinite(value):
450
+ return None
451
+ return value
452
+
453
+
454
+ def finite_float(value, default=0.0):
455
+ out = finite_float_or_none(value)
456
+ return float(default) if out is None else float(out)
457
+
458
+
459
+ def int_or_none(value):
460
+ try:
461
+ return int(value)
462
+ except Exception:
463
+ return None
464
+
465
+
466
+ def complex_list_from_json(items):
467
+ out = []
468
+ for item in items or []:
469
+ if isinstance(item, dict):
470
+ out.append(complex(float(item.get("real", 0.0)), float(item.get("imag", 0.0))))
471
+ elif isinstance(item, (list, tuple)) and len(item) >= 2:
472
+ out.append(complex(float(item[0]), float(item[1])))
473
+ else:
474
+ out.append(complex(item))
475
+ return out
476
+
477
+
478
+ def _stage_common_kwargs(stage):
479
+ return {
480
+ "stage_sequence_number": int(stage.get("stage_sequence_number", 0)),
481
+ "stage_gain": finite_float(stage.get("stage_gain", 1.0), 1.0),
482
+ "stage_gain_frequency": finite_float(stage.get("stage_gain_frequency", 0.0), 0.0),
483
+ "input_units": stage.get("input_units") or "",
484
+ "output_units": stage.get("output_units") or "",
485
+ "input_units_description": stage.get("input_units_description"),
486
+ "output_units_description": stage.get("output_units_description"),
487
+ "decimation_input_sample_rate": finite_float_or_none(
488
+ stage.get("decimation_input_sample_rate")
489
+ ),
490
+ "decimation_factor": int_or_none(stage.get("decimation_factor")),
491
+ "decimation_offset": int_or_none(stage.get("decimation_offset")),
492
+ "decimation_delay": finite_float_or_none(stage.get("decimation_delay")),
493
+ "decimation_correction": finite_float_or_none(stage.get("decimation_correction")),
494
+ }
495
+
496
+
497
+ def response_stage_from_json(stage):
498
+ stage_type = stage.get("type", "ResponseStage")
499
+ common = _stage_common_kwargs(stage)
500
+
501
+ if stage_type == "PolesZerosResponseStage":
502
+ return PolesZerosResponseStage(
503
+ **common,
504
+ pz_transfer_function_type=stage.get(
505
+ "pz_transfer_function_type",
506
+ "LAPLACE (RADIANS/SECOND)",
507
+ ),
508
+ normalization_frequency=finite_float(
509
+ stage.get("normalization_frequency", common["stage_gain_frequency"]),
510
+ common["stage_gain_frequency"],
511
+ ),
512
+ normalization_factor=finite_float(stage.get("normalization_factor", 1.0), 1.0),
513
+ zeros=complex_list_from_json(stage.get("zeros", [])),
514
+ poles=complex_list_from_json(stage.get("poles", [])),
515
+ )
516
+
517
+ if stage_type == "CoefficientsTypeResponseStage":
518
+ return CoefficientsTypeResponseStage(
519
+ **common,
520
+ cf_transfer_function_type=stage.get("cf_transfer_function_type", "DIGITAL"),
521
+ numerator=list(stage.get("numerator", stage.get("numerators", [])) or []),
522
+ denominator=list(stage.get("denominator", stage.get("denominators", [])) or []),
523
+ )
524
+
525
+ if stage_type == "FIRResponseStage":
526
+ return FIRResponseStage(
527
+ **common,
528
+ symmetry=stage.get("symmetry", "NONE"),
529
+ coefficients=list(stage.get("coefficients", []) or []),
530
+ )
531
+
532
+ if stage_type == "PolynomialResponseStage":
533
+ return PolynomialResponseStage(
534
+ **common,
535
+ frequency_lower_bound=finite_float(stage.get("frequency_lower_bound", 0.0), 0.0),
536
+ frequency_upper_bound=finite_float(stage.get("frequency_upper_bound", 0.0), 0.0),
537
+ approximation_lower_bound=finite_float(
538
+ stage.get("approximation_lower_bound", 0.0),
539
+ 0.0,
540
+ ),
541
+ approximation_upper_bound=finite_float(
542
+ stage.get("approximation_upper_bound", 0.0),
543
+ 0.0,
544
+ ),
545
+ maximum_error=finite_float(stage.get("maximum_error", 0.0), 0.0),
546
+ coefficients=list(stage.get("coefficients", []) or []),
547
+ approximation_type=stage.get("approximation_type", "MACLAURIN"),
548
+ )
549
+
550
+ return ResponseStage(**common)
551
+
552
+
553
+ def response_from_json_record(record):
554
+ sensitivity = None
555
+ sens = record.get("instrument_sensitivity") or {}
556
+ if sens:
557
+ sensitivity = InstrumentSensitivity(
558
+ value=finite_float(sens.get("value", 1.0), 1.0),
559
+ frequency=finite_float(sens.get("frequency", 0.0), 0.0),
560
+ input_units=sens.get("input_units") or "",
561
+ output_units=sens.get("output_units") or "",
562
+ input_units_description=sens.get("input_units_description"),
563
+ output_units_description=sens.get("output_units_description"),
564
+ )
565
+
566
+ stages = [response_stage_from_json(stage) for stage in record.get("stages", []) or []]
567
+ return Response(
568
+ resource_id=record.get("response_id"),
569
+ instrument_sensitivity=sensitivity,
570
+ response_stages=stages,
571
+ )
572
+
573
+
574
+ def inventory_from_response_record(record, response):
575
+ start_date = utc_or_none(record.get("epoch_start"))
576
+ end_date = utc_or_none(record.get("epoch_end"))
577
+ latitude = finite_float(record.get("latitude", 0.0), 0.0)
578
+ longitude = finite_float(record.get("longitude", 0.0), 0.0)
579
+ elevation = finite_float(record.get("elevation_m", 0.0), 0.0)
580
+
581
+ channel = Channel(
582
+ code=str(record.get("channel", "")),
583
+ location_code=normalize_location(record.get("location", DEFAULT_LOCATION), DEFAULT_LOCATION),
584
+ latitude=latitude,
585
+ longitude=longitude,
586
+ elevation=elevation,
587
+ depth=finite_float(record.get("depth_m", 0.0), 0.0),
588
+ azimuth=finite_float_or_none(record.get("azimuth")),
589
+ dip=finite_float_or_none(record.get("dip")),
590
+ sample_rate=finite_float_or_none(record.get("sample_rate")),
591
+ start_date=start_date,
592
+ end_date=end_date,
593
+ response=response,
594
+ )
595
+ station = Station(
596
+ code=str(record.get("station", "")),
597
+ latitude=latitude,
598
+ longitude=longitude,
599
+ elevation=elevation,
600
+ site=Site(name=str(record.get("station", ""))),
601
+ channels=[channel],
602
+ start_date=start_date,
603
+ end_date=end_date,
604
+ )
605
+ network = Network(code=str(record.get("network", "")), stations=[station])
606
+ return Inventory(networks=[network], source="SeismicX-Cont response JSON")
607
+
608
+
609
+ def load_response_json(path):
610
+ path = Path(path)
611
+ with path.open("r", encoding="utf-8") as f:
612
+ obj = json.load(f)
613
+
614
+ by_key = {}
615
+ by_id = {}
616
+ responses = obj.get("responses", [])
617
+
618
+ for record in responses:
619
+ key = (
620
+ str(record.get("network", "")),
621
+ str(record.get("station", "")),
622
+ normalize_location(record.get("location", DEFAULT_LOCATION), DEFAULT_LOCATION),
623
+ str(record.get("channel", "")),
624
+ )
625
+ by_key.setdefault(key, []).append(record)
626
+ response_id = record.get("response_id")
627
+ if response_id:
628
+ by_id[str(response_id)] = record
629
+
630
+ for records in by_key.values():
631
+ records.sort(key=lambda item: str(item.get("epoch_start", "")))
632
+
633
+ return {
634
+ "path": str(path),
635
+ "schema": obj.get("schema", ""),
636
+ "source": obj.get("source", {}),
637
+ "summary": obj.get("summary", {}),
638
+ "responses_by_key": by_key,
639
+ "responses_by_id": by_id,
640
+ "response_count": len(responses),
641
+ }
642
+
643
+
644
+ def response_record_matches_time(record, starttime, endtime=None):
645
+ epoch_start = utc_or_none(record.get("epoch_start"))
646
+ epoch_end = utc_or_none(record.get("epoch_end"))
647
+
648
+ if starttime is None:
649
+ return True
650
+ if epoch_start is not None and starttime < epoch_start:
651
+ return False
652
+ if epoch_end is not None and starttime > epoch_end:
653
+ return False
654
+ return True
655
+
656
+
657
+ def next_pow_2(n):
658
+ n = int(n)
659
+ if n <= 1:
660
+ return 1
661
+ return 1 << (n - 1).bit_length()
662
+
663
+
664
+ def apply_response_spectrum(data, sampling_rate, response, output="VEL"):
665
+ data = np.asarray(data, dtype=np.float64)
666
+ npts = int(data.shape[0])
667
+ if npts <= 1:
668
+ return data
669
+
670
+ nfft = next_pow_2(npts)
671
+ delta = 1.0 / float(sampling_rate)
672
+ spectrum = np.fft.rfft(data, n=nfft)
673
+ resp, _freq = response.get_evalresp_response(
674
+ t_samp=delta,
675
+ nfft=nfft,
676
+ output=output,
677
+ )
678
+ spectrum *= resp
679
+ return np.fft.irfft(spectrum, n=nfft)[:npts]
680
+
681
+
682
+ def get_position_from_segments(segments):
683
+ for seg in segments:
684
+ if seg.get("location_available", False):
685
+ return {
686
+ "longitude": seg.get("longitude", np.nan),
687
+ "latitude": seg.get("latitude", np.nan),
688
+ "elevation": seg.get("elevation", np.nan),
689
+ "location_available": True,
690
+ "location_source": seg.get("location_source", ""),
691
+ "position_match_mode": seg.get("position_match_mode", ""),
692
+ "position_is_fallback": seg.get("position_is_fallback", False),
693
+ "station_position_starttime": seg.get("station_position_starttime", ""),
694
+ "station_position_endtime": seg.get("station_position_endtime", ""),
695
+ }
696
+
697
+ return {
698
+ "longitude": np.nan,
699
+ "latitude": np.nan,
700
+ "elevation": np.nan,
701
+ "location_available": False,
702
+ "location_source": "default_nan_no_station_record",
703
+ "position_match_mode": "default_nan_no_station_record",
704
+ "position_is_fallback": False,
705
+ "station_position_starttime": "",
706
+ "station_position_endtime": "",
707
+ }
708
+
709
+
710
+ class HDF5WaveformDataset(Dataset):
711
+ """
712
+ HDF5 连续波形 dataloader。
713
+
714
+ 默认行为:
715
+ 1. mode="three"
716
+ 2. 默认保留 HH/BH/EH/HN 三分量
717
+ 3. 默认保留 EHZ 单通道
718
+ 4. 默认将单通道 Z 复制为 [Z, Z, Z]
719
+ 5. 可选重采样到 target_sampling_rate
720
+
721
+ mode:
722
+ single:
723
+ 每个 channel 一个样本,返回 waveform: [T]
724
+
725
+ three:
726
+ 每个通道族一个样本,返回 waveform: [T, 3]
727
+ 分量顺序为 E/N/Z 或 1/2/3
728
+
729
+ multi:
730
+ 每个通道族一个样本,返回 waveform: [T, C]
731
+ """
732
+
733
+ def __init__(
734
+ self,
735
+ h5_file,
736
+ mode="three",
737
+ fill_value=0.0,
738
+ dtype=np.float32,
739
+ default_location=DEFAULT_LOCATION,
740
+ allowed_families=("HH", "BH", "EH", "HN"),
741
+ allowed_z_only_channels=("EHZ",),
742
+ allow_z_only=True,
743
+ replicate_z_only=True,
744
+ target_sampling_rate=None,
745
+ skip_sample_keys=None,
746
+ skip_jsonl=None,
747
+ skip_record_type="phase_pick",
748
+ keep_h5_open=True,
749
+ include_segments_metadata=True,
750
+ use_overlap_mask=True,
751
+ h5_rdcc_nbytes=8 * 1024 * 1024,
752
+ max_duration_sec=90000.0,
753
+ instrument_response_json=None,
754
+ remove_instrument_response=False,
755
+ response_output="VEL",
756
+ response_pre_filt=None,
757
+ response_water_level=60,
758
+ response_zero_mean=True,
759
+ response_taper=True,
760
+ response_taper_fraction=0.05,
761
+ response_error_behavior="raise",
762
+ simulate_instrument_response=False,
763
+ simulation_response_json=None,
764
+ simulation_response_id=None,
765
+ simulation_response_selector=None,
766
+ simulation_paz=None,
767
+ simulation_output=None,
768
+ simulation_sensitivity=True,
769
+ ):
770
+ assert mode in ["single", "three", "multi"]
771
+ assert response_error_behavior in ["raise", "warn", "skip"]
772
+
773
+ self.h5_files = resolve_h5_files(h5_file)
774
+ self.mode = mode
775
+ self.fill_value = fill_value
776
+ self.dtype = dtype
777
+ self.default_location = default_location
778
+
779
+ self.allowed_families = tuple(x.upper() for x in allowed_families)
780
+ self.allowed_z_only_channels = tuple(x.upper() for x in allowed_z_only_channels)
781
+ self.allow_z_only = bool(allow_z_only)
782
+ self.replicate_z_only = bool(replicate_z_only)
783
+ self.target_sampling_rate = target_sampling_rate
784
+ self.keep_h5_open = bool(keep_h5_open)
785
+ self.include_segments_metadata = bool(include_segments_metadata)
786
+ self.use_overlap_mask = bool(use_overlap_mask)
787
+ # HDF5 raw-data chunk cache per open file handle. h5py default is 1 MB.
788
+ # 8 MB is a good balance for single-pass inference: large enough to avoid
789
+ # re-reading chunks within one channel, small enough not to waste RAM.
790
+ # (Training / repeated-access workloads can benefit from a larger value.)
791
+ self.h5_rdcc_nbytes = max(0, int(h5_rdcc_nbytes))
792
+ # Hard safety limit for one consolidated channel waveform.
793
+ # Default 90000 s = 25 h, enough for one UTC day with small tolerance.
794
+ self.max_duration_sec = float(max_duration_sec) if max_duration_sec is not None else 0.0
795
+ self.instrument_response_json = (
796
+ str(instrument_response_json) if instrument_response_json is not None else None
797
+ )
798
+ self.remove_instrument_response = bool(remove_instrument_response)
799
+ self.response_output = str(response_output).upper() if response_output is not None else "VEL"
800
+ self.response_pre_filt = (
801
+ tuple(float(x) for x in response_pre_filt)
802
+ if response_pre_filt is not None else None
803
+ )
804
+ self.response_water_level = response_water_level
805
+ self.response_zero_mean = bool(response_zero_mean)
806
+ self.response_taper = bool(response_taper)
807
+ self.response_taper_fraction = float(response_taper_fraction)
808
+ self.response_error_behavior = response_error_behavior
809
+ self.simulate_instrument_response = bool(simulate_instrument_response)
810
+ self.simulation_response_json = (
811
+ str(simulation_response_json) if simulation_response_json is not None else None
812
+ )
813
+ self.simulation_response_id = (
814
+ str(simulation_response_id) if simulation_response_id is not None else None
815
+ )
816
+ self.simulation_response_selector = dict(simulation_response_selector or {})
817
+ self.simulation_paz = simulation_paz
818
+ self.simulation_output = (
819
+ str(simulation_output).upper()
820
+ if simulation_output is not None else self.response_output
821
+ )
822
+ self.simulation_sensitivity = bool(simulation_sensitivity)
823
+
824
+ if self.remove_instrument_response and self.instrument_response_json is None:
825
+ raise ValueError(
826
+ "instrument_response_json is required when remove_instrument_response is enabled."
827
+ )
828
+ if self.simulate_instrument_response and (
829
+ self.simulation_paz is None
830
+ and self.simulation_response_id is None
831
+ and not self.simulation_response_selector
832
+ and self.simulation_response_json is None
833
+ ):
834
+ raise ValueError(
835
+ "simulate_instrument_response=True requires simulation_paz, "
836
+ "simulation_response_id, simulation_response_selector, or "
837
+ "simulation_response_json."
838
+ )
839
+ if self.simulate_instrument_response and (
840
+ self.simulation_response_json is None
841
+ and self.simulation_paz is None
842
+ and self.instrument_response_json is None
843
+ ):
844
+ raise ValueError(
845
+ "simulation_response_json is required when simulation selects a "
846
+ "response record and instrument_response_json is not set."
847
+ )
848
+
849
+ # Per-process HDF5 handle cache. DataLoader workers get their own cache.
850
+ self._h5_cache = {}
851
+ self._response_store = None
852
+ self._simulation_response_store = None
853
+ self._response_object_cache = {}
854
+ self._inventory_cache = {}
855
+ self._simulation_response_record = None
856
+ self._simulation_response_object = None
857
+
858
+ self.index = []
859
+ self._build_index()
860
+
861
+ # Resume filtering happens on metadata-only index entries. Removed samples
862
+ # will never enter __getitem__, so their waveform data are not read.
863
+ self.finished_sample_keys = set(skip_sample_keys or [])
864
+ self.skip_jsonl_stats = None
865
+ if skip_jsonl is not None:
866
+ keys, total_lines, bad_lines = load_finished_sample_keys(
867
+ skip_jsonl,
868
+ record_type=skip_record_type,
869
+ )
870
+ self.finished_sample_keys.update(keys)
871
+ self.skip_jsonl_stats = {
872
+ "jsonl_file": str(skip_jsonl),
873
+ "total_lines": total_lines,
874
+ "bad_lines": bad_lines,
875
+ "finished_keys": len(keys),
876
+ }
877
+
878
+ self.original_index_size = len(self.index)
879
+ self.filtered_index_size = 0
880
+ if self.finished_sample_keys:
881
+ self.filter_index_by_finished_keys(self.finished_sample_keys)
882
+
883
+ def __getstate__(self):
884
+ """Do not pickle open h5py handles into DataLoader workers."""
885
+ state = self.__dict__.copy()
886
+ state["_h5_cache"] = {}
887
+ state["_response_store"] = None
888
+ state["_simulation_response_store"] = None
889
+ state["_response_object_cache"] = {}
890
+ state["_inventory_cache"] = {}
891
+ state["_simulation_response_record"] = None
892
+ state["_simulation_response_object"] = None
893
+ return state
894
+
895
+ def __setstate__(self, state):
896
+ """Restore state in a worker process with a fresh, empty handle cache.
897
+
898
+ Called by pickle when DataLoader workers deserialize the dataset. Ensures
899
+ _h5_cache is always empty in the new process regardless of start method
900
+ (spawn, forkserver, or fork), so each worker opens its own HDF5 handles
901
+ lazily on the first __getitem__ call.
902
+ """
903
+ self.__dict__.update(state)
904
+ self._h5_cache = {} # always start clean in every process
905
+ self._response_object_cache = {}
906
+ self._inventory_cache = {}
907
+
908
+ def close(self):
909
+ """Close all cached HDF5 handles and free their chunk + metadata caches."""
910
+ cache = getattr(self, "_h5_cache", {})
911
+ for h5 in list(cache.values()):
912
+ try:
913
+ h5.close()
914
+ except Exception:
915
+ pass
916
+ cache.clear()
917
+
918
+ def flush_h5_cache(self):
919
+ """Close the current HDF5 handle and clear _h5_cache.
920
+
921
+ Call this periodically (e.g. every N samples) to flush the per-file
922
+ HDF5 metadata cache that the C library accumulates as it visits
923
+ dataset groups. The handle is reopened lazily on the next
924
+ __getitem__ call, so this is safe to call at any time between samples.
925
+ """
926
+ self.close()
927
+
928
+ def __del__(self):
929
+ try:
930
+ self.close()
931
+ except Exception:
932
+ pass
933
+
934
+ def _get_h5_handle(self, h5_file):
935
+ rdcc = getattr(self, "h5_rdcc_nbytes", 8 * 1024 * 1024)
936
+
937
+ if not self.keep_h5_open:
938
+ return h5py.File(h5_file, "r", rdcc_nbytes=rdcc)
939
+
940
+ if not hasattr(self, "_h5_cache"):
941
+ self._h5_cache = {}
942
+
943
+ h5 = self._h5_cache.get(h5_file)
944
+ if h5 is None:
945
+ # Inference is a single pass over sorted files: when a new file is
946
+ # requested the previous file will not be accessed again. Close all
947
+ # stale handles immediately so their HDF5 chunk caches (rdcc_nbytes
948
+ # each) are released rather than accumulating for the life of the
949
+ # process. Keeping only the current file's handle preserves the
950
+ # within-file I/O benefit while bounding cache memory to O(1) files.
951
+ for _f, _h in list(self._h5_cache.items()):
952
+ if _f != h5_file:
953
+ try:
954
+ _h.close()
955
+ except Exception:
956
+ pass
957
+ self._h5_cache.pop(_f, None)
958
+ h5 = h5py.File(h5_file, "r", rdcc_nbytes=rdcc)
959
+ self._h5_cache[h5_file] = h5
960
+ return h5
961
+
962
+ def sample_key(self, idx_or_item):
963
+ if isinstance(idx_or_item, int):
964
+ item = self.index[idx_or_item]
965
+ else:
966
+ item = idx_or_item
967
+ return make_sample_key_from_index_item(item)
968
+
969
+ def filter_index_by_finished_keys(self, finished_keys):
970
+ """Remove finished samples from self.index before waveform reading."""
971
+ finished_keys = set(finished_keys or [])
972
+ if not finished_keys:
973
+ return 0
974
+
975
+ old_n = len(self.index)
976
+ self.index = [
977
+ item for item in self.index
978
+ if make_sample_key_from_index_item(item) not in finished_keys
979
+ ]
980
+ removed = old_n - len(self.index)
981
+ self.filtered_index_size += removed
982
+ return removed
983
+
984
+ def filter_index_by_jsonl(self, jsonl_file, record_type="phase_pick"):
985
+ keys, total_lines, bad_lines = load_finished_sample_keys(
986
+ jsonl_file,
987
+ record_type=record_type,
988
+ )
989
+ removed = self.filter_index_by_finished_keys(keys)
990
+ self.skip_jsonl_stats = {
991
+ "jsonl_file": str(jsonl_file),
992
+ "total_lines": total_lines,
993
+ "bad_lines": bad_lines,
994
+ "finished_keys": len(keys),
995
+ "removed_from_index": removed,
996
+ }
997
+ return removed, keys, total_lines, bad_lines
998
+
999
+ def _ensure_response_store(self):
1000
+ if self._response_store is None:
1001
+ if self.instrument_response_json is None:
1002
+ raise ValueError("instrument_response_json is not configured")
1003
+ self._response_store = load_response_json(self.instrument_response_json)
1004
+ return self._response_store
1005
+
1006
+ def _ensure_simulation_response_store(self):
1007
+ if self._simulation_response_store is None:
1008
+ path = self.simulation_response_json or self.instrument_response_json
1009
+ if path is None:
1010
+ raise ValueError("No simulation response JSON is configured")
1011
+ self._simulation_response_store = load_response_json(path)
1012
+ return self._simulation_response_store
1013
+
1014
+ def _get_response_object(self, record):
1015
+ response_id = str(record.get("response_id", ""))
1016
+ cache_key = response_id or id(record)
1017
+ if cache_key not in self._response_object_cache:
1018
+ self._response_object_cache[cache_key] = response_from_json_record(record)
1019
+ return self._response_object_cache[cache_key]
1020
+
1021
+ def _get_inventory(self, record):
1022
+ response_id = str(record.get("response_id", ""))
1023
+ cache_key = response_id or id(record)
1024
+ if cache_key not in self._inventory_cache:
1025
+ response = self._get_response_object(record)
1026
+ self._inventory_cache[cache_key] = inventory_from_response_record(record, response)
1027
+ return self._inventory_cache[cache_key]
1028
+
1029
+ def _find_response_record(self, network, station, location, channel, starttime, endtime=None):
1030
+ store = self._ensure_response_store()
1031
+ key = (
1032
+ str(network),
1033
+ str(station),
1034
+ normalize_location(location, self.default_location),
1035
+ str(channel),
1036
+ )
1037
+ candidates = store["responses_by_key"].get(key, [])
1038
+ for record in candidates:
1039
+ if response_record_matches_time(record, starttime, endtime):
1040
+ return record
1041
+ return None
1042
+
1043
+ def _select_simulation_response_record(self):
1044
+ if self._simulation_response_record is not None:
1045
+ return self._simulation_response_record
1046
+
1047
+ store = self._ensure_simulation_response_store()
1048
+ record = None
1049
+
1050
+ if self.simulation_response_id:
1051
+ record = store["responses_by_id"].get(self.simulation_response_id)
1052
+ if record is None:
1053
+ raise KeyError(
1054
+ f"simulation_response_id not found: {self.simulation_response_id}"
1055
+ )
1056
+ elif self.simulation_response_selector:
1057
+ sel = self.simulation_response_selector
1058
+ key = (
1059
+ str(sel.get("network", "")),
1060
+ str(sel.get("station", "")),
1061
+ normalize_location(sel.get("location", self.default_location), self.default_location),
1062
+ str(sel.get("channel", "")),
1063
+ )
1064
+ starttime = utc_or_none(sel.get("time")) or utc_or_none(sel.get("starttime"))
1065
+ candidates = store["responses_by_key"].get(key, [])
1066
+ for item in candidates:
1067
+ if response_record_matches_time(item, starttime):
1068
+ record = item
1069
+ break
1070
+ if record is None:
1071
+ raise KeyError(f"simulation_response_selector did not match any response: {sel}")
1072
+ else:
1073
+ records_by_id = store["responses_by_id"]
1074
+ if len(records_by_id) != 1:
1075
+ raise ValueError(
1076
+ "simulation_response_json must contain exactly one response unless "
1077
+ "simulation_response_id or simulation_response_selector is provided."
1078
+ )
1079
+ record = next(iter(records_by_id.values()))
1080
+
1081
+ self._simulation_response_record = record
1082
+ self._simulation_response_object = self._get_response_object(record)
1083
+ return record
1084
+
1085
+ def _handle_response_error(self, message):
1086
+ if self.response_error_behavior == "raise":
1087
+ raise RuntimeError(message)
1088
+ if self.response_error_behavior == "warn":
1089
+ warnings.warn(message, RuntimeWarning, stacklevel=2)
1090
+ return None
1091
+
1092
+ def _apply_instrument_processing(
1093
+ self,
1094
+ waveform,
1095
+ segments,
1096
+ channel,
1097
+ starttime,
1098
+ endtime,
1099
+ sampling_rate,
1100
+ ):
1101
+ metadata = {
1102
+ "remove_instrument_response": self.remove_instrument_response,
1103
+ "simulate_instrument_response": self.simulate_instrument_response,
1104
+ "response_output": self.response_output,
1105
+ "simulation_output": self.simulation_output,
1106
+ "response_id": "",
1107
+ "response_epoch_start": "",
1108
+ "response_epoch_end": "",
1109
+ "simulation_response_id": "",
1110
+ "error": "",
1111
+ "processed": False,
1112
+ }
1113
+
1114
+ if waveform is None or len(waveform) == 0:
1115
+ return waveform, metadata
1116
+ if not self.remove_instrument_response and not self.simulate_instrument_response:
1117
+ return waveform, metadata
1118
+
1119
+ first_segment = segments[0] if segments else {}
1120
+ network = first_segment.get("network", "")
1121
+ station = first_segment.get("station", "")
1122
+ location = first_segment.get("location", self.default_location)
1123
+ channel = first_segment.get("channel", channel)
1124
+
1125
+ try:
1126
+ trace = Trace(
1127
+ data=np.asarray(waveform, dtype=np.float64),
1128
+ header={
1129
+ "network": str(network),
1130
+ "station": str(station),
1131
+ "location": normalize_location(location, self.default_location),
1132
+ "channel": str(channel),
1133
+ "starttime": starttime,
1134
+ "sampling_rate": float(sampling_rate),
1135
+ },
1136
+ )
1137
+
1138
+ if self.remove_instrument_response:
1139
+ record = self._find_response_record(
1140
+ network,
1141
+ station,
1142
+ location,
1143
+ channel,
1144
+ starttime,
1145
+ endtime=endtime,
1146
+ )
1147
+ if record is None:
1148
+ key = ".".join([
1149
+ str(network),
1150
+ str(station),
1151
+ normalize_location(location, self.default_location),
1152
+ str(channel),
1153
+ ])
1154
+ raise KeyError(f"No response found for {key} at {starttime}")
1155
+
1156
+ metadata.update(
1157
+ {
1158
+ "response_id": record.get("response_id", ""),
1159
+ "response_epoch_start": record.get("epoch_start", ""),
1160
+ "response_epoch_end": record.get("epoch_end", ""),
1161
+ }
1162
+ )
1163
+ trace.remove_response(
1164
+ inventory=self._get_inventory(record),
1165
+ output=self.response_output,
1166
+ water_level=self.response_water_level,
1167
+ pre_filt=self.response_pre_filt,
1168
+ zero_mean=self.response_zero_mean,
1169
+ taper=self.response_taper,
1170
+ taper_fraction=self.response_taper_fraction,
1171
+ )
1172
+
1173
+ if self.simulate_instrument_response:
1174
+ if self.simulation_paz is not None:
1175
+ trace.simulate(
1176
+ paz_remove=None,
1177
+ paz_simulate=self.simulation_paz,
1178
+ remove_sensitivity=False,
1179
+ simulate_sensitivity=self.simulation_sensitivity,
1180
+ )
1181
+ metadata["simulation_response_id"] = "simulation_paz"
1182
+ else:
1183
+ sim_record = self._select_simulation_response_record()
1184
+ sim_response = self._simulation_response_object
1185
+ trace.data = apply_response_spectrum(
1186
+ trace.data,
1187
+ sampling_rate=trace.stats.sampling_rate,
1188
+ response=sim_response,
1189
+ output=self.simulation_output,
1190
+ )
1191
+ metadata["simulation_response_id"] = sim_record.get("response_id", "")
1192
+
1193
+ metadata["processed"] = True
1194
+ return np.asarray(trace.data, dtype=self.dtype), metadata
1195
+ except Exception as exc:
1196
+ metadata["error"] = str(exc)
1197
+ self._handle_response_error(str(exc))
1198
+ return np.asarray(waveform, dtype=self.dtype), metadata
1199
+
1200
+ def _is_allowed_channel(self, channel):
1201
+ ch = str(channel).upper()
1202
+ prefix = channel_prefix(ch)
1203
+
1204
+ if prefix in self.allowed_families:
1205
+ return True
1206
+
1207
+ if self.allow_z_only and ch in self.allowed_z_only_channels:
1208
+ return True
1209
+
1210
+ return False
1211
+
1212
+ def _is_allowed_family_sample(self, prefix, family_channels):
1213
+ prefix = str(prefix).upper()
1214
+ family_channels = [str(x).upper() for x in family_channels]
1215
+
1216
+ if prefix not in self.allowed_families:
1217
+ if not any(ch in self.allowed_z_only_channels for ch in family_channels):
1218
+ return False
1219
+
1220
+ if self.mode == "multi":
1221
+ return True
1222
+
1223
+ if has_three_components(family_channels):
1224
+ return True
1225
+
1226
+ if self.allow_z_only:
1227
+ z_only = [
1228
+ ch for ch in family_channels
1229
+ if ch in self.allowed_z_only_channels
1230
+ ]
1231
+ return len(z_only) > 0
1232
+
1233
+ return False
1234
+
1235
+ def _build_index(self):
1236
+ for h5_file in self.h5_files:
1237
+ with h5py.File(h5_file, "r") as h5:
1238
+ for year_id in sorted(h5.keys()):
1239
+ year_grp = h5[year_id]
1240
+ if not isinstance(year_grp, h5py.Group):
1241
+ continue
1242
+
1243
+ for day_id in sorted(year_grp.keys()):
1244
+ day_grp = year_grp[day_id]
1245
+ if not isinstance(day_grp, h5py.Group):
1246
+ continue
1247
+
1248
+ if "stations" not in day_grp:
1249
+ continue
1250
+
1251
+ stations_grp = day_grp["stations"]
1252
+
1253
+ for station_id in sorted(stations_grp.keys()):
1254
+ station_grp = stations_grp[station_id]
1255
+
1256
+ if "waveform" not in station_grp:
1257
+ continue
1258
+
1259
+ waveform_grp = station_grp["waveform"]
1260
+ channels = sorted(
1261
+ ch for ch in waveform_grp.keys()
1262
+ if self._is_allowed_channel(ch)
1263
+ )
1264
+
1265
+ if len(channels) == 0:
1266
+ continue
1267
+
1268
+ if self.mode == "single":
1269
+ for cha in channels:
1270
+ self.index.append(
1271
+ {
1272
+ "h5_file": h5_file,
1273
+ "year_id": year_id,
1274
+ "day_id": day_id,
1275
+ "station_id": station_id,
1276
+ "channel": cha,
1277
+ }
1278
+ )
1279
+ continue
1280
+
1281
+ families = {}
1282
+ for cha in channels:
1283
+ prefix = channel_prefix(cha)
1284
+ families.setdefault(prefix, []).append(cha)
1285
+
1286
+ for prefix, family_channels in families.items():
1287
+ family_channels = sorted(
1288
+ family_channels,
1289
+ key=component_rank,
1290
+ )
1291
+
1292
+ if not self._is_allowed_family_sample(prefix, family_channels):
1293
+ continue
1294
+
1295
+ self.index.append(
1296
+ {
1297
+ "h5_file": h5_file,
1298
+ "year_id": year_id,
1299
+ "day_id": day_id,
1300
+ "station_id": station_id,
1301
+ "channel_family": prefix,
1302
+ "channels": family_channels,
1303
+ }
1304
+ )
1305
+
1306
+ def __len__(self):
1307
+ return len(self.index)
1308
+
1309
+ def _get_station_group(self, h5, year_id, day_id, station_id):
1310
+ return h5[year_id][day_id]["stations"][station_id]
1311
+
1312
+ def _read_position_history(self, station_grp):
1313
+ if "position_history" not in station_grp:
1314
+ return []
1315
+
1316
+ pos_grp = station_grp["position_history"]
1317
+ out = []
1318
+
1319
+ for key in sorted(pos_grp.keys(), key=lambda x: int(x) if str(x).isdigit() else str(x)):
1320
+ item = pos_grp[key]
1321
+
1322
+ out.append(
1323
+ {
1324
+ "network": get_attr(item, "network", ""),
1325
+ "station": get_attr(item, "station", ""),
1326
+ "location": normalize_location(
1327
+ get_attr(item, "location", self.default_location),
1328
+ self.default_location,
1329
+ ),
1330
+ "longitude": get_float_attr(item, "longitude", np.nan),
1331
+ "latitude": get_float_attr(item, "latitude", np.nan),
1332
+ "elevation": get_float_attr(item, "elevation", np.nan),
1333
+ "starttime": get_attr(item, "starttime", ""),
1334
+ "endtime": get_attr(item, "endtime", ""),
1335
+ }
1336
+ )
1337
+
1338
+ return out
1339
+
1340
+ def _read_station_attrs(self, station_grp):
1341
+ location = normalize_location(
1342
+ get_attr(station_grp, "location", self.default_location),
1343
+ self.default_location,
1344
+ )
1345
+
1346
+ return {
1347
+ "station_id": get_attr(station_grp, "station_id", ""),
1348
+ "network": get_attr(station_grp, "network", ""),
1349
+ "station": get_attr(station_grp, "station", ""),
1350
+ "location": location,
1351
+ "location_is_default": get_bool_attr(
1352
+ station_grp,
1353
+ "location_is_default",
1354
+ location == self.default_location,
1355
+ ),
1356
+ "longitude": get_float_attr(station_grp, "longitude", np.nan),
1357
+ "latitude": get_float_attr(station_grp, "latitude", np.nan),
1358
+ "elevation": get_float_attr(station_grp, "elevation", np.nan),
1359
+ "location_available": get_bool_attr(station_grp, "location_available", False),
1360
+ "location_source": get_attr(station_grp, "location_source", ""),
1361
+ "position_match_mode": get_attr(station_grp, "position_match_mode", ""),
1362
+ "position_is_fallback": get_bool_attr(station_grp, "position_is_fallback", False),
1363
+ "station_position_starttime": get_attr(station_grp, "station_position_starttime", ""),
1364
+ "station_position_endtime": get_attr(station_grp, "station_position_endtime", ""),
1365
+ "instrument_time_range_start": get_attr(station_grp, "instrument_time_range_start", ""),
1366
+ "instrument_time_range_end": get_attr(station_grp, "instrument_time_range_end", ""),
1367
+ "position_history": self._read_position_history(station_grp),
1368
+ }
1369
+
1370
+ def _read_channel_attrs(self, channel_grp):
1371
+ return {
1372
+ "channel": get_attr(channel_grp, "channel", ""),
1373
+ "segment_count": int(get_attr(channel_grp, "segment_count", 0)),
1374
+ "starttime": get_attr(channel_grp, "starttime", ""),
1375
+ "endtime": get_attr(channel_grp, "endtime", ""),
1376
+ "longitude": get_float_attr(channel_grp, "longitude", np.nan),
1377
+ "latitude": get_float_attr(channel_grp, "latitude", np.nan),
1378
+ "elevation": get_float_attr(channel_grp, "elevation", np.nan),
1379
+ "location_available": get_bool_attr(channel_grp, "location_available", False),
1380
+ "location_source": get_attr(channel_grp, "location_source", ""),
1381
+ "position_match_mode": get_attr(channel_grp, "position_match_mode", ""),
1382
+ "position_is_fallback": get_bool_attr(channel_grp, "position_is_fallback", False),
1383
+ "station_position_starttime": get_attr(channel_grp, "station_position_starttime", ""),
1384
+ "station_position_endtime": get_attr(channel_grp, "station_position_endtime", ""),
1385
+ }
1386
+
1387
+ def _read_channel_segments(self, h5, year_id, day_id, station_id, channel):
1388
+ station_grp = self._get_station_group(h5, year_id, day_id, station_id)
1389
+ channel_grp = station_grp["waveform"][channel]
1390
+
1391
+ segments = []
1392
+
1393
+ for ds_key in sorted(channel_grp.keys(), key=lambda x: int(x)):
1394
+ ds = channel_grp[ds_key]
1395
+
1396
+ segments.append(
1397
+ {
1398
+ "data": ds[()],
1399
+ "segment_index": int(get_attr(ds, "segment_index", ds_key)),
1400
+ "starttime": parse_time(get_attr(ds, "starttime", "")),
1401
+ "endtime": parse_time(get_attr(ds, "endtime", "")),
1402
+ "sampling_rate": float(get_attr(ds, "sampling_rate", np.nan)),
1403
+ "delta": float(get_attr(ds, "delta", np.nan)),
1404
+ "npts": int(get_attr(ds, "npts", ds.shape[0])),
1405
+ "network": get_attr(ds, "network", ""),
1406
+ "station": get_attr(ds, "station", ""),
1407
+ "location": normalize_location(
1408
+ get_attr(ds, "location", self.default_location),
1409
+ self.default_location,
1410
+ ),
1411
+ "channel": get_attr(ds, "channel", channel),
1412
+ "mseed_source_file": get_attr(ds, "mseed_source_file", ""),
1413
+ "dtype": get_attr(ds, "dtype", str(ds.dtype)),
1414
+ "longitude": get_float_attr(ds, "longitude", np.nan),
1415
+ "latitude": get_float_attr(ds, "latitude", np.nan),
1416
+ "elevation": get_float_attr(ds, "elevation", np.nan),
1417
+ "location_available": get_bool_attr(ds, "location_available", False),
1418
+ "location_source": get_attr(ds, "location_source", ""),
1419
+ "station_position_starttime": get_attr(ds, "station_position_starttime", ""),
1420
+ "station_position_endtime": get_attr(ds, "station_position_endtime", ""),
1421
+ "position_match_mode": get_attr(ds, "position_match_mode", ""),
1422
+ "position_is_fallback": get_bool_attr(ds, "position_is_fallback", False),
1423
+ }
1424
+ )
1425
+
1426
+ channel_info = self._read_channel_attrs(channel_grp)
1427
+ return segments, channel_info
1428
+
1429
+ def __getitem__(self, idx):
1430
+ item = self.index[idx]
1431
+ h5_file = item["h5_file"]
1432
+
1433
+ h5 = self._get_h5_handle(h5_file)
1434
+ should_close = not self.keep_h5_open
1435
+
1436
+ try:
1437
+ year_id = item["year_id"]
1438
+ day_id = item["day_id"]
1439
+ station_id = item["station_id"]
1440
+
1441
+ station_grp = self._get_station_group(h5, year_id, day_id, station_id)
1442
+ station_info = self._read_station_attrs(station_grp)
1443
+
1444
+ if self.mode == "single":
1445
+ return self._getitem_single(h5, item, station_info)
1446
+
1447
+ if self.mode == "three":
1448
+ return self._getitem_three(h5, item, station_info)
1449
+
1450
+ if self.mode == "multi":
1451
+ return self._getitem_multi(h5, item, station_info)
1452
+
1453
+ raise ValueError(f"Unsupported mode: {self.mode}")
1454
+ finally:
1455
+ if should_close:
1456
+ try:
1457
+ h5.close()
1458
+ except Exception:
1459
+ pass
1460
+
1461
+ def _getitem_single(self, h5, item, station_info):
1462
+ year_id = item["year_id"]
1463
+ day_id = item["day_id"]
1464
+ station_id = item["station_id"]
1465
+ channel = item["channel"]
1466
+
1467
+ segments, channel_info = self._read_channel_segments(
1468
+ h5, year_id, day_id, station_id, channel
1469
+ )
1470
+
1471
+ waveform, starttime, endtime, original_sr = fill_segments_to_array(
1472
+ segments,
1473
+ fill_value=self.fill_value,
1474
+ dtype=self.dtype,
1475
+ use_overlap_mask=self.use_overlap_mask,
1476
+ max_duration_sec=self.max_duration_sec,
1477
+ )
1478
+ # Free raw HDF5 data arrays immediately after consolidation.
1479
+ # For day-long waveforms each segment["data"] can be tens of MB;
1480
+ # holding them until function return causes unbounded RSS growth.
1481
+ for _seg in segments:
1482
+ _seg.pop("data", None)
1483
+
1484
+ if waveform is None:
1485
+ waveform = np.zeros(0, dtype=self.dtype)
1486
+
1487
+ waveform, instrument_processing = self._apply_instrument_processing(
1488
+ waveform,
1489
+ segments=segments,
1490
+ channel=channel,
1491
+ starttime=starttime,
1492
+ endtime=endtime,
1493
+ sampling_rate=original_sr,
1494
+ )
1495
+
1496
+ waveform, current_sr = resample_1d_array(
1497
+ waveform,
1498
+ original_sr=original_sr,
1499
+ target_sr=self.target_sampling_rate,
1500
+ dtype=self.dtype,
1501
+ )
1502
+
1503
+ position_info = get_position_from_segments(segments)
1504
+ station_info = dict(station_info)
1505
+ station_info.update(position_info)
1506
+
1507
+ return {
1508
+ "mode": "single",
1509
+ "h5_file": item["h5_file"],
1510
+ "year_id": year_id,
1511
+ "day_id": day_id,
1512
+ "station_id": station_id,
1513
+ "station_info": station_info,
1514
+ "channel_info": channel_info,
1515
+ "channel": channel,
1516
+ "channels": [channel],
1517
+ "instrument_processing": instrument_processing,
1518
+ "waveform": torch.from_numpy(waveform),
1519
+ "segments": (
1520
+ [
1521
+ {k: v for k, v in seg.items() if k != "data"}
1522
+ for seg in segments
1523
+ ]
1524
+ if self.include_segments_metadata else []
1525
+ ),
1526
+ "starttime": str(starttime) if starttime is not None else "",
1527
+ "endtime": str(endtime) if endtime is not None else "",
1528
+ "original_sampling_rate": original_sr,
1529
+ "sampling_rate": current_sr,
1530
+ "target_sampling_rate": self.target_sampling_rate,
1531
+ "resampled": (
1532
+ self.target_sampling_rate is not None
1533
+ and np.isfinite(original_sr)
1534
+ and abs(float(original_sr) - float(self.target_sampling_rate)) > 1e-6
1535
+ ),
1536
+ "npts_original_estimated": int(round((endtime - starttime) * original_sr)) + 1
1537
+ if starttime is not None and endtime is not None and np.isfinite(original_sr)
1538
+ else 0,
1539
+ "npts": waveform.shape[0],
1540
+ }
1541
+
1542
+ def _select_three_channels(self, candidate_channels):
1543
+ candidate_channels = sorted(candidate_channels, key=component_rank)
1544
+
1545
+ selected = {}
1546
+
1547
+ for cha in candidate_channels:
1548
+ suf = channel_suffix(cha)
1549
+
1550
+ if suf in ["E", "1"] and 0 not in selected:
1551
+ selected[0] = cha
1552
+ elif suf in ["N", "2"] and 1 not in selected:
1553
+ selected[1] = cha
1554
+ elif suf in ["Z", "3"] and 2 not in selected:
1555
+ selected[2] = cha
1556
+
1557
+ is_z_only = False
1558
+ z_only_replicated = False
1559
+
1560
+ if not has_three_components(candidate_channels):
1561
+ z_candidates = [
1562
+ ch for ch in candidate_channels
1563
+ if str(ch).upper() in self.allowed_z_only_channels
1564
+ ]
1565
+
1566
+ if len(z_candidates) > 0:
1567
+ zch = z_candidates[0]
1568
+ selected = {2: zch}
1569
+ is_z_only = True
1570
+
1571
+ if self.replicate_z_only:
1572
+ selected = {0: zch, 1: zch, 2: zch}
1573
+ z_only_replicated = True
1574
+
1575
+ return selected, is_z_only, z_only_replicated
1576
+
1577
+ def _getitem_three(self, h5, item, station_info):
1578
+ year_id = item["year_id"]
1579
+ day_id = item["day_id"]
1580
+ station_id = item["station_id"]
1581
+ channel_family = item["channel_family"]
1582
+ candidate_channels = item["channels"]
1583
+
1584
+ selected, is_z_only, z_only_replicated = self._select_three_channels(
1585
+ candidate_channels
1586
+ )
1587
+
1588
+ arrays = {}
1589
+ starts = []
1590
+ ends = []
1591
+ srs = []
1592
+ all_segments = []
1593
+ channel_infos = {}
1594
+ instrument_processing = {}
1595
+
1596
+ unique_channels = sorted(set(selected.values()))
1597
+ channel_arrays = {}
1598
+
1599
+ for cha in unique_channels:
1600
+ segments, channel_info = self._read_channel_segments(
1601
+ h5, year_id, day_id, station_id, cha
1602
+ )
1603
+
1604
+ all_segments.extend(segments)
1605
+ channel_infos[cha] = channel_info
1606
+
1607
+ arr, st, et, sr = fill_segments_to_array(
1608
+ segments,
1609
+ fill_value=self.fill_value,
1610
+ dtype=self.dtype,
1611
+ use_overlap_mask=self.use_overlap_mask,
1612
+ max_duration_sec=self.max_duration_sec,
1613
+ )
1614
+ # Free raw HDF5 data arrays immediately after consolidation.
1615
+ # all_segments holds the same dict objects, so popping here
1616
+ # also clears the data refs from all_segments — no deep copy needed.
1617
+ for _seg in segments:
1618
+ _seg.pop("data", None)
1619
+
1620
+ if arr is None:
1621
+ continue
1622
+
1623
+ arr, instrument_processing[cha] = self._apply_instrument_processing(
1624
+ arr,
1625
+ segments=segments,
1626
+ channel=cha,
1627
+ starttime=st,
1628
+ endtime=et,
1629
+ sampling_rate=sr,
1630
+ )
1631
+ channel_arrays[cha] = arr
1632
+ starts.append(st)
1633
+ ends.append(et)
1634
+ srs.append(sr)
1635
+
1636
+ for comp_idx, cha in selected.items():
1637
+ if cha in channel_arrays:
1638
+ arrays[comp_idx] = channel_arrays[cha]
1639
+
1640
+ _arrays_empty = len(arrays) == 0
1641
+ if _arrays_empty:
1642
+ waveform = np.zeros((0, 3), dtype=self.dtype)
1643
+ starttime = None
1644
+ endtime = None
1645
+ original_sr = np.nan
1646
+ else:
1647
+ original_sr = float(srs[0])
1648
+ starttime = min(starts)
1649
+ endtime = max(ends)
1650
+
1651
+ # Align components by absolute start time. The previous version
1652
+ # blindly wrote each channel from index 0, which silently misaligned
1653
+ # E/N/Z if their first segment start times differed.
1654
+ channel_starts = {}
1655
+ for cha, arr in channel_arrays.items():
1656
+ # Find the start time recorded for this channel by matching the
1657
+ # selected channel and using the minimum segment start.
1658
+ cha_starts = [
1659
+ seg["starttime"] for seg in all_segments
1660
+ if str(seg.get("channel", "")) == str(cha)
1661
+ ]
1662
+ if cha_starts:
1663
+ channel_starts[cha] = min(cha_starts)
1664
+ else:
1665
+ channel_starts[cha] = starttime
1666
+
1667
+ if is_z_only and not self.replicate_z_only:
1668
+ comp_count = 1
1669
+ max_end_index = 0
1670
+ for comp_idx, arr in arrays.items():
1671
+ cha = selected.get(comp_idx, "")
1672
+ offset = int(round((channel_starts.get(cha, starttime) - starttime) * original_sr))
1673
+ max_end_index = max(max_end_index, max(0, offset) + len(arr))
1674
+ waveform = np.full((max_end_index, comp_count), self.fill_value, dtype=self.dtype)
1675
+
1676
+ if 2 in arrays:
1677
+ cha = selected.get(2, "")
1678
+ offset = int(round((channel_starts.get(cha, starttime) - starttime) * original_sr))
1679
+ offset = max(0, offset)
1680
+ waveform[offset: offset + len(arrays[2]), 0] = arrays[2]
1681
+ else:
1682
+ comp_count = 3
1683
+ max_end_index = 0
1684
+ for comp_idx, arr in arrays.items():
1685
+ cha = selected.get(comp_idx, "")
1686
+ offset = int(round((channel_starts.get(cha, starttime) - starttime) * original_sr))
1687
+ max_end_index = max(max_end_index, max(0, offset) + len(arr))
1688
+
1689
+ waveform = np.full((max_end_index, comp_count), self.fill_value, dtype=self.dtype)
1690
+
1691
+ for comp_idx, arr in arrays.items():
1692
+ cha = selected.get(comp_idx, "")
1693
+ offset = int(round((channel_starts.get(cha, starttime) - starttime) * original_sr))
1694
+ offset = max(0, offset)
1695
+ waveform[offset: offset + len(arr), comp_idx] = arr
1696
+
1697
+ waveform, current_sr = resample_2d_array(
1698
+ waveform,
1699
+ original_sr=original_sr,
1700
+ target_sr=self.target_sampling_rate,
1701
+ dtype=self.dtype,
1702
+ )
1703
+ # Release per-channel intermediate arrays now that waveform is built.
1704
+ del arrays, channel_arrays
1705
+ _arrays_empty = False
1706
+
1707
+ if _arrays_empty:
1708
+ current_sr = np.nan
1709
+
1710
+ position_info = get_position_from_segments(all_segments)
1711
+ station_info = dict(station_info)
1712
+ station_info.update(position_info)
1713
+
1714
+ if is_z_only and not self.replicate_z_only:
1715
+ channels_out = [selected.get(2, "")]
1716
+ component_order = "Z only"
1717
+ else:
1718
+ channels_out = [
1719
+ selected.get(0, ""),
1720
+ selected.get(1, ""),
1721
+ selected.get(2, ""),
1722
+ ]
1723
+ component_order = "E/N/Z or 1/2/3"
1724
+
1725
+ return {
1726
+ "mode": "three",
1727
+ "h5_file": item["h5_file"],
1728
+ "year_id": year_id,
1729
+ "day_id": day_id,
1730
+ "station_id": station_id,
1731
+ "station_info": station_info,
1732
+ "channel_family": channel_family,
1733
+ "channel_info": channel_infos,
1734
+ "channels": channels_out,
1735
+ "component_order": component_order,
1736
+ "is_z_only": is_z_only,
1737
+ "z_only_replicated": z_only_replicated,
1738
+ "instrument_processing": instrument_processing,
1739
+ "waveform": torch.from_numpy(waveform),
1740
+ "segments": (
1741
+ [
1742
+ {k: v for k, v in seg.items() if k != "data"}
1743
+ for seg in all_segments
1744
+ ]
1745
+ if self.include_segments_metadata else []
1746
+ ),
1747
+ "starttime": str(starttime) if starttime is not None else "",
1748
+ "endtime": str(endtime) if endtime is not None else "",
1749
+ "original_sampling_rate": original_sr,
1750
+ "sampling_rate": current_sr,
1751
+ "target_sampling_rate": self.target_sampling_rate,
1752
+ "resampled": (
1753
+ self.target_sampling_rate is not None
1754
+ and np.isfinite(original_sr)
1755
+ and abs(float(original_sr) - float(self.target_sampling_rate)) > 1e-6
1756
+ ),
1757
+ "npts": waveform.shape[0],
1758
+ }
1759
+
1760
+ def _getitem_multi(self, h5, item, station_info):
1761
+ year_id = item["year_id"]
1762
+ day_id = item["day_id"]
1763
+ station_id = item["station_id"]
1764
+ channel_family = item["channel_family"]
1765
+ channels = item["channels"]
1766
+
1767
+ arrays = []
1768
+ used_channels = []
1769
+ starts = []
1770
+ ends = []
1771
+ srs = []
1772
+ all_segments = []
1773
+ channel_infos = {}
1774
+ instrument_processing = {}
1775
+
1776
+ for cha in channels:
1777
+ segments, channel_info = self._read_channel_segments(
1778
+ h5, year_id, day_id, station_id, cha
1779
+ )
1780
+
1781
+ all_segments.extend(segments)
1782
+ channel_infos[cha] = channel_info
1783
+
1784
+ arr, st, et, sr = fill_segments_to_array(
1785
+ segments,
1786
+ fill_value=self.fill_value,
1787
+ dtype=self.dtype,
1788
+ use_overlap_mask=self.use_overlap_mask,
1789
+ max_duration_sec=self.max_duration_sec,
1790
+ )
1791
+ # Free raw HDF5 data arrays immediately after consolidation.
1792
+ for _seg in segments:
1793
+ _seg.pop("data", None)
1794
+
1795
+ if arr is None:
1796
+ continue
1797
+
1798
+ arr, instrument_processing[cha] = self._apply_instrument_processing(
1799
+ arr,
1800
+ segments=segments,
1801
+ channel=cha,
1802
+ starttime=st,
1803
+ endtime=et,
1804
+ sampling_rate=sr,
1805
+ )
1806
+ arrays.append(arr)
1807
+ used_channels.append(cha)
1808
+ starts.append(st)
1809
+ ends.append(et)
1810
+ srs.append(sr)
1811
+
1812
+ if len(arrays) == 0:
1813
+ waveform = np.zeros((0, 0), dtype=self.dtype)
1814
+ starttime = None
1815
+ endtime = None
1816
+ original_sr = np.nan
1817
+ current_sr = np.nan
1818
+ else:
1819
+ max_len = max(len(a) for a in arrays)
1820
+ waveform = np.full(
1821
+ (max_len, len(arrays)),
1822
+ self.fill_value,
1823
+ dtype=self.dtype,
1824
+ )
1825
+
1826
+ for i, arr in enumerate(arrays):
1827
+ waveform[: len(arr), i] = arr
1828
+
1829
+ starttime = min(starts)
1830
+ endtime = max(ends)
1831
+ original_sr = float(srs[0])
1832
+
1833
+ waveform, current_sr = resample_2d_array(
1834
+ waveform,
1835
+ original_sr=original_sr,
1836
+ target_sr=self.target_sampling_rate,
1837
+ dtype=self.dtype,
1838
+ )
1839
+ # Release per-channel arrays now that waveform is built.
1840
+ del arrays
1841
+
1842
+ position_info = get_position_from_segments(all_segments)
1843
+ station_info = dict(station_info)
1844
+ station_info.update(position_info)
1845
+
1846
+ return {
1847
+ "mode": "multi",
1848
+ "h5_file": item["h5_file"],
1849
+ "year_id": year_id,
1850
+ "day_id": day_id,
1851
+ "station_id": station_id,
1852
+ "station_info": station_info,
1853
+ "channel_family": channel_family,
1854
+ "channel_info": channel_infos,
1855
+ "channels": used_channels,
1856
+ "instrument_processing": instrument_processing,
1857
+ "waveform": torch.from_numpy(waveform),
1858
+ "segments": (
1859
+ [
1860
+ {k: v for k, v in seg.items() if k != "data"}
1861
+ for seg in all_segments
1862
+ ]
1863
+ if self.include_segments_metadata else []
1864
+ ),
1865
+ "starttime": str(starttime) if starttime is not None else "",
1866
+ "endtime": str(endtime) if endtime is not None else "",
1867
+ "original_sampling_rate": original_sr,
1868
+ "sampling_rate": current_sr,
1869
+ "target_sampling_rate": self.target_sampling_rate,
1870
+ "resampled": (
1871
+ self.target_sampling_rate is not None
1872
+ and np.isfinite(original_sr)
1873
+ and abs(float(original_sr) - float(self.target_sampling_rate)) > 1e-6
1874
+ ),
1875
+ "npts": waveform.shape[0],
1876
+ }
1877
+
1878
+
1879
+ def waveform_collate_fn(batch):
1880
+ return batch
1881
+
1882
+
1883
+ def hdf5_worker_init_fn(worker_id):
1884
+ """Worker initializer for DataLoader when using fork-based multiprocessing.
1885
+
1886
+ With 'fork', child processes inherit the parent's open h5py file handles.
1887
+ Accessing inherited handles from multiple processes simultaneously causes
1888
+ HDF5 library errors or silent data corruption. This function walks all live
1889
+ objects and resets the handle cache of every HDF5WaveformDataset instance it
1890
+ finds, forcing each worker to open fresh, independent handles on its first
1891
+ __getitem__ call.
1892
+
1893
+ Usage::
1894
+
1895
+ from torch.utils.data import DataLoader
1896
+ loader = DataLoader(
1897
+ dataset,
1898
+ num_workers=4,
1899
+ multiprocessing_context='fork', # only if you must use fork
1900
+ worker_init_fn=hdf5_worker_init_fn,
1901
+ )
1902
+
1903
+ Note: With 'spawn' or 'forkserver' (the recommended and default choice on
1904
+ Linux when num_workers > 0), this function is not needed because the worker
1905
+ process starts fresh and HDF5WaveformDataset.__setstate__ already ensures an
1906
+ empty _h5_cache. It is safe to pass it regardless.
1907
+ """
1908
+ import gc as _gc
1909
+
1910
+ for obj in _gc.get_objects():
1911
+ if isinstance(obj, HDF5WaveformDataset):
1912
+ try:
1913
+ obj.close()
1914
+ except Exception:
1915
+ pass
1916
+ try:
1917
+ obj._h5_cache = {}
1918
+ except Exception:
1919
+ pass
1920
+
1921
+
1922
+ def padded_collate_fn(batch, fill_value=0.0):
1923
+ lengths = []
1924
+ arrays = []
1925
+
1926
+ max_t = 0
1927
+ max_c = 1
1928
+
1929
+ for item in batch:
1930
+ x = item["waveform"]
1931
+
1932
+ if x.ndim == 1:
1933
+ x = x[:, None]
1934
+
1935
+ t, c = x.shape
1936
+ max_t = max(max_t, t)
1937
+ max_c = max(max_c, c)
1938
+
1939
+ lengths.append(t)
1940
+ arrays.append(x)
1941
+
1942
+ out = torch.full(
1943
+ (len(batch), max_t, max_c),
1944
+ fill_value=float(fill_value),
1945
+ dtype=arrays[0].dtype,
1946
+ )
1947
+
1948
+ for i, x in enumerate(arrays):
1949
+ t, c = x.shape
1950
+ out[i, :t, :c] = x
1951
+
1952
+ meta = []
1953
+
1954
+ for item in batch:
1955
+ d = dict(item)
1956
+ d.pop("waveform")
1957
+ meta.append(d)
1958
+
1959
+ return {
1960
+ "waveform": out,
1961
+ "lengths": torch.tensor(lengths, dtype=torch.long),
1962
+ "meta": meta,
1963
+ }
1964
+
1965
+
1966
+ if __name__ == "__main__":
1967
+ h5_input = "data/continuous_waveform_usa_20190701.h5"
1968
+ """
1969
+ # 1. single file
1970
+ h5_input = "data/continuous_waveform_usa.h5"
1971
+
1972
+ # 2. glob multiple files
1973
+ h5_input = "data/continuous_waveform_usa_*.h5"
1974
+
1975
+ # 3. data directory
1976
+ h5_input = "data/"
1977
+
1978
+ # 4. explicit file list
1979
+ h5_input = [
1980
+ "data/continuous_waveform_usa_20190701.h5",
1981
+ "data/continuous_waveform_usa_20211108.h5",
1982
+ ]
1983
+ """
1984
+ dataset = HDF5WaveformDataset(
1985
+ h5_file=h5_input,
1986
+ mode="three",
1987
+
1988
+ # Default: keep commonly used seismic channel families
1989
+ allowed_families=("HH", "BH", "EH", "HN"),
1990
+
1991
+ # Additionally allow single-component (Z only) samples such as EHZ
1992
+ allowed_z_only_channels=("EHZ",),
1993
+ allow_z_only=True,
1994
+
1995
+ # Whether to replicate single Z component to three channels [Z, Z, Z]
1996
+ replicate_z_only=True,
1997
+
1998
+ # Target sampling rate (Hz); None means no resampling
1999
+ # e.g., 100.0 → resample all waveforms to 100 Hz
2000
+ target_sampling_rate=100.0,
2001
+
2002
+ fill_value=0.0,
2003
+ dtype=np.float32,
2004
+ default_location="--",
2005
+ )
2006
+
2007
+ loader = DataLoader(
2008
+ dataset,
2009
+ batch_size=2,
2010
+ shuffle=False,
2011
+ num_workers=0,
2012
+ collate_fn=waveform_collate_fn,
2013
+ )
2014
+
2015
+ print("HDF5 files:", len(dataset.h5_files))
2016
+ for f in dataset.h5_files:
2017
+ print(" ", f)
2018
+
2019
+ print("Number of samples:", len(dataset))
2020
+
2021
+ for batch in loader:
2022
+ for item in batch:
2023
+ print("=" * 80)
2024
+ print("h5_file:", item["h5_file"])
2025
+ print("station_id:", item["station_id"])
2026
+ print("mode:", item["mode"])
2027
+ print("channel_family:", item.get("channel_family", ""))
2028
+ print("channels:", item["channels"])
2029
+ print("is_z_only:", item.get("is_z_only", False))
2030
+ print("z_only_replicated:", item.get("z_only_replicated", False))
2031
+ print("starttime:", item["starttime"])
2032
+ print("endtime:", item["endtime"])
2033
+ print("original_sampling_rate:", item["original_sampling_rate"])
2034
+ print("sampling_rate:", item["sampling_rate"])
2035
+ print("target_sampling_rate:", item["target_sampling_rate"])
2036
+ print("resampled:", item["resampled"])
2037
+ print("waveform shape:", tuple(item["waveform"].shape))
2038
+ break
utils/hdf5_waveform_index.py ADDED
@@ -0,0 +1,850 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Build and query a SQLite index for hierarchical HDF5 continuous waveform datasets.
6
+
7
+ Supported HDF5 structure:
8
+
9
+ /year_id
10
+ /day_id
11
+ /stations
12
+ /network.station.location
13
+ /waveform
14
+ /channel
15
+ /segment_dataset
16
+
17
+ Example usage:
18
+
19
+ 1. Build index from a single HDF5 file:
20
+
21
+ python utils/hdf5_waveform_index.py build \
22
+ --h5 data/continuous_waveform_usa.h5 \
23
+ --db data/index/waveform_index.sqlite
24
+
25
+ 2. Build index from daily HDF5 files:
26
+
27
+ python utils/hdf5_waveform_index.py build \
28
+ --h5 "data/hdf5/continuous_waveform_usa_*.h5" \
29
+ --db data/index/waveform_index.sqlite
30
+
31
+ 3. Query one station and time range:
32
+
33
+ python utils/hdf5_waveform_index.py query \
34
+ --db data/index/waveform_index.sqlite \
35
+ --network BK \
36
+ --station BDM \
37
+ --starttime 2019-07-01T00:00:00 \
38
+ --endtime 2019-07-01T01:00:00
39
+
40
+ 4. Query specific channels:
41
+
42
+ python utils/hdf5_waveform_index.py query \
43
+ --db data/index/waveform_index.sqlite \
44
+ --network BK \
45
+ --station BDM \
46
+ --channels BHE,BHN,BHZ \
47
+ --starttime 2019-07-01T00:00:00 \
48
+ --endtime 2019-07-01T01:00:00
49
+
50
+ 5. Read matched waveform segments into memory:
51
+
52
+ python utils/hdf5_waveform_index.py read \
53
+ --db data/index/waveform_index.sqlite \
54
+ --network BK \
55
+ --station BDM \
56
+ --channels BHE,BHN,BHZ \
57
+ --starttime 2019-07-01T00:00:00 \
58
+ --endtime 2019-07-01T01:00:00
59
+ """
60
+
61
+ import argparse
62
+ import glob
63
+ import json
64
+ import os
65
+ import sqlite3
66
+ from pathlib import Path
67
+
68
+ import h5py
69
+ import numpy as np
70
+ from obspy import UTCDateTime
71
+
72
+
73
+ DEFAULT_LOCATION = "--"
74
+
75
+
76
+ # -----------------------------
77
+ # Basic utilities
78
+ # -----------------------------
79
+
80
+ def decode_attr(value):
81
+ if isinstance(value, bytes):
82
+ return value.decode("utf-8", errors="ignore")
83
+ if isinstance(value, np.bytes_):
84
+ return value.decode("utf-8", errors="ignore")
85
+ return value
86
+
87
+
88
+ def get_attr(obj, name, default=None):
89
+ if name in obj.attrs:
90
+ return decode_attr(obj.attrs[name])
91
+ return default
92
+
93
+
94
+ def normalize_location(location, default=DEFAULT_LOCATION):
95
+ location = decode_attr(location)
96
+ if location is None:
97
+ return default
98
+ location = str(location).strip()
99
+ return location if location else default
100
+
101
+
102
+ def split_station_id(station_id, default_location=DEFAULT_LOCATION):
103
+ parts = str(station_id).split(".")
104
+ network = parts[0] if len(parts) > 0 else ""
105
+ station = parts[1] if len(parts) > 1 else ""
106
+ location = parts[2] if len(parts) > 2 else default_location
107
+ return network, station, normalize_location(location, default_location)
108
+
109
+
110
+ def make_station_key(network, station):
111
+ return f"{str(network).strip()}.{str(station).strip()}"
112
+
113
+
114
+ def parse_time_to_epoch(value):
115
+ if value is None:
116
+ return None
117
+ value = str(value).strip()
118
+ if not value:
119
+ return None
120
+ return float(UTCDateTime(value).timestamp)
121
+
122
+
123
+ def epoch_to_utc_string(epoch):
124
+ if epoch is None:
125
+ return ""
126
+ return str(UTCDateTime(float(epoch)))
127
+
128
+
129
+ def resolve_h5_files(h5_input):
130
+ """
131
+ Supports:
132
+ - single file
133
+ - list of files
134
+ - directory
135
+ - glob pattern
136
+ """
137
+ if isinstance(h5_input, (list, tuple)):
138
+ out = []
139
+ for item in h5_input:
140
+ out.extend(resolve_h5_files(item))
141
+ return sorted(set(out))
142
+
143
+ h5_input = str(h5_input)
144
+ p = Path(h5_input)
145
+
146
+ if p.is_file():
147
+ return [str(p)]
148
+
149
+ if p.is_dir():
150
+ files = []
151
+ files.extend(str(x) for x in p.glob("*.h5"))
152
+ files.extend(str(x) for x in p.glob("*.hdf5"))
153
+ return sorted(files)
154
+
155
+ files = sorted(glob.glob(h5_input))
156
+ if files:
157
+ return files
158
+
159
+ raise FileNotFoundError(f"No HDF5 files found from input: {h5_input}")
160
+
161
+
162
+ def comma_list(value):
163
+ if value is None:
164
+ return None
165
+ value = str(value).strip()
166
+ if not value:
167
+ return None
168
+ return [x.strip() for x in value.split(",") if x.strip()]
169
+
170
+
171
+ # -----------------------------
172
+ # SQLite schema
173
+ # -----------------------------
174
+
175
+ def connect_db(db_file):
176
+ conn = sqlite3.connect(db_file)
177
+ conn.row_factory = sqlite3.Row
178
+ return conn
179
+
180
+
181
+ def init_db(conn, reset=False):
182
+ cur = conn.cursor()
183
+
184
+ if reset:
185
+ cur.execute("DROP TABLE IF EXISTS waveform_segments")
186
+ cur.execute("DROP TABLE IF EXISTS hdf5_files")
187
+ cur.execute("DROP TABLE IF EXISTS stations")
188
+
189
+ cur.execute(
190
+ """
191
+ CREATE TABLE IF NOT EXISTS hdf5_files (
192
+ file_id INTEGER PRIMARY KEY AUTOINCREMENT,
193
+ h5_file TEXT UNIQUE NOT NULL
194
+ )
195
+ """
196
+ )
197
+
198
+ cur.execute(
199
+ """
200
+ CREATE TABLE IF NOT EXISTS stations (
201
+ station_key TEXT PRIMARY KEY,
202
+ network TEXT NOT NULL,
203
+ station TEXT NOT NULL,
204
+ latitude REAL,
205
+ longitude REAL,
206
+ elevation REAL,
207
+ location_available INTEGER
208
+ )
209
+ """
210
+ )
211
+
212
+ cur.execute(
213
+ """
214
+ CREATE TABLE IF NOT EXISTS waveform_segments (
215
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
216
+
217
+ file_id INTEGER NOT NULL,
218
+ h5_file TEXT NOT NULL,
219
+ dataset_path TEXT NOT NULL,
220
+
221
+ year_id TEXT,
222
+ day_id TEXT,
223
+
224
+ station_id TEXT NOT NULL,
225
+ station_key TEXT NOT NULL,
226
+ network TEXT NOT NULL,
227
+ station TEXT NOT NULL,
228
+ location TEXT,
229
+
230
+ channel TEXT NOT NULL,
231
+
232
+ starttime TEXT NOT NULL,
233
+ endtime TEXT NOT NULL,
234
+ start_epoch REAL NOT NULL,
235
+ end_epoch REAL NOT NULL,
236
+
237
+ sampling_rate REAL,
238
+ delta REAL,
239
+ npts INTEGER,
240
+ dtype TEXT,
241
+ source_file TEXT,
242
+
243
+ latitude REAL,
244
+ longitude REAL,
245
+ elevation REAL,
246
+ location_available INTEGER,
247
+
248
+ UNIQUE(h5_file, dataset_path)
249
+ )
250
+ """
251
+ )
252
+
253
+ cur.execute(
254
+ """
255
+ CREATE INDEX IF NOT EXISTS idx_segments_station_time
256
+ ON waveform_segments (network, station, start_epoch, end_epoch)
257
+ """
258
+ )
259
+
260
+ cur.execute(
261
+ """
262
+ CREATE INDEX IF NOT EXISTS idx_segments_station_channel_time
263
+ ON waveform_segments (network, station, channel, start_epoch, end_epoch)
264
+ """
265
+ )
266
+
267
+ cur.execute(
268
+ """
269
+ CREATE INDEX IF NOT EXISTS idx_segments_station_key_time
270
+ ON waveform_segments (station_key, start_epoch, end_epoch)
271
+ """
272
+ )
273
+
274
+ cur.execute(
275
+ """
276
+ CREATE INDEX IF NOT EXISTS idx_segments_location
277
+ ON waveform_segments (location)
278
+ """
279
+ )
280
+
281
+ cur.execute(
282
+ """
283
+ CREATE INDEX IF NOT EXISTS idx_segments_h5_file
284
+ ON waveform_segments (h5_file)
285
+ """
286
+ )
287
+
288
+ conn.commit()
289
+
290
+
291
+ def get_or_insert_file_id(conn, h5_file):
292
+ cur = conn.cursor()
293
+ cur.execute(
294
+ "INSERT OR IGNORE INTO hdf5_files (h5_file) VALUES (?)",
295
+ (h5_file,),
296
+ )
297
+ conn.commit()
298
+
299
+ cur.execute(
300
+ "SELECT file_id FROM hdf5_files WHERE h5_file = ?",
301
+ (h5_file,),
302
+ )
303
+ return int(cur.fetchone()["file_id"])
304
+
305
+
306
+ # -----------------------------
307
+ # HDF5 scanning
308
+ # -----------------------------
309
+
310
+ def iter_waveform_datasets(h5_file, default_location=DEFAULT_LOCATION):
311
+ """
312
+ Yield one record per waveform segment dataset.
313
+ """
314
+ with h5py.File(h5_file, "r") as h5:
315
+ for year_id in sorted(h5.keys()):
316
+ year_grp = h5[year_id]
317
+ if not isinstance(year_grp, h5py.Group):
318
+ continue
319
+
320
+ for day_id in sorted(year_grp.keys()):
321
+ day_grp = year_grp[day_id]
322
+ if not isinstance(day_grp, h5py.Group):
323
+ continue
324
+
325
+ if "stations" not in day_grp:
326
+ continue
327
+
328
+ stations_grp = day_grp["stations"]
329
+
330
+ for station_id in sorted(stations_grp.keys()):
331
+ station_grp = stations_grp[station_id]
332
+ if not isinstance(station_grp, h5py.Group):
333
+ continue
334
+
335
+ if "waveform" not in station_grp:
336
+ continue
337
+
338
+ waveform_grp = station_grp["waveform"]
339
+
340
+ for channel in sorted(waveform_grp.keys()):
341
+ channel_grp = waveform_grp[channel]
342
+ if not isinstance(channel_grp, h5py.Group):
343
+ continue
344
+
345
+ for ds_key in sorted(channel_grp.keys(), key=lambda x: int(x) if str(x).isdigit() else str(x)):
346
+ ds = channel_grp[ds_key]
347
+ if not isinstance(ds, h5py.Dataset):
348
+ continue
349
+
350
+ dataset_path = ds.name
351
+
352
+ network = get_attr(ds, "network", None)
353
+ station = get_attr(ds, "station", None)
354
+ location = get_attr(ds, "location", None)
355
+
356
+ if not network or not station:
357
+ net2, sta2, loc2 = split_station_id(station_id, default_location)
358
+ network = network or net2
359
+ station = station or sta2
360
+ location = location if location is not None else loc2
361
+
362
+ location = normalize_location(location, default_location)
363
+ station_key = make_station_key(network, station)
364
+
365
+ starttime = get_attr(ds, "starttime", "")
366
+ endtime = get_attr(ds, "endtime", "")
367
+
368
+ start_epoch = parse_time_to_epoch(starttime)
369
+ end_epoch = parse_time_to_epoch(endtime)
370
+
371
+ if start_epoch is None or end_epoch is None:
372
+ continue
373
+
374
+ yield {
375
+ "h5_file": str(h5_file),
376
+ "dataset_path": dataset_path,
377
+ "year_id": year_id,
378
+ "day_id": day_id,
379
+ "station_id": station_id,
380
+ "station_key": station_key,
381
+ "network": str(network),
382
+ "station": str(station),
383
+ "location": location,
384
+ "channel": str(get_attr(ds, "channel", channel)),
385
+ "starttime": str(starttime),
386
+ "endtime": str(endtime),
387
+ "start_epoch": float(start_epoch),
388
+ "end_epoch": float(end_epoch),
389
+ "sampling_rate": float(get_attr(ds, "sampling_rate", np.nan)),
390
+ "delta": float(get_attr(ds, "delta", np.nan)),
391
+ "npts": int(get_attr(ds, "npts", ds.shape[0])),
392
+ "dtype": str(get_attr(ds, "dtype", str(ds.dtype))),
393
+ "source_file": str(get_attr(ds, "mseed_source_file", "")),
394
+ "latitude": float(get_attr(ds, "latitude", np.nan)),
395
+ "longitude": float(get_attr(ds, "longitude", np.nan)),
396
+ "elevation": float(get_attr(ds, "elevation", np.nan)),
397
+ "location_available": int(bool(get_attr(ds, "location_available", False))),
398
+ }
399
+
400
+
401
+ def insert_segment_records(conn, file_id, records, batch_size=5000):
402
+ cur = conn.cursor()
403
+
404
+ sql = """
405
+ INSERT OR IGNORE INTO waveform_segments (
406
+ file_id,
407
+ h5_file,
408
+ dataset_path,
409
+ year_id,
410
+ day_id,
411
+ station_id,
412
+ station_key,
413
+ network,
414
+ station,
415
+ location,
416
+ channel,
417
+ starttime,
418
+ endtime,
419
+ start_epoch,
420
+ end_epoch,
421
+ sampling_rate,
422
+ delta,
423
+ npts,
424
+ dtype,
425
+ source_file,
426
+ latitude,
427
+ longitude,
428
+ elevation,
429
+ location_available
430
+ )
431
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
432
+ """
433
+
434
+ batch = []
435
+
436
+ for rec in records:
437
+ batch.append(
438
+ (
439
+ file_id,
440
+ rec["h5_file"],
441
+ rec["dataset_path"],
442
+ rec["year_id"],
443
+ rec["day_id"],
444
+ rec["station_id"],
445
+ rec["station_key"],
446
+ rec["network"],
447
+ rec["station"],
448
+ rec["location"],
449
+ rec["channel"],
450
+ rec["starttime"],
451
+ rec["endtime"],
452
+ rec["start_epoch"],
453
+ rec["end_epoch"],
454
+ rec["sampling_rate"],
455
+ rec["delta"],
456
+ rec["npts"],
457
+ rec["dtype"],
458
+ rec["source_file"],
459
+ rec["latitude"],
460
+ rec["longitude"],
461
+ rec["elevation"],
462
+ rec["location_available"],
463
+ )
464
+ )
465
+
466
+ if len(batch) >= batch_size:
467
+ cur.executemany(sql, batch)
468
+ conn.commit()
469
+ batch.clear()
470
+
471
+ if batch:
472
+ cur.executemany(sql, batch)
473
+ conn.commit()
474
+
475
+
476
+ def update_station_table(conn):
477
+ cur = conn.cursor()
478
+
479
+ cur.execute(
480
+ """
481
+ INSERT OR REPLACE INTO stations (
482
+ station_key,
483
+ network,
484
+ station,
485
+ latitude,
486
+ longitude,
487
+ elevation,
488
+ location_available
489
+ )
490
+ SELECT
491
+ station_key,
492
+ network,
493
+ station,
494
+ AVG(latitude),
495
+ AVG(longitude),
496
+ AVG(elevation),
497
+ MAX(location_available)
498
+ FROM waveform_segments
499
+ GROUP BY station_key, network, station
500
+ """
501
+ )
502
+
503
+ conn.commit()
504
+
505
+
506
+ def build_index(h5_input, db_file, reset=True, default_location=DEFAULT_LOCATION):
507
+ h5_files = resolve_h5_files(h5_input)
508
+
509
+ conn = connect_db(db_file)
510
+ init_db(conn, reset=reset)
511
+
512
+ print(f"[INFO] HDF5 files: {len(h5_files)}")
513
+ print(f"[INFO] SQLite DB: {db_file}")
514
+
515
+ total = 0
516
+
517
+ for i, h5_file in enumerate(h5_files, start=1):
518
+ print(f"[INFO] Indexing {i}/{len(h5_files)}: {h5_file}")
519
+
520
+ file_id = get_or_insert_file_id(conn, h5_file)
521
+
522
+ count = 0
523
+
524
+ def record_generator():
525
+ nonlocal count
526
+ for rec in iter_waveform_datasets(h5_file, default_location=default_location):
527
+ count += 1
528
+ yield rec
529
+
530
+ insert_segment_records(conn, file_id, record_generator())
531
+ total += count
532
+
533
+ print(f"[INFO] segments indexed: {count}")
534
+
535
+ update_station_table(conn)
536
+
537
+ cur = conn.cursor()
538
+ cur.execute("SELECT COUNT(*) AS n FROM waveform_segments")
539
+ n_segments = cur.fetchone()["n"]
540
+
541
+ cur.execute("SELECT COUNT(*) AS n FROM stations")
542
+ n_stations = cur.fetchone()["n"]
543
+
544
+ conn.close()
545
+
546
+ print(f"[OK] Indexed segments: {n_segments}")
547
+ print(f"[OK] Indexed stations: {n_stations}")
548
+
549
+
550
+ # -----------------------------
551
+ # Querying
552
+ # -----------------------------
553
+
554
+ def query_segments(
555
+ db_file,
556
+ network=None,
557
+ station=None,
558
+ station_key=None,
559
+ location=None,
560
+ channels=None,
561
+ starttime=None,
562
+ endtime=None,
563
+ limit=None,
564
+ ):
565
+ start_epoch = parse_time_to_epoch(starttime) if starttime else None
566
+ end_epoch = parse_time_to_epoch(endtime) if endtime else None
567
+
568
+ if start_epoch is None:
569
+ start_epoch = -1.0e30
570
+ if end_epoch is None:
571
+ end_epoch = 1.0e30
572
+
573
+ channels = comma_list(channels) if isinstance(channels, str) else channels
574
+
575
+ clauses = [
576
+ "end_epoch >= ?",
577
+ "start_epoch <= ?",
578
+ ]
579
+ params = [start_epoch, end_epoch]
580
+
581
+ if station_key:
582
+ clauses.append("station_key = ?")
583
+ params.append(station_key)
584
+ else:
585
+ if network:
586
+ clauses.append("network = ?")
587
+ params.append(network)
588
+ if station:
589
+ clauses.append("station = ?")
590
+ params.append(station)
591
+
592
+ if location:
593
+ clauses.append("location = ?")
594
+ params.append(location)
595
+
596
+ if channels:
597
+ placeholders = ",".join(["?"] * len(channels))
598
+ clauses.append(f"channel IN ({placeholders})")
599
+ params.extend(channels)
600
+
601
+ sql = f"""
602
+ SELECT *
603
+ FROM waveform_segments
604
+ WHERE {' AND '.join(clauses)}
605
+ ORDER BY network, station, location, channel, start_epoch
606
+ """
607
+
608
+ if limit is not None:
609
+ sql += " LIMIT ?"
610
+ params.append(int(limit))
611
+
612
+ conn = connect_db(db_file)
613
+ cur = conn.cursor()
614
+ cur.execute(sql, params)
615
+ rows = [dict(row) for row in cur.fetchall()]
616
+ conn.close()
617
+
618
+ return rows
619
+
620
+
621
+ def print_query_results(rows, as_json=False):
622
+ if as_json:
623
+ print(json.dumps(rows, indent=2, ensure_ascii=False))
624
+ return
625
+
626
+ print(f"[OK] Matched segments: {len(rows)}")
627
+
628
+ for row in rows:
629
+ print(
630
+ f"{row['network']}.{row['station']}.{row['location']} "
631
+ f"{row['channel']} "
632
+ f"{row['starttime']} -> {row['endtime']} "
633
+ f"npts={row['npts']} sr={row['sampling_rate']} "
634
+ f"path={row['dataset_path']} "
635
+ f"h5={row['h5_file']}"
636
+ )
637
+
638
+
639
+ def read_segment(row):
640
+ with h5py.File(row["h5_file"], "r") as h5:
641
+ ds = h5[row["dataset_path"]]
642
+ data = ds[()]
643
+ return data
644
+
645
+
646
+ def read_query_results(rows):
647
+ out = []
648
+
649
+ for row in rows:
650
+ data = read_segment(row)
651
+ item = dict(row)
652
+ item["data_shape"] = tuple(data.shape)
653
+ item["data"] = data
654
+ out.append(item)
655
+
656
+ return out
657
+
658
+
659
+ def trim_array_by_time(data, row, query_starttime=None, query_endtime=None):
660
+ """
661
+ Optional trimming by query time.
662
+
663
+ This assumes regular sampling and uses segment-level starttime/sampling_rate.
664
+ """
665
+ if query_starttime is None and query_endtime is None:
666
+ return data
667
+
668
+ sr = float(row["sampling_rate"])
669
+ seg_start = float(row["start_epoch"])
670
+ seg_end = float(row["end_epoch"])
671
+
672
+ q0 = parse_time_to_epoch(query_starttime) if query_starttime else seg_start
673
+ q1 = parse_time_to_epoch(query_endtime) if query_endtime else seg_end
674
+
675
+ q0 = max(q0, seg_start)
676
+ q1 = min(q1, seg_end)
677
+
678
+ if q1 < q0:
679
+ return data[:0]
680
+
681
+ i0 = int(round((q0 - seg_start) * sr))
682
+ i1 = int(round((q1 - seg_start) * sr)) + 1
683
+
684
+ i0 = max(i0, 0)
685
+ i1 = min(i1, len(data))
686
+
687
+ return data[i0:i1]
688
+
689
+
690
+ def read_query_results_trimmed(rows, query_starttime=None, query_endtime=None):
691
+ out = []
692
+
693
+ for row in rows:
694
+ data = read_segment(row)
695
+ data = trim_array_by_time(
696
+ data,
697
+ row,
698
+ query_starttime=query_starttime,
699
+ query_endtime=query_endtime,
700
+ )
701
+
702
+ item = dict(row)
703
+ item["data_shape"] = tuple(data.shape)
704
+ item["data"] = data
705
+ out.append(item)
706
+
707
+ return out
708
+
709
+
710
+ # -----------------------------
711
+ # CLI
712
+ # -----------------------------
713
+
714
+ def cmd_build(args):
715
+ build_index(
716
+ h5_input=args.h5,
717
+ db_file=args.db,
718
+ reset=not args.no_reset,
719
+ default_location=args.default_location,
720
+ )
721
+
722
+
723
+ def cmd_query(args):
724
+ rows = query_segments(
725
+ db_file=args.db,
726
+ network=args.network,
727
+ station=args.station,
728
+ station_key=args.station_key,
729
+ location=args.location,
730
+ channels=args.channels,
731
+ starttime=args.starttime,
732
+ endtime=args.endtime,
733
+ limit=args.limit,
734
+ )
735
+ print_query_results(rows, as_json=args.json)
736
+
737
+
738
+ def cmd_read(args):
739
+ rows = query_segments(
740
+ db_file=args.db,
741
+ network=args.network,
742
+ station=args.station,
743
+ station_key=args.station_key,
744
+ location=args.location,
745
+ channels=args.channels,
746
+ starttime=args.starttime,
747
+ endtime=args.endtime,
748
+ limit=args.limit,
749
+ )
750
+
751
+ items = read_query_results_trimmed(
752
+ rows,
753
+ query_starttime=args.starttime,
754
+ query_endtime=args.endtime,
755
+ )
756
+
757
+ print(f"[OK] Loaded segments: {len(items)}")
758
+ for item in items:
759
+ print(
760
+ f"{item['network']}.{item['station']}.{item['location']} "
761
+ f"{item['channel']} "
762
+ f"{item['starttime']} -> {item['endtime']} "
763
+ f"trimmed_shape={item['data_shape']} "
764
+ f"path={item['dataset_path']}"
765
+ )
766
+
767
+ if args.output_npz:
768
+ arrays = {}
769
+ meta = []
770
+
771
+ for i, item in enumerate(items):
772
+ key = f"arr_{i:06d}"
773
+ arrays[key] = item["data"]
774
+
775
+ meta_item = dict(item)
776
+ meta_item.pop("data", None)
777
+ meta.append(meta_item)
778
+
779
+ arrays["metadata_json"] = np.array(json.dumps(meta, ensure_ascii=False))
780
+ np.savez(args.output_npz, **arrays)
781
+ print(f"[OK] Saved NPZ: {args.output_npz}")
782
+
783
+
784
+ def build_arg_parser():
785
+ parser = argparse.ArgumentParser(
786
+ description="SQLite index tool for hierarchical HDF5 continuous waveform datasets."
787
+ )
788
+
789
+ sub = parser.add_subparsers(dest="command", required=True)
790
+
791
+ p_build = sub.add_parser("build", help="Build SQLite index from HDF5 files.")
792
+ p_build.add_argument(
793
+ "--h5",
794
+ required=True,
795
+ help="HDF5 input: single file, directory, glob pattern, or file path.",
796
+ )
797
+ p_build.add_argument(
798
+ "--db",
799
+ required=True,
800
+ help="Output SQLite database file.",
801
+ )
802
+ p_build.add_argument(
803
+ "--no_reset",
804
+ action="store_true",
805
+ help="Do not reset existing tables; append new records with INSERT OR IGNORE.",
806
+ )
807
+ p_build.add_argument(
808
+ "--default_location",
809
+ default=DEFAULT_LOCATION,
810
+ help='Default location code. Default: "--".',
811
+ )
812
+ p_build.set_defaults(func=cmd_build)
813
+
814
+ p_query = sub.add_parser("query", help="Query indexed waveform segments.")
815
+ p_query.add_argument("--db", required=True, help="SQLite database file.")
816
+ p_query.add_argument("--network", default=None, help="Network code, e.g. BK.")
817
+ p_query.add_argument("--station", default=None, help="Station code, e.g. BDM.")
818
+ p_query.add_argument("--station_key", default=None, help="Station key, e.g. BK.BDM.")
819
+ p_query.add_argument("--location", default=None, help="Location code. Optional.")
820
+ p_query.add_argument("--channels", default=None, help="Comma-separated channels, e.g. BHE,BHN,BHZ.")
821
+ p_query.add_argument("--starttime", default=None, help="Query start time.")
822
+ p_query.add_argument("--endtime", default=None, help="Query end time.")
823
+ p_query.add_argument("--limit", type=int, default=None, help="Limit number of results.")
824
+ p_query.add_argument("--json", action="store_true", help="Print results as JSON.")
825
+ p_query.set_defaults(func=cmd_query)
826
+
827
+ p_read = sub.add_parser("read", help="Query and read waveform data.")
828
+ p_read.add_argument("--db", required=True, help="SQLite database file.")
829
+ p_read.add_argument("--network", default=None, help="Network code, e.g. BK.")
830
+ p_read.add_argument("--station", default=None, help="Station code, e.g. BDM.")
831
+ p_read.add_argument("--station_key", default=None, help="Station key, e.g. BK.BDM.")
832
+ p_read.add_argument("--location", default=None, help="Location code. Optional.")
833
+ p_read.add_argument("--channels", default=None, help="Comma-separated channels, e.g. BHE,BHN,BHZ.")
834
+ p_read.add_argument("--starttime", default=None, help="Query start time.")
835
+ p_read.add_argument("--endtime", default=None, help="Query end time.")
836
+ p_read.add_argument("--limit", type=int, default=None, help="Limit number of results.")
837
+ p_read.add_argument("--output_npz", default=None, help="Optional output NPZ file.")
838
+ p_read.set_defaults(func=cmd_read)
839
+
840
+ return parser
841
+
842
+
843
+ def main():
844
+ parser = build_arg_parser()
845
+ args = parser.parse_args()
846
+ args.func(args)
847
+
848
+
849
+ if __name__ == "__main__":
850
+ main()
utils/waveform_index_api.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import json
5
+ import sqlite3
6
+ import warnings
7
+ from collections import defaultdict
8
+
9
+ import h5py
10
+ import numpy as np
11
+ from obspy import Trace, UTCDateTime
12
+
13
+ from utils.hdf5_waveform_dataset import (
14
+ DEFAULT_LOCATION,
15
+ apply_response_spectrum,
16
+ inventory_from_response_record,
17
+ load_response_json,
18
+ normalize_location,
19
+ response_from_json_record,
20
+ response_record_matches_time,
21
+ utc_or_none,
22
+ )
23
+
24
+
25
+ def parse_time_to_epoch(t):
26
+ return float(UTCDateTime(t).timestamp)
27
+
28
+
29
+ def epoch_to_utc(t):
30
+ return str(UTCDateTime(float(t)))
31
+
32
+
33
+ def wildcard_to_sql_like(pattern):
34
+ """
35
+ Convert wildcard pattern to SQL LIKE pattern.
36
+
37
+ Examples:
38
+ "*" -> "%"
39
+ "BK" -> "BK"
40
+ "B*" -> "B%"
41
+ "*Z" -> "%Z"
42
+ "BH*" -> "BH%"
43
+ """
44
+ if pattern is None or str(pattern).strip() == "":
45
+ return "%"
46
+
47
+ return str(pattern).strip().replace("*", "%")
48
+
49
+
50
+ def query_segments(
51
+ db_file,
52
+ network="*",
53
+ station="*",
54
+ location="*",
55
+ channel="*",
56
+ starttime=None,
57
+ endtime=None,
58
+ limit=None,
59
+ ):
60
+ """
61
+ Query waveform segments from SQLite index.
62
+
63
+ Parameters
64
+ ----------
65
+ db_file : str
66
+ SQLite index database path.
67
+ network : str
68
+ Network code or wildcard pattern, e.g. "BK", "C*", "*".
69
+ station : str
70
+ Station code or wildcard pattern, e.g. "BDM", "BD*", "*".
71
+ location : str
72
+ Location code or wildcard pattern, e.g. "00", "--", "*".
73
+ channel : str
74
+ Channel code or wildcard pattern, e.g. "BHE", "BH*", "*Z", "*".
75
+ starttime : str
76
+ Query start time.
77
+ endtime : str
78
+ Query end time.
79
+ limit : int or None
80
+ Optional maximum number of returned segments.
81
+
82
+ Returns
83
+ -------
84
+ rows : list[dict]
85
+ Matched waveform segment metadata.
86
+ """
87
+
88
+ if starttime is None or endtime is None:
89
+ raise ValueError("starttime and endtime are required.")
90
+
91
+ query_start = parse_time_to_epoch(starttime)
92
+ query_end = parse_time_to_epoch(endtime)
93
+
94
+ sql = """
95
+ SELECT *
96
+ FROM waveform_segments
97
+ WHERE network LIKE ?
98
+ AND station LIKE ?
99
+ AND location LIKE ?
100
+ AND channel LIKE ?
101
+ AND end_epoch >= ?
102
+ AND start_epoch <= ?
103
+ ORDER BY network, station, location, channel, start_epoch
104
+ """
105
+
106
+ params = [
107
+ wildcard_to_sql_like(network),
108
+ wildcard_to_sql_like(station),
109
+ wildcard_to_sql_like(location),
110
+ wildcard_to_sql_like(channel),
111
+ query_start,
112
+ query_end,
113
+ ]
114
+
115
+ if limit is not None:
116
+ sql += " LIMIT ?"
117
+ params.append(int(limit))
118
+
119
+ conn = sqlite3.connect(db_file)
120
+ conn.row_factory = sqlite3.Row
121
+
122
+ try:
123
+ cur = conn.cursor()
124
+ cur.execute(sql, params)
125
+ rows = [dict(r) for r in cur.fetchall()]
126
+ finally:
127
+ conn.close()
128
+
129
+ return rows
130
+
131
+
132
+ def read_hdf5_segment(row):
133
+ """
134
+ Read a single waveform segment from HDF5 using h5_file and dataset_path.
135
+ """
136
+ with h5py.File(row["h5_file"], "r") as h5:
137
+ data = h5[row["dataset_path"]][()]
138
+
139
+ return np.asarray(data)
140
+
141
+
142
+ def trim_segment_to_window(data, row, starttime, endtime):
143
+ """
144
+ Trim one segment to the requested time window.
145
+ """
146
+ sr = float(row["sampling_rate"])
147
+
148
+ seg_start = float(row["start_epoch"])
149
+ seg_end = float(row["end_epoch"])
150
+
151
+ query_start = parse_time_to_epoch(starttime)
152
+ query_end = parse_time_to_epoch(endtime)
153
+
154
+ use_start = max(seg_start, query_start)
155
+ use_end = min(seg_end, query_end)
156
+
157
+ if use_end < use_start:
158
+ return data[:0], use_start, use_end
159
+
160
+ i0 = int(round((use_start - seg_start) * sr))
161
+ i1 = int(round((use_end - seg_start) * sr)) + 1
162
+
163
+ i0 = max(i0, 0)
164
+ i1 = min(i1, len(data))
165
+
166
+ return data[i0:i1], use_start, use_end
167
+
168
+
169
+ def merge_segments(
170
+ rows,
171
+ starttime,
172
+ endtime,
173
+ fill_value=0.0,
174
+ dtype=np.float32,
175
+ ):
176
+ """
177
+ Merge multiple waveform segments into continuous arrays.
178
+
179
+ Segments are grouped by:
180
+ network.station.location.channel
181
+
182
+ Missing samples are filled by fill_value.
183
+
184
+ Returns
185
+ -------
186
+ merged : dict
187
+ {
188
+ "BK.BDM.00.BHE": {
189
+ "data": np.ndarray,
190
+ "network": "BK",
191
+ "station": "BDM",
192
+ "location": "00",
193
+ "channel": "BHE",
194
+ "starttime": "...",
195
+ "endtime": "...",
196
+ "sampling_rate": 100.0,
197
+ "npts": 360001,
198
+ "segments": [...]
199
+ },
200
+ ...
201
+ }
202
+ """
203
+
204
+ if len(rows) == 0:
205
+ return {}
206
+
207
+ query_start = parse_time_to_epoch(starttime)
208
+ query_end = parse_time_to_epoch(endtime)
209
+
210
+ groups = defaultdict(list)
211
+
212
+ for row in rows:
213
+ key = (
214
+ row["network"],
215
+ row["station"],
216
+ row["location"],
217
+ row["channel"],
218
+ )
219
+ groups[key].append(row)
220
+
221
+ merged = {}
222
+
223
+ for key, seg_rows in groups.items():
224
+ network, station, location, channel = key
225
+
226
+ seg_rows = sorted(seg_rows, key=lambda r: float(r["start_epoch"]))
227
+
228
+ sampling_rates = sorted(set(float(r["sampling_rate"]) for r in seg_rows))
229
+ if len(sampling_rates) != 1:
230
+ raise ValueError(
231
+ f"Multiple sampling rates found for {network}.{station}.{location}.{channel}: "
232
+ f"{sampling_rates}"
233
+ )
234
+
235
+ sr = sampling_rates[0]
236
+
237
+ npts = int(round((query_end - query_start) * sr)) + 1
238
+ out = np.full(npts, fill_value, dtype=dtype)
239
+ filled = np.zeros(npts, dtype=bool)
240
+
241
+ used_segments = []
242
+
243
+ for row in seg_rows:
244
+ data = read_hdf5_segment(row)
245
+ data, use_start, use_end = trim_segment_to_window(
246
+ data,
247
+ row,
248
+ starttime=starttime,
249
+ endtime=endtime,
250
+ )
251
+
252
+ if len(data) == 0:
253
+ continue
254
+
255
+ i0 = int(round((use_start - query_start) * sr))
256
+ i1 = i0 + len(data)
257
+
258
+ if i0 < 0:
259
+ data = data[-i0:]
260
+ i0 = 0
261
+
262
+ if i1 > npts:
263
+ data = data[: npts - i0]
264
+ i1 = npts
265
+
266
+ if i0 >= i1:
267
+ continue
268
+
269
+ target = slice(i0, i1)
270
+ mask = ~filled[target]
271
+
272
+ out[target][mask] = data[: i1 - i0][mask].astype(dtype, copy=False)
273
+ filled[target][mask] = True
274
+
275
+ used_segments.append(
276
+ {
277
+ "h5_file": row["h5_file"],
278
+ "dataset_path": row["dataset_path"],
279
+ "network": row["network"],
280
+ "station": row["station"],
281
+ "location": row["location"],
282
+ "channel": row["channel"],
283
+ "segment_starttime": row["starttime"],
284
+ "segment_endtime": row["endtime"],
285
+ "segment_start_epoch": float(row["start_epoch"]),
286
+ "segment_end_epoch": float(row["end_epoch"]),
287
+ "used_starttime": epoch_to_utc(use_start),
288
+ "used_endtime": epoch_to_utc(use_end),
289
+ "npts": int(len(data)),
290
+ }
291
+ )
292
+
293
+ out_key = f"{network}.{station}.{location}.{channel}"
294
+
295
+ merged[out_key] = {
296
+ "data": out,
297
+ "network": network,
298
+ "station": station,
299
+ "location": location,
300
+ "channel": channel,
301
+ "starttime": str(UTCDateTime(starttime)),
302
+ "endtime": str(UTCDateTime(endtime)),
303
+ "sampling_rate": sr,
304
+ "npts": int(len(out)),
305
+ "filled_ratio": float(filled.mean()) if len(filled) > 0 else 0.0,
306
+ "segments": used_segments,
307
+ }
308
+
309
+ return merged
310
+
311
+
312
+ class InstrumentResponseProcessor:
313
+ """
314
+ Apply the same response-removal and response-simulation options used by the
315
+ PyTorch dataloader to waveforms returned by the SQLite query API.
316
+ """
317
+
318
+ def __init__(
319
+ self,
320
+ instrument_response_json=None,
321
+ remove_instrument_response=False,
322
+ response_output="VEL",
323
+ response_pre_filt=None,
324
+ response_water_level=60,
325
+ response_zero_mean=True,
326
+ response_taper=True,
327
+ response_taper_fraction=0.05,
328
+ response_error_behavior="raise",
329
+ simulate_instrument_response=False,
330
+ simulation_response_json=None,
331
+ simulation_response_id=None,
332
+ simulation_response_selector=None,
333
+ simulation_paz=None,
334
+ simulation_output=None,
335
+ simulation_sensitivity=True,
336
+ default_location=DEFAULT_LOCATION,
337
+ dtype=np.float32,
338
+ ):
339
+ if response_error_behavior not in {"raise", "warn", "skip"}:
340
+ raise ValueError("response_error_behavior must be 'raise', 'warn', or 'skip'")
341
+
342
+ self.instrument_response_json = (
343
+ str(instrument_response_json) if instrument_response_json is not None else None
344
+ )
345
+ self.remove_instrument_response = bool(remove_instrument_response)
346
+ self.response_output = str(response_output).upper() if response_output is not None else "VEL"
347
+ self.response_pre_filt = (
348
+ tuple(float(x) for x in response_pre_filt)
349
+ if response_pre_filt is not None else None
350
+ )
351
+ self.response_water_level = response_water_level
352
+ self.response_zero_mean = bool(response_zero_mean)
353
+ self.response_taper = bool(response_taper)
354
+ self.response_taper_fraction = float(response_taper_fraction)
355
+ self.response_error_behavior = response_error_behavior
356
+ self.simulate_instrument_response = bool(simulate_instrument_response)
357
+ self.simulation_response_json = (
358
+ str(simulation_response_json) if simulation_response_json is not None else None
359
+ )
360
+ self.simulation_response_id = (
361
+ str(simulation_response_id) if simulation_response_id is not None else None
362
+ )
363
+ self.simulation_response_selector = dict(simulation_response_selector or {})
364
+ self.simulation_paz = simulation_paz
365
+ self.simulation_output = (
366
+ str(simulation_output).upper()
367
+ if simulation_output is not None else self.response_output
368
+ )
369
+ self.simulation_sensitivity = bool(simulation_sensitivity)
370
+ self.default_location = default_location
371
+ self.dtype = dtype
372
+
373
+ if self.remove_instrument_response and self.instrument_response_json is None:
374
+ raise ValueError(
375
+ "instrument_response_json is required when remove_instrument_response is enabled."
376
+ )
377
+ if self.simulate_instrument_response and (
378
+ self.simulation_paz is None
379
+ and self.simulation_response_id is None
380
+ and not self.simulation_response_selector
381
+ and self.simulation_response_json is None
382
+ and self.instrument_response_json is None
383
+ ):
384
+ raise ValueError(
385
+ "simulate_instrument_response=True requires simulation_paz, "
386
+ "simulation_response_id, simulation_response_selector, "
387
+ "simulation_response_json, or instrument_response_json."
388
+ )
389
+
390
+ self._response_store = None
391
+ self._simulation_response_store = None
392
+ self._response_object_cache = {}
393
+ self._inventory_cache = {}
394
+ self._simulation_response_record = None
395
+ self._simulation_response_object = None
396
+
397
+ @property
398
+ def enabled(self):
399
+ return self.remove_instrument_response or self.simulate_instrument_response
400
+
401
+ def _ensure_response_store(self):
402
+ if self._response_store is None:
403
+ if self.instrument_response_json is None:
404
+ raise ValueError("instrument_response_json is not configured")
405
+ self._response_store = load_response_json(self.instrument_response_json)
406
+ return self._response_store
407
+
408
+ def _ensure_simulation_response_store(self):
409
+ if self._simulation_response_store is None:
410
+ path = self.simulation_response_json or self.instrument_response_json
411
+ if path is None:
412
+ raise ValueError("No simulation response JSON is configured")
413
+ self._simulation_response_store = load_response_json(path)
414
+ return self._simulation_response_store
415
+
416
+ def _get_response_object(self, record):
417
+ response_id = str(record.get("response_id", ""))
418
+ cache_key = response_id or id(record)
419
+ if cache_key not in self._response_object_cache:
420
+ self._response_object_cache[cache_key] = response_from_json_record(record)
421
+ return self._response_object_cache[cache_key]
422
+
423
+ def _get_inventory(self, record):
424
+ response_id = str(record.get("response_id", ""))
425
+ cache_key = response_id or id(record)
426
+ if cache_key not in self._inventory_cache:
427
+ response = self._get_response_object(record)
428
+ self._inventory_cache[cache_key] = inventory_from_response_record(record, response)
429
+ return self._inventory_cache[cache_key]
430
+
431
+ def _find_response_record(self, network, station, location, channel, starttime, endtime=None):
432
+ store = self._ensure_response_store()
433
+ key = (
434
+ str(network),
435
+ str(station),
436
+ normalize_location(location, self.default_location),
437
+ str(channel),
438
+ )
439
+ for record in store["responses_by_key"].get(key, []):
440
+ if response_record_matches_time(record, starttime, endtime):
441
+ return record
442
+ return None
443
+
444
+ def _select_simulation_response_record(self):
445
+ if self._simulation_response_record is not None:
446
+ return self._simulation_response_record
447
+
448
+ store = self._ensure_simulation_response_store()
449
+ record = None
450
+
451
+ if self.simulation_response_id:
452
+ record = store["responses_by_id"].get(self.simulation_response_id)
453
+ if record is None:
454
+ raise KeyError(
455
+ f"simulation_response_id not found: {self.simulation_response_id}"
456
+ )
457
+ elif self.simulation_response_selector:
458
+ sel = self.simulation_response_selector
459
+ key = (
460
+ str(sel.get("network", "")),
461
+ str(sel.get("station", "")),
462
+ normalize_location(sel.get("location", self.default_location), self.default_location),
463
+ str(sel.get("channel", "")),
464
+ )
465
+ starttime = utc_or_none(sel.get("time")) or utc_or_none(sel.get("starttime"))
466
+ for item in store["responses_by_key"].get(key, []):
467
+ if response_record_matches_time(item, starttime):
468
+ record = item
469
+ break
470
+ if record is None:
471
+ raise KeyError(f"simulation_response_selector did not match any response: {sel}")
472
+ else:
473
+ records_by_id = store["responses_by_id"]
474
+ if len(records_by_id) != 1:
475
+ raise ValueError(
476
+ "simulation_response_json must contain exactly one response unless "
477
+ "simulation_response_id or simulation_response_selector is provided."
478
+ )
479
+ record = next(iter(records_by_id.values()))
480
+
481
+ self._simulation_response_record = record
482
+ self._simulation_response_object = self._get_response_object(record)
483
+ return record
484
+
485
+ def _handle_response_error(self, message):
486
+ if self.response_error_behavior == "raise":
487
+ raise RuntimeError(message)
488
+ if self.response_error_behavior == "warn":
489
+ warnings.warn(message, RuntimeWarning, stacklevel=2)
490
+ return None
491
+
492
+ def metadata_template(self):
493
+ return {
494
+ "remove_instrument_response": self.remove_instrument_response,
495
+ "simulate_instrument_response": self.simulate_instrument_response,
496
+ "response_output": self.response_output,
497
+ "simulation_output": self.simulation_output,
498
+ "response_id": "",
499
+ "response_epoch_start": "",
500
+ "response_epoch_end": "",
501
+ "simulation_response_id": "",
502
+ "error": "",
503
+ "processed": False,
504
+ }
505
+
506
+ def apply_to_item(self, item):
507
+ metadata = self.metadata_template()
508
+ item["instrument_processing"] = metadata
509
+
510
+ waveform = item.get("data")
511
+ if waveform is None or len(waveform) == 0 or not self.enabled:
512
+ return item
513
+
514
+ segments = item.get("segments") or []
515
+ first_segment = segments[0] if segments else {}
516
+ network = item.get("network") or first_segment.get("network", "")
517
+ station = item.get("station") or first_segment.get("station", "")
518
+ location = item.get("location") or first_segment.get("location", self.default_location)
519
+ channel = item.get("channel") or first_segment.get("channel", "")
520
+ sampling_rate = float(item.get("sampling_rate"))
521
+ starttime = UTCDateTime(item.get("starttime"))
522
+ endtime = UTCDateTime(item.get("endtime"))
523
+
524
+ try:
525
+ trace = Trace(
526
+ data=np.asarray(waveform, dtype=np.float64),
527
+ header={
528
+ "network": str(network),
529
+ "station": str(station),
530
+ "location": normalize_location(location, self.default_location),
531
+ "channel": str(channel),
532
+ "starttime": starttime,
533
+ "sampling_rate": sampling_rate,
534
+ },
535
+ )
536
+
537
+ if self.remove_instrument_response:
538
+ record = self._find_response_record(
539
+ network,
540
+ station,
541
+ location,
542
+ channel,
543
+ starttime,
544
+ endtime=endtime,
545
+ )
546
+ if record is None:
547
+ key = ".".join([
548
+ str(network),
549
+ str(station),
550
+ normalize_location(location, self.default_location),
551
+ str(channel),
552
+ ])
553
+ raise KeyError(f"No response found for {key} at {starttime}")
554
+
555
+ metadata.update(
556
+ {
557
+ "response_id": record.get("response_id", ""),
558
+ "response_epoch_start": record.get("epoch_start", ""),
559
+ "response_epoch_end": record.get("epoch_end", ""),
560
+ }
561
+ )
562
+ trace.remove_response(
563
+ inventory=self._get_inventory(record),
564
+ output=self.response_output,
565
+ water_level=self.response_water_level,
566
+ pre_filt=self.response_pre_filt,
567
+ zero_mean=self.response_zero_mean,
568
+ taper=self.response_taper,
569
+ taper_fraction=self.response_taper_fraction,
570
+ )
571
+
572
+ if self.simulate_instrument_response:
573
+ if self.simulation_paz is not None:
574
+ trace.simulate(
575
+ paz_remove=None,
576
+ paz_simulate=self.simulation_paz,
577
+ remove_sensitivity=False,
578
+ simulate_sensitivity=self.simulation_sensitivity,
579
+ )
580
+ metadata["simulation_response_id"] = "simulation_paz"
581
+ else:
582
+ sim_record = self._select_simulation_response_record()
583
+ sim_response = self._simulation_response_object
584
+ trace.data = apply_response_spectrum(
585
+ trace.data,
586
+ sampling_rate=trace.stats.sampling_rate,
587
+ response=sim_response,
588
+ output=self.simulation_output,
589
+ )
590
+ metadata["simulation_response_id"] = sim_record.get("response_id", "")
591
+
592
+ metadata["processed"] = True
593
+ item["data"] = np.asarray(trace.data, dtype=self.dtype)
594
+ return item
595
+ except Exception as exc:
596
+ metadata["error"] = str(exc)
597
+ self._handle_response_error(str(exc))
598
+ item["data"] = np.asarray(waveform, dtype=self.dtype)
599
+ return item
600
+
601
+
602
+ def apply_instrument_processing_to_merged(merged, **kwargs):
603
+ processor = InstrumentResponseProcessor(**kwargs)
604
+ for item in merged.values():
605
+ processor.apply_to_item(item)
606
+ return merged
607
+
608
+
609
+ def query_and_merge(
610
+ db_file,
611
+ network="*",
612
+ station="*",
613
+ location="*",
614
+ channel="*",
615
+ starttime=None,
616
+ endtime=None,
617
+ fill_value=0.0,
618
+ dtype=np.float32,
619
+ limit=None,
620
+ instrument_response_json=None,
621
+ remove_instrument_response=False,
622
+ response_output="VEL",
623
+ response_pre_filt=None,
624
+ response_water_level=60,
625
+ response_zero_mean=True,
626
+ response_taper=True,
627
+ response_taper_fraction=0.05,
628
+ response_error_behavior="raise",
629
+ simulate_instrument_response=False,
630
+ simulation_response_json=None,
631
+ simulation_response_id=None,
632
+ simulation_response_selector=None,
633
+ simulation_paz=None,
634
+ simulation_output=None,
635
+ simulation_sensitivity=True,
636
+ default_location=DEFAULT_LOCATION,
637
+ ):
638
+ """
639
+ Query waveform segments and merge them into continuous waveforms.
640
+ """
641
+ rows = query_segments(
642
+ db_file=db_file,
643
+ network=network,
644
+ station=station,
645
+ location=location,
646
+ channel=channel,
647
+ starttime=starttime,
648
+ endtime=endtime,
649
+ limit=limit,
650
+ )
651
+
652
+ merged = merge_segments(
653
+ rows=rows,
654
+ starttime=starttime,
655
+ endtime=endtime,
656
+ fill_value=fill_value,
657
+ dtype=dtype,
658
+ )
659
+
660
+ if remove_instrument_response or simulate_instrument_response:
661
+ apply_instrument_processing_to_merged(
662
+ merged,
663
+ instrument_response_json=instrument_response_json,
664
+ remove_instrument_response=remove_instrument_response,
665
+ response_output=response_output,
666
+ response_pre_filt=response_pre_filt,
667
+ response_water_level=response_water_level,
668
+ response_zero_mean=response_zero_mean,
669
+ response_taper=response_taper,
670
+ response_taper_fraction=response_taper_fraction,
671
+ response_error_behavior=response_error_behavior,
672
+ simulate_instrument_response=simulate_instrument_response,
673
+ simulation_response_json=simulation_response_json,
674
+ simulation_response_id=simulation_response_id,
675
+ simulation_response_selector=simulation_response_selector,
676
+ simulation_paz=simulation_paz,
677
+ simulation_output=simulation_output,
678
+ simulation_sensitivity=simulation_sensitivity,
679
+ default_location=default_location,
680
+ dtype=dtype,
681
+ )
682
+
683
+ return merged, rows
684
+
685
+
686
+ def save_merged_to_npz(merged, output_npz):
687
+ """
688
+ Save merged waveforms and metadata to NPZ.
689
+ """
690
+ arrays = {}
691
+ metadata = {}
692
+
693
+ for key, item in merged.items():
694
+ safe_key = key.replace(".", "_").replace("-", "_")
695
+ arrays[safe_key] = item["data"]
696
+
697
+ meta = dict(item)
698
+ meta.pop("data", None)
699
+ metadata[safe_key] = meta
700
+
701
+ arrays["metadata_json"] = np.array(json.dumps(metadata, ensure_ascii=False))
702
+
703
+ np.savez(output_npz, **arrays)