#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import sqlite3 import warnings from collections import defaultdict import h5py import numpy as np from obspy import Trace, UTCDateTime from utils.hdf5_waveform_dataset import ( DEFAULT_LOCATION, apply_response_spectrum, inventory_from_response_record, load_response_json, normalize_location, response_from_json_record, response_record_matches_time, utc_or_none, ) def parse_time_to_epoch(t): return float(UTCDateTime(t).timestamp) def epoch_to_utc(t): return str(UTCDateTime(float(t))) def wildcard_to_sql_like(pattern): """ Convert wildcard pattern to SQL LIKE pattern. Examples: "*" -> "%" "BK" -> "BK" "B*" -> "B%" "*Z" -> "%Z" "BH*" -> "BH%" """ if pattern is None or str(pattern).strip() == "": return "%" return str(pattern).strip().replace("*", "%") def query_segments( db_file, network="*", station="*", location="*", channel="*", starttime=None, endtime=None, limit=None, ): """ Query waveform segments from SQLite index. Parameters ---------- db_file : str SQLite index database path. network : str Network code or wildcard pattern, e.g. "BK", "C*", "*". station : str Station code or wildcard pattern, e.g. "BDM", "BD*", "*". location : str Location code or wildcard pattern, e.g. "00", "--", "*". channel : str Channel code or wildcard pattern, e.g. "BHE", "BH*", "*Z", "*". starttime : str Query start time. endtime : str Query end time. limit : int or None Optional maximum number of returned segments. Returns ------- rows : list[dict] Matched waveform segment metadata. """ if starttime is None or endtime is None: raise ValueError("starttime and endtime are required.") query_start = parse_time_to_epoch(starttime) query_end = parse_time_to_epoch(endtime) sql = """ SELECT * FROM waveform_segments WHERE network LIKE ? AND station LIKE ? AND location LIKE ? AND channel LIKE ? AND end_epoch >= ? AND start_epoch <= ? ORDER BY network, station, location, channel, start_epoch """ params = [ wildcard_to_sql_like(network), wildcard_to_sql_like(station), wildcard_to_sql_like(location), wildcard_to_sql_like(channel), query_start, query_end, ] if limit is not None: sql += " LIMIT ?" params.append(int(limit)) conn = sqlite3.connect(db_file) conn.row_factory = sqlite3.Row try: cur = conn.cursor() cur.execute(sql, params) rows = [dict(r) for r in cur.fetchall()] finally: conn.close() return rows def read_hdf5_segment(row): """ Read a single waveform segment from HDF5 using h5_file and dataset_path. """ with h5py.File(row["h5_file"], "r") as h5: data = h5[row["dataset_path"]][()] return np.asarray(data) def trim_segment_to_window(data, row, starttime, endtime): """ Trim one segment to the requested time window. """ sr = float(row["sampling_rate"]) seg_start = float(row["start_epoch"]) seg_end = float(row["end_epoch"]) query_start = parse_time_to_epoch(starttime) query_end = parse_time_to_epoch(endtime) use_start = max(seg_start, query_start) use_end = min(seg_end, query_end) if use_end < use_start: return data[:0], use_start, use_end i0 = int(round((use_start - seg_start) * sr)) i1 = int(round((use_end - seg_start) * sr)) + 1 i0 = max(i0, 0) i1 = min(i1, len(data)) return data[i0:i1], use_start, use_end def merge_segments( rows, starttime, endtime, fill_value=0.0, dtype=np.float32, ): """ Merge multiple waveform segments into continuous arrays. Segments are grouped by: network.station.location.channel Missing samples are filled by fill_value. Returns ------- merged : dict { "BK.BDM.00.BHE": { "data": np.ndarray, "network": "BK", "station": "BDM", "location": "00", "channel": "BHE", "starttime": "...", "endtime": "...", "sampling_rate": 100.0, "npts": 360001, "segments": [...] }, ... } """ if len(rows) == 0: return {} query_start = parse_time_to_epoch(starttime) query_end = parse_time_to_epoch(endtime) groups = defaultdict(list) for row in rows: key = ( row["network"], row["station"], row["location"], row["channel"], ) groups[key].append(row) merged = {} for key, seg_rows in groups.items(): network, station, location, channel = key seg_rows = sorted(seg_rows, key=lambda r: float(r["start_epoch"])) sampling_rates = sorted(set(float(r["sampling_rate"]) for r in seg_rows)) if len(sampling_rates) != 1: raise ValueError( f"Multiple sampling rates found for {network}.{station}.{location}.{channel}: " f"{sampling_rates}" ) sr = sampling_rates[0] npts = int(round((query_end - query_start) * sr)) + 1 out = np.full(npts, fill_value, dtype=dtype) filled = np.zeros(npts, dtype=bool) used_segments = [] for row in seg_rows: data = read_hdf5_segment(row) data, use_start, use_end = trim_segment_to_window( data, row, starttime=starttime, endtime=endtime, ) if len(data) == 0: continue i0 = int(round((use_start - query_start) * sr)) i1 = i0 + len(data) if i0 < 0: data = data[-i0:] i0 = 0 if i1 > npts: data = data[: npts - i0] i1 = npts if i0 >= i1: continue target = slice(i0, i1) mask = ~filled[target] out[target][mask] = data[: i1 - i0][mask].astype(dtype, copy=False) filled[target][mask] = True used_segments.append( { "h5_file": row["h5_file"], "dataset_path": row["dataset_path"], "network": row["network"], "station": row["station"], "location": row["location"], "channel": row["channel"], "segment_starttime": row["starttime"], "segment_endtime": row["endtime"], "segment_start_epoch": float(row["start_epoch"]), "segment_end_epoch": float(row["end_epoch"]), "used_starttime": epoch_to_utc(use_start), "used_endtime": epoch_to_utc(use_end), "npts": int(len(data)), } ) out_key = f"{network}.{station}.{location}.{channel}" merged[out_key] = { "data": out, "network": network, "station": station, "location": location, "channel": channel, "starttime": str(UTCDateTime(starttime)), "endtime": str(UTCDateTime(endtime)), "sampling_rate": sr, "npts": int(len(out)), "filled_ratio": float(filled.mean()) if len(filled) > 0 else 0.0, "segments": used_segments, } return merged class InstrumentResponseProcessor: """ Apply the same response-removal and response-simulation options used by the PyTorch dataloader to waveforms returned by the SQLite query API. """ def __init__( self, instrument_response_json=None, remove_instrument_response=False, response_output="VEL", response_pre_filt=None, response_water_level=60, response_zero_mean=True, response_taper=True, response_taper_fraction=0.05, response_error_behavior="raise", simulate_instrument_response=False, simulation_response_json=None, simulation_response_id=None, simulation_response_selector=None, simulation_paz=None, simulation_output=None, simulation_sensitivity=True, default_location=DEFAULT_LOCATION, dtype=np.float32, ): if response_error_behavior not in {"raise", "warn", "skip"}: raise ValueError("response_error_behavior must be 'raise', 'warn', or 'skip'") self.instrument_response_json = ( str(instrument_response_json) if instrument_response_json is not None else None ) self.remove_instrument_response = bool(remove_instrument_response) self.response_output = str(response_output).upper() if response_output is not None else "VEL" self.response_pre_filt = ( tuple(float(x) for x in response_pre_filt) if response_pre_filt is not None else None ) self.response_water_level = response_water_level self.response_zero_mean = bool(response_zero_mean) self.response_taper = bool(response_taper) self.response_taper_fraction = float(response_taper_fraction) self.response_error_behavior = response_error_behavior self.simulate_instrument_response = bool(simulate_instrument_response) self.simulation_response_json = ( str(simulation_response_json) if simulation_response_json is not None else None ) self.simulation_response_id = ( str(simulation_response_id) if simulation_response_id is not None else None ) self.simulation_response_selector = dict(simulation_response_selector or {}) self.simulation_paz = simulation_paz self.simulation_output = ( str(simulation_output).upper() if simulation_output is not None else self.response_output ) self.simulation_sensitivity = bool(simulation_sensitivity) self.default_location = default_location self.dtype = dtype if self.remove_instrument_response and self.instrument_response_json is None: raise ValueError( "instrument_response_json is required when remove_instrument_response is enabled." ) if self.simulate_instrument_response and ( self.simulation_paz is None and self.simulation_response_id is None and not self.simulation_response_selector and self.simulation_response_json is None and self.instrument_response_json is None ): raise ValueError( "simulate_instrument_response=True requires simulation_paz, " "simulation_response_id, simulation_response_selector, " "simulation_response_json, or instrument_response_json." ) self._response_store = None self._simulation_response_store = None self._response_object_cache = {} self._inventory_cache = {} self._simulation_response_record = None self._simulation_response_object = None @property def enabled(self): return self.remove_instrument_response or self.simulate_instrument_response def _ensure_response_store(self): if self._response_store is None: if self.instrument_response_json is None: raise ValueError("instrument_response_json is not configured") self._response_store = load_response_json(self.instrument_response_json) return self._response_store def _ensure_simulation_response_store(self): if self._simulation_response_store is None: path = self.simulation_response_json or self.instrument_response_json if path is None: raise ValueError("No simulation response JSON is configured") self._simulation_response_store = load_response_json(path) return self._simulation_response_store def _get_response_object(self, record): response_id = str(record.get("response_id", "")) cache_key = response_id or id(record) if cache_key not in self._response_object_cache: self._response_object_cache[cache_key] = response_from_json_record(record) return self._response_object_cache[cache_key] def _get_inventory(self, record): response_id = str(record.get("response_id", "")) cache_key = response_id or id(record) if cache_key not in self._inventory_cache: response = self._get_response_object(record) self._inventory_cache[cache_key] = inventory_from_response_record(record, response) return self._inventory_cache[cache_key] def _find_response_record(self, network, station, location, channel, starttime, endtime=None): store = self._ensure_response_store() key = ( str(network), str(station), normalize_location(location, self.default_location), str(channel), ) for record in store["responses_by_key"].get(key, []): if response_record_matches_time(record, starttime, endtime): return record return None def _select_simulation_response_record(self): if self._simulation_response_record is not None: return self._simulation_response_record store = self._ensure_simulation_response_store() record = None if self.simulation_response_id: record = store["responses_by_id"].get(self.simulation_response_id) if record is None: raise KeyError( f"simulation_response_id not found: {self.simulation_response_id}" ) elif self.simulation_response_selector: sel = self.simulation_response_selector key = ( str(sel.get("network", "")), str(sel.get("station", "")), normalize_location(sel.get("location", self.default_location), self.default_location), str(sel.get("channel", "")), ) starttime = utc_or_none(sel.get("time")) or utc_or_none(sel.get("starttime")) for item in store["responses_by_key"].get(key, []): if response_record_matches_time(item, starttime): record = item break if record is None: raise KeyError(f"simulation_response_selector did not match any response: {sel}") else: records_by_id = store["responses_by_id"] if len(records_by_id) != 1: raise ValueError( "simulation_response_json must contain exactly one response unless " "simulation_response_id or simulation_response_selector is provided." ) record = next(iter(records_by_id.values())) self._simulation_response_record = record self._simulation_response_object = self._get_response_object(record) return record def _handle_response_error(self, message): if self.response_error_behavior == "raise": raise RuntimeError(message) if self.response_error_behavior == "warn": warnings.warn(message, RuntimeWarning, stacklevel=2) return None def metadata_template(self): return { "remove_instrument_response": self.remove_instrument_response, "simulate_instrument_response": self.simulate_instrument_response, "response_output": self.response_output, "simulation_output": self.simulation_output, "response_id": "", "response_epoch_start": "", "response_epoch_end": "", "simulation_response_id": "", "error": "", "processed": False, } def apply_to_item(self, item): metadata = self.metadata_template() item["instrument_processing"] = metadata waveform = item.get("data") if waveform is None or len(waveform) == 0 or not self.enabled: return item segments = item.get("segments") or [] first_segment = segments[0] if segments else {} network = item.get("network") or first_segment.get("network", "") station = item.get("station") or first_segment.get("station", "") location = item.get("location") or first_segment.get("location", self.default_location) channel = item.get("channel") or first_segment.get("channel", "") sampling_rate = float(item.get("sampling_rate")) starttime = UTCDateTime(item.get("starttime")) endtime = UTCDateTime(item.get("endtime")) try: trace = Trace( data=np.asarray(waveform, dtype=np.float64), header={ "network": str(network), "station": str(station), "location": normalize_location(location, self.default_location), "channel": str(channel), "starttime": starttime, "sampling_rate": sampling_rate, }, ) if self.remove_instrument_response: record = self._find_response_record( network, station, location, channel, starttime, endtime=endtime, ) if record is None: key = ".".join([ str(network), str(station), normalize_location(location, self.default_location), str(channel), ]) raise KeyError(f"No response found for {key} at {starttime}") metadata.update( { "response_id": record.get("response_id", ""), "response_epoch_start": record.get("epoch_start", ""), "response_epoch_end": record.get("epoch_end", ""), } ) trace.remove_response( inventory=self._get_inventory(record), output=self.response_output, water_level=self.response_water_level, pre_filt=self.response_pre_filt, zero_mean=self.response_zero_mean, taper=self.response_taper, taper_fraction=self.response_taper_fraction, ) if self.simulate_instrument_response: if self.simulation_paz is not None: trace.simulate( paz_remove=None, paz_simulate=self.simulation_paz, remove_sensitivity=False, simulate_sensitivity=self.simulation_sensitivity, ) metadata["simulation_response_id"] = "simulation_paz" else: sim_record = self._select_simulation_response_record() sim_response = self._simulation_response_object trace.data = apply_response_spectrum( trace.data, sampling_rate=trace.stats.sampling_rate, response=sim_response, output=self.simulation_output, ) metadata["simulation_response_id"] = sim_record.get("response_id", "") metadata["processed"] = True item["data"] = np.asarray(trace.data, dtype=self.dtype) return item except Exception as exc: metadata["error"] = str(exc) self._handle_response_error(str(exc)) item["data"] = np.asarray(waveform, dtype=self.dtype) return item def apply_instrument_processing_to_merged(merged, **kwargs): processor = InstrumentResponseProcessor(**kwargs) for item in merged.values(): processor.apply_to_item(item) return merged def query_and_merge( db_file, network="*", station="*", location="*", channel="*", starttime=None, endtime=None, fill_value=0.0, dtype=np.float32, limit=None, instrument_response_json=None, remove_instrument_response=False, response_output="VEL", response_pre_filt=None, response_water_level=60, response_zero_mean=True, response_taper=True, response_taper_fraction=0.05, response_error_behavior="raise", simulate_instrument_response=False, simulation_response_json=None, simulation_response_id=None, simulation_response_selector=None, simulation_paz=None, simulation_output=None, simulation_sensitivity=True, default_location=DEFAULT_LOCATION, ): """ Query waveform segments and merge them into continuous waveforms. """ rows = query_segments( db_file=db_file, network=network, station=station, location=location, channel=channel, starttime=starttime, endtime=endtime, limit=limit, ) merged = merge_segments( rows=rows, starttime=starttime, endtime=endtime, fill_value=fill_value, dtype=dtype, ) if remove_instrument_response or simulate_instrument_response: apply_instrument_processing_to_merged( merged, instrument_response_json=instrument_response_json, remove_instrument_response=remove_instrument_response, response_output=response_output, response_pre_filt=response_pre_filt, response_water_level=response_water_level, response_zero_mean=response_zero_mean, response_taper=response_taper, response_taper_fraction=response_taper_fraction, response_error_behavior=response_error_behavior, simulate_instrument_response=simulate_instrument_response, simulation_response_json=simulation_response_json, simulation_response_id=simulation_response_id, simulation_response_selector=simulation_response_selector, simulation_paz=simulation_paz, simulation_output=simulation_output, simulation_sensitivity=simulation_sensitivity, default_location=default_location, dtype=dtype, ) return merged, rows def save_merged_to_npz(merged, output_npz): """ Save merged waveforms and metadata to NPZ. """ arrays = {} metadata = {} for key, item in merged.items(): safe_key = key.replace(".", "_").replace("-", "_") arrays[safe_key] = item["data"] meta = dict(item) meta.pop("data", None) metadata[safe_key] = meta arrays["metadata_json"] = np.array(json.dumps(metadata, ensure_ascii=False)) np.savez(output_npz, **arrays)