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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
import h5py
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import Dataset, DataLoader
|
| 8 |
+
from obspy import UTCDateTime
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
DEFAULT_LOCATION = "--"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_time(t):
|
| 15 |
+
return UTCDateTime(str(t))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def decode_attr(value):
|
| 19 |
+
if isinstance(value, bytes):
|
| 20 |
+
return value.decode("utf-8", errors="ignore")
|
| 21 |
+
if isinstance(value, np.bytes_):
|
| 22 |
+
return value.decode("utf-8", errors="ignore")
|
| 23 |
+
return value
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def normalize_location(location, default=DEFAULT_LOCATION):
|
| 27 |
+
location = decode_attr(location)
|
| 28 |
+
if location is None:
|
| 29 |
+
return default
|
| 30 |
+
location = str(location).strip()
|
| 31 |
+
return location if location else default
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def channel_suffix(channel):
|
| 35 |
+
return str(channel)[-1].upper()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def channel_prefix(channel):
|
| 39 |
+
# 前两位作为 family,例如 BHE/BHN/BHZ -> BH
|
| 40 |
+
ch = str(channel).upper()
|
| 41 |
+
if len(ch) >= 3:
|
| 42 |
+
return ch[:2]
|
| 43 |
+
return ch[:-1]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def component_rank(channel):
|
| 47 |
+
order = {
|
| 48 |
+
"E": 0,
|
| 49 |
+
"1": 0,
|
| 50 |
+
"N": 1,
|
| 51 |
+
"2": 1,
|
| 52 |
+
"Z": 2,
|
| 53 |
+
"3": 2,
|
| 54 |
+
}
|
| 55 |
+
return order.get(channel_suffix(channel), 99)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def is_valid_waveform_family(channels):
|
| 59 |
+
"""
|
| 60 |
+
判断一个 channel family 是否可以构成三分量输入。
|
| 61 |
+
|
| 62 |
+
支持:
|
| 63 |
+
1. E/N/Z
|
| 64 |
+
2. 1/2/3
|
| 65 |
+
3. only Z,后续复制成三分量
|
| 66 |
+
"""
|
| 67 |
+
suffixes = {channel_suffix(ch) for ch in channels}
|
| 68 |
+
|
| 69 |
+
if {"E", "N", "Z"}.issubset(suffixes):
|
| 70 |
+
return True
|
| 71 |
+
|
| 72 |
+
if {"1", "2", "3"}.issubset(suffixes):
|
| 73 |
+
return True
|
| 74 |
+
|
| 75 |
+
if suffixes == {"Z"}:
|
| 76 |
+
return True
|
| 77 |
+
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_attr(obj, name, default=None):
|
| 82 |
+
if name in obj.attrs:
|
| 83 |
+
return decode_attr(obj.attrs[name])
|
| 84 |
+
return default
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def get_float_attr(obj, name, default=np.nan):
|
| 88 |
+
try:
|
| 89 |
+
return float(get_attr(obj, name, default))
|
| 90 |
+
except Exception:
|
| 91 |
+
return float(default)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_bool_attr(obj, name, default=False):
|
| 95 |
+
value = get_attr(obj, name, default)
|
| 96 |
+
|
| 97 |
+
if isinstance(value, (bool, np.bool_)):
|
| 98 |
+
return bool(value)
|
| 99 |
+
|
| 100 |
+
if isinstance(value, (int, np.integer)):
|
| 101 |
+
return bool(value)
|
| 102 |
+
|
| 103 |
+
if isinstance(value, str):
|
| 104 |
+
return value.lower() in ["true", "1", "yes"]
|
| 105 |
+
|
| 106 |
+
return bool(value)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def fill_segments_to_array(segments, fill_value=0.0, dtype=np.float32):
|
| 110 |
+
if len(segments) == 0:
|
| 111 |
+
return None, None, None, None
|
| 112 |
+
|
| 113 |
+
segments = sorted(segments, key=lambda x: x["starttime"])
|
| 114 |
+
|
| 115 |
+
sampling_rate = segments[0]["sampling_rate"]
|
| 116 |
+
global_start = min(s["starttime"] for s in segments)
|
| 117 |
+
global_end = max(s["endtime"] for s in segments)
|
| 118 |
+
|
| 119 |
+
npts = int(round((global_end - global_start) * sampling_rate)) + 1
|
| 120 |
+
|
| 121 |
+
data = np.full(npts, fill_value, dtype=dtype)
|
| 122 |
+
filled = np.zeros(npts, dtype=bool)
|
| 123 |
+
|
| 124 |
+
for seg in segments:
|
| 125 |
+
seg_data = seg["data"].astype(dtype, copy=False)
|
| 126 |
+
|
| 127 |
+
i0 = int(round((seg["starttime"] - global_start) * sampling_rate))
|
| 128 |
+
i1 = i0 + len(seg_data)
|
| 129 |
+
|
| 130 |
+
if i0 < 0:
|
| 131 |
+
seg_data = seg_data[-i0:]
|
| 132 |
+
i0 = 0
|
| 133 |
+
|
| 134 |
+
if i1 > npts:
|
| 135 |
+
seg_data = seg_data[: npts - i0]
|
| 136 |
+
i1 = npts
|
| 137 |
+
|
| 138 |
+
if i0 >= i1:
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
target = slice(i0, i1)
|
| 142 |
+
mask = ~filled[target]
|
| 143 |
+
|
| 144 |
+
data[target][mask] = seg_data[: i1 - i0][mask]
|
| 145 |
+
filled[target][mask] = True
|
| 146 |
+
|
| 147 |
+
return data, global_start, global_end, sampling_rate
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_position_from_segments(segments):
|
| 151 |
+
for seg in segments:
|
| 152 |
+
if seg.get("location_available", False):
|
| 153 |
+
return {
|
| 154 |
+
"longitude": seg.get("longitude", np.nan),
|
| 155 |
+
"latitude": seg.get("latitude", np.nan),
|
| 156 |
+
"elevation": seg.get("elevation", np.nan),
|
| 157 |
+
"location_available": True,
|
| 158 |
+
"location_source": seg.get("location_source", ""),
|
| 159 |
+
"position_match_mode": seg.get("position_match_mode", ""),
|
| 160 |
+
"position_is_fallback": seg.get("position_is_fallback", False),
|
| 161 |
+
"station_position_starttime": seg.get("station_position_starttime", ""),
|
| 162 |
+
"station_position_endtime": seg.get("station_position_endtime", ""),
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
return {
|
| 166 |
+
"longitude": np.nan,
|
| 167 |
+
"latitude": np.nan,
|
| 168 |
+
"elevation": np.nan,
|
| 169 |
+
"location_available": False,
|
| 170 |
+
"location_source": "default_nan_no_station_record",
|
| 171 |
+
"position_match_mode": "default_nan_no_station_record",
|
| 172 |
+
"position_is_fallback": False,
|
| 173 |
+
"station_position_starttime": "",
|
| 174 |
+
"station_position_endtime": "",
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class HDF5WaveformDataset(Dataset):
|
| 179 |
+
"""
|
| 180 |
+
mode:
|
| 181 |
+
single: 每个 channel 一个样本,返回 [T]
|
| 182 |
+
three : 每个 channel family 一个样本,返回 [T, 3]
|
| 183 |
+
multi : 每个 channel family 一个样本,返回 [T, C]
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
def __init__(
|
| 187 |
+
self,
|
| 188 |
+
h5_file,
|
| 189 |
+
mode="three",
|
| 190 |
+
fill_value=0.0,
|
| 191 |
+
dtype=np.float32,
|
| 192 |
+
default_location=DEFAULT_LOCATION,
|
| 193 |
+
):
|
| 194 |
+
assert mode in ["single", "three", "multi"]
|
| 195 |
+
|
| 196 |
+
self.h5_file = h5_file
|
| 197 |
+
self.mode = mode
|
| 198 |
+
self.fill_value = fill_value
|
| 199 |
+
self.dtype = dtype
|
| 200 |
+
self.default_location = default_location
|
| 201 |
+
|
| 202 |
+
self.index = []
|
| 203 |
+
self._build_index()
|
| 204 |
+
|
| 205 |
+
def _build_index(self):
|
| 206 |
+
with h5py.File(self.h5_file, "r") as h5:
|
| 207 |
+
for year_id in sorted(h5.keys()):
|
| 208 |
+
year_grp = h5[year_id]
|
| 209 |
+
|
| 210 |
+
for day_id in sorted(year_grp.keys()):
|
| 211 |
+
day_grp = year_grp[day_id]
|
| 212 |
+
|
| 213 |
+
if "stations" not in day_grp:
|
| 214 |
+
continue
|
| 215 |
+
|
| 216 |
+
stations_grp = day_grp["stations"]
|
| 217 |
+
|
| 218 |
+
for station_id in sorted(stations_grp.keys()):
|
| 219 |
+
station_grp = stations_grp[station_id]
|
| 220 |
+
|
| 221 |
+
if "waveform" not in station_grp:
|
| 222 |
+
continue
|
| 223 |
+
|
| 224 |
+
waveform_grp = station_grp["waveform"]
|
| 225 |
+
channels = sorted(list(waveform_grp.keys()))
|
| 226 |
+
|
| 227 |
+
if self.mode == "single":
|
| 228 |
+
for cha in channels:
|
| 229 |
+
self.index.append(
|
| 230 |
+
{
|
| 231 |
+
"year_id": year_id,
|
| 232 |
+
"day_id": day_id,
|
| 233 |
+
"station_id": station_id,
|
| 234 |
+
"channel": cha,
|
| 235 |
+
}
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
else:
|
| 239 |
+
families = {}
|
| 240 |
+
|
| 241 |
+
for cha in channels:
|
| 242 |
+
prefix = channel_prefix(cha)
|
| 243 |
+
families.setdefault(prefix, []).append(cha)
|
| 244 |
+
|
| 245 |
+
for prefix, family_channels in families.items():
|
| 246 |
+
family_channels = sorted(
|
| 247 |
+
family_channels,
|
| 248 |
+
key=component_rank,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
if self.mode == "three":
|
| 252 |
+
if not is_valid_waveform_family(family_channels):
|
| 253 |
+
continue
|
| 254 |
+
|
| 255 |
+
self.index.append(
|
| 256 |
+
{
|
| 257 |
+
"year_id": year_id,
|
| 258 |
+
"day_id": day_id,
|
| 259 |
+
"station_id": station_id,
|
| 260 |
+
"channel_family": prefix,
|
| 261 |
+
"channels": family_channels,
|
| 262 |
+
}
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
def __len__(self):
|
| 266 |
+
return len(self.index)
|
| 267 |
+
|
| 268 |
+
def _get_station_group(self, h5, year_id, day_id, station_id):
|
| 269 |
+
return h5[year_id][day_id]["stations"][station_id]
|
| 270 |
+
|
| 271 |
+
def _read_position_history(self, station_grp):
|
| 272 |
+
if "position_history" not in station_grp:
|
| 273 |
+
return []
|
| 274 |
+
|
| 275 |
+
pos_grp = station_grp["position_history"]
|
| 276 |
+
out = []
|
| 277 |
+
|
| 278 |
+
for key in sorted(pos_grp.keys(), key=lambda x: int(x) if str(x).isdigit() else str(x)):
|
| 279 |
+
item = pos_grp[key]
|
| 280 |
+
|
| 281 |
+
out.append(
|
| 282 |
+
{
|
| 283 |
+
"network": get_attr(item, "network", ""),
|
| 284 |
+
"station": get_attr(item, "station", ""),
|
| 285 |
+
"location": normalize_location(
|
| 286 |
+
get_attr(item, "location", self.default_location),
|
| 287 |
+
self.default_location,
|
| 288 |
+
),
|
| 289 |
+
"longitude": get_float_attr(item, "longitude", np.nan),
|
| 290 |
+
"latitude": get_float_attr(item, "latitude", np.nan),
|
| 291 |
+
"elevation": get_float_attr(item, "elevation", np.nan),
|
| 292 |
+
"starttime": get_attr(item, "starttime", ""),
|
| 293 |
+
"endtime": get_attr(item, "endtime", ""),
|
| 294 |
+
}
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
return out
|
| 298 |
+
|
| 299 |
+
def _read_station_attrs(self, station_grp):
|
| 300 |
+
location = normalize_location(
|
| 301 |
+
get_attr(station_grp, "location", self.default_location),
|
| 302 |
+
self.default_location,
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
return {
|
| 306 |
+
"station_id": get_attr(station_grp, "station_id", ""),
|
| 307 |
+
"network": get_attr(station_grp, "network", ""),
|
| 308 |
+
"station": get_attr(station_grp, "station", ""),
|
| 309 |
+
"location": location,
|
| 310 |
+
"location_is_default": get_bool_attr(
|
| 311 |
+
station_grp,
|
| 312 |
+
"location_is_default",
|
| 313 |
+
location == self.default_location,
|
| 314 |
+
),
|
| 315 |
+
"longitude": get_float_attr(station_grp, "longitude", np.nan),
|
| 316 |
+
"latitude": get_float_attr(station_grp, "latitude", np.nan),
|
| 317 |
+
"elevation": get_float_attr(station_grp, "elevation", np.nan),
|
| 318 |
+
"location_available": get_bool_attr(station_grp, "location_available", False),
|
| 319 |
+
"location_source": get_attr(station_grp, "location_source", ""),
|
| 320 |
+
"position_match_mode": get_attr(station_grp, "position_match_mode", ""),
|
| 321 |
+
"position_is_fallback": get_bool_attr(station_grp, "position_is_fallback", False),
|
| 322 |
+
"station_position_starttime": get_attr(station_grp, "station_position_starttime", ""),
|
| 323 |
+
"station_position_endtime": get_attr(station_grp, "station_position_endtime", ""),
|
| 324 |
+
"instrument_time_range_start": get_attr(station_grp, "instrument_time_range_start", ""),
|
| 325 |
+
"instrument_time_range_end": get_attr(station_grp, "instrument_time_range_end", ""),
|
| 326 |
+
"position_history": self._read_position_history(station_grp),
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
def _read_channel_attrs(self, channel_grp):
|
| 330 |
+
return {
|
| 331 |
+
"channel": get_attr(channel_grp, "channel", ""),
|
| 332 |
+
"segment_count": int(get_attr(channel_grp, "segment_count", 0)),
|
| 333 |
+
"starttime": get_attr(channel_grp, "starttime", ""),
|
| 334 |
+
"endtime": get_attr(channel_grp, "endtime", ""),
|
| 335 |
+
"longitude": get_float_attr(channel_grp, "longitude", np.nan),
|
| 336 |
+
"latitude": get_float_attr(channel_grp, "latitude", np.nan),
|
| 337 |
+
"elevation": get_float_attr(channel_grp, "elevation", np.nan),
|
| 338 |
+
"location_available": get_bool_attr(channel_grp, "location_available", False),
|
| 339 |
+
"location_source": get_attr(channel_grp, "location_source", ""),
|
| 340 |
+
"position_match_mode": get_attr(channel_grp, "position_match_mode", ""),
|
| 341 |
+
"position_is_fallback": get_bool_attr(channel_grp, "position_is_fallback", False),
|
| 342 |
+
"station_position_starttime": get_attr(channel_grp, "station_position_starttime", ""),
|
| 343 |
+
"station_position_endtime": get_attr(channel_grp, "station_position_endtime", ""),
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
def _read_channel_segments(self, h5, year_id, day_id, station_id, channel):
|
| 347 |
+
station_grp = self._get_station_group(h5, year_id, day_id, station_id)
|
| 348 |
+
channel_grp = station_grp["waveform"][channel]
|
| 349 |
+
|
| 350 |
+
segments = []
|
| 351 |
+
|
| 352 |
+
for ds_key in sorted(channel_grp.keys(), key=lambda x: int(x)):
|
| 353 |
+
ds = channel_grp[ds_key]
|
| 354 |
+
|
| 355 |
+
segments.append(
|
| 356 |
+
{
|
| 357 |
+
"data": ds[()],
|
| 358 |
+
"segment_index": int(get_attr(ds, "segment_index", ds_key)),
|
| 359 |
+
"starttime": parse_time(get_attr(ds, "starttime", "")),
|
| 360 |
+
"endtime": parse_time(get_attr(ds, "endtime", "")),
|
| 361 |
+
"sampling_rate": float(get_attr(ds, "sampling_rate", np.nan)),
|
| 362 |
+
"delta": float(get_attr(ds, "delta", np.nan)),
|
| 363 |
+
"npts": int(get_attr(ds, "npts", ds.shape[0])),
|
| 364 |
+
"network": get_attr(ds, "network", ""),
|
| 365 |
+
"station": get_attr(ds, "station", ""),
|
| 366 |
+
"location": normalize_location(
|
| 367 |
+
get_attr(ds, "location", self.default_location),
|
| 368 |
+
self.default_location,
|
| 369 |
+
),
|
| 370 |
+
"channel": get_attr(ds, "channel", channel),
|
| 371 |
+
"mseed_source_file": get_attr(ds, "mseed_source_file", ""),
|
| 372 |
+
"dtype": get_attr(ds, "dtype", str(ds.dtype)),
|
| 373 |
+
"longitude": get_float_attr(ds, "longitude", np.nan),
|
| 374 |
+
"latitude": get_float_attr(ds, "latitude", np.nan),
|
| 375 |
+
"elevation": get_float_attr(ds, "elevation", np.nan),
|
| 376 |
+
"location_available": get_bool_attr(ds, "location_available", False),
|
| 377 |
+
"location_source": get_attr(ds, "location_source", ""),
|
| 378 |
+
"station_position_starttime": get_attr(ds, "station_position_starttime", ""),
|
| 379 |
+
"station_position_endtime": get_attr(ds, "station_position_endtime", ""),
|
| 380 |
+
"position_match_mode": get_attr(ds, "position_match_mode", ""),
|
| 381 |
+
"position_is_fallback": get_bool_attr(ds, "position_is_fallback", False),
|
| 382 |
+
}
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
channel_info = self._read_channel_attrs(channel_grp)
|
| 386 |
+
return segments, channel_info
|
| 387 |
+
|
| 388 |
+
def __getitem__(self, idx):
|
| 389 |
+
item = self.index[idx]
|
| 390 |
+
|
| 391 |
+
with h5py.File(self.h5_file, "r") as h5:
|
| 392 |
+
year_id = item["year_id"]
|
| 393 |
+
day_id = item["day_id"]
|
| 394 |
+
station_id = item["station_id"]
|
| 395 |
+
|
| 396 |
+
station_grp = self._get_station_group(h5, year_id, day_id, station_id)
|
| 397 |
+
station_info = self._read_station_attrs(station_grp)
|
| 398 |
+
|
| 399 |
+
if self.mode == "single":
|
| 400 |
+
return self._getitem_single(h5, item, station_info)
|
| 401 |
+
|
| 402 |
+
if self.mode == "three":
|
| 403 |
+
return self._getitem_three(h5, item, station_info)
|
| 404 |
+
|
| 405 |
+
if self.mode == "multi":
|
| 406 |
+
return self._getitem_multi(h5, item, station_info)
|
| 407 |
+
|
| 408 |
+
raise ValueError(f"Unsupported mode: {self.mode}")
|
| 409 |
+
|
| 410 |
+
def _getitem_single(self, h5, item, station_info):
|
| 411 |
+
year_id = item["year_id"]
|
| 412 |
+
day_id = item["day_id"]
|
| 413 |
+
station_id = item["station_id"]
|
| 414 |
+
channel = item["channel"]
|
| 415 |
+
|
| 416 |
+
segments, channel_info = self._read_channel_segments(
|
| 417 |
+
h5, year_id, day_id, station_id, channel
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
waveform, starttime, endtime, sr = fill_segments_to_array(
|
| 421 |
+
segments,
|
| 422 |
+
fill_value=self.fill_value,
|
| 423 |
+
dtype=self.dtype,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
if waveform is None:
|
| 427 |
+
waveform = np.zeros(0, dtype=self.dtype)
|
| 428 |
+
|
| 429 |
+
position_info = get_position_from_segments(segments)
|
| 430 |
+
station_info = dict(station_info)
|
| 431 |
+
station_info.update(position_info)
|
| 432 |
+
|
| 433 |
+
return {
|
| 434 |
+
"mode": "single",
|
| 435 |
+
"year_id": year_id,
|
| 436 |
+
"day_id": day_id,
|
| 437 |
+
"station_id": station_id,
|
| 438 |
+
"station_info": station_info,
|
| 439 |
+
"channel_info": channel_info,
|
| 440 |
+
"channel": channel,
|
| 441 |
+
"channels": [channel],
|
| 442 |
+
"waveform": torch.from_numpy(waveform),
|
| 443 |
+
"segments": [
|
| 444 |
+
{k: v for k, v in seg.items() if k != "data"}
|
| 445 |
+
for seg in segments
|
| 446 |
+
],
|
| 447 |
+
"starttime": str(starttime) if starttime is not None else "",
|
| 448 |
+
"endtime": str(endtime) if endtime is not None else "",
|
| 449 |
+
"sampling_rate": sr,
|
| 450 |
+
"npts": waveform.shape[0],
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
def _getitem_three(self, h5, item, station_info):
|
| 454 |
+
year_id = item["year_id"]
|
| 455 |
+
day_id = item["day_id"]
|
| 456 |
+
station_id = item["station_id"]
|
| 457 |
+
channel_family = item["channel_family"]
|
| 458 |
+
candidate_channels = item["channels"]
|
| 459 |
+
|
| 460 |
+
selected = {}
|
| 461 |
+
|
| 462 |
+
for cha in candidate_channels:
|
| 463 |
+
suf = channel_suffix(cha)
|
| 464 |
+
|
| 465 |
+
if suf in ["E", "1"] and 0 not in selected:
|
| 466 |
+
selected[0] = cha
|
| 467 |
+
elif suf in ["N", "2"] and 1 not in selected:
|
| 468 |
+
selected[1] = cha
|
| 469 |
+
elif suf in ["Z", "3"] and 2 not in selected:
|
| 470 |
+
selected[2] = cha
|
| 471 |
+
|
| 472 |
+
z_only_replicated = False
|
| 473 |
+
|
| 474 |
+
# 只有 Z 的情况:复制为三分量
|
| 475 |
+
if 2 in selected and 0 not in selected and 1 not in selected:
|
| 476 |
+
selected[0] = selected[2]
|
| 477 |
+
selected[1] = selected[2]
|
| 478 |
+
z_only_replicated = True
|
| 479 |
+
|
| 480 |
+
arrays = {}
|
| 481 |
+
starts = []
|
| 482 |
+
ends = []
|
| 483 |
+
srs = []
|
| 484 |
+
all_segments = []
|
| 485 |
+
channel_infos = {}
|
| 486 |
+
|
| 487 |
+
# 避免 Z-only 情况重复读取同一个 channel 三次
|
| 488 |
+
unique_channels = sorted(set(selected.values()))
|
| 489 |
+
|
| 490 |
+
channel_arrays = {}
|
| 491 |
+
|
| 492 |
+
for cha in unique_channels:
|
| 493 |
+
segments, channel_info = self._read_channel_segments(
|
| 494 |
+
h5, year_id, day_id, station_id, cha
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
all_segments.extend(segments)
|
| 498 |
+
channel_infos[cha] = channel_info
|
| 499 |
+
|
| 500 |
+
arr, st, et, sr = fill_segments_to_array(
|
| 501 |
+
segments,
|
| 502 |
+
fill_value=self.fill_value,
|
| 503 |
+
dtype=self.dtype,
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
if arr is None:
|
| 507 |
+
continue
|
| 508 |
+
|
| 509 |
+
channel_arrays[cha] = arr
|
| 510 |
+
starts.append(st)
|
| 511 |
+
ends.append(et)
|
| 512 |
+
srs.append(sr)
|
| 513 |
+
|
| 514 |
+
for comp_idx, cha in selected.items():
|
| 515 |
+
if cha in channel_arrays:
|
| 516 |
+
arrays[comp_idx] = channel_arrays[cha]
|
| 517 |
+
|
| 518 |
+
if len(arrays) == 0:
|
| 519 |
+
waveform = np.zeros((0, 3), dtype=self.dtype)
|
| 520 |
+
starttime = None
|
| 521 |
+
endtime = None
|
| 522 |
+
sr = np.nan
|
| 523 |
+
else:
|
| 524 |
+
sr = srs[0]
|
| 525 |
+
starttime = min(starts)
|
| 526 |
+
endtime = max(ends)
|
| 527 |
+
|
| 528 |
+
max_len = max(len(a) for a in arrays.values())
|
| 529 |
+
waveform = np.full((max_len, 3), self.fill_value, dtype=self.dtype)
|
| 530 |
+
|
| 531 |
+
for comp_idx, arr in arrays.items():
|
| 532 |
+
waveform[: len(arr), comp_idx] = arr
|
| 533 |
+
|
| 534 |
+
position_info = get_position_from_segments(all_segments)
|
| 535 |
+
station_info = dict(station_info)
|
| 536 |
+
station_info.update(position_info)
|
| 537 |
+
|
| 538 |
+
channels_out = [
|
| 539 |
+
selected.get(0, ""),
|
| 540 |
+
selected.get(1, ""),
|
| 541 |
+
selected.get(2, ""),
|
| 542 |
+
]
|
| 543 |
+
|
| 544 |
+
return {
|
| 545 |
+
"mode": "three",
|
| 546 |
+
"year_id": year_id,
|
| 547 |
+
"day_id": day_id,
|
| 548 |
+
"station_id": station_id,
|
| 549 |
+
"station_info": station_info,
|
| 550 |
+
"channel_family": channel_family,
|
| 551 |
+
"channel_info": channel_infos,
|
| 552 |
+
"channels": channels_out,
|
| 553 |
+
"component_order": "E/N/Z or 1/2/3; Z-only is replicated",
|
| 554 |
+
"z_only_replicated": z_only_replicated,
|
| 555 |
+
"waveform": torch.from_numpy(waveform),
|
| 556 |
+
"segments": [
|
| 557 |
+
{k: v for k, v in seg.items() if k != "data"}
|
| 558 |
+
for seg in all_segments
|
| 559 |
+
],
|
| 560 |
+
"starttime": str(starttime) if starttime is not None else "",
|
| 561 |
+
"endtime": str(endtime) if endtime is not None else "",
|
| 562 |
+
"sampling_rate": sr,
|
| 563 |
+
"npts": waveform.shape[0],
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
def _getitem_multi(self, h5, item, station_info):
|
| 567 |
+
year_id = item["year_id"]
|
| 568 |
+
day_id = item["day_id"]
|
| 569 |
+
station_id = item["station_id"]
|
| 570 |
+
channel_family = item["channel_family"]
|
| 571 |
+
channels = item["channels"]
|
| 572 |
+
|
| 573 |
+
arrays = []
|
| 574 |
+
used_channels = []
|
| 575 |
+
starts = []
|
| 576 |
+
ends = []
|
| 577 |
+
srs = []
|
| 578 |
+
all_segments = []
|
| 579 |
+
channel_infos = {}
|
| 580 |
+
|
| 581 |
+
for cha in channels:
|
| 582 |
+
segments, channel_info = self._read_channel_segments(
|
| 583 |
+
h5, year_id, day_id, station_id, cha
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
all_segments.extend(segments)
|
| 587 |
+
channel_infos[cha] = channel_info
|
| 588 |
+
|
| 589 |
+
arr, st, et, sr = fill_segments_to_array(
|
| 590 |
+
segments,
|
| 591 |
+
fill_value=self.fill_value,
|
| 592 |
+
dtype=self.dtype,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
if arr is None:
|
| 596 |
+
continue
|
| 597 |
+
|
| 598 |
+
arrays.append(arr)
|
| 599 |
+
used_channels.append(cha)
|
| 600 |
+
starts.append(st)
|
| 601 |
+
ends.append(et)
|
| 602 |
+
srs.append(sr)
|
| 603 |
+
|
| 604 |
+
if len(arrays) == 0:
|
| 605 |
+
waveform = np.zeros((0, 0), dtype=self.dtype)
|
| 606 |
+
starttime = None
|
| 607 |
+
endtime = None
|
| 608 |
+
sr = np.nan
|
| 609 |
+
else:
|
| 610 |
+
max_len = max(len(a) for a in arrays)
|
| 611 |
+
waveform = np.full(
|
| 612 |
+
(max_len, len(arrays)),
|
| 613 |
+
self.fill_value,
|
| 614 |
+
dtype=self.dtype,
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
for i, arr in enumerate(arrays):
|
| 618 |
+
waveform[: len(arr), i] = arr
|
| 619 |
+
|
| 620 |
+
starttime = min(starts)
|
| 621 |
+
endtime = max(ends)
|
| 622 |
+
sr = srs[0]
|
| 623 |
+
|
| 624 |
+
position_info = get_position_from_segments(all_segments)
|
| 625 |
+
station_info = dict(station_info)
|
| 626 |
+
station_info.update(position_info)
|
| 627 |
+
|
| 628 |
+
return {
|
| 629 |
+
"mode": "multi",
|
| 630 |
+
"year_id": year_id,
|
| 631 |
+
"day_id": day_id,
|
| 632 |
+
"station_id": station_id,
|
| 633 |
+
"station_info": station_info,
|
| 634 |
+
"channel_family": channel_family,
|
| 635 |
+
"channel_info": channel_infos,
|
| 636 |
+
"channels": used_channels,
|
| 637 |
+
"waveform": torch.from_numpy(waveform),
|
| 638 |
+
"segments": [
|
| 639 |
+
{k: v for k, v in seg.items() if k != "data"}
|
| 640 |
+
for seg in all_segments
|
| 641 |
+
],
|
| 642 |
+
"starttime": str(starttime) if starttime is not None else "",
|
| 643 |
+
"endtime": str(endtime) if endtime is not None else "",
|
| 644 |
+
"sampling_rate": sr,
|
| 645 |
+
"npts": waveform.shape[0],
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def waveform_collate_fn(batch):
|
| 650 |
+
return batch
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def padded_collate_fn(batch, fill_value=0.0):
|
| 654 |
+
lengths = []
|
| 655 |
+
arrays = []
|
| 656 |
+
|
| 657 |
+
max_t = 0
|
| 658 |
+
max_c = 1
|
| 659 |
+
|
| 660 |
+
for item in batch:
|
| 661 |
+
x = item["waveform"]
|
| 662 |
+
|
| 663 |
+
if x.ndim == 1:
|
| 664 |
+
x = x[:, None]
|
| 665 |
+
|
| 666 |
+
t, c = x.shape
|
| 667 |
+
max_t = max(max_t, t)
|
| 668 |
+
max_c = max(max_c, c)
|
| 669 |
+
|
| 670 |
+
lengths.append(t)
|
| 671 |
+
arrays.append(x)
|
| 672 |
+
|
| 673 |
+
out = torch.full(
|
| 674 |
+
(len(batch), max_t, max_c),
|
| 675 |
+
fill_value=float(fill_value),
|
| 676 |
+
dtype=arrays[0].dtype,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
for i, x in enumerate(arrays):
|
| 680 |
+
t, c = x.shape
|
| 681 |
+
out[i, :t, :c] = x
|
| 682 |
+
|
| 683 |
+
meta = []
|
| 684 |
+
|
| 685 |
+
for item in batch:
|
| 686 |
+
d = dict(item)
|
| 687 |
+
d.pop("waveform")
|
| 688 |
+
meta.append(d)
|
| 689 |
+
|
| 690 |
+
return {
|
| 691 |
+
"waveform": out,
|
| 692 |
+
"lengths": torch.tensor(lengths, dtype=torch.long),
|
| 693 |
+
"meta": meta,
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
if __name__ == "__main__":
|
| 698 |
+
h5_file = "data/continuous_waveform_usa.h5"
|
| 699 |
+
|
| 700 |
+
dataset = HDF5WaveformDataset(
|
| 701 |
+
h5_file=h5_file,
|
| 702 |
+
mode="three",
|
| 703 |
+
fill_value=0.0,
|
| 704 |
+
dtype=np.float32,
|
| 705 |
+
default_location="--",
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
loader = DataLoader(
|
| 709 |
+
dataset,
|
| 710 |
+
batch_size=2,
|
| 711 |
+
shuffle=False,
|
| 712 |
+
num_workers=0,
|
| 713 |
+
collate_fn=waveform_collate_fn,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
print("Number of samples:", len(dataset))
|
| 717 |
+
|
| 718 |
+
for batch in loader:
|
| 719 |
+
for item in batch:
|
| 720 |
+
print("=" * 80)
|
| 721 |
+
print("station_id:", item["station_id"])
|
| 722 |
+
print("station_info:", item["station_info"])
|
| 723 |
+
print("mode:", item["mode"])
|
| 724 |
+
print("channel_family:", item["channel_family"])
|
| 725 |
+
print("channels:", item["channels"])
|
| 726 |
+
print("z_only_replicated:", item["z_only_replicated"])
|
| 727 |
+
print("starttime:", item["starttime"])
|
| 728 |
+
print("endtime:", item["endtime"])
|
| 729 |
+
print("sampling_rate:", item["sampling_rate"])
|
| 730 |
+
print("waveform shape:", tuple(item["waveform"].shape))
|
| 731 |
+
print("first segment meta:", item["segments"][0] if item["segments"] else None)
|
| 732 |
+
break
|