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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 floor_utc_to_interval(t: UTCDateTime, interval_seconds):
|
| 63 |
+
"""Return the UTC start time of the fixed-length interval containing t."""
|
| 64 |
+
if interval_seconds is None:
|
| 65 |
+
return None
|
| 66 |
+
interval_seconds = int(interval_seconds)
|
| 67 |
+
if interval_seconds <= 0:
|
| 68 |
+
raise ValueError("interval_seconds must be positive")
|
| 69 |
+
|
| 70 |
+
ts = float(t.timestamp)
|
| 71 |
+
start_ts = int(ts // interval_seconds) * interval_seconds
|
| 72 |
+
return UTCDateTime(start_ts)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def interval_file_id(t: UTCDateTime, interval_seconds) -> str:
|
| 76 |
+
"""Create a safe file id from the interval start time."""
|
| 77 |
+
if interval_seconds is None:
|
| 78 |
+
return "single"
|
| 79 |
+
|
| 80 |
+
interval_start = floor_utc_to_interval(t, interval_seconds)
|
| 81 |
+
|
| 82 |
+
if int(interval_seconds) == 86400:
|
| 83 |
+
return f"{interval_start.year:04d}{interval_start.month:02d}{interval_start.day:02d}"
|
| 84 |
+
|
| 85 |
+
if int(interval_seconds) == 3600:
|
| 86 |
+
return (
|
| 87 |
+
f"{interval_start.year:04d}{interval_start.month:02d}{interval_start.day:02d}_"
|
| 88 |
+
f"{interval_start.hour:02d}"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
return (
|
| 92 |
+
f"{interval_start.year:04d}{interval_start.month:02d}{interval_start.day:02d}T"
|
| 93 |
+
f"{interval_start.hour:02d}{interval_start.minute:02d}{interval_start.second:02d}_"
|
| 94 |
+
f"{int(interval_seconds)}s"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def split_mode_from_seconds(interval_seconds):
|
| 99 |
+
if interval_seconds is None:
|
| 100 |
+
return "single"
|
| 101 |
+
if int(interval_seconds) == 86400:
|
| 102 |
+
return "day"
|
| 103 |
+
if int(interval_seconds) == 3600:
|
| 104 |
+
return "hour"
|
| 105 |
+
return "custom"
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def set_common_attrs(obj, level, node_type, parent_type):
|
| 109 |
+
obj.attrs["level"] = level
|
| 110 |
+
obj.attrs["type"] = node_type
|
| 111 |
+
obj.attrs["parent_type"] = parent_type
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def load_station_locations_csv(loc_file, default_location=DEFAULT_LOCATION):
|
| 115 |
+
"""
|
| 116 |
+
支持两种格式:
|
| 117 |
+
|
| 118 |
+
1. 有表头:
|
| 119 |
+
net,sta,lat,lon,elev_m,start,end
|
| 120 |
+
|
| 121 |
+
2. 无表头:
|
| 122 |
+
CI,WBM,35.60839,-117.89049,892.0,1979-09-26T00:00:00.000000Z,3000-01-01T00:00:00.000000Z
|
| 123 |
+
|
| 124 |
+
注意:
|
| 125 |
+
位置匹配只使用 network.station,不使用 location。
|
| 126 |
+
"""
|
| 127 |
+
locations = defaultdict(list)
|
| 128 |
+
|
| 129 |
+
if not loc_file or not os.path.exists(loc_file):
|
| 130 |
+
print(f"[WARN] Location CSV file not found: {loc_file}")
|
| 131 |
+
return dict(locations)
|
| 132 |
+
|
| 133 |
+
with open(loc_file, "r", encoding="utf-8-sig", newline="") as f:
|
| 134 |
+
sample = f.readline()
|
| 135 |
+
f.seek(0)
|
| 136 |
+
|
| 137 |
+
first_cols = [x.strip().lower() for x in sample.strip().split(",")]
|
| 138 |
+
has_header = {"net", "sta", "lat", "lon"}.issubset(set(first_cols))
|
| 139 |
+
|
| 140 |
+
if has_header:
|
| 141 |
+
reader = csv.DictReader(f)
|
| 142 |
+
|
| 143 |
+
for line_no, row in enumerate(reader, start=2):
|
| 144 |
+
try:
|
| 145 |
+
net = row["net"].strip()
|
| 146 |
+
sta = row["sta"].strip()
|
| 147 |
+
loc = normalize_location(row.get("location", default_location), default_location)
|
| 148 |
+
|
| 149 |
+
start = parse_utc_or_none(row["start"])
|
| 150 |
+
end = parse_utc_or_none(row["end"])
|
| 151 |
+
|
| 152 |
+
key = make_station_key(net, sta)
|
| 153 |
+
|
| 154 |
+
locations[key].append(
|
| 155 |
+
{
|
| 156 |
+
"network": net,
|
| 157 |
+
"station": sta,
|
| 158 |
+
"location": loc,
|
| 159 |
+
"latitude": float(row["lat"]),
|
| 160 |
+
"longitude": float(row["lon"]),
|
| 161 |
+
"elevation": float(row["elev_m"]),
|
| 162 |
+
"start": start,
|
| 163 |
+
"end": end,
|
| 164 |
+
"starttime": str(start) if start is not None else "",
|
| 165 |
+
"endtime": str(end) if end is not None else "",
|
| 166 |
+
}
|
| 167 |
+
)
|
| 168 |
+
except Exception as e:
|
| 169 |
+
print(f"[WARN] Failed to parse location CSV line {line_no}: {row}, error={e}")
|
| 170 |
+
|
| 171 |
+
else:
|
| 172 |
+
reader = csv.reader(f)
|
| 173 |
+
|
| 174 |
+
for line_no, row in enumerate(reader, start=1):
|
| 175 |
+
if not row or len(row) < 7:
|
| 176 |
+
continue
|
| 177 |
+
|
| 178 |
+
try:
|
| 179 |
+
net = row[0].strip()
|
| 180 |
+
sta = row[1].strip()
|
| 181 |
+
lat = float(row[2])
|
| 182 |
+
lon = float(row[3])
|
| 183 |
+
elev = float(row[4])
|
| 184 |
+
start = parse_utc_or_none(row[5])
|
| 185 |
+
end = parse_utc_or_none(row[6])
|
| 186 |
+
|
| 187 |
+
key = make_station_key(net, sta)
|
| 188 |
+
|
| 189 |
+
locations[key].append(
|
| 190 |
+
{
|
| 191 |
+
"network": net,
|
| 192 |
+
"station": sta,
|
| 193 |
+
"location": default_location,
|
| 194 |
+
"latitude": lat,
|
| 195 |
+
"longitude": lon,
|
| 196 |
+
"elevation": elev,
|
| 197 |
+
"start": start,
|
| 198 |
+
"end": end,
|
| 199 |
+
"starttime": str(start) if start is not None else "",
|
| 200 |
+
"endtime": str(end) if end is not None else "",
|
| 201 |
+
}
|
| 202 |
+
)
|
| 203 |
+
except Exception as e:
|
| 204 |
+
print(f"[WARN] Failed to parse location CSV line {line_no}: {row}, error={e}")
|
| 205 |
+
|
| 206 |
+
for key in locations:
|
| 207 |
+
locations[key].sort(
|
| 208 |
+
key=lambda x: x["start"] if x["start"] is not None else UTCDateTime(0)
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
return dict(locations)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def match_station_location(
|
| 215 |
+
station_locations,
|
| 216 |
+
station_id,
|
| 217 |
+
trace_start=None,
|
| 218 |
+
trace_end=None,
|
| 219 |
+
allow_fallback=True,
|
| 220 |
+
):
|
| 221 |
+
"""
|
| 222 |
+
只按 network.station 匹配台站位置。
|
| 223 |
+
不使用 location code。
|
| 224 |
+
|
| 225 |
+
例如:
|
| 226 |
+
waveform station_id = BK.BDM.00
|
| 227 |
+
location key = BK.BDM
|
| 228 |
+
"""
|
| 229 |
+
net, sta, _ = split_station_id(station_id)
|
| 230 |
+
station_key = make_station_key(net, sta)
|
| 231 |
+
|
| 232 |
+
records = station_locations.get(station_key, [])
|
| 233 |
+
|
| 234 |
+
if not records:
|
| 235 |
+
return None, "default_nan_no_station_record"
|
| 236 |
+
|
| 237 |
+
if trace_start is None and trace_end is None:
|
| 238 |
+
if allow_fallback:
|
| 239 |
+
return records[-1], "fallback_nearest_time_network_station_only"
|
| 240 |
+
return None, "default_nan_no_time_matched_position"
|
| 241 |
+
|
| 242 |
+
matched = []
|
| 243 |
+
|
| 244 |
+
for rec in records:
|
| 245 |
+
rec_start = rec.get("start")
|
| 246 |
+
rec_end = rec.get("end")
|
| 247 |
+
|
| 248 |
+
left_ok = True if rec_end is None or trace_start is None else trace_start < rec_end
|
| 249 |
+
right_ok = True if rec_start is None or trace_end is None else trace_end >= rec_start
|
| 250 |
+
|
| 251 |
+
if left_ok and right_ok:
|
| 252 |
+
matched.append(rec)
|
| 253 |
+
|
| 254 |
+
if matched:
|
| 255 |
+
def strict_score(rec):
|
| 256 |
+
rec_start = rec.get("start")
|
| 257 |
+
if rec_start is None or trace_start is None:
|
| 258 |
+
return 0
|
| 259 |
+
if rec_start <= trace_start:
|
| 260 |
+
return abs(trace_start - rec_start)
|
| 261 |
+
return abs(trace_start - rec_start) + 1e12
|
| 262 |
+
|
| 263 |
+
return sorted(matched, key=strict_score)[0], "strict_time_matched_network_station_only"
|
| 264 |
+
|
| 265 |
+
if not allow_fallback:
|
| 266 |
+
return None, "default_nan_no_time_matched_position"
|
| 267 |
+
|
| 268 |
+
def fallback_score(rec):
|
| 269 |
+
if trace_start is None:
|
| 270 |
+
return 0
|
| 271 |
+
|
| 272 |
+
candidates = []
|
| 273 |
+
if rec.get("start") is not None:
|
| 274 |
+
candidates.append(abs(trace_start - rec["start"]))
|
| 275 |
+
if rec.get("end") is not None:
|
| 276 |
+
candidates.append(abs(trace_start - rec["end"]))
|
| 277 |
+
|
| 278 |
+
return min(candidates) if candidates else 0
|
| 279 |
+
|
| 280 |
+
return sorted(records, key=fallback_score)[0], "fallback_nearest_time_network_station_only"
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def find_mseed_files(input_dir):
|
| 284 |
+
input_dir = Path(input_dir)
|
| 285 |
+
|
| 286 |
+
suffixes = {
|
| 287 |
+
".mseed", ".msd", ".miniseed", ".seed",
|
| 288 |
+
".MSEED", ".MSD", ".MINISEED", ".SEED",
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
return sorted(
|
| 292 |
+
p for p in input_dir.rglob("*")
|
| 293 |
+
if p.is_file() and p.suffix in suffixes
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def build_record_from_trace_chunk(
|
| 298 |
+
tr,
|
| 299 |
+
mseed_file,
|
| 300 |
+
station_id,
|
| 301 |
+
channel,
|
| 302 |
+
network,
|
| 303 |
+
station,
|
| 304 |
+
location,
|
| 305 |
+
data,
|
| 306 |
+
idx_start,
|
| 307 |
+
idx_end,
|
| 308 |
+
split_interval_seconds,
|
| 309 |
+
default_location=DEFAULT_LOCATION,
|
| 310 |
+
):
|
| 311 |
+
"""Build one HDF5 segment record from a trace chunk.
|
| 312 |
+
|
| 313 |
+
idx_end is exclusive. Samples are assigned to files by their sample time.
|
| 314 |
+
This means an input trace crossing an hour/day/custom boundary is physically
|
| 315 |
+
cut into multiple HDF5 datasets rather than merely written to the file of
|
| 316 |
+
its first sample.
|
| 317 |
+
"""
|
| 318 |
+
delta = float(tr.stats.delta)
|
| 319 |
+
sr = float(tr.stats.sampling_rate)
|
| 320 |
+
|
| 321 |
+
chunk_start = tr.stats.starttime + idx_start * delta
|
| 322 |
+
chunk_end = tr.stats.starttime + (idx_end - 1) * delta
|
| 323 |
+
interval_start = floor_utc_to_interval(chunk_start, split_interval_seconds)
|
| 324 |
+
interval_end = (interval_start + int(split_interval_seconds)) if interval_start is not None else None
|
| 325 |
+
|
| 326 |
+
return {
|
| 327 |
+
"year_id": utc_to_group_id(chunk_start, "year"),
|
| 328 |
+
"day_id": utc_to_group_id(chunk_start, "day"),
|
| 329 |
+
"split_file_id": interval_file_id(chunk_start, split_interval_seconds),
|
| 330 |
+
"split_interval_seconds": -1 if split_interval_seconds is None else int(split_interval_seconds),
|
| 331 |
+
"split_interval_starttime": str(interval_start) if interval_start is not None else "",
|
| 332 |
+
"split_interval_endtime": str(interval_end) if interval_end is not None else "",
|
| 333 |
+
"station_id": station_id,
|
| 334 |
+
"channel": channel,
|
| 335 |
+
"starttime_obj": chunk_start,
|
| 336 |
+
"endtime_obj": chunk_end,
|
| 337 |
+
"starttime": str(chunk_start),
|
| 338 |
+
"endtime": str(chunk_end),
|
| 339 |
+
"sampling_rate": sr,
|
| 340 |
+
"delta": delta,
|
| 341 |
+
"npts": int(idx_end - idx_start),
|
| 342 |
+
"network": network,
|
| 343 |
+
"station": station,
|
| 344 |
+
"location": location,
|
| 345 |
+
"data": np.asarray(data[idx_start:idx_end]),
|
| 346 |
+
"dtype": str(data.dtype),
|
| 347 |
+
"source_file": str(mseed_file),
|
| 348 |
+
"source_trace_starttime": str(tr.stats.starttime),
|
| 349 |
+
"source_trace_endtime": str(tr.stats.endtime),
|
| 350 |
+
"source_trace_npts": int(tr.stats.npts),
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def trace_to_records(tr, mseed_file, default_location=DEFAULT_LOCATION, split_interval_seconds=None):
|
| 355 |
+
records = []
|
| 356 |
+
|
| 357 |
+
net = tr.stats.network or ""
|
| 358 |
+
sta = tr.stats.station or ""
|
| 359 |
+
loc = normalize_location(tr.stats.location, default_location)
|
| 360 |
+
cha = tr.stats.channel or ""
|
| 361 |
+
station_id = make_station_id(net, sta, loc, default_location)
|
| 362 |
+
|
| 363 |
+
data = np.asarray(tr.data)
|
| 364 |
+
npts = int(tr.stats.npts)
|
| 365 |
+
if npts <= 0:
|
| 366 |
+
return records
|
| 367 |
+
|
| 368 |
+
if split_interval_seconds is None:
|
| 369 |
+
records.append(
|
| 370 |
+
build_record_from_trace_chunk(
|
| 371 |
+
tr=tr,
|
| 372 |
+
mseed_file=mseed_file,
|
| 373 |
+
station_id=station_id,
|
| 374 |
+
channel=cha,
|
| 375 |
+
network=net,
|
| 376 |
+
station=sta,
|
| 377 |
+
location=loc,
|
| 378 |
+
data=data,
|
| 379 |
+
idx_start=0,
|
| 380 |
+
idx_end=npts,
|
| 381 |
+
split_interval_seconds=None,
|
| 382 |
+
default_location=default_location,
|
| 383 |
+
)
|
| 384 |
+
)
|
| 385 |
+
return records
|
| 386 |
+
|
| 387 |
+
split_interval_seconds = int(split_interval_seconds)
|
| 388 |
+
if split_interval_seconds <= 0:
|
| 389 |
+
raise ValueError("split_interval_seconds must be positive or None")
|
| 390 |
+
|
| 391 |
+
sr = float(tr.stats.sampling_rate)
|
| 392 |
+
idx_start = 0
|
| 393 |
+
|
| 394 |
+
while idx_start < npts:
|
| 395 |
+
sample_time = tr.stats.starttime + idx_start / sr
|
| 396 |
+
interval_start = floor_utc_to_interval(sample_time, split_interval_seconds)
|
| 397 |
+
next_boundary = interval_start + split_interval_seconds
|
| 398 |
+
|
| 399 |
+
# First sample with sample_time >= next_boundary.
|
| 400 |
+
idx_end = int(np.ceil((float(next_boundary - tr.stats.starttime) * sr) - 1e-9))
|
| 401 |
+
idx_end = max(idx_start + 1, min(idx_end, npts))
|
| 402 |
+
|
| 403 |
+
records.append(
|
| 404 |
+
build_record_from_trace_chunk(
|
| 405 |
+
tr=tr,
|
| 406 |
+
mseed_file=mseed_file,
|
| 407 |
+
station_id=station_id,
|
| 408 |
+
channel=cha,
|
| 409 |
+
network=net,
|
| 410 |
+
station=sta,
|
| 411 |
+
location=loc,
|
| 412 |
+
data=data,
|
| 413 |
+
idx_start=idx_start,
|
| 414 |
+
idx_end=idx_end,
|
| 415 |
+
split_interval_seconds=split_interval_seconds,
|
| 416 |
+
default_location=default_location,
|
| 417 |
+
)
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
idx_start = idx_end
|
| 421 |
+
|
| 422 |
+
return records
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def read_one_mseed(mseed_file, default_location=DEFAULT_LOCATION, split_interval_seconds=None):
|
| 426 |
+
records = []
|
| 427 |
+
|
| 428 |
+
try:
|
| 429 |
+
st = read(str(mseed_file))
|
| 430 |
+
except Exception as e:
|
| 431 |
+
return records, f"[WARN] Failed to read {mseed_file}: {e}"
|
| 432 |
+
|
| 433 |
+
for tr in st:
|
| 434 |
+
records.extend(
|
| 435 |
+
trace_to_records(
|
| 436 |
+
tr=tr,
|
| 437 |
+
mseed_file=mseed_file,
|
| 438 |
+
default_location=default_location,
|
| 439 |
+
split_interval_seconds=split_interval_seconds,
|
| 440 |
+
)
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
return records, None
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def write_position_attrs(obj, matched, match_mode):
|
| 447 |
+
obj.attrs["position_match_mode"] = match_mode
|
| 448 |
+
obj.attrs["position_is_fallback"] = "fallback" in str(match_mode)
|
| 449 |
+
|
| 450 |
+
if matched is not None:
|
| 451 |
+
obj.attrs["longitude"] = matched.get("longitude", np.nan)
|
| 452 |
+
obj.attrs["latitude"] = matched.get("latitude", np.nan)
|
| 453 |
+
obj.attrs["elevation"] = matched.get("elevation", np.nan)
|
| 454 |
+
obj.attrs["location_available"] = True
|
| 455 |
+
obj.attrs["location_source"] = match_mode
|
| 456 |
+
obj.attrs["station_position_starttime"] = matched.get("starttime", "")
|
| 457 |
+
obj.attrs["station_position_endtime"] = matched.get("endtime", "")
|
| 458 |
+
else:
|
| 459 |
+
obj.attrs["longitude"] = np.nan
|
| 460 |
+
obj.attrs["latitude"] = np.nan
|
| 461 |
+
obj.attrs["elevation"] = np.nan
|
| 462 |
+
obj.attrs["location_available"] = False
|
| 463 |
+
obj.attrs["location_source"] = match_mode
|
| 464 |
+
obj.attrs["station_position_starttime"] = ""
|
| 465 |
+
obj.attrs["station_position_endtime"] = ""
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def write_station_position_history(station_grp, station_id, station_locations, default_location):
|
| 469 |
+
if "position_history" in station_grp:
|
| 470 |
+
return
|
| 471 |
+
|
| 472 |
+
net, sta, _ = split_station_id(station_id, default_location)
|
| 473 |
+
station_key = make_station_key(net, sta)
|
| 474 |
+
|
| 475 |
+
pos_grp = station_grp.create_group("position_history")
|
| 476 |
+
set_common_attrs(pos_grp, "position_history", "position_history_group", "station_group")
|
| 477 |
+
|
| 478 |
+
records = station_locations.get(station_key, [])
|
| 479 |
+
pos_grp.attrs["record_count"] = len(records)
|
| 480 |
+
pos_grp.attrs["match_key"] = station_key
|
| 481 |
+
pos_grp.attrs["match_rule"] = "network.station only; location ignored"
|
| 482 |
+
|
| 483 |
+
for i, rec in enumerate(records):
|
| 484 |
+
item_grp = pos_grp.create_group(str(i))
|
| 485 |
+
set_common_attrs(item_grp, "position_record", "position_record_group", "position_history_group")
|
| 486 |
+
|
| 487 |
+
item_grp.attrs["network"] = rec.get("network", "")
|
| 488 |
+
item_grp.attrs["station"] = rec.get("station", "")
|
| 489 |
+
item_grp.attrs["location"] = rec.get("location", default_location)
|
| 490 |
+
item_grp.attrs["longitude"] = rec.get("longitude", np.nan)
|
| 491 |
+
item_grp.attrs["latitude"] = rec.get("latitude", np.nan)
|
| 492 |
+
item_grp.attrs["elevation"] = rec.get("elevation", np.nan)
|
| 493 |
+
item_grp.attrs["starttime"] = rec.get("starttime", "")
|
| 494 |
+
item_grp.attrs["endtime"] = rec.get("endtime", "")
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def init_hdf5_root(h5, default_location, split_interval_seconds=None):
|
| 498 |
+
set_common_attrs(h5, "root", "hdf5_file", "none")
|
| 499 |
+
h5.attrs["description"] = "Continuous waveform dataset converted from MiniSEED"
|
| 500 |
+
h5.attrs["station_id_format"] = "network.station.location"
|
| 501 |
+
h5.attrs["station_location_match_rule"] = "network.station only; location ignored"
|
| 502 |
+
h5.attrs["empty_location_value"] = default_location
|
| 503 |
+
h5.attrs["missing_coordinate_value"] = "NaN"
|
| 504 |
+
h5.attrs["station_location_format"] = (
|
| 505 |
+
"CSV with header: net,sta,lat,lon,elev_m,start,end "
|
| 506 |
+
"or no-header: net,sta,lat,lon,elev_m,start,end"
|
| 507 |
+
)
|
| 508 |
+
h5.attrs["split_mode"] = split_mode_from_seconds(split_interval_seconds)
|
| 509 |
+
h5.attrs["split_interval_seconds"] = -1 if split_interval_seconds is None else int(split_interval_seconds)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def get_or_create_station_group(
|
| 513 |
+
h5,
|
| 514 |
+
year_id,
|
| 515 |
+
day_id,
|
| 516 |
+
station_id,
|
| 517 |
+
station_locations,
|
| 518 |
+
trace_start,
|
| 519 |
+
trace_end,
|
| 520 |
+
default_location,
|
| 521 |
+
):
|
| 522 |
+
year_grp = h5.require_group(year_id)
|
| 523 |
+
set_common_attrs(year_grp, "year", "year_group", "root")
|
| 524 |
+
year_grp.attrs["utc_time"] = year_id
|
| 525 |
+
|
| 526 |
+
day_grp = year_grp.require_group(day_id)
|
| 527 |
+
set_common_attrs(day_grp, "day", "day_group", "year_group")
|
| 528 |
+
day_grp.attrs["utc_time"] = day_id
|
| 529 |
+
|
| 530 |
+
stations_grp = day_grp.require_group("stations")
|
| 531 |
+
set_common_attrs(stations_grp, "stations", "stations_group", "day_group")
|
| 532 |
+
stations_grp.attrs["description"] = "Container group for all stations under this day"
|
| 533 |
+
|
| 534 |
+
station_grp = stations_grp.require_group(station_id)
|
| 535 |
+
set_common_attrs(station_grp, "station", "station_group", "stations_group")
|
| 536 |
+
|
| 537 |
+
network, station, location = split_station_id(station_id, default_location)
|
| 538 |
+
station_grp.attrs["station_id"] = station_id
|
| 539 |
+
station_grp.attrs["station_key"] = make_station_key(network, station)
|
| 540 |
+
station_grp.attrs["network"] = network
|
| 541 |
+
station_grp.attrs["station"] = station
|
| 542 |
+
station_grp.attrs["location"] = location
|
| 543 |
+
station_grp.attrs["location_default_value"] = default_location
|
| 544 |
+
station_grp.attrs["location_is_default"] = location == default_location
|
| 545 |
+
station_grp.attrs["instrument_time_range_start"] = str(trace_start)
|
| 546 |
+
station_grp.attrs["instrument_time_range_end"] = str(trace_end)
|
| 547 |
+
|
| 548 |
+
matched, match_mode = match_station_location(
|
| 549 |
+
station_locations=station_locations,
|
| 550 |
+
station_id=station_id,
|
| 551 |
+
trace_start=trace_start,
|
| 552 |
+
trace_end=trace_end,
|
| 553 |
+
allow_fallback=True,
|
| 554 |
+
)
|
| 555 |
+
write_position_attrs(station_grp, matched, match_mode)
|
| 556 |
+
|
| 557 |
+
write_station_position_history(
|
| 558 |
+
station_grp=station_grp,
|
| 559 |
+
station_id=station_id,
|
| 560 |
+
station_locations=station_locations,
|
| 561 |
+
default_location=default_location,
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
waveform_grp = station_grp.require_group("waveform")
|
| 565 |
+
set_common_attrs(waveform_grp, "waveform", "waveform_group", "station_group")
|
| 566 |
+
|
| 567 |
+
return station_grp, waveform_grp
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def next_dataset_index(channel_grp):
|
| 571 |
+
max_idx = -1
|
| 572 |
+
for key in channel_grp.keys():
|
| 573 |
+
if str(key).isdigit():
|
| 574 |
+
max_idx = max(max_idx, int(key))
|
| 575 |
+
return max_idx + 1
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def update_channel_summary_attrs(channel_grp, rec):
|
| 579 |
+
channel_grp.attrs["channel"] = rec["channel"]
|
| 580 |
+
|
| 581 |
+
old_count = int(channel_grp.attrs.get("segment_count", 0))
|
| 582 |
+
channel_grp.attrs["segment_count"] = old_count + 1
|
| 583 |
+
|
| 584 |
+
rec_start = rec["starttime_obj"]
|
| 585 |
+
rec_end = rec["endtime_obj"]
|
| 586 |
+
|
| 587 |
+
old_start = channel_grp.attrs.get("starttime", "")
|
| 588 |
+
old_end = channel_grp.attrs.get("endtime", "")
|
| 589 |
+
|
| 590 |
+
if not old_start:
|
| 591 |
+
channel_grp.attrs["starttime"] = str(rec_start)
|
| 592 |
+
else:
|
| 593 |
+
old_start_t = UTCDateTime(str(old_start))
|
| 594 |
+
channel_grp.attrs["starttime"] = str(min(old_start_t, rec_start))
|
| 595 |
+
|
| 596 |
+
if not old_end:
|
| 597 |
+
channel_grp.attrs["endtime"] = str(rec_end)
|
| 598 |
+
else:
|
| 599 |
+
old_end_t = UTCDateTime(str(old_end))
|
| 600 |
+
channel_grp.attrs["endtime"] = str(max(old_end_t, rec_end))
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def write_one_record(
|
| 604 |
+
h5,
|
| 605 |
+
rec,
|
| 606 |
+
station_locations,
|
| 607 |
+
default_location,
|
| 608 |
+
compression,
|
| 609 |
+
compression_opts,
|
| 610 |
+
shuffle,
|
| 611 |
+
):
|
| 612 |
+
station_grp, waveform_grp = get_or_create_station_group(
|
| 613 |
+
h5=h5,
|
| 614 |
+
year_id=rec["year_id"],
|
| 615 |
+
day_id=rec["day_id"],
|
| 616 |
+
station_id=rec["station_id"],
|
| 617 |
+
station_locations=station_locations,
|
| 618 |
+
trace_start=rec["starttime_obj"],
|
| 619 |
+
trace_end=rec["endtime_obj"],
|
| 620 |
+
default_location=default_location,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
channel_grp = waveform_grp.require_group(rec["channel"])
|
| 624 |
+
set_common_attrs(channel_grp, "channel", "channel_group", "waveform_group")
|
| 625 |
+
|
| 626 |
+
update_channel_summary_attrs(channel_grp, rec)
|
| 627 |
+
|
| 628 |
+
matched, match_mode = match_station_location(
|
| 629 |
+
station_locations=station_locations,
|
| 630 |
+
station_id=rec["station_id"],
|
| 631 |
+
trace_start=rec["starttime_obj"],
|
| 632 |
+
trace_end=rec["endtime_obj"],
|
| 633 |
+
allow_fallback=True,
|
| 634 |
+
)
|
| 635 |
+
write_position_attrs(channel_grp, matched, match_mode)
|
| 636 |
+
|
| 637 |
+
ds_name = str(next_dataset_index(channel_grp))
|
| 638 |
+
|
| 639 |
+
create_kwargs = {}
|
| 640 |
+
if compression and compression.lower() != "none":
|
| 641 |
+
create_kwargs["compression"] = compression
|
| 642 |
+
if compression.lower() == "gzip":
|
| 643 |
+
create_kwargs["compression_opts"] = compression_opts
|
| 644 |
+
create_kwargs["shuffle"] = shuffle
|
| 645 |
+
|
| 646 |
+
ds = channel_grp.create_dataset(
|
| 647 |
+
ds_name,
|
| 648 |
+
data=rec["data"],
|
| 649 |
+
**create_kwargs,
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
set_common_attrs(ds, "segment", "waveform_dataset", "channel_group")
|
| 653 |
+
|
| 654 |
+
write_position_attrs(ds, matched, match_mode)
|
| 655 |
+
|
| 656 |
+
ds.attrs["segment_index"] = int(ds_name)
|
| 657 |
+
ds.attrs["network"] = rec["network"]
|
| 658 |
+
ds.attrs["station"] = rec["station"]
|
| 659 |
+
ds.attrs["station_key"] = make_station_key(rec["network"], rec["station"])
|
| 660 |
+
ds.attrs["location"] = rec["location"]
|
| 661 |
+
ds.attrs["location_is_default"] = rec["location"] == default_location
|
| 662 |
+
ds.attrs["channel"] = rec["channel"]
|
| 663 |
+
ds.attrs["sampling_rate"] = rec["sampling_rate"]
|
| 664 |
+
ds.attrs["delta"] = rec["delta"]
|
| 665 |
+
ds.attrs["npts"] = rec["npts"]
|
| 666 |
+
ds.attrs["starttime"] = rec["starttime"]
|
| 667 |
+
ds.attrs["endtime"] = rec["endtime"]
|
| 668 |
+
ds.attrs["mseed_source_file"] = rec["source_file"]
|
| 669 |
+
ds.attrs["dtype"] = rec["dtype"]
|
| 670 |
+
ds.attrs["split_file_id"] = rec.get("split_file_id", "single")
|
| 671 |
+
ds.attrs["split_interval_seconds"] = rec.get("split_interval_seconds", -1)
|
| 672 |
+
ds.attrs["split_interval_starttime"] = rec.get("split_interval_starttime", "")
|
| 673 |
+
ds.attrs["split_interval_endtime"] = rec.get("split_interval_endtime", "")
|
| 674 |
+
ds.attrs["source_trace_starttime"] = rec.get("source_trace_starttime", rec["starttime"])
|
| 675 |
+
ds.attrs["source_trace_endtime"] = rec.get("source_trace_endtime", rec["endtime"])
|
| 676 |
+
ds.attrs["source_trace_npts"] = rec.get("source_trace_npts", rec["npts"])
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def output_path_for_interval(output, split_file_id):
|
| 680 |
+
output = Path(output)
|
| 681 |
+
|
| 682 |
+
if output.suffix.lower() in [".h5", ".hdf5"]:
|
| 683 |
+
out_dir = output.parent
|
| 684 |
+
stem = output.stem
|
| 685 |
+
else:
|
| 686 |
+
out_dir = output
|
| 687 |
+
stem = "continuous_waveform"
|
| 688 |
+
|
| 689 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 690 |
+
return out_dir / f"{stem}_{split_file_id}.h5"
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def convert_mseed_to_hdf5_streaming(
|
| 694 |
+
mseed_files,
|
| 695 |
+
station_locations,
|
| 696 |
+
output_file,
|
| 697 |
+
num_workers=4,
|
| 698 |
+
max_pending=16,
|
| 699 |
+
default_location=DEFAULT_LOCATION,
|
| 700 |
+
compression="gzip",
|
| 701 |
+
compression_opts=4,
|
| 702 |
+
shuffle=True,
|
| 703 |
+
split_interval_seconds=86400,
|
| 704 |
+
include_split_file_ids=None,
|
| 705 |
+
):
|
| 706 |
+
total = len(mseed_files)
|
| 707 |
+
submitted = 0
|
| 708 |
+
finished = 0
|
| 709 |
+
written_records = 0
|
| 710 |
+
skipped_records = 0
|
| 711 |
+
include_split_file_ids = set(include_split_file_ids or [])
|
| 712 |
+
|
| 713 |
+
h5_files = {}
|
| 714 |
+
|
| 715 |
+
def get_h5_for_record(rec):
|
| 716 |
+
if split_interval_seconds is None:
|
| 717 |
+
key = "__single__"
|
| 718 |
+
if key not in h5_files:
|
| 719 |
+
output_path = Path(output_file)
|
| 720 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 721 |
+
h5 = h5py.File(output_path, "w")
|
| 722 |
+
init_hdf5_root(h5, default_location, split_interval_seconds=None)
|
| 723 |
+
h5_files[key] = h5
|
| 724 |
+
return h5_files[key]
|
| 725 |
+
|
| 726 |
+
key = rec["split_file_id"]
|
| 727 |
+
if key not in h5_files:
|
| 728 |
+
output_path = output_path_for_interval(output_file, key)
|
| 729 |
+
h5 = h5py.File(output_path, "w")
|
| 730 |
+
init_hdf5_root(h5, default_location, split_interval_seconds=split_interval_seconds)
|
| 731 |
+
h5.attrs["split_file_id"] = key
|
| 732 |
+
h5.attrs["split_interval_seconds"] = int(split_interval_seconds)
|
| 733 |
+
h5.attrs["split_interval_starttime"] = rec.get("split_interval_starttime", "")
|
| 734 |
+
h5.attrs["split_interval_endtime"] = rec.get("split_interval_endtime", "")
|
| 735 |
+
h5_files[key] = h5
|
| 736 |
+
return h5_files[key]
|
| 737 |
+
|
| 738 |
+
try:
|
| 739 |
+
with ThreadPoolExecutor(max_workers=num_workers) as executor:
|
| 740 |
+
pending = set()
|
| 741 |
+
|
| 742 |
+
def submit_more():
|
| 743 |
+
nonlocal submitted
|
| 744 |
+
while submitted < total and len(pending) < max_pending:
|
| 745 |
+
future = executor.submit(
|
| 746 |
+
read_one_mseed,
|
| 747 |
+
mseed_files[submitted],
|
| 748 |
+
default_location,
|
| 749 |
+
split_interval_seconds,
|
| 750 |
+
)
|
| 751 |
+
pending.add(future)
|
| 752 |
+
submitted += 1
|
| 753 |
+
|
| 754 |
+
submit_more()
|
| 755 |
+
|
| 756 |
+
while pending:
|
| 757 |
+
done, pending_remaining = wait(pending, return_when=FIRST_COMPLETED)
|
| 758 |
+
pending = pending_remaining
|
| 759 |
+
|
| 760 |
+
for future in done:
|
| 761 |
+
finished += 1
|
| 762 |
+
records, warning = future.result()
|
| 763 |
+
|
| 764 |
+
if warning:
|
| 765 |
+
print(warning)
|
| 766 |
+
|
| 767 |
+
records.sort(
|
| 768 |
+
key=lambda r: (
|
| 769 |
+
r["split_file_id"],
|
| 770 |
+
r["year_id"],
|
| 771 |
+
r["day_id"],
|
| 772 |
+
r["station_id"],
|
| 773 |
+
r["channel"],
|
| 774 |
+
r["starttime_obj"],
|
| 775 |
+
)
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
for rec in records:
|
| 779 |
+
if include_split_file_ids and rec["split_file_id"] not in include_split_file_ids:
|
| 780 |
+
skipped_records += 1
|
| 781 |
+
continue
|
| 782 |
+
|
| 783 |
+
h5 = get_h5_for_record(rec)
|
| 784 |
+
|
| 785 |
+
write_one_record(
|
| 786 |
+
h5=h5,
|
| 787 |
+
rec=rec,
|
| 788 |
+
station_locations=station_locations,
|
| 789 |
+
default_location=default_location,
|
| 790 |
+
compression=compression,
|
| 791 |
+
compression_opts=compression_opts,
|
| 792 |
+
shuffle=shuffle,
|
| 793 |
+
)
|
| 794 |
+
written_records += 1
|
| 795 |
+
|
| 796 |
+
if finished % 100 == 0 or finished == total:
|
| 797 |
+
print(
|
| 798 |
+
f"[INFO] Progress: files {finished}/{total}, "
|
| 799 |
+
f"written waveform segments {written_records}, "
|
| 800 |
+
f"open hdf5 files {len(h5_files)}"
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
del records
|
| 804 |
+
|
| 805 |
+
submit_more()
|
| 806 |
+
|
| 807 |
+
finally:
|
| 808 |
+
for h5 in h5_files.values():
|
| 809 |
+
h5.close()
|
| 810 |
+
|
| 811 |
+
print(f"[OK] Written waveform segments: {written_records}")
|
| 812 |
+
if include_split_file_ids:
|
| 813 |
+
print(
|
| 814 |
+
f"[OK] Kept split_file_id(s): {', '.join(sorted(include_split_file_ids))}; "
|
| 815 |
+
f"skipped waveform segments outside selection: {skipped_records}"
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
if split_interval_seconds is None:
|
| 819 |
+
print(f"[OK] HDF5 written to: {output_file}")
|
| 820 |
+
else:
|
| 821 |
+
out_dir = Path(output_file).parent if Path(output_file).suffix else output_file
|
| 822 |
+
print(
|
| 823 |
+
f"[OK] HDF5 files written by {split_mode_from_seconds(split_interval_seconds)} "
|
| 824 |
+
f"intervals ({int(split_interval_seconds)} s) under: {out_dir}"
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def resolve_split_interval_seconds(args):
|
| 829 |
+
if getattr(args, "split_by_day", False):
|
| 830 |
+
return 86400
|
| 831 |
+
|
| 832 |
+
if args.split_interval == "single":
|
| 833 |
+
return None
|
| 834 |
+
if args.split_interval == "day":
|
| 835 |
+
return 86400
|
| 836 |
+
if args.split_interval == "hour":
|
| 837 |
+
return 3600
|
| 838 |
+
if args.split_interval == "custom":
|
| 839 |
+
if args.custom_interval_seconds <= 0:
|
| 840 |
+
raise ValueError("--custom_interval_seconds must be positive")
|
| 841 |
+
return int(args.custom_interval_seconds)
|
| 842 |
+
|
| 843 |
+
raise ValueError(f"Unsupported split interval: {args.split_interval}")
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def main():
|
| 847 |
+
parser = argparse.ArgumentParser(
|
| 848 |
+
description="Convert MiniSEED files to hierarchical HDF5."
|
| 849 |
+
)
|
| 850 |
+
|
| 851 |
+
parser.add_argument(
|
| 852 |
+
"--input_dir",
|
| 853 |
+
default="/Volumes/Data/continous_dataset_tool/data/continous_usa/data/07/01",
|
| 854 |
+
help="Directory containing MiniSEED files.",
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
parser.add_argument(
|
| 858 |
+
"--loc_file",
|
| 859 |
+
default="data/label/stations.csv",
|
| 860 |
+
help="Station CSV file.",
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
parser.add_argument(
|
| 864 |
+
"--output",
|
| 865 |
+
default="data/hdf5_one_day_with_hour_segment/continuous_waveform_usa.h5",
|
| 866 |
+
help=(
|
| 867 |
+
"Output HDF5 file or filename prefix. With --split_interval day/hour/custom, "
|
| 868 |
+
"this is used as a prefix, e.g. continuous_waveform_usa_20190701.h5 "
|
| 869 |
+
"or continuous_waveform_usa_20190701_13.h5."
|
| 870 |
+
),
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
parser.add_argument(
|
| 874 |
+
"--split_interval",
|
| 875 |
+
default="hour",
|
| 876 |
+
choices=["single", "day", "hour", "custom"],
|
| 877 |
+
help=(
|
| 878 |
+
"Output split interval. "
|
| 879 |
+
"single = one HDF5 file; day = one file per day; "
|
| 880 |
+
"hour = one file per hour; custom = use --custom_interval_seconds."
|
| 881 |
+
),
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
parser.add_argument(
|
| 885 |
+
"--custom_interval_seconds",
|
| 886 |
+
type=int,
|
| 887 |
+
default=3600,
|
| 888 |
+
help="Custom output interval length in seconds when --split_interval custom.",
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
parser.add_argument(
|
| 892 |
+
"--split_by_day",
|
| 893 |
+
action="store_true",
|
| 894 |
+
help="Backward-compatible alias: equivalent to --split_interval day.",
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
parser.add_argument(
|
| 898 |
+
"--num_workers",
|
| 899 |
+
type=int,
|
| 900 |
+
default=2,
|
| 901 |
+
help="Number of threads for reading MiniSEED files.",
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
parser.add_argument(
|
| 905 |
+
"--max_pending",
|
| 906 |
+
type=int,
|
| 907 |
+
default=4,
|
| 908 |
+
help="Maximum number of pending read tasks.",
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
parser.add_argument(
|
| 912 |
+
"--default_location",
|
| 913 |
+
default=DEFAULT_LOCATION,
|
| 914 |
+
help='Default location code when MiniSEED location is empty. Default: "--".',
|
| 915 |
+
)
|
| 916 |
+
|
| 917 |
+
parser.add_argument(
|
| 918 |
+
"--compression",
|
| 919 |
+
default="gzip",
|
| 920 |
+
choices=["gzip", "lzf", "none"],
|
| 921 |
+
help="Dataset compression method.",
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
parser.add_argument(
|
| 925 |
+
"--compression_opts",
|
| 926 |
+
type=int,
|
| 927 |
+
default=4,
|
| 928 |
+
help="Compression level for gzip.",
|
| 929 |
+
)
|
| 930 |
+
|
| 931 |
+
parser.add_argument(
|
| 932 |
+
"--no_shuffle",
|
| 933 |
+
action="store_true",
|
| 934 |
+
help="Disable HDF5 shuffle filter.",
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
+
parser.add_argument(
|
| 938 |
+
"--include_split_file_id",
|
| 939 |
+
action="append",
|
| 940 |
+
default=[],
|
| 941 |
+
help=(
|
| 942 |
+
"Only write selected split file id(s), e.g. 20190706_04. "
|
| 943 |
+
"Can be supplied multiple times. Useful for building small hour subsets."
|
| 944 |
+
),
|
| 945 |
+
)
|
| 946 |
+
|
| 947 |
+
args = parser.parse_args()
|
| 948 |
+
|
| 949 |
+
split_interval_seconds = resolve_split_interval_seconds(args)
|
| 950 |
+
print(
|
| 951 |
+
f"[INFO] Output split mode: {split_mode_from_seconds(split_interval_seconds)} "
|
| 952 |
+
f"({split_interval_seconds if split_interval_seconds is not None else 'single file'} s)"
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
station_locations = load_station_locations_csv(
|
| 956 |
+
args.loc_file,
|
| 957 |
+
default_location=args.default_location,
|
| 958 |
+
)
|
| 959 |
+
print(f"[INFO] Loaded station location histories for {len(station_locations)} station keys.")
|
| 960 |
+
|
| 961 |
+
mseed_files = find_mseed_files(args.input_dir)
|
| 962 |
+
print(f"[INFO] Found {len(mseed_files)} MiniSEED files.")
|
| 963 |
+
|
| 964 |
+
convert_mseed_to_hdf5_streaming(
|
| 965 |
+
mseed_files=mseed_files,
|
| 966 |
+
station_locations=station_locations,
|
| 967 |
+
output_file=args.output,
|
| 968 |
+
num_workers=args.num_workers,
|
| 969 |
+
max_pending=args.max_pending,
|
| 970 |
+
default_location=args.default_location,
|
| 971 |
+
compression=args.compression,
|
| 972 |
+
compression_opts=args.compression_opts,
|
| 973 |
+
shuffle=not args.no_shuffle,
|
| 974 |
+
split_interval_seconds=split_interval_seconds,
|
| 975 |
+
include_split_file_ids=args.include_split_file_id,
|
| 976 |
+
)
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
if __name__ == "__main__":
|
| 980 |
+
main()
|