SeismicX-Cont / scripts /response_json_to_stationxml.py
cangyeone's picture
Sync canonical release scripts and config
9b0709d verified
Raw
History Blame Contribute Delete
6 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Convert SeismicX-Cont instrument-response JSON to StationXML.
The response JSON is produced by scripts/download_instrument_responses.py and
stores one response epoch per network/station/location/channel. This converter
rebuilds ObsPy Inventory objects and writes standard StationXML.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from obspy.core.inventory import Inventory, Network, Site, Station
from utils.hdf5_waveform_dataset import (
finite_float,
inventory_from_response_record,
response_from_json_record,
utc_or_none,
)
def matches(value, pattern):
if pattern in (None, "", "*"):
return True
return str(value or "") == str(pattern)
def iter_response_records(path, args):
with Path(path).open("r", encoding="utf-8") as f:
obj = json.load(f)
records = obj.get("responses", [])
if not isinstance(records, list):
raise ValueError(f"{path} does not contain a list at key 'responses'")
n_seen = 0
for record in records:
if not matches(record.get("network"), args.network):
continue
if not matches(record.get("station"), args.station):
continue
if not matches(record.get("location"), args.location):
continue
if not matches(record.get("channel"), args.channel):
continue
yield record
n_seen += 1
if args.limit is not None and n_seen >= args.limit:
break
def merge_record_inventory(target, record):
response = response_from_json_record(record)
one = inventory_from_response_record(record, response)
one_network = one.networks[0]
one_station = one_network.stations[0]
one_channel = one_station.channels[0]
network = target.get(one_network.code)
if network is None:
network = Network(code=one_network.code, stations=[])
target[one_network.code] = network
station = None
for item in network.stations:
if item.code == one_station.code:
station = item
break
if station is None:
station = Station(
code=one_station.code,
latitude=finite_float(record.get("latitude", 0.0), 0.0),
longitude=finite_float(record.get("longitude", 0.0), 0.0),
elevation=finite_float(record.get("elevation_m", 0.0), 0.0),
site=Site(name=str(record.get("station", ""))),
channels=[],
start_date=utc_or_none(record.get("epoch_start")),
end_date=utc_or_none(record.get("epoch_end")),
)
network.stations.append(station)
station.channels.append(one_channel)
def convert(args):
networks = {}
n_records = 0
n_failed = 0
for record in iter_response_records(args.input_json, args):
try:
merge_record_inventory(networks, record)
n_records += 1
except Exception as exc:
n_failed += 1
if not args.skip_bad:
response_id = record.get("response_id", "<unknown>")
raise RuntimeError(f"failed to convert response {response_id}: {exc}") from exc
print(
f"[WARN] skipped bad response {record.get('response_id', '<unknown>')}: {exc}",
file=sys.stderr,
)
inventory = Inventory(
networks=sorted(networks.values(), key=lambda item: item.code),
source=args.source,
sender=args.sender,
)
for network in inventory.networks:
network.stations.sort(key=lambda item: item.code)
for station in network.stations:
station.channels.sort(
key=lambda ch: (
ch.location_code or "",
ch.code or "",
str(ch.start_date or ""),
str(ch.end_date or ""),
)
)
args.output_xml.parent.mkdir(parents=True, exist_ok=True)
inventory.write(str(args.output_xml), format="STATIONXML", validate=args.validate)
print(f"[OK] wrote {args.output_xml}")
print(f"[OK] response records converted: {n_records}")
print(f"[OK] skipped records: {n_failed}")
print(f"[OK] networks: {len(inventory.networks)}")
print(f"[OK] stations: {sum(len(net.stations) for net in inventory.networks)}")
print(
"[OK] channels: "
f"{sum(len(sta.channels) for net in inventory.networks for sta in net.stations)}"
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--input-json",
type=Path,
default=Path("data/response/instrument_responses.json"),
help="Input SeismicX-Cont instrument-response JSON.",
)
parser.add_argument(
"--output-xml",
type=Path,
default=Path("data/response/instrument_responses.stationxml"),
help="Output StationXML path.",
)
parser.add_argument("--network", default="*", help="Optional exact network filter.")
parser.add_argument("--station", default="*", help="Optional exact station filter.")
parser.add_argument("--location", default="*", help="Optional exact location filter.")
parser.add_argument("--channel", default="*", help="Optional exact channel filter.")
parser.add_argument("--limit", type=int, default=None, help="Optional max records to convert.")
parser.add_argument("--source", default="SeismicX-Cont response JSON")
parser.add_argument("--sender", default="SeismicX-Cont")
parser.add_argument("--skip-bad", action="store_true", help="Skip records that fail conversion.")
parser.add_argument(
"--validate",
action="store_true",
help="Ask ObsPy/lxml to validate StationXML while writing.",
)
args = parser.parse_args()
convert(args)
if __name__ == "__main__":
main()