/
test_spectral_cube.py
2248 lines (1645 loc) · 74.9 KB
/
test_spectral_cube.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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function, absolute_import, division
import re
import six
import operator
import itertools
import warnings
import mmap
from distutils.version import LooseVersion
import sys
import pytest
import astropy
from astropy.io import fits
from astropy import units as u
from astropy.wcs import WCS
from astropy.wcs import _wcs
from astropy.tests.helper import assert_quantity_allclose
from astropy.convolution import Gaussian2DKernel, Tophat2DKernel
import numpy as np
from .. import (SpectralCube, VaryingResolutionSpectralCube, BooleanArrayMask,
FunctionMask, LazyMask, CompositeMask)
from ..spectral_cube import (OneDSpectrum, Projection,
VaryingResolutionOneDSpectrum,
LowerDimensionalObject)
from ..np_compat import allbadtonan
from .. import spectral_axis
from .. import base_class
from .. import utils
from . import path
from .helpers import assert_allclose, assert_array_equal
try:
import casatools
ia = casatools.image()
casaOK = True
except ImportError:
try:
from taskinit import ia
casaOK = True
except ImportError:
casaOK = False
WINDOWS = sys.platform == "win32"
# needed to test for warnings later
warnings.simplefilter('always', UserWarning)
warnings.simplefilter('error', utils.UnsupportedIterationStrategyWarning)
warnings.simplefilter('error', utils.NotImplementedWarning)
warnings.simplefilter('error', utils.WCSMismatchWarning)
warnings.simplefilter('error', FutureWarning)
warnings.filterwarnings(action='ignore', category=FutureWarning,
module='reproject')
try:
import yt
YT_INSTALLED = True
YT_LT_301 = LooseVersion(yt.__version__) < LooseVersion('3.0.1')
except ImportError:
YT_INSTALLED = False
YT_LT_301 = False
try:
import scipy
scipyOK = True
except ImportError:
scipyOK = False
import os
# if ON_TRAVIS is set, we're on travis.
on_travis = bool(os.environ.get('ON_TRAVIS'))
from radio_beam import Beam, Beams
NUMPY_LT_19 = LooseVersion(np.__version__) < LooseVersion('1.9.0')
def cube_and_raw(filename):
p = path(filename)
if os.path.splitext(p)[-1] == '.fits':
with fits.open(p) as hdulist:
d = hdulist[0].data
c = SpectralCube.read(p, format='fits', mode='readonly')
elif os.path.splitext(p)[-1] == '.image':
ia.open(p)
d = ia.getchunk()
ia.unlock()
ia.close()
ia.done()
c = SpectralCube.read(p, format='casa_image')
else:
raise ValueError("Unsupported filetype")
return c, d
def test_arithmetic_warning(data_vda_jybeam_lower, recwarn):
cube, data = cube_and_raw(data_vda_jybeam_lower)
assert not cube._is_huge
# make sure the small cube raises a warning about loading into memory
cube + 5*cube.unit
w = recwarn.list[-1]
assert 'requires loading the entire cube into' in str(w.message)
def test_huge_disallowed(data_vda_jybeam_lower):
cube, data = cube_and_raw(data_vda_jybeam_lower)
assert not cube._is_huge
# We need to reduce the memory threshold rather than use a large cube to
# make sure we don't use too much memory during testing.
from .. import cube_utils
OLD_MEMORY_THRESHOLD = cube_utils.MEMORY_THRESHOLD
try:
cube_utils.MEMORY_THRESHOLD = 10
assert cube._is_huge
with pytest.raises(ValueError, match='entire cube into memory'):
cube + 5*cube.unit
with pytest.raises(ValueError, match='entire cube into memory'):
cube.max(how='cube')
cube.allow_huge_operations = True
# just make sure it doesn't fail
cube + 5*cube.unit
finally:
cube_utils.MEMORY_THRESHOLD = OLD_MEMORY_THRESHOLD
del cube
class BaseTest(object):
@pytest.fixture(autouse=True)
def setup_method_fixture(self, request, data_adv):
c, d = cube_and_raw(data_adv)
mask = BooleanArrayMask(d > 0.5, c._wcs)
c._mask = mask
self.c = c
self.mask = mask
self.d = d
class BaseTestMultiBeams(object):
@pytest.fixture(autouse=True)
def setup_method_fixture(self, request, data_adv_beams):
c, d = cube_and_raw(data_adv_beams)
mask = BooleanArrayMask(d > 0.5, c._wcs)
c._mask = mask
self.c = c
self.mask = mask
self.d = d
@pytest.fixture
def filename(request):
return request.getfixturevalue(request.param)
translist = [('data_advs', [0, 1, 2, 3]),
('data_dvsa', [2, 3, 0, 1]),
('data_sdav', [0, 2, 1, 3]),
('data_sadv', [0, 1, 2, 3]),
('data_vsad', [3, 0, 1, 2]),
('data_vad', [2, 0, 1]),
('data_vda', [0, 2, 1]),
('data_adv', [0, 1, 2]),
]
translist_vrsc = [('data_vda_beams', [0, 2, 1])]
class TestSpectralCube(object):
@pytest.mark.parametrize(('filename', 'trans'), translist + translist_vrsc,
indirect=['filename'])
def test_consistent_transposition(self, filename, trans):
"""data() should return velocity axis first, then world 1, then world 0"""
c, d = cube_and_raw(filename)
expected = np.squeeze(d.transpose(trans))
assert_allclose(c._get_filled_data(), expected)
@pytest.mark.parametrize(('filename', 'view'), (
('data_adv', np.s_[:, :,:]),
('data_adv', np.s_[::2, :, :2]),
('data_adv', np.s_[0]),
), indirect=['filename'])
def test_world(self, filename, view):
p = path(filename)
# d = fits.getdata(p)
# wcs = WCS(p)
# c = SpectralCube(d, wcs)
c = SpectralCube.read(p)
wcs = c.wcs
# shp = d.shape
# inds = np.indices(d.shape)
shp = c.shape
inds = np.indices(c.shape)
pix = np.column_stack([i.ravel() for i in inds[::-1]])
world = wcs.all_pix2world(pix, 0).T
world = [w.reshape(shp) for w in world]
world = [w[view] * u.Unit(wcs.wcs.cunit[i])
for i, w in enumerate(world)][::-1]
w2 = c.world[view]
for result, expected in zip(w2, world):
assert_allclose(result, expected)
# Test world_flattened here, too
w2_flat = c.flattened_world(view=view)
for result, expected in zip(w2_flat, world):
print(result.shape, expected.flatten().shape)
assert_allclose(result, expected.flatten())
@pytest.mark.parametrize('view', (np.s_[:, :,:],
np.s_[:2, :3, ::2]))
def test_world_transposes_3d(self, view, data_adv, data_vad):
c1, d1 = cube_and_raw(data_adv)
c2, d2 = cube_and_raw(data_vad)
for w1, w2 in zip(c1.world[view], c2.world[view]):
assert_allclose(w1, w2)
@pytest.mark.parametrize('view',
(np.s_[:, :,:],
np.s_[:2, :3, ::2],
np.s_[::3, ::2, :1],
np.s_[:], ))
def test_world_transposes_4d(self, view, data_advs, data_sadv):
c1, d1 = cube_and_raw(data_advs)
c2, d2 = cube_and_raw(data_sadv)
for w1, w2 in zip(c1.world[view], c2.world[view]):
assert_allclose(w1, w2)
@pytest.mark.parametrize(('filename','masktype','unit','suffix'),
itertools.product(('data_advs', 'data_dvsa', 'data_sdav', 'data_sadv', 'data_vsad', 'data_vad', 'data_adv',),
(BooleanArrayMask, LazyMask, FunctionMask, CompositeMask),
('Hz', u.Hz),
('.fits', '.image') if casaOK else ('.fits',)
),
indirect=['filename'])
def test_with_spectral_unit(self, filename, masktype, unit, suffix):
if suffix == '.image':
import casatasks
filename = str(filename)
casatasks.importfits(filename, filename.replace('.fits', '.image'))
filename = filename.replace('.fits', '.image')
cube, data = cube_and_raw(filename)
cube_freq = cube.with_spectral_unit(unit)
if masktype == BooleanArrayMask:
# don't use data here:
# data haven't necessarily been rearranged to the correct shape by
# cube_utils.orient
mask = BooleanArrayMask(cube.filled_data[:].value>0,
wcs=cube._wcs)
elif masktype == LazyMask:
mask = LazyMask(lambda x: x>0, cube=cube)
elif masktype == FunctionMask:
mask = FunctionMask(lambda x: x>0)
elif masktype == CompositeMask:
mask1 = FunctionMask(lambda x: x>0)
mask2 = LazyMask(lambda x: x>0, cube)
mask = CompositeMask(mask1, mask2)
cube2 = cube.with_mask(mask)
cube_masked_freq = cube2.with_spectral_unit(unit)
if suffix == '.fits':
assert cube_freq._wcs.wcs.ctype[cube_freq._wcs.wcs.spec] == 'FREQ-W2F'
assert cube_masked_freq._wcs.wcs.ctype[cube_masked_freq._wcs.wcs.spec] == 'FREQ-W2F'
assert cube_masked_freq._mask._wcs.wcs.ctype[cube_masked_freq._mask._wcs.wcs.spec] == 'FREQ-W2F'
elif suffix == '.image':
# this is *not correct* but it's a known failure in CASA: CASA's
# image headers don't support any of the FITS spectral standard, so
# it just ends up as 'FREQ'. This isn't on us to fix so this is
# really an "xfail" that we hope will change...
assert cube_freq._wcs.wcs.ctype[cube_freq._wcs.wcs.spec] == 'FREQ'
assert cube_masked_freq._wcs.wcs.ctype[cube_masked_freq._wcs.wcs.spec] == 'FREQ'
assert cube_masked_freq._mask._wcs.wcs.ctype[cube_masked_freq._mask._wcs.wcs.spec] == 'FREQ'
# values taken from header
rest = 1.42040571841E+09*u.Hz
crval = -3.21214698632E+05*u.m/u.s
outcv = crval.to(u.m, u.doppler_optical(rest)).to(u.Hz, u.spectral())
assert_allclose(cube_freq._wcs.wcs.crval[cube_freq._wcs.wcs.spec],
outcv.to(u.Hz).value)
assert_allclose(cube_masked_freq._wcs.wcs.crval[cube_masked_freq._wcs.wcs.spec],
outcv.to(u.Hz).value)
assert_allclose(cube_masked_freq._mask._wcs.wcs.crval[cube_masked_freq._mask._wcs.wcs.spec],
outcv.to(u.Hz).value)
@pytest.mark.parametrize(('operation', 'value'),
((operator.add, 0.5*u.K),
(operator.sub, 0.5*u.K),
(operator.mul, 0.5*u.K),
(operator.truediv, 0.5*u.K),
(operator.div if hasattr(operator,'div') else operator.floordiv, 0.5*u.K),
))
def test_apply_everywhere(self, operation, value, data_advs):
c1, d1 = cube_and_raw(data_advs)
# append 'o' to indicate that it has been operated on
c1o = c1._apply_everywhere(operation, value)
d1o = operation(u.Quantity(d1, u.K), value)
assert np.all(d1o == c1o.filled_data[:])
# allclose fails on identical data?
#assert_allclose(d1o, c1o.filled_data[:])
@pytest.mark.parametrize(('filename', 'trans'), translist, indirect=['filename'])
def test_getitem(self, filename, trans):
c, d = cube_and_raw(filename)
expected = np.squeeze(d.transpose(trans))
assert_allclose(c[0,:,:].value, expected[0,:,:])
assert_allclose(c[:,:,0].value, expected[:,:,0])
assert_allclose(c[:,0,:].value, expected[:,0,:])
# Not implemented:
#assert_allclose(c[0,0,:].value, expected[0,0,:])
#assert_allclose(c[0,:,0].value, expected[0,:,0])
assert_allclose(c[:,0,0].value, expected[:,0,0])
assert_allclose(c[1,:,:].value, expected[1,:,:])
assert_allclose(c[:,:,1].value, expected[:,:,1])
assert_allclose(c[:,1,:].value, expected[:,1,:])
# Not implemented:
#assert_allclose(c[1,1,:].value, expected[1,1,:])
#assert_allclose(c[1,:,1].value, expected[1,:,1])
assert_allclose(c[:,1,1].value, expected[:,1,1])
c2 = c.with_spectral_unit(u.km/u.s, velocity_convention='radio')
assert_allclose(c2[0,:,:].value, expected[0,:,:])
assert_allclose(c2[:,:,0].value, expected[:,:,0])
assert_allclose(c2[:,0,:].value, expected[:,0,:])
# Not implemented:
#assert_allclose(c2[0,0,:].value, expected[0,0,:])
#assert_allclose(c2[0,:,0].value, expected[0,:,0])
assert_allclose(c2[:,0,0].value, expected[:,0,0])
assert_allclose(c2[1,:,:].value, expected[1,:,:])
assert_allclose(c2[:,:,1].value, expected[:,:,1])
assert_allclose(c2[:,1,:].value, expected[:,1,:])
# Not implemented:
#assert_allclose(c2[1,1,:].value, expected[1,1,:])
#assert_allclose(c2[1,:,1].value, expected[1,:,1])
assert_allclose(c2[:,1,1].value, expected[:,1,1])
@pytest.mark.parametrize(('filename', 'trans'), translist_vrsc, indirect=['filename'])
def test_getitem_vrsc(self, filename, trans):
c, d = cube_and_raw(filename)
expected = np.squeeze(d.transpose(trans))
# No pv slices for VRSC.
assert_allclose(c[0,:,:].value, expected[0,:,:])
# Not implemented:
#assert_allclose(c[0,0,:].value, expected[0,0,:])
#assert_allclose(c[0,:,0].value, expected[0,:,0])
assert_allclose(c[:,0,0].value, expected[:,0,0])
assert_allclose(c[1,:,:].value, expected[1,:,:])
# Not implemented:
#assert_allclose(c[1,1,:].value, expected[1,1,:])
#assert_allclose(c[1,:,1].value, expected[1,:,1])
assert_allclose(c[:,1,1].value, expected[:,1,1])
c2 = c.with_spectral_unit(u.km/u.s, velocity_convention='radio')
assert_allclose(c2[0,:,:].value, expected[0,:,:])
# Not implemented:
#assert_allclose(c2[0,0,:].value, expected[0,0,:])
#assert_allclose(c2[0,:,0].value, expected[0,:,0])
assert_allclose(c2[:,0,0].value, expected[:,0,0])
assert_allclose(c2[1,:,:].value, expected[1,:,:])
# Not implemented:
#assert_allclose(c2[1,1,:].value, expected[1,1,:])
#assert_allclose(c2[1,:,1].value, expected[1,:,1])
assert_allclose(c2[:,1,1].value, expected[:,1,1])
# @pytest.mark.xfail(raises=AttributeError)
@pytest.mark.parametrize(('filename', 'trans'), translist_vrsc, indirect=['filename'])
def test_getitem_vrsc(self, filename, trans):
c, d = cube_and_raw(filename)
expected = np.squeeze(d.transpose(trans))
assert_allclose(c[:,:,0].value, expected[:,:,0])
class TestArithmetic(object):
# FIXME: in the tests below we need to manually do self.c1 = self.d1 = None
# because if we try and do this in a teardown method, the open-files check
# gets done first. This is an issue that should be resolved in pytest-openfiles.
@pytest.fixture(autouse=True)
def setup_method_fixture(self, request, data_adv):
self.c1, self.d1 = cube_and_raw(data_adv)
# make nice easy-to-test numbers
self.d1.flat[:] = np.arange(self.d1.size)
self.c1._data.flat[:] = np.arange(self.d1.size)
@pytest.mark.parametrize(('value'),(1,1.0,2,2.0))
def test_add(self,value):
d2 = self.d1 + value
c2 = self.c1 + value*u.K
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K
self.c1 = self.d1 = None
def test_add_cubes(self):
d2 = self.d1 + self.d1
c2 = self.c1 + self.c1
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K
self.c1 = self.d1 = None
@pytest.mark.parametrize(('value'),(1,1.0,2,2.0))
def test_subtract(self, value):
d2 = self.d1 - value
c2 = self.c1 - value*u.K
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K
# regression test #251: the _data attribute must not be a quantity
assert not hasattr(c2._data, 'unit')
self.c1 = self.d1 = None
def test_subtract_cubes(self):
d2 = self.d1 - self.d1
c2 = self.c1 - self.c1
assert np.all(d2 == c2.filled_data[:].value)
assert np.all(c2.filled_data[:].value == 0)
assert c2.unit == u.K
# regression test #251: the _data attribute must not be a quantity
assert not hasattr(c2._data, 'unit')
self.c1 = self.d1 = None
@pytest.mark.parametrize(('value'),(1,1.0,2,2.0))
def test_mul(self, value):
d2 = self.d1 * value
c2 = self.c1 * value
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K
self.c1 = self.d1 = None
def test_mul_cubes(self):
d2 = self.d1 * self.d1
c2 = self.c1 * self.c1
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K**2
self.c1 = self.d1 = None
@pytest.mark.parametrize(('value'),(1,1.0,2,2.0))
def test_div(self, value):
d2 = self.d1 / value
c2 = self.c1 / value
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K
self.c1 = self.d1 = None
def test_div_cubes(self):
d2 = self.d1 / self.d1
c2 = self.c1 / self.c1
assert np.all((d2 == c2.filled_data[:].value) | (np.isnan(c2.filled_data[:])))
assert np.all((c2.filled_data[:] == 1) | (np.isnan(c2.filled_data[:])))
assert c2.unit == u.one
self.c1 = self.d1 = None
@pytest.mark.parametrize(('value'),
(1,1.0,2,2.0))
def test_pow(self, value):
d2 = self.d1 ** value
c2 = self.c1 ** value
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K**value
self.c1 = self.d1 = None
def test_cube_add(self):
c2 = self.c1 + self.c1
d2 = self.d1 + self.d1
assert np.all(d2 == c2.filled_data[:].value)
assert c2.unit == u.K
self.c1 = self.d1 = None
class TestFilters(BaseTest):
def test_mask_data(self):
c, d = self.c, self.d
expected = np.where(d > .5, d, np.nan)
assert_allclose(c._get_filled_data(), expected)
expected = np.where(d > .5, d, 0)
assert_allclose(c._get_filled_data(fill=0), expected)
self.c = self.d = None
@pytest.mark.parametrize('operation', (operator.lt, operator.gt, operator.le, operator.ge))
def test_mask_comparison(self, operation):
c, d = self.c, self.d
dmask = operation(d, 0.6) & self.c.mask.include()
cmask = operation(c, 0.6*u.K)
assert (self.c.mask.include() & cmask.include()).sum() == dmask.sum()
assert np.all(c.with_mask(cmask).mask.include() == dmask)
np.testing.assert_almost_equal(c.with_mask(cmask).sum().value,
d[dmask].sum())
self.c = self.d = None
def test_flatten(self):
c, d = self.c, self.d
expected = d[d > 0.5]
assert_allclose(c.flattened(), expected)
self.c = self.d = None
def test_flatten_weights(self):
c, d = self.c, self.d
expected = d[d > 0.5] ** 2
assert_allclose(c.flattened(weights=d), expected)
self.c = self.d = None
def test_slice(self):
c, d = self.c, self.d
expected = d[:3, :2, ::2]
expected = expected[expected > 0.5]
assert_allclose(c[0:3, 0:2, 0::2].flattened(), expected)
self.c = self.d = None
class TestNumpyMethods(BaseTest):
def _check_numpy(self, cubemethod, array, func):
for axis in [None, 0, 1, 2]:
for how in ['auto', 'slice', 'cube', 'ray']:
expected = func(array, axis=axis)
actual = cubemethod(axis=axis)
assert_allclose(actual, expected)
def test_sum(self):
d = np.where(self.d > 0.5, self.d, np.nan)
self._check_numpy(self.c.sum, d, allbadtonan(np.nansum))
# Need a secondary check to make sure it works with no
# axis keyword being passed (regression test for issue introduced in
# 150)
assert np.all(self.c.sum().value == np.nansum(d))
self.c = self.d = None
def test_max(self):
d = np.where(self.d > 0.5, self.d, np.nan)
self._check_numpy(self.c.max, d, np.nanmax)
self.c = self.d = None
def test_min(self):
d = np.where(self.d > 0.5, self.d, np.nan)
self._check_numpy(self.c.min, d, np.nanmin)
self.c = self.d = None
def test_argmax(self):
d = np.where(self.d > 0.5, self.d, -10)
self._check_numpy(self.c.argmax, d, np.nanargmax)
self.c = self.d = None
def test_argmin(self):
d = np.where(self.d > 0.5, self.d, 10)
self._check_numpy(self.c.argmin, d, np.nanargmin)
self.c = self.d = None
@pytest.mark.parametrize('iterate_rays', (True,False))
def test_median(self, iterate_rays):
# Make sure that medians ignore empty/bad/NaN values
m = np.empty(self.d.shape[1:])
for y in range(m.shape[0]):
for x in range(m.shape[1]):
ray = self.d[:, y, x]
# the cube mask is for values >0.5
ray = ray[ray > 0.5]
m[y, x] = np.median(ray)
scmed = self.c.median(axis=0, iterate_rays=iterate_rays)
assert_allclose(scmed, m)
assert not np.any(np.isnan(scmed.value))
assert scmed.unit == self.c.unit
self.c = self.d = None
@pytest.mark.skipif('NUMPY_LT_19')
def test_bad_median_apply(self):
# this is a test for manually-applied numpy medians, which are different
# from the cube.median method that does "the right thing"
#
# for regular median, we expect a failure, which is why we don't use
# regular median.
scmed = self.c.apply_numpy_function(np.median, axis=0)
# this checks whether numpy <=1.9.3 has a bug?
# as far as I can tell, np==1.9.3 no longer has this bug/feature
#if LooseVersion(np.__version__) <= LooseVersion('1.9.3'):
# # print statements added so we get more info in the travis builds
# print("Numpy version is: {0}".format(LooseVersion(np.__version__)))
# assert np.count_nonzero(np.isnan(scmed)) == 5
#else:
# print("Numpy version is: {0}".format(LooseVersion(np.__version__)))
assert np.count_nonzero(np.isnan(scmed)) == 6
scmed = self.c.apply_numpy_function(np.nanmedian, axis=0)
assert np.count_nonzero(np.isnan(scmed)) == 0
# use a more aggressive mask to force there to be some all-nan axes
m2 = self.c>0.74*self.c.unit
scmed = self.c.with_mask(m2).apply_numpy_function(np.nanmedian, axis=0)
assert np.count_nonzero(np.isnan(scmed)) == 1
self.c = self.d = None
@pytest.mark.parametrize('iterate_rays', (True,False))
def test_bad_median(self, iterate_rays):
# This should have the same result as np.nanmedian, though it might be
# faster if bottleneck loads
scmed = self.c.median(axis=0, iterate_rays=iterate_rays)
assert np.count_nonzero(np.isnan(scmed)) == 0
m2 = self.c>0.74*self.c.unit
scmed = self.c.with_mask(m2).median(axis=0, iterate_rays=iterate_rays)
assert np.count_nonzero(np.isnan(scmed)) == 1
self.c = self.d = None
@pytest.mark.parametrize(('pct', 'iterate_rays'),
(zip((3,25,50,75,97)*2,(True,)*5 + (False,)*5)))
def test_percentile(self, pct, iterate_rays):
m = np.empty(self.d.sum(axis=0).shape)
for y in range(m.shape[0]):
for x in range(m.shape[1]):
ray = self.d[:, y, x]
ray = ray[ray > 0.5]
m[y, x] = np.percentile(ray, pct)
scpct = self.c.percentile(pct, axis=0, iterate_rays=iterate_rays)
assert_allclose(scpct, m)
assert not np.any(np.isnan(scpct.value))
assert scpct.unit == self.c.unit
self.c = self.d = None
@pytest.mark.parametrize('method', ('sum', 'min', 'max', 'std', 'mad_std',
'median', 'argmin', 'argmax'))
def test_transpose(self, method, data_adv, data_vad):
c1, d1 = cube_and_raw(data_adv)
c2, d2 = cube_and_raw(data_vad)
for axis in [None, 0, 1, 2]:
assert_allclose(getattr(c1, method)(axis=axis),
getattr(c2, method)(axis=axis))
# check that all these accept progressbar kwargs
assert_allclose(getattr(c1, method)(axis=axis, progressbar=True),
getattr(c2, method)(axis=axis, progressbar=True))
self.c = self.d = None
class TestSlab(BaseTest):
def test_closest_spectral_channel(self):
c = self.c
ms = u.m / u.s
assert c.closest_spectral_channel(-321214.698632 * ms) == 0
assert c.closest_spectral_channel(-319926.48366321 * ms) == 1
assert c.closest_spectral_channel(-318638.26869442 * ms) == 2
assert c.closest_spectral_channel(-320000 * ms) == 1
assert c.closest_spectral_channel(-340000 * ms) == 0
assert c.closest_spectral_channel(0 * ms) == 3
self.c = self.d = None
def test_spectral_channel_bad_units(self):
with pytest.raises(u.UnitsError,
match=re.escape("'value' should be in frequency equivalent or velocity units (got s)")):
self.c.closest_spectral_channel(1 * u.s)
with pytest.raises(u.UnitsError,
match=re.escape("Spectral axis is in velocity units and 'value' is in frequency-equivalent units - use SpectralCube.with_spectral_unit first to convert the cube to frequency-equivalent units, or search for a velocity instead")):
self.c.closest_spectral_channel(1. * u.Hz)
self.c = self.d = None
def test_slab(self):
ms = u.m / u.s
c2 = self.c.spectral_slab(-320000 * ms, -318600 * ms)
assert_allclose(c2._data, self.d[1:3])
assert c2._mask is not None
self.c = self.d = None
def test_slab_reverse_limits(self):
ms = u.m / u.s
c2 = self.c.spectral_slab(-318600 * ms, -320000 * ms)
assert_allclose(c2._data, self.d[1:3])
assert c2._mask is not None
self.c = self.d = None
def test_slab_preserves_wcs(self):
# regression test
ms = u.m / u.s
crpix = list(self.c._wcs.wcs.crpix)
self.c.spectral_slab(-318600 * ms, -320000 * ms)
assert list(self.c._wcs.wcs.crpix) == crpix
self.c = self.d = None
class TestSlabMultiBeams(BaseTestMultiBeams, TestSlab):
""" same tests with multibeams """
pass
class TestRepr(BaseTest):
def test_repr(self):
assert repr(self.c) == """
SpectralCube with shape=(4, 3, 2) and unit=K:
n_x: 2 type_x: RA---SIN unit_x: deg range: 24.062698 deg: 24.063349 deg
n_y: 3 type_y: DEC--SIN unit_y: deg range: 29.934094 deg: 29.935209 deg
n_s: 4 type_s: VOPT unit_s: km / s range: -321.215 km / s: -317.350 km / s
""".strip()
self.c = self.d = None
def test_repr_withunit(self):
self.c._unit = u.Jy
assert repr(self.c) == """
SpectralCube with shape=(4, 3, 2) and unit=Jy:
n_x: 2 type_x: RA---SIN unit_x: deg range: 24.062698 deg: 24.063349 deg
n_y: 3 type_y: DEC--SIN unit_y: deg range: 29.934094 deg: 29.935209 deg
n_s: 4 type_s: VOPT unit_s: km / s range: -321.215 km / s: -317.350 km / s
""".strip()
self.c = self.d = None
@pytest.mark.skipif('not YT_INSTALLED')
class TestYt():
@pytest.fixture(autouse=True)
def setup_method_fixture(self, request, data_adv):
self.cube = SpectralCube.read(data_adv)
# Without any special arguments
self.ytc1 = self.cube.to_yt()
# With spectral factor = 0.5
self.spectral_factor = 0.5
self.ytc2 = self.cube.to_yt(spectral_factor=self.spectral_factor)
# With nprocs = 4
self.nprocs = 4
self.ytc3 = self.cube.to_yt(nprocs=self.nprocs)
def test_yt(self):
# The following assertions just make sure everything is
# kosher with the datasets generated in different ways
ytc1,ytc2,ytc3 = self.ytc1,self.ytc2,self.ytc3
ds1,ds2,ds3 = ytc1.dataset, ytc2.dataset, ytc3.dataset
assert_array_equal(ds1.domain_dimensions, ds2.domain_dimensions)
assert_array_equal(ds2.domain_dimensions, ds3.domain_dimensions)
assert_allclose(ds1.domain_left_edge.value, ds2.domain_left_edge.value)
assert_allclose(ds2.domain_left_edge.value, ds3.domain_left_edge.value)
assert_allclose(ds1.domain_width.value,
ds2.domain_width.value*np.array([1,1,1.0/self.spectral_factor]))
assert_allclose(ds1.domain_width.value, ds3.domain_width.value)
assert self.nprocs == len(ds3.index.grids)
ds1.index
ds2.index
ds3.index
unit1 = ds1.field_info["fits","flux"].units
unit2 = ds2.field_info["fits","flux"].units
unit3 = ds3.field_info["fits","flux"].units
ds1.quan(1.0,unit1)
ds2.quan(1.0,unit2)
ds3.quan(1.0,unit3)
self.cube = self.ytc1 = self.ytc2 = self.ytc3 = None
@pytest.mark.skipif('YT_LT_301', reason='yt 3.0 has a FITS-related bug')
def test_yt_fluxcompare(self):
# Now check that we can compute quantities of the flux
# and that they are equal
ytc1,ytc2,ytc3 = self.ytc1,self.ytc2,self.ytc3
ds1,ds2,ds3 = ytc1.dataset, ytc2.dataset, ytc3.dataset
dd1 = ds1.all_data()
dd2 = ds2.all_data()
dd3 = ds3.all_data()
flux1_tot = dd1.quantities.total_quantity("flux")
flux2_tot = dd2.quantities.total_quantity("flux")
flux3_tot = dd3.quantities.total_quantity("flux")
flux1_min, flux1_max = dd1.quantities.extrema("flux")
flux2_min, flux2_max = dd2.quantities.extrema("flux")
flux3_min, flux3_max = dd3.quantities.extrema("flux")
assert flux1_tot == flux2_tot
assert flux1_tot == flux3_tot
assert flux1_min == flux2_min
assert flux1_min == flux3_min
assert flux1_max == flux2_max
assert flux1_max == flux3_max
self.cube = self.ytc1 = self.ytc2 = self.ytc3 = None
def test_yt_roundtrip_wcs(self):
# Now test round-trip conversions between yt and world coordinates
ytc1,ytc2,ytc3 = self.ytc1,self.ytc2,self.ytc3
ds1,ds2,ds3 = ytc1.dataset, ytc2.dataset, ytc3.dataset
yt_coord1 = ds1.domain_left_edge + np.random.random(size=3)*ds1.domain_width
world_coord1 = ytc1.yt2world(yt_coord1)
assert_allclose(ytc1.world2yt(world_coord1), yt_coord1.value)
yt_coord2 = ds2.domain_left_edge + np.random.random(size=3)*ds2.domain_width
world_coord2 = ytc2.yt2world(yt_coord2)
assert_allclose(ytc2.world2yt(world_coord2), yt_coord2.value)
yt_coord3 = ds3.domain_left_edge + np.random.random(size=3)*ds3.domain_width
world_coord3 = ytc3.yt2world(yt_coord3)
assert_allclose(ytc3.world2yt(world_coord3), yt_coord3.value)
self.cube = self.ytc1 = self.ytc2 = self.ytc3 = None
def test_read_write_rountrip(tmpdir, data_adv):
cube = SpectralCube.read(data_adv)
tmp_file = str(tmpdir.join('test.fits'))
cube.write(tmp_file)
cube2 = SpectralCube.read(tmp_file)
assert cube.shape == cube.shape
assert_allclose(cube._data, cube2._data)
if (((hasattr(_wcs, '__version__')
and LooseVersion(_wcs.__version__) < LooseVersion('5.9'))
or not hasattr(_wcs, '__version__'))):
# see https://github.com/astropy/astropy/pull/3992 for reasons:
# we should upgrade this for 5.10 when the absolute accuracy is
# maximized
assert cube._wcs.to_header_string() == cube2._wcs.to_header_string()
# in 5.11 and maybe even 5.12, the round trip fails. Maybe
# https://github.com/astropy/astropy/issues/4292 will solve it?
@pytest.mark.parametrize(('memmap', 'base'),
((True, mmap.mmap),
(False, None)))
def test_read_memmap(memmap, base, data_adv):
cube = SpectralCube.read(data_adv, memmap=memmap)
bb = cube.base
while hasattr(bb, 'base'):
bb = bb.base
if base is None:
assert bb is None
else:
assert isinstance(bb, base)
def _dummy_cube():
data = np.array([[[0, 1, 2, 3, 4]]])
wcs = WCS(naxis=3)
wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'VELO-HEL']
def lower_threshold(data, wcs, view=()):
return data[view] > 0
m1 = FunctionMask(lower_threshold)
cube = SpectralCube(data, wcs=wcs, mask=m1)
return cube
def test_with_mask():
def upper_threshold(data, wcs, view=()):
return data[view] < 3
m2 = FunctionMask(upper_threshold)
cube = _dummy_cube()
cube2 = cube.with_mask(m2)
assert_allclose(cube._get_filled_data(), [[[np.nan, 1, 2, 3, 4]]])
assert_allclose(cube2._get_filled_data(), [[[np.nan, 1, 2, np.nan, np.nan]]])
def test_with_mask_with_boolean_array():
cube = _dummy_cube()
mask = cube._data > 2
cube2 = cube.with_mask(mask, inherit_mask=False)
assert isinstance(cube2._mask, BooleanArrayMask)
assert cube2._mask._wcs is cube._wcs
assert cube2._mask._mask is mask
def test_with_mask_with_good_array_shape():
cube = _dummy_cube()
mask = np.zeros((1, 5), dtype=np.bool)
cube2 = cube.with_mask(mask, inherit_mask=False)
assert isinstance(cube2._mask, BooleanArrayMask)
np.testing.assert_equal(cube2._mask._mask, mask.reshape((1, 1, 5)))
def test_with_mask_with_bad_array_shape():
cube = _dummy_cube()
mask = np.zeros((5, 5), dtype=np.bool)
with pytest.raises(ValueError) as exc:
cube.with_mask(mask)
assert exc.value.args[0] == ("Mask shape is not broadcastable to data shape: "
"(5, 5) vs (1, 1, 5)")
class TestMasks(BaseTest):
@pytest.mark.parametrize('op', (operator.gt, operator.lt,
operator.le, operator.ge))
def test_operator_threshold(self, op):
# choose thresh to exercise proper equality tests
thresh = self.d.ravel()[0]
m = op(self.c, thresh*u.K)
self.c._mask = m
expected = self.d[op(self.d, thresh)]
actual = self.c.flattened()
assert_allclose(actual, expected)
self.c = self.d = None
def test_preserve_spectral_unit(data_advs):
# astropy.wcs has a tendancy to change spectral units from e.g. km/s to
# m/s, so we have a workaround - check that it works.
cube, data = cube_and_raw(data_advs)
cube_freq = cube.with_spectral_unit(u.GHz)
assert cube_freq.wcs.wcs.cunit[2] == 'Hz' # check internal
assert cube_freq.spectral_axis.unit is u.GHz
# Check that this preferred unit is propagated
new_cube = cube_freq.with_fill_value(fill_value=3.4)
assert new_cube.spectral_axis.unit is u.GHz
def test_endians():
"""
Test that the endianness checking returns something in Native form
(this is only needed for non-numpy functions that worry about the
endianness of their data)
WARNING: Because the endianness is machine-dependent, this may fail on
different architectures! This is because numpy automatically converts
little-endian to native in the dtype parameter; I need a workaround for
this.
"""
pytest.importorskip('bottleneck')
big = np.array([[[1],[2]]], dtype='>f4')
lil = np.array([[[1],[2]]], dtype='<f4')
mywcs = WCS(naxis=3)
mywcs.wcs.ctype[0] = 'RA'
mywcs.wcs.ctype[1] = 'DEC'
mywcs.wcs.ctype[2] = 'VELO'
bigcube = SpectralCube(data=big, wcs=mywcs)
xbig = bigcube._get_filled_data(check_endian=True)
lilcube = SpectralCube(data=lil, wcs=mywcs)
xlil = lilcube._get_filled_data(check_endian=True)
assert xbig.dtype.byteorder == '='
assert xlil.dtype.byteorder == '='
xbig = bigcube._get_filled_data(check_endian=False)
xlil = lilcube._get_filled_data(check_endian=False)