-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathtest_scene.py
2393 lines (2195 loc) · 109 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 os
import unittest
from unittest import mock
import numpy as np
import pytest
from satpy.tests.utils import (default_id_keys_config, make_cid, make_dataid,
make_dsq)
# clear the config dir environment variable so it doesn't interfere
os.environ.pop("PPP_CONFIG_DIR", None)
class TestScene(unittest.TestCase):
"""Test the scene class."""
def test_init(self):
"""Test scene initialization."""
import satpy.scene
with mock.patch('satpy.scene.Scene._create_reader_instances') as cri:
cri.return_value = {}
satpy.scene.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."""
import satpy.scene
self.assertRaises(ValueError, satpy.scene.Scene, reader='blo', filenames='test.nc')
def test_init_with_sensor(self):
"""Test initializing with a sensor."""
import satpy.scene
from satpy.tests.utils import FakeReader
with mock.patch('satpy.scene.Scene._create_reader_instances') as cri:
cri.return_value = {
'fake_reader': FakeReader('fake_reader', sensor_name='fake_sensor'),
}
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
sensor='fake_sensor')
self.assertIsInstance(scene.attrs['sensor'], set)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
sensor=['fake_sensor'])
self.assertIsInstance(scene.attrs['sensor'], set)
def test_start_end_times(self):
"""Test start and end times for a scene."""
import satpy.scene
from satpy.tests.utils import FakeReader
from datetime import datetime
with mock.patch('satpy.scene.Scene._create_reader_instances') as cri:
r = FakeReader('fake_reader',
start_time=datetime(2017, 1, 1, 0, 0, 0),
end_time=datetime(2017, 1, 1, 1, 0, 0),
)
cri.return_value = {'fake_reader': r}
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
sensor='fake_sensor')
self.assertEqual(scene.start_time, r.start_time)
self.assertEqual(scene.end_time, r.end_time)
def test_init_preserve_reader_kwargs(self):
"""Test that the initialization preserves the kwargs."""
import satpy.scene
from satpy.tests.utils import FakeReader
from datetime import datetime
with mock.patch('satpy.scene.Scene._create_reader_instances') as cri:
r = FakeReader('fake_reader',
start_time=datetime(2017, 1, 1, 0, 0, 0),
end_time=datetime(2017, 1, 1, 1, 0, 0),
)
cri.return_value = {'fake_reader': r}
reader_kwargs = {'calibration_type': 'gsics'}
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
sensor='fake_sensor',
filter_parameters={'area': 'euron1'},
reader_kwargs=reader_kwargs)
self.assertIsNot(reader_kwargs, cri.call_args[1]['reader_kwargs'])
self.assertEqual(scene.start_time, r.start_time)
self.assertEqual(scene.end_time, r.end_time)
def test_init_alone(self):
"""Test simple initialization."""
from satpy.scene import Scene
from satpy.config import PACKAGE_CONFIG_PATH
scn = Scene()
self.assertEqual(scn._ppp_config_dir, PACKAGE_CONFIG_PATH)
self.assertFalse(scn._readers, 'Empty scene should not load any readers')
def test_init_no_files(self):
"""Test that providing an empty list of filenames fails."""
from satpy.scene import Scene
self.assertRaises(ValueError, Scene, reader='viirs_sdr', filenames=[])
def test_init_with_ppp_config_dir(self):
"""Test initializing with a ppp_config_dir."""
from satpy.scene import Scene
scn = Scene(ppp_config_dir="foo")
self.assertEqual(scn._ppp_config_dir, 'foo')
def test_create_reader_instances_with_filenames(self):
"""Test creating a reader providing filenames."""
import satpy.scene
filenames = ["bla", "foo", "bar"]
reader_name = None
with mock.patch('satpy.scene.Scene._compute_metadata_from_readers') as md:
md.return_value = {'sensor': {'sensor'}}
with mock.patch('satpy.scene.load_readers') as findermock:
satpy.scene.Scene(filenames=filenames)
findermock.assert_called_once_with(
filenames=filenames,
reader=reader_name,
reader_kwargs=None,
ppp_config_dir=mock.ANY
)
def test_init_with_empty_filenames(self):
"""Test initialization with empty filename list."""
from satpy.scene import Scene
filenames = []
Scene(filenames=filenames)
# 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."""
from satpy.scene import Scene
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(ppp_config_dir=mock.ANY,
reader=reader,
filenames=filenames,
reader_kwargs=None,
)
def test_create_reader_instances_with_reader_kwargs(self):
"""Test creating a reader instance with reader kwargs."""
import satpy.scene
from satpy.tests.utils import FakeReader
from datetime import datetime
filenames = ["1", "2", "3"]
reader_kwargs = {'calibration_type': 'gsics'}
filter_parameters = {'area': 'euron1'}
reader_kwargs2 = {'calibration_type': 'gsics', 'filter_parameters': filter_parameters}
with mock.patch('satpy.readers.load_reader') as lr_mock:
r = FakeReader('fake_reader',
start_time=datetime(2017, 1, 1, 0, 0, 0),
end_time=datetime(2017, 1, 1, 1, 0, 0),
)
lr_mock.return_value = r
r.select_files_from_pathnames = mock.MagicMock()
r.select_files_from_pathnames.return_value = filenames
r.create_filehandlers = mock.MagicMock()
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
sensor='fake_sensor',
filter_parameters={'area': 'euron1'},
reader_kwargs=reader_kwargs)
del scene
self.assertDictEqual(reader_kwargs, r.create_filehandlers.call_args[1]['fh_kwargs'])
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
sensor='fake_sensor',
reader_kwargs=reader_kwargs2)
self.assertDictEqual(reader_kwargs, r.create_filehandlers.call_args[1]['fh_kwargs'])
del scene
def test_create_multiple_reader_different_kwargs(self):
"""Test passing different kwargs to different readers."""
from satpy.scene import Scene
from satpy.tests.utils import FakeReader
with mock.patch('satpy.readers.configs_for_reader') as src, \
mock.patch("satpy.readers.load_reader") as srl:
r1 = FakeReader('strona')
r1.select_files_from_pathnames = mock.MagicMock()
r1.select_files_from_pathnames.return_value = ["campello monti"]
r1.create_filehandlers = mock.MagicMock()
r2 = FakeReader('mastallone')
r2.select_files_from_pathnames = mock.MagicMock()
r2.select_files_from_pathnames.return_value = ["rimella"]
r2.create_filehandlers = mock.MagicMock()
def fake_lr(reader_configs, **reader_kwargs):
if reader_configs == ["/fake/strona.yaml"]:
return r1
elif reader_configs == ["/fake/mastallone.yaml"]:
return r2
raise RuntimeError("Test is broken") # pragma: no cover
srl.side_effect = fake_lr
src.return_value = [["/fake/strona.yaml"], ["/fake/mastallone.yaml"]]
Scene(filenames={"strona": ["campello monti"],
"mastallone": ["rimella"]},
reader_kwargs={"strona": {"mouth": "omegna"},
"mastallone": {"mouth": "varallo"}})
srl.assert_has_calls([
mock.call(["/fake/strona.yaml"], mouth="omegna"),
mock.call(["/fake/mastallone.yaml"], mouth="varallo")])
def test_iter(self):
"""Test iteration over the scene."""
from satpy import Scene
from xarray import DataArray
scene = Scene()
scene["1"] = DataArray(np.arange(5))
scene["2"] = DataArray(np.arange(5))
scene["3"] = DataArray(np.arange(5))
for x in scene:
self.assertIsInstance(x, DataArray)
def test_iter_by_area_swath(self):
"""Test iterating by area on a swath."""
from satpy import Scene
from xarray import DataArray
from pyresample.geometry import SwathDefinition
scene = Scene()
sd = SwathDefinition(lons=np.arange(5), lats=np.arange(5))
scene["1"] = DataArray(np.arange(5), attrs={'area': sd})
scene["2"] = DataArray(np.arange(5), attrs={'area': sd})
scene["3"] = 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:
self.assertSetEqual(ds_list_names, {'1', '2'})
else:
self.assertIsNone(area_obj)
self.assertSetEqual(ds_list_names, {'3'})
def test_bad_setitem(self):
"""Test setting an item wrongly."""
from satpy import Scene
scene = Scene()
self.assertRaises(ValueError, scene.__setitem__, '1', np.arange(5))
def test_setitem(self):
"""Test setting an item."""
from satpy import Scene
from satpy.tests.utils import make_dataid
import xarray as xr
scene = Scene()
scene["1"] = ds1 = xr.DataArray(np.arange(5))
expected_id = make_cid(**ds1.attrs)
self.assertSetEqual(set(scene._datasets.keys()), {expected_id})
self.assertSetEqual(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."""
from satpy import Scene
from xarray import DataArray
scene = Scene()
scene["1"] = ds1 = DataArray(np.arange(5))
scene["2"] = ds2 = DataArray(np.arange(5))
scene["3"] = ds3 = DataArray(np.arange(5))
self.assertIs(scene['1'], ds1)
self.assertIs(scene['2'], ds2)
self.assertIs(scene['3'], ds3)
self.assertRaises(KeyError, scene.__getitem__, '4')
self.assertIs(scene.get('3'), ds3)
self.assertIs(scene.get('4'), None)
def test_getitem_modifiers(self):
"""Test __getitem__ with names and modifiers."""
from satpy import Scene
from xarray import DataArray
# Return least modified item
scene = Scene()
scene['1'] = ds1_m0 = DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1',))
] = ds1_m1 = DataArray(np.arange(5))
self.assertIs(scene['1'], ds1_m0)
self.assertEqual(len(list(scene.keys())), 2)
scene = Scene()
scene['1'] = ds1_m0 = DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1',))
] = ds1_m1 = DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1', 'mod2'))
] = ds1_m2 = DataArray(np.arange(5))
self.assertIs(scene['1'], ds1_m0)
self.assertEqual(len(list(scene.keys())), 3)
scene = Scene()
scene[make_dataid(name='1', modifiers=('mod1', 'mod2'))
] = ds1_m2 = DataArray(np.arange(5))
scene[make_dataid(name='1', modifiers=('mod1',))
] = ds1_m1 = DataArray(np.arange(5))
self.assertIs(scene['1'], ds1_m1)
self.assertIs(scene[make_dataid(name='1', modifiers=('mod1', 'mod2'))], ds1_m2)
self.assertRaises(KeyError, scene.__getitem__,
make_dataid(name='1', modifiers=tuple()))
self.assertEqual(len(list(scene.keys())), 2)
def test_getitem_slices(self):
"""Test __getitem__ with slices."""
from satpy import Scene
from xarray import DataArray
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"] = DataArray(np.zeros((5, 10)))
scene1["2"] = scene2["2"] = DataArray(np.zeros((5, 10)),
dims=('y', 'x'))
scene1["3"] = DataArray(np.zeros((5, 10)), dims=('y', 'x'),
attrs={'area': area_def})
anc_vars = [DataArray(np.ones((5, 10)), attrs={'name': 'anc_var',
'area': area_def})]
attrs = {'ancillary_variables': anc_vars, 'area': area_def}
scene1["3a"] = DataArray(np.zeros((5, 10)),
dims=('y', 'x'),
attrs=attrs)
scene2["4"] = DataArray(np.zeros((5, 10)), dims=('y', 'x'),
attrs={'area': swath_def})
anc_vars = [DataArray(np.ones((5, 10)), attrs={'name': 'anc_var',
'area': swath_def})]
attrs = {'ancillary_variables': anc_vars, 'area': swath_def}
scene2["4a"] = 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
self.assertTupleEqual(new_scn['1'].shape, (5, 10))
self.assertTupleEqual(new_scn['2'].shape, (5, 10))
self.assertTupleEqual(new_scn1['3'].shape, (3, 6))
self.assertIn('area', new_scn1['3'].attrs)
self.assertTupleEqual(new_scn1['3'].attrs['area'].shape, (3, 6))
self.assertTupleEqual(new_scn1['3a'].shape, (3, 6))
a_var = new_scn1['3a'].attrs['ancillary_variables'][0]
self.assertTupleEqual(a_var.shape, (3, 6))
self.assertTupleEqual(new_scn2['4'].shape, (3, 6))
self.assertIn('area', new_scn2['4'].attrs)
self.assertTupleEqual(new_scn2['4'].attrs['area'].shape, (3, 6))
self.assertTupleEqual(new_scn2['4a'].shape, (3, 6))
a_var = new_scn2['4a'].attrs['ancillary_variables'][0]
self.assertTupleEqual(a_var.shape, (3, 6))
def test_crop(self):
"""Test the crop method."""
from satpy import Scene
from xarray import DataArray
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"] = DataArray(np.zeros((y_size, x_size)))
scene1["2"] = DataArray(np.zeros((y_size, x_size)), dims=('y', 'x'))
scene1["3"] = DataArray(np.zeros((y_size, x_size)), dims=('y', 'x'),
attrs={'area': area_def})
scene1["4"] = 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)
self.assertIn('1', new_scn1)
self.assertIn('2', new_scn1)
self.assertIn('3', new_scn1)
self.assertTupleEqual(new_scn1['1'].shape, (y_size, x_size))
self.assertTupleEqual(new_scn1['2'].shape, (y_size, x_size))
self.assertTupleEqual(new_scn1['3'].shape, (3380, 3708))
self.assertTupleEqual(new_scn1['4'].shape, (1690, 1854))
# by lon/lat bbox
new_scn1 = scene1.crop(ll_bbox=(-20., -5., 0, 0))
self.assertIn('1', new_scn1)
self.assertIn('2', new_scn1)
self.assertIn('3', new_scn1)
self.assertTupleEqual(new_scn1['1'].shape, (y_size, x_size))
self.assertTupleEqual(new_scn1['2'].shape, (y_size, x_size))
self.assertTupleEqual(new_scn1['3'].shape, (184, 714))
self.assertTupleEqual(new_scn1['4'].shape, (92, 357))
# by x/y bbox
new_scn1 = scene1.crop(xy_bbox=(-200000., -100000., 0, 0))
self.assertIn('1', new_scn1)
self.assertIn('2', new_scn1)
self.assertIn('3', new_scn1)
self.assertTupleEqual(new_scn1['1'].shape, (y_size, x_size))
self.assertTupleEqual(new_scn1['2'].shape, (y_size, x_size))
self.assertTupleEqual(new_scn1['3'].shape, (36, 70))
self.assertTupleEqual(new_scn1['4'].shape, (18, 35))
def test_crop_epsg_crs(self):
"""Test the crop method when source area uses an EPSG code."""
from satpy import Scene
from xarray import DataArray
from pyresample.geometry import AreaDefinition
try:
from pyproj import CRS # noqa
except ImportError:
self.skipTest("Test requires pyproj 2.0+")
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"] = 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))
self.assertIn('1', new_scn1)
self.assertTupleEqual(new_scn1['1'].shape, (198, 182))
def test_crop_rgb(self):
"""Test the crop method on multi-dimensional data."""
from satpy import Scene
from xarray import DataArray
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"] = DataArray(np.zeros((3, y_size, x_size)), dims=('bands', 'y', 'x'), attrs={'area': area_def})
scene1["2"] = 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))
self.assertIn('1', new_scn1)
self.assertIn('2', new_scn1)
self.assertIn('bands', new_scn1['1'].dims)
self.assertIn('bands', new_scn1['2'].dims)
self.assertTupleEqual(new_scn1['1'].shape, (3, 184, 714))
self.assertTupleEqual(new_scn1['2'].shape, (92, 3, 357))
def test_contains(self):
"""Test contains."""
from satpy import Scene
from xarray import DataArray
scene = Scene()
scene["1"] = DataArray(np.arange(5), attrs={'wavelength': (0.1, 0.2, 0.3),
'_satpy_id_keys': default_id_keys_config})
self.assertTrue('1' in scene)
self.assertTrue(0.15 in scene)
self.assertFalse('2' in scene)
self.assertFalse(0.31 in scene)
scene = Scene()
scene['blueberry'] = DataArray(np.arange(5))
scene['blackberry'] = DataArray(np.arange(5))
scene['strawberry'] = DataArray(np.arange(5))
scene['raspberry'] = 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."""
from satpy import Scene
from xarray import DataArray
scene = Scene()
scene["1"] = DataArray(np.arange(5), attrs={'wavelength': (0.1, 0.2, 0.3),
'_satpy_id_keys': default_id_keys_config})
scene["2"] = DataArray(np.arange(5), attrs={'wavelength': (0.4, 0.5, 0.6),
'_satpy_id_keys': default_id_keys_config})
scene["3"] = 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]
self.assertEqual(len(scene._wishlist), 0)
self.assertEqual(len(scene._datasets.keys()), 0)
self.assertRaises(KeyError, scene.__delitem__, 0.2)
def test_min_max_area(self):
"""Test 'min_area' and 'max_area' methods."""
from satpy import Scene
from xarray import DataArray
from pyresample.geometry import AreaDefinition
from pyresample.utils import proj4_str_to_dict
scene = Scene()
scene["1"] = ds1 = DataArray(np.arange(10).reshape((2, 5)),
attrs={'wavelength': (0.1, 0.2, 0.3)})
scene["2"] = ds2 = DataArray(np.arange(40).reshape((4, 10)),
attrs={'wavelength': (0.4, 0.5, 0.6)})
scene["3"] = ds3 = DataArray(np.arange(40).reshape((4, 10)),
attrs={'wavelength': (0.7, 0.8, 0.9)})
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_def1 = AreaDefinition(
'test',
'test',
'test',
proj_dict,
100,
200,
(-1000., -1500., 1000., 1500.),
)
area_def2 = AreaDefinition(
'test',
'test',
'test',
proj_dict,
200,
400,
(-1000., -1500., 1000., 1500.),
)
ds1.attrs['area'] = area_def1
ds2.attrs['area'] = area_def2
ds3.attrs['area'] = area_def2
self.assertIs(scene.min_area(), area_def1)
self.assertIs(scene.max_area(), area_def2)
self.assertIs(scene.min_area(['2', '3']), area_def2)
def test_all_datasets_no_readers(self):
"""Test all datasets with no reader."""
from satpy import Scene
scene = Scene()
self.assertRaises(KeyError, scene.all_dataset_ids, reader_name='fake')
id_list = scene.all_dataset_ids()
self.assertListEqual(id_list, [])
# no sensors are loaded so we shouldn't get any comps either
id_list = scene.all_dataset_ids(composites=True)
self.assertListEqual(id_list, [])
def test_all_dataset_names_no_readers(self):
"""Test all dataset names with no reader."""
from satpy import Scene
scene = Scene()
self.assertRaises(KeyError, scene.all_dataset_names, reader_name='fake')
name_list = scene.all_dataset_names()
self.assertListEqual(name_list, [])
# no sensors are loaded so we shouldn't get any comps either
name_list = scene.all_dataset_names(composites=True)
self.assertListEqual(name_list, [])
def test_available_dataset_no_readers(self):
"""Test the available datasets without a reader."""
from satpy import Scene
scene = Scene()
self.assertRaises(
KeyError, scene.available_dataset_ids, reader_name='fake')
name_list = scene.available_dataset_ids()
self.assertListEqual(name_list, [])
# no sensors are loaded so we shouldn't get any comps either
name_list = scene.available_dataset_ids(composites=True)
self.assertListEqual(name_list, [])
def test_available_dataset_names_no_readers(self):
"""Test the available dataset names without a reader."""
from satpy import Scene
scene = Scene()
self.assertRaises(
KeyError, scene.available_dataset_names, reader_name='fake')
name_list = scene.available_dataset_names()
self.assertListEqual(name_list, [])
# no sensors are loaded so we shouldn't get any comps either
name_list = scene.available_dataset_names(composites=True)
self.assertListEqual(name_list, [])
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_all_datasets_one_reader(self, cri, cl):
"""Test all datasets for one reader."""
from satpy import Scene
from satpy.tests.utils import FakeReader, test_composites
r = FakeReader('fake_reader', 'fake_sensor')
cri.return_value = {'fake_reader': r}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
# patch the _composite_loader
scene._composite_loader.compositors = comps
scene._composite_loader.modifiers = mods
id_list = scene.all_dataset_ids()
self.assertEqual(len(id_list), len(r.all_ids))
id_list = scene.all_dataset_ids(composites=True)
self.assertEqual(len(id_list),
len(r.all_ids) + 30)
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_all_datasets_multiple_reader(self, cri, cl):
"""Test all datasets for multiple readers."""
from satpy import Scene
from satpy.tests.utils import FakeReader, test_composites
r = FakeReader('fake_reader', 'fake_sensor', datasets=['ds1'])
r2 = FakeReader(
'fake_reader2', 'fake_sensor2', datasets=['ds2'])
cri.return_value = {'fake_reader': r, 'fake_reader2': r2}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
# patch the _composite_loader
scene._composite_loader.compositors = comps
scene._composite_loader.modifiers = mods
id_list = scene.all_dataset_ids()
self.assertEqual(len(id_list), 2)
id_list = scene.all_dataset_ids(composites=True)
# ds1 and ds2 => 2
# composites that use these two datasets => 11
self.assertEqual(len(id_list), 2 + 11)
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_available_datasets_one_reader(self, cri, cl):
"""Test the available datasets for one reader."""
from satpy import Scene
from satpy.tests.utils import FakeReader, test_composites
r = FakeReader('fake_reader', 'fake_sensor', datasets=['ds1'])
cri.return_value = {'fake_reader': r}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
# patch the _composite_loader
scene._composite_loader.compositors = comps
scene._composite_loader.modifiers = mods
id_list = scene.available_dataset_ids()
self.assertEqual(len(id_list), 1)
id_list = scene.available_dataset_ids(composites=True)
# ds1, comp1, comp14, comp16, static_image, comp26
self.assertEqual(len(id_list), 6)
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_available_composite_ids_missing_available(self, cri, cl):
"""Test available_composite_ids when a composites dep is missing."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
# only the 500m is available
available_datasets = ['ds1']
cri.return_value = {
'fake_reader': FakeReader(
'fake_reader', 'fake_sensor',
available_datasets=available_datasets),
}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
self.assertNotIn('comp2', scene.available_composite_names())
class TestSceneLoading(unittest.TestCase):
"""Test the Scene objects `.load` method."""
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_str(self, cri, cl):
"""Test passing a string to Scene.load."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
self.assertRaises(TypeError, scene.load, 'ds1')
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_no_exist(self, cri, cl):
"""Test loading a dataset that doesn't exist."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
self.assertRaises(KeyError, scene.load, [
'im_a_dataset_that_doesnt_exist'])
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_no_exist2(self, cri, cl):
"""Test loading a dataset that doesn't exist then another load."""
from satpy.tests.utils import FakeReader, test_composites
from satpy import Scene
r = FakeReader('fake_reader', 'fake_sensor')
cri.return_value = {'fake_reader': r}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
scene.load(['ds9_fail_load'])
loaded_ids = list(scene._datasets.keys())
self.assertEqual(len(loaded_ids), 0)
r.load.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())
self.assertEqual(r.load.call_count, 2)
# most recent call should have only been ds1
r.load.assert_called_with(set([make_dataid(name='ds1',
resolution=250,
calibration='reflectance',
modifiers=tuple())]))
self.assertEqual(len(loaded_ids), 1)
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds1_no_comps(self, cri):
"""Test loading one dataset with no loaded compositors."""
import satpy.scene
from satpy.tests.utils import FakeReader
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
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())
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds1_load_twice(self, cri):
"""Test loading one dataset with no loaded compositors."""
import satpy.scene
from satpy.tests.utils import FakeReader
r = FakeReader('fake_reader', 'fake_sensor')
cri.return_value = {'fake_reader': r}
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
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())
with mock.patch.object(r, 'load') as m:
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())
self.assertFalse(
m.called, "Reader.load was called again when loading something that's already loaded")
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds1_unknown_modifier(self, cri, cl):
"""Test loading one dataset with no loaded compositors."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
self.assertRaises(KeyError, scene.load,
[make_dataid(name='ds1', modifiers=('_fake_bad_mod_',))])
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds4_cal(self, cri, cl):
"""Test loading a dataset that has two calibration variations."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
scene.load(['ds4'])
loaded_ids = list(scene._datasets.keys())
self.assertEqual(len(loaded_ids), 1)
self.assertEqual(loaded_ids[0]['calibration'], 'reflectance')
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds5_best_resolution(self, cri, cl):
"""Test loading a dataset has multiple resolutions available."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
scene.load(['ds5'])
loaded_ids = list(scene._datasets.keys())
self.assertEqual(len(loaded_ids), 1)
self.assertEqual(loaded_ids[0]['name'], 'ds5')
self.assertEqual(loaded_ids[0]['resolution'], 250)
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds5_multiple_resolution(self, cri, cl):
"""Test loading a dataset has multiple resolutions available with different resolutions."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
scene.load(['ds5'], resolution=1000)
scene.load(['ds5'], resolution=500)
loaded_ids = list(scene._datasets.keys())
self.assertEqual(len(loaded_ids), 2)
self.assertEqual(loaded_ids[0]['name'], 'ds5')
self.assertEqual(loaded_ids[0]['resolution'], 500)
self.assertEqual(loaded_ids[1]['name'], 'ds5')
self.assertEqual(loaded_ids[1]['resolution'], 1000)
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds5_resolution_list(self, cri, cl):
"""Test loading a dataset has multiple resolutions available with different resolutions."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',
reader='fake_reader')
scene.load(['ds5'], resolution=[500, 1000])
loaded_ids = list(scene._datasets.keys())
assert len(loaded_ids) == 1
assert loaded_ids[0]['name'] == 'ds5'
assert loaded_ids[0]['resolution'] == 500
@mock.patch('satpy.composites.config_loader.CompositorLoader.load_compositors')
@mock.patch('satpy.scene.Scene._create_reader_instances')
def test_load_ds5_empty_modifiers(self, cri, cl):
"""Test loading a dataset has multiple resolutions available with different resolutions."""
import satpy.scene
from satpy.tests.utils import FakeReader, test_composites
cri.return_value = {'fake_reader': FakeReader(
'fake_reader', 'fake_sensor')}
comps, mods = test_composites('fake_sensor')
cl.return_value = (comps, mods)
scene = satpy.scene.Scene(filenames=['bla'],
base_dir='bli',