-
Notifications
You must be signed in to change notification settings - Fork 285
/
test_composites.py
1835 lines (1576 loc) · 80.9 KB
/
test_composites.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 Satpy developers
#
# This file is part of satpy.
#
# satpy is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# satpy is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# satpy. If not, see <http://www.gnu.org/licenses/>.
"""Tests for compositors in composites/__init__.py."""
import os
import unittest
from datetime import datetime
from unittest import mock
import dask
import dask.array as da
import numpy as np
import pytest
import xarray as xr
from pyresample import AreaDefinition
import satpy
# NOTE:
# The following fixtures are not defined in this file, but are used and injected by Pytest:
# - tmp_path
class TestMatchDataArrays(unittest.TestCase):
"""Test the utility method 'match_data_arrays'."""
def _get_test_ds(self, shape=(50, 100), dims=('y', 'x')):
"""Get a fake DataArray."""
from pyresample.geometry import AreaDefinition
data = da.random.random(shape, chunks=25)
area = AreaDefinition(
'test', 'test', 'test',
{'proj': 'eqc', 'lon_0': 0.0,
'lat_0': 0.0},
shape[dims.index('x')], shape[dims.index('y')],
(-20037508.34, -10018754.17, 20037508.34, 10018754.17))
attrs = {'area': area}
return xr.DataArray(data, dims=dims, attrs=attrs)
def test_single_ds(self):
"""Test a single dataset is returned unharmed."""
from satpy.composites import CompositeBase
ds1 = self._get_test_ds()
comp = CompositeBase('test_comp')
ret_datasets = comp.match_data_arrays((ds1,))
assert ret_datasets[0].identical(ds1)
def test_mult_ds_area(self):
"""Test multiple datasets successfully pass."""
from satpy.composites import CompositeBase
ds1 = self._get_test_ds()
ds2 = self._get_test_ds()
comp = CompositeBase('test_comp')
ret_datasets = comp.match_data_arrays((ds1, ds2))
assert ret_datasets[0].identical(ds1)
assert ret_datasets[1].identical(ds2)
def test_mult_ds_no_area(self):
"""Test that all datasets must have an area attribute."""
from satpy.composites import CompositeBase
ds1 = self._get_test_ds()
ds2 = self._get_test_ds()
del ds2.attrs['area']
comp = CompositeBase('test_comp')
self.assertRaises(ValueError, comp.match_data_arrays, (ds1, ds2))
def test_mult_ds_diff_area(self):
"""Test that datasets with different areas fail."""
from pyresample.geometry import AreaDefinition
from satpy.composites import CompositeBase, IncompatibleAreas
ds1 = self._get_test_ds()
ds2 = self._get_test_ds()
ds2.attrs['area'] = AreaDefinition(
'test', 'test', 'test',
{'proj': 'eqc', 'lon_0': 0.0,
'lat_0': 0.0},
100, 50,
(-30037508.34, -20018754.17, 10037508.34, 18754.17))
comp = CompositeBase('test_comp')
self.assertRaises(IncompatibleAreas, comp.match_data_arrays, (ds1, ds2))
def test_mult_ds_diff_dims(self):
"""Test that datasets with different dimensions still pass."""
from satpy.composites import CompositeBase
# x is still 50, y is still 100, even though they are in
# different order
ds1 = self._get_test_ds(shape=(50, 100), dims=('y', 'x'))
ds2 = self._get_test_ds(shape=(3, 100, 50), dims=('bands', 'x', 'y'))
comp = CompositeBase('test_comp')
ret_datasets = comp.match_data_arrays((ds1, ds2))
assert ret_datasets[0].identical(ds1)
assert ret_datasets[1].identical(ds2)
def test_mult_ds_diff_size(self):
"""Test that datasets with different sizes fail."""
from satpy.composites import CompositeBase, IncompatibleAreas
# x is 50 in this one, 100 in ds2
# y is 100 in this one, 50 in ds2
ds1 = self._get_test_ds(shape=(50, 100), dims=('x', 'y'))
ds2 = self._get_test_ds(shape=(3, 50, 100), dims=('bands', 'y', 'x'))
comp = CompositeBase('test_comp')
self.assertRaises(IncompatibleAreas, comp.match_data_arrays, (ds1, ds2))
def test_nondimensional_coords(self):
"""Test the removal of non-dimensional coordinates when compositing."""
from satpy.composites import CompositeBase
ds = self._get_test_ds(shape=(2, 2))
ds['acq_time'] = ('y', [0, 1])
comp = CompositeBase('test_comp')
ret_datasets = comp.match_data_arrays([ds, ds])
self.assertNotIn('acq_time', ret_datasets[0].coords)
class TestRatioSharpenedCompositors:
"""Test RatioSharpenedRGB and SelfSharpendRGB compositors."""
def setup_method(self):
"""Create test data."""
from pyresample.geometry import AreaDefinition
area = AreaDefinition('test', 'test', 'test',
{'proj': 'merc'}, 2, 2,
(-2000, -2000, 2000, 2000))
attrs = {'area': area,
'start_time': datetime(2018, 1, 1, 18),
'modifiers': tuple(),
'resolution': 1000,
'calibration': 'reflectance',
'units': '%',
'name': 'test_vis'}
low_res_data = np.ones((2, 2), dtype=np.float64) + 4
low_res_data[1, 1] = 0.0 # produces infinite ratio
ds1 = xr.DataArray(da.from_array(low_res_data, chunks=2),
attrs=attrs, dims=('y', 'x'),
coords={'y': [0, 1], 'x': [0, 1]})
self.ds1 = ds1
ds2 = xr.DataArray(da.ones((2, 2), chunks=2, dtype=np.float64) + 2,
attrs=attrs, dims=('y', 'x'),
coords={'y': [0, 1], 'x': [0, 1]})
ds2.attrs['name'] += '2'
self.ds2 = ds2
ds3 = xr.DataArray(da.ones((2, 2), chunks=2, dtype=np.float64) + 3,
attrs=attrs, dims=('y', 'x'),
coords={'y': [0, 1], 'x': [0, 1]})
ds3.attrs['name'] += '3'
self.ds3 = ds3
# high resolution version
high_res_data = np.ones((2, 2), dtype=np.float64)
high_res_data[1, 0] = np.nan # invalid value in one band
ds4 = xr.DataArray(da.from_array(high_res_data, chunks=2),
attrs=attrs, dims=('y', 'x'),
coords={'y': [0, 1], 'x': [0, 1]})
ds4.attrs['name'] += '4'
ds4.attrs['resolution'] = 500
self.ds4 = ds4
# high resolution version - but too big
ds4_big = xr.DataArray(da.ones((4, 4), chunks=2, dtype=np.float64),
attrs=attrs.copy(), dims=('y', 'x'),
coords={'y': [0, 1, 2, 3], 'x': [0, 1, 2, 3]})
ds4_big.attrs['name'] += '4'
ds4_big.attrs['resolution'] = 500
ds4_big.attrs['rows_per_scan'] = 1
ds4_big.attrs['area'] = AreaDefinition('test', 'test', 'test',
{'proj': 'merc'}, 4, 4,
(-2000, -2000, 2000, 2000))
self.ds4_big = ds4_big
@pytest.mark.parametrize(
"init_kwargs",
[
{'high_resolution_band': "bad", 'neutral_resolution_band': "red"},
{'high_resolution_band': "red", 'neutral_resolution_band': "bad"}
]
)
def test_bad_colors(self, init_kwargs):
"""Test that only valid band colors can be provided."""
from satpy.composites import RatioSharpenedRGB
with pytest.raises(ValueError):
RatioSharpenedRGB(name='true_color', **init_kwargs)
def test_match_data_arrays(self):
"""Test that all areas have to be the same resolution."""
from satpy.composites import IncompatibleAreas, RatioSharpenedRGB
comp = RatioSharpenedRGB(name='true_color')
with pytest.raises(IncompatibleAreas):
comp((self.ds1, self.ds2, self.ds3), optional_datasets=(self.ds4_big,))
def test_more_than_three_datasets(self):
"""Test that only 3 datasets can be passed."""
from satpy.composites import RatioSharpenedRGB
comp = RatioSharpenedRGB(name='true_color')
with pytest.raises(ValueError):
comp((self.ds1, self.ds2, self.ds3, self.ds1), optional_datasets=(self.ds4_big,))
def test_self_sharpened_no_high_res(self):
"""Test for exception when no high_res band is specified."""
from satpy.composites import SelfSharpenedRGB
comp = SelfSharpenedRGB(name='true_color', high_resolution_band=None)
with pytest.raises(ValueError):
comp((self.ds1, self.ds2, self.ds3))
def test_basic_no_high_res(self):
"""Test that three datasets can be passed without optional high res."""
from satpy.composites import RatioSharpenedRGB
comp = RatioSharpenedRGB(name="true_color")
res = comp((self.ds1, self.ds2, self.ds3))
assert res.shape == (3, 2, 2)
def test_basic_no_sharpen(self):
"""Test that color None does no sharpening."""
from satpy.composites import RatioSharpenedRGB
comp = RatioSharpenedRGB(name="true_color", high_resolution_band=None)
res = comp((self.ds1, self.ds2, self.ds3), optional_datasets=(self.ds4,))
assert res.shape == (3, 2, 2)
@pytest.mark.parametrize(
("high_resolution_band", "neutral_resolution_band", "exp_r", "exp_g", "exp_b"),
[
("red", None,
np.array([[1.0, 1.0], [np.nan, 1.0]], dtype=np.float64),
np.array([[0.6, 0.6], [np.nan, 3.0]], dtype=np.float64),
np.array([[0.8, 0.8], [np.nan, 4.0]], dtype=np.float64)),
("red", "green",
np.array([[1.0, 1.0], [np.nan, 1.0]], dtype=np.float64),
np.array([[3.0, 3.0], [np.nan, 3.0]], dtype=np.float64),
np.array([[0.8, 0.8], [np.nan, 4.0]], dtype=np.float64)),
("green", None,
np.array([[5 / 3, 5 / 3], [np.nan, 0.0]], dtype=np.float64),
np.array([[1.0, 1.0], [np.nan, 1.0]], dtype=np.float64),
np.array([[4 / 3, 4 / 3], [np.nan, 4 / 3]], dtype=np.float64)),
("green", "blue",
np.array([[5 / 3, 5 / 3], [np.nan, 0.0]], dtype=np.float64),
np.array([[1.0, 1.0], [np.nan, 1.0]], dtype=np.float64),
np.array([[4.0, 4.0], [np.nan, 4.0]], dtype=np.float64)),
("blue", None,
np.array([[1.25, 1.25], [np.nan, 0.0]], dtype=np.float64),
np.array([[0.75, 0.75], [np.nan, 0.75]], dtype=np.float64),
np.array([[1.0, 1.0], [np.nan, 1.0]], dtype=np.float64)),
("blue", "red",
np.array([[5.0, 5.0], [np.nan, 0.0]], dtype=np.float64),
np.array([[0.75, 0.75], [np.nan, 0.75]], dtype=np.float64),
np.array([[1.0, 1.0], [np.nan, 1.0]], dtype=np.float64))
]
)
def test_ratio_sharpening(self, high_resolution_band, neutral_resolution_band, exp_r, exp_g, exp_b):
"""Test RatioSharpenedRGB by different groups of high_resolution_band and neutral_resolution_band."""
from satpy.composites import RatioSharpenedRGB
comp = RatioSharpenedRGB(name='true_color', high_resolution_band=high_resolution_band,
neutral_resolution_band=neutral_resolution_band)
res = comp((self.ds1, self.ds2, self.ds3), optional_datasets=(self.ds4,))
assert "units" not in res.attrs
assert isinstance(res, xr.DataArray)
assert isinstance(res.data, da.Array)
data = res.values
np.testing.assert_allclose(data[0], exp_r, rtol=1e-5)
np.testing.assert_allclose(data[1], exp_g, rtol=1e-5)
np.testing.assert_allclose(data[2], exp_b, rtol=1e-5)
@pytest.mark.parametrize(
("exp_shape", "exp_r", "exp_g", "exp_b"),
[
((3, 2, 2),
np.array([[5.0, 5.0], [5.0, 0]], dtype=np.float64),
np.array([[4.0, 4.0], [4.0, 0]], dtype=np.float64),
np.array([[16 / 3, 16 / 3], [16 / 3, 0]], dtype=np.float64))
]
)
def test_self_sharpened_basic(self, exp_shape, exp_r, exp_g, exp_b):
"""Test that three datasets can be passed without optional high res."""
from satpy.composites import SelfSharpenedRGB
comp = SelfSharpenedRGB(name='true_color')
res = comp((self.ds1, self.ds2, self.ds3))
data = res.values
assert data.shape == exp_shape
np.testing.assert_allclose(data[0], exp_r, rtol=1e-5)
np.testing.assert_allclose(data[1], exp_g, rtol=1e-5)
np.testing.assert_allclose(data[2], exp_b, rtol=1e-5)
class TestDifferenceCompositor(unittest.TestCase):
"""Test case for the difference compositor."""
def setUp(self):
"""Create test data."""
from pyresample.geometry import AreaDefinition
area = AreaDefinition('test', 'test', 'test',
{'proj': 'merc'}, 2, 2,
(-2000, -2000, 2000, 2000))
attrs = {'area': area,
'start_time': datetime(2018, 1, 1, 18),
'modifiers': tuple(),
'resolution': 1000,
'name': 'test_vis'}
ds1 = xr.DataArray(da.ones((2, 2), chunks=2, dtype=np.float64),
attrs=attrs, dims=('y', 'x'),
coords={'y': [0, 1], 'x': [0, 1]})
self.ds1 = ds1
ds2 = xr.DataArray(da.ones((2, 2), chunks=2, dtype=np.float64) + 2,
attrs=attrs, dims=('y', 'x'),
coords={'y': [0, 1], 'x': [0, 1]})
ds2.attrs['name'] += '2'
self.ds2 = ds2
# high res version
ds2 = xr.DataArray(da.ones((4, 4), chunks=2, dtype=np.float64) + 4,
attrs=attrs.copy(), dims=('y', 'x'),
coords={'y': [0, 1, 2, 3], 'x': [0, 1, 2, 3]})
ds2.attrs['name'] += '2'
ds2.attrs['resolution'] = 500
ds2.attrs['rows_per_scan'] = 1
ds2.attrs['area'] = AreaDefinition('test', 'test', 'test',
{'proj': 'merc'}, 4, 4,
(-2000, -2000, 2000, 2000))
self.ds2_big = ds2
def test_basic_diff(self):
"""Test that a basic difference composite works."""
from satpy.composites import DifferenceCompositor
comp = DifferenceCompositor(name='diff', standard_name='temperature_difference')
res = comp((self.ds1, self.ds2))
np.testing.assert_allclose(res.values, -2)
assert res.attrs.get('standard_name') == 'temperature_difference'
def test_bad_areas_diff(self):
"""Test that a difference where resolutions are different fails."""
from satpy.composites import DifferenceCompositor, IncompatibleAreas
comp = DifferenceCompositor(name='diff')
# too many arguments
self.assertRaises(ValueError, comp, (self.ds1, self.ds2, self.ds2_big))
# different resolution
self.assertRaises(IncompatibleAreas, comp, (self.ds1, self.ds2_big))
@pytest.fixture
def fake_area():
"""Return a fake 2×2 area."""
from pyresample.geometry import create_area_def
return create_area_def("skierffe", 4087, area_extent=[-5_000, -5_000, 5_000, 5_000], shape=(2, 2))
@pytest.fixture
def fake_dataset_pair(fake_area):
"""Return a fake pair of 2×2 datasets."""
ds1 = xr.DataArray(da.full((2, 2), 8, chunks=2, dtype=np.float32), attrs={"area": fake_area})
ds2 = xr.DataArray(da.full((2, 2), 4, chunks=2, dtype=np.float32), attrs={"area": fake_area})
return (ds1, ds2)
def test_ratio_compositor(fake_dataset_pair):
"""Test the ratio compositor."""
from satpy.composites import RatioCompositor
comp = RatioCompositor(name="ratio", standard_name="channel_ratio")
res = comp(fake_dataset_pair)
np.testing.assert_allclose(res.values, 2)
def test_sum_compositor(fake_dataset_pair):
"""Test the sum compositor."""
from satpy.composites import SumCompositor
comp = SumCompositor(name="sum", standard_name="channel_sum")
res = comp(fake_dataset_pair)
np.testing.assert_allclose(res.values, 12)
class TestDayNightCompositor(unittest.TestCase):
"""Test DayNightCompositor."""
def setUp(self):
"""Create test data."""
bands = ['R', 'G', 'B']
start_time = datetime(2018, 1, 1, 18, 0, 0)
# RGB
a = np.zeros((3, 2, 2), dtype=np.float64)
a[:, 0, 0] = 0.1
a[:, 0, 1] = 0.2
a[:, 1, 0] = 0.3
a[:, 1, 1] = 0.4
a = da.from_array(a, a.shape)
self.data_a = xr.DataArray(a, attrs={'test': 'a', 'start_time': start_time},
coords={'bands': bands}, dims=('bands', 'y', 'x'))
b = np.zeros((3, 2, 2), dtype=np.float64)
b[:, 0, 0] = np.nan
b[:, 0, 1] = 0.25
b[:, 1, 0] = 0.50
b[:, 1, 1] = 0.75
b = da.from_array(b, b.shape)
self.data_b = xr.DataArray(b, attrs={'test': 'b', 'start_time': start_time},
coords={'bands': bands}, dims=('bands', 'y', 'x'))
sza = np.array([[80., 86.], [94., 100.]])
sza = da.from_array(sza, sza.shape)
self.sza = xr.DataArray(sza, dims=('y', 'x'))
# fake area
my_area = AreaDefinition(
"test", "", "",
"+proj=longlat",
2, 2,
(-95.0, 40.0, -92.0, 43.0),
)
self.data_a.attrs['area'] = my_area
self.data_b.attrs['area'] = my_area
# not used except to check that it matches the data arrays
self.sza.attrs['area'] = my_area
def test_daynight_sza(self):
"""Test compositor with both day and night portions when SZA data is included."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="day_night")
res = comp((self.data_a, self.data_b, self.sza))
res = res.compute()
expected = np.array([[0., 0.22122352], [0.5, 1.]])
np.testing.assert_allclose(res.values[0], expected)
def test_daynight_area(self):
"""Test compositor both day and night portions when SZA data is not provided."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="day_night")
res = comp((self.data_a, self.data_b))
res = res.compute()
expected_channel = np.array([[0., 0.33164983], [0.66835017, 1.]])
for i in range(3):
np.testing.assert_allclose(res.values[i], expected_channel)
def test_night_only_sza_with_alpha(self):
"""Test compositor with night portion with alpha band when SZA data is included."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="night_only", include_alpha=True)
res = comp((self.data_b, self.sza))
res = res.compute()
expected_red_channel = np.array([[np.nan, 0.], [0.5, 1.]])
expected_alpha = np.array([[0., 0.33296056], [1., 1.]])
np.testing.assert_allclose(res.values[0], expected_red_channel)
np.testing.assert_allclose(res.values[-1], expected_alpha)
def test_night_only_sza_without_alpha(self):
"""Test compositor with night portion without alpha band when SZA data is included."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="night_only", include_alpha=False)
res = comp((self.data_a, self.sza))
res = res.compute()
expected = np.array([[0., 0.11042631], [0.66835017, 1.]])
np.testing.assert_allclose(res.values[0], expected)
assert 'A' not in res.bands
def test_night_only_area_with_alpha(self):
"""Test compositor with night portion with alpha band when SZA data is not provided."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="night_only", include_alpha=True)
res = comp((self.data_b,))
res = res.compute()
expected_l_channel = np.array([[np.nan, 0.], [0.5, 1.]])
expected_alpha = np.array([[np.nan, 0.], [0., 0.]])
np.testing.assert_allclose(res.values[0], expected_l_channel)
np.testing.assert_allclose(res.values[-1], expected_alpha)
def test_night_only_area_without_alpha(self):
"""Test compositor with night portion without alpha band when SZA data is not provided."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="night_only", include_alpha=False)
res = comp((self.data_b,))
res = res.compute()
expected = np.array([[np.nan, 0.], [0., 0.]])
np.testing.assert_allclose(res.values[0], expected)
assert 'A' not in res.bands
def test_day_only_sza_with_alpha(self):
"""Test compositor with day portion with alpha band when SZA data is included."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="day_only", include_alpha=True)
res = comp((self.data_a, self.sza))
res = res.compute()
expected_red_channel = np.array([[0., 0.33164983], [0.66835017, 1.]])
expected_alpha = np.array([[1., 0.66703944], [0., 0.]])
np.testing.assert_allclose(res.values[0], expected_red_channel)
np.testing.assert_allclose(res.values[-1], expected_alpha)
def test_day_only_sza_without_alpha(self):
"""Test compositor with day portion without alpha band when SZA data is included."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="day_only", include_alpha=False)
res = comp((self.data_a, self.sza))
res = res.compute()
expected_channel_data = np.array([[0., 0.22122352], [0., 0.]])
for i in range(3):
np.testing.assert_allclose(res.values[i], expected_channel_data)
assert 'A' not in res.bands
def test_day_only_area_with_alpha(self):
"""Test compositor with day portion with alpha_band when SZA data is not provided."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="day_only", include_alpha=True)
res = comp((self.data_a,))
res = res.compute()
expected_l_channel = np.array([[0., 0.33164983], [0.66835017, 1.]])
expected_alpha = np.array([[1., 1.], [1., 1.]])
np.testing.assert_allclose(res.values[0], expected_l_channel)
np.testing.assert_allclose(res.values[-1], expected_alpha)
def test_day_only_area_with_alpha_and_missing_data(self):
"""Test compositor with day portion with alpha_band when SZA data is not provided and there is missing data."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="day_only", include_alpha=True)
res = comp((self.data_b,))
res = res.compute()
expected_l_channel = np.array([[np.nan, 0.], [0.5, 1.]])
expected_alpha = np.array([[np.nan, 1.], [1., 1.]])
np.testing.assert_allclose(res.values[0], expected_l_channel)
np.testing.assert_allclose(res.values[-1], expected_alpha)
def test_day_only_area_without_alpha(self):
"""Test compositor with day portion without alpha_band when SZA data is not provided."""
from satpy.composites import DayNightCompositor
comp = DayNightCompositor(name='dn_test', day_night="day_only", include_alpha=False)
res = comp((self.data_a,))
res = res.compute()
expected = np.array([[0., 0.33164983], [0.66835017, 1.]])
np.testing.assert_allclose(res.values[0], expected)
assert 'A' not in res.bands
class TestFillingCompositor(unittest.TestCase):
"""Test case for the filling compositor."""
def test_fill(self):
"""Test filling."""
from satpy.composites import FillingCompositor
comp = FillingCompositor(name='fill_test')
filler = xr.DataArray(np.array([1, 2, 3, 4, 3, 2, 1]))
red = xr.DataArray(np.array([1, 2, 3, np.nan, 3, 2, 1]))
green = xr.DataArray(np.array([np.nan, 2, 3, 4, 3, 2, np.nan]))
blue = xr.DataArray(np.array([4, 3, 2, 1, 2, 3, 4]))
res = comp([filler, red, green, blue])
np.testing.assert_allclose(res.sel(bands='R').data, filler.data)
np.testing.assert_allclose(res.sel(bands='G').data, filler.data)
np.testing.assert_allclose(res.sel(bands='B').data, blue.data)
class TestMultiFiller(unittest.TestCase):
"""Test case for the MultiFiller compositor."""
def test_fill(self):
"""Test filling."""
from satpy.composites import MultiFiller
comp = MultiFiller(name='fill_test')
attrs = {"units": "K"}
a = xr.DataArray(np.array([1, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]), attrs=attrs.copy())
b = xr.DataArray(np.array([np.nan, 2, 3, np.nan, np.nan, np.nan, np.nan]), attrs=attrs.copy())
c = xr.DataArray(np.array([np.nan, 22, 3, np.nan, np.nan, np.nan, 7]), attrs=attrs.copy())
d = xr.DataArray(np.array([np.nan, np.nan, np.nan, np.nan, np.nan, 6, np.nan]), attrs=attrs.copy())
e = xr.DataArray(np.array([np.nan, np.nan, np.nan, np.nan, 5, np.nan, np.nan]), attrs=attrs.copy())
expected = xr.DataArray(np.array([1, 2, 3, np.nan, 5, 6, 7]))
res = comp([a, b, c], optional_datasets=[d, e])
np.testing.assert_allclose(res.data, expected.data)
assert "units" in res.attrs
assert res.attrs["units"] == "K"
class TestLuminanceSharpeningCompositor(unittest.TestCase):
"""Test luminance sharpening compositor."""
def test_compositor(self):
"""Test luminance sharpening compositor."""
from satpy.composites import LuminanceSharpeningCompositor
comp = LuminanceSharpeningCompositor(name='test')
# Three shades of grey
rgb_arr = np.array([1, 50, 100, 200, 1, 50, 100, 200, 1, 50, 100, 200])
rgb = xr.DataArray(rgb_arr.reshape((3, 2, 2)),
dims=['bands', 'y', 'x'], coords={'bands': ['R', 'G', 'B']})
# 100 % luminance -> all result values ~1.0
lum = xr.DataArray(np.array([[100., 100.], [100., 100.]]),
dims=['y', 'x'])
res = comp([lum, rgb])
np.testing.assert_allclose(res.data, 1., atol=1e-9)
# 50 % luminance, all result values ~0.5
lum = xr.DataArray(np.array([[50., 50.], [50., 50.]]),
dims=['y', 'x'])
res = comp([lum, rgb])
np.testing.assert_allclose(res.data, 0.5, atol=1e-9)
# 30 % luminance, all result values ~0.3
lum = xr.DataArray(np.array([[30., 30.], [30., 30.]]),
dims=['y', 'x'])
res = comp([lum, rgb])
np.testing.assert_allclose(res.data, 0.3, atol=1e-9)
# 0 % luminance, all values ~0.0
lum = xr.DataArray(np.array([[0., 0.], [0., 0.]]),
dims=['y', 'x'])
res = comp([lum, rgb])
np.testing.assert_allclose(res.data, 0.0, atol=1e-9)
class TestSandwichCompositor:
"""Test sandwich compositor."""
# Test RGB and RGBA
@pytest.mark.parametrize(
"input_shape,bands",
[
((3, 2, 2), ['R', 'G', 'B']),
((4, 2, 2), ['R', 'G', 'B', 'A'])
]
)
@mock.patch('satpy.composites.enhance2dataset')
def test_compositor(self, e2d, input_shape, bands):
"""Test luminance sharpening compositor."""
from satpy.composites import SandwichCompositor
rgb_arr = da.from_array(np.random.random(input_shape), chunks=2)
rgb = xr.DataArray(rgb_arr, dims=['bands', 'y', 'x'],
coords={'bands': bands})
lum_arr = da.from_array(100 * np.random.random((2, 2)), chunks=2)
lum = xr.DataArray(lum_arr, dims=['y', 'x'])
# Make enhance2dataset return unmodified dataset
e2d.return_value = rgb
comp = SandwichCompositor(name='test')
res = comp([lum, rgb])
for band in rgb:
if band.bands != 'A':
# Check compositor has modified this band
np.testing.assert_allclose(res.loc[band.bands].to_numpy(),
band.to_numpy() * lum_arr / 100.)
else:
# Check Alpha band remains intact
np.testing.assert_allclose(res.loc[band.bands].to_numpy(),
band.to_numpy())
# make sure the compositor doesn't modify the input data
np.testing.assert_allclose(lum.values, lum_arr.compute())
class TestInlineComposites(unittest.TestCase):
"""Test inline composites."""
def test_inline_composites(self):
"""Test that inline composites are working."""
from satpy.composites.config_loader import load_compositor_configs_for_sensors
comps = load_compositor_configs_for_sensors(['visir'])[0]
# Check that "fog" product has all its prerequisites defined
keys = comps['visir'].keys()
fog = [comps['visir'][dsid] for dsid in keys if "fog" == dsid['name']][0]
self.assertEqual(fog.attrs['prerequisites'][0]['name'], '_fog_dep_0')
self.assertEqual(fog.attrs['prerequisites'][1]['name'], '_fog_dep_1')
self.assertEqual(fog.attrs['prerequisites'][2], 10.8)
# Check that the sub-composite dependencies use wavelengths
# (numeric values)
keys = comps['visir'].keys()
fog_dep_ids = [dsid for dsid in keys if "fog_dep" in dsid['name']]
self.assertEqual(comps['visir'][fog_dep_ids[0]].attrs['prerequisites'],
[12.0, 10.8])
self.assertEqual(comps['visir'][fog_dep_ids[1]].attrs['prerequisites'],
[10.8, 8.7])
# Check the same for SEVIRI and verify channel names are used
# in the sub-composite dependencies instead of wavelengths
comps = load_compositor_configs_for_sensors(['seviri'])[0]
keys = comps['seviri'].keys()
fog_dep_ids = [dsid for dsid in keys if "fog_dep" in dsid['name']]
self.assertEqual(comps['seviri'][fog_dep_ids[0]].attrs['prerequisites'],
['IR_120', 'IR_108'])
self.assertEqual(comps['seviri'][fog_dep_ids[1]].attrs['prerequisites'],
['IR_108', 'IR_087'])
class TestColormapCompositor(unittest.TestCase):
"""Test the ColormapCompositor."""
def setUp(self):
"""Set up the test case."""
from satpy.composites import ColormapCompositor
self.colormap_compositor = ColormapCompositor('test_cmap_compositor')
def test_build_colormap_with_int_data_and_without_meanings(self):
"""Test colormap building."""
palette = np.array([[0, 0, 0], [127, 127, 127], [255, 255, 255]])
colormap, squeezed_palette = self.colormap_compositor.build_colormap(palette, np.uint8, {})
self.assertTrue(np.allclose(colormap.values, [0, 1]))
self.assertTrue(np.allclose(squeezed_palette, palette / 255.0))
def test_build_colormap_with_int_data_and_with_meanings(self):
"""Test colormap building."""
palette = xr.DataArray(np.array([[0, 0, 0], [127, 127, 127], [255, 255, 255]]),
dims=['value', 'band'])
palette.attrs['palette_meanings'] = [2, 3, 4]
colormap, squeezed_palette = self.colormap_compositor.build_colormap(palette, np.uint8, {})
self.assertTrue(np.allclose(colormap.values, [2, 3, 4]))
self.assertTrue(np.allclose(squeezed_palette, palette / 255.0))
class TestPaletteCompositor(unittest.TestCase):
"""Test the PaletteCompositor."""
def test_call(self):
"""Test palette compositing."""
from satpy.composites import PaletteCompositor
cmap_comp = PaletteCompositor('test_cmap_compositor')
palette = xr.DataArray(np.array([[0, 0, 0], [127, 127, 127], [255, 255, 255]]),
dims=['value', 'band'])
palette.attrs['palette_meanings'] = [2, 3, 4]
data = xr.DataArray(da.from_array(np.array([[4, 3, 2], [2, 3, 4]], dtype=np.uint8)), dims=['y', 'x'])
res = cmap_comp([data, palette])
exp = np.array([[[1., 0.498039, 0.],
[0., 0.498039, 1.]],
[[1., 0.498039, 0.],
[0., 0.498039, 1.]],
[[1., 0.498039, 0.],
[0., 0.498039, 1.]]])
self.assertTrue(np.allclose(res, exp))
class TestColorizeCompositor(unittest.TestCase):
"""Test the ColorizeCompositor."""
def test_colorize_no_fill(self):
"""Test colorizing."""
from satpy.composites import ColorizeCompositor
colormap_composite = ColorizeCompositor('test_color_compositor')
palette = xr.DataArray(np.array([[0, 0, 0], [127, 127, 127], [255, 255, 255]]),
dims=['value', 'band'])
palette.attrs['palette_meanings'] = [2, 3, 4]
data = xr.DataArray(np.array([[4, 3, 2],
[2, 3, 4]],
dtype=np.uint8),
dims=['y', 'x'])
res = colormap_composite([data, palette])
exp = np.array([[[1., 0.498039, 0.],
[0., 0.498039, 1.]],
[[1., 0.498039, 0.],
[0., 0.498039, 1.]],
[[1., 0.498039, 0.],
[0., 0.498039, 1.]]])
self.assertTrue(np.allclose(res, exp, atol=1e-4))
def test_colorize_with_interpolation(self):
"""Test colorizing with interpolation."""
from satpy.composites import ColorizeCompositor
colormap_composite = ColorizeCompositor('test_color_compositor')
palette = xr.DataArray(np.array([[0, 0, 0], [127, 127, 127], [255, 255, 255]]),
dims=['value', 'band'])
palette.attrs['palette_meanings'] = [2, 3, 4]
data = xr.DataArray(da.from_array(np.array([[4, 3, 2.5],
[2, 3.2, 4]])),
dims=['y', 'x'],
attrs={'valid_range': np.array([2, 4])})
res = colormap_composite([data, palette])
exp = np.array([[[1.0, 0.498039, 0.246575],
[0., 0.59309977, 1.0]],
[[1.0, 0.49803924, 0.24657543],
[0., 0.59309983, 1.0]],
[[1.0, 0.4980392, 0.24657541],
[0., 0.59309978, 1.0]]])
np.testing.assert_allclose(res, exp, atol=1e-4)
class TestCloudCompositorWithoutCloudfree:
"""Test the CloudCompositorWithoutCloudfree."""
def setup_method(self):
"""Set up the test case."""
from satpy.composites.cloud_products import CloudCompositorWithoutCloudfree
self.colormap_composite = CloudCompositorWithoutCloudfree('test_cmap_compositor')
self.exp = np.array([[4, 3, 2], [2, 3, np.nan], [8, 7, 655350]])
self.exp_bad_oc = np.array([[4, 3, 2],
[2, np.nan, 4],
[np.nan, 7, 255]])
def test_call_numpy_with_invalid_value_in_status(self):
"""Test the CloudCompositorWithoutCloudfree composite generation."""
status = xr.DataArray(np.array([[0, 0, 0], [0, 0, 65535], [0, 0, 1]]), dims=['y', 'x'],
attrs={'_FillValue': 65535})
data = xr.DataArray(np.array([[4, 3, 2], [2, 3, np.nan], [8, 7, np.nan]], dtype=np.float32),
dims=['y', 'x'],
attrs={'_FillValue': 65535,
'scaled_FillValue': 655350})
res = self.colormap_composite([data, status])
np.testing.assert_allclose(res, self.exp, atol=1e-4)
def test_call_dask_with_invalid_value_in_status(self):
"""Test the CloudCompositorWithoutCloudfree composite generation."""
status = xr.DataArray(da.from_array(np.array([[0, 0, 0], [0, 0, 65535], [0, 0, 1]])), dims=['y', 'x'],
attrs={'_FillValue': 65535})
data = xr.DataArray(da.from_array(np.array([[4, 3, 2], [2, 3, np.nan], [8, 7, np.nan]], dtype=np.float32)),
dims=['y', 'x'],
attrs={'_FillValue': 99,
'scaled_FillValue': 655350})
res = self.colormap_composite([data, status])
np.testing.assert_allclose(res, self.exp, atol=1e-4)
def test_call_bad_optical_conditions(self):
"""Test the CloudCompositorWithoutCloudfree composite generation."""
status = xr.DataArray(da.from_array(np.array([[0, 0, 0], [3, 3, 3], [0, 0, 1]])), dims=['y', 'x'],
attrs={'_FillValue': 65535,
"flag_meanings": 'bad_optical_conditions'})
data = xr.DataArray(np.array([[4, 3, 2], [2, 255, 4], [255, 7, 255]], dtype=np.uint8),
dims=['y', 'x'],
name='cmic_cre',
attrs={'_FillValue': 255,
'scaled_FillValue': 255})
res = self.colormap_composite([data, status])
np.testing.assert_allclose(res, self.exp_bad_oc, atol=1e-4)
def test_bad_indata(self):
"""Test the CloudCompositorWithoutCloudfree composite generation without status."""
data = xr.DataArray(np.array([[4, 3, 2], [2, 3, 4], [255, 7, 255]], dtype=np.uint8),
dims=['y', 'x'],
attrs={'_FillValue': 255,
'scaled_FillValue': 255})
np.testing.assert_raises(ValueError, self.colormap_composite, [data])
class TestCloudCompositorCommonMask:
"""Test the CloudCompositorCommonMask."""
def setup_method(self):
"""Set up the test case."""
from satpy.composites.cloud_products import CloudCompositorCommonMask
self.exp_a = np.array([[4, 3, 2],
[2, 3, 655350],
[np.nan, np.nan, np.nan]])
self.exp_b = np.array([[4, 3, 2],
[2, 3, 255],
[np.nan, np.nan, np.nan]])
self.colormap_composite = CloudCompositorCommonMask('test_cmap_compositor')
def test_call_numpy(self):
"""Test the CloudCompositorCommonMask with numpy."""
mask = xr.DataArray(np.array([[0, 0, 0], [1, 1, 1], [255, 255, 255]]), dims=['y', 'x'],
attrs={'_FillValue': 255})
data = xr.DataArray(np.array([[4, 3, 2], [2, 3, np.nan], [np.nan, np.nan, np.nan]], dtype=np.float32),
dims=['y', 'x'],
attrs={'_FillValue': 65535,
'scaled_FillValue': 655350})
res = self.colormap_composite([data, mask])
np.testing.assert_allclose(res, self.exp_a, atol=1e-4)
def test_call_dask(self):
"""Test the CloudCompositorCommonMask with dask."""
mask = xr.DataArray(da.from_array(np.array([[0, 0, 0], [1, 1, 1], [255, 255, 255]])), dims=['y', 'x'],
attrs={'_FillValue': 255})
data = xr.DataArray(da.from_array(np.array([[4, 3, 2], [2, 3, 255], [255, 255, 255]], dtype=np.int16)),
dims=['y', 'x'],
attrs={'_FillValue': 255,
'scaled_FillValue': 255})
res = self.colormap_composite([data, mask])
np.testing.assert_allclose(res, self.exp_b, atol=1e-4)
def test_bad_call(self):
"""Test the CloudCompositorCommonMask without mask."""
data = xr.DataArray(np.array([[4, 3, 2], [2, 3, 255], [255, 255, 255]], dtype=np.int16),
dims=['y', 'x'],
attrs={'_FillValue': 255,
'scaled_FillValue': 255})
np.testing.assert_raises(ValueError, self.colormap_composite, [data])
class TestPrecipCloudsCompositor(unittest.TestCase):
"""Test the PrecipClouds compositor."""
def test_call(self):
"""Test the precip composite generation."""
from satpy.composites.cloud_products import PrecipCloudsRGB
colormap_compositor = PrecipCloudsRGB('test_precip_compositor')
data_light = xr.DataArray(np.array([[80, 70, 60, 0], [20, 30, 40, 255]], dtype=np.uint8),
dims=['y', 'x'], attrs={'_FillValue': 255})
data_moderate = xr.DataArray(np.array([[60, 50, 40, 0], [20, 30, 40, 255]], dtype=np.uint8),
dims=['y', 'x'], attrs={'_FillValue': 255})
data_intense = xr.DataArray(np.array([[40, 30, 20, 0], [20, 30, 40, 255]], dtype=np.uint8),
dims=['y', 'x'], attrs={'_FillValue': 255})
data_flags = xr.DataArray(np.array([[0, 0, 4, 0], [0, 0, 0, 0]], dtype=np.uint8),
dims=['y', 'x'])
res = colormap_compositor([data_light, data_moderate, data_intense, data_flags])
exp = np.array([[[0.24313725, 0.18235294, 0.12156863, np.nan],
[0.12156863, 0.18235294, 0.24313725, np.nan]],
[[0.62184874, 0.51820728, 0.41456583, np.nan],
[0.20728291, 0.31092437, 0.41456583, np.nan]],
[[0.82913165, 0.7254902, 0.62184874, np.nan],
[0.20728291, 0.31092437, 0.41456583, np.nan]]])
np.testing.assert_allclose(res, exp)
class TestSingleBandCompositor(unittest.TestCase):
"""Test the single-band compositor."""
def setUp(self):
"""Create test data."""
from satpy.composites import SingleBandCompositor
self.comp = SingleBandCompositor(name='test')
all_valid = np.ones((2, 2))
self.all_valid = xr.DataArray(all_valid, dims=['y', 'x'])
def test_call(self):
"""Test calling the compositor."""
# Dataset with extra attributes
all_valid = self.all_valid
all_valid.attrs['sensor'] = 'foo'
attrs = {
'foo': 'bar',
'resolution': 333,
'units': 'K',
'sensor': {'fake_sensor1', 'fake_sensor2'},
'calibration': 'BT',
'wavelength': 10.8
}
self.comp.attrs['resolution'] = None
res = self.comp([all_valid], **attrs)
# Verify attributes
self.assertEqual(res.attrs.get('sensor'), 'foo')
self.assertTrue('foo' in res.attrs)
self.assertEqual(res.attrs.get('foo'), 'bar')
self.assertTrue('units' in res.attrs)
self.assertTrue('calibration' in res.attrs)
self.assertFalse('modifiers' in res.attrs)
self.assertEqual(res.attrs['wavelength'], 10.8)
self.assertEqual(res.attrs['resolution'], 333)
class TestCategoricalDataCompositor(unittest.TestCase):
"""Test composiotor for recategorization of categorical data."""
def setUp(self):
"""Create test data."""
attrs = {'name': 'foo'}
data = xr.DataArray(da.from_array([[2., 1.], [3., 0.]]), attrs=attrs,
dims=('y', 'x'), coords={'y': [0, 1], 'x': [0, 1]})
self.data = data
def test_basic_recategorization(self):
"""Test general functionality of compositor incl. attributes."""
from satpy.composites import CategoricalDataCompositor
lut = [np.nan, 0, 1, 1]
name = 'bar'
comp = CategoricalDataCompositor(name=name, lut=lut)
res = comp([self.data])
res = res.compute()
expected = np.array([[1., 0.], [1., np.nan]])
np.testing.assert_equal(res.values, expected)
np.testing.assert_equal(res.attrs['name'], name)
np.testing.assert_equal(res.attrs['composite_lut'], lut)
def test_too_many_datasets(self):
"""Test that ValueError is raised if more than one dataset is provided."""
from satpy.composites import CategoricalDataCompositor
lut = [np.nan, 0, 1, 1]
comp = CategoricalDataCompositor(name='foo', lut=lut)
np.testing.assert_raises(ValueError, comp, [self.data, self.data])
class TestGenericCompositor(unittest.TestCase):
"""Test generic compositor."""
def setUp(self):
"""Create test data."""
from satpy.composites import GenericCompositor
self.comp = GenericCompositor(name='test')
self.comp2 = GenericCompositor(name='test2', common_channel_mask=False)
all_valid = np.ones((1, 2, 2))
self.all_valid = xr.DataArray(all_valid, dims=['bands', 'y', 'x'])
first_invalid = np.reshape(np.array([np.nan, 1., 1., 1.]), (1, 2, 2))
self.first_invalid = xr.DataArray(first_invalid,
dims=['bands', 'y', 'x'])
second_invalid = np.reshape(np.array([1., np.nan, 1., 1.]), (1, 2, 2))
self.second_invalid = xr.DataArray(second_invalid,