zhuwq0 commited on
Commit
07ffa4b
1 Parent(s): ad02bf4
Files changed (2) hide show
  1. data/1990.h5 +3 -0
  2. quakeflow_demo.py +214 -0
data/1990.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7fd8404fa0d8a6939c0daa76ccaed24e28ccf649eee8364c50a13c1689bb658f
3
+ size 59532944
quakeflow_demo.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ import datasets
4
+ import fsspec
5
+ import h5py
6
+ import numpy as np
7
+ import torch
8
+
9
+ _CITATION = """\
10
+ @InProceedings{huggingface:dataset,
11
+ title = {NCEDC dataset for QuakeFlow},
12
+ author={Zhu et al.},
13
+ year={2023}
14
+ }
15
+ """
16
+
17
+ _DESCRIPTION = """\
18
+ A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format.
19
+ """
20
+
21
+ _HOMEPAGE = ""
22
+
23
+ _LICENSE = ""
24
+
25
+ _REPO = "https://huggingface.co/datasets/AI4EPS/quakeflow_nc/resolve/main/data"
26
+ _FILES = ["1990.h5"]
27
+ _URLS = {
28
+ "station": [f"{_REPO}/{x}" for x in _FILES],
29
+ "event": [f"{_REPO}/{x}" for x in _FILES],
30
+ "station_train": [f"{_REPO}/{x}" for x in _FILES[:-1]],
31
+ "event_train": [f"{_REPO}/{x}" for x in _FILES[:-1]],
32
+ "station_test": [f"{_REPO}/{x}" for x in _FILES[-1:]],
33
+ "event_test": [f"{_REPO}/{x}" for x in _FILES[-1:]],
34
+ }
35
+
36
+
37
+ class BatchBuilderConfig(datasets.BuilderConfig):
38
+ """
39
+ yield a batch of event-based sample, so the number of sample stations can vary among batches
40
+ Batch Config for QuakeFlow_NC
41
+ :param batch_size: number of samples in a batch
42
+ :param num_stations_list: possible number of stations in a batch
43
+ """
44
+
45
+ def __init__(self, batch_size: int, num_stations_list: List, **kwargs):
46
+ super().__init__(**kwargs)
47
+ self.batch_size = batch_size
48
+ self.num_stations_list = num_stations_list
49
+
50
+
51
+ class QuakeFlow_NC(datasets.GeneratorBasedBuilder):
52
+ """QuakeFlow_NC: A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format."""
53
+
54
+ VERSION = datasets.Version("1.1.0")
55
+
56
+ degree2km = 111.32
57
+ nt = 8192
58
+ feature_nt = 512
59
+ feature_scale = int(nt / feature_nt)
60
+ sampling_rate = 100.0
61
+
62
+ BUILDER_CONFIGS = [
63
+ datasets.BuilderConfig(
64
+ name="station", version=VERSION, description="yield station-based samples one by one of whole dataset"
65
+ ),
66
+ datasets.BuilderConfig(
67
+ name="event", version=VERSION, description="yield event-based samples one by one of whole dataset"
68
+ ),
69
+ datasets.BuilderConfig(
70
+ name="station_train",
71
+ version=VERSION,
72
+ description="yield station-based samples one by one of training dataset",
73
+ ),
74
+ datasets.BuilderConfig(
75
+ name="event_train", version=VERSION, description="yield event-based samples one by one of training dataset"
76
+ ),
77
+ datasets.BuilderConfig(
78
+ name="station_test", version=VERSION, description="yield station-based samples one by one of test dataset"
79
+ ),
80
+ datasets.BuilderConfig(
81
+ name="event_test", version=VERSION, description="yield event-based samples one by one of test dataset"
82
+ ),
83
+ ]
84
+
85
+ DEFAULT_CONFIG_NAME = "station_test"
86
+
87
+ def _info(self):
88
+ if (
89
+ (self.config.name == "station")
90
+ or (self.config.name == "station_train")
91
+ or (self.config.name == "station_test")
92
+ ):
93
+ features = datasets.Features(
94
+ {
95
+ "data": datasets.Array2D(shape=(3, self.nt), dtype="float32"),
96
+ }
97
+ )
98
+
99
+ elif (self.config.name == "event") or (self.config.name == "event_train") or (self.config.name == "event_test"):
100
+ features = datasets.Features(
101
+ {
102
+ "data": datasets.Array3D(shape=(None, 3, self.nt), dtype="float32"),
103
+ }
104
+ )
105
+
106
+ return datasets.DatasetInfo(
107
+ description=_DESCRIPTION,
108
+ features=features,
109
+ homepage=_HOMEPAGE,
110
+ license=_LICENSE,
111
+ citation=_CITATION,
112
+ )
113
+
114
+ def _split_generators(self, dl_manager):
115
+ urls = _URLS[self.config.name]
116
+ files = dl_manager.download_and_extract(urls)
117
+ print(files)
118
+
119
+ if self.config.name == "station" or self.config.name == "event":
120
+ return [
121
+ datasets.SplitGenerator(
122
+ name=datasets.Split.TRAIN,
123
+ gen_kwargs={
124
+ "filepath": files[:-1],
125
+ "split": "train",
126
+ },
127
+ ),
128
+ datasets.SplitGenerator(
129
+ name=datasets.Split.TEST,
130
+ gen_kwargs={"filepath": files[-1:], "split": "test"},
131
+ ),
132
+ ]
133
+ elif self.config.name == "station_train" or self.config.name == "event_train":
134
+ return [
135
+ datasets.SplitGenerator(
136
+ name=datasets.Split.TRAIN,
137
+ gen_kwargs={
138
+ "filepath": files,
139
+ "split": "train",
140
+ },
141
+ ),
142
+ ]
143
+ elif self.config.name == "station_test" or self.config.name == "event_test":
144
+ return [
145
+ datasets.SplitGenerator(
146
+ name=datasets.Split.TEST,
147
+ gen_kwargs={"filepath": files, "split": "test"},
148
+ ),
149
+ ]
150
+ else:
151
+ raise ValueError("config.name is not in BUILDER_CONFIGS")
152
+
153
+ def _generate_examples(self, filepath, split):
154
+ for file in filepath:
155
+ with fsspec.open(file, "rb") as fs:
156
+ with h5py.File(fs, "r") as fp:
157
+ event_ids = list(fp.keys())
158
+ for event_id in event_ids:
159
+ event = fp[event_id]
160
+ station_ids = list(event.keys())
161
+ if (
162
+ (self.config.name == "station")
163
+ or (self.config.name == "station_train")
164
+ or (self.config.name == "station_test")
165
+ ):
166
+ waveforms = np.zeros([3, self.nt], dtype="float32")
167
+ phase_pick = np.zeros_like(waveforms)
168
+ station_attrs = event.attrs
169
+ event_location = [
170
+ station_attrs["longitude"],
171
+ station_attrs["latitude"],
172
+ station_attrs["depth_km"],
173
+ station_attrs["event_time_index"],
174
+ ]
175
+
176
+ for i, sta_id in enumerate(station_ids):
177
+ waveforms[:, : self.nt] = event[sta_id][:, : self.nt]
178
+ station_attrs = event[sta_id].attrs
179
+
180
+ yield f"{event_id}/{sta_id}", {"data": torch.from_numpy(waveforms).float()}
181
+
182
+ elif (
183
+ (self.config.name == "event")
184
+ or (self.config.name == "event_train")
185
+ or (self.config.name == "event_test")
186
+ ):
187
+ event_attrs = event.attrs
188
+
189
+ is_sick = False
190
+ for sta_id in station_ids:
191
+ station_attrs = event[sta_id].attrs
192
+ if (
193
+ station_attrs["phase_index"][station_attrs["phase_type"] == "P"]
194
+ == station_attrs["phase_index"][station_attrs["phase_type"] == "S"]
195
+ ):
196
+ is_sick = True
197
+ break
198
+ if is_sick:
199
+ continue
200
+
201
+ waveforms = np.zeros([len(station_ids), 3, self.nt], dtype="float32")
202
+
203
+ for i, sta_id in enumerate(station_ids):
204
+ waveforms[i, :, :] = event[sta_id][:, : self.nt]
205
+ station_attrs = event[sta_id].attrs
206
+ p_picks = station_attrs["phase_index"][station_attrs["phase_type"] == "P"]
207
+ s_picks = station_attrs["phase_index"][station_attrs["phase_type"] == "S"]
208
+
209
+ std = np.std(waveforms, axis=1, keepdims=True)
210
+ std[std == 0] = 1.0
211
+ waveforms = (waveforms - np.mean(waveforms, axis=1, keepdims=True)) / std
212
+ waveforms = waveforms.astype(np.float32)
213
+
214
+ yield event_id, {"data": torch.from_numpy(waveforms).float()}