File size: 8,010 Bytes
cbe8603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10914e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbe8603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10914e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbe8603
 
10914e4
cbe8603
 
 
 
 
 
 
 
 
 
 
 
10914e4
 
 
 
 
 
 
 
 
 
 
cbe8603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10914e4
 
 
 
 
 
 
 
 
cbe8603
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
python example_query_waveform.py \
  --db data/index/waveform_index.sqlite \
  --network BK \
  --station CMB \
  --starttime 2019-07-01T00:00:00 \
  --endtime 2019-07-01T01:00:00
"""
import argparse
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from utils.waveform_index_api import query_and_merge, save_merged_to_npz


def parse_optional_float(value):
    if value is None:
        return None
    text = str(value).strip().lower()
    if text in {"none", "null", ""}:
        return None
    out = float(value)
    return None if out < 0 else out


def build_simulation_selector(args):
    fields = {
        "network": args.simulation_network,
        "station": args.simulation_station,
        "location": args.simulation_location,
        "channel": args.simulation_channel,
        "time": args.simulation_time,
    }
    selector = {key: value for key, value in fields.items() if value not in (None, "")}
    return selector or None


def main():
    parser = argparse.ArgumentParser(
        description="Example API client for querying and merging waveform data."
    )

    parser.add_argument(
        "--db",
        required=True,
        help="SQLite waveform index database, e.g. data/index/waveform_index.sqlite",
    )

    parser.add_argument(
        "--network",
        default="*",
        help='Network code or wildcard, e.g. "BK", "C*", "*".',
    )

    parser.add_argument(
        "--station",
        default="*",
        help='Station code or wildcard, e.g. "BDM", "BD*", "*".',
    )

    parser.add_argument(
        "--location",
        default="*",
        help='Location code or wildcard, e.g. "00", "--", "*".',
    )

    parser.add_argument(
        "--channel",
        default="*",
        help='Channel code or wildcard, e.g. "BHE", "BH*", "*Z", "*".',
    )

    parser.add_argument(
        "--starttime",
        required=True,
        help="Query start time, e.g. 2019-07-01T00:00:00",
    )

    parser.add_argument(
        "--endtime",
        required=True,
        help="Query end time, e.g. 2019-07-01T01:00:00",
    )

    parser.add_argument(
        "--fill_value",
        type=float,
        default=0.0,
        help="Fill value for gaps.",
    )

    parser.add_argument(
        "--limit",
        type=int,
        default=None,
        help="Optional limit for matched segments.",
    )

    parser.add_argument(
        "--output_npz",
        default=None,
        help="Optional output NPZ file.",
    )

    parser.add_argument(
        "--show_segments",
        action="store_true",
        help="Print segment details.",
    )
    parser.add_argument(
        "--response_json",
        default="data/response/instrument_responses.json",
        help="Instrument-response JSON used by --remove_response or --simulate_response.",
    )
    parser.add_argument(
        "--remove_response",
        action="store_true",
        help="Remove the native instrument response with ObsPy before returning arrays.",
    )
    parser.add_argument(
        "--response_output",
        default="VEL",
        help="Physical output unit for response removal: DISP, VEL, or ACC.",
    )
    parser.add_argument(
        "--response_pre_filt",
        nargs=4,
        type=float,
        default=None,
        metavar=("F1", "F2", "F3", "F4"),
        help="Four-corner frequency pre-filter passed to ObsPy remove_response.",
    )
    parser.add_argument(
        "--response_water_level",
        default="60",
        help='ObsPy water level. Use "none" or a negative value to pass None.',
    )
    parser.add_argument(
        "--response_error_behavior",
        choices=("raise", "warn", "skip"),
        default="raise",
        help="How to handle response-processing failures.",
    )
    parser.add_argument(
        "--simulate_response",
        action="store_true",
        help="Simulate a target instrument response after optional native-response removal.",
    )
    parser.add_argument(
        "--simulation_response_json",
        default=None,
        help="Response JSON containing the target response; defaults to --response_json.",
    )
    parser.add_argument(
        "--simulation_response_id",
        default=None,
        help="Exact target response_id to simulate.",
    )
    parser.add_argument("--simulation_network", default=None)
    parser.add_argument("--simulation_station", default=None)
    parser.add_argument("--simulation_location", default=None)
    parser.add_argument("--simulation_channel", default=None)
    parser.add_argument(
        "--simulation_time",
        default=None,
        help="Time used with station-channel target-response selection.",
    )
    parser.add_argument(
        "--simulation_output",
        default=None,
        help="Physical unit used when evaluating the target response; defaults to --response_output.",
    )

    args = parser.parse_args()
    simulation_selector = build_simulation_selector(args)

    merged, rows = query_and_merge(
        db_file=args.db,
        network=args.network,
        station=args.station,
        location=args.location,
        channel=args.channel,
        starttime=args.starttime,
        endtime=args.endtime,
        fill_value=args.fill_value,
        dtype=np.float32,
        limit=args.limit,
        instrument_response_json=args.response_json,
        remove_instrument_response=args.remove_response,
        response_output=args.response_output,
        response_pre_filt=tuple(args.response_pre_filt) if args.response_pre_filt else None,
        response_water_level=parse_optional_float(args.response_water_level),
        response_error_behavior=args.response_error_behavior,
        simulate_instrument_response=args.simulate_response,
        simulation_response_json=args.simulation_response_json,
        simulation_response_id=args.simulation_response_id,
        simulation_response_selector=simulation_selector,
        simulation_output=args.simulation_output,
    )

    print("=" * 80)
    print("Query")
    print("=" * 80)
    print(f"network   : {args.network}")
    print(f"station   : {args.station}")
    print(f"location  : {args.location}")
    print(f"channel   : {args.channel}")
    print(f"starttime : {args.starttime}")
    print(f"endtime   : {args.endtime}")

    print()
    print("=" * 80)
    print("Matched segments")
    print("=" * 80)
    print(f"Segment count: {len(rows)}")

    if args.show_segments:
        for row in rows:
            print(
                f"{row['network']}.{row['station']}.{row['location']} "
                f"{row['channel']} "
                f"{row['starttime']} -> {row['endtime']} "
                f"sr={row['sampling_rate']} "
                f"npts={row['npts']} "
                f"path={row['dataset_path']} "
                f"h5={row['h5_file']}"
            )

    print()
    print("=" * 80)
    print("Merged waveforms")
    print("=" * 80)

    if len(merged) == 0:
        print("No waveform found.")
        return

    for key, item in merged.items():
        print(
            f"{key}: "
            f"shape={item['data'].shape}, "
            f"sr={item['sampling_rate']}, "
            f"filled_ratio={item['filled_ratio']:.4f}, "
            f"segments={len(item['segments'])}"
        )
        if "instrument_processing" in item:
            proc = item["instrument_processing"]
            print(
                "  instrument_processing: "
                f"processed={proc.get('processed')} "
                f"response_id={proc.get('response_id', '')} "
                f"simulation_response_id={proc.get('simulation_response_id', '')} "
                f"error={proc.get('error', '')}"
            )

    if args.output_npz:
        save_merged_to_npz(merged, args.output_npz)
        print()
        print(f"[OK] Saved merged waveform NPZ: {args.output_npz}")


if __name__ == "__main__":
    main()