forked from DeepPSP/torch_ecg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset.py
381 lines (330 loc) · 12.9 KB
/
dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"""
"""
import json
from copy import deepcopy
from random import sample, shuffle
from typing import Dict, List, Optional, Sequence
import numpy as np
import torch
from cfg import BaseCfg, ModelCfg, TrainCfg # noqa: F401
from data_reader import CINC2022Reader, PCGDataBase
from inputs import InputConfig, MelSpectrogramInput, MFCCInput, SpectralInput, SpectrogramInput, WaveformInput # noqa: F401
from torch.utils.data.dataset import Dataset
from tqdm.auto import tqdm
from torch_ecg._preprocessors import PreprocManager
from torch_ecg.cfg import CFG
from torch_ecg.utils.misc import ReprMixin, list_sum
from torch_ecg.utils.utils_data import ensure_siglen, stratified_train_test_split
__all__ = [
"CinC2022Dataset",
]
class CinC2022Dataset(Dataset, ReprMixin):
""" """
__name__ = "CinC2022Dataset"
def __init__(self, config: CFG, task: str, training: bool = True, lazy: bool = True) -> None:
""" """
super().__init__()
self.config = CFG(deepcopy(config))
# self.task = task.lower() # task will be set in self.__set_task
self.training = training
self.lazy = lazy
self.reader = CINC2022Reader(
self.config.db_dir,
ignore_unannotated=self.config.get("ignore_unannotated", True),
)
self.subjects = self._train_test_split()
df = self.reader.df_stats[self.reader.df_stats["Patient ID"].isin(self.subjects)]
self.records = list_sum([self.reader.subject_records[row["Patient ID"]] for _, row in df.iterrows()])
if self.config.get("entry_test_flag", False):
self.records = sample(self.records, int(len(self.records) * 0.2))
if self.training:
shuffle(self.records)
if self.config.torch_dtype == torch.float64:
self.dtype = np.float64
else:
self.dtype = np.float32
ppm_config = CFG(random=False)
ppm_config.update(deepcopy(self.config.classification))
seg_ppm_config = CFG(random=False)
seg_ppm_config.update(deepcopy(self.config.segmentation))
self.ppm = PreprocManager.from_config(ppm_config)
self.seg_ppm = PreprocManager.from_config(seg_ppm_config)
self.__cache = None
self.__set_task(task, lazy)
def __len__(self) -> int:
""" """
if self.cache is None:
self._load_all_data()
return self.cache["waveforms"].shape[0]
def __getitem__(self, index: int) -> Dict[str, np.ndarray]:
""" """
if self.cache is None:
self._load_all_data()
return {k: v[index] for k, v in self.cache.items()}
def __set_task(self, task: str, lazy: bool) -> None:
""" """
assert task.lower() in TrainCfg.tasks, f"illegal task \042{task}\042"
if hasattr(self, "task") and self.task == task.lower() and self.cache is not None and len(self.cache["waveforms"]) > 0:
return
self.task = task.lower()
self.siglen = int(self.config[self.task].fs * self.config[self.task].siglen)
self.classes = self.config[task].classes
self.n_classes = len(self.config[task].classes)
self.lazy = lazy
if self.task in ["classification"]:
self.fdr = FastDataReader(self.reader, self.records, self.config, self.task, self.ppm)
elif self.task in ["segmentation"]:
self.fdr = FastDataReader(self.reader, self.records, self.config, self.task, self.seg_ppm)
elif self.task in ["multi_task"]:
self.fdr = MutiTaskFastDataReader(self.reader, self.records, self.config, self.task, self.ppm)
else:
raise ValueError("Illegal task")
if self.lazy:
return
tmp_cache = []
with tqdm(
range(len(self.fdr)),
desc="Loading data",
unit="records",
dynamic_ncols=True,
mininterval=1.0,
) as pbar:
for idx in pbar:
tmp_cache.append(self.fdr[idx])
keys = tmp_cache[0].keys()
self.__cache = {k: np.concatenate([v[k] for v in tmp_cache]) for k in keys}
for k in keys:
if self.__cache[k].ndim == 1:
self.__cache[k] = self.__cache[k]
def _load_all_data(self) -> None:
""" """
self.__set_task(self.task, lazy=False)
def _train_test_split(self, train_ratio: float = 0.8, force_recompute: bool = False) -> List[str]:
""" """
_train_ratio = int(train_ratio * 100)
_test_ratio = 100 - _train_ratio
assert _train_ratio * _test_ratio > 0
train_file = self.reader.db_dir / f"train_ratio_{_train_ratio}.json"
test_file = self.reader.db_dir / f"test_ratio_{_test_ratio}.json"
aux_train_file = BaseCfg.project_dir / "utils" / f"train_ratio_{_train_ratio}.json"
aux_test_file = BaseCfg.project_dir / "utils" / f"test_ratio_{_test_ratio}.json"
if not force_recompute and train_file.exists() and test_file.exists():
if self.training:
return json.loads(train_file.read_text())
else:
return json.loads(test_file.read_text())
if not force_recompute and aux_train_file.exists() and aux_test_file.exists():
if self.training:
return json.loads(aux_train_file.read_text())
else:
return json.loads(aux_test_file.read_text())
df_train, df_test = stratified_train_test_split(
self.reader.df_stats,
[
"Murmur",
"Age",
"Sex",
"Pregnancy status",
"Outcome",
],
test_ratio=1 - train_ratio,
)
train_set = df_train["Patient ID"].tolist()
test_set = df_test["Patient ID"].tolist()
train_file.write_text(json.dumps(train_set, ensure_ascii=False))
aux_train_file.write_text(json.dumps(train_set, ensure_ascii=False))
test_file.write_text(json.dumps(test_set, ensure_ascii=False))
aux_test_file.write_text(json.dumps(test_set, ensure_ascii=False))
shuffle(train_set)
shuffle(test_set)
if self.training:
return train_set
else:
return test_set
@property
def cache(self) -> List[Dict[str, np.ndarray]]:
return self.__cache
def extra_repr_keys(self) -> List[str]:
""" """
return ["task", "training"]
class FastDataReader(ReprMixin, Dataset):
""" """
def __init__(
self,
reader: PCGDataBase,
records: Sequence[str],
config: CFG,
task: str,
ppm: Optional[PreprocManager] = None,
) -> None:
""" """
self.reader = reader
self.records = records
self.config = config
self.task = task
self.ppm = ppm
if self.config.torch_dtype == torch.float64:
self.dtype = np.float64
else:
self.dtype = np.float32
def __len__(self) -> int:
""" """
return len(self.records)
def __getitem__(self, index: int) -> Dict[str, np.ndarray]:
""" """
rec = self.records[index]
waveforms = self.reader.load_data(
rec,
data_format=self.config[self.task].data_format,
)
if self.ppm:
waveforms, _ = self.ppm(waveforms, self.reader.fs)
waveforms = ensure_siglen(
waveforms,
siglen=self.config[self.task].input_len,
fmt=self.config[self.task].data_format,
tolerance=self.config[self.task].sig_slice_tol,
).astype(self.dtype)
if waveforms.ndim == 2:
waveforms = waveforms[np.newaxis, ...]
n_segments = waveforms.shape[0]
if self.task in ["classification"]:
label = self.reader.load_ann(rec)
if self.config[self.task].loss != "CrossEntropyLoss":
label = (
np.isin(self.config[self.task].classes, label)
.astype(self.dtype)[np.newaxis, ...]
.repeat(n_segments, axis=0)
)
else:
label = np.array(
[self.config[self.task].class_map[label] for _ in range(n_segments)],
dtype=int,
)
out = {"waveforms": waveforms, "murmur": label}
if self.config[self.task].outcomes is not None:
outcome = self.reader.load_outcome(rec)
if self.config[self.task].loss["outcome"] != "CrossEntropyLoss":
outcome = (
np.isin(self.config[self.task].outcomes, outcome)
.astype(self.dtype)[np.newaxis, ...]
.repeat(n_segments, axis=0)
)
else:
outcome = np.array(
[self.config[self.task].outcome_map[outcome] for _ in range(n_segments)],
dtype=int,
)
out["outcome"] = outcome
return out
elif self.task in ["segmentation"]:
label = self.reader.load_segmentation(
rec,
seg_format="binary",
ensure_same_len=True,
fs=self.config[self.task].fs,
)
label = ensure_siglen(
label,
siglen=self.config[self.task].input_len,
fmt="channel_last",
tolerance=self.config[self.task].sig_slice_tol,
).astype(self.dtype)
return {"waveforms": waveforms, "segmentation": label}
else:
raise ValueError(f"Illegal task: {self.task}")
def extra_repr_keys(self) -> List[str]:
return [
"reader",
"ppm",
]
class MutiTaskFastDataReader(ReprMixin, Dataset):
""" """
def __init__(
self,
reader: PCGDataBase,
records: Sequence[str],
config: CFG,
task: str = "multi_task",
ppm: Optional[PreprocManager] = None,
) -> None:
""" """
self.reader = reader
self.records = records
self.config = config
self.task = task
assert self.task == "multi_task"
self.ppm = ppm
if self.config.torch_dtype == torch.float64:
self.dtype = np.float64
else:
self.dtype = np.float32
def __len__(self) -> int:
""" """
return len(self.records)
def __getitem__(self, index: int) -> Dict[str, np.ndarray]:
""" """
rec = self.records[index]
waveforms = self.reader.load_data(
rec,
data_format=self.config[self.task].data_format,
)
if self.ppm:
waveforms, _ = self.ppm(waveforms, self.reader.fs)
waveforms = ensure_siglen(
waveforms,
siglen=self.config[self.task].input_len,
fmt=self.config[self.task].data_format,
tolerance=self.config[self.task].sig_slice_tol,
).astype(self.dtype)
if waveforms.ndim == 2:
waveforms = waveforms[np.newaxis, ...]
n_segments = waveforms.shape[0]
label = self.reader.load_ann(rec)
if self.config[self.task].loss["murmur"] != "CrossEntropyLoss":
label = (
np.isin(self.config[self.task].classes, label).astype(self.dtype)[np.newaxis, ...].repeat(n_segments, axis=0)
)
else:
label = np.array(
[self.config[self.task].class_map[label] for _ in range(n_segments)],
dtype=int,
)
out_tensors = {
"waveforms": waveforms,
"murmur": label,
}
if self.config[self.task].outcomes is not None:
outcome = self.reader.load_outcome(rec)
if self.config[self.task].loss["outcome"] != "CrossEntropyLoss":
outcome = (
np.isin(self.config[self.task].outcomes, outcome)
.astype(self.dtype)[np.newaxis, ...]
.repeat(n_segments, axis=0)
)
else:
outcome = np.array(
[self.config[self.task].outcome_map[outcome] for _ in range(n_segments)],
dtype=int,
)
out_tensors["outcome"] = outcome
if self.config[self.task].states is not None:
mask = self.reader.load_segmentation(
rec,
seg_format="binary",
ensure_same_len=True,
fs=self.config[self.task].fs,
)
mask = ensure_siglen(
mask,
siglen=self.config[self.task].input_len,
fmt="channel_last",
tolerance=self.config[self.task].sig_slice_tol,
).astype(self.dtype)
out_tensors["segmentation"] = mask
return out_tensors
def extra_repr_keys(self) -> List[str]:
return [
"reader",
"ppm",
]