| |
| |
|
|
| import json |
| import argparse |
| from pathlib import Path |
| from collections import defaultdict |
| from obspy import UTCDateTime |
|
|
|
|
| DEFAULT_LOCATION = "--" |
|
|
|
|
| DROP_EVENT_KEYS = { |
| "event_time_index", |
| "nt", |
| "nx", |
| "sampling_rate", |
| "begin_time", |
| "end_time", |
| } |
|
|
| DROP_RECORD_KEYS = { |
| "phase_index", |
| "p_phase_index", |
| "s_phase_index", |
| "phase_picking_channel", |
| "phase_polarity", |
| "phase_remark", |
| "phase_score", |
| "phase_time", |
| "phase_type", |
| "snr", |
| } |
|
|
|
|
| def normalize_location(location, default=DEFAULT_LOCATION): |
| if location is None: |
| return default |
| location = str(location).strip() |
| return location if location else default |
|
|
|
|
| def make_station_id(network, station, location, default=DEFAULT_LOCATION): |
| return f"{str(network or '').strip()}.{str(station or '').strip()}.{normalize_location(location, default)}" |
|
|
|
|
| def parse_utc(value): |
| if not value: |
| return None |
| return UTCDateTime(str(value)) |
|
|
|
|
| def utc_to_group_id(t, level): |
| if level == "year": |
| return f"{t.year:04d}-01-01T00:00:00.000000Z" |
| if level == "day": |
| return f"{t.year:04d}-{t.month:02d}-{t.day:02d}T00:00:00.000000Z" |
| raise ValueError(level) |
|
|
|
|
| def clean_dict(d, drop_keys): |
| return {k: v for k, v in dict(d or {}).items() if k not in drop_keys} |
|
|
|
|
| def phase_from_record(record, phase): |
| block = record.get(phase) |
| if not isinstance(block, dict): |
| return None |
|
|
| if not block.get("time"): |
| return None |
|
|
| return { |
| "phase": phase, |
| "time": block.get("time"), |
| "polarity": block.get("polarity"), |
| "score": block.get("score"), |
| "status": block.get("status"), |
| } |
|
|
|
|
| def convert_record_to_station_pick(record, default_location=DEFAULT_LOCATION): |
| network = record.get("network", "") |
| station = record.get("station", "") |
| location = normalize_location(record.get("location"), default_location) |
| station_id = make_station_id(network, station, location, default_location) |
|
|
| station_metadata = { |
| "station_id": station_id, |
| "network": network, |
| "station": station, |
| "location": location, |
| "latitude": record.get("latitude"), |
| "longitude": record.get("longitude"), |
| "elevation": record.get("elevation_m"), |
| "depth_km": record.get("depth_km"), |
| "local_depth_m": record.get("local_depth_m"), |
| "instrument": record.get("instrument"), |
| "component": record.get("component"), |
| "unit": record.get("unit"), |
| } |
|
|
| picks = [] |
| for phase in ["P", "S"]: |
| p = phase_from_record(record, phase) |
| if p is not None: |
| p.update({ |
| "network": network, |
| "station": station, |
| "location": location, |
| "station_id": station_id, |
| "channel_hint": record.get("component"), |
| "distance_km": record.get("distance_km"), |
| "azimuth": record.get("azimuth"), |
| "back_azimuth": record.get("back_azimuth"), |
| "takeoff_angle": record.get("takeoff_angle"), |
| }) |
| picks.append(p) |
|
|
| record_clean = clean_dict(record, DROP_RECORD_KEYS) |
|
|
| for key in [ |
| "P", "S", |
| "p_phase_time", "p_phase_polarity", "p_phase_score", "p_phase_status", |
| "s_phase_time", "s_phase_polarity", "s_phase_score", "s_phase_status", |
| ]: |
| record_clean.pop(key, None) |
|
|
| record_clean["station_id"] = station_id |
| record_clean["location"] = location |
|
|
| return station_id, station_metadata, picks, record_clean |
|
|
|
|
| def convert_event(event_id, item, default_location=DEFAULT_LOCATION): |
| event = item.get("event", {}) |
| records = item.get("records", []) |
|
|
| event_time = parse_utc(event.get("event_time")) |
| if event_time is None: |
| return None, None, None |
|
|
| event_clean = clean_dict(event, DROP_EVENT_KEYS) |
|
|
| event_obj = { |
| "event_id": event.get("event_id", event_id), |
| "event": event_clean, |
| "preferred_origin": { |
| "time": event.get("event_time"), |
| "latitude": event.get("latitude"), |
| "longitude": event.get("longitude"), |
| "depth_m": event.get("depth_km") * 1000.0 |
| if event.get("depth_km") is not None else None, |
| }, |
| "preferred_magnitude": { |
| "mag": event.get("magnitude"), |
| "magnitude_type": event.get("magnitude_type"), |
| }, |
| "stations": {}, |
| "counts": { |
| "station_count": 0, |
| "pick_count": 0, |
| "record_count": 0, |
| }, |
| } |
|
|
| station_groups = defaultdict(lambda: { |
| "station_id": "", |
| "network": "", |
| "station": "", |
| "location": "", |
| "station_metadata": None, |
| "picks": [], |
| "records": [], |
| }) |
|
|
| pick_count = 0 |
|
|
| for record in records: |
| station_id, station_metadata, picks, record_clean = convert_record_to_station_pick( |
| record, |
| default_location=default_location, |
| ) |
|
|
| sg = station_groups[station_id] |
| sg["station_id"] = station_id |
| sg["network"] = station_metadata["network"] |
| sg["station"] = station_metadata["station"] |
| sg["location"] = station_metadata["location"] |
| sg["station_metadata"] = station_metadata |
| sg["picks"].extend(picks) |
| sg["records"].append(record_clean) |
|
|
| pick_count += len(picks) |
|
|
| event_obj["stations"] = dict(station_groups) |
| event_obj["counts"]["station_count"] = len(station_groups) |
| event_obj["counts"]["pick_count"] = pick_count |
| event_obj["counts"]["record_count"] = len(records) |
|
|
| year_id = utc_to_group_id(event_time, "year") |
| day_id = utc_to_group_id(event_time, "day") |
|
|
| return year_id, day_id, event_obj |
|
|
|
|
| def convert_files(input_files, output_file, default_location=DEFAULT_LOCATION): |
| output = { |
| "format": "seismic_annotation_json_for_continuous_hdf5_v1", |
| "hdf5_hierarchy": "year/day/stations/station_id/waveform/channel/segment", |
| "station_id_format": "network.station.location", |
| "empty_location_value": default_location, |
| "years": {}, |
| "summary": { |
| "event_count": 0, |
| "station_event_count": 0, |
| "pick_count": 0, |
| "record_count": 0, |
| }, |
| } |
|
|
| for input_file in input_files: |
| with open(input_file, "r", encoding="utf-8") as f: |
| data = json.load(f) |
|
|
| for event_id, item in data.get("events", {}).items(): |
| year_id, day_id, event_obj = convert_event( |
| event_id, |
| item, |
| default_location=default_location, |
| ) |
|
|
| if event_obj is None: |
| continue |
|
|
| year_grp = output["years"].setdefault(year_id, { |
| "utc_time": year_id, |
| "days": {}, |
| }) |
|
|
| day_grp = year_grp["days"].setdefault(day_id, { |
| "utc_time": day_id, |
| "events": {}, |
| }) |
|
|
| safe_event_id = event_obj["event_id"].replace("/", "_").replace(":", "_") |
| day_grp["events"][safe_event_id] = event_obj |
|
|
| output["summary"]["event_count"] += 1 |
| output["summary"]["station_event_count"] += event_obj["counts"]["station_count"] |
| output["summary"]["pick_count"] += event_obj["counts"]["pick_count"] |
| output["summary"]["record_count"] += event_obj["counts"]["record_count"] |
|
|
| Path(output_file).parent.mkdir(parents=True, exist_ok=True) |
| with open(output_file, "w", encoding="utf-8") as f: |
| json.dump(output, f, ensure_ascii=False, indent=2) |
|
|
| print(f"[OK] saved: {output_file}") |
| print(f"[OK] events: {output['summary']['event_count']}") |
| print(f"[OK] station-event records: {output['summary']['station_event_count']}") |
| print(f"[OK] picks: {output['summary']['pick_count']}") |
| print(f"[OK] raw records: {output['summary']['record_count']}") |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("inputs", nargs="+") |
| parser.add_argument("-o", "--output", default="annotations_for_continuous_hdf5.json") |
| parser.add_argument("--default_location", default=DEFAULT_LOCATION) |
| args = parser.parse_args() |
|
|
| convert_files( |
| input_files=args.inputs, |
| output_file=args.output, |
| default_location=args.default_location, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |