cangyeone commited on
Commit
192c1dd
·
verified ·
1 Parent(s): cbe8603

Upload scripts/makeh5.py

Browse files
Files changed (1) hide show
  1. scripts/makeh5.py +753 -0
scripts/makeh5.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import os
5
+ import csv
6
+ import argparse
7
+ from pathlib import Path
8
+ from collections import defaultdict
9
+ from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
10
+
11
+ import h5py
12
+ import numpy as np
13
+ from obspy import read, UTCDateTime
14
+
15
+
16
+ DEFAULT_LOCATION = "--"
17
+
18
+
19
+ def normalize_location(location, default=DEFAULT_LOCATION):
20
+ if location is None:
21
+ return default
22
+ location = str(location).strip()
23
+ return location if location else default
24
+
25
+
26
+ def make_station_id(network, station, location, default_location=DEFAULT_LOCATION):
27
+ network = str(network or "").strip()
28
+ station = str(station or "").strip()
29
+ location = normalize_location(location, default_location)
30
+ return f"{network}.{station}.{location}"
31
+
32
+
33
+ def make_station_key(network, station):
34
+ network = str(network or "").strip()
35
+ station = str(station or "").strip()
36
+ return f"{network}.{station}"
37
+
38
+
39
+ def split_station_id(station_id, default_location=DEFAULT_LOCATION):
40
+ parts = str(station_id).split(".")
41
+ network = parts[0] if len(parts) > 0 else ""
42
+ station = parts[1] if len(parts) > 1 else ""
43
+ location = parts[2] if len(parts) > 2 else default_location
44
+ return network, station, normalize_location(location, default_location)
45
+
46
+
47
+ def parse_utc_or_none(value):
48
+ value = str(value or "").strip()
49
+ if not value:
50
+ return None
51
+ return UTCDateTime(value)
52
+
53
+
54
+ def utc_to_group_id(t: UTCDateTime, level: str) -> str:
55
+ if level == "year":
56
+ return f"{t.year:04d}-01-01T00:00:00.000000Z"
57
+ if level == "day":
58
+ return f"{t.year:04d}-{t.month:02d}-{t.day:02d}T00:00:00.000000Z"
59
+ raise ValueError(f"Unsupported level: {level}")
60
+
61
+
62
+ def day_file_id(t: UTCDateTime) -> str:
63
+ return f"{t.year:04d}{t.month:02d}{t.day:02d}"
64
+
65
+
66
+ def set_common_attrs(obj, level, node_type, parent_type):
67
+ obj.attrs["level"] = level
68
+ obj.attrs["type"] = node_type
69
+ obj.attrs["parent_type"] = parent_type
70
+
71
+
72
+ def load_station_locations_csv(loc_file, default_location=DEFAULT_LOCATION):
73
+ """
74
+ 支持两种格式:
75
+
76
+ 1. 有表头:
77
+ net,sta,lat,lon,elev_m,start,end
78
+
79
+ 2. 无表头:
80
+ CI,WBM,35.60839,-117.89049,892.0,1979-09-26T00:00:00.000000Z,3000-01-01T00:00:00.000000Z
81
+
82
+ 注意:
83
+ 位置匹配只使用 network.station,不使用 location。
84
+ """
85
+ locations = defaultdict(list)
86
+
87
+ if not loc_file or not os.path.exists(loc_file):
88
+ print(f"[WARN] Location CSV file not found: {loc_file}")
89
+ return dict(locations)
90
+
91
+ with open(loc_file, "r", encoding="utf-8-sig", newline="") as f:
92
+ sample = f.readline()
93
+ f.seek(0)
94
+
95
+ first_cols = [x.strip().lower() for x in sample.strip().split(",")]
96
+ has_header = {"net", "sta", "lat", "lon"}.issubset(set(first_cols))
97
+
98
+ if has_header:
99
+ reader = csv.DictReader(f)
100
+
101
+ for line_no, row in enumerate(reader, start=2):
102
+ try:
103
+ net = row["net"].strip()
104
+ sta = row["sta"].strip()
105
+ loc = normalize_location(row.get("location", default_location), default_location)
106
+
107
+ start = parse_utc_or_none(row["start"])
108
+ end = parse_utc_or_none(row["end"])
109
+
110
+ key = make_station_key(net, sta)
111
+
112
+ locations[key].append(
113
+ {
114
+ "network": net,
115
+ "station": sta,
116
+ "location": loc,
117
+ "latitude": float(row["lat"]),
118
+ "longitude": float(row["lon"]),
119
+ "elevation": float(row["elev_m"]),
120
+ "start": start,
121
+ "end": end,
122
+ "starttime": str(start) if start is not None else "",
123
+ "endtime": str(end) if end is not None else "",
124
+ }
125
+ )
126
+ except Exception as e:
127
+ print(f"[WARN] Failed to parse location CSV line {line_no}: {row}, error={e}")
128
+
129
+ else:
130
+ reader = csv.reader(f)
131
+
132
+ for line_no, row in enumerate(reader, start=1):
133
+ if not row or len(row) < 7:
134
+ continue
135
+
136
+ try:
137
+ net = row[0].strip()
138
+ sta = row[1].strip()
139
+ lat = float(row[2])
140
+ lon = float(row[3])
141
+ elev = float(row[4])
142
+ start = parse_utc_or_none(row[5])
143
+ end = parse_utc_or_none(row[6])
144
+
145
+ key = make_station_key(net, sta)
146
+
147
+ locations[key].append(
148
+ {
149
+ "network": net,
150
+ "station": sta,
151
+ "location": default_location,
152
+ "latitude": lat,
153
+ "longitude": lon,
154
+ "elevation": elev,
155
+ "start": start,
156
+ "end": end,
157
+ "starttime": str(start) if start is not None else "",
158
+ "endtime": str(end) if end is not None else "",
159
+ }
160
+ )
161
+ except Exception as e:
162
+ print(f"[WARN] Failed to parse location CSV line {line_no}: {row}, error={e}")
163
+
164
+ for key in locations:
165
+ locations[key].sort(
166
+ key=lambda x: x["start"] if x["start"] is not None else UTCDateTime(0)
167
+ )
168
+
169
+ return dict(locations)
170
+
171
+
172
+ def match_station_location(
173
+ station_locations,
174
+ station_id,
175
+ trace_start=None,
176
+ trace_end=None,
177
+ allow_fallback=True,
178
+ ):
179
+ """
180
+ 只按 network.station 匹配台站位置。
181
+ 不使用 location code。
182
+
183
+ 例如:
184
+ waveform station_id = BK.BDM.00
185
+ location key = BK.BDM
186
+ """
187
+ net, sta, _ = split_station_id(station_id)
188
+ station_key = make_station_key(net, sta)
189
+
190
+ records = station_locations.get(station_key, [])
191
+
192
+ if not records:
193
+ return None, "default_nan_no_station_record"
194
+
195
+ if trace_start is None and trace_end is None:
196
+ if allow_fallback:
197
+ return records[-1], "fallback_nearest_time_network_station_only"
198
+ return None, "default_nan_no_time_matched_position"
199
+
200
+ matched = []
201
+
202
+ for rec in records:
203
+ rec_start = rec.get("start")
204
+ rec_end = rec.get("end")
205
+
206
+ left_ok = True if rec_end is None or trace_start is None else trace_start < rec_end
207
+ right_ok = True if rec_start is None or trace_end is None else trace_end >= rec_start
208
+
209
+ if left_ok and right_ok:
210
+ matched.append(rec)
211
+
212
+ if matched:
213
+ def strict_score(rec):
214
+ rec_start = rec.get("start")
215
+ if rec_start is None or trace_start is None:
216
+ return 0
217
+ if rec_start <= trace_start:
218
+ return abs(trace_start - rec_start)
219
+ return abs(trace_start - rec_start) + 1e12
220
+
221
+ return sorted(matched, key=strict_score)[0], "strict_time_matched_network_station_only"
222
+
223
+ if not allow_fallback:
224
+ return None, "default_nan_no_time_matched_position"
225
+
226
+ def fallback_score(rec):
227
+ if trace_start is None:
228
+ return 0
229
+
230
+ candidates = []
231
+ if rec.get("start") is not None:
232
+ candidates.append(abs(trace_start - rec["start"]))
233
+ if rec.get("end") is not None:
234
+ candidates.append(abs(trace_start - rec["end"]))
235
+
236
+ return min(candidates) if candidates else 0
237
+
238
+ return sorted(records, key=fallback_score)[0], "fallback_nearest_time_network_station_only"
239
+
240
+
241
+ def find_mseed_files(input_dir):
242
+ input_dir = Path(input_dir)
243
+
244
+ suffixes = {
245
+ ".mseed", ".msd", ".miniseed", ".seed",
246
+ ".MSEED", ".MSD", ".MINISEED", ".SEED",
247
+ }
248
+
249
+ return sorted(
250
+ p for p in input_dir.rglob("*")
251
+ if p.is_file() and p.suffix in suffixes
252
+ )
253
+
254
+
255
+ def read_one_mseed(mseed_file, default_location=DEFAULT_LOCATION):
256
+ records = []
257
+
258
+ try:
259
+ st = read(str(mseed_file))
260
+ except Exception as e:
261
+ return records, f"[WARN] Failed to read {mseed_file}: {e}"
262
+
263
+ for tr in st:
264
+ net = tr.stats.network or ""
265
+ sta = tr.stats.station or ""
266
+ loc = normalize_location(tr.stats.location, default_location)
267
+ cha = tr.stats.channel or ""
268
+
269
+ start = tr.stats.starttime
270
+ end = tr.stats.endtime
271
+
272
+ station_id = make_station_id(net, sta, loc, default_location)
273
+
274
+ records.append(
275
+ {
276
+ "year_id": utc_to_group_id(start, "year"),
277
+ "day_id": utc_to_group_id(start, "day"),
278
+ "day_file_id": day_file_id(start),
279
+ "station_id": station_id,
280
+ "channel": cha,
281
+ "starttime_obj": start,
282
+ "endtime_obj": end,
283
+ "starttime": str(start),
284
+ "endtime": str(end),
285
+ "sampling_rate": float(tr.stats.sampling_rate),
286
+ "delta": float(tr.stats.delta),
287
+ "npts": int(tr.stats.npts),
288
+ "network": net,
289
+ "station": sta,
290
+ "location": loc,
291
+ "data": np.asarray(tr.data),
292
+ "dtype": str(tr.data.dtype),
293
+ "source_file": str(mseed_file),
294
+ }
295
+ )
296
+
297
+ return records, None
298
+
299
+
300
+ def write_position_attrs(obj, matched, match_mode):
301
+ obj.attrs["position_match_mode"] = match_mode
302
+ obj.attrs["position_is_fallback"] = "fallback" in str(match_mode)
303
+
304
+ if matched is not None:
305
+ obj.attrs["longitude"] = matched.get("longitude", np.nan)
306
+ obj.attrs["latitude"] = matched.get("latitude", np.nan)
307
+ obj.attrs["elevation"] = matched.get("elevation", np.nan)
308
+ obj.attrs["location_available"] = True
309
+ obj.attrs["location_source"] = match_mode
310
+ obj.attrs["station_position_starttime"] = matched.get("starttime", "")
311
+ obj.attrs["station_position_endtime"] = matched.get("endtime", "")
312
+ else:
313
+ obj.attrs["longitude"] = np.nan
314
+ obj.attrs["latitude"] = np.nan
315
+ obj.attrs["elevation"] = np.nan
316
+ obj.attrs["location_available"] = False
317
+ obj.attrs["location_source"] = match_mode
318
+ obj.attrs["station_position_starttime"] = ""
319
+ obj.attrs["station_position_endtime"] = ""
320
+
321
+
322
+ def write_station_position_history(station_grp, station_id, station_locations, default_location):
323
+ if "position_history" in station_grp:
324
+ return
325
+
326
+ net, sta, _ = split_station_id(station_id, default_location)
327
+ station_key = make_station_key(net, sta)
328
+
329
+ pos_grp = station_grp.create_group("position_history")
330
+ set_common_attrs(pos_grp, "position_history", "position_history_group", "station_group")
331
+
332
+ records = station_locations.get(station_key, [])
333
+ pos_grp.attrs["record_count"] = len(records)
334
+ pos_grp.attrs["match_key"] = station_key
335
+ pos_grp.attrs["match_rule"] = "network.station only; location ignored"
336
+
337
+ for i, rec in enumerate(records):
338
+ item_grp = pos_grp.create_group(str(i))
339
+ set_common_attrs(item_grp, "position_record", "position_record_group", "position_history_group")
340
+
341
+ item_grp.attrs["network"] = rec.get("network", "")
342
+ item_grp.attrs["station"] = rec.get("station", "")
343
+ item_grp.attrs["location"] = rec.get("location", default_location)
344
+ item_grp.attrs["longitude"] = rec.get("longitude", np.nan)
345
+ item_grp.attrs["latitude"] = rec.get("latitude", np.nan)
346
+ item_grp.attrs["elevation"] = rec.get("elevation", np.nan)
347
+ item_grp.attrs["starttime"] = rec.get("starttime", "")
348
+ item_grp.attrs["endtime"] = rec.get("endtime", "")
349
+
350
+
351
+ def init_hdf5_root(h5, default_location, split_by_day=False):
352
+ set_common_attrs(h5, "root", "hdf5_file", "none")
353
+ h5.attrs["description"] = "Continuous waveform dataset converted from MiniSEED"
354
+ h5.attrs["station_id_format"] = "network.station.location"
355
+ h5.attrs["station_location_match_rule"] = "network.station only; location ignored"
356
+ h5.attrs["empty_location_value"] = default_location
357
+ h5.attrs["missing_coordinate_value"] = "NaN"
358
+ h5.attrs["station_location_format"] = (
359
+ "CSV with header: net,sta,lat,lon,elev_m,start,end "
360
+ "or no-header: net,sta,lat,lon,elev_m,start,end"
361
+ )
362
+ h5.attrs["split_by_day"] = bool(split_by_day)
363
+
364
+
365
+ def get_or_create_station_group(
366
+ h5,
367
+ year_id,
368
+ day_id,
369
+ station_id,
370
+ station_locations,
371
+ trace_start,
372
+ trace_end,
373
+ default_location,
374
+ ):
375
+ year_grp = h5.require_group(year_id)
376
+ set_common_attrs(year_grp, "year", "year_group", "root")
377
+ year_grp.attrs["utc_time"] = year_id
378
+
379
+ day_grp = year_grp.require_group(day_id)
380
+ set_common_attrs(day_grp, "day", "day_group", "year_group")
381
+ day_grp.attrs["utc_time"] = day_id
382
+
383
+ stations_grp = day_grp.require_group("stations")
384
+ set_common_attrs(stations_grp, "stations", "stations_group", "day_group")
385
+ stations_grp.attrs["description"] = "Container group for all stations under this day"
386
+
387
+ station_grp = stations_grp.require_group(station_id)
388
+ set_common_attrs(station_grp, "station", "station_group", "stations_group")
389
+
390
+ network, station, location = split_station_id(station_id, default_location)
391
+ station_grp.attrs["station_id"] = station_id
392
+ station_grp.attrs["station_key"] = make_station_key(network, station)
393
+ station_grp.attrs["network"] = network
394
+ station_grp.attrs["station"] = station
395
+ station_grp.attrs["location"] = location
396
+ station_grp.attrs["location_default_value"] = default_location
397
+ station_grp.attrs["location_is_default"] = location == default_location
398
+ station_grp.attrs["instrument_time_range_start"] = str(trace_start)
399
+ station_grp.attrs["instrument_time_range_end"] = str(trace_end)
400
+
401
+ matched, match_mode = match_station_location(
402
+ station_locations=station_locations,
403
+ station_id=station_id,
404
+ trace_start=trace_start,
405
+ trace_end=trace_end,
406
+ allow_fallback=True,
407
+ )
408
+ write_position_attrs(station_grp, matched, match_mode)
409
+
410
+ write_station_position_history(
411
+ station_grp=station_grp,
412
+ station_id=station_id,
413
+ station_locations=station_locations,
414
+ default_location=default_location,
415
+ )
416
+
417
+ waveform_grp = station_grp.require_group("waveform")
418
+ set_common_attrs(waveform_grp, "waveform", "waveform_group", "station_group")
419
+
420
+ return station_grp, waveform_grp
421
+
422
+
423
+ def next_dataset_index(channel_grp):
424
+ max_idx = -1
425
+ for key in channel_grp.keys():
426
+ if str(key).isdigit():
427
+ max_idx = max(max_idx, int(key))
428
+ return max_idx + 1
429
+
430
+
431
+ def update_channel_summary_attrs(channel_grp, rec):
432
+ channel_grp.attrs["channel"] = rec["channel"]
433
+
434
+ old_count = int(channel_grp.attrs.get("segment_count", 0))
435
+ channel_grp.attrs["segment_count"] = old_count + 1
436
+
437
+ rec_start = rec["starttime_obj"]
438
+ rec_end = rec["endtime_obj"]
439
+
440
+ old_start = channel_grp.attrs.get("starttime", "")
441
+ old_end = channel_grp.attrs.get("endtime", "")
442
+
443
+ if not old_start:
444
+ channel_grp.attrs["starttime"] = str(rec_start)
445
+ else:
446
+ old_start_t = UTCDateTime(str(old_start))
447
+ channel_grp.attrs["starttime"] = str(min(old_start_t, rec_start))
448
+
449
+ if not old_end:
450
+ channel_grp.attrs["endtime"] = str(rec_end)
451
+ else:
452
+ old_end_t = UTCDateTime(str(old_end))
453
+ channel_grp.attrs["endtime"] = str(max(old_end_t, rec_end))
454
+
455
+
456
+ def write_one_record(
457
+ h5,
458
+ rec,
459
+ station_locations,
460
+ default_location,
461
+ compression,
462
+ compression_opts,
463
+ shuffle,
464
+ ):
465
+ station_grp, waveform_grp = get_or_create_station_group(
466
+ h5=h5,
467
+ year_id=rec["year_id"],
468
+ day_id=rec["day_id"],
469
+ station_id=rec["station_id"],
470
+ station_locations=station_locations,
471
+ trace_start=rec["starttime_obj"],
472
+ trace_end=rec["endtime_obj"],
473
+ default_location=default_location,
474
+ )
475
+
476
+ channel_grp = waveform_grp.require_group(rec["channel"])
477
+ set_common_attrs(channel_grp, "channel", "channel_group", "waveform_group")
478
+
479
+ update_channel_summary_attrs(channel_grp, rec)
480
+
481
+ matched, match_mode = match_station_location(
482
+ station_locations=station_locations,
483
+ station_id=rec["station_id"],
484
+ trace_start=rec["starttime_obj"],
485
+ trace_end=rec["endtime_obj"],
486
+ allow_fallback=True,
487
+ )
488
+ write_position_attrs(channel_grp, matched, match_mode)
489
+
490
+ ds_name = str(next_dataset_index(channel_grp))
491
+
492
+ create_kwargs = {}
493
+ if compression and compression.lower() != "none":
494
+ create_kwargs["compression"] = compression
495
+ if compression.lower() == "gzip":
496
+ create_kwargs["compression_opts"] = compression_opts
497
+ create_kwargs["shuffle"] = shuffle
498
+
499
+ ds = channel_grp.create_dataset(
500
+ ds_name,
501
+ data=rec["data"],
502
+ **create_kwargs,
503
+ )
504
+
505
+ set_common_attrs(ds, "segment", "waveform_dataset", "channel_group")
506
+
507
+ write_position_attrs(ds, matched, match_mode)
508
+
509
+ ds.attrs["segment_index"] = int(ds_name)
510
+ ds.attrs["network"] = rec["network"]
511
+ ds.attrs["station"] = rec["station"]
512
+ ds.attrs["station_key"] = make_station_key(rec["network"], rec["station"])
513
+ ds.attrs["location"] = rec["location"]
514
+ ds.attrs["location_is_default"] = rec["location"] == default_location
515
+ ds.attrs["channel"] = rec["channel"]
516
+ ds.attrs["sampling_rate"] = rec["sampling_rate"]
517
+ ds.attrs["delta"] = rec["delta"]
518
+ ds.attrs["npts"] = rec["npts"]
519
+ ds.attrs["starttime"] = rec["starttime"]
520
+ ds.attrs["endtime"] = rec["endtime"]
521
+ ds.attrs["mseed_source_file"] = rec["source_file"]
522
+ ds.attrs["dtype"] = rec["dtype"]
523
+
524
+
525
+ def output_path_for_day(output, day_id):
526
+ output = Path(output)
527
+
528
+ if output.suffix.lower() in [".h5", ".hdf5"]:
529
+ out_dir = output.parent
530
+ stem = output.stem
531
+ else:
532
+ out_dir = output
533
+ stem = "continuous_waveform"
534
+
535
+ out_dir.mkdir(parents=True, exist_ok=True)
536
+ return out_dir / f"{stem}_{day_id}.h5"
537
+
538
+
539
+ def convert_mseed_to_hdf5_streaming(
540
+ mseed_files,
541
+ station_locations,
542
+ output_file,
543
+ num_workers=4,
544
+ max_pending=16,
545
+ default_location=DEFAULT_LOCATION,
546
+ compression="gzip",
547
+ compression_opts=4,
548
+ shuffle=True,
549
+ split_by_day=False,
550
+ ):
551
+ total = len(mseed_files)
552
+ submitted = 0
553
+ finished = 0
554
+ written_records = 0
555
+
556
+ h5_files = {}
557
+
558
+ def get_h5_for_record(rec):
559
+ if not split_by_day:
560
+ key = "__single__"
561
+ if key not in h5_files:
562
+ output_path = Path(output_file)
563
+ output_path.parent.mkdir(parents=True, exist_ok=True)
564
+ h5 = h5py.File(output_path, "w")
565
+ init_hdf5_root(h5, default_location, split_by_day=False)
566
+ h5_files[key] = h5
567
+ return h5_files[key]
568
+
569
+ key = rec["day_file_id"]
570
+ if key not in h5_files:
571
+ output_path = output_path_for_day(output_file, key)
572
+ h5 = h5py.File(output_path, "w")
573
+ init_hdf5_root(h5, default_location, split_by_day=True)
574
+ h5.attrs["day_file_id"] = key
575
+ h5_files[key] = h5
576
+ return h5_files[key]
577
+
578
+ try:
579
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
580
+ pending = set()
581
+
582
+ def submit_more():
583
+ nonlocal submitted
584
+ while submitted < total and len(pending) < max_pending:
585
+ future = executor.submit(
586
+ read_one_mseed,
587
+ mseed_files[submitted],
588
+ default_location,
589
+ )
590
+ pending.add(future)
591
+ submitted += 1
592
+
593
+ submit_more()
594
+
595
+ while pending:
596
+ done, pending_remaining = wait(pending, return_when=FIRST_COMPLETED)
597
+ pending = pending_remaining
598
+
599
+ for future in done:
600
+ finished += 1
601
+ records, warning = future.result()
602
+
603
+ if warning:
604
+ print(warning)
605
+
606
+ records.sort(
607
+ key=lambda r: (
608
+ r["day_file_id"],
609
+ r["year_id"],
610
+ r["day_id"],
611
+ r["station_id"],
612
+ r["channel"],
613
+ r["starttime_obj"],
614
+ )
615
+ )
616
+
617
+ for rec in records:
618
+ h5 = get_h5_for_record(rec)
619
+
620
+ write_one_record(
621
+ h5=h5,
622
+ rec=rec,
623
+ station_locations=station_locations,
624
+ default_location=default_location,
625
+ compression=compression,
626
+ compression_opts=compression_opts,
627
+ shuffle=shuffle,
628
+ )
629
+ written_records += 1
630
+
631
+ if finished % 100 == 0 or finished == total:
632
+ print(
633
+ f"[INFO] Progress: files {finished}/{total}, "
634
+ f"written waveform segments {written_records}, "
635
+ f"open hdf5 files {len(h5_files)}"
636
+ )
637
+
638
+ del records
639
+
640
+ submit_more()
641
+
642
+ finally:
643
+ for h5 in h5_files.values():
644
+ h5.close()
645
+
646
+ print(f"[OK] Written waveform segments: {written_records}")
647
+
648
+ if split_by_day:
649
+ print(f"[OK] HDF5 files written by day under: {Path(output_file).parent if Path(output_file).suffix else output_file}")
650
+ else:
651
+ print(f"[OK] HDF5 written to: {output_file}")
652
+
653
+
654
+ def main():
655
+ parser = argparse.ArgumentParser(
656
+ description="Convert MiniSEED files to hierarchical HDF5."
657
+ )
658
+
659
+ parser.add_argument(
660
+ "--input_dir",
661
+ default="data/continous_usa/data",
662
+ help="Directory containing MiniSEED files.",
663
+ )
664
+
665
+ parser.add_argument(
666
+ "--loc_file",
667
+ default="data/continous_usa/stations.csv",
668
+ help="Station CSV file.",
669
+ )
670
+
671
+ parser.add_argument(
672
+ "--output",
673
+ default="data/hdf5/continuous_waveform_usa.h5",
674
+ help=(
675
+ "Output HDF5 file. If --split_by_day is enabled, this is used as "
676
+ "a filename prefix, e.g. continuous_waveform_usa_20190701.h5."
677
+ ),
678
+ )
679
+
680
+ parser.add_argument(
681
+ "--split_by_day",
682
+ action="store_true",
683
+ default=True,
684
+ help="Write one HDF5 file per day.",
685
+ )
686
+
687
+ parser.add_argument(
688
+ "--num_workers",
689
+ type=int,
690
+ default=2,
691
+ help="Number of threads for reading MiniSEED files.",
692
+ )
693
+
694
+ parser.add_argument(
695
+ "--max_pending",
696
+ type=int,
697
+ default=4,
698
+ help="Maximum number of pending read tasks.",
699
+ )
700
+
701
+ parser.add_argument(
702
+ "--default_location",
703
+ default=DEFAULT_LOCATION,
704
+ help='Default location code when MiniSEED location is empty. Default: "--".',
705
+ )
706
+
707
+ parser.add_argument(
708
+ "--compression",
709
+ default="gzip",
710
+ choices=["gzip", "lzf", "none"],
711
+ help="Dataset compression method.",
712
+ )
713
+
714
+ parser.add_argument(
715
+ "--compression_opts",
716
+ type=int,
717
+ default=4,
718
+ help="Compression level for gzip.",
719
+ )
720
+
721
+ parser.add_argument(
722
+ "--no_shuffle",
723
+ action="store_true",
724
+ help="Disable HDF5 shuffle filter.",
725
+ )
726
+
727
+ args = parser.parse_args()
728
+
729
+ station_locations = load_station_locations_csv(
730
+ args.loc_file,
731
+ default_location=args.default_location,
732
+ )
733
+ print(f"[INFO] Loaded station location histories for {len(station_locations)} station keys.")
734
+
735
+ mseed_files = find_mseed_files(args.input_dir)
736
+ print(f"[INFO] Found {len(mseed_files)} MiniSEED files.")
737
+
738
+ convert_mseed_to_hdf5_streaming(
739
+ mseed_files=mseed_files,
740
+ station_locations=station_locations,
741
+ output_file=args.output,
742
+ num_workers=args.num_workers,
743
+ max_pending=args.max_pending,
744
+ default_location=args.default_location,
745
+ compression=args.compression,
746
+ compression_opts=args.compression_opts,
747
+ shuffle=not args.no_shuffle,
748
+ split_by_day=args.split_by_day,
749
+ )
750
+
751
+
752
+ if __name__ == "__main__":
753
+ main()