SeismicX-Cont / utils /continous_dataloader_singlefile.py
cangyeone's picture
Upload utils/continous_dataloader_singlefile.py
a6754c6 verified
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import h5py
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from obspy import UTCDateTime
DEFAULT_LOCATION = "--"
def parse_time(t):
return UTCDateTime(str(t))
def decode_attr(value):
if isinstance(value, bytes):
return value.decode("utf-8", errors="ignore")
if isinstance(value, np.bytes_):
return value.decode("utf-8", errors="ignore")
return value
def normalize_location(location, default=DEFAULT_LOCATION):
location = decode_attr(location)
if location is None:
return default
location = str(location).strip()
return location if location else default
def channel_suffix(channel):
return str(channel)[-1].upper()
def channel_prefix(channel):
# 前两位作为 family,例如 BHE/BHN/BHZ -> BH
ch = str(channel).upper()
if len(ch) >= 3:
return ch[:2]
return ch[:-1]
def component_rank(channel):
order = {
"E": 0,
"1": 0,
"N": 1,
"2": 1,
"Z": 2,
"3": 2,
}
return order.get(channel_suffix(channel), 99)
def is_valid_waveform_family(channels):
"""
判断一个 channel family 是否可以构成三分量输入。
支持:
1. E/N/Z
2. 1/2/3
3. only Z,后续复制成三分量
"""
suffixes = {channel_suffix(ch) for ch in channels}
if {"E", "N", "Z"}.issubset(suffixes):
return True
if {"1", "2", "3"}.issubset(suffixes):
return True
if suffixes == {"Z"}:
return True
return False
def get_attr(obj, name, default=None):
if name in obj.attrs:
return decode_attr(obj.attrs[name])
return default
def get_float_attr(obj, name, default=np.nan):
try:
return float(get_attr(obj, name, default))
except Exception:
return float(default)
def get_bool_attr(obj, name, default=False):
value = get_attr(obj, name, default)
if isinstance(value, (bool, np.bool_)):
return bool(value)
if isinstance(value, (int, np.integer)):
return bool(value)
if isinstance(value, str):
return value.lower() in ["true", "1", "yes"]
return bool(value)
def fill_segments_to_array(segments, fill_value=0.0, dtype=np.float32):
if len(segments) == 0:
return None, None, None, None
segments = sorted(segments, key=lambda x: x["starttime"])
sampling_rate = segments[0]["sampling_rate"]
global_start = min(s["starttime"] for s in segments)
global_end = max(s["endtime"] for s in segments)
npts = int(round((global_end - global_start) * sampling_rate)) + 1
data = np.full(npts, fill_value, dtype=dtype)
filled = np.zeros(npts, dtype=bool)
for seg in segments:
seg_data = seg["data"].astype(dtype, copy=False)
i0 = int(round((seg["starttime"] - global_start) * sampling_rate))
i1 = i0 + len(seg_data)
if i0 < 0:
seg_data = seg_data[-i0:]
i0 = 0
if i1 > npts:
seg_data = seg_data[: npts - i0]
i1 = npts
if i0 >= i1:
continue
target = slice(i0, i1)
mask = ~filled[target]
data[target][mask] = seg_data[: i1 - i0][mask]
filled[target][mask] = True
return data, global_start, global_end, sampling_rate
def get_position_from_segments(segments):
for seg in segments:
if seg.get("location_available", False):
return {
"longitude": seg.get("longitude", np.nan),
"latitude": seg.get("latitude", np.nan),
"elevation": seg.get("elevation", np.nan),
"location_available": True,
"location_source": seg.get("location_source", ""),
"position_match_mode": seg.get("position_match_mode", ""),
"position_is_fallback": seg.get("position_is_fallback", False),
"station_position_starttime": seg.get("station_position_starttime", ""),
"station_position_endtime": seg.get("station_position_endtime", ""),
}
return {
"longitude": np.nan,
"latitude": np.nan,
"elevation": np.nan,
"location_available": False,
"location_source": "default_nan_no_station_record",
"position_match_mode": "default_nan_no_station_record",
"position_is_fallback": False,
"station_position_starttime": "",
"station_position_endtime": "",
}
class HDF5WaveformDataset(Dataset):
"""
mode:
single: 每个 channel 一个样本,返回 [T]
three : 每个 channel family 一个样本,返回 [T, 3]
multi : 每个 channel family 一个样本,返回 [T, C]
"""
def __init__(
self,
h5_file,
mode="three",
fill_value=0.0,
dtype=np.float32,
default_location=DEFAULT_LOCATION,
):
assert mode in ["single", "three", "multi"]
self.h5_file = h5_file
self.mode = mode
self.fill_value = fill_value
self.dtype = dtype
self.default_location = default_location
self.index = []
self._build_index()
def _build_index(self):
with h5py.File(self.h5_file, "r") as h5:
for year_id in sorted(h5.keys()):
year_grp = h5[year_id]
for day_id in sorted(year_grp.keys()):
day_grp = year_grp[day_id]
if "stations" not in day_grp:
continue
stations_grp = day_grp["stations"]
for station_id in sorted(stations_grp.keys()):
station_grp = stations_grp[station_id]
if "waveform" not in station_grp:
continue
waveform_grp = station_grp["waveform"]
channels = sorted(list(waveform_grp.keys()))
if self.mode == "single":
for cha in channels:
self.index.append(
{
"year_id": year_id,
"day_id": day_id,
"station_id": station_id,
"channel": cha,
}
)
else:
families = {}
for cha in channels:
prefix = channel_prefix(cha)
families.setdefault(prefix, []).append(cha)
for prefix, family_channels in families.items():
family_channels = sorted(
family_channels,
key=component_rank,
)
if self.mode == "three":
if not is_valid_waveform_family(family_channels):
continue
self.index.append(
{
"year_id": year_id,
"day_id": day_id,
"station_id": station_id,
"channel_family": prefix,
"channels": family_channels,
}
)
def __len__(self):
return len(self.index)
def _get_station_group(self, h5, year_id, day_id, station_id):
return h5[year_id][day_id]["stations"][station_id]
def _read_position_history(self, station_grp):
if "position_history" not in station_grp:
return []
pos_grp = station_grp["position_history"]
out = []
for key in sorted(pos_grp.keys(), key=lambda x: int(x) if str(x).isdigit() else str(x)):
item = pos_grp[key]
out.append(
{
"network": get_attr(item, "network", ""),
"station": get_attr(item, "station", ""),
"location": normalize_location(
get_attr(item, "location", self.default_location),
self.default_location,
),
"longitude": get_float_attr(item, "longitude", np.nan),
"latitude": get_float_attr(item, "latitude", np.nan),
"elevation": get_float_attr(item, "elevation", np.nan),
"starttime": get_attr(item, "starttime", ""),
"endtime": get_attr(item, "endtime", ""),
}
)
return out
def _read_station_attrs(self, station_grp):
location = normalize_location(
get_attr(station_grp, "location", self.default_location),
self.default_location,
)
return {
"station_id": get_attr(station_grp, "station_id", ""),
"network": get_attr(station_grp, "network", ""),
"station": get_attr(station_grp, "station", ""),
"location": location,
"location_is_default": get_bool_attr(
station_grp,
"location_is_default",
location == self.default_location,
),
"longitude": get_float_attr(station_grp, "longitude", np.nan),
"latitude": get_float_attr(station_grp, "latitude", np.nan),
"elevation": get_float_attr(station_grp, "elevation", np.nan),
"location_available": get_bool_attr(station_grp, "location_available", False),
"location_source": get_attr(station_grp, "location_source", ""),
"position_match_mode": get_attr(station_grp, "position_match_mode", ""),
"position_is_fallback": get_bool_attr(station_grp, "position_is_fallback", False),
"station_position_starttime": get_attr(station_grp, "station_position_starttime", ""),
"station_position_endtime": get_attr(station_grp, "station_position_endtime", ""),
"instrument_time_range_start": get_attr(station_grp, "instrument_time_range_start", ""),
"instrument_time_range_end": get_attr(station_grp, "instrument_time_range_end", ""),
"position_history": self._read_position_history(station_grp),
}
def _read_channel_attrs(self, channel_grp):
return {
"channel": get_attr(channel_grp, "channel", ""),
"segment_count": int(get_attr(channel_grp, "segment_count", 0)),
"starttime": get_attr(channel_grp, "starttime", ""),
"endtime": get_attr(channel_grp, "endtime", ""),
"longitude": get_float_attr(channel_grp, "longitude", np.nan),
"latitude": get_float_attr(channel_grp, "latitude", np.nan),
"elevation": get_float_attr(channel_grp, "elevation", np.nan),
"location_available": get_bool_attr(channel_grp, "location_available", False),
"location_source": get_attr(channel_grp, "location_source", ""),
"position_match_mode": get_attr(channel_grp, "position_match_mode", ""),
"position_is_fallback": get_bool_attr(channel_grp, "position_is_fallback", False),
"station_position_starttime": get_attr(channel_grp, "station_position_starttime", ""),
"station_position_endtime": get_attr(channel_grp, "station_position_endtime", ""),
}
def _read_channel_segments(self, h5, year_id, day_id, station_id, channel):
station_grp = self._get_station_group(h5, year_id, day_id, station_id)
channel_grp = station_grp["waveform"][channel]
segments = []
for ds_key in sorted(channel_grp.keys(), key=lambda x: int(x)):
ds = channel_grp[ds_key]
segments.append(
{
"data": ds[()],
"segment_index": int(get_attr(ds, "segment_index", ds_key)),
"starttime": parse_time(get_attr(ds, "starttime", "")),
"endtime": parse_time(get_attr(ds, "endtime", "")),
"sampling_rate": float(get_attr(ds, "sampling_rate", np.nan)),
"delta": float(get_attr(ds, "delta", np.nan)),
"npts": int(get_attr(ds, "npts", ds.shape[0])),
"network": get_attr(ds, "network", ""),
"station": get_attr(ds, "station", ""),
"location": normalize_location(
get_attr(ds, "location", self.default_location),
self.default_location,
),
"channel": get_attr(ds, "channel", channel),
"mseed_source_file": get_attr(ds, "mseed_source_file", ""),
"dtype": get_attr(ds, "dtype", str(ds.dtype)),
"longitude": get_float_attr(ds, "longitude", np.nan),
"latitude": get_float_attr(ds, "latitude", np.nan),
"elevation": get_float_attr(ds, "elevation", np.nan),
"location_available": get_bool_attr(ds, "location_available", False),
"location_source": get_attr(ds, "location_source", ""),
"station_position_starttime": get_attr(ds, "station_position_starttime", ""),
"station_position_endtime": get_attr(ds, "station_position_endtime", ""),
"position_match_mode": get_attr(ds, "position_match_mode", ""),
"position_is_fallback": get_bool_attr(ds, "position_is_fallback", False),
}
)
channel_info = self._read_channel_attrs(channel_grp)
return segments, channel_info
def __getitem__(self, idx):
item = self.index[idx]
with h5py.File(self.h5_file, "r") as h5:
year_id = item["year_id"]
day_id = item["day_id"]
station_id = item["station_id"]
station_grp = self._get_station_group(h5, year_id, day_id, station_id)
station_info = self._read_station_attrs(station_grp)
if self.mode == "single":
return self._getitem_single(h5, item, station_info)
if self.mode == "three":
return self._getitem_three(h5, item, station_info)
if self.mode == "multi":
return self._getitem_multi(h5, item, station_info)
raise ValueError(f"Unsupported mode: {self.mode}")
def _getitem_single(self, h5, item, station_info):
year_id = item["year_id"]
day_id = item["day_id"]
station_id = item["station_id"]
channel = item["channel"]
segments, channel_info = self._read_channel_segments(
h5, year_id, day_id, station_id, channel
)
waveform, starttime, endtime, sr = fill_segments_to_array(
segments,
fill_value=self.fill_value,
dtype=self.dtype,
)
if waveform is None:
waveform = np.zeros(0, dtype=self.dtype)
position_info = get_position_from_segments(segments)
station_info = dict(station_info)
station_info.update(position_info)
return {
"mode": "single",
"year_id": year_id,
"day_id": day_id,
"station_id": station_id,
"station_info": station_info,
"channel_info": channel_info,
"channel": channel,
"channels": [channel],
"waveform": torch.from_numpy(waveform),
"segments": [
{k: v for k, v in seg.items() if k != "data"}
for seg in segments
],
"starttime": str(starttime) if starttime is not None else "",
"endtime": str(endtime) if endtime is not None else "",
"sampling_rate": sr,
"npts": waveform.shape[0],
}
def _getitem_three(self, h5, item, station_info):
year_id = item["year_id"]
day_id = item["day_id"]
station_id = item["station_id"]
channel_family = item["channel_family"]
candidate_channels = item["channels"]
selected = {}
for cha in candidate_channels:
suf = channel_suffix(cha)
if suf in ["E", "1"] and 0 not in selected:
selected[0] = cha
elif suf in ["N", "2"] and 1 not in selected:
selected[1] = cha
elif suf in ["Z", "3"] and 2 not in selected:
selected[2] = cha
z_only_replicated = False
# 只有 Z 的情况:复制为三分量
if 2 in selected and 0 not in selected and 1 not in selected:
selected[0] = selected[2]
selected[1] = selected[2]
z_only_replicated = True
arrays = {}
starts = []
ends = []
srs = []
all_segments = []
channel_infos = {}
# 避免 Z-only 情况重复读取同一个 channel 三次
unique_channels = sorted(set(selected.values()))
channel_arrays = {}
for cha in unique_channels:
segments, channel_info = self._read_channel_segments(
h5, year_id, day_id, station_id, cha
)
all_segments.extend(segments)
channel_infos[cha] = channel_info
arr, st, et, sr = fill_segments_to_array(
segments,
fill_value=self.fill_value,
dtype=self.dtype,
)
if arr is None:
continue
channel_arrays[cha] = arr
starts.append(st)
ends.append(et)
srs.append(sr)
for comp_idx, cha in selected.items():
if cha in channel_arrays:
arrays[comp_idx] = channel_arrays[cha]
if len(arrays) == 0:
waveform = np.zeros((0, 3), dtype=self.dtype)
starttime = None
endtime = None
sr = np.nan
else:
sr = srs[0]
starttime = min(starts)
endtime = max(ends)
max_len = max(len(a) for a in arrays.values())
waveform = np.full((max_len, 3), self.fill_value, dtype=self.dtype)
for comp_idx, arr in arrays.items():
waveform[: len(arr), comp_idx] = arr
position_info = get_position_from_segments(all_segments)
station_info = dict(station_info)
station_info.update(position_info)
channels_out = [
selected.get(0, ""),
selected.get(1, ""),
selected.get(2, ""),
]
return {
"mode": "three",
"year_id": year_id,
"day_id": day_id,
"station_id": station_id,
"station_info": station_info,
"channel_family": channel_family,
"channel_info": channel_infos,
"channels": channels_out,
"component_order": "E/N/Z or 1/2/3; Z-only is replicated",
"z_only_replicated": z_only_replicated,
"waveform": torch.from_numpy(waveform),
"segments": [
{k: v for k, v in seg.items() if k != "data"}
for seg in all_segments
],
"starttime": str(starttime) if starttime is not None else "",
"endtime": str(endtime) if endtime is not None else "",
"sampling_rate": sr,
"npts": waveform.shape[0],
}
def _getitem_multi(self, h5, item, station_info):
year_id = item["year_id"]
day_id = item["day_id"]
station_id = item["station_id"]
channel_family = item["channel_family"]
channels = item["channels"]
arrays = []
used_channels = []
starts = []
ends = []
srs = []
all_segments = []
channel_infos = {}
for cha in channels:
segments, channel_info = self._read_channel_segments(
h5, year_id, day_id, station_id, cha
)
all_segments.extend(segments)
channel_infos[cha] = channel_info
arr, st, et, sr = fill_segments_to_array(
segments,
fill_value=self.fill_value,
dtype=self.dtype,
)
if arr is None:
continue
arrays.append(arr)
used_channels.append(cha)
starts.append(st)
ends.append(et)
srs.append(sr)
if len(arrays) == 0:
waveform = np.zeros((0, 0), dtype=self.dtype)
starttime = None
endtime = None
sr = np.nan
else:
max_len = max(len(a) for a in arrays)
waveform = np.full(
(max_len, len(arrays)),
self.fill_value,
dtype=self.dtype,
)
for i, arr in enumerate(arrays):
waveform[: len(arr), i] = arr
starttime = min(starts)
endtime = max(ends)
sr = srs[0]
position_info = get_position_from_segments(all_segments)
station_info = dict(station_info)
station_info.update(position_info)
return {
"mode": "multi",
"year_id": year_id,
"day_id": day_id,
"station_id": station_id,
"station_info": station_info,
"channel_family": channel_family,
"channel_info": channel_infos,
"channels": used_channels,
"waveform": torch.from_numpy(waveform),
"segments": [
{k: v for k, v in seg.items() if k != "data"}
for seg in all_segments
],
"starttime": str(starttime) if starttime is not None else "",
"endtime": str(endtime) if endtime is not None else "",
"sampling_rate": sr,
"npts": waveform.shape[0],
}
def waveform_collate_fn(batch):
return batch
def padded_collate_fn(batch, fill_value=0.0):
lengths = []
arrays = []
max_t = 0
max_c = 1
for item in batch:
x = item["waveform"]
if x.ndim == 1:
x = x[:, None]
t, c = x.shape
max_t = max(max_t, t)
max_c = max(max_c, c)
lengths.append(t)
arrays.append(x)
out = torch.full(
(len(batch), max_t, max_c),
fill_value=float(fill_value),
dtype=arrays[0].dtype,
)
for i, x in enumerate(arrays):
t, c = x.shape
out[i, :t, :c] = x
meta = []
for item in batch:
d = dict(item)
d.pop("waveform")
meta.append(d)
return {
"waveform": out,
"lengths": torch.tensor(lengths, dtype=torch.long),
"meta": meta,
}
if __name__ == "__main__":
h5_file = "data/continuous_waveform_usa.h5"
dataset = HDF5WaveformDataset(
h5_file=h5_file,
mode="three",
fill_value=0.0,
dtype=np.float32,
default_location="--",
)
loader = DataLoader(
dataset,
batch_size=2,
shuffle=False,
num_workers=0,
collate_fn=waveform_collate_fn,
)
print("Number of samples:", len(dataset))
for batch in loader:
for item in batch:
print("=" * 80)
print("station_id:", item["station_id"])
print("station_info:", item["station_info"])
print("mode:", item["mode"])
print("channel_family:", item["channel_family"])
print("channels:", item["channels"])
print("z_only_replicated:", item["z_only_replicated"])
print("starttime:", item["starttime"])
print("endtime:", item["endtime"])
print("sampling_rate:", item["sampling_rate"])
print("waveform shape:", tuple(item["waveform"].shape))
print("first segment meta:", item["segments"][0] if item["segments"] else None)
break