cangyeone commited on
Commit
48f4563
·
verified ·
1 Parent(s): 2a8a916

Upload scripts/example_dataloader.py

Browse files
Files changed (1) hide show
  1. scripts/example_dataloader.py +109 -0
scripts/example_dataloader.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Minimal HDF5WaveformDataset usage example.
4
+
5
+ Run:
6
+ python example_dataloader.py --h5_input path/to/data.h5
7
+ """
8
+
9
+ import argparse
10
+ import numpy as np
11
+ import sys
12
+ from pathlib import Path
13
+ from torch.utils.data import DataLoader
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
16
+
17
+ from utils.hdf5_waveform_dataset import HDF5WaveformDataset, waveform_collate_fn
18
+
19
+
20
+ def main():
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument("--h5_input", default="data/hdf5/continuous_waveform_usa_20190701.h5",
23
+ help="HDF5 file, directory, or glob pattern")
24
+ parser.add_argument("--n_samples", type=int, default=3,
25
+ help="Number of samples to print")
26
+ parser.add_argument("--response_json", default="data/response/instrument_responses.json",
27
+ help="Instrument-response JSON used with --remove_response")
28
+ parser.add_argument("--remove_response", action="store_true",
29
+ help="Remove the native instrument response before resampling")
30
+ parser.add_argument("--response_output", default="VEL",
31
+ help="Physical output unit for response removal: DISP, VEL, or ACC")
32
+ parser.add_argument("--response_pre_filt", nargs=4, type=float, default=None,
33
+ metavar=("F1", "F2", "F3", "F4"),
34
+ help="Four-corner pre-filter passed to ObsPy remove_response")
35
+ parser.add_argument("--response_water_level", type=float, default=60.0,
36
+ help="ObsPy water level; use a negative value to pass None")
37
+ args = parser.parse_args()
38
+ water_level = None if args.response_water_level < 0 else args.response_water_level
39
+
40
+ # ── 1. Build dataset ───────────────────────────────────────────────────
41
+ dataset = HDF5WaveformDataset(
42
+ h5_file=args.h5_input,
43
+ mode="three", # returns [T, 3] waveform per station-day
44
+ allowed_families=("HH", "BH", "EH", "HN"),
45
+ allowed_z_only_channels=("EHZ",),
46
+ allow_z_only=True,
47
+ replicate_z_only=True, # Z-only → [Z, Z, Z]
48
+ target_sampling_rate=100.0, # resample everything to 100 Hz
49
+ instrument_response_json=args.response_json if args.remove_response else None,
50
+ remove_instrument_response=args.remove_response,
51
+ response_output=args.response_output,
52
+ response_pre_filt=tuple(args.response_pre_filt) if args.response_pre_filt else None,
53
+ response_water_level=water_level,
54
+ )
55
+
56
+ print(f"HDF5 files : {len(dataset.h5_files)}")
57
+ print(f"Total samples: {len(dataset)}")
58
+ print()
59
+
60
+ # ── 2. Build DataLoader ────────────────────────────────────────────────
61
+ loader = DataLoader(
62
+ dataset,
63
+ batch_size=1,
64
+ shuffle=False,
65
+ num_workers=0, # 0 = single-process, safest for h5py
66
+ collate_fn=waveform_collate_fn,
67
+ )
68
+
69
+ # ── 3. Iterate and print ───────────────────────────────────────────────
70
+ for i, batch in enumerate(loader):
71
+ if i >= args.n_samples:
72
+ break
73
+
74
+ item = batch[0] # batch_size=1, so one item per batch
75
+
76
+ w = item["waveform"] # torch.Tensor [T, 3]
77
+ sr = item["sampling_rate"]
78
+ duration_sec = w.shape[0] / sr if sr and sr > 0 else float("nan")
79
+
80
+ print(f"── Sample {i + 1} ──────────────────────────────────────────")
81
+ print(f" station_id : {item['station_id']}")
82
+ print(f" network : {item['station_info'].get('network', '')}."
83
+ f"{item['station_info'].get('station', '')}")
84
+ print(f" channels : {item['channels']}")
85
+ print(f" starttime : {item['starttime']}")
86
+ print(f" sampling_rate : {sr} Hz")
87
+ print(f" waveform shape: {tuple(w.shape)} "
88
+ f"({duration_sec:.1f} s × 3 components)")
89
+ print(f" waveform dtype: {w.dtype}")
90
+ print(f" Z-only : {item.get('is_z_only', False)}")
91
+ if args.remove_response:
92
+ print(f" response : {item.get('instrument_processing', {})}")
93
+ print(f" location : "
94
+ f"lon={item['station_info'].get('longitude', float('nan')):.4f} "
95
+ f"lat={item['station_info'].get('latitude', float('nan')):.4f}")
96
+ # Quick per-channel stats
97
+ for c, name in enumerate(["E/1", "N/2", "Z/3"]):
98
+ ch = w[:, c].numpy()
99
+ print(f" ch[{name}] "
100
+ f"min={float(np.min(ch)):+.3e} "
101
+ f"max={float(np.max(ch)):+.3e} "
102
+ f"std={float(np.std(ch)):.3e}")
103
+ print()
104
+
105
+ dataset.close()
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()