Datasets:
ArXiv:
DOI:
License:
add batched configuration (#3)
Browse files- add batched configuration (fa3c8cdd117884e5405801754ddea6fbc0845399)
- remove batched operation and leave it to sampler (4fd86c8e2af7da1cf379391d953769a14e16cac8)
Co-authored-by: kylewhy <kylewhy@users.noreply.huggingface.co>
- README.md +79 -6
- quakeflow_nc.py +68 -37
README.md
CHANGED
@@ -82,36 +82,63 @@ Group: / len:10000
|
|
82 |
- torch (for PyTorch)
|
83 |
|
84 |
### Usage
|
|
|
85 |
```python
|
86 |
import h5py
|
87 |
import numpy as np
|
88 |
import torch
|
89 |
from torch.utils.data import Dataset, IterableDataset, DataLoader
|
90 |
from datasets import load_dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
|
|
|
|
|
92 |
# load dataset
|
93 |
# ATTENTION: Streaming(Iterable Dataset) is difficult to support because of the feature of HDF5
|
94 |
# So we recommend to directly load the dataset and convert it into iterable later
|
95 |
# The dataset is very large, so you need to wait for some time at the first time
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
```
|
99 |
-
|
|
|
100 |
```python
|
101 |
# change the 37 to the number of shards you want
|
102 |
_URLS = {
|
103 |
"NCEDC": [f"{_REPO}/ncedc_event_dataset_{i:03d}.h5" for i in range(37)]
|
104 |
}
|
105 |
```
|
106 |
-
Then you can use the dataset like this:
|
107 |
```python
|
108 |
-
|
|
|
109 |
quakeflow_nc
|
110 |
```
|
|
|
|
|
111 |
Then you can change the dataset into PyTorch format iterable dataset, and view the first sample:
|
112 |
```python
|
|
|
113 |
quakeflow_nc = quakeflow_nc.to_iterable_dataset()
|
114 |
-
quakeflow_nc = quakeflow_nc.with_format("torch")
|
115 |
# because add examples formatting to get tensors when using the "torch" format
|
116 |
# has not been implemented yet, we need to manually add the formatting
|
117 |
quakeflow_nc = quakeflow_nc.map(lambda x: {key: torch.from_numpy(np.array(value, dtype=np.float32)) for key, value in x.items()})
|
@@ -136,4 +163,50 @@ for batch in dataloader:
|
|
136 |
for key in batch.keys():
|
137 |
print(key, batch[key].shape, batch[key].dtype)
|
138 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
```
|
|
|
82 |
- torch (for PyTorch)
|
83 |
|
84 |
### Usage
|
85 |
+
Import the necessary packages:
|
86 |
```python
|
87 |
import h5py
|
88 |
import numpy as np
|
89 |
import torch
|
90 |
from torch.utils.data import Dataset, IterableDataset, DataLoader
|
91 |
from datasets import load_dataset
|
92 |
+
```
|
93 |
+
We have 2 configurations for the dataset: `NCEDC` and `NCEDC_full_size`. They all return event-based samples one by one. But `NCEDC` returns samples with 10 stations each, while `NCEDC_full_size` return samples with stations same as the original data.
|
94 |
+
|
95 |
+
The sample of `NCEDC` is a dictionary with the following keys:
|
96 |
+
- `waveform`: the waveform with shape `(3, nt, n_sta)`, the first dimension is 3 components, the second dimension is the number of time samples, the third dimension is the number of stations
|
97 |
+
- `phase_pick`: the probability of the phase pick with shape `(3, nt, n_sta)`, the first dimension is noise, P and S
|
98 |
+
- `event_location`: the event location with shape `(4,)`, including latitude, longitude, depth and time
|
99 |
+
- `station_location`: the station location with shape `(n_sta, 3)`, the first dimension is latitude, longitude and depth
|
100 |
+
|
101 |
+
Because Huggingface datasets only support dynamic size on first dimension, so the sample of `NCEDC_full_size` is a dictionary with the following keys:
|
102 |
+
- `waveform`: the waveform with shape `(n_sta, 3, nt)`,
|
103 |
+
- `phase_pick`: the probability of the phase pick with shape `(n_sta, 3, nt)`
|
104 |
+
- `event_location`: the event location with shape `(4,)`
|
105 |
+
- `station_location`: the station location with shape `(n_sta, 3)`, the first dimension is latitude, longitude and depth
|
106 |
|
107 |
+
The default configuration is `NCEDC`. You can specify the configuration by argument `name`. For example:
|
108 |
+
```python
|
109 |
# load dataset
|
110 |
# ATTENTION: Streaming(Iterable Dataset) is difficult to support because of the feature of HDF5
|
111 |
# So we recommend to directly load the dataset and convert it into iterable later
|
112 |
# The dataset is very large, so you need to wait for some time at the first time
|
113 |
+
|
114 |
+
# to load "NCEDC"
|
115 |
+
quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", split="train")
|
116 |
+
# or
|
117 |
+
quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", name="NCEDC", split="train")
|
118 |
+
|
119 |
+
# to load "NCEDC_full_size"
|
120 |
+
quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", name="NCEDC_full_size", split="train")
|
121 |
```
|
122 |
+
|
123 |
+
If you want to use the first several shards of the dataset, you can download the script `quakeflow_nc.py` and change the code as below:
|
124 |
```python
|
125 |
# change the 37 to the number of shards you want
|
126 |
_URLS = {
|
127 |
"NCEDC": [f"{_REPO}/ncedc_event_dataset_{i:03d}.h5" for i in range(37)]
|
128 |
}
|
129 |
```
|
130 |
+
Then you can use the dataset like this (Don't forget to specify the argument `name`):
|
131 |
```python
|
132 |
+
# don't forget to specify the script path
|
133 |
+
quakeflow_nc = datasets.load_dataset("path_to_script/quakeflow_nc.py", split="train")
|
134 |
quakeflow_nc
|
135 |
```
|
136 |
+
|
137 |
+
#### Usage for `NCEDC`
|
138 |
Then you can change the dataset into PyTorch format iterable dataset, and view the first sample:
|
139 |
```python
|
140 |
+
quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", name="NCEDC", split="train")
|
141 |
quakeflow_nc = quakeflow_nc.to_iterable_dataset()
|
|
|
142 |
# because add examples formatting to get tensors when using the "torch" format
|
143 |
# has not been implemented yet, we need to manually add the formatting
|
144 |
quakeflow_nc = quakeflow_nc.map(lambda x: {key: torch.from_numpy(np.array(value, dtype=np.float32)) for key, value in x.items()})
|
|
|
163 |
for key in batch.keys():
|
164 |
print(key, batch[key].shape, batch[key].dtype)
|
165 |
break
|
166 |
+
```
|
167 |
+
|
168 |
+
#### Usage for `NCEDC_full_size`
|
169 |
+
|
170 |
+
Then you can change the dataset into PyTorch format dataset, and view the first sample (Don't forget to reorder the keys):
|
171 |
+
```python
|
172 |
+
quakeflow_nc = datasets.load_dataset("AI4EPS/quakeflow_nc", split="train", name="NCEDC_full_size")
|
173 |
+
|
174 |
+
# for PyTorch DataLoader, we need to divide the dataset into several shards
|
175 |
+
num_workers=4
|
176 |
+
quakeflow_nc = quakeflow_nc.to_iterable_dataset(num_shards=num_workers)
|
177 |
+
# because add examples formatting to get tensors when using the "torch" format
|
178 |
+
# has not been implemented yet, we need to manually add the formatting
|
179 |
+
quakeflow_nc = quakeflow_nc.map(lambda x: {key: torch.from_numpy(np.array(value, dtype=np.float32)) for key, value in x.items()})
|
180 |
+
def reorder_keys(example):
|
181 |
+
example["waveform"] = example["waveform"].permute(1,2,0).contiguous()
|
182 |
+
example["phase_pick"] = example["phase_pick"].permute(1,2,0).contiguous()
|
183 |
+
return example
|
184 |
+
|
185 |
+
quakeflow_nc = quakeflow_nc.map(reorder_keys)
|
186 |
+
|
187 |
+
try:
|
188 |
+
isinstance(quakeflow_nc, torch.utils.data.IterableDataset)
|
189 |
+
except:
|
190 |
+
raise Exception("quakeflow_nc is not an IterableDataset")
|
191 |
+
|
192 |
+
data_loader = DataLoader(
|
193 |
+
quakeflow_nc,
|
194 |
+
batch_size=1,
|
195 |
+
num_workers=num_workers,
|
196 |
+
)
|
197 |
+
|
198 |
+
for batch in quakeflow_nc:
|
199 |
+
print("\nIterable test\n")
|
200 |
+
print(batch.keys())
|
201 |
+
for key in batch.keys():
|
202 |
+
print(key, batch[key].shape, batch[key].dtype)
|
203 |
+
break
|
204 |
+
|
205 |
+
for batch in data_loader:
|
206 |
+
print("\nDataloader test\n")
|
207 |
+
print(batch.keys())
|
208 |
+
for key in batch.keys():
|
209 |
+
batch[key] = batch[key].squeeze(0)
|
210 |
+
print(key, batch[key].shape, batch[key].dtype)
|
211 |
+
break
|
212 |
```
|
quakeflow_nc.py
CHANGED
@@ -17,14 +17,9 @@
|
|
17 |
"""QuakeFlow_NC: A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format."""
|
18 |
|
19 |
|
20 |
-
import csv
|
21 |
-
import json
|
22 |
-
import os
|
23 |
import h5py
|
24 |
import numpy as np
|
25 |
import torch
|
26 |
-
import fsspec
|
27 |
-
from glob import glob
|
28 |
from typing import Dict, List, Optional, Tuple, Union
|
29 |
|
30 |
import datasets
|
@@ -58,16 +53,36 @@ _LICENSE = ""
|
|
58 |
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
|
59 |
_REPO = "https://huggingface.co/datasets/AI4EPS/quakeflow_nc/resolve/main/data"
|
60 |
_URLS = {
|
61 |
-
"NCEDC": [f"{_REPO}/ncedc_event_dataset_{i:03d}.h5" for i in range(37)]
|
|
|
62 |
}
|
63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
|
66 |
class QuakeFlow_NC(datasets.GeneratorBasedBuilder):
|
67 |
"""QuakeFlow_NC: A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format."""
|
68 |
-
|
69 |
VERSION = datasets.Version("1.1.0")
|
70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
# This is an example of a dataset with multiple configurations.
|
72 |
# If you don't want/need to define several sub-sets in your dataset,
|
73 |
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
|
@@ -79,22 +94,36 @@ class QuakeFlow_NC(datasets.GeneratorBasedBuilder):
|
|
79 |
# You will be able to load one or the other configurations in the following list with
|
80 |
# data = datasets.load_dataset('my_dataset', 'first_domain')
|
81 |
# data = datasets.load_dataset('my_dataset', 'second_domain')
|
|
|
|
|
82 |
BUILDER_CONFIGS = [
|
83 |
-
datasets.BuilderConfig(name="NCEDC", version=VERSION, description="
|
|
|
84 |
]
|
85 |
|
86 |
DEFAULT_CONFIG_NAME = "NCEDC" # It's not mandatory to have a default configuration. Just use one if it make sense.
|
87 |
|
88 |
def _info(self):
|
89 |
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
return datasets.DatasetInfo(
|
99 |
# This is the description that will appear on the datasets page.
|
100 |
description=_DESCRIPTION,
|
@@ -150,30 +179,26 @@ class QuakeFlow_NC(datasets.GeneratorBasedBuilder):
|
|
150 |
# ),
|
151 |
]
|
152 |
|
153 |
-
|
154 |
-
nt = 8192
|
155 |
-
feature_nt = 512
|
156 |
-
feature_scale = int(nt / feature_nt)
|
157 |
-
sampling_rate=100.0
|
158 |
-
num_stations = 10
|
159 |
|
160 |
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
|
161 |
def _generate_examples(self, filepath, split):
|
162 |
# TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
|
163 |
# The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
|
164 |
num_stations = self.num_stations
|
165 |
-
|
166 |
for file in filepath:
|
167 |
with h5py.File(file, "r") as fp:
|
168 |
# for event_id in sorted(list(fp.keys())):
|
169 |
for event_id in fp.keys():
|
170 |
event = fp[event_id]
|
171 |
station_ids = list(event.keys())
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
|
|
|
|
177 |
waveforms = np.zeros([3, self.nt, len(station_ids)])
|
178 |
phase_pick = np.zeros_like(waveforms)
|
179 |
attrs = event.attrs
|
@@ -182,13 +207,11 @@ class QuakeFlow_NC(datasets.GeneratorBasedBuilder):
|
|
182 |
|
183 |
for i, sta_id in enumerate(station_ids):
|
184 |
# trace_id = event_id + "/" + sta_id
|
185 |
-
|
186 |
waveforms[:, :, i] = event[sta_id][:,:self.nt]
|
187 |
attrs = event[sta_id].attrs
|
188 |
p_picks = attrs["phase_index"][attrs["phase_type"] == "P"]
|
189 |
s_picks = attrs["phase_index"][attrs["phase_type"] == "S"]
|
190 |
phase_pick[:, :, i] = generate_label([p_picks, s_picks], nt=self.nt)
|
191 |
-
|
192 |
station_location.append([attrs["longitude"], attrs["latitude"], -attrs["elevation_m"]/1e3])
|
193 |
|
194 |
std = np.std(waveforms, axis=1, keepdims=True)
|
@@ -196,13 +219,21 @@ class QuakeFlow_NC(datasets.GeneratorBasedBuilder):
|
|
196 |
waveforms = (waveforms - np.mean(waveforms, axis=1, keepdims=True)) / std
|
197 |
waveforms = waveforms.astype(np.float32)
|
198 |
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
|
207 |
|
208 |
def generate_label(phase_list, label_width=[150, 150], nt=8192):
|
|
|
17 |
"""QuakeFlow_NC: A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format."""
|
18 |
|
19 |
|
|
|
|
|
|
|
20 |
import h5py
|
21 |
import numpy as np
|
22 |
import torch
|
|
|
|
|
23 |
from typing import Dict, List, Optional, Tuple, Union
|
24 |
|
25 |
import datasets
|
|
|
53 |
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
|
54 |
_REPO = "https://huggingface.co/datasets/AI4EPS/quakeflow_nc/resolve/main/data"
|
55 |
_URLS = {
|
56 |
+
"NCEDC": [f"{_REPO}/ncedc_event_dataset_{i:03d}.h5" for i in range(37)],
|
57 |
+
"NCEDC_full_size": [f"{_REPO}/ncedc_event_dataset_{i:03d}.h5" for i in range(37)],
|
58 |
}
|
59 |
|
60 |
+
class BatchBuilderConfig(datasets.BuilderConfig):
|
61 |
+
"""
|
62 |
+
yield a batch of event-based sample, so the number of sample stations can vary among batches
|
63 |
+
Batch Config for QuakeFlow_NC
|
64 |
+
:param batch_size: number of samples in a batch
|
65 |
+
:param num_stations_list: possible number of stations in a batch
|
66 |
+
"""
|
67 |
+
def __init__(self, batch_size: int, num_stations_list: List, **kwargs):
|
68 |
+
super().__init__(**kwargs)
|
69 |
+
self.batch_size = batch_size
|
70 |
+
self.num_stations_list = num_stations_list
|
71 |
+
|
72 |
|
73 |
# TODO: Name of the dataset usually matches the script name with CamelCase instead of snake_case
|
74 |
class QuakeFlow_NC(datasets.GeneratorBasedBuilder):
|
75 |
"""QuakeFlow_NC: A dataset of earthquake waveforms organized by earthquake events and based on the HDF5 format."""
|
76 |
+
|
77 |
VERSION = datasets.Version("1.1.0")
|
78 |
|
79 |
+
degree2km = 111.32
|
80 |
+
nt = 8192
|
81 |
+
feature_nt = 512
|
82 |
+
feature_scale = int(nt / feature_nt)
|
83 |
+
sampling_rate=100.0
|
84 |
+
num_stations = 10
|
85 |
+
|
86 |
# This is an example of a dataset with multiple configurations.
|
87 |
# If you don't want/need to define several sub-sets in your dataset,
|
88 |
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
|
|
|
94 |
# You will be able to load one or the other configurations in the following list with
|
95 |
# data = datasets.load_dataset('my_dataset', 'first_domain')
|
96 |
# data = datasets.load_dataset('my_dataset', 'second_domain')
|
97 |
+
|
98 |
+
# default config, you can change batch_size and num_stations_list when use `datasets.load_dataset`
|
99 |
BUILDER_CONFIGS = [
|
100 |
+
datasets.BuilderConfig(name="NCEDC", version=VERSION, description="yield event-based samples one by one, the number of sample stations is fixed(default: 10)"),
|
101 |
+
datasets.BuilderConfig(name="NCEDC_full_size", version=VERSION, description="yield event-based samples one by one, the number of sample stations is the same as the number of stations in the event"),
|
102 |
]
|
103 |
|
104 |
DEFAULT_CONFIG_NAME = "NCEDC" # It's not mandatory to have a default configuration. Just use one if it make sense.
|
105 |
|
106 |
def _info(self):
|
107 |
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
|
108 |
+
if self.config.name=="NCEDC":
|
109 |
+
features=datasets.Features(
|
110 |
+
{
|
111 |
+
"waveform": datasets.Array3D(shape=(3, self.nt, self.num_stations), dtype='float32'),
|
112 |
+
"phase_pick": datasets.Array3D(shape=(3, self.nt, self.num_stations), dtype='float32'),
|
113 |
+
"event_location": datasets.Sequence(datasets.Value("float32")),
|
114 |
+
"station_location": datasets.Array2D(shape=(self.num_stations, 3), dtype="float32"),
|
115 |
+
})
|
116 |
+
|
117 |
+
elif self.config.name=="NCEDC_full_size":
|
118 |
+
features=datasets.Features(
|
119 |
+
{
|
120 |
+
"waveform": datasets.Array3D(shape=(None, 3, self.nt), dtype='float32'),
|
121 |
+
"phase_pick": datasets.Array3D(shape=(None, 3, self.nt), dtype='float32'),
|
122 |
+
"event_location": datasets.Sequence(datasets.Value("float32")),
|
123 |
+
"station_location": datasets.Array2D(shape=(None, 3), dtype="float32"),
|
124 |
+
}
|
125 |
+
)
|
126 |
+
|
127 |
return datasets.DatasetInfo(
|
128 |
# This is the description that will appear on the datasets page.
|
129 |
description=_DESCRIPTION,
|
|
|
179 |
# ),
|
180 |
]
|
181 |
|
182 |
+
|
|
|
|
|
|
|
|
|
|
|
183 |
|
184 |
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
|
185 |
def _generate_examples(self, filepath, split):
|
186 |
# TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
|
187 |
# The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
|
188 |
num_stations = self.num_stations
|
|
|
189 |
for file in filepath:
|
190 |
with h5py.File(file, "r") as fp:
|
191 |
# for event_id in sorted(list(fp.keys())):
|
192 |
for event_id in fp.keys():
|
193 |
event = fp[event_id]
|
194 |
station_ids = list(event.keys())
|
195 |
+
|
196 |
+
if self.config.name=="NCEDC":
|
197 |
+
if len(station_ids) < num_stations:
|
198 |
+
continue
|
199 |
+
else:
|
200 |
+
station_ids = np.random.choice(station_ids, num_stations, replace=False)
|
201 |
+
|
202 |
waveforms = np.zeros([3, self.nt, len(station_ids)])
|
203 |
phase_pick = np.zeros_like(waveforms)
|
204 |
attrs = event.attrs
|
|
|
207 |
|
208 |
for i, sta_id in enumerate(station_ids):
|
209 |
# trace_id = event_id + "/" + sta_id
|
|
|
210 |
waveforms[:, :, i] = event[sta_id][:,:self.nt]
|
211 |
attrs = event[sta_id].attrs
|
212 |
p_picks = attrs["phase_index"][attrs["phase_type"] == "P"]
|
213 |
s_picks = attrs["phase_index"][attrs["phase_type"] == "S"]
|
214 |
phase_pick[:, :, i] = generate_label([p_picks, s_picks], nt=self.nt)
|
|
|
215 |
station_location.append([attrs["longitude"], attrs["latitude"], -attrs["elevation_m"]/1e3])
|
216 |
|
217 |
std = np.std(waveforms, axis=1, keepdims=True)
|
|
|
219 |
waveforms = (waveforms - np.mean(waveforms, axis=1, keepdims=True)) / std
|
220 |
waveforms = waveforms.astype(np.float32)
|
221 |
|
222 |
+
if self.config.name=="NCEDC":
|
223 |
+
yield event_id, {
|
224 |
+
"waveform": torch.from_numpy(waveforms).float(),
|
225 |
+
"phase_pick": torch.from_numpy(phase_pick).float(),
|
226 |
+
"event_location": torch.from_numpy(np.array(event_location)).float(),
|
227 |
+
"station_location": torch.from_numpy(np.array(station_location)).float(),
|
228 |
+
}
|
229 |
+
elif self.config.name=="NCEDC_full_size":
|
230 |
+
|
231 |
+
yield event_id, {
|
232 |
+
"waveform": torch.from_numpy(waveforms).float().permute(2,0,1),
|
233 |
+
"phase_pick": torch.from_numpy(phase_pick).float().permute(2,0,1),
|
234 |
+
"event_location": torch.from_numpy(np.array(event_location)).float(),
|
235 |
+
"station_location": torch.from_numpy(np.array(station_location)).float(),
|
236 |
+
}
|
237 |
|
238 |
|
239 |
def generate_label(phase_list, label_width=[150, 150], nt=8192):
|