forked from pytroll/satpy
/
test_scene.py
2192 lines (1930 loc) · 94 KB
/
test_scene.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) 2010-2019 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/>.
"""Unit tests for scene.py."""
import math
import os
import random
import string
import unittest
from copy import deepcopy
from datetime import datetime
from unittest import mock
import dask.array as da
import numpy as np
import pytest
import xarray as xr
import satpy
from satpy import Scene
from satpy.tests.utils import (
FAKE_FILEHANDLER_END,
FAKE_FILEHANDLER_START,
default_id_keys_config,
make_cid,
make_dataid,
make_dsq,
spy_decorator,
)
TEST_ETC_DIR = os.path.join(os.path.dirname(__file__), 'etc')
def _check_comp19_deps_are_loaded(scene):
# comp19 required resampling to produce so we should have its 3 deps
# 1. comp13
# 2. ds5
# 3. ds2
loaded_ids = list(scene.keys())
assert len(loaded_ids) == 3
for name in ('comp13', 'ds5', 'ds2'):
assert any(x['name'] == name for x in loaded_ids)
class TestScene:
"""Test the scene class."""
def setup_method(self):
"""Set config_path to point to test 'etc' directory."""
self.old_config_path = satpy.config.get('config_path')
satpy.config.set(config_path=[TEST_ETC_DIR])
def teardown_method(self):
"""Restore previous 'config_path' setting."""
satpy.config.set(config_path=self.old_config_path)
def test_init(self):
"""Test scene initialization."""
with mock.patch('satpy.scene.Scene._create_reader_instances') as cri:
cri.return_value = {}
Scene(filenames=['bla'], reader='blo')
cri.assert_called_once_with(filenames=['bla'], reader='blo',
reader_kwargs=None)
def test_init_str_filename(self):
"""Test initializing with a single string as filenames."""
pytest.raises(ValueError, Scene, reader='blo', filenames='test.nc')
def test_start_end_times(self):
"""Test start and end times for a scene."""
scene = Scene(filenames=['fake1_1.txt'], reader='fake1')
assert scene.start_time == FAKE_FILEHANDLER_START
assert scene.end_time == FAKE_FILEHANDLER_END
def test_init_preserve_reader_kwargs(self):
"""Test that the initialization preserves the kwargs."""
cri = spy_decorator(Scene._create_reader_instances)
with mock.patch('satpy.scene.Scene._create_reader_instances', cri):
reader_kwargs = {'calibration_type': 'gsics'}
scene = Scene(filenames=['fake1_1.txt'],
reader='fake1',
filter_parameters={'area': 'euron1'},
reader_kwargs=reader_kwargs)
assert reader_kwargs is not cri.mock.call_args[1]['reader_kwargs']
assert scene.start_time == FAKE_FILEHANDLER_START
assert scene.end_time == FAKE_FILEHANDLER_END
@pytest.mark.parametrize(
("reader", "filenames", "exp_sensors"),
[
("fake1", ["fake1_1.txt"], {"fake_sensor"}),
(None, {"fake1": ["fake1_1.txt"], "fake2_1ds": ["fake2_1ds_1.txt"]}, {"fake_sensor", "fake_sensor2"}),
]
)
def test_sensor_names_readers(self, reader, filenames, exp_sensors):
"""Test that Scene sensor_names handles different cases properly."""
scene = Scene(reader=reader, filenames=filenames)
assert scene.start_time == FAKE_FILEHANDLER_START
assert scene.end_time == FAKE_FILEHANDLER_END
assert scene.sensor_names == exp_sensors
@pytest.mark.parametrize(
("include_reader", "added_sensor", "exp_sensors"),
[
(False, "my_sensor", {"my_sensor"}),
(True, "my_sensor", {"my_sensor", "fake_sensor"}),
(False, {"my_sensor"}, {"my_sensor"}),
(True, {"my_sensor"}, {"my_sensor", "fake_sensor"}),
(False, {"my_sensor1", "my_sensor2"}, {"my_sensor1", "my_sensor2"}),
(True, {"my_sensor1", "my_sensor2"}, {"my_sensor1", "my_sensor2", "fake_sensor"}),
]
)
def test_sensor_names_added_datasets(self, include_reader, added_sensor, exp_sensors):
"""Test that Scene sensor_names handles contained sensors properly."""
if include_reader:
scene = Scene(reader="fake1", filenames=["fake1_1.txt"])
else:
scene = Scene()
scene["my_ds"] = xr.DataArray([], attrs={"sensor": added_sensor})
assert scene.sensor_names == exp_sensors
def test_init_alone(self):
"""Test simple initialization."""
scn = Scene()
assert not scn._readers, 'Empty scene should not load any readers'
def test_init_no_files(self):
"""Test that providing an empty list of filenames fails."""
pytest.raises(ValueError, Scene, reader='viirs_sdr', filenames=[])
def test_create_reader_instances_with_filenames(self):
"""Test creating a reader providing filenames."""
filenames = ["bla", "foo", "bar"]
reader_name = None
with mock.patch('satpy.scene.load_readers') as findermock:
Scene(filenames=filenames)
findermock.assert_called_once_with(
filenames=filenames,
reader=reader_name,
reader_kwargs=None,
)
def test_init_with_empty_filenames(self):
"""Test initialization with empty filename list."""
filenames = []
Scene(filenames=filenames)
def test_init_with_fsfile(self):
"""Test initialisation with FSFile objects."""
from satpy.readers import FSFile
# We should not mock _create_reader_instances here, because in
# https://github.com/pytroll/satpy/issues/1605 satpy fails with
# TypeError within that method if passed an FSFile instance.
# Instead rely on the ValueError that satpy raises if no readers
# are found.
# Choose random filename that doesn't exist. Not using tempfile here,
# because tempfile creates files and we don't want that here.
fsf = FSFile("".join(random.choices(string.printable, k=50)))
with pytest.raises(ValueError, match="No supported files found"):
Scene(filenames=[fsf], reader=[])
# TODO: Rewrite this test for the 'find_files_and_readers' function
# def test_create_reader_instances_with_sensor(self):
# import satpy.scene
# sensors = ["bla", "foo", "bar"]
# filenames = None
# reader_name = None
# with mock.patch('satpy.scene.Scene._compute_metadata_from_readers'):
# with mock.patch('satpy.scene.load_readers') as findermock:
# scene = satpy.scene.Scene(sensor=sensors)
# findermock.assert_called_once_with(
# ppp_config_dir=mock.ANY,
# reader=reader_name,
# filenames=filenames,
# reader_kwargs=None,
# )
# def test_create_reader_instances_with_sensor_and_filenames(self):
# import satpy.scene
# sensors = ["bla", "foo", "bar"]
# filenames = ["1", "2", "3"]
# reader_name = None
# with mock.patch('satpy.scene.Scene._compute_metadata_from_readers'):
# with mock.patch('satpy.scene.load_readers') as findermock:
# scene = satpy.scene.Scene(sensor=sensors, filenames=filenames)
# findermock.assert_called_once_with(
# ppp_config_dir=mock.ANY,
# reader=reader_name,
# sensor=sensors,
# filenames=filenames,
# reader_kwargs=None,
# )
def test_create_reader_instances_with_reader(self):
"""Test createring a reader instance providing the reader name."""
reader = "foo"
filenames = ["1", "2", "3"]
with mock.patch('satpy.scene.load_readers') as findermock:
findermock.return_value = {}
Scene(reader=reader, filenames=filenames)
findermock.assert_called_once_with(reader=reader,
filenames=filenames,
reader_kwargs=None,
)
def test_create_reader_instances_with_reader_kwargs(self):
"""Test creating a reader instance with reader kwargs."""
from satpy.readers.yaml_reader import FileYAMLReader
reader_kwargs = {'calibration_type': 'gsics'}
filter_parameters = {'area': 'euron1'}
reader_kwargs2 = {'calibration_type': 'gsics', 'filter_parameters': filter_parameters}
rinit = spy_decorator(FileYAMLReader.create_filehandlers)
with mock.patch('satpy.readers.yaml_reader.FileYAMLReader.create_filehandlers', rinit):
scene = Scene(filenames=['fake1_1.txt'],
reader='fake1',
filter_parameters={'area': 'euron1'},
reader_kwargs=reader_kwargs)
del scene
assert reader_kwargs == rinit.mock.call_args[1]['fh_kwargs']
rinit.mock.reset_mock()
scene = Scene(filenames=['fake1_1.txt'],
reader='fake1',
reader_kwargs=reader_kwargs2)
assert reader_kwargs == rinit.mock.call_args[1]['fh_kwargs']
del scene
def test_create_multiple_reader_different_kwargs(self):
"""Test passing different kwargs to different readers."""
from satpy.readers import load_reader
with satpy.config.set(config_path=[TEST_ETC_DIR]), \
mock.patch.object(satpy.readers, 'load_reader', wraps=load_reader) as lr:
Scene(filenames={"fake1_1ds": ["fake1_1ds_1.txt"],
"fake2_1ds": ["fake2_1ds_1.txt"]},
reader_kwargs={
"fake1_1ds": {"mouth": "omegna"},
"fake2_1ds": {"mouth": "varallo"}
})
lr.assert_has_calls([
mock.call([os.path.join(TEST_ETC_DIR, 'readers', 'fake1_1ds.yaml')], mouth="omegna"),
mock.call([os.path.join(TEST_ETC_DIR, 'readers', 'fake2_1ds.yaml')], mouth="varallo")])
def test_iter(self):
"""Test iteration over the scene."""
scene = Scene()
scene["1"] = xr.DataArray(np.arange(5))
scene["2"] = xr.DataArray(np.arange(5))
scene["3"] = xr.DataArray(np.arange(5))
for x in scene:
assert isinstance(x, xr.DataArray)
def test_iter_by_area_swath(self):
"""Test iterating by area on a swath."""
from pyresample.geometry import SwathDefinition
scene = Scene()
sd = SwathDefinition(lons=np.arange(5), lats=np.arange(5))
scene["1"] = xr.DataArray(np.arange(5), attrs={'area': sd})
scene["2"] = xr.DataArray(np.arange(5), attrs={'area': sd})
scene["3"] = xr.DataArray(np.arange(5))
for area_obj, ds_list in scene.iter_by_area():
ds_list_names = set(ds['name'] for ds in ds_list)
if area_obj is sd:
assert ds_list_names == {'1', '2'}
else:
assert area_obj is None
assert ds_list_names == {'3'}
def test_bad_setitem(self):
"""Test setting an item wrongly."""
scene = Scene()
pytest.raises(ValueError, scene.__setitem__, '1', np.arange(5))
def test_setitem(self):
"""Test setting an item."""
from satpy.tests.utils import make_dataid
scene = Scene()
scene["1"] = ds1 = xr.DataArray(np.arange(5))
expected_id = make_cid(**ds1.attrs)
assert set(scene._datasets.keys()) == {expected_id}
assert set(scene._wishlist) == {expected_id}
did = make_dataid(name='oranges')
scene[did] = ds1
assert 'oranges' in scene
nparray = np.arange(5*5).reshape(5, 5)
with pytest.raises(ValueError):
scene['apples'] = nparray
assert 'apples' not in scene
did = make_dataid(name='apples')
scene[did] = nparray
assert 'apples' in scene
def test_getitem(self):
"""Test __getitem__ with names only."""
scene = Scene()
scene["1"] = ds1 = xr.DataArray(np.arange(5))
scene["2"] = ds2 = xr.DataArray(np.arange(5))
scene["3"] = ds3 = xr.DataArray(np.arange(5))
assert scene['1'] is ds1
assert scene['2'] is ds2
assert scene['3'] is ds3
pytest.raises(KeyError, scene.__getitem__, '4')
assert scene.get('3') is ds3
assert scene.get('4') is None
def test_getitem_modifiers(self):
"""Test __getitem__ with names and modifiers."""
# Return least modified item
scene = Scene()
scene['1'] = ds1_m0 = xr.DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1',))
] = xr.DataArray(np.arange(5))
assert scene['1'] is ds1_m0
assert len(list(scene.keys())) == 2
scene = Scene()
scene['1'] = ds1_m0 = xr.DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1',))
] = xr.DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1', 'mod2'))
] = xr.DataArray(np.arange(5))
assert scene['1'] is ds1_m0
assert len(list(scene.keys())) == 3
scene = Scene()
scene[make_dataid(name='1', modifiers=('mod1', 'mod2'))
] = ds1_m2 = xr.DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1',))
] = ds1_m1 = xr.DataArray(np.arange(5))
assert scene['1'] is ds1_m1
assert scene[make_dataid(name='1', modifiers=('mod1', 'mod2'))] is ds1_m2
pytest.raises(KeyError, scene.__getitem__,
make_dataid(name='1', modifiers=tuple()))
assert len(list(scene.keys())) == 2
def test_getitem_slices(self):
"""Test __getitem__ with slices."""
from pyresample.geometry import AreaDefinition, SwathDefinition
from pyresample.utils import proj4_str_to_dict
scene1 = Scene()
scene2 = Scene()
proj_dict = proj4_str_to_dict('+proj=lcc +datum=WGS84 +ellps=WGS84 '
'+lon_0=-95. +lat_0=25 +lat_1=25 '
'+units=m +no_defs')
area_def = AreaDefinition(
'test',
'test',
'test',
proj_dict,
200,
400,
(-1000., -1500., 1000., 1500.),
)
swath_def = SwathDefinition(lons=np.zeros((5, 10)),
lats=np.zeros((5, 10)))
scene1["1"] = scene2["1"] = xr.DataArray(np.zeros((5, 10)))
scene1["2"] = scene2["2"] = xr.DataArray(np.zeros((5, 10)),
dims=('y', 'x'))
scene1["3"] = xr.DataArray(np.zeros((5, 10)), dims=('y', 'x'),
attrs={'area': area_def})
anc_vars = [xr.DataArray(np.ones((5, 10)),
attrs={'name': 'anc_var', 'area': area_def})]
attrs = {'ancillary_variables': anc_vars, 'area': area_def}
scene1["3a"] = xr.DataArray(np.zeros((5, 10)),
dims=('y', 'x'),
attrs=attrs)
scene2["4"] = xr.DataArray(np.zeros((5, 10)), dims=('y', 'x'),
attrs={'area': swath_def})
anc_vars = [xr.DataArray(np.ones((5, 10)),
attrs={'name': 'anc_var', 'area': swath_def})]
attrs = {'ancillary_variables': anc_vars, 'area': swath_def}
scene2["4a"] = xr.DataArray(np.zeros((5, 10)),
dims=('y', 'x'),
attrs=attrs)
new_scn1 = scene1[2:5, 2:8]
new_scn2 = scene2[2:5, 2:8]
for new_scn in [new_scn1, new_scn2]:
# datasets without an area don't get sliced
assert new_scn['1'].shape == (5, 10)
assert new_scn['2'].shape == (5, 10)
assert new_scn1['3'].shape == (3, 6)
assert 'area' in new_scn1['3'].attrs
assert new_scn1['3'].attrs['area'].shape == (3, 6)
assert new_scn1['3a'].shape == (3, 6)
a_var = new_scn1['3a'].attrs['ancillary_variables'][0]
assert a_var.shape == (3, 6)
assert new_scn2['4'].shape == (3, 6)
assert 'area' in new_scn2['4'].attrs
assert new_scn2['4'].attrs['area'].shape == (3, 6)
assert new_scn2['4a'].shape == (3, 6)
a_var = new_scn2['4a'].attrs['ancillary_variables'][0]
assert a_var.shape == (3, 6)
def test_crop(self):
"""Test the crop method."""
from pyresample.geometry import AreaDefinition
scene1 = Scene()
area_extent = (-5570248.477339745, -5561247.267842293, 5567248.074173927,
5570248.477339745)
proj_dict = {'a': 6378169.0, 'b': 6356583.8, 'h': 35785831.0,
'lon_0': 0.0, 'proj': 'geos', 'units': 'm'}
x_size = 3712
y_size = 3712
area_def = AreaDefinition(
'test',
'test',
'test',
proj_dict,
x_size,
y_size,
area_extent,
)
area_def2 = AreaDefinition(
'test2',
'test2',
'test2',
proj_dict,
x_size // 2,
y_size // 2,
area_extent,
)
scene1["1"] = xr.DataArray(np.zeros((y_size, x_size)))
scene1["2"] = xr.DataArray(np.zeros((y_size, x_size)), dims=('y', 'x'))
scene1["3"] = xr.DataArray(np.zeros((y_size, x_size)), dims=('y', 'x'),
attrs={'area': area_def})
scene1["4"] = xr.DataArray(np.zeros((y_size // 2, x_size // 2)), dims=('y', 'x'),
attrs={'area': area_def2})
# by area
crop_area = AreaDefinition(
'test',
'test',
'test',
proj_dict,
x_size,
y_size,
(area_extent[0] + 10000., area_extent[1] + 500000.,
area_extent[2] - 10000., area_extent[3] - 500000.)
)
new_scn1 = scene1.crop(crop_area)
assert '1' in new_scn1
assert '2' in new_scn1
assert '3' in new_scn1
assert new_scn1['1'].shape == (y_size, x_size)
assert new_scn1['2'].shape == (y_size, x_size)
assert new_scn1['3'].shape == (3380, 3708)
assert new_scn1['4'].shape == (1690, 1854)
# by lon/lat bbox
new_scn1 = scene1.crop(ll_bbox=(-20., -5., 0, 0))
assert '1' in new_scn1
assert '2' in new_scn1
assert '3' in new_scn1
assert new_scn1['1'].shape == (y_size, x_size)
assert new_scn1['2'].shape == (y_size, x_size)
assert new_scn1['3'].shape == (184, 714)
assert new_scn1['4'].shape == (92, 357)
# by x/y bbox
new_scn1 = scene1.crop(xy_bbox=(-200000., -100000., 0, 0))
assert '1' in new_scn1
assert '2' in new_scn1
assert '3' in new_scn1
assert new_scn1['1'].shape == (y_size, x_size)
assert new_scn1['2'].shape == (y_size, x_size)
assert new_scn1['3'].shape == (36, 70)
assert new_scn1['4'].shape == (18, 35)
def test_crop_epsg_crs(self):
"""Test the crop method when source area uses an EPSG code."""
from pyresample.geometry import AreaDefinition
scene1 = Scene()
area_extent = (699960.0, 5390220.0, 809760.0, 5500020.0)
x_size = 3712
y_size = 3712
area_def = AreaDefinition(
'test', 'test', 'test',
"EPSG:32630",
x_size,
y_size,
area_extent,
)
scene1["1"] = xr.DataArray(np.zeros((y_size, x_size)), dims=('y', 'x'),
attrs={'area': area_def})
# by x/y bbox
new_scn1 = scene1.crop(xy_bbox=(719695.7781587119, 5427887.407618969, 725068.1609052602, 5433708.364368956))
assert '1' in new_scn1
assert new_scn1['1'].shape == (198, 182)
def test_crop_rgb(self):
"""Test the crop method on multi-dimensional data."""
from pyresample.geometry import AreaDefinition
scene1 = Scene()
area_extent = (-5570248.477339745, -5561247.267842293, 5567248.074173927,
5570248.477339745)
proj_dict = {'a': 6378169.0, 'b': 6356583.8, 'h': 35785831.0,
'lon_0': 0.0, 'proj': 'geos', 'units': 'm'}
x_size = 3712
y_size = 3712
area_def = AreaDefinition(
'test',
'test',
'test',
proj_dict,
x_size,
y_size,
area_extent,
)
area_def2 = AreaDefinition(
'test2',
'test2',
'test2',
proj_dict,
x_size // 2,
y_size // 2,
area_extent,
)
scene1["1"] = xr.DataArray(np.zeros((3, y_size, x_size)),
dims=('bands', 'y', 'x'),
attrs={'area': area_def})
scene1["2"] = xr.DataArray(np.zeros((y_size // 2, 3, x_size // 2)),
dims=('y', 'bands', 'x'),
attrs={'area': area_def2})
# by lon/lat bbox
new_scn1 = scene1.crop(ll_bbox=(-20., -5., 0, 0))
assert '1' in new_scn1
assert '2' in new_scn1
assert 'bands' in new_scn1['1'].dims
assert 'bands' in new_scn1['2'].dims
assert new_scn1['1'].shape == (3, 184, 714)
assert new_scn1['2'].shape == (92, 3, 357)
def test_contains(self):
"""Test contains."""
scene = Scene()
scene["1"] = xr.DataArray(np.arange(5),
attrs={'wavelength': (0.1, 0.2, 0.3),
'_satpy_id_keys': default_id_keys_config})
assert '1' in scene
assert 0.15 in scene
assert '2' not in scene
assert 0.31 not in scene
scene = Scene()
scene['blueberry'] = xr.DataArray(np.arange(5))
scene['blackberry'] = xr.DataArray(np.arange(5))
scene['strawberry'] = xr.DataArray(np.arange(5))
scene['raspberry'] = xr.DataArray(np.arange(5))
# deepcode ignore replace~keys~list~compare: This is on purpose
assert make_cid(name='blueberry') in scene.keys()
assert make_cid(name='blueberry') in scene
assert 'blueberry' in scene
assert 'blueberry' not in scene.keys()
def test_delitem(self):
"""Test deleting an item."""
scene = Scene()
scene["1"] = xr.DataArray(np.arange(5),
attrs={'wavelength': (0.1, 0.2, 0.3),
'_satpy_id_keys': default_id_keys_config})
scene["2"] = xr.DataArray(np.arange(5),
attrs={'wavelength': (0.4, 0.5, 0.6),
'_satpy_id_keys': default_id_keys_config})
scene["3"] = xr.DataArray(np.arange(5),
attrs={'wavelength': (0.7, 0.8, 0.9),
'_satpy_id_keys': default_id_keys_config})
del scene['1']
del scene['3']
del scene[0.45]
assert not scene._wishlist
assert not list(scene._datasets.keys())
pytest.raises(KeyError, scene.__delitem__, 0.2)
def test_all_datasets_no_readers(self):
"""Test all datasets with no reader."""
scene = Scene()
pytest.raises(KeyError, scene.all_dataset_ids, reader_name='fake')
id_list = scene.all_dataset_ids()
assert id_list == []
# no sensors are loaded so we shouldn't get any comps either
id_list = scene.all_dataset_ids(composites=True)
assert id_list == []
def test_all_dataset_names_no_readers(self):
"""Test all dataset names with no reader."""
scene = Scene()
pytest.raises(KeyError, scene.all_dataset_names, reader_name='fake')
name_list = scene.all_dataset_names()
assert name_list == []
# no sensors are loaded so we shouldn't get any comps either
name_list = scene.all_dataset_names(composites=True)
assert name_list == []
def test_available_dataset_no_readers(self):
"""Test the available datasets without a reader."""
scene = Scene()
pytest.raises(
KeyError, scene.available_dataset_ids, reader_name='fake')
name_list = scene.available_dataset_ids()
assert name_list == []
# no sensors are loaded so we shouldn't get any comps either
name_list = scene.available_dataset_ids(composites=True)
assert name_list == []
def test_available_dataset_names_no_readers(self):
"""Test the available dataset names without a reader."""
scene = Scene()
pytest.raises(
KeyError, scene.available_dataset_names, reader_name='fake')
name_list = scene.available_dataset_names()
assert name_list == []
# no sensors are loaded so we shouldn't get any comps either
name_list = scene.available_dataset_names(composites=True)
assert name_list == []
def test_storage_options_from_reader_kwargs_no_options(self):
"""Test getting storage options from reader kwargs.
Case where there are no options given.
"""
filenames = ["s3://data-bucket/file1", "s3://data-bucket/file2", "s3://data-bucket/file3"]
with mock.patch('satpy.scene.load_readers'):
with mock.patch('fsspec.open_files') as open_files:
Scene(filenames=filenames)
open_files.assert_called_once_with(filenames)
def test_storage_options_from_reader_kwargs_single_dict_no_options(self):
"""Test getting storage options from reader kwargs for remote files.
Case where a single dict is given for all readers without storage options.
"""
filenames = ["s3://data-bucket/file1", "s3://data-bucket/file2", "s3://data-bucket/file3"]
reader_kwargs = {'reader_opt': 'foo'}
with mock.patch('satpy.scene.load_readers'):
with mock.patch('fsspec.open_files') as open_files:
Scene(filenames=filenames, reader_kwargs=reader_kwargs)
open_files.assert_called_once_with(filenames)
def test_storage_options_from_reader_kwargs_single_dict(self):
"""Test getting storage options from reader kwargs.
Case where a single dict is given for all readers with some common storage options.
"""
filenames = ["s3://data-bucket/file1", "s3://data-bucket/file2", "s3://data-bucket/file3"]
reader_kwargs = {'reader_opt': 'foo'}
expected_reader_kwargs = reader_kwargs.copy()
storage_options = {'option1': '1'}
reader_kwargs['storage_options'] = storage_options
orig_reader_kwargs = deepcopy(reader_kwargs)
with mock.patch('satpy.scene.load_readers') as load_readers:
with mock.patch('fsspec.open_files') as open_files:
Scene(filenames=filenames, reader_kwargs=reader_kwargs)
call_ = load_readers.mock_calls[0]
assert call_.kwargs['reader_kwargs'] == expected_reader_kwargs
open_files.assert_called_once_with(filenames, **storage_options)
assert reader_kwargs == orig_reader_kwargs
def test_storage_options_from_reader_kwargs_per_reader(self):
"""Test getting storage options from reader kwargs.
Case where each reader have their own storage options.
"""
filenames = {
"reader1": ["s3://data-bucket/file1"],
"reader2": ["s3://data-bucket/file2"],
"reader3": ["s3://data-bucket/file3"],
}
storage_options_1 = {'option1': '1'}
storage_options_2 = {'option2': '2'}
storage_options_3 = {'option3': '3'}
reader_kwargs = {
"reader1": {'reader_opt_1': 'foo'},
"reader2": {'reader_opt_2': 'bar'},
"reader3": {'reader_opt_3': 'baz'},
}
expected_reader_kwargs = deepcopy(reader_kwargs)
reader_kwargs['reader1']['storage_options'] = storage_options_1
reader_kwargs['reader2']['storage_options'] = storage_options_2
reader_kwargs['reader3']['storage_options'] = storage_options_3
orig_reader_kwargs = deepcopy(reader_kwargs)
with mock.patch('satpy.scene.load_readers') as load_readers:
with mock.patch('fsspec.open_files') as open_files:
Scene(filenames=filenames, reader_kwargs=reader_kwargs)
call_ = load_readers.mock_calls[0]
assert call_.kwargs['reader_kwargs'] == expected_reader_kwargs
assert mock.call(filenames["reader1"], **storage_options_1) in open_files.mock_calls
assert mock.call(filenames["reader2"], **storage_options_2) in open_files.mock_calls
assert mock.call(filenames["reader3"], **storage_options_3) in open_files.mock_calls
assert reader_kwargs == orig_reader_kwargs
def test_storage_options_from_reader_kwargs_per_reader_and_global(self):
"""Test getting storage options from reader kwargs.
Case where each reader have their own storage options and there are
global options to merge.
"""
filenames = {
"reader1": ["s3://data-bucket/file1"],
"reader2": ["s3://data-bucket/file2"],
"reader3": ["s3://data-bucket/file3"],
}
reader_kwargs = {
"reader1": {'reader_opt_1': 'foo', 'storage_options': {'option1': '1'}},
"reader2": {'reader_opt_2': 'bar', 'storage_options': {'option2': '2'}},
"storage_options": {"endpoint_url": "url"},
}
orig_reader_kwargs = deepcopy(reader_kwargs)
with mock.patch('satpy.scene.load_readers'):
with mock.patch('fsspec.open_files') as open_files:
Scene(filenames=filenames, reader_kwargs=reader_kwargs)
assert mock.call(filenames["reader1"], option1='1', endpoint_url='url') in open_files.mock_calls
assert mock.call(filenames["reader2"], option2='2', endpoint_url='url') in open_files.mock_calls
assert reader_kwargs == orig_reader_kwargs
def _create_coarest_finest_data_array(shape, area_def, attrs=None):
data_arr = xr.DataArray(
da.arange(math.prod(shape)).reshape(shape),
attrs={
'area': area_def,
})
if attrs:
data_arr.attrs.update(attrs)
return data_arr
def _create_coarsest_finest_area_def(shape, extents):
from pyresample import AreaDefinition
proj_str = '+proj=lcc +datum=WGS84 +ellps=WGS84 +lon_0=-95. +lat_0=25 +lat_1=25 +units=m +no_defs'
area_def = AreaDefinition(
'test',
'test',
'test',
proj_str,
shape[1],
shape[0],
extents,
)
return area_def
def _create_coarsest_finest_swath_def(shape, extents, name_suffix):
from pyresample import SwathDefinition
if len(shape) == 1:
lons_arr = da.linspace(extents[0], extents[2], shape[0], dtype=np.float32)
lats_arr = da.linspace(extents[1], extents[3], shape[0], dtype=np.float32)
else:
lons_arr = da.repeat(da.linspace(extents[0], extents[2], shape[1], dtype=np.float32)[None, :], shape[0], axis=0)
lats_arr = da.repeat(da.linspace(extents[1], extents[3], shape[0], dtype=np.float32)[:, None], shape[1], axis=1)
lons_data_arr = xr.DataArray(lons_arr, attrs={"name": f"longitude{name_suffix}"})
lats_data_arr = xr.DataArray(lats_arr, attrs={"name": f"latitude1{name_suffix}"})
return SwathDefinition(lons_data_arr, lats_data_arr)
class TestFinestCoarsestArea:
"""Test the Scene logic for finding the finest and coarsest area."""
@pytest.mark.parametrize(
("coarse_area", "fine_area"),
[
(_create_coarsest_finest_area_def((2, 5), (1000.0, 1500.0, -1000.0, -1500.0)),
_create_coarsest_finest_area_def((4, 10), (1000.0, 1500.0, -1000.0, -1500.0))),
(_create_coarsest_finest_area_def((2, 5), (-1000.0, -1500.0, 1000.0, 1500.0)),
_create_coarsest_finest_area_def((4, 10), (-1000.0, -1500.0, 1000.0, 1500.0))),
(_create_coarsest_finest_swath_def((2, 5), (1000.0, 1500.0, -1000.0, -1500.0), "1"),
_create_coarsest_finest_swath_def((4, 10), (1000.0, 1500.0, -1000.0, -1500.0), "1")),
(_create_coarsest_finest_swath_def((5,), (1000.0, 1500.0, -1000.0, -1500.0), "1"),
_create_coarsest_finest_swath_def((10,), (1000.0, 1500.0, -1000.0, -1500.0), "1")),
]
)
def test_coarsest_finest_area_different_shape(self, coarse_area, fine_area):
"""Test 'coarsest_area' and 'finest_area' methods for upright areas."""
ds1 = _create_coarest_finest_data_array(coarse_area.shape, coarse_area, {"wavelength": (0.1, 0.2, 0.3)})
ds2 = _create_coarest_finest_data_array(fine_area.shape, fine_area, {"wavelength": (0.4, 0.5, 0.6)})
ds3 = _create_coarest_finest_data_array(fine_area.shape, fine_area, {"wavelength": (0.7, 0.8, 0.9)})
scn = Scene()
scn["1"] = ds1
scn["2"] = ds2
scn["3"] = ds3
assert scn.coarsest_area() is coarse_area
assert scn.finest_area() is fine_area
assert scn.coarsest_area(['2', '3']) is fine_area
@pytest.mark.parametrize(
("area_def", "shifted_area"),
[
(_create_coarsest_finest_area_def((2, 5), (-1000.0, -1500.0, 1000.0, 1500.0)),
_create_coarsest_finest_area_def((2, 5), (-900.0, -1400.0, 1100.0, 1600.0))),
(_create_coarsest_finest_swath_def((2, 5), (-1000.0, -1500.0, 1000.0, 1500.0), "1"),
_create_coarsest_finest_swath_def((2, 5), (-900.0, -1400.0, 1100.0, 1600.0), "2")),
],
)
def test_coarsest_finest_area_same_shape(self, area_def, shifted_area):
"""Test that two areas with the same shape are consistently returned.
If two geometries (ex. two AreaDefinitions or two SwathDefinitions)
have the same resolution (shape) but different
coordinates, which one has the finer resolution would ultimately be
determined by the semi-random ordering of the internal container of
the Scene (a dict) if only pixel resolution was compared. This test
makes sure that it is always the same object returned.
"""
ds1 = _create_coarest_finest_data_array(area_def.shape, area_def)
ds2 = _create_coarest_finest_data_array(area_def.shape, shifted_area)
scn = Scene()
scn["ds1"] = ds1
scn["ds2"] = ds2
course_area1 = scn.coarsest_area()
scn = Scene()
scn["ds2"] = ds2
scn["ds1"] = ds1
coarse_area2 = scn.coarsest_area()
# doesn't matter what order they were added, this should be the same area
assert coarse_area2 is course_area1
class TestSceneAvailableDatasets:
"""Test the Scene's handling of various dependencies."""
def setup_method(self):
"""Set config_path to point to test 'etc' directory."""
self.old_config_path = satpy.config.get('config_path')
satpy.config.set(config_path=[TEST_ETC_DIR])
def teardown_method(self):
"""Restore previous 'config_path' setting."""
satpy.config.set(config_path=self.old_config_path)
def test_all_datasets_one_reader(self):
"""Test all datasets for one reader."""
scene = Scene(filenames=['fake1_1.txt'],
reader='fake1')
id_list = scene.all_dataset_ids()
# 20 data products + 6 lon/lat products
num_reader_ds = 21 + 6
assert len(id_list) == num_reader_ds
id_list = scene.all_dataset_ids(composites=True)
assert len(id_list) == num_reader_ds + 33
def test_all_datasets_multiple_reader(self):
"""Test all datasets for multiple readers."""
scene = Scene(filenames={'fake1_1ds': ['fake1_1ds_1.txt'],
'fake2_1ds': ['fake2_1ds_1.txt']})
id_list = scene.all_dataset_ids()
assert len(id_list) == 2
id_list = scene.all_dataset_ids(composites=True)
# ds1 and ds2 => 2
# composites that use these two datasets => 11
assert len(id_list) == 2 + 11
def test_available_datasets_one_reader(self):
"""Test the available datasets for one reader."""
scene = Scene(filenames=['fake1_1ds_1.txt'],
reader='fake1_1ds')
id_list = scene.available_dataset_ids()
assert len(id_list) == 1
id_list = scene.available_dataset_ids(composites=True)
# ds1, comp1, comp14, comp16, static_image, comp26
assert len(id_list) == 6
def test_available_composite_ids_missing_available(self):
"""Test available_composite_ids when a composites dep is missing."""
scene = Scene(filenames=['fake1_1ds_1.txt'],
reader='fake1_1ds')
assert 'comp2' not in scene.available_composite_names()
def test_available_composites_known_versus_all(self):
"""Test available_composite_ids when some datasets aren't available."""
scene = Scene(filenames=['fake1_1.txt'], reader='fake1',
reader_kwargs={"not_available": ["ds2", "ds3"]})
all_comps = scene.all_composite_names()
avail_comps = scene.available_composite_names()
# there should always be more known composites than available composites
assert len(all_comps) > len(avail_comps)
for not_avail_comp in ("comp2", "comp3"):
assert not_avail_comp in all_comps
assert not_avail_comp not in avail_comps
class TestSceneSerialization:
"""Test the Scene serialization."""
def setup_method(self):
"""Set config_path to point to test 'etc' directory."""
self.old_config_path = satpy.config.get('config_path')
satpy.config.set(config_path=[TEST_ETC_DIR])
def teardown_method(self):
"""Restore previous 'config_path' setting."""
satpy.config.set(config_path=self.old_config_path)
def test_serialization_with_readers_and_data_arr(self):
"""Test that dask can serialize a Scene with readers."""
from distributed.protocol import deserialize, serialize
scene = Scene(filenames=['fake1_1.txt'], reader='fake1')
scene.load(['ds1'])
cloned_scene = deserialize(*serialize(scene))
assert scene._readers.keys() == cloned_scene._readers.keys()
assert scene.all_dataset_ids == scene.all_dataset_ids
class TestSceneLoading:
"""Test the Scene objects `.load` method."""
def setup_method(self):
"""Set config_path to point to test 'etc' directory."""
self.old_config_path = satpy.config.get('config_path')
satpy.config.set(config_path=[TEST_ETC_DIR])
def teardown_method(self):
"""Restore previous 'config_path' setting."""
satpy.config.set(config_path=self.old_config_path)
def test_load_str(self):
"""Test passing a string to Scene.load."""
scene = Scene(filenames=['fake1_1.txt'], reader='fake1')
pytest.raises(TypeError, scene.load, 'ds1')
def test_load_no_exist(self):
"""Test loading a dataset that doesn't exist."""
scene = Scene(filenames=['fake1_1.txt'], reader='fake1')
pytest.raises(KeyError, scene.load, ['im_a_dataset_that_doesnt_exist'])
def test_load_no_exist2(self):
"""Test loading a dataset that doesn't exist then another load."""
from satpy.readers.yaml_reader import FileYAMLReader
load_mock = spy_decorator(FileYAMLReader.load)
with mock.patch.object(FileYAMLReader, 'load', load_mock):
lmock = load_mock.mock
scene = Scene(filenames=['fake1_1.txt'], reader='fake1')
scene.load(['ds9_fail_load'])
loaded_ids = list(scene._datasets.keys())
assert len(loaded_ids) == 0
lmock.assert_called_once_with(
set([make_dataid(name='ds9_fail_load', wavelength=(1.0, 1.1, 1.2))]))
scene.load(['ds1'])
loaded_ids = list(scene._datasets.keys())
assert lmock.call_count == 2
# most recent call should have only been ds1
lmock.assert_called_with(set([
make_dataid(name='ds1', resolution=250,
calibration='reflectance', modifiers=tuple())]))
assert len(loaded_ids) == 1
def test_load_ds1_no_comps(self):
"""Test loading one dataset with no loaded compositors."""
scene = Scene(filenames=['fake1_1.txt'], reader='fake1')
scene.load(['ds1'])
loaded_ids = list(scene._datasets.keys())
assert len(loaded_ids) == 1
assert loaded_ids[0] == make_dataid(name='ds1', resolution=250, calibration='reflectance', modifiers=tuple())
def test_load_ds1_load_twice(self):
"""Test loading one dataset with no loaded compositors."""
from satpy.readers.yaml_reader import FileYAMLReader
scene = Scene(filenames=['fake1_1.txt'], reader='fake1')
scene.load(['ds1'])
loaded_ids = list(scene._datasets.keys())
assert len(loaded_ids) == 1
assert loaded_ids[0] == make_dataid(name='ds1', resolution=250, calibration='reflectance', modifiers=tuple())
load_mock = spy_decorator(FileYAMLReader.load)
with mock.patch.object(FileYAMLReader, 'load', load_mock):
lmock = load_mock.mock
scene.load(['ds1'])
loaded_ids = list(scene._datasets.keys())
assert len(loaded_ids) == 1
assert loaded_ids[0] == make_dataid(name='ds1',
resolution=250,
calibration='reflectance',
modifiers=tuple())
assert not lmock.called, ("Reader.load was called again when "