cangyeone commited on
Commit
d2dce16
·
verified ·
1 Parent(s): cbf8e76

Upload utils/waveform_index_api.py

Browse files
Files changed (1) hide show
  1. utils/waveform_index_api.py +349 -0
utils/waveform_index_api.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import sqlite3
5
+ from collections import defaultdict
6
+
7
+ import h5py
8
+ import numpy as np
9
+ from obspy import UTCDateTime
10
+
11
+
12
+ def parse_time_to_epoch(t):
13
+ return float(UTCDateTime(t).timestamp)
14
+
15
+
16
+ def epoch_to_utc(t):
17
+ return str(UTCDateTime(float(t)))
18
+
19
+
20
+ def wildcard_to_sql_like(pattern):
21
+ """
22
+ Convert wildcard pattern to SQL LIKE pattern.
23
+
24
+ Examples:
25
+ "*" -> "%"
26
+ "BK" -> "BK"
27
+ "B*" -> "B%"
28
+ "*Z" -> "%Z"
29
+ "BH*" -> "BH%"
30
+ """
31
+ if pattern is None or str(pattern).strip() == "":
32
+ return "%"
33
+
34
+ return str(pattern).strip().replace("*", "%")
35
+
36
+
37
+ def query_segments(
38
+ db_file,
39
+ network="*",
40
+ station="*",
41
+ location="*",
42
+ channel="*",
43
+ starttime=None,
44
+ endtime=None,
45
+ limit=None,
46
+ ):
47
+ """
48
+ Query waveform segments from SQLite index.
49
+
50
+ Parameters
51
+ ----------
52
+ db_file : str
53
+ SQLite index database path.
54
+ network : str
55
+ Network code or wildcard pattern, e.g. "BK", "C*", "*".
56
+ station : str
57
+ Station code or wildcard pattern, e.g. "BDM", "BD*", "*".
58
+ location : str
59
+ Location code or wildcard pattern, e.g. "00", "--", "*".
60
+ channel : str
61
+ Channel code or wildcard pattern, e.g. "BHE", "BH*", "*Z", "*".
62
+ starttime : str
63
+ Query start time.
64
+ endtime : str
65
+ Query end time.
66
+ limit : int or None
67
+ Optional maximum number of returned segments.
68
+
69
+ Returns
70
+ -------
71
+ rows : list[dict]
72
+ Matched waveform segment metadata.
73
+ """
74
+
75
+ if starttime is None or endtime is None:
76
+ raise ValueError("starttime and endtime are required.")
77
+
78
+ query_start = parse_time_to_epoch(starttime)
79
+ query_end = parse_time_to_epoch(endtime)
80
+
81
+ sql = """
82
+ SELECT *
83
+ FROM waveform_segments
84
+ WHERE network LIKE ?
85
+ AND station LIKE ?
86
+ AND location LIKE ?
87
+ AND channel LIKE ?
88
+ AND end_epoch >= ?
89
+ AND start_epoch <= ?
90
+ ORDER BY network, station, location, channel, start_epoch
91
+ """
92
+
93
+ params = [
94
+ wildcard_to_sql_like(network),
95
+ wildcard_to_sql_like(station),
96
+ wildcard_to_sql_like(location),
97
+ wildcard_to_sql_like(channel),
98
+ query_start,
99
+ query_end,
100
+ ]
101
+
102
+ if limit is not None:
103
+ sql += " LIMIT ?"
104
+ params.append(int(limit))
105
+
106
+ conn = sqlite3.connect(db_file)
107
+ conn.row_factory = sqlite3.Row
108
+
109
+ try:
110
+ cur = conn.cursor()
111
+ cur.execute(sql, params)
112
+ rows = [dict(r) for r in cur.fetchall()]
113
+ finally:
114
+ conn.close()
115
+
116
+ return rows
117
+
118
+
119
+ def read_hdf5_segment(row):
120
+ """
121
+ Read a single waveform segment from HDF5 using h5_file and dataset_path.
122
+ """
123
+ with h5py.File(row["h5_file"], "r") as h5:
124
+ data = h5[row["dataset_path"]][()]
125
+
126
+ return np.asarray(data)
127
+
128
+
129
+ def trim_segment_to_window(data, row, starttime, endtime):
130
+ """
131
+ Trim one segment to the requested time window.
132
+ """
133
+ sr = float(row["sampling_rate"])
134
+
135
+ seg_start = float(row["start_epoch"])
136
+ seg_end = float(row["end_epoch"])
137
+
138
+ query_start = parse_time_to_epoch(starttime)
139
+ query_end = parse_time_to_epoch(endtime)
140
+
141
+ use_start = max(seg_start, query_start)
142
+ use_end = min(seg_end, query_end)
143
+
144
+ if use_end < use_start:
145
+ return data[:0], use_start, use_end
146
+
147
+ i0 = int(round((use_start - seg_start) * sr))
148
+ i1 = int(round((use_end - seg_start) * sr)) + 1
149
+
150
+ i0 = max(i0, 0)
151
+ i1 = min(i1, len(data))
152
+
153
+ return data[i0:i1], use_start, use_end
154
+
155
+
156
+ def merge_segments(
157
+ rows,
158
+ starttime,
159
+ endtime,
160
+ fill_value=0.0,
161
+ dtype=np.float32,
162
+ ):
163
+ """
164
+ Merge multiple waveform segments into continuous arrays.
165
+
166
+ Segments are grouped by:
167
+ network.station.location.channel
168
+
169
+ Missing samples are filled by fill_value.
170
+
171
+ Returns
172
+ -------
173
+ merged : dict
174
+ {
175
+ "BK.BDM.00.BHE": {
176
+ "data": np.ndarray,
177
+ "network": "BK",
178
+ "station": "BDM",
179
+ "location": "00",
180
+ "channel": "BHE",
181
+ "starttime": "...",
182
+ "endtime": "...",
183
+ "sampling_rate": 100.0,
184
+ "npts": 360001,
185
+ "segments": [...]
186
+ },
187
+ ...
188
+ }
189
+ """
190
+
191
+ if len(rows) == 0:
192
+ return {}
193
+
194
+ query_start = parse_time_to_epoch(starttime)
195
+ query_end = parse_time_to_epoch(endtime)
196
+
197
+ groups = defaultdict(list)
198
+
199
+ for row in rows:
200
+ key = (
201
+ row["network"],
202
+ row["station"],
203
+ row["location"],
204
+ row["channel"],
205
+ )
206
+ groups[key].append(row)
207
+
208
+ merged = {}
209
+
210
+ for key, seg_rows in groups.items():
211
+ network, station, location, channel = key
212
+
213
+ seg_rows = sorted(seg_rows, key=lambda r: float(r["start_epoch"]))
214
+
215
+ sampling_rates = sorted(set(float(r["sampling_rate"]) for r in seg_rows))
216
+ if len(sampling_rates) != 1:
217
+ raise ValueError(
218
+ f"Multiple sampling rates found for {network}.{station}.{location}.{channel}: "
219
+ f"{sampling_rates}"
220
+ )
221
+
222
+ sr = sampling_rates[0]
223
+
224
+ npts = int(round((query_end - query_start) * sr)) + 1
225
+ out = np.full(npts, fill_value, dtype=dtype)
226
+ filled = np.zeros(npts, dtype=bool)
227
+
228
+ used_segments = []
229
+
230
+ for row in seg_rows:
231
+ data = read_hdf5_segment(row)
232
+ data, use_start, use_end = trim_segment_to_window(
233
+ data,
234
+ row,
235
+ starttime=starttime,
236
+ endtime=endtime,
237
+ )
238
+
239
+ if len(data) == 0:
240
+ continue
241
+
242
+ i0 = int(round((use_start - query_start) * sr))
243
+ i1 = i0 + len(data)
244
+
245
+ if i0 < 0:
246
+ data = data[-i0:]
247
+ i0 = 0
248
+
249
+ if i1 > npts:
250
+ data = data[: npts - i0]
251
+ i1 = npts
252
+
253
+ if i0 >= i1:
254
+ continue
255
+
256
+ target = slice(i0, i1)
257
+ mask = ~filled[target]
258
+
259
+ out[target][mask] = data[: i1 - i0][mask].astype(dtype, copy=False)
260
+ filled[target][mask] = True
261
+
262
+ used_segments.append(
263
+ {
264
+ "h5_file": row["h5_file"],
265
+ "dataset_path": row["dataset_path"],
266
+ "segment_starttime": row["starttime"],
267
+ "segment_endtime": row["endtime"],
268
+ "used_starttime": epoch_to_utc(use_start),
269
+ "used_endtime": epoch_to_utc(use_end),
270
+ "npts": int(len(data)),
271
+ }
272
+ )
273
+
274
+ out_key = f"{network}.{station}.{location}.{channel}"
275
+
276
+ merged[out_key] = {
277
+ "data": out,
278
+ "network": network,
279
+ "station": station,
280
+ "location": location,
281
+ "channel": channel,
282
+ "starttime": str(UTCDateTime(starttime)),
283
+ "endtime": str(UTCDateTime(endtime)),
284
+ "sampling_rate": sr,
285
+ "npts": int(len(out)),
286
+ "filled_ratio": float(filled.mean()) if len(filled) > 0 else 0.0,
287
+ "segments": used_segments,
288
+ }
289
+
290
+ return merged
291
+
292
+
293
+ def query_and_merge(
294
+ db_file,
295
+ network="*",
296
+ station="*",
297
+ location="*",
298
+ channel="*",
299
+ starttime=None,
300
+ endtime=None,
301
+ fill_value=0.0,
302
+ dtype=np.float32,
303
+ limit=None,
304
+ ):
305
+ """
306
+ Query waveform segments and merge them into continuous waveforms.
307
+ """
308
+ rows = query_segments(
309
+ db_file=db_file,
310
+ network=network,
311
+ station=station,
312
+ location=location,
313
+ channel=channel,
314
+ starttime=starttime,
315
+ endtime=endtime,
316
+ limit=limit,
317
+ )
318
+
319
+ merged = merge_segments(
320
+ rows=rows,
321
+ starttime=starttime,
322
+ endtime=endtime,
323
+ fill_value=fill_value,
324
+ dtype=dtype,
325
+ )
326
+
327
+ return merged, rows
328
+
329
+
330
+ def save_merged_to_npz(merged, output_npz):
331
+ """
332
+ Save merged waveforms and metadata to NPZ.
333
+ """
334
+ arrays = {}
335
+ metadata = {}
336
+
337
+ for key, item in merged.items():
338
+ safe_key = key.replace(".", "_").replace("-", "_")
339
+ arrays[safe_key] = item["data"]
340
+
341
+ meta = dict(item)
342
+ meta.pop("data", None)
343
+ metadata[safe_key] = meta
344
+
345
+ arrays["metadata_json"] = np.array(
346
+ __import__("json").dumps(metadata, ensure_ascii=False)
347
+ )
348
+
349
+ np.savez(output_npz, **arrays)