forked from joleroi/nddata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nddata.py
269 lines (209 loc) · 7.16 KB
/
nddata.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
"""Scratch for NDDataArray class"""
import numpy as np
from astropy.units import Quantity, Unit
from astropy.table import Table, Column
import IPython
class NDDataArray(object):
"""ND Data Array
This class represents an ND Data Array. The data stored as numpy array
attribute. The data axis are separate classes and this class has them as
members. The axis order follows numpy convention for arrays, i.e. the axis
added last is at index 0. For an example see NDData_demo.ipynb.
"""
def __init__(self):
self._axes = list()
self._data = None
def add_axis(self, axis):
"""Add axis
This data array is set to None to avoid unwanted behaviour.
Parameters
----------
axis : `DataAxis`
axis
"""
default_names = {0: 'x', 1: 'y', 2: 'z'}
if axis.name is None:
axis.name = default_names[self.dim]
self._axes = [axis] + self._axes
# Quick solution: delete data to prevent unwanted behaviour
self._data = None
@property
def axes(self):
"""Array holding all axes"""
return self._axes
@property
def data(self):
"""Array holding the ND data"""
return self._data
@data.setter
def data(self, data):
"""Set data
Some sanitiy checks are performed to avoid an invalid array
Parameters
----------
data : np.array
Data array
"""
data = np.array(data)
d = len(data.shape)
if d != self.dim:
raise ValueError('Overall dimensions to not match. '
'Data: {}, Hist: {}'.format(d, self.dim))
for dim in np.arange(self.dim):
if self.axes[dim].nbins != data.shape[dim]:
a = self.axes[dim]
raise ValueError('Data shape does not match in dimension {d}\n'
'Axis "{n}": {sa}, Data {sd}'.format(
d=dim, n=a.name, sa=a.nbins,
sd=data.shape[dim]))
self._data = data
@property
def axis_names(self):
"""Currently set axis names"""
return [a.name for a in self.axes]
def get_axis_index(self, name):
"""Return axis index by it name
Parameters
----------
name : str
Valid axis name
"""
for a in self.axes:
if a.name == name:
return self.axes.index(a)
raise ValueError("No axis with name {}".format(name))
def get_axis(self, name):
"""Return axis by it name
Parameters
----------
name : str
Valid axis name
"""
idx = self.get_axis_index(name)
return self.axes[idx]
@property
def dim(self):
"""Dimension (number of axes)"""
return len(self.axes)
def to_table(self):
"""Convert to astropy.Table"""
# This can be used as starting point for FITS serialization
# http://docs.astropy.org/en/stable/io/unified.html
cols = [Column(data=[a.value], unit=a.unit) for a in self.axes]
cols.append(Column(data=[self.data], name='data'))
t = Table(cols)
return t
def __str__(self):
"""String representation"""
return str(self.to_table())
def find_node(self, **kwargs):
"""Find nearest node
Parameters
----------
kwargs : dict
Search values
"""
for key in kwargs.keys():
if key not in self.axis_names:
raise ValueError('No axis for key {}'.format(key))
for name, val in zip(self.axis_names, self.axes):
kwargs.setdefault(name, val.nodes)
nodes = list()
for a in self.axes:
value = kwargs[a.name]
nodes.append(a.find_node(value))
return nodes
def evaluate(self, **kwargs):
"""Evaluate NDData Array
No interpolation
Parameters
----------
kwargs : dict
Axis names are keys, Quantity array are values
"""
idx = self.find_node(**kwargs)
data = self.data
for i in np.arange(self.dim):
data = np.take(data, idx[i], axis=i)
return data
def plot_image(self, ax=None, plot_kwargs = {}, **kwargs):
"""Plot image
Only avalable for 2D (after slicing)
"""
import matplotlib.pyplot as plt
ax = plt.gca() if ax is None else ax
data = self.evaluate(**kwargs)
if len(data.squeeze().shape) != 2:
raise ValueError('Data has shape {} after slicing. '
'Need 2d data for image plot'.format(data.shape))
ax.set_xlabel('{} [{}]'.format(self.axes[0].name, self.axes[0].unit))
ax.set_ylabel('{} [{}]'.format(self.axes[1].name, self.axes[1].unit))
ax.imshow(data.transpose(), origin='lower', **plot_kwargs)
def plot_profile(self, axis, ax=None, **kwargs):
"""Show data as function of one axis
Parameters
----------
axis : DataAxis
data axis to use
"""
raise NotImplementedError
import matplotlib.pyplot as plt
ax = plt.gca() if ax is None else ax
ax_ind = self.get_axis_index(axis)
kwargs.setdefault(axis, self.axes[ax_ind])
x = kwargs.pop(axis)
y = self.evaluate(**kwargs)
class DataAxis(Quantity):
def __new__(cls, energy, unit=None, dtype=None, copy=True, name=None):
self = super(DataAxis, cls).__new__(cls, energy, unit,
dtype=dtype, copy=copy)
self.name = name
return self
def __array_finalize__(self, obj):
super(DataAxis, self).__array_finalize__(obj)
def find_node(self, val):
"""Find next node
Parameters
----------
val : `~astropy.units.Quantity`
Lookup value
"""
val = Quantity(val)
if not val.unit.is_equivalent(self.unit):
raise ValueError('Units {} and {} do not match'.format(
val.unit, self.unit))
val = val.to(self.unit)
val = np.atleast_1d(val)
x1 = np.array([val] * self.nbins).transpose()
x2 = np.array([self.nodes] * len(val))
temp = np.abs(x1 - x2)
idx = np.argmin(temp, axis=1)
return idx
@property
def nbins(self):
"""Number of bins"""
return self.size
@property
def nodes(self):
"""Evaluation nodes"""
return self
class BinnedDataAxis(DataAxis):
@classmethod
def linspace(cls, min, max, nbins, unit=None):
"""Create linearly spaced axis"""
if unit is None:
raise NotImplementedError
data = np.linspace(min, max, nbins+1)
unit = Unit(unit)
return cls(data, unit)
@property
def nbins(self):
"""Number of bins"""
return self.size - 1
@property
def nodes(self):
"""Evaluation nodes"""
return self.lin_center()
def lin_center(self):
"""Linear bin centers"""
return DataAxis(self[:-1] + self[1:]) / 2