File: test_analysis_functions.py

package info (click to toggle)
spectral-cube 0.6.6-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,136 kB
  • sloc: python: 13,236; makefile: 154
file content (421 lines) | stat: -rw-r--r-- 13,651 bytes parent folder | download | duplicates (2)
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

import pytest
import warnings
import numpy as np
import astropy.units as u
# from astropy.modeling import models, fitting

from ..analysis_utilities import stack_spectra, fourier_shift, stack_cube
from .utilities import generate_gaussian_cube, gaussian
from ..utils import BadVelocitiesWarning

def test_shift():

    amp = 1
    v0 = 0 * u.m / u.s
    sigma = 8
    spectral_axis = np.arange(-50, 51) * u.m / u.s

    true_spectrum = gaussian(spectral_axis.value,
                             amp, v0.value, sigma)

    # Shift is an integer, so rolling is equivalent
    rolled_spectrum = np.roll(true_spectrum, 10)

    shift_spectrum = fourier_shift(true_spectrum, 10)

    np.testing.assert_allclose(shift_spectrum,
                               rolled_spectrum,
                               rtol=1e-4)

    # With part masked
    masked_spectrum = true_spectrum.copy()
    mask = np.abs(spectral_axis.value) <= 30
    masked_spectrum[~mask] = np.nan

    rolled_mask = np.roll(mask, 10)
    rolled_masked_spectrum = rolled_spectrum.copy()
    rolled_masked_spectrum[~rolled_mask] = np.nan

    shift_spectrum = fourier_shift(masked_spectrum, 10)

    np.testing.assert_allclose(shift_spectrum,
                               rolled_masked_spectrum,
                               rtol=1e-4)


def test_stacking(use_dask):
    '''
    Use a set of identical Gaussian profiles randomly offset to ensure the
    shifted spectrum has the correct properties.
    '''

    amp = 1.
    v0 = 0. * u.km / u.s
    sigma = 8.
    noise = None
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(amp=amp, sigma=sigma, noise=noise,
                               shape=shape, use_dask=use_dask)

    true_spectrum = gaussian(test_cube.spectral_axis.value,
                             amp, v0.value, sigma)

    # Stack the spectra in the cube
    stacked = \
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False, pad_edges=False)

    # Calculate residuals
    resid = np.abs(stacked.value - true_spectrum)
    assert np.std(resid) <= 1e-3

    # Now fit a Gaussian to the mean stacked profile.
    # fit_vals = fit_gaussian(stacked.spectral_axis.value, stacked.value)[0]

    # np.testing.assert_allclose(fit_vals, np.array([amp, v0.value, sigma]),
    #                            atol=1e-3)

    # The stacked spectrum should have the same spectral axis
    np.testing.assert_allclose(stacked.spectral_axis.value,
                               test_cube.spectral_axis.value)


def test_cube_stacking(use_dask):
    '''
    Test passing a list of cubes

    This test simply averages two copies of the same thing.

    A more thorough test might be to verify that cubes with different frequency
    supports also yield good results.
    '''

    amp = 1.
    sigma = 8.
    noise = None
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(amp=amp, sigma=sigma, noise=noise,
                               shape=shape, use_dask=use_dask)

    test_cube1 = test_cube.with_spectral_unit(u.GHz, rest_value=1*u.GHz, velocity_convention='radio')
    test_cube2 = test_cube.with_spectral_unit(u.GHz, rest_value=2*u.GHz, velocity_convention='radio')

    vmin = -10*u.km/u.s
    vmax = 10*u.km/u.s

    # Stack two cubes
    stacked = stack_cube([test_cube1, test_cube2], linelist=[1.,2.]*u.GHz,
                         vmin=vmin, vmax=vmax, average=np.nanmean,
                         convolve_beam=None, return_cutouts=False)

    np.testing.assert_allclose(stacked.filled_data[:],
                               test_cube.spectral_slab(vmin, vmax).filled_data[:])

    # Stack one cube with two frequencies, one that's out of band
    stacked = stack_cube(test_cube1, linelist=[1.,2.]*u.GHz,
                         vmin=vmin, vmax=vmax, average=np.nanmean,
                         convolve_beam=None, return_cutouts=False)

    np.testing.assert_allclose(stacked.filled_data[:],
                               test_cube.spectral_slab(vmin, vmax).filled_data[:])

    # TODO: add tests of multiple lines in the same cube
    # (this requires a different test cube setup)



def test_stacking_badvels(use_dask):
    '''
    Regression test for #493: don't include bad velocities when stacking
    '''

    amp = 1.
    v0 = 0. * u.km / u.s
    sigma = 8.
    noise = None
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(amp=amp, sigma=sigma, noise=noise,
                               shape=shape, use_dask=use_dask)

    true_spectrum = gaussian(test_cube.spectral_axis.value,
                             amp, v0.value, sigma)

    test_vels[12,11] = 500*u.km/u.s

    with pytest.warns(BadVelocitiesWarning,
                      match='Some velocities are outside the allowed range and will be'):
        # Stack the spectra in the cube
        stacked = \
            stack_spectra(test_cube, test_vels, v0=v0,
                          stack_function=np.nanmean,
                          xy_posns=None, num_cores=1,
                          chunk_size=-1,
                          progressbar=False, pad_edges=False)

    # Calculate residuals (the one bad value shouldn't have caused a problem)
    resid = np.abs(stacked.value - true_spectrum)
    assert np.std(resid) <= 1e-3


def test_stacking_reversed_specaxis(use_dask):
    '''
    Use a set of identical Gaussian profiles randomly offset to ensure the
    shifted spectrum has the correct properties.
    '''

    amp = 1.
    v0 = 0. * u.km / u.s
    sigma = 8.
    noise = None
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(amp=amp, sigma=sigma, noise=noise,
                               shape=shape, spec_scale=-1. * u.km / u.s, use_dask=use_dask)

    true_spectrum = gaussian(test_cube.spectral_axis.value,
                             amp, v0.value, sigma)

    # Stack the spectra in the cube
    stacked = \
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False, pad_edges=False)

    # Calculate residuals
    resid = np.abs(stacked.value - true_spectrum)
    assert np.std(resid) <= 1e-3

    # The stacked spectrum should have the same spectral axis
    np.testing.assert_allclose(stacked.spectral_axis.value,
                               test_cube.spectral_axis.value)


def test_stacking_wpadding(use_dask):
    '''
    Use a set of identical Gaussian profiles randomly offset to ensure the
    shifted spectrum has the correct properties.
    '''

    amp = 1.
    sigma = 8.
    v0 = 0. * u.km / u.s
    noise = None
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(shape=shape, amp=amp, sigma=sigma, noise=noise, use_dask=use_dask)

    # Stack the spectra in the cube
    stacked = \
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False, pad_edges=True)

    true_spectrum = gaussian(stacked.spectral_axis.value,
                             amp, v0.value, sigma)

    # Calculate residuals
    resid = np.abs(stacked.value - true_spectrum)
    assert np.std(resid) <= 1e-3

    # Now fit a Gaussian to the mean stacked profile.
    # fit_vals = fit_gaussian(stacked.spectral_axis.value, stacked.value)[0]

    # np.testing.assert_allclose(fit_vals, np.array([amp, 0.0, sigma]),
    #                            atol=1e-3)

    # The spectral axis should be padded by ~25% on each side
    stack_shape = int(test_cube.shape[0] * 1.5)
    # This is rounded, so the shape could be +/- 1
    assert (stacked.size == stack_shape) or (stacked.size == stack_shape - 1) \
        or (stacked.size == stack_shape + 1)


def test_padding_direction(use_dask):

    amp = 1.
    sigma = 8.
    v0 = 0. * u.km / u.s
    noise = None
    shape = (100, 2, 2)

    vel_surface = np.array([[0, 5], [5, 10]])

    test_cube, test_vels = \
        generate_gaussian_cube(shape=shape, amp=amp, sigma=sigma, noise=noise,
                               vel_surface=vel_surface, use_dask=use_dask)

    # Stack the spectra in the cube
    stacked = \
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False, pad_edges=True)

    true_spectrum = gaussian(stacked.spectral_axis.value,
                             amp, v0.value, sigma)

    # now check that the stacked spectral axis is right
    # (all shifts are negative, so vmin < -50 km/s, should be -60?)
    assert stacked.spectral_axis.min() == -60*u.km/u.s
    assert stacked.spectral_axis.max() == 49*u.km/u.s

    # Calculate residuals
    resid = np.abs(stacked.value - true_spectrum)
    assert np.std(resid) <= 1e-3


def test_stacking_woffset(use_dask):
    '''
    Use a set of identical Gaussian profiles randomly offset to ensure the
    shifted spectrum has the correct properties.

    Make sure the operations aren't affected by absolute velocity offsets

    '''

    amp = 1.
    sigma = 8.
    v0 = 100. * u.km / u.s
    noise = None
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(shape=shape, amp=amp, sigma=sigma, noise=noise,
                               v0=v0.value, use_dask=use_dask)

    # Stack the spectra in the cube
    stacked = \
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False, pad_edges=True)

    true_spectrum = gaussian(stacked.spectral_axis.value,
                             amp, v0.value, sigma)

    # Calculate residuals
    resid = np.abs(stacked.value - true_spectrum)
    assert np.std(resid) <= 1e-3

    # The spectral axis should be padded by ~25% on each side
    stack_shape = int(test_cube.shape[0] * 1.5)
    # This is rounded, so the shape could be +/- 1
    assert (stacked.size == stack_shape) or (stacked.size == stack_shape - 1) \
        or (stacked.size == stack_shape + 1)


def test_stacking_shape_failure(use_dask):
    """
    Regression test for #466
    """
    amp = 1.
    v0 = 0. * u.km / u.s
    sigma = 8.
    noise = None
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(amp=amp, sigma=sigma, noise=noise,
                               shape=shape, use_dask=use_dask)

    # make the test_vels array the wrong shape
    test_vels = test_vels[:-1, :-1]

    with pytest.raises(ValueError) as exc:
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False, pad_edges=False)

    assert 'Velocity surface map does not match' in exc.value.args[0]


    test_vels = np.ones(shape[1:], dtype='float') + np.nan

    with pytest.raises(ValueError) as exc:
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False, pad_edges=False)

    assert "velocity_surface contains no finite values" in exc.value.args[0]


def test_stacking_noisy(use_dask):

    # Test stack w/ S/N of 0.2
    # This is cheating b/c we know the correct peak velocities, but serves as
    # a good test that the stacking is working.

    amp = 1.
    sigma = 8.
    v0 = 0 * u.km / u.s
    noise = 5.0
    shape = (100, 25, 25)

    test_cube, test_vels = \
        generate_gaussian_cube(amp=amp, sigma=sigma, noise=noise,
                               shape=shape, use_dask=use_dask)

    # Stack the spectra in the cube
    stacked = \
        stack_spectra(test_cube, test_vels, v0=v0,
                      stack_function=np.nanmean,
                      xy_posns=None, num_cores=1,
                      chunk_size=-1,
                      progressbar=False,
                      pad_edges=True)

    true_spectrum = gaussian(stacked.spectral_axis.value,
                             amp, v0.value, sigma)

    # Calculate residuals
    resid = np.abs(stacked.value - true_spectrum)
    assert np.std(resid) <= noise / np.sqrt(shape[1] * shape[2])

    # Now fit a Gaussian to the mean stacked profile.
    # fit_vals, fit_errs = fit_gaussian(stacked.spectral_axis.value,
    #                                   stacked.value)

    # Check that the fit is consistent with the true values within 1-sigma err
    # for fit_val, fit_err, true_val in zip(fit_vals, fit_errs,
    #                                       [amp, v0.value, sigma]):
    #     np.testing.assert_allclose(fit_val, true_val,
    #                                atol=fit_err)


# def fit_gaussian(vels, data):
#     g_init = models.Gaussian1D()

#     fit_g = fitting.LevMarLSQFitter()

#     g_fit = fit_g(g_init, vels, data)

#     cov = fit_g.fit_info['param_cov']
#     if cov is None:
#         cov = np.zeros((3, 3)) * np.nan
#     parvals = g_fit.parameters

#     parerrs = np.sqrt(np.diag(cov))

#     return parvals, parerrs