File: test_fitter.py

package info (click to toggle)
python-sidpy 0.12.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 21,988 kB
  • sloc: python: 11,456; makefile: 17
file content (480 lines) | stat: -rw-r--r-- 23,206 bytes parent folder | download
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import sys
import unittest
import numpy as np

sys.path.insert(0, "../../sidpy/")

from sidpy.proc.fitter import SidFitter
from sidpy import Dataset, Dimension, DataType
import sidpy as sid
from ..sid.test_dataset import validate_dataset_properties
import inspect


class Test_3Ddset_1Dfit(unittest.TestCase):
    def setUp(self):
        self.data_set_3D, self.xvec = make_3D_dataset(shape=(3, 4, 7))
        fitter = SidFitter(self.data_set_3D, xvec=self.xvec,
                           fit_fn=return_quad, guess_fn=guess_quad, num_workers=3,
                           threads=2, return_cov=True, return_fit=True, return_std=True,
                           km_guess=True, n_clus=3)

        lb, ub = [-50, -50, -50], [50, 50, 50]
        self.fit_results = fitter.do_fit(bounds=(lb, ub), maxfev=20)

        self.metadata = self.data_set_3D.metadata.copy()
        fit_parms_dict = {'fit_parameters_labels': None,
                          'fitting_function': inspect.getsource(return_quad),
                          'guess_function': inspect.getsource(guess_quad),
                          'ind_dims': (0, 1)
                          }
        self.metadata['fit_parms_dict'] = fit_parms_dict

    def test_num_fitter_outputs(self):
        self.assertEqual(len(self.fit_results), 4)  # add assertion here

    def test_fit_parms_dset(self):
        # First dataset would be the fitting parameters dataset
        self.assertEqual(self.fit_results[0].shape, (3, 4, 3))
        ## Getting the dimension dict
        dim_dict = {0: self.data_set_3D._axes[0].copy(), 1: self.data_set_3D._axes[1].copy(),
                    2: Dimension(np.arange(3),
                                 name='fit_parms', units='a.u.',
                                 quantity='fit_parameters',
                                 dimension_type='temporal')}

        validate_dataset_properties(self, self.fit_results[0], np.array(self.fit_results[0]),
                                    title='Fitting_Map', data_type=DataType.IMAGE_STACK,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_3D.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_cov_dset(self):
        # Second dataset is the covariance dataset
        self.assertEqual(self.fit_results[1].shape, (3, 4, 3, 3))
        ## Getting the dim_dict
        dim_dict = {0: self.data_set_3D._axes[0].copy(), 1: self.data_set_3D._axes[1].copy(),
                    2: Dimension(np.arange(3),
                                 name='fit_cov_parms_x', units='a.u.',
                                 quantity='fit_cov_parameters',
                                 dimension_type='spectral'),
                    3: Dimension(np.arange(3),
                                 name='fit_cov_parms_y', units='a.u.',
                                 quantity='fit_cov_parameters',
                                 dimension_type='spectral')
                    }

        validate_dataset_properties(self, self.fit_results[1], np.array(self.fit_results[1]),
                                    title='Fitting_Map_Covariance', data_type=DataType.IMAGE_4D,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_3D.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_std_dev_dset(self):
        # Third dataset is the std_dev dataset
        self.assertEqual(self.fit_results[2].shape, (3, 4, 3))
        ## Getting the dim_dict
        dim_dict = {0: self.data_set_3D._axes[0].copy(), 1: self.data_set_3D._axes[1].copy(),
                    2: Dimension(np.arange(3),
                                 name='std_dev', units='a.u.',
                                 quantity='std_dev_fit_parms',
                                 dimension_type='temporal')}
        validate_dataset_properties(self, self.fit_results[2], np.array(self.fit_results[2]),
                                    title='Fitting_Map_std_dev', data_type=DataType.IMAGE_STACK,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_3D.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_fitted_dset(self):
        # Fourth dataset is the fitted dataset
        self.assertEqual(self.fit_results[3].shape, self.data_set_3D.shape)
        validate_dataset_properties(self, self.fit_results[3], np.array(self.fit_results[3]),
                                    title='fitted_' + self.data_set_3D.title, data_type=self.data_set_3D.data_type,
                                    quantity=self.data_set_3D.quantity, modality=self.data_set_3D.modality,
                                    units=self.data_set_3D.units, source=self.data_set_3D.source,
                                    dimension_dict=self.data_set_3D._axes,
                                    original_metadata=self.data_set_3D.original_metadata,
                                    metadata=self.metadata)


class Test_4Ddset_2Dfit(unittest.TestCase):
    def setUp(self):
        self.data_set_4D, self.xyvec = make_4D_dataset(shape=(3, 5, 9, 13))
        # Here we don't provide the xyvec as the input, we let the class figure it
        fitter = SidFitter(self.data_set_4D, fit_fn=gauss_2D, num_workers=8, num_fit_parms=5,
                           threads=2, return_std=True, return_fit=True,
                           km_guess=True, n_clus=4,
                           fit_parameter_labels=['amplitude', 'x', 'y', 'sigma', 'offset'])

        self.fit_results = fitter.do_fit(maxfev=100)

        self.metadata = self.data_set_4D.metadata.copy()
        fit_parms_dict = {'fit_parameters_labels': ['amplitude', 'x', 'y', 'sigma', 'offset'],
                          'fitting_function': inspect.getsource(gauss_2D),
                          'guess_function': 'Not Provided',
                          'ind_dims': (0, 1)
                          }
        self.metadata['fit_parms_dict'] = fit_parms_dict

    def test_num_fitter_outputs(self):
        self.assertEqual(len(self.fit_results), 3)  # add assertion here

    def test_fit_parms_dset(self):
        # First dataset would be the fitting parameters dataset
        self.assertEqual(self.fit_results[0].shape, (3, 5, 5))
        ## Getting the dimension dict
        dim_dict = {0: self.data_set_4D._axes[0].copy(), 1: self.data_set_4D._axes[1].copy(),
                    2: Dimension(np.arange(5),
                                 name='fit_parms', units='a.u.',
                                 quantity='fit_parameters',
                                 dimension_type='temporal')}

        validate_dataset_properties(self, self.fit_results[0], np.array(self.fit_results[0]),
                                    title='Fitting_Map', data_type=DataType.IMAGE_STACK,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_4D.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_std_dev_dset(self):
        # Third dataset is the std_dev dataset
        self.assertEqual(self.fit_results[1].shape, (3, 5, 5))
        ## Getting the dim_dict
        dim_dict = {0: self.data_set_4D._axes[0].copy(), 1: self.data_set_4D._axes[1].copy(),
                    2: Dimension(np.arange(5),
                                 name='std_dev', units='a.u.',
                                 quantity='std_dev_fit_parms',
                                 dimension_type='temporal')}
        validate_dataset_properties(self, self.fit_results[1], np.array(self.fit_results[1]),
                                    title='Fitting_Map_std_dev', data_type=DataType.IMAGE_STACK,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_4D.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_fitted_dset(self):
        # Fourth dataset is the fitted dataset
        self.assertEqual(self.fit_results[2].shape, self.data_set_4D.shape)
        validate_dataset_properties(self, self.fit_results[2], np.array(self.fit_results[2]),
                                    title='fitted_' + self.data_set_4D.title, data_type=self.data_set_4D.data_type,
                                    quantity=self.data_set_4D.quantity, modality=self.data_set_4D.modality,
                                    units=self.data_set_4D.units, source=self.data_set_4D.source,
                                    dimension_dict=self.data_set_4D._axes,
                                    original_metadata=self.data_set_4D.original_metadata,
                                    metadata=self.metadata)


class Test_4Ddset_1Dfit(unittest.TestCase):
    def setUp(self):
        self.data_set_cycles, self.xvec = make_3D_dataset(shape=(2, 2, 16), cycles=3)
        fitter = SidFitter(self.data_set_cycles, xvec=self.xvec,
                           fit_fn=return_quad, guess_fn=guess_quad, num_workers=8,
                           threads=2, return_cov=True, return_fit=True, return_std=True,
                           km_guess=True, n_clus=4, ind_dims=[0, 1, 3])

        lb, ub = [-50, -50, -50], [50, 50, 50]
        self.fit_results = fitter.do_fit(bounds=(lb, ub), maxfev=10)

        self.metadata = self.data_set_cycles.metadata.copy()
        fit_parms_dict = {'fit_parameters_labels': None,
                          'fitting_function': inspect.getsource(return_quad),
                          'guess_function': inspect.getsource(guess_quad),
                          'ind_dims': (0, 1, 3)
                          }
        self.metadata['fit_parms_dict'] = fit_parms_dict

    def test_num_fitter_outputs(self):
        self.assertEqual(len(self.fit_results), 4)  # add assertion here

    def test_fit_parms_dset(self):
        # First dataset would be the fitting parameters dataset
        self.assertEqual(self.fit_results[0].shape, (2, 2, 3, 3))
        ## Getting the dimension dict
        dim_dict = {0: self.data_set_cycles._axes[0].copy(), 1: self.data_set_cycles._axes[1].copy(),
                    2: self.data_set_cycles._axes[3].copy(),
                    3: Dimension(np.arange(3),
                                 name='fit_parms', units='a.u.',
                                 quantity='fit_parameters',
                                 dimension_type='temporal')}

        validate_dataset_properties(self, self.fit_results[0], np.array(self.fit_results[0]),
                                    title='Fitting_Map', data_type=DataType.IMAGE_STACK,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_cycles.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_cov_dset(self):
        # Second dataset is the covariance dataset
        self.assertEqual(self.fit_results[1].shape, (2, 2, 3, 3, 3))
        ## Getting the dim_dict
        dim_dict = {0: self.data_set_cycles._axes[0].copy(), 1: self.data_set_cycles._axes[1].copy(),
                    2: self.data_set_cycles._axes[3].copy(),
                    3: Dimension(np.arange(3),
                                 name='fit_cov_parms_x', units='a.u.',
                                 quantity='fit_cov_parameters',
                                 dimension_type='spectral'),
                    4: Dimension(np.arange(3),
                                 name='fit_cov_parms_y', units='a.u.',
                                 quantity='fit_cov_parameters',
                                 dimension_type='spectral')
                    }

        validate_dataset_properties(self, self.fit_results[1], np.array(self.fit_results[1]),
                                    title='Fitting_Map_Covariance', data_type=DataType.IMAGE_4D,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_cycles.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_std_dev_dset(self):
        # Third dataset is the std_dev dataset
        self.assertEqual(self.fit_results[2].shape, (2, 2, 3, 3))
        ## Getting the dim_dict
        dim_dict = {0: self.data_set_cycles._axes[0].copy(), 1: self.data_set_cycles._axes[1].copy(),
                    2: self.data_set_cycles._axes[3].copy(),
                    3: Dimension(np.arange(3),
                                 name='std_dev', units='a.u.',
                                 quantity='std_dev_fit_parms',
                                 dimension_type='temporal')}
        validate_dataset_properties(self, self.fit_results[2], np.array(self.fit_results[2]),
                                    title='Fitting_Map_std_dev', data_type=DataType.IMAGE_STACK,
                                    dimension_dict=dim_dict,
                                    original_metadata=self.data_set_cycles.original_metadata.copy(),
                                    metadata=self.metadata)

    def test_fitted_dset(self):
        # Fourth dataset is the fitted dataset
        shape = [self.data_set_cycles.shape[i] for i in [0, 1, 3, 2]]
        self.assertEqual(self.fit_results[3].shape, self.data_set_cycles.shape)
        validate_dataset_properties(self, self.fit_results[3], np.array(self.fit_results[3]),
                                    title='fitted_' + self.data_set_cycles.title,
                                    data_type=self.data_set_cycles.data_type,
                                    quantity=self.data_set_cycles.quantity, modality=self.data_set_cycles.modality,
                                    units=self.data_set_cycles.units, source=self.data_set_cycles.source,
                                    dimension_dict=self.data_set_cycles._axes,
                                    original_metadata=self.data_set_cycles.original_metadata,
                                    metadata=self.metadata)


# The following functions are used to generate datasets
def return_quad(x, *parms):
    a, b, c, = parms
    return a * x ** 2 + b * x + c


def guess_quad(xvec, yvec):
    popt = np.polyfit(xvec, yvec, 2)
    return popt


def make_3D_dataset(shape=(60, 60, 32), cycles=1):
    data_mat = np.zeros(shape=(shape[0], shape[1], shape[2], cycles))
    xvec = np.linspace(0, 5, shape[-1])

    for row in range(data_mat.shape[0]):
        for col in range(data_mat.shape[1]):
            for cycle in range(cycles):
                if row ** 2 + col ** 2 < data_mat.shape[0] * data_mat.shape[1] / 3:
                    a = np.random.normal(loc=3.0, scale=0.4)
                    b = np.random.normal(loc=1.0, scale=2.4)
                    c = np.random.normal(loc=0.5, scale=1.0)
                else:
                    a = np.random.normal(loc=1.0, scale=0.8)
                    b = np.random.normal(loc=0.0, scale=1.4)
                    c = np.random.normal(loc=-0.5, scale=1.3)
                data_mat[row, col, :, cycle] = return_quad(xvec, *[a, b, c]) + 2.5 * np.random.normal(size=len(xvec))

    data_mat = np.squeeze(data_mat)
    parms_dict = {'info_1': np.linspace(0, 1, 100), 'instrument': 'perseverence rover AFM'}

    # Let's convert it to a sidpy dataset

    # Specify dimensions
    x_dim = np.linspace(0, 1E-6,
                        data_mat.shape[0])
    y_dim = np.linspace(0, 1E-6,
                        data_mat.shape[1])

    z_dim = xvec

    # Make a sidpy dataset
    data_set = sid.Dataset.from_array(data_mat, title='Current_spectral_map')

    # Set the data type
    data_set.data_type = sid.DataType.SPECTRAL_IMAGE

    # Add quantity and units
    data_set.units = 'nA'
    data_set.quantity = 'Current'

    # Add dimension info
    data_set.set_dimension(0, sid.Dimension(x_dim,
                                            name='x',
                                            units='m', quantity='x',
                                            dimension_type='spatial'))
    data_set.set_dimension(1, sid.Dimension(y_dim,
                                            name='y',
                                            units='m', quantity='y',
                                            dimension_type='spatial'))

    data_set.set_dimension(2, sid.Dimension(z_dim,
                                            name='Voltage',
                                            units='V', quantity='Voltage',
                                            dimension_type='spectral'))
    if cycles > 1:
        cycles_dim = np.arange(cycles)
        data_set.set_dimension(3, sid.Dimension(cycles_dim,
                                                name='Cycle',
                                                units='#', quantity='Cycle',
                                                dimension_type='spectral'))

    # append metadata
    data_set.metadata = parms_dict

    return data_set, xvec


def gauss_2D(fitting_space, *parms):
    x = fitting_space[0]
    y = fitting_space[1]
    amplitude, xo, yo, sigma, offset = parms
    xo = float(xo)
    yo = float(yo)
    r = ((x - xo) ** 2 + (y - yo) ** 2) ** .5
    g = amplitude * np.exp(-(r / sigma) ** 2) + offset

    return g.ravel()


def make_4D_dataset(shape=(32, 16, 64, 48)):
    dataset = np.zeros(shape=shape, dtype=np.float64)
    xlen, ylen, kxlen, kylen = shape
    kx, ky = np.meshgrid(np.linspace(0, 11, kxlen), np.linspace(0, 7, kylen), indexing='ij')
    true_parms = np.zeros((dataset.shape[0], dataset.shape[1], 5))

    for row in range(xlen):
        for col in range(ylen):
            amp = np.sqrt(row * col // xlen * ylen) + 3.5
            sigma = np.random.normal(loc=2.5, scale=0.34)
            offset = 0.1  # col
            xo = np.random.uniform(low=0, high=6)
            yo = np.random.uniform(low=0, high=5)
            cur_parms = [amp, xo, yo, sigma, offset]
            true_parms[row, col, :] = cur_parms
            # amplitude, xo, yo, sigma, offset
            gauss_mat = gauss_2D([kx.ravel(), ky.ravel()], *cur_parms)
            gauss_mat += np.mean(gauss_mat) / 2 * np.random.normal(size=len(gauss_mat))
            gauss_mat = gauss_mat.reshape([kxlen, kylen])
            dataset[row, col, :, :] = gauss_mat

    # Now make it a sidpy dataset
    parms_dict = {'info_1': np.linspace(0, 5.6, 30), 'instrument': 'opportunity rover AFM'}

    # Let's convert it to a sidpy dataset
    # Specify dimensions
    x_dim = np.linspace(0, 1E-6,
                        dataset.shape[0])
    y_dim = np.linspace(0, 2E-6,
                        dataset.shape[1])
    kx_dim = np.linspace(0, 11, kxlen)
    ky_dim = np.linspace(0, 5, kylen)

    # Make a sidpy dataset
    data_set = sid.Dataset.from_array(dataset, name='4D_STEM')

    # Set the data type
    data_set.data_type = sid.DataType.IMAGE_4D

    # Add quantity and units
    data_set.units = 'nA'
    data_set.quantity = 'Current'

    # Add dimension info
    data_set.set_dimension(0, sid.Dimension(x_dim,
                                            name='x',
                                            units='m', quantity='x',
                                            dimension_type='spatial'))
    data_set.set_dimension(1, sid.Dimension(y_dim,
                                            name='y',
                                            units='m', quantity='y',
                                            dimension_type='spatial'))
    data_set.set_dimension(2, sid.Dimension(kx_dim,
                                            name='Intensity KX',
                                            units='counts', quantity='Intensity',
                                            dimension_type='spectral'))
    data_set.set_dimension(3, sid.Dimension(ky_dim,
                                            name='Intensity KY',
                                            units='counts', quantity='Intensity',
                                            dimension_type='spectral'))

    # append metadata
    data_set.metadata = parms_dict

    return data_set, [kx.ravel(), ky.ravel()]

def make_4D_dataset_spectral_image(shape=(32, 16, 64, 48)):
    dataset = np.zeros(shape=shape, dtype=np.float64)
    xlen, ylen, kxlen, kylen = shape
    kx, ky = np.meshgrid(np.linspace(0, 11, kxlen), np.linspace(0, 7, kylen), indexing='ij')
    true_parms = np.zeros((dataset.shape[0], dataset.shape[1], 5))

    for row in range(xlen):
        for col in range(ylen):
            amp = np.sqrt(row * col // xlen * ylen) + 3.5
            sigma = np.random.normal(loc=2.5, scale=0.34)
            offset = 0.1  # col
            xo = np.random.uniform(low=0, high=6)
            yo = np.random.uniform(low=0, high=5)
            cur_parms = [amp, xo, yo, sigma, offset]
            true_parms[row, col, :] = cur_parms
            # amplitude, xo, yo, sigma, offset
            gauss_mat = gauss_2D([kx.ravel(), ky.ravel()], *cur_parms)
            gauss_mat += np.mean(gauss_mat) / 2 * np.random.normal(size=len(gauss_mat))
            gauss_mat = gauss_mat.reshape([kxlen, kylen])
            dataset[row, col, :, :] = gauss_mat

    # Now make it a sidpy dataset
    parms_dict = {'info_1': np.linspace(0, 5.6, 30), 'instrument': 'opportunity rover AFM'}

    # Let's convert it to a sidpy dataset
    # Specify dimensions
    x_dim = np.linspace(0, 1E-6,
                        dataset.shape[0])
    y_dim = np.linspace(0, 2E-6,
                        dataset.shape[1])
    kx_dim = np.linspace(0, 11, kxlen)
    ky_dim = np.linspace(0, 5, kylen)

    # Make a sidpy dataset
    data_set = sid.Dataset.from_array(dataset)

    # Set the data type
    data_set.data_type = sid.DataType.SPECTRAL_IMAGE

    # Add quantity and units
    data_set.units = 'nA'
    data_set.quantity = 'Current'

    # Add dimension info
    data_set.set_dimension(0, sid.Dimension(x_dim,
                                            name='x',
                                            units='m', quantity='x',
                                            dimension_type='spatial'))
    data_set.set_dimension(1, sid.Dimension(y_dim,
                                            name='y',
                                            units='m', quantity='y',
                                            dimension_type='spatial'))
    data_set.set_dimension(2, sid.Dimension(kx_dim,
                                            name='Intensity KX',
                                            units='counts', quantity='Intensity',
                                            dimension_type='spectral'))
    data_set.set_dimension(3, sid.Dimension(ky_dim,
                                            name='Intensity KY',
                                            units='counts', quantity='Intensity',
                                            dimension_type='channel'))

    # append metadata
    data_set.metadata = parms_dict

    return data_set, [kx.ravel(), ky.ravel()]


if __name__ == '__main__':
    unittest.main()