add batched configuration

#3
by kylewhy - opened
Files changed (2) hide show
  1. README.md +79 -6
  2. quakeflow_nc.py +68 -37
README.md CHANGED
@@ -76,36 +76,63 @@ Group: / len:10000
76
  - torch (for PyTorch)
77
 
78
  ### Usage
 
79
  ```python
80
  import h5py
81
  import numpy as np
82
  import torch
83
  from torch.utils.data import Dataset, IterableDataset, DataLoader
84
  from datasets import load_dataset
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
 
 
86
  # load dataset
87
  # ATTENTION: Streaming(Iterable Dataset) is difficult to support because of the feature of HDF5
88
  # So we recommend to directly load the dataset and convert it into iterable later
89
  # The dataset is very large, so you need to wait for some time at the first time
90
- quakeflow_nc = datasets.load_dataset("AI4EPS/quakeflow_nc", split="train")
91
- quakeflow_nc
 
 
 
 
 
 
92
  ```
93
- If you want to use the first several shards of the dataset, you can download the script `quakeflow_nc.py` and change the code below:
 
94
  ```python
95
  # change the 37 to the number of shards you want
96
  _URLS = {
97
  "NCEDC": [f"{_REPO}/ncedc_event_dataset_{i:03d}.h5" for i in range(37)]
98
  }
99
  ```
100
- Then you can use the dataset like this:
101
  ```python
102
- quakeflow_nc = datasets.load_dataset("./quakeflow_nc.py", split="train")
 
103
  quakeflow_nc
104
  ```
 
 
105
  Then you can change the dataset into PyTorch format iterable dataset, and view the first sample:
106
  ```python
 
107
  quakeflow_nc = quakeflow_nc.to_iterable_dataset()
108
- quakeflow_nc = quakeflow_nc.with_format("torch")
109
  # because add examples formatting to get tensors when using the "torch" format
110
  # has not been implemented yet, we need to manually add the formatting
111
  quakeflow_nc = quakeflow_nc.map(lambda x: {key: torch.from_numpy(np.array(value, dtype=np.float32)) for key, value in x.items()})
@@ -130,4 +157,50 @@ for batch in dataloader:
130
  for key in batch.keys():
131
  print(key, batch[key].shape, batch[key].dtype)
132
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  ```
 
76
  - torch (for PyTorch)
77
 
78
  ### Usage
79
+ Import the necessary packages:
80
  ```python
81
  import h5py
82
  import numpy as np
83
  import torch
84
  from torch.utils.data import Dataset, IterableDataset, DataLoader
85
  from datasets import load_dataset
86
+ ```
87
+ 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.
88
+
89
+ The sample of `NCEDC` is a dictionary with the following keys:
90
+ - `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
91
+ - `phase_pick`: the probability of the phase pick with shape `(3, nt, n_sta)`, the first dimension is noise, P and S
92
+ - `event_location`: the event location with shape `(4,)`, including latitude, longitude, depth and time
93
+ - `station_location`: the station location with shape `(n_sta, 3)`, the first dimension is latitude, longitude and depth
94
+
95
+ Because Huggingface datasets only support dynamic size on first dimension, so the sample of `NCEDC_full_size` is a dictionary with the following keys:
96
+ - `waveform`: the waveform with shape `(n_sta, 3, nt)`,
97
+ - `phase_pick`: the probability of the phase pick with shape `(n_sta, 3, nt)`
98
+ - `event_location`: the event location with shape `(4,)`
99
+ - `station_location`: the station location with shape `(n_sta, 3)`, the first dimension is latitude, longitude and depth
100
 
101
+ The default configuration is `NCEDC`. You can specify the configuration by argument `name`. For example:
102
+ ```python
103
  # load dataset
104
  # ATTENTION: Streaming(Iterable Dataset) is difficult to support because of the feature of HDF5
105
  # So we recommend to directly load the dataset and convert it into iterable later
106
  # The dataset is very large, so you need to wait for some time at the first time
107
+
108
+ # to load "NCEDC"
109
+ quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", split="train")
110
+ # or
111
+ quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", name="NCEDC", split="train")
112
+
113
+ # to load "NCEDC_full_size"
114
+ quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", name="NCEDC_full_size", split="train")
115
  ```
116
+
117
+ 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:
118
  ```python
119
  # change the 37 to the number of shards you want
120
  _URLS = {
121
  "NCEDC": [f"{_REPO}/ncedc_event_dataset_{i:03d}.h5" for i in range(37)]
122
  }
123
  ```
124
+ Then you can use the dataset like this (Don't forget to specify the argument `name`):
125
  ```python
126
+ # don't forget to specify the script path
127
+ quakeflow_nc = datasets.load_dataset("path_to_script/quakeflow_nc.py", split="train")
128
  quakeflow_nc
129
  ```
130
+
131
+ #### Usage for `NCEDC`
132
  Then you can change the dataset into PyTorch format iterable dataset, and view the first sample:
133
  ```python
134
+ quakeflow_nc = load_dataset("AI4EPS/quakeflow_nc", name="NCEDC", split="train")
135
  quakeflow_nc = quakeflow_nc.to_iterable_dataset()
 
136
  # because add examples formatting to get tensors when using the "torch" format
137
  # has not been implemented yet, we need to manually add the formatting
138
  quakeflow_nc = quakeflow_nc.map(lambda x: {key: torch.from_numpy(np.array(value, dtype=np.float32)) for key, value in x.items()})
 
157
  for key in batch.keys():
158
  print(key, batch[key].shape, batch[key].dtype)
159
  break
160
+ ```
161
+
162
+ #### Usage for `NCEDC_full_size`
163
+
164
+ Then you can change the dataset into PyTorch format dataset, and view the first sample (Don't forget to reorder the keys):
165
+ ```python
166
+ quakeflow_nc = datasets.load_dataset("AI4EPS/quakeflow_nc", split="train", name="NCEDC_full_size")
167
+
168
+ # for PyTorch DataLoader, we need to divide the dataset into several shards
169
+ num_workers=4
170
+ quakeflow_nc = quakeflow_nc.to_iterable_dataset(num_shards=num_workers)
171
+ # because add examples formatting to get tensors when using the "torch" format
172
+ # has not been implemented yet, we need to manually add the formatting
173
+ quakeflow_nc = quakeflow_nc.map(lambda x: {key: torch.from_numpy(np.array(value, dtype=np.float32)) for key, value in x.items()})
174
+ def reorder_keys(example):
175
+ example["waveform"] = example["waveform"].permute(1,2,0).contiguous()
176
+ example["phase_pick"] = example["phase_pick"].permute(1,2,0).contiguous()
177
+ return example
178
+
179
+ quakeflow_nc = quakeflow_nc.map(reorder_keys)
180
+
181
+ try:
182
+ isinstance(quakeflow_nc, torch.utils.data.IterableDataset)
183
+ except:
184
+ raise Exception("quakeflow_nc is not an IterableDataset")
185
+
186
+ data_loader = DataLoader(
187
+ quakeflow_nc,
188
+ batch_size=1,
189
+ num_workers=num_workers,
190
+ )
191
+
192
+ for batch in quakeflow_nc:
193
+ print("\nIterable test\n")
194
+ print(batch.keys())
195
+ for key in batch.keys():
196
+ print(key, batch[key].shape, batch[key].dtype)
197
+ break
198
+
199
+ for batch in data_loader:
200
+ print("\nDataloader test\n")
201
+ print(batch.keys())
202
+ for key in batch.keys():
203
+ batch[key] = batch[key].squeeze(0)
204
+ print(key, batch[key].shape, batch[key].dtype)
205
+ break
206
  ```
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="This part of my dataset covers a first domain"),
 
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
- features=datasets.Features(
91
- {
92
- "waveform": datasets.Array3D(shape=(3, self.nt, self.num_stations), dtype='float32'),
93
- "phase_pick": datasets.Array3D(shape=(3, self.nt, self.num_stations), dtype='float32'),
94
- "event_location": [datasets.Value("float32")],
95
- "station_location": datasets.Array2D(shape=(self.num_stations, 3), dtype="float32"),
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
- degree2km = 111.32
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
- if len(station_ids) < num_stations:
173
- continue
174
- else:
175
- station_ids = np.random.choice(station_ids, num_stations, replace=False)
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
- yield event_id, {
200
- "waveform": torch.from_numpy(waveforms).float(),
201
- "phase_pick": torch.from_numpy(phase_pick).float(),
202
- "event_location": event_location,
203
- "station_location": station_location,
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):