Datasets:

DOI:
License:
zhuwq0 commited on
Commit
f04c17e
·
0 Parent(s):

add scripts

Browse files
Files changed (5) hide show
  1. example.py +41 -0
  2. merge_hdf5.py +66 -0
  3. quakeflow_sc.py +346 -0
  4. split_large_files.py +37 -0
  5. upload.py +11 -0
example.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import numpy as np
3
+ from datasets import load_dataset
4
+ from torch.utils.data import DataLoader
5
+
6
+ # quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", name="station_test", split="test")
7
+ quakeflow_nc = load_dataset(
8
+ "./quakeflow_sc.py",
9
+ name="station_test",
10
+ # name="event_test",
11
+ split="test",
12
+ download_mode="force_redownload",
13
+ )
14
+
15
+ # print the first sample of the iterable dataset
16
+ for example in quakeflow_nc:
17
+ print("\nIterable test\n")
18
+ print(example.keys())
19
+ for key in example.keys():
20
+ if key == "data":
21
+ print(key, np.array(example[key]).shape)
22
+ else:
23
+ print(key, example[key])
24
+ break
25
+
26
+ # %%
27
+ quakeflow_nc = quakeflow_nc.with_format("torch")
28
+ dataloader = DataLoader(quakeflow_nc, batch_size=8, num_workers=0, collate_fn=lambda x: x)
29
+
30
+ for batch in dataloader:
31
+ print("\nDataloader test\n")
32
+ print(f"Batch size: {len(batch)}")
33
+ print(batch[0].keys())
34
+ for key in batch[0].keys():
35
+ if key == "data":
36
+ print(key, np.array(batch[0][key]).shape)
37
+ else:
38
+ print(key, batch[0][key])
39
+ break
40
+
41
+ # %%
merge_hdf5.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import os
3
+
4
+ import h5py
5
+ import matplotlib.pyplot as plt
6
+ from tqdm import tqdm
7
+
8
+ # %%
9
+ h5_dir = "waveform_h5"
10
+ h5_out = "waveform.h5"
11
+ h5_train = "waveform_train.h5"
12
+ h5_test = "waveform_test.h5"
13
+
14
+ # # %%
15
+ # h5_dir = "waveform_h5"
16
+ # h5_out = "waveform.h5"
17
+ # h5_train = "waveform_train.h5"
18
+ # h5_test = "waveform_test.h5"
19
+
20
+ h5_files = sorted(os.listdir(h5_dir))
21
+ #h5_files = [x for x in h5_files if (x not in ["2019.h5", "2020.h5"])]
22
+ train_files = h5_files[:-1]
23
+ test_files = h5_files[-1:]
24
+ # train_files = h5_files
25
+ # train_files = [x for x in train_files if (x != "2014.h5") and (x not in [])]
26
+ # test_files = []
27
+ print(f"train files: {train_files}")
28
+ print(f"test files: {test_files}")
29
+
30
+ # %%
31
+ with h5py.File(h5_out, "w") as fp:
32
+ # external linked file
33
+ for h5_file in h5_files:
34
+ with h5py.File(os.path.join(h5_dir, h5_file), "r") as f:
35
+ for event in tqdm(f.keys(), desc=h5_file, total=len(f.keys())):
36
+ if event not in fp:
37
+ fp[event] = h5py.ExternalLink(os.path.join(h5_dir, h5_file), event)
38
+ else:
39
+ print(f"{event} already exists")
40
+ continue
41
+
42
+ # %%
43
+ with h5py.File(h5_train, "w") as fp:
44
+ # external linked file
45
+ for h5_file in train_files:
46
+ with h5py.File(os.path.join(h5_dir, h5_file), "r") as f:
47
+ for event in tqdm(f.keys(), desc=h5_file, total=len(f.keys())):
48
+ if event not in fp:
49
+ fp[event] = h5py.ExternalLink(os.path.join(h5_dir, h5_file), event)
50
+ else:
51
+ print(f"{event} already exists")
52
+ continue
53
+
54
+ # %%
55
+ with h5py.File(h5_test, "w") as fp:
56
+ # external linked file
57
+ for h5_file in test_files:
58
+ with h5py.File(os.path.join(h5_dir, h5_file), "r") as f:
59
+ for event in tqdm(f.keys(), desc=h5_file, total=len(f.keys())):
60
+ if event not in fp:
61
+ fp[event] = h5py.ExternalLink(os.path.join(h5_dir, h5_file), event)
62
+ else:
63
+ print(f"{event} already exists")
64
+ continue
65
+
66
+ # %%
quakeflow_sc.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # TODO: Address all TODOs and remove all explanatory comments
16
+ # Lint as: python3
17
+ """QuakeFlow_SC: A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format."""
18
+
19
+
20
+ from typing import Dict, List, Optional, Tuple, Union
21
+
22
+ import datasets
23
+ import fsspec
24
+ import h5py
25
+ import numpy as np
26
+ import torch
27
+
28
+ # TODO: Add BibTeX citation
29
+ # Find for instance the citation on arxiv or on the dataset repo/website
30
+ _CITATION = """\
31
+ @InProceedings{huggingface:dataset,
32
+ title = {SCEDC dataset for QuakeFlow},
33
+ author={Zhu et al.},
34
+ year={2023}
35
+ }
36
+ """
37
+
38
+ # TODO: Add description of the dataset here
39
+ # You can copy an official description
40
+ _DESCRIPTION = """\
41
+ A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format.
42
+ """
43
+
44
+ # TODO: Add a link to an official homepage for the dataset here
45
+ _HOMEPAGE = ""
46
+
47
+ # TODO: Add the licence for the dataset here if you can find it
48
+ _LICENSE = ""
49
+
50
+ # TODO: Add link to the official dataset URLs here
51
+ # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
52
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
53
+ _REPO = "https://huggingface.co/datasets/AI4EPS/quakeflow_sc/resolve/main/waveform_h5"
54
+ _FILES = [
55
+ "1999.h5",
56
+ "2000.h5",
57
+ "2001.h5",
58
+ "2002.h5",
59
+ "2003.h5",
60
+ "2004.h5",
61
+ "2005.h5",
62
+ "2006.h5",
63
+ "2007.h5",
64
+ "2008.h5",
65
+ "2009.h5",
66
+ "2010.h5",
67
+ "2011.h5",
68
+ "2012.h5",
69
+ "2013.h5",
70
+ "2014.h5",
71
+ "2015.h5",
72
+ "2016.h5",
73
+ "2017.h5",
74
+ "2018.h5",
75
+ "2019_0.h5",
76
+ "2019_1.h5",
77
+ "2019_2.h5",
78
+ "2020_0.h5",
79
+ "2020_1.h5",
80
+ "2021.h5",
81
+ "2022.h5",
82
+ "2023.h5",
83
+ ]
84
+ _URLS = {
85
+ "station": [f"{_REPO}/{x}" for x in _FILES],
86
+ "event": [f"{_REPO}/{x}" for x in _FILES],
87
+ "station_train": [f"{_REPO}/{x}" for x in _FILES[:-1]],
88
+ "event_train": [f"{_REPO}/{x}" for x in _FILES[:-1]],
89
+ "station_test": [f"{_REPO}/{x}" for x in _FILES[-1:]],
90
+ "event_test": [f"{_REPO}/{x}" for x in _FILES[-1:]],
91
+ }
92
+
93
+
94
+ class BatchBuilderConfig(datasets.BuilderConfig):
95
+ """
96
+ yield a batch of event-based sample, so the number of sample stations can vary among batches
97
+ Batch Config for QuakeFlow_SC
98
+ """
99
+
100
+ def __init__(self, **kwargs):
101
+ super().__init__(**kwargs)
102
+
103
+
104
+ # TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
105
+ class QuakeFlow_SC(datasets.GeneratorBasedBuilder):
106
+ """QuakeFlow_SC: A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format."""
107
+
108
+ VERSION = datasets.Version("1.1.0")
109
+
110
+ nt = 8192
111
+
112
+ # This is an example of a dataset with multiple configurations.
113
+ # If you don't want/need to define several sub-sets in your dataset,
114
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
115
+
116
+ # If you need to make complex sub-parts in the datasets with configurable options
117
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
118
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
119
+
120
+ # You will be able to load one or the other configurations in the following list with
121
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
122
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
123
+
124
+ # default config, you can change batch_size and num_stations_list when use `datasets.load_dataset`
125
+ BUILDER_CONFIGS = [
126
+ datasets.BuilderConfig(
127
+ name="station", version=VERSION, description="yield station-based samples one by one of whole dataset"
128
+ ),
129
+ datasets.BuilderConfig(
130
+ name="event", version=VERSION, description="yield event-based samples one by one of whole dataset"
131
+ ),
132
+ datasets.BuilderConfig(
133
+ name="station_train",
134
+ version=VERSION,
135
+ description="yield station-based samples one by one of training dataset",
136
+ ),
137
+ datasets.BuilderConfig(
138
+ name="event_train", version=VERSION, description="yield event-based samples one by one of training dataset"
139
+ ),
140
+ datasets.BuilderConfig(
141
+ name="station_test", version=VERSION, description="yield station-based samples one by one of test dataset"
142
+ ),
143
+ datasets.BuilderConfig(
144
+ name="event_test", version=VERSION, description="yield event-based samples one by one of test dataset"
145
+ ),
146
+ ]
147
+
148
+ DEFAULT_CONFIG_NAME = (
149
+ "station_test" # It's not mandatory to have a default configuration. Just use one if it make sense.
150
+ )
151
+
152
+ def _info(self):
153
+ # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
154
+ if (
155
+ (self.config.name == "station")
156
+ or (self.config.name == "station_train")
157
+ or (self.config.name == "station_test")
158
+ ):
159
+ features = datasets.Features(
160
+ {
161
+ "data": datasets.Array2D(shape=(3, self.nt), dtype="float32"),
162
+ "phase_time": datasets.Sequence(datasets.Value("string")),
163
+ "phase_index": datasets.Sequence(datasets.Value("int32")),
164
+ "phase_type": datasets.Sequence(datasets.Value("string")),
165
+ "phase_polarity": datasets.Sequence(datasets.Value("string")),
166
+ "begin_time": datasets.Value("string"),
167
+ "end_time": datasets.Value("string"),
168
+ "event_time": datasets.Value("string"),
169
+ "event_time_index": datasets.Value("int32"),
170
+ "event_location": datasets.Sequence(datasets.Value("float32")),
171
+ "station_location": datasets.Sequence(datasets.Value("float32")),
172
+ },
173
+ )
174
+ elif (self.config.name == "event") or (self.config.name == "event_train") or (self.config.name == "event_test"):
175
+ features = datasets.Features(
176
+ {
177
+ "data": datasets.Array3D(shape=(None, 3, self.nt), dtype="float32"),
178
+ "phase_time": datasets.Sequence(datasets.Sequence(datasets.Value("string"))),
179
+ "phase_index": datasets.Sequence(datasets.Sequence(datasets.Value("int32"))),
180
+ "phase_type": datasets.Sequence(datasets.Sequence(datasets.Value("string"))),
181
+ "phase_polarity": datasets.Sequence(datasets.Sequence(datasets.Value("string"))),
182
+ "begin_time": datasets.Value("string"),
183
+ "end_time": datasets.Value("string"),
184
+ "event_time": datasets.Value("string"),
185
+ "event_time_index": datasets.Value("int32"),
186
+ "event_location": datasets.Sequence(datasets.Value("float32")),
187
+ "station_location": datasets.Sequence(datasets.Sequence(datasets.Value("float32"))),
188
+ },
189
+ )
190
+ else:
191
+ raise ValueError(f"config.name = {self.config.name} is not in BUILDER_CONFIGS")
192
+
193
+ return datasets.DatasetInfo(
194
+ # This is the description that will appear on the datasets page.
195
+ description=_DESCRIPTION,
196
+ # This defines the different columns of the dataset and their types
197
+ features=features, # Here we define them above because they are different between the two configurations
198
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
199
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
200
+ # supervised_keys=("sentence", "label"),
201
+ # Homepage of the dataset for documentation
202
+ homepage=_HOMEPAGE,
203
+ # License for the dataset if available
204
+ license=_LICENSE,
205
+ # Citation for the dataset
206
+ citation=_CITATION,
207
+ )
208
+
209
+ def _split_generators(self, dl_manager):
210
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
211
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
212
+
213
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
214
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
215
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
216
+ urls = _URLS[self.config.name]
217
+ # files = dl_manager.download(urls)
218
+ # files = dl_manager.download_and_extract(urls)
219
+ files = ["waveform_h5/1999.h5", "waveform_h5/2000.h5"]
220
+ print(files)
221
+
222
+ if self.config.name == "station" or self.config.name == "event":
223
+ return [
224
+ datasets.SplitGenerator(
225
+ name=datasets.Split.TRAIN,
226
+ # These kwargs will be passed to _generate_examples
227
+ gen_kwargs={
228
+ "filepath": files[:-1],
229
+ "split": "train",
230
+ },
231
+ ),
232
+ datasets.SplitGenerator(
233
+ name=datasets.Split.TEST,
234
+ gen_kwargs={"filepath": files[-1:], "split": "test"},
235
+ ),
236
+ ]
237
+ elif self.config.name == "station_train" or self.config.name == "event_train":
238
+ return [
239
+ datasets.SplitGenerator(
240
+ name=datasets.Split.TRAIN,
241
+ gen_kwargs={
242
+ "filepath": files,
243
+ "split": "train",
244
+ },
245
+ ),
246
+ ]
247
+ elif self.config.name == "station_test" or self.config.name == "event_test":
248
+ return [
249
+ datasets.SplitGenerator(
250
+ name=datasets.Split.TEST,
251
+ gen_kwargs={"filepath": files, "split": "test"},
252
+ ),
253
+ ]
254
+ else:
255
+ raise ValueError("config.name is not in BUILDER_CONFIGS")
256
+
257
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
258
+ def _generate_examples(self, filepath, split):
259
+ # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
260
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
261
+
262
+ for file in filepath:
263
+ with fsspec.open(file, "rb") as fs:
264
+ with h5py.File(fs, "r") as fp:
265
+ event_ids = list(fp.keys())
266
+ for event_id in event_ids:
267
+ event = fp[event_id]
268
+ event_attrs = event.attrs
269
+ begin_time = event_attrs["begin_time"]
270
+ end_time = event_attrs["end_time"]
271
+ event_location = [
272
+ event_attrs["longitude"],
273
+ event_attrs["latitude"],
274
+ event_attrs["depth_km"],
275
+ ]
276
+ event_time = event_attrs["event_time"]
277
+ event_time_index = event_attrs["event_time_index"]
278
+ station_ids = list(event.keys())
279
+ if len(station_ids) == 0:
280
+ continue
281
+ if (
282
+ (self.config.name == "station")
283
+ or (self.config.name == "station_train")
284
+ or (self.config.name == "station_test")
285
+ ):
286
+ waveforms = np.zeros([3, self.nt], dtype="float32")
287
+
288
+ for i, sta_id in enumerate(station_ids):
289
+ waveforms[:, : self.nt] = event[sta_id][:, : self.nt]
290
+ attrs = event[sta_id].attrs
291
+ phase_type = attrs["phase_type"]
292
+ phase_time = attrs["phase_time"]
293
+ phase_index = attrs["phase_index"]
294
+ phase_polarity = attrs["phase_polarity"]
295
+ station_location = [attrs["longitude"], attrs["latitude"], -attrs["elevation_m"] / 1e3]
296
+
297
+ yield f"{event_id}/{sta_id}", {
298
+ "data": waveforms,
299
+ "phase_time": phase_time,
300
+ "phase_index": phase_index,
301
+ "phase_type": phase_type,
302
+ "phase_polarity": phase_polarity,
303
+ "begin_time": begin_time,
304
+ "end_time": end_time,
305
+ "event_time": event_time,
306
+ "event_time_index": event_time_index,
307
+ "event_location": event_location,
308
+ "station_location": station_location,
309
+ }
310
+
311
+ elif (
312
+ (self.config.name == "event")
313
+ or (self.config.name == "event_train")
314
+ or (self.config.name == "event_test")
315
+ ):
316
+
317
+ waveforms = np.zeros([len(station_ids), 3, self.nt], dtype="float32")
318
+ phase_type = []
319
+ phase_time = []
320
+ phase_index = []
321
+ phase_polarity = []
322
+ station_location = []
323
+
324
+ for i, sta_id in enumerate(station_ids):
325
+ waveforms[i, :, : self.nt] = event[sta_id][:, : self.nt]
326
+ attrs = event[sta_id].attrs
327
+ phase_type.append(list(attrs["phase_type"]))
328
+ phase_time.append(list(attrs["phase_time"]))
329
+ phase_index.append(list(attrs["phase_index"]))
330
+ phase_polarity.append(list(attrs["phase_polarity"]))
331
+ station_location.append(
332
+ [attrs["longitude"], attrs["latitude"], -attrs["elevation_m"] / 1e3]
333
+ )
334
+ yield event_id, {
335
+ "data": waveforms,
336
+ "phase_time": phase_time,
337
+ "phase_index": phase_index,
338
+ "phase_type": phase_type,
339
+ "phase_polarity": phase_polarity,
340
+ "begin_time": begin_time,
341
+ "end_time": end_time,
342
+ "event_time": event_time,
343
+ "event_time_index": event_time_index,
344
+ "event_location": event_location,
345
+ "station_location": station_location,
346
+ }
split_large_files.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import multiprocessing as mp
3
+ import os
4
+ from glob import glob
5
+
6
+ import h5py
7
+ import numpy as np
8
+ import pandas as pd
9
+ from tqdm import tqdm
10
+
11
+ # %%
12
+ data_path = "waveform_h5"
13
+ result_path = "waveform_h5"
14
+ file_list = sorted(glob(f"{data_path}/*.h5"))
15
+ # %%
16
+ file_size = {file: os.path.getsize(file)/1e9 for file in file_list}
17
+
18
+ # %%
19
+ MAX_SIZE = 45 # GB
20
+ for file, size in file_size.items():
21
+ if size > MAX_SIZE:
22
+ # split into smaller files
23
+ NUM_FILES = int(np.ceil(size / MAX_SIZE))
24
+ with h5py.File(file, "r") as f:
25
+ event_ids = list(f.keys())
26
+ for event_id in tqdm(event_ids, desc=f"Processing {file}"):
27
+ index = int(event_id[-1]) % NUM_FILES
28
+ # with h5py.File(f"{result_path}/{file.split('/')[-1].replace('.h5', '')}_{index}.h5", "a") as g:
29
+ with h5py.File(f"{data_path}/{file.split('/')[-1].replace('.h5', '')}_{index}.h5", "a") as g:
30
+ # if event_id in g:
31
+ # print(f"Event {event_id} already exists in {file.split('/')[-1].replace('.h5', '')}_{index}.h5")
32
+ # continue
33
+ # copy
34
+ f.copy(event_id, g)
35
+ # else:
36
+ # print(f"Copying {file} to {result_path}")
37
+ # os.system(f"cp {file} {result_path}")
upload.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi
2
+
3
+ api = HfApi()
4
+
5
+ # Upload all the content from the local folder to your remote Space.
6
+ # By default, files are uploaded at the root of the repo
7
+ api.upload_folder(
8
+ folder_path="./",
9
+ repo_id="AI4EPS/quakeflow_nc",
10
+ repo_type="space",
11
+ )