-
Notifications
You must be signed in to change notification settings - Fork 8
/
_dataset.py
409 lines (332 loc) · 12.4 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"""Dataset base class."""
# --- import --------------------------------------------------------------------------------------
import collections
import numpy as np
import h5py
from . import exceptions as wt_exceptions
from . import kit as wt_kit
from . import units as wt_units
# --- class ---------------------------------------------------------------------------------------
class Dataset(h5py.Dataset):
"""Array-like data container."""
_instances = {}
class_name = "Dataset"
def __getitem__(self, index):
if not hasattr(index, "__iter__"):
index = [index]
index = wt_kit.valid_index(index, self.shape)
return super().__getitem__(index)
def __iadd__(self, value):
def f(dataset, s, value):
if hasattr(value, "shape"):
dataset[s] += value[wt_kit.valid_index(s, value.shape)]
else:
dataset[s] += value
self.chunkwise(f, value=value)
return self
def __imul__(self, value):
def f(dataset, s, value):
if hasattr(value, "shape"):
dataset[s] *= value[wt_kit.valid_index(s, value.shape)]
else:
dataset[s] *= value
self.chunkwise(f, value=value)
return self
def __ipow__(self, value):
def f(dataset, s, value):
if hasattr(value, "shape"):
dataset[s] **= value[wt_kit.valid_index(s, value.shape)]
else:
dataset[s] **= value
self.chunkwise(f, value=value)
return self
def __isub__(self, value):
def f(dataset, s, value):
if hasattr(value, "shape"):
dataset[s] -= value[wt_kit.valid_index(s, value.shape)]
else:
dataset[s] -= value
self.chunkwise(f, value=value)
return self
def __itruediv__(self, value):
def f(dataset, s, value):
if hasattr(value, "shape"):
dataset[s] /= value[wt_kit.valid_index(s, value.shape)]
else:
dataset[s] /= value
self.chunkwise(f, value=value)
return self
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __new__(cls, parent, id, **kwargs):
"""New object formation handler."""
fullpath = parent.fullpath + h5py.h5i.get_name(id).decode()
fullpath = fullpath.replace("//", "/")
if fullpath in cls._instances.keys():
return cls._instances[fullpath]
else:
instance = super(Dataset, cls).__new__(cls)
cls.__init__(instance, parent, id, **kwargs)
cls._instances[fullpath] = instance
return instance
def __repr__(self):
return "<WrightTools.{0} '{1}' at {2}>".format(
self.class_name, self.natural_name, self.fullpath
)
def __setitem__(self, index, value):
self._clear_array_attributes_cache()
return super().__setitem__(index, value)
def _clear_array_attributes_cache(self):
if "max" in self.attrs.keys():
del self.attrs["max"]
if "min" in self.attrs.keys():
del self.attrs["min"]
if "argmax" in self.attrs.keys():
del self.attrs["argmax"]
if "argmin" in self.attrs.keys():
del self.attrs["argmin"]
@property
def _leaf(self):
out = self.natural_name
if self.units is not None:
out += " ({0})".format(self.units)
out += " {0}".format(self.shape)
return out
@property
def full(self):
arr = self[:]
for i in range(arr.ndim):
if arr.shape[i] == 1:
arr = np.repeat(arr, self.parent.shape[i], axis=i)
return arr
@property
def fullpath(self):
"""Full path: file and internal structure."""
return self.parent.filepath + "::" + self.name
@property
def natural_name(self):
"""Natural name of the dataset. May be different from name."""
try:
assert self._natural_name is not None
except (AssertionError, AttributeError):
self._natural_name = self.attrs["name"]
finally:
return self._natural_name
@natural_name.setter
def natural_name(self, value):
self.attrs["name"] = value
self._natural_name = None
@property
def parent(self):
"""Parent."""
return self._parent
@property
def points(self):
"""Squeezed array."""
return np.squeeze(self[:])
@property
def units(self):
"""Units."""
if "units" in self.attrs.keys():
# This try-except here for compatibility with v1.0.0 of WT5 format
try:
self.attrs["units"] = self.attrs["units"].decode()
except AttributeError:
pass # already a string, not bytes
return self.attrs["units"]
return None
@units.setter
def units(self, value):
"""Set units."""
if value is None:
if "units" in self.attrs.keys():
self.attrs.pop("units")
else:
try:
self.attrs["units"] = value
except AttributeError:
self.attrs["units"] = value
def argmax(self):
"""Index of the maximum, ignorning nans."""
if "argmax" not in self.attrs.keys():
def f(dataset, s):
arr = dataset[s]
try:
amin = np.nanargmax(arr)
except ValueError:
amin = 0
idx = np.unravel_index(amin, arr.shape)
val = arr[idx]
return (tuple(i + (ss.start if ss.start else 0) for i, ss in zip(idx, s)), val)
chunk_res = self.chunkwise(f)
idxs = [i[0] for i in chunk_res.values()]
vals = [i[1] for i in chunk_res.values()]
self.attrs["argmax"] = idxs[np.nanargmax(vals)]
return tuple(self.attrs["argmax"])
def argmin(self):
"""Index of the minimum, ignoring nans."""
if "argmin" not in self.attrs.keys():
def f(dataset, s):
arr = dataset[s]
try:
amin = np.nanargmin(arr)
except ValueError:
amin = 0
idx = np.unravel_index(amin, arr.shape)
val = arr[idx]
return (tuple(i + (ss.start if ss.start else 0) for i, ss in zip(idx, s)), val)
chunk_res = self.chunkwise(f)
idxs = [i[0] for i in chunk_res.values()]
vals = [i[1] for i in chunk_res.values()]
self.attrs["argmin"] = idxs[np.nanargmin(vals)]
return tuple(self.attrs["argmin"])
def chunkwise(self, func, *args, **kwargs):
"""Execute a function for each chunk in the dataset.
Order of excecution is not guaranteed.
Parameters
----------
func : function
Function to execute. First two arguments must be dataset,
slices.
args (optional)
Additional (unchanging) arguments passed to func.
kwargs (optional)
Additional (unchanging) keyword arguments passed to func.
Returns
-------
collections OrderedDict
Dictionary of index: function output. Index is to lowest corner
of each chunk.
"""
out = collections.OrderedDict()
for s in self.slices():
key = tuple(sss.start for sss in s)
out[key] = func(self, s, *args, **kwargs)
self._clear_array_attributes_cache()
return out
def clip(self, min=None, max=None, replace=np.nan):
"""Clip values outside of a defined range.
Parameters
----------
min : number (optional)
New channel minimum. Default is None.
max : number (optional)
New channel maximum. Default is None.
replace : number or 'value' (optional)
Replace behavior. Default is nan.
"""
if max is None:
max = self.max()
if min is None:
min = self.min()
def f(dataset, s, min, max, replace):
if hasattr(min, "shape"):
min = min[wt_kit.valid_index(s, min.shape)]
if hasattr(max, "shape"):
max = max[wt_kit.valid_index(s, max.shape)]
if hasattr(replace, "shape"):
replace = replace[wt_kit.valid_index(s, replace.shape)]
arr = dataset[s]
if replace == "value":
dataset[s] = np.clip(arr, min, max)
else:
arr[arr < min] = replace
arr[arr > max] = replace
dataset[s] = arr
self.chunkwise(f, min=min, max=max, replace=replace)
def convert(self, destination_units):
"""Convert units.
Parameters
----------
destination_units : string (optional)
Units to convert into.
"""
if not wt_units.is_valid_conversion(self.units, destination_units):
kind = wt_units.kind(self.units)
valid = list(wt_units.dicts[kind].keys())
raise wt_exceptions.UnitsError(valid, destination_units)
if self.units is None:
return
def f(dataset, s, destination_units):
dataset[s] = wt_units.converter(dataset[s], dataset.units, destination_units)
self.chunkwise(f, destination_units=destination_units)
self.units = destination_units
def log(self, base=np.e, floor=None):
"""Take the log of the entire dataset.
Parameters
----------
base : number (optional)
Base of log. Default is e.
floor : number (optional)
Clip values below floor after log. Default is None.
"""
def f(dataset, s, base, floor):
arr = dataset[s]
arr = np.log(arr)
if base != np.e:
arr /= np.log(base)
if floor is not None:
arr[arr < floor] = floor
dataset[s] = arr
self.chunkwise(f, base=base, floor=floor)
def log10(self, floor=None):
"""Take the log base 10 of the entire dataset.
Parameters
----------
floor : number (optional)
Clip values below floor after log. Default is None.
"""
def f(dataset, s, floor):
arr = dataset[s]
arr = np.log10(arr)
if floor is not None:
arr[arr < floor] = floor
dataset[s] = arr
self.chunkwise(f, floor=floor)
def log2(self, floor=None):
"""Take the log base 2 of the entire dataset.
Parameters
----------
floor : number (optional)
Clip values below floor after log. Default is None.
"""
def f(dataset, s, floor):
arr = dataset[s]
arr = np.log2(arr)
if floor is not None:
arr[arr < floor] = floor
dataset[s] = arr
self.chunkwise(f, floor=floor)
def max(self):
"""Maximum, ignorning nans."""
if "max" not in self.attrs.keys():
def f(dataset, s):
return np.nanmax(dataset[s])
self.attrs["max"] = np.nanmax(list(self.chunkwise(f).values()))
return self.attrs["max"]
def min(self):
"""Minimum, ignoring nans."""
if "min" not in self.attrs.keys():
def f(dataset, s):
return np.nanmin(dataset[s])
self.attrs["min"] = np.nanmin(list(self.chunkwise(f).values()))
return self.attrs["min"]
def slices(self):
"""Returns a generator yielding tuple of slice objects.
Order is not guaranteed.
"""
if self.chunks is None:
yield tuple(slice(None, s) for s in self.shape)
else:
ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))
for idx in np.ndindex(ceilings): # could also use itertools.product
out = []
for i, c, s in zip(idx, self.chunks, self.shape):
start = i * c
stop = min(start + c, s + 1)
out.append(slice(start, stop, 1))
yield tuple(out)
def symmetric_root(self, root=2):
def f(dataset, s, root):
dataset[s] = np.sign(dataset[s]) * (np.abs(dataset[s]) ** (1 / root))
self.chunkwise(f, root=root)