-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy path__init__.py
2036 lines (1653 loc) · 81.5 KB
/
__init__.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
# Copyright (c) 2015-2023 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/>.
"""Base classes for composite objects."""
from __future__ import annotations
import logging
import os
import warnings
from typing import Optional, Sequence
import dask.array as da
import numpy as np
import xarray as xr
from trollimage.colormap import Colormap
import satpy
from satpy.aux_download import DataDownloadMixin
from satpy.dataset import DataID, combine_metadata
from satpy.dataset.id_keys import minimal_default_keys_config
from satpy.utils import unify_chunks
from satpy.writers import get_enhanced_image
LOG = logging.getLogger(__name__)
NEGLIGIBLE_COORDS = ["time"]
"""Keywords identifying non-dimensional coordinates to be ignored during composite generation."""
MASKING_COMPOSITOR_METHODS = ["less", "less_equal", "equal", "greater_equal",
"greater", "not_equal", "isnan", "isfinite",
"isneginf", "isposinf"]
class IncompatibleAreas(Exception):
"""Error raised upon compositing things of different shapes."""
class IncompatibleTimes(Exception):
"""Error raised upon compositing things from different times."""
def check_times(projectables):
"""Check that *projectables* have compatible times."""
times = []
for proj in projectables:
try:
if proj["time"].size and proj["time"][0] != 0:
times.append(proj["time"][0].values)
else:
break # right?
except KeyError:
# the datasets don't have times
break
except IndexError:
# time is a scalar
if proj["time"].values != 0:
times.append(proj["time"].values)
else:
break
else:
# Is there a more gracious way to handle this ?
if np.max(times) - np.min(times) > np.timedelta64(1, "s"):
raise IncompatibleTimes
mid_time = (np.max(times) - np.min(times)) / 2 + np.min(times)
return mid_time
def sub_arrays(proj1, proj2):
"""Substract two DataArrays and combine their attrs."""
attrs = combine_metadata(proj1.attrs, proj2.attrs)
if (attrs.get("area") is None
and proj1.attrs.get("area") is not None
and proj2.attrs.get("area") is not None):
raise IncompatibleAreas
res = proj1 - proj2
res.attrs = attrs
return res
class CompositeBase:
"""Base class for all compositors and modifiers.
A compositor in Satpy is a class that takes in zero or more input
DataArrays and produces a new DataArray with its own identifier (name).
The result of a compositor is typically a brand new "product" that
represents something different than the inputs that went into the
operation.
See the :class:`~satpy.composites.ModifierBase` class for information
on the similar concept of "modifiers".
"""
def __init__(self, name, prerequisites=None, optional_prerequisites=None, **kwargs):
"""Initialise the compositor."""
# Required info
kwargs["name"] = name
kwargs["prerequisites"] = prerequisites or []
kwargs["optional_prerequisites"] = optional_prerequisites or []
self.attrs = kwargs
@property
def id(self): # noqa: A003
"""Return the DataID of the object."""
try:
return self.attrs["_satpy_id"]
except KeyError:
id_keys = self.attrs.get("_satpy_id_keys", minimal_default_keys_config)
return DataID(id_keys, **self.attrs)
def __call__(
self,
datasets: Sequence[xr.DataArray],
optional_datasets: Optional[Sequence[xr.DataArray]] = None,
**info
) -> xr.DataArray:
"""Generate a composite."""
raise NotImplementedError()
def __str__(self):
"""Stringify the object."""
from pprint import pformat
return pformat(self.attrs)
def __repr__(self):
"""Represent the object."""
from pprint import pformat
return pformat(self.attrs)
def apply_modifier_info(self, origin, destination):
"""Apply the modifier info from *origin* to *destination*."""
o = getattr(origin, "attrs", origin)
d = getattr(destination, "attrs", destination)
try:
dataset_keys = self.attrs["_satpy_id"].id_keys.keys()
except KeyError:
dataset_keys = ["name", "modifiers"]
for k in dataset_keys:
if k == "modifiers" and k in self.attrs:
d[k] = self.attrs[k]
elif d.get(k) is None:
if self.attrs.get(k) is not None:
d[k] = self.attrs[k]
elif o.get(k) is not None:
d[k] = o[k]
def match_data_arrays(self, data_arrays: Sequence[xr.DataArray]) -> list[xr.DataArray]:
"""Match data arrays so that they can be used together in a composite.
For the purpose of this method, "can be used together" means:
- All arrays should have the same dimensions.
- Either all arrays should have an area, or none should.
- If all have an area, the areas should be all the same.
In addition, negligible non-dimensional coordinates are dropped (see
:meth:`drop_coordinates`) and dask chunks are unified (see
:func:`satpy.utils.unify_chunks`).
Args:
data_arrays (List[arrays]): Arrays to be checked
Returns:
data_arrays (List[arrays]):
Arrays with negligible non-dimensional coordinates removed.
Raises:
:class:`IncompatibleAreas`:
If dimension or areas do not match.
:class:`ValueError`:
If some, but not all data arrays lack an area attribute.
"""
self.check_geolocation(data_arrays)
new_arrays = self.drop_coordinates(data_arrays)
new_arrays = self.align_geo_coordinates(new_arrays)
new_arrays = list(unify_chunks(*new_arrays))
return new_arrays
def check_geolocation(self, data_arrays: Sequence[xr.DataArray]) -> None:
"""Check that the geolocations of the *data_arrays* are compatible.
For the purpose of this method, "compatible" means:
- All arrays should have the same dimensions.
- Either all arrays should have an area, or none should.
- If all have an area, the areas should be all the same.
Args:
data_arrays: Arrays to be checked
Raises:
:class:`IncompatibleAreas`:
If dimension or areas do not match.
:class:`ValueError`:
If some, but not all data arrays lack an area attribute.
"""
if len(data_arrays) == 1:
return
if "x" in data_arrays[0].dims and \
not all(x.sizes["x"] == data_arrays[0].sizes["x"]
for x in data_arrays[1:]):
raise IncompatibleAreas("X dimension has different sizes")
if "y" in data_arrays[0].dims and \
not all(x.sizes["y"] == data_arrays[0].sizes["y"]
for x in data_arrays[1:]):
raise IncompatibleAreas("Y dimension has different sizes")
areas = [ds.attrs.get("area") for ds in data_arrays]
if all(a is None for a in areas):
return
if any(a is None for a in areas):
raise ValueError("Missing 'area' attribute")
if not all(areas[0] == x for x in areas[1:]):
LOG.debug("Not all areas are the same in "
"'{}'".format(self.attrs["name"]))
raise IncompatibleAreas("Areas are different")
@staticmethod
def drop_coordinates(data_arrays: Sequence[xr.DataArray]) -> list[xr.DataArray]:
"""Drop negligible non-dimensional coordinates.
Drops negligible coordinates if they do not correspond to any
dimension. Negligible coordinates are defined in the
:attr:`NEGLIGIBLE_COORDS` module attribute.
Args:
data_arrays (List[arrays]): Arrays to be checked
"""
new_arrays = []
for ds in data_arrays:
drop = [coord for coord in ds.coords
if coord not in ds.dims and
any([neglible in coord for neglible in NEGLIGIBLE_COORDS])]
if drop:
new_arrays.append(ds.drop_vars(drop))
else:
new_arrays.append(ds)
return new_arrays
@staticmethod
def align_geo_coordinates(data_arrays: Sequence[xr.DataArray]) -> list[xr.DataArray]:
"""Align DataArrays along geolocation coordinates.
See :func:`~xarray.align` for more information. This function uses
the "override" join method to essentially ignore differences between
coordinates. The :meth:`check_geolocation` should be called before
this to ensure that geolocation coordinates and "area" are compatible.
The :meth:`drop_coordinates` method should be called before this to
ensure that coordinates that are considered "negligible" when computing
composites do not affect alignment.
"""
non_geo_coords = tuple(
coord_name for data_arr in data_arrays
for coord_name in data_arr.coords if coord_name not in ("x", "y"))
return list(xr.align(*data_arrays, join="override", exclude=non_geo_coords))
class DifferenceCompositor(CompositeBase):
"""Make the difference of two data arrays."""
def __call__(self, projectables, nonprojectables=None, **attrs):
"""Generate the composite."""
if len(projectables) != 2:
raise ValueError("Expected 2 datasets, got %d" % (len(projectables),))
projectables = self.match_data_arrays(projectables)
info = combine_metadata(*projectables)
info["name"] = self.attrs["name"]
info.update(self.attrs) # attrs from YAML/__init__
info.update(attrs) # overwriting of DataID properties
proj = projectables[0] - projectables[1]
proj.attrs = info
return proj
class RatioCompositor(CompositeBase):
"""Make the ratio of two data arrays."""
def __call__(self, projectables, nonprojectables=None, **info):
"""Generate the composite."""
if len(projectables) != 2:
raise ValueError("Expected 2 datasets, got %d" % (len(projectables),))
projectables = self.match_data_arrays(projectables)
info = combine_metadata(*projectables)
info["name"] = self.attrs["name"]
proj = projectables[0] / projectables[1]
proj.attrs = info
return proj
class SumCompositor(CompositeBase):
"""Make the sum of two data arrays."""
def __call__(self, projectables, nonprojectables=None, **info):
"""Generate the composite."""
if len(projectables) != 2:
raise ValueError("Expected 2 datasets, got %d" % (len(projectables),))
projectables = self.match_data_arrays(projectables)
info = combine_metadata(*projectables)
info["name"] = self.attrs["name"]
proj = projectables[0] + projectables[1]
proj.attrs = info
return proj
class SingleBandCompositor(CompositeBase):
"""Basic single-band composite builder.
This preserves all the attributes of the dataset it is derived from.
"""
@staticmethod
def _update_missing_metadata(existing_attrs, new_attrs):
for key, val in new_attrs.items():
if key not in existing_attrs and val is not None:
existing_attrs[key] = val
def __call__(self, projectables, nonprojectables=None, **attrs):
"""Build the composite."""
if len(projectables) != 1:
raise ValueError("Can't have more than one band in a single-band composite")
data = projectables[0]
new_attrs = data.attrs.copy()
self._update_missing_metadata(new_attrs, attrs)
resolution = new_attrs.get("resolution", None)
new_attrs.update(self.attrs)
if resolution is not None:
new_attrs["resolution"] = resolution
return xr.DataArray(data=data.data, attrs=new_attrs,
dims=data.dims, coords=data.coords)
class CategoricalDataCompositor(CompositeBase):
"""Compositor used to recategorize categorical data using a look-up-table.
Each value in the data array will be recategorized to a new category defined in
the look-up-table using the original value as an index for that look-up-table.
Example:
data = [[1, 3, 2], [4, 2, 0]]
lut = [10, 20, 30, 40, 50]
res = [[20, 40, 30], [50, 30, 10]]
"""
def __init__(self, name, lut=None, **kwargs): # noqa: D417
"""Get look-up-table used to recategorize data.
Args:
lut (list): a list of new categories. The lenght must be greater than the
maximum value in the data array that should be recategorized.
"""
self.lut = np.array(lut)
super(CategoricalDataCompositor, self).__init__(name, **kwargs)
def _update_attrs(self, new_attrs):
"""Modify name and add LUT."""
new_attrs["name"] = self.attrs["name"]
new_attrs["composite_lut"] = list(self.lut)
@staticmethod
def _getitem(block, lut):
return lut[block]
def __call__(self, projectables, **kwargs):
"""Recategorize the data."""
if len(projectables) != 1:
raise ValueError("Can't have more than one dataset for a categorical data composite")
data = projectables[0].astype(int)
res = data.data.map_blocks(self._getitem, self.lut, dtype=self.lut.dtype)
new_attrs = data.attrs.copy()
self._update_attrs(new_attrs)
return xr.DataArray(res, dims=data.dims, attrs=new_attrs, coords=data.coords)
class GenericCompositor(CompositeBase):
"""Basic colored composite builder."""
modes = {1: "L", 2: "LA", 3: "RGB", 4: "RGBA"}
def __init__(self, name, common_channel_mask=True, **kwargs): # noqa: D417
"""Collect custom configuration values.
Args:
common_channel_mask (bool): If True, mask all the channels with
a mask that combines all the invalid areas of the given data.
"""
self.common_channel_mask = common_channel_mask
super(GenericCompositor, self).__init__(name, **kwargs)
@classmethod
def infer_mode(cls, data_arr):
"""Guess at the mode for a particular DataArray."""
if "mode" in data_arr.attrs:
return data_arr.attrs["mode"]
if "bands" not in data_arr.dims:
return cls.modes[1]
if "bands" in data_arr.coords and isinstance(data_arr.coords["bands"][0].item(), str):
return "".join(data_arr.coords["bands"].values)
return cls.modes[data_arr.sizes["bands"]]
def _concat_datasets(self, projectables, mode):
try:
data = xr.concat(projectables, "bands", coords="minimal")
data["bands"] = list(mode)
except ValueError as e:
LOG.debug("Original exception for incompatible areas: {}".format(str(e)))
raise IncompatibleAreas
return data
def _get_sensors(self, projectables):
sensor = set()
for projectable in projectables:
current_sensor = projectable.attrs.get("sensor", None)
if current_sensor:
if isinstance(current_sensor, (str, bytes)):
sensor.add(current_sensor)
else:
sensor |= current_sensor
if len(sensor) == 0:
sensor = None
elif len(sensor) == 1:
sensor = list(sensor)[0]
return sensor
def __call__(
self,
datasets: Sequence[xr.DataArray],
optional_datasets: Optional[Sequence[xr.DataArray]] = None,
**attrs
) -> xr.DataArray:
"""Build the composite."""
if "deprecation_warning" in self.attrs:
warnings.warn(
self.attrs["deprecation_warning"],
UserWarning,
stacklevel=2
)
self.attrs.pop("deprecation_warning", None)
num = len(datasets)
mode = attrs.get("mode")
if mode is None:
# num may not be in `self.modes` so only check if we need to
mode = self.modes[num]
if len(datasets) > 1:
datasets = self.match_data_arrays(datasets)
data = self._concat_datasets(datasets, mode)
# Skip masking if user wants it or a specific alpha channel is given.
if self.common_channel_mask and mode[-1] != "A":
data = data.where(data.notnull().all(dim="bands"))
else:
data = datasets[0]
# if inputs have a time coordinate that may differ slightly between
# themselves then find the mid time and use that as the single
# time coordinate value
if len(datasets) > 1:
time = check_times(datasets)
if time is not None and "time" in data.dims:
data["time"] = [time]
new_attrs = combine_metadata(*datasets)
# remove metadata that shouldn't make sense in a composite
new_attrs["wavelength"] = None
new_attrs.pop("units", None)
new_attrs.pop("calibration", None)
new_attrs.pop("modifiers", None)
new_attrs.update({key: val
for (key, val) in attrs.items()
if val is not None})
resolution = new_attrs.get("resolution", None)
new_attrs.update(self.attrs)
if resolution is not None:
new_attrs["resolution"] = resolution
new_attrs["sensor"] = self._get_sensors(datasets)
new_attrs["mode"] = mode
return xr.DataArray(data=data.data, attrs=new_attrs,
dims=data.dims, coords=data.coords)
class FillingCompositor(GenericCompositor):
"""Make a regular RGB, filling the RGB bands with the first provided dataset's values."""
def __call__(self, projectables, nonprojectables=None, **info):
"""Generate the composite."""
projectables = self.match_data_arrays(projectables)
projectables[1] = projectables[1].fillna(projectables[0])
projectables[2] = projectables[2].fillna(projectables[0])
projectables[3] = projectables[3].fillna(projectables[0])
return super(FillingCompositor, self).__call__(projectables[1:], **info)
class Filler(GenericCompositor):
"""Fix holes in projectable 1 with data from projectable 2."""
def __call__(self, projectables, nonprojectables=None, **info):
"""Generate the composite."""
projectables = self.match_data_arrays(projectables)
filled_projectable = projectables[0].fillna(projectables[1])
return super(Filler, self).__call__([filled_projectable], **info)
class MultiFiller(SingleBandCompositor):
"""Fix holes in projectable 1 with data from the next projectables."""
def __call__(self, projectables, nonprojectables=None, **info):
"""Generate the composite."""
projectables = self.match_data_arrays(projectables)
filled_projectable = projectables[0]
for next_projectable in projectables[1:]:
filled_projectable = filled_projectable.fillna(next_projectable)
if "optional_datasets" in info.keys():
for next_projectable in info["optional_datasets"]:
filled_projectable = filled_projectable.fillna(next_projectable)
return super().__call__([filled_projectable], **info)
class RGBCompositor(GenericCompositor):
"""Make a composite from three color bands (deprecated)."""
def __call__(self, projectables, nonprojectables=None, **info):
"""Generate the composite."""
warnings.warn(
"RGBCompositor is deprecated, use GenericCompositor instead.",
DeprecationWarning,
stacklevel=2
)
if len(projectables) != 3:
raise ValueError("Expected 3 datasets, got %d" % (len(projectables),))
return super(RGBCompositor, self).__call__(projectables, **info)
class ColormapCompositor(GenericCompositor):
"""A compositor that uses colormaps.
.. warning::
Deprecated since Satpy 0.39.
This compositor is deprecated. To apply a colormap, use a
:class:`SingleBandCompositor` composite with a
:func:`~satpy.enhancements.colorize` or
:func:`~satpy.enhancements.palettize` enhancement instead.
For example, to make a ``cloud_top_height`` composite based on a dataset
``ctth_alti`` palettized by ``ctth_alti_pal``, the composite would be::
cloud_top_height:
compositor: !!python/name:satpy.composites.SingleBandCompositor
prerequisites:
- ctth_alti
tandard_name: cloud_top_height
and the enhancement::
cloud_top_height:
standard_name: cloud_top_height
operations:
- name: palettize
method: !!python/name:satpy.enhancements.palettize
kwargs:
palettes:
- dataset: ctth_alti_pal
color_scale: 255
min_value: 0
max_value: 255
"""
@staticmethod
def build_colormap(palette, dtype, info):
"""Create the colormap from the `raw_palette` and the valid_range.
Colormaps come in different forms, but they are all supposed to have
color values between 0 and 255. The following cases are considered:
- Palettes comprised of only a list of colors. If *dtype* is uint8,
the values of the colormap are the enumeration of the colors.
Otherwise, the colormap values will be spread evenly from the min
to the max of the valid_range provided in `info`.
- Palettes that have a palette_meanings attribute. The palette meanings
will be used as values of the colormap.
"""
squeezed_palette = np.asanyarray(palette).squeeze() / 255.0
cmap = Colormap.from_array_with_metadata(
palette,
dtype,
color_scale=255,
valid_range=info.get("valid_range"),
scale_factor=info.get("scale_factor", 1),
add_offset=info.get("add_offset", 0))
return cmap, squeezed_palette
def __call__(self, projectables, **info):
"""Generate the composite."""
if len(projectables) != 2:
raise ValueError("Expected 2 datasets, got %d" %
(len(projectables), ))
data, palette = projectables
colormap, palette = self.build_colormap(palette, data.dtype, data.attrs)
channels = self._apply_colormap(colormap, data, palette)
return self._create_composite_from_channels(channels, data)
def _create_composite_from_channels(self, channels, template):
mask = self._get_mask_from_data(template)
channels = [self._create_masked_dataarray_like(channel, template, mask) for channel in channels]
res = super(ColormapCompositor, self).__call__(channels, **template.attrs)
res.attrs["_FillValue"] = np.nan
return res
@staticmethod
def _get_mask_from_data(data):
fill_value = data.attrs.get("_FillValue", np.nan)
if np.isnan(fill_value):
mask = data.notnull()
else:
mask = data != data.attrs["_FillValue"]
return mask
@staticmethod
def _create_masked_dataarray_like(array, template, mask):
return xr.DataArray(array.reshape(template.shape),
dims=template.dims, coords=template.coords,
attrs=template.attrs).where(mask)
class ColorizeCompositor(ColormapCompositor):
"""A compositor colorizing the data, interpolating the palette colors when needed.
.. warning::
Deprecated since Satpy 0.39. See the :class:`ColormapCompositor`
docstring for documentation on the alternative.
"""
@staticmethod
def _apply_colormap(colormap, data, palette):
del palette
return colormap.colorize(data.data.squeeze())
class PaletteCompositor(ColormapCompositor):
"""A compositor colorizing the data, not interpolating the palette colors.
.. warning::
Deprecated since Satpy 0.39. See the :class:`ColormapCompositor`
docstring for documentation on the alternative.
"""
@staticmethod
def _apply_colormap(colormap, data, palette):
channels, colors = colormap.palettize(data.data.squeeze())
channels = channels.map_blocks(_insert_palette_colors, palette, dtype=palette.dtype,
new_axis=2, chunks=list(channels.chunks) + [palette.shape[1]])
return [channels[:, :, i] for i in range(channels.shape[2])]
def _insert_palette_colors(channels, palette):
channels = palette[channels]
return channels
class DayNightCompositor(GenericCompositor):
"""A compositor that blends day data with night data.
Using the `day_night` flag it is also possible to provide only a day product
or only a night product and mask out (make transparent) the opposite portion
of the image (night or day). See the documentation below for more details.
"""
def __init__(self, name, lim_low=85., lim_high=88., day_night="day_night", include_alpha=True, **kwargs): # noqa: D417
"""Collect custom configuration values.
Args:
lim_low (float): lower limit of Sun zenith angle for the
blending of the given channels
lim_high (float): upper limit of Sun zenith angle for the
blending of the given channels
day_night (string): "day_night" means both day and night portions will be kept
"day_only" means only day portion will be kept
"night_only" means only night portion will be kept
include_alpha (bool): This only affects the "day only" or "night only" result.
True means an alpha band will be added to the output image for transparency.
False means the output is a single-band image with undesired pixels being masked out
(replaced with NaNs).
"""
self.lim_low = lim_low
self.lim_high = lim_high
self.day_night = day_night
self.include_alpha = include_alpha
self._has_sza = False
super().__init__(name, **kwargs)
def __call__(
self,
datasets: Sequence[xr.DataArray],
optional_datasets: Optional[Sequence[xr.DataArray]] = None,
**attrs
) -> xr.DataArray:
"""Generate the composite."""
datasets = self.match_data_arrays(datasets)
# At least one composite is requested.
foreground_data = datasets[0]
weights = self._get_coszen_blending_weights(datasets)
# Apply enhancements to the foreground data
foreground_data = enhance2dataset(foreground_data)
if "only" in self.day_night:
fg_attrs = foreground_data.attrs.copy()
day_data, night_data, weights = self._get_data_for_single_side_product(foreground_data, weights)
else:
day_data, night_data, fg_attrs = self._get_data_for_combined_product(foreground_data, datasets[1])
# The computed coszen is for the full area, so it needs to be masked for missing and off-swath data
if self.include_alpha and not self._has_sza:
weights = self._mask_weights_with_data(weights, day_data, night_data)
if "only" not in self.day_night:
# Replace missing channel data with zeros
day_data = zero_missing_data(day_data, night_data)
night_data = zero_missing_data(night_data, day_data)
data = self._weight_data(day_data, night_data, weights, fg_attrs)
return super(DayNightCompositor, self).__call__(
data,
optional_datasets=optional_datasets,
**attrs
)
def _get_coszen_blending_weights(
self,
projectables: Sequence[xr.DataArray],
) -> xr.DataArray:
lim_low = float(np.cos(np.deg2rad(self.lim_low)))
lim_high = float(np.cos(np.deg2rad(self.lim_high)))
try:
coszen = np.cos(np.deg2rad(projectables[2 if self.day_night == "day_night" else 1]))
self._has_sza = True
except IndexError:
from satpy.modifiers.angles import get_cos_sza
LOG.debug("Computing sun zenith angles.")
# Get chunking that matches the data
coszen = get_cos_sza(projectables[0])
# Calculate blending weights
coszen -= min(lim_high, lim_low)
coszen /= abs(lim_low - lim_high)
return coszen.clip(0, 1)
def _get_data_for_single_side_product(
self,
foreground_data: xr.DataArray,
weights: xr.DataArray,
) -> tuple[xr.DataArray, xr.DataArray, xr.DataArray]:
# Only one portion (day or night) is selected. One composite is requested.
# Add alpha band to single L/RGB composite to make the masked-out portion transparent when needed
# L -> LA
# RGB -> RGBA
if self.include_alpha:
foreground_data = add_alpha_bands(foreground_data)
else:
weights = self._mask_weights(weights)
day_data, night_data = self._get_day_night_data_for_single_side_product(foreground_data)
return day_data, night_data, weights
def _mask_weights(self, weights):
if "day" in self.day_night:
return weights.where(weights != 0, np.nan)
return weights.where(weights != 1, np.nan)
def _get_day_night_data_for_single_side_product(self, foreground_data):
if "day" in self.day_night:
return foreground_data, foreground_data.dtype.type(0)
return foreground_data.dtype.type(0), foreground_data
def _get_data_for_combined_product(self, day_data, night_data):
# Apply enhancements also to night-side data
night_data = enhance2dataset(night_data)
# Adjust bands so that they match
# L/RGB -> RGB/RGB
# LA/RGB -> RGBA/RGBA
# RGB/RGBA -> RGBA/RGBA
day_data = add_bands(day_data, night_data["bands"])
night_data = add_bands(night_data, day_data["bands"])
# Get merged metadata
attrs = combine_metadata(day_data, night_data)
return day_data, night_data, attrs
def _mask_weights_with_data(
self,
weights: xr.DataArray,
day_data: xr.DataArray,
night_data: xr.DataArray,
) -> xr.DataArray:
data_a = _get_single_channel(day_data)
data_b = _get_single_channel(night_data)
if "only" in self.day_night:
mask = _get_weight_mask_for_single_side_product(data_a, data_b)
else:
mask = _get_weight_mask_for_daynight_product(weights, data_a, data_b)
return weights.where(mask, np.nan)
def _weight_data(
self,
day_data: xr.DataArray,
night_data: xr.DataArray,
weights: xr.DataArray,
attrs: dict,
) -> list[xr.DataArray]:
if not self.include_alpha:
fill = 1 if self.day_night == "night_only" else 0
weights = weights.where(~np.isnan(weights), fill)
data = []
for b in _get_band_names(day_data, night_data):
day_band = _get_single_band_data(day_data, b)
night_band = _get_single_band_data(night_data, b)
# For day-only and night-only products only the alpha channel is weighted
# If there's no alpha band, weight the actual data
if b == "A" or "only" not in self.day_night or not self.include_alpha:
day_band = day_band * weights
night_band = night_band * (1 - weights)
band = day_band + night_band
band.attrs = attrs
data.append(band)
return data
def _get_band_names(day_data, night_data):
try:
bands = day_data["bands"]
except (IndexError, TypeError):
bands = night_data["bands"]
return bands
def _get_single_band_data(data, band):
try:
return data.sel(bands=band)
except AttributeError:
return data
def _get_single_channel(data: xr.DataArray) -> xr.DataArray:
try:
data = data[0, :, :]
# remove coordinates that may be band-specific (ex. "bands")
# and we don't care about anymore
data = data.reset_coords(drop=True)
except (IndexError, TypeError):
pass
return data
def _get_weight_mask_for_single_side_product(data_a, data_b):
if data_b.shape:
return ~da.isnan(data_b)
return ~da.isnan(data_a)
def _get_weight_mask_for_daynight_product(weights, data_a, data_b):
mask1 = (weights > 0) & ~np.isnan(data_a)
mask2 = (weights < 1) & ~np.isnan(data_b)
return mask1 | mask2
def add_alpha_bands(data):
"""Only used for DayNightCompositor.
Add an alpha band to L or RGB composite as prerequisites for the following band matching
to make the masked-out area transparent.
"""
if "A" not in data["bands"].data:
new_data = [data.sel(bands=band) for band in data["bands"].data]
# Create alpha band based on a copy of the first "real" band
alpha = new_data[0].copy()
alpha.data = da.ones((data.sizes["y"],
data.sizes["x"]),
chunks=new_data[0].chunks,
dtype=data.dtype)
# Rename band to indicate it's alpha
alpha["bands"] = "A"
new_data.append(alpha)
new_data = xr.concat(new_data, dim="bands")
new_data.attrs["mode"] = data.attrs["mode"] + "A"
data = new_data
return data
def enhance2dataset(dset, convert_p=False):
"""Return the enhancement dataset *dset* as an array.
If `convert_p` is True, enhancements generating a P mode will be converted to RGB or RGBA.
"""
attrs = dset.attrs
data = _get_data_from_enhanced_image(dset, convert_p)
data.attrs = attrs
# remove 'mode' if it is specified since it may have been updated
data.attrs.pop("mode", None)
# update mode since it may have changed (colorized/palettize)
data.attrs["mode"] = GenericCompositor.infer_mode(data)
return data
def _get_data_from_enhanced_image(dset, convert_p):
img = get_enhanced_image(dset)
if convert_p and img.mode == "P":
img = _apply_palette_to_image(img)
if img.mode != "P":
data = img.data.clip(0.0, 1.0)
else:
data = img.data
return data
def _apply_palette_to_image(img):
if len(img.palette[0]) == 3:
img = img.convert("RGB")
elif len(img.palette[0]) == 4:
img = img.convert("RGBA")
return img
def add_bands(data, bands):
"""Add bands so that they match *bands*."""
# Add R, G and B bands, remove L band
bands = bands.compute()
if "P" in data["bands"].data or "P" in bands.data:
raise NotImplementedError("Cannot mix datasets of mode P with other datasets at the moment.")
if "L" in data["bands"].data and "R" in bands.data:
lum = data.sel(bands="L")
# Keep 'A' if it was present
if "A" in data["bands"]:
alpha = data.sel(bands="A")
new_data = (lum, lum, lum, alpha)
new_bands = ["R", "G", "B", "A"]
mode = "RGBA"
else:
new_data = (lum, lum, lum)
new_bands = ["R", "G", "B"]
mode = "RGB"
data = xr.concat(new_data, dim="bands", coords={"bands": new_bands})
data["bands"] = new_bands
data.attrs["mode"] = mode
# Add alpha band
if "A" not in data["bands"].data and "A" in bands.data:
new_data = [data.sel(bands=band) for band in data["bands"].data]
# Create alpha band based on a copy of the first "real" band
alpha = new_data[0].copy()
alpha.data = da.ones((data.sizes["y"],
data.sizes["x"]),
dtype=new_data[0].dtype,
chunks=new_data[0].chunks)
# Rename band to indicate it's alpha
alpha["bands"] = "A"
new_data.append(alpha)
new_data = xr.concat(new_data, dim="bands")
new_data.attrs["mode"] = data.attrs["mode"] + "A"
data = new_data
return data
def zero_missing_data(data1, data2):
"""Replace NaN values with zeros in data1 if the data is valid in data2."""