File size: 23,490 Bytes
d2dce16
 
 
a419e59
d2dce16
a419e59
d2dce16
 
 
 
a419e59
 
 
 
 
 
 
 
 
 
 
 
d2dce16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a419e59
 
 
 
d2dce16
 
a419e59
 
d2dce16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a419e59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2dce16
 
 
 
 
 
 
 
 
 
 
a419e59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2dce16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a419e59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2dce16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a419e59
d2dce16
a419e59
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
#!/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)