File size: 24,392 Bytes
a6754c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import h5py
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from obspy import UTCDateTime


DEFAULT_LOCATION = "--"


def parse_time(t):
    return UTCDateTime(str(t))


def decode_attr(value):
    if isinstance(value, bytes):
        return value.decode("utf-8", errors="ignore")
    if isinstance(value, np.bytes_):
        return value.decode("utf-8", errors="ignore")
    return value


def normalize_location(location, default=DEFAULT_LOCATION):
    location = decode_attr(location)
    if location is None:
        return default
    location = str(location).strip()
    return location if location else default


def channel_suffix(channel):
    return str(channel)[-1].upper()


def channel_prefix(channel):
    # 前两位作为 family,例如 BHE/BHN/BHZ -> BH
    ch = str(channel).upper()
    if len(ch) >= 3:
        return ch[:2]
    return ch[:-1]


def component_rank(channel):
    order = {
        "E": 0,
        "1": 0,
        "N": 1,
        "2": 1,
        "Z": 2,
        "3": 2,
    }
    return order.get(channel_suffix(channel), 99)


def is_valid_waveform_family(channels):
    """
    判断一个 channel family 是否可以构成三分量输入。

    支持:
    1. E/N/Z
    2. 1/2/3
    3. only Z,后续复制成三分量
    """
    suffixes = {channel_suffix(ch) for ch in channels}

    if {"E", "N", "Z"}.issubset(suffixes):
        return True

    if {"1", "2", "3"}.issubset(suffixes):
        return True

    if suffixes == {"Z"}:
        return True

    return False


def get_attr(obj, name, default=None):
    if name in obj.attrs:
        return decode_attr(obj.attrs[name])
    return default


def get_float_attr(obj, name, default=np.nan):
    try:
        return float(get_attr(obj, name, default))
    except Exception:
        return float(default)


def get_bool_attr(obj, name, default=False):
    value = get_attr(obj, name, default)

    if isinstance(value, (bool, np.bool_)):
        return bool(value)

    if isinstance(value, (int, np.integer)):
        return bool(value)

    if isinstance(value, str):
        return value.lower() in ["true", "1", "yes"]

    return bool(value)


def fill_segments_to_array(segments, fill_value=0.0, dtype=np.float32):
    if len(segments) == 0:
        return None, None, None, None

    segments = sorted(segments, key=lambda x: x["starttime"])

    sampling_rate = segments[0]["sampling_rate"]
    global_start = min(s["starttime"] for s in segments)
    global_end = max(s["endtime"] for s in segments)

    npts = int(round((global_end - global_start) * sampling_rate)) + 1

    data = np.full(npts, fill_value, dtype=dtype)
    filled = np.zeros(npts, dtype=bool)

    for seg in segments:
        seg_data = seg["data"].astype(dtype, copy=False)

        i0 = int(round((seg["starttime"] - global_start) * sampling_rate))
        i1 = i0 + len(seg_data)

        if i0 < 0:
            seg_data = seg_data[-i0:]
            i0 = 0

        if i1 > npts:
            seg_data = seg_data[: npts - i0]
            i1 = npts

        if i0 >= i1:
            continue

        target = slice(i0, i1)
        mask = ~filled[target]

        data[target][mask] = seg_data[: i1 - i0][mask]
        filled[target][mask] = True

    return data, global_start, global_end, sampling_rate


def get_position_from_segments(segments):
    for seg in segments:
        if seg.get("location_available", False):
            return {
                "longitude": seg.get("longitude", np.nan),
                "latitude": seg.get("latitude", np.nan),
                "elevation": seg.get("elevation", np.nan),
                "location_available": True,
                "location_source": seg.get("location_source", ""),
                "position_match_mode": seg.get("position_match_mode", ""),
                "position_is_fallback": seg.get("position_is_fallback", False),
                "station_position_starttime": seg.get("station_position_starttime", ""),
                "station_position_endtime": seg.get("station_position_endtime", ""),
            }

    return {
        "longitude": np.nan,
        "latitude": np.nan,
        "elevation": np.nan,
        "location_available": False,
        "location_source": "default_nan_no_station_record",
        "position_match_mode": "default_nan_no_station_record",
        "position_is_fallback": False,
        "station_position_starttime": "",
        "station_position_endtime": "",
    }


class HDF5WaveformDataset(Dataset):
    """
    mode:
        single: 每个 channel 一个样本,返回 [T]
        three : 每个 channel family 一个样本,返回 [T, 3]
        multi : 每个 channel family 一个样本,返回 [T, C]
    """

    def __init__(
        self,
        h5_file,
        mode="three",
        fill_value=0.0,
        dtype=np.float32,
        default_location=DEFAULT_LOCATION,
    ):
        assert mode in ["single", "three", "multi"]

        self.h5_file = h5_file
        self.mode = mode
        self.fill_value = fill_value
        self.dtype = dtype
        self.default_location = default_location

        self.index = []
        self._build_index()

    def _build_index(self):
        with h5py.File(self.h5_file, "r") as h5:
            for year_id in sorted(h5.keys()):
                year_grp = h5[year_id]

                for day_id in sorted(year_grp.keys()):
                    day_grp = year_grp[day_id]

                    if "stations" not in day_grp:
                        continue

                    stations_grp = day_grp["stations"]

                    for station_id in sorted(stations_grp.keys()):
                        station_grp = stations_grp[station_id]

                        if "waveform" not in station_grp:
                            continue

                        waveform_grp = station_grp["waveform"]
                        channels = sorted(list(waveform_grp.keys()))

                        if self.mode == "single":
                            for cha in channels:
                                self.index.append(
                                    {
                                        "year_id": year_id,
                                        "day_id": day_id,
                                        "station_id": station_id,
                                        "channel": cha,
                                    }
                                )

                        else:
                            families = {}

                            for cha in channels:
                                prefix = channel_prefix(cha)
                                families.setdefault(prefix, []).append(cha)

                            for prefix, family_channels in families.items():
                                family_channels = sorted(
                                    family_channels,
                                    key=component_rank,
                                )

                                if self.mode == "three":
                                    if not is_valid_waveform_family(family_channels):
                                        continue

                                self.index.append(
                                    {
                                        "year_id": year_id,
                                        "day_id": day_id,
                                        "station_id": station_id,
                                        "channel_family": prefix,
                                        "channels": family_channels,
                                    }
                                )

    def __len__(self):
        return len(self.index)

    def _get_station_group(self, h5, year_id, day_id, station_id):
        return h5[year_id][day_id]["stations"][station_id]

    def _read_position_history(self, station_grp):
        if "position_history" not in station_grp:
            return []

        pos_grp = station_grp["position_history"]
        out = []

        for key in sorted(pos_grp.keys(), key=lambda x: int(x) if str(x).isdigit() else str(x)):
            item = pos_grp[key]

            out.append(
                {
                    "network": get_attr(item, "network", ""),
                    "station": get_attr(item, "station", ""),
                    "location": normalize_location(
                        get_attr(item, "location", self.default_location),
                        self.default_location,
                    ),
                    "longitude": get_float_attr(item, "longitude", np.nan),
                    "latitude": get_float_attr(item, "latitude", np.nan),
                    "elevation": get_float_attr(item, "elevation", np.nan),
                    "starttime": get_attr(item, "starttime", ""),
                    "endtime": get_attr(item, "endtime", ""),
                }
            )

        return out

    def _read_station_attrs(self, station_grp):
        location = normalize_location(
            get_attr(station_grp, "location", self.default_location),
            self.default_location,
        )

        return {
            "station_id": get_attr(station_grp, "station_id", ""),
            "network": get_attr(station_grp, "network", ""),
            "station": get_attr(station_grp, "station", ""),
            "location": location,
            "location_is_default": get_bool_attr(
                station_grp,
                "location_is_default",
                location == self.default_location,
            ),
            "longitude": get_float_attr(station_grp, "longitude", np.nan),
            "latitude": get_float_attr(station_grp, "latitude", np.nan),
            "elevation": get_float_attr(station_grp, "elevation", np.nan),
            "location_available": get_bool_attr(station_grp, "location_available", False),
            "location_source": get_attr(station_grp, "location_source", ""),
            "position_match_mode": get_attr(station_grp, "position_match_mode", ""),
            "position_is_fallback": get_bool_attr(station_grp, "position_is_fallback", False),
            "station_position_starttime": get_attr(station_grp, "station_position_starttime", ""),
            "station_position_endtime": get_attr(station_grp, "station_position_endtime", ""),
            "instrument_time_range_start": get_attr(station_grp, "instrument_time_range_start", ""),
            "instrument_time_range_end": get_attr(station_grp, "instrument_time_range_end", ""),
            "position_history": self._read_position_history(station_grp),
        }

    def _read_channel_attrs(self, channel_grp):
        return {
            "channel": get_attr(channel_grp, "channel", ""),
            "segment_count": int(get_attr(channel_grp, "segment_count", 0)),
            "starttime": get_attr(channel_grp, "starttime", ""),
            "endtime": get_attr(channel_grp, "endtime", ""),
            "longitude": get_float_attr(channel_grp, "longitude", np.nan),
            "latitude": get_float_attr(channel_grp, "latitude", np.nan),
            "elevation": get_float_attr(channel_grp, "elevation", np.nan),
            "location_available": get_bool_attr(channel_grp, "location_available", False),
            "location_source": get_attr(channel_grp, "location_source", ""),
            "position_match_mode": get_attr(channel_grp, "position_match_mode", ""),
            "position_is_fallback": get_bool_attr(channel_grp, "position_is_fallback", False),
            "station_position_starttime": get_attr(channel_grp, "station_position_starttime", ""),
            "station_position_endtime": get_attr(channel_grp, "station_position_endtime", ""),
        }

    def _read_channel_segments(self, h5, year_id, day_id, station_id, channel):
        station_grp = self._get_station_group(h5, year_id, day_id, station_id)
        channel_grp = station_grp["waveform"][channel]

        segments = []

        for ds_key in sorted(channel_grp.keys(), key=lambda x: int(x)):
            ds = channel_grp[ds_key]

            segments.append(
                {
                    "data": ds[()],
                    "segment_index": int(get_attr(ds, "segment_index", ds_key)),
                    "starttime": parse_time(get_attr(ds, "starttime", "")),
                    "endtime": parse_time(get_attr(ds, "endtime", "")),
                    "sampling_rate": float(get_attr(ds, "sampling_rate", np.nan)),
                    "delta": float(get_attr(ds, "delta", np.nan)),
                    "npts": int(get_attr(ds, "npts", ds.shape[0])),
                    "network": get_attr(ds, "network", ""),
                    "station": get_attr(ds, "station", ""),
                    "location": normalize_location(
                        get_attr(ds, "location", self.default_location),
                        self.default_location,
                    ),
                    "channel": get_attr(ds, "channel", channel),
                    "mseed_source_file": get_attr(ds, "mseed_source_file", ""),
                    "dtype": get_attr(ds, "dtype", str(ds.dtype)),
                    "longitude": get_float_attr(ds, "longitude", np.nan),
                    "latitude": get_float_attr(ds, "latitude", np.nan),
                    "elevation": get_float_attr(ds, "elevation", np.nan),
                    "location_available": get_bool_attr(ds, "location_available", False),
                    "location_source": get_attr(ds, "location_source", ""),
                    "station_position_starttime": get_attr(ds, "station_position_starttime", ""),
                    "station_position_endtime": get_attr(ds, "station_position_endtime", ""),
                    "position_match_mode": get_attr(ds, "position_match_mode", ""),
                    "position_is_fallback": get_bool_attr(ds, "position_is_fallback", False),
                }
            )

        channel_info = self._read_channel_attrs(channel_grp)
        return segments, channel_info

    def __getitem__(self, idx):
        item = self.index[idx]

        with h5py.File(self.h5_file, "r") as h5:
            year_id = item["year_id"]
            day_id = item["day_id"]
            station_id = item["station_id"]

            station_grp = self._get_station_group(h5, year_id, day_id, station_id)
            station_info = self._read_station_attrs(station_grp)

            if self.mode == "single":
                return self._getitem_single(h5, item, station_info)

            if self.mode == "three":
                return self._getitem_three(h5, item, station_info)

            if self.mode == "multi":
                return self._getitem_multi(h5, item, station_info)

            raise ValueError(f"Unsupported mode: {self.mode}")

    def _getitem_single(self, h5, item, station_info):
        year_id = item["year_id"]
        day_id = item["day_id"]
        station_id = item["station_id"]
        channel = item["channel"]

        segments, channel_info = self._read_channel_segments(
            h5, year_id, day_id, station_id, channel
        )

        waveform, starttime, endtime, sr = fill_segments_to_array(
            segments,
            fill_value=self.fill_value,
            dtype=self.dtype,
        )

        if waveform is None:
            waveform = np.zeros(0, dtype=self.dtype)

        position_info = get_position_from_segments(segments)
        station_info = dict(station_info)
        station_info.update(position_info)

        return {
            "mode": "single",
            "year_id": year_id,
            "day_id": day_id,
            "station_id": station_id,
            "station_info": station_info,
            "channel_info": channel_info,
            "channel": channel,
            "channels": [channel],
            "waveform": torch.from_numpy(waveform),
            "segments": [
                {k: v for k, v in seg.items() if k != "data"}
                for seg in segments
            ],
            "starttime": str(starttime) if starttime is not None else "",
            "endtime": str(endtime) if endtime is not None else "",
            "sampling_rate": sr,
            "npts": waveform.shape[0],
        }

    def _getitem_three(self, h5, item, station_info):
        year_id = item["year_id"]
        day_id = item["day_id"]
        station_id = item["station_id"]
        channel_family = item["channel_family"]
        candidate_channels = item["channels"]

        selected = {}

        for cha in candidate_channels:
            suf = channel_suffix(cha)

            if suf in ["E", "1"] and 0 not in selected:
                selected[0] = cha
            elif suf in ["N", "2"] and 1 not in selected:
                selected[1] = cha
            elif suf in ["Z", "3"] and 2 not in selected:
                selected[2] = cha

        z_only_replicated = False

        # 只有 Z 的情况:复制为三分量
        if 2 in selected and 0 not in selected and 1 not in selected:
            selected[0] = selected[2]
            selected[1] = selected[2]
            z_only_replicated = True

        arrays = {}
        starts = []
        ends = []
        srs = []
        all_segments = []
        channel_infos = {}

        # 避免 Z-only 情况重复读取同一个 channel 三次
        unique_channels = sorted(set(selected.values()))

        channel_arrays = {}

        for cha in unique_channels:
            segments, channel_info = self._read_channel_segments(
                h5, year_id, day_id, station_id, cha
            )

            all_segments.extend(segments)
            channel_infos[cha] = channel_info

            arr, st, et, sr = fill_segments_to_array(
                segments,
                fill_value=self.fill_value,
                dtype=self.dtype,
            )

            if arr is None:
                continue

            channel_arrays[cha] = arr
            starts.append(st)
            ends.append(et)
            srs.append(sr)

        for comp_idx, cha in selected.items():
            if cha in channel_arrays:
                arrays[comp_idx] = channel_arrays[cha]

        if len(arrays) == 0:
            waveform = np.zeros((0, 3), dtype=self.dtype)
            starttime = None
            endtime = None
            sr = np.nan
        else:
            sr = srs[0]
            starttime = min(starts)
            endtime = max(ends)

            max_len = max(len(a) for a in arrays.values())
            waveform = np.full((max_len, 3), self.fill_value, dtype=self.dtype)

            for comp_idx, arr in arrays.items():
                waveform[: len(arr), comp_idx] = arr

        position_info = get_position_from_segments(all_segments)
        station_info = dict(station_info)
        station_info.update(position_info)

        channels_out = [
            selected.get(0, ""),
            selected.get(1, ""),
            selected.get(2, ""),
        ]

        return {
            "mode": "three",
            "year_id": year_id,
            "day_id": day_id,
            "station_id": station_id,
            "station_info": station_info,
            "channel_family": channel_family,
            "channel_info": channel_infos,
            "channels": channels_out,
            "component_order": "E/N/Z or 1/2/3; Z-only is replicated",
            "z_only_replicated": z_only_replicated,
            "waveform": torch.from_numpy(waveform),
            "segments": [
                {k: v for k, v in seg.items() if k != "data"}
                for seg in all_segments
            ],
            "starttime": str(starttime) if starttime is not None else "",
            "endtime": str(endtime) if endtime is not None else "",
            "sampling_rate": sr,
            "npts": waveform.shape[0],
        }

    def _getitem_multi(self, h5, item, station_info):
        year_id = item["year_id"]
        day_id = item["day_id"]
        station_id = item["station_id"]
        channel_family = item["channel_family"]
        channels = item["channels"]

        arrays = []
        used_channels = []
        starts = []
        ends = []
        srs = []
        all_segments = []
        channel_infos = {}

        for cha in channels:
            segments, channel_info = self._read_channel_segments(
                h5, year_id, day_id, station_id, cha
            )

            all_segments.extend(segments)
            channel_infos[cha] = channel_info

            arr, st, et, sr = fill_segments_to_array(
                segments,
                fill_value=self.fill_value,
                dtype=self.dtype,
            )

            if arr is None:
                continue

            arrays.append(arr)
            used_channels.append(cha)
            starts.append(st)
            ends.append(et)
            srs.append(sr)

        if len(arrays) == 0:
            waveform = np.zeros((0, 0), dtype=self.dtype)
            starttime = None
            endtime = None
            sr = np.nan
        else:
            max_len = max(len(a) for a in arrays)
            waveform = np.full(
                (max_len, len(arrays)),
                self.fill_value,
                dtype=self.dtype,
            )

            for i, arr in enumerate(arrays):
                waveform[: len(arr), i] = arr

            starttime = min(starts)
            endtime = max(ends)
            sr = srs[0]

        position_info = get_position_from_segments(all_segments)
        station_info = dict(station_info)
        station_info.update(position_info)

        return {
            "mode": "multi",
            "year_id": year_id,
            "day_id": day_id,
            "station_id": station_id,
            "station_info": station_info,
            "channel_family": channel_family,
            "channel_info": channel_infos,
            "channels": used_channels,
            "waveform": torch.from_numpy(waveform),
            "segments": [
                {k: v for k, v in seg.items() if k != "data"}
                for seg in all_segments
            ],
            "starttime": str(starttime) if starttime is not None else "",
            "endtime": str(endtime) if endtime is not None else "",
            "sampling_rate": sr,
            "npts": waveform.shape[0],
        }


def waveform_collate_fn(batch):
    return batch


def padded_collate_fn(batch, fill_value=0.0):
    lengths = []
    arrays = []

    max_t = 0
    max_c = 1

    for item in batch:
        x = item["waveform"]

        if x.ndim == 1:
            x = x[:, None]

        t, c = x.shape
        max_t = max(max_t, t)
        max_c = max(max_c, c)

        lengths.append(t)
        arrays.append(x)

    out = torch.full(
        (len(batch), max_t, max_c),
        fill_value=float(fill_value),
        dtype=arrays[0].dtype,
    )

    for i, x in enumerate(arrays):
        t, c = x.shape
        out[i, :t, :c] = x

    meta = []

    for item in batch:
        d = dict(item)
        d.pop("waveform")
        meta.append(d)

    return {
        "waveform": out,
        "lengths": torch.tensor(lengths, dtype=torch.long),
        "meta": meta,
    }


if __name__ == "__main__":
    h5_file = "data/continuous_waveform_usa.h5"

    dataset = HDF5WaveformDataset(
        h5_file=h5_file,
        mode="three",
        fill_value=0.0,
        dtype=np.float32,
        default_location="--",
    )

    loader = DataLoader(
        dataset,
        batch_size=2,
        shuffle=False,
        num_workers=0,
        collate_fn=waveform_collate_fn,
    )

    print("Number of samples:", len(dataset))

    for batch in loader:
        for item in batch:
            print("=" * 80)
            print("station_id:", item["station_id"])
            print("station_info:", item["station_info"])
            print("mode:", item["mode"])
            print("channel_family:", item["channel_family"])
            print("channels:", item["channels"])
            print("z_only_replicated:", item["z_only_replicated"])
            print("starttime:", item["starttime"])
            print("endtime:", item["endtime"])
            print("sampling_rate:", item["sampling_rate"])
            print("waveform shape:", tuple(item["waveform"].shape))
            print("first segment meta:", item["segments"][0] if item["segments"] else None)
        break