/
geometry.py
2712 lines (2306 loc) · 105 KB
/
geometry.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 -*-
# pyresample, Resampling of remote sensing image data in python
#
# Copyright (C) 2010-2020 Pyresample developers
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Classes for geometry operations."""
import hashlib
import math
import warnings
from collections import OrderedDict
from logging import getLogger
from pathlib import Path
from functools import partial, wraps
import numpy as np
import yaml
from pyproj import Geod, transform
from pyresample import CHUNK_SIZE
from pyresample._spatial_mp import Cartesian, Cartesian_MP, Proj, Proj_MP
from pyresample.boundary import AreaDefBoundary, Boundary, SimpleBoundary
from pyresample.utils import (proj4_dict_to_str,
proj4_radius_parameters,
get_geostationary_height,
check_slice_orientation, load_cf_area)
from pyresample.area_config import create_area_def
try:
from xarray import DataArray
except ImportError:
DataArray = np.ndarray
try:
import dask.array as da
except ImportError:
da = None
from pyproj import CRS
logger = getLogger(__name__)
class DimensionError(ValueError):
"""Wrap ValueError."""
pass
class IncompatibleAreas(ValueError):
"""Error when the areas to combine are not compatible."""
pass
class BaseDefinition:
"""Base class for geometry definitions.
.. versionchanged:: 1.8.0
`BaseDefinition` no longer checks the validity of the provided
longitude and latitude coordinates to improve performance. Longitude
arrays are expected to be between -180 and 180 degrees, latitude -90
to 90 degrees. Use :func:`~pyresample.utils.check_and_wrap` to preprocess
your arrays.
"""
def __init__(self, lons=None, lats=None, nprocs=1):
"""Initialize BaseDefinition."""
if type(lons) != type(lats):
raise TypeError('lons and lats must be of same type')
elif lons is not None:
if not isinstance(lons, (np.ndarray, DataArray)):
lons = np.asanyarray(lons)
lats = np.asanyarray(lats)
if lons.shape != lats.shape:
raise ValueError('lons and lats must have same shape')
self.nprocs = nprocs
self.lats = lats
self.lons = lons
self.ndim = None
self.cartesian_coords = None
self.hash = None
def __getitem__(self, key):
"""Slice a 2D geographic definition."""
y_slice, x_slice = key
return self.__class__(
lons=self.lons[y_slice, x_slice],
lats=self.lats[y_slice, x_slice],
nprocs=self.nprocs
)
def __hash__(self):
"""Compute the hash of this object."""
if self.hash is None:
self.hash = int(self.update_hash().hexdigest(), 16)
return self.hash
def __eq__(self, other):
"""Test for approximate equality."""
if self is other:
return True
if not isinstance(other, BaseDefinition):
return False
if other.lons is None or other.lats is None:
other_lons, other_lats = other.get_lonlats()
else:
other_lons = other.lons
other_lats = other.lats
if self.lons is None or self.lats is None:
self_lons, self_lats = self.get_lonlats()
else:
self_lons = self.lons
self_lats = self.lats
if self_lons is other_lons and self_lats is other_lats:
return True
if isinstance(self_lons, DataArray) and np.ndarray is not DataArray:
self_lons = self_lons.data
self_lats = self_lats.data
if isinstance(other_lons, DataArray) and np.ndarray is not DataArray:
other_lons = other_lons.data
other_lats = other_lats.data
try:
from dask.array import allclose
except ImportError:
from numpy import allclose
try:
return (allclose(self_lons, other_lons, atol=1e-6, rtol=5e-9, equal_nan=True) and
allclose(self_lats, other_lats, atol=1e-6, rtol=5e-9, equal_nan=True))
except (AttributeError, ValueError):
return False
def __ne__(self, other):
"""Test for approximate equality."""
return not self.__eq__(other)
def get_area_extent_for_subset(self, row_LR, col_LR, row_UL, col_UL):
"""Calculate extent for a subdomain of this area.
Rows are counted from upper left to lower left and columns are
counted from upper left to upper right.
Args:
row_LR (int): row of the lower right pixel
col_LR (int): col of the lower right pixel
row_UL (int): row of the upper left pixel
col_UL (int): col of the upper left pixel
Returns:
area_extent (tuple):
Area extent (LL_x, LL_y, UR_x, UR_y) of the subset
Author:
Ulrich Hamann
"""
(a, b) = self.get_proj_coords(data_slice=(row_LR, col_LR))
a = a - 0.5 * self.pixel_size_x
b = b - 0.5 * self.pixel_size_y
(c, d) = self.get_proj_coords(data_slice=(row_UL, col_UL))
c = c + 0.5 * self.pixel_size_x
d = d + 0.5 * self.pixel_size_y
return a, b, c, d
def get_lonlat(self, row, col):
"""Retrieve lon and lat of single pixel.
Parameters
----------
row : int
col : int
Returns
-------
(lon, lat) : tuple of floats
"""
if self.ndim != 2:
raise DimensionError(('operation undefined '
'for %sD geometry ') % self.ndim)
elif self.lons is None or self.lats is None:
raise ValueError('lon/lat values are not defined')
return self.lons[row, col], self.lats[row, col]
def get_lonlats(self, data_slice=None, chunks=None, **kwargs):
"""Get longitude and latitude arrays representing this geometry.
Returns
-------
(lon, lat) : tuple of numpy arrays
If `chunks` is provided then the arrays will be dask arrays
with the provided chunk size. If `chunks` is not provided then
the returned arrays are the same as the internal data types
of this geometry object (numpy or dask).
"""
lons = self.lons
lats = self.lats
if lons is None or lats is None:
raise ValueError('lon/lat values are not defined')
elif DataArray is not np.ndarray and isinstance(lons, DataArray):
# lons/lats are xarray DataArray objects, use numpy/dask array underneath
lons = lons.data
lats = lats.data
if chunks is not None:
import dask.array as da
if isinstance(lons, da.Array):
# rechunk to this specific chunk size
lons = lons.rechunk(chunks)
lats = lats.rechunk(chunks)
elif not isinstance(lons, da.Array):
# convert numpy array to dask array
lons = da.from_array(np.asanyarray(lons), chunks=chunks)
lats = da.from_array(np.asanyarray(lats), chunks=chunks)
if data_slice is not None:
lons, lats = lons[data_slice], lats[data_slice]
return lons, lats
def get_lonlats_dask(self, chunks=None):
"""Get the lon lats as a single dask array."""
warnings.warn("'get_lonlats_dask' is deprecated, please use "
"'get_lonlats' with the 'chunks' keyword argument specified.", DeprecationWarning)
if chunks is None:
chunks = CHUNK_SIZE # FUTURE: Use a global config object instead
return self.get_lonlats(chunks=chunks)
def get_boundary_lonlats(self):
"""Return Boundary objects."""
s1_lon, s1_lat = self.get_lonlats(data_slice=(0, slice(None)))
s2_lon, s2_lat = self.get_lonlats(data_slice=(slice(None), -1))
s3_lon, s3_lat = self.get_lonlats(data_slice=(-1, slice(None, None, -1)))
s4_lon, s4_lat = self.get_lonlats(data_slice=(slice(None, None, -1), 0))
return (SimpleBoundary(s1_lon.squeeze(), s2_lon.squeeze(), s3_lon.squeeze(), s4_lon.squeeze()),
SimpleBoundary(s1_lat.squeeze(), s2_lat.squeeze(), s3_lat.squeeze(), s4_lat.squeeze()))
def get_bbox_lonlats(self):
"""Return the bounding box lons and lats."""
s1_lon, s1_lat = self.get_lonlats(data_slice=(0, slice(None)))
s2_lon, s2_lat = self.get_lonlats(data_slice=(slice(None), -1))
s3_lon, s3_lat = self.get_lonlats(data_slice=(-1, slice(None, None, -1)))
s4_lon, s4_lat = self.get_lonlats(data_slice=(slice(None, None, -1), 0))
return zip(*[(s1_lon.squeeze(), s1_lat.squeeze()),
(s2_lon.squeeze(), s2_lat.squeeze()),
(s3_lon.squeeze(), s3_lat.squeeze()),
(s4_lon.squeeze(), s4_lat.squeeze())])
def get_cartesian_coords(self, nprocs=None, data_slice=None, cache=False):
"""Retrieve cartesian coordinates of geometry definition.
Parameters
----------
nprocs : int, optional
Number of processor cores to be used.
Defaults to the nprocs set when instantiating object
data_slice : slice object, optional
Calculate only cartesian coordnates for the defined slice
cache : bool, optional
Store result the result. Requires data_slice to be None
Returns
-------
cartesian_coords : numpy array
"""
if cache:
warnings.warn("'cache' keyword argument will be removed in the "
"future and data will not be cached.", PendingDeprecationWarning)
if self.cartesian_coords is None:
# Coordinates are not cached
if nprocs is None:
nprocs = self.nprocs
if data_slice is None:
# Use full slice
data_slice = slice(None)
lons, lats = self.get_lonlats(nprocs=nprocs, data_slice=data_slice)
if nprocs > 1:
cartesian = Cartesian_MP(nprocs)
else:
cartesian = Cartesian()
cartesian_coords = cartesian.transform_lonlats(np.ravel(lons), np.ravel(lats))
if isinstance(lons, np.ndarray) and lons.ndim > 1:
# Reshape to correct shape
cartesian_coords = cartesian_coords.reshape(lons.shape[0], lons.shape[1], 3)
if cache and data_slice is None:
self.cartesian_coords = cartesian_coords
else:
# Coordinates are cached
if data_slice is None:
cartesian_coords = self.cartesian_coords
else:
cartesian_coords = self.cartesian_coords[data_slice]
return cartesian_coords
@property
def corners(self):
"""Return the corners of the current area."""
from pyresample.spherical_geometry import Coordinate
return [Coordinate(*self.get_lonlat(0, 0)),
Coordinate(*self.get_lonlat(0, -1)),
Coordinate(*self.get_lonlat(-1, -1)),
Coordinate(*self.get_lonlat(-1, 0))]
def __contains__(self, point):
"""Check if a point is inside the 4 corners of the current area.
This uses great circle arcs as area boundaries.
"""
from pyresample.spherical_geometry import point_inside, Coordinate
corners = self.corners
if isinstance(point, tuple):
return point_inside(Coordinate(*point), corners)
else:
return point_inside(point, corners)
def overlaps(self, other):
"""Test if the current area overlaps the *other* area.
This is based solely on the corners of areas, assuming the
boundaries to be great circles.
Parameters
----------
other : object
Instance of subclass of BaseDefinition
Returns
-------
overlaps : bool
"""
from pyresample.spherical_geometry import Arc
self_corners = self.corners
other_corners = other.corners
for i in self_corners:
if i in other:
return True
for i in other_corners:
if i in self:
return True
self_arc1 = Arc(self_corners[0], self_corners[1])
self_arc2 = Arc(self_corners[1], self_corners[2])
self_arc3 = Arc(self_corners[2], self_corners[3])
self_arc4 = Arc(self_corners[3], self_corners[0])
other_arc1 = Arc(other_corners[0], other_corners[1])
other_arc2 = Arc(other_corners[1], other_corners[2])
other_arc3 = Arc(other_corners[2], other_corners[3])
other_arc4 = Arc(other_corners[3], other_corners[0])
for i in (self_arc1, self_arc2, self_arc3, self_arc4):
for j in (other_arc1, other_arc2, other_arc3, other_arc4):
if i.intersects(j):
return True
return False
def get_area(self):
"""Get the area of the convex area defined by the corners of the curren area."""
from pyresample.spherical_geometry import get_polygon_area
return get_polygon_area(self.corners)
def intersection(self, other):
"""Return the corners of the intersection polygon of the current area with *other*.
Parameters
----------
other : object
Instance of subclass of BaseDefinition
Returns
-------
(corner1, corner2, corner3, corner4) : tuple of points
"""
from pyresample.spherical_geometry import intersection_polygon
return intersection_polygon(self.corners, other.corners)
def overlap_rate(self, other):
"""Get how much the current area overlaps an *other* area.
Parameters
----------
other : object
Instance of subclass of BaseDefinition
Returns
-------
overlap_rate : float
"""
from pyresample.spherical_geometry import get_polygon_area
other_area = other.get_area()
inter_area = get_polygon_area(self.intersection(other))
return inter_area / other_area
def get_area_slices(self, area_to_cover):
"""Compute the slice to read based on an `area_to_cover`."""
raise NotImplementedError
class CoordinateDefinition(BaseDefinition):
"""Base class for geometry definitions defined by lons and lats only."""
def __init__(self, lons, lats, nprocs=1):
"""Initialize CoordinateDefinition."""
if not isinstance(lons, (np.ndarray, DataArray)):
lons = np.asanyarray(lons)
lats = np.asanyarray(lats)
super(CoordinateDefinition, self).__init__(lons, lats, nprocs)
if lons.shape == lats.shape and lons.dtype == lats.dtype:
self.shape = lons.shape
self.size = lons.size
self.ndim = lons.ndim
self.dtype = lons.dtype
else:
raise ValueError(('%s must be created with either '
'lon/lats of the same shape with same dtype') %
self.__class__.__name__)
def concatenate(self, other):
"""Concatenate coordinate definitions."""
if self.ndim != other.ndim:
raise DimensionError(('Unable to concatenate %sD and %sD '
'geometries') % (self.ndim, other.ndim))
klass = _get_highest_level_class(self, other)
lons = np.concatenate((self.lons, other.lons))
lats = np.concatenate((self.lats, other.lats))
nprocs = min(self.nprocs, other.nprocs)
return klass(lons, lats, nprocs=nprocs)
def append(self, other):
"""Append another coordinate definition to existing one."""
if self.ndim != other.ndim:
raise DimensionError(('Unable to append %sD and %sD '
'geometries') % (self.ndim, other.ndim))
self.lons = np.concatenate((self.lons, other.lons))
self.lats = np.concatenate((self.lats, other.lats))
self.shape = self.lons.shape
self.size = self.lons.size
def __str__(self):
"""Return string representation of the coordinate definition."""
# Rely on numpy's object printing
return ('Shape: %s\nLons: %s\nLats: %s') % (str(self.shape),
str(self.lons),
str(self.lats))
def geocentric_resolution(self, ellps='WGS84', radius=None, nadir_factor=2):
"""Calculate maximum geocentric pixel resolution.
If `lons` is a :class:`xarray.DataArray` object with a `resolution`
attribute, this will be used instead of loading the longitude and
latitude data. In this case the resolution attribute is assumed to
mean the nadir resolution of a swath and will be multiplied by the
`nadir_factor` to adjust for increases in the spatial resolution
towards the limb of the swath.
Args:
ellps (str): PROJ Ellipsoid for the Cartographic projection
used as the target geocentric coordinate reference system.
Default: 'WGS84'. Ignored if `radius` is provided.
radius (float): Spherical radius of the Earth to use instead of
the definitions in `ellps`.
nadir_factor (int): Number to multiply the nadir resolution
attribute by to reflect pixel size on the limb of the swath.
Returns: Estimated maximum pixel size in meters on a geocentric
coordinate system (X, Y, Z) representing the Earth.
Raises: RuntimeError if a simple search for valid longitude/latitude
data points found no valid data points.
"""
if hasattr(self.lons, 'attrs') and \
self.lons.attrs.get('resolution') is not None:
return self.lons.attrs['resolution'] * nadir_factor
if self.ndim == 1:
raise RuntimeError("Can't confidently determine geocentric "
"resolution for 1D swath.")
from pyproj import transform
rows = self.shape[0]
start_row = rows // 2 # middle row
src = Proj('+proj=latlong +datum=WGS84')
if radius:
dst = Proj("+proj=cart +a={} +b={}".format(radius, radius))
else:
dst = Proj("+proj=cart +ellps={}".format(ellps))
# simply take the first two columns of the middle of the swath
lons = self.lons[start_row: start_row + 1, :2]
lats = self.lats[start_row: start_row + 1, :2]
if hasattr(lons.data, 'compute'):
# dask arrays, compute them together
import dask.array as da
lons, lats = da.compute(lons, lats)
if hasattr(lons, 'values'):
# convert xarray to numpy array
lons = lons.values
lats = lats.values
lons = lons.ravel()
lats = lats.ravel()
alt = np.zeros_like(lons)
xyz = np.stack(transform(src, dst, lons, lats, alt), axis=1)
dist = np.linalg.norm(xyz[1] - xyz[0])
dist = dist[np.isfinite(dist)]
if not dist.size:
raise RuntimeError("Could not calculate geocentric resolution")
return dist[0]
class GridDefinition(CoordinateDefinition):
"""Grid defined by lons and lats.
Parameters
----------
lons : numpy array
lats : numpy array
nprocs : int, optional
Number of processor cores to be used for calculations.
Attributes
----------
shape : tuple
Grid shape as (rows, cols)
size : int
Number of elements in grid
lons : object
Grid lons
lats : object
Grid lats
cartesian_coords : object
Grid cartesian coordinates
"""
def __init__(self, lons, lats, nprocs=1):
"""Initialize GridDefinition."""
super(GridDefinition, self).__init__(lons, lats, nprocs)
if lons.shape != lats.shape:
raise ValueError('lon and lat grid must have same shape')
elif lons.ndim != 2:
raise ValueError('2 dimensional lon lat grid expected')
def get_array_hashable(arr):
"""Compute a hashable form of the array `arr`.
Works with numpy arrays, dask.array.Array, and xarray.DataArray.
"""
# look for precomputed value
if isinstance(arr, DataArray) and np.ndarray is not DataArray:
return arr.attrs.get('hash', get_array_hashable(arr.data))
else:
try:
return arr.name.encode('utf-8') # dask array
except AttributeError:
return np.asarray(arr).view(np.uint8) # np array
class SwathDefinition(CoordinateDefinition):
"""Swath defined by lons and lats.
Parameters
----------
lons : numpy array
lats : numpy array
nprocs : int, optional
Number of processor cores to be used for calculations.
Attributes
----------
shape : tuple
Swath shape
size : int
Number of elements in swath
ndims : int
Swath dimensions
lons : object
Swath lons
lats : object
Swath lats
cartesian_coords : object
Swath cartesian coordinates
"""
def __init__(self, lons, lats, nprocs=1):
"""Initialize SwathDefinition."""
if not isinstance(lons, (np.ndarray, DataArray)):
lons = np.asanyarray(lons)
lats = np.asanyarray(lats)
super(SwathDefinition, self).__init__(lons, lats, nprocs)
if lons.shape != lats.shape:
raise ValueError('lon and lat arrays must have same shape')
elif lons.ndim > 2:
raise ValueError('Only 1 and 2 dimensional swaths are allowed')
def copy(self):
"""Copy the current swath."""
return SwathDefinition(self.lons, self.lats)
@staticmethod
def _do_transform(src, dst, lons, lats, alt):
"""Run pyproj.transform and stack the results."""
x, y, z = transform(src, dst, lons, lats, alt)
return np.dstack((x, y, z))
def aggregate(self, **dims):
"""Aggregate the current swath definition by averaging.
For example, averaging over 2x2 windows:
`sd.aggregate(x=2, y=2)`
"""
import pyproj
import dask.array as da
geocent = pyproj.Proj(proj='geocent')
latlong = pyproj.Proj(proj='latlong')
res = da.map_blocks(self._do_transform, latlong, geocent,
self.lons.data, self.lats.data,
da.zeros_like(self.lons.data), new_axis=[2],
chunks=(self.lons.chunks[0], self.lons.chunks[1], 3))
res = DataArray(res, dims=['y', 'x', 'coord'], coords=self.lons.coords)
res = res.coarsen(**dims).mean()
lonlatalt = da.map_blocks(self._do_transform, geocent, latlong,
res[:, :, 0].data, res[:, :, 1].data,
res[:, :, 2].data, new_axis=[2],
chunks=res.data.chunks)
lons = DataArray(lonlatalt[:, :, 0], dims=self.lons.dims,
coords=res.coords, attrs=self.lons.attrs.copy())
lats = DataArray(lonlatalt[:, :, 1], dims=self.lons.dims,
coords=res.coords, attrs=self.lons.attrs.copy())
try:
resolution = lons.attrs['resolution'] * ((dims.get('x', 1) + dims.get('y', 1)) / 2)
lons.attrs['resolution'] = resolution
lats.attrs['resolution'] = resolution
except KeyError:
pass
return SwathDefinition(lons, lats)
def __hash__(self):
"""Compute the hash of this object."""
if self.hash is None:
self.hash = int(self.update_hash().hexdigest(), 16)
return self.hash
def update_hash(self, the_hash=None):
"""Update the hash."""
if the_hash is None:
the_hash = hashlib.sha1()
the_hash.update(get_array_hashable(self.lons))
the_hash.update(get_array_hashable(self.lats))
try:
if self.lons.mask is not False:
the_hash.update(get_array_hashable(self.lons.mask))
except AttributeError:
pass
return the_hash
def _compute_omerc_parameters(self, ellipsoid):
"""Compute the oblique mercator projection bouding box parameters."""
lines, cols = self.lons.shape
lon1, lon2 = np.asanyarray(self.lons[[0, -1], int(cols / 2)])
lat1, lat, lat2 = np.asanyarray(
self.lats[[0, int(lines / 2), -1], int(cols / 2)])
if any(np.isnan((lon1, lon2, lat1, lat, lat2))):
thelons = self.lons[:, int(cols / 2)]
thelons = thelons.where(thelons.notnull(), drop=True)
thelats = self.lats[:, int(cols / 2)]
thelats = thelats.where(thelats.notnull(), drop=True)
lon1, lon2 = np.asanyarray(thelons[[0, -1]])
lines = len(thelats)
lat1, lat, lat2 = np.asanyarray(thelats[[0, int(lines / 2), -1]])
proj_dict2points = {'proj': 'omerc', 'lat_0': lat, 'ellps': ellipsoid,
'lat_1': lat1, 'lon_1': lon1,
'lat_2': lat2, 'lon_2': lon2,
'no_rot': True
}
# We need to compute alpha-based omerc for geotiff support
lonc, lat0 = Proj(**proj_dict2points)(0, 0, inverse=True)
az1, az2, _ = Geod(**proj_dict2points).inv(lonc, lat0, lon2, lat2)
azimuth = az1
az1, az2, _ = Geod(**proj_dict2points).inv(lonc, lat0, lon1, lat1)
if abs(az1 - azimuth) > 1:
if abs(az2 - azimuth) > 1:
logger.warning("Can't find appropriate azimuth.")
else:
azimuth += az2
azimuth /= 2
else:
azimuth += az1
azimuth /= 2
if abs(azimuth) > 90:
azimuth = 180 + azimuth
prj_params = {'proj': 'omerc', 'alpha': float(azimuth), 'lat_0': float(lat0), 'lonc': float(lonc),
'gamma': 0,
'ellps': ellipsoid}
return prj_params
def _compute_generic_parameters(self, projection, ellipsoid):
"""Compute the projection bb parameters for most projections."""
lines, cols = self.lons.shape
lat_0 = self.lats[int(lines / 2), int(cols / 2)]
lon_0 = self.lons[int(lines / 2), int(cols / 2)]
return {'proj': projection, 'ellps': ellipsoid,
'lat_0': lat_0, 'lon_0': lon_0}
def get_edge_lonlats(self):
"""Get the concatenated boundary of the current swath."""
lons, lats = self.get_bbox_lonlats()
blons = np.ma.concatenate(lons)
blats = np.ma.concatenate(lats)
return blons, blats
def compute_bb_proj_params(self, proj_dict):
"""Compute BB projection parameters."""
projection = proj_dict['proj']
if projection == 'omerc':
ellipsoid = proj_dict.get('ellps', 'sphere')
return self._compute_omerc_parameters(ellipsoid)
else:
ellipsoid = proj_dict.get('ellps', 'WGS84')
new_proj = self._compute_generic_parameters(projection, ellipsoid)
new_proj.update(proj_dict)
return new_proj
def _compute_uniform_shape(self):
"""Compute the height and width of a domain to have uniform resolution across dimensions."""
g = Geod(ellps='WGS84')
def notnull(arr):
try:
return arr.where(arr.notnull(), drop=True)
except AttributeError:
return arr[np.isfinite(arr)]
leftlons = self.lons[:, 0]
rightlons = self.lons[:, -1]
middlelons = self.lons[:, int(self.lons.shape[1] / 2)]
leftlats = self.lats[:, 0]
rightlats = self.lats[:, -1]
middlelats = self.lats[:, int(self.lats.shape[1] / 2)]
try:
import dask.array as da
except ImportError:
pass
else:
leftlons, rightlons, middlelons, leftlats, rightlats, middlelats = da.compute(leftlons, rightlons,
middlelons, leftlats,
rightlats, middlelats)
leftlons = notnull(leftlons)
rightlons = notnull(rightlons)
middlelons = notnull(middlelons)
leftlats = notnull(leftlats)
rightlats = notnull(rightlats)
middlelats = notnull(middlelats)
az1, az2, width1 = g.inv(leftlons[0], leftlats[0], rightlons[0], rightlats[0])
az1, az2, width2 = g.inv(leftlons[-1], leftlats[-1], rightlons[-1], rightlats[-1])
az1, az2, height = g.inv(middlelons[0], middlelats[0], middlelons[-1], middlelats[-1])
width = min(width1, width2)
vresolution = height * 1.0 / self.lons.shape[0]
hresolution = width * 1.0 / self.lons.shape[1]
resolution = min(vresolution, hresolution)
width = int(width * 1.1 / resolution)
height = int(height * 1.1 / resolution)
return height, width
def compute_optimal_bb_area(self, proj_dict=None):
"""Compute the "best" bounding box area for this swath with `proj_dict`.
By default, the projection is Oblique Mercator (`omerc` in proj.4), in
which case the right projection angle `alpha` is computed from the
swath centerline. For other projections, only the appropriate center of
projection and area extents are computed.
The height and width are computed so that the resolution is
approximately the same across dimensions.
"""
if proj_dict is None:
proj_dict = {}
projection = proj_dict.setdefault('proj', 'omerc')
area_id = projection + '_otf'
description = 'On-the-fly ' + projection + ' area'
height, width = self._compute_uniform_shape()
proj_dict = self.compute_bb_proj_params(proj_dict)
area = DynamicAreaDefinition(area_id, description, proj_dict)
lons, lats = self.get_edge_lonlats()
return area.freeze((lons, lats), shape=(height, width))
class DynamicAreaDefinition(object):
"""An AreaDefintion containing just a subset of the needed parameters.
The purpose of this class is to be able to adapt the area extent and shape
of the area to a given set of longitudes and latitudes, such that e.g.
polar satellite granules can be resampled optimally to a given projection.
Note that if the provided projection is geographic (lon/lat degrees) and
the provided longitude and latitude data crosses the anti-meridian
(-180/180), the resulting area will be the smallest possible in order to
contain that data and avoid a large area spanning from -180 to 180
longitude. This means the resulting AreaDefinition will have a right-most
X extent greater than 180 degrees. This does not apply to data crossing
the north or south pole as there is no "smallest" area in this case.
Attributes:
area_id:
The name of the area.
description:
The description of the area.
projection:
The dictionary or string or CRS object of projection parameters.
Doesn't have to be complete. If not complete, ``proj_info`` must
be provided to ``freeze`` to "fill in" any missing parameters.
width:
x dimension in number of pixels, aka number of grid columns
height:
y dimension in number of pixels, aka number of grid rows
shape:
Corresponding array shape as (height, width)
area_extent:
The area extent of the area.
pixel_size_x:
Pixel width in projection units
pixel_size_y:
Pixel height in projection units
resolution:
Resolution of the resulting area as (pixel_size_x, pixel_size_y)
or a scalar if pixel_size_x == pixel_size_y.
optimize_projection:
Whether the projection parameters have to be optimized.
rotation:
Rotation in degrees (negative is cw)
"""
def __init__(self, area_id=None, description=None, projection=None,
width=None, height=None, area_extent=None,
resolution=None, optimize_projection=False, rotation=None):
"""Initialize the DynamicAreaDefinition."""
self.area_id = area_id
self.description = description
self.width = width
self.height = height
self.shape = (self.height, self.width)
self.area_extent = area_extent
self.optimize_projection = optimize_projection
if isinstance(resolution, (int, float)):
resolution = (resolution, resolution)
self.resolution = resolution
self.rotation = rotation
self._projection = projection
# check if non-dict projections are valid
# dicts may be updated later
if not isinstance(self._projection, dict):
CRS(projection)
def _get_proj_dict(self):
projection = self._projection
try:
crs = CRS(projection)
except RuntimeError:
# could be incomplete dictionary
return projection
return crs.to_dict()
@property
def pixel_size_x(self):
"""Return pixel size in X direction."""
if self.resolution is None:
return None
return self.resolution[0]
@property
def pixel_size_y(self):
"""Return pixel size in Y direction."""
if self.resolution is None:
return None
return self.resolution[1]
def compute_domain(self, corners, resolution=None, shape=None):
"""Compute shape and area_extent from corners and [shape or resolution] info.
Corners represents the center of pixels, while area_extent represents the edge of pixels.
Note that ``shape`` is (rows, columns) and ``resolution`` is
(x_size, y_size); the dimensions are flipped.
"""
if resolution is not None and shape is not None:
raise ValueError("Both resolution and shape can't be provided.")
elif resolution is None and shape is None:
raise ValueError("Either resolution or shape must be provided.")
if shape:
height, width = shape
x_resolution = (corners[2] - corners[0]) * 1.0 / (width - 1)
y_resolution = (corners[3] - corners[1]) * 1.0 / (height - 1)
else:
if isinstance(resolution, (int, float)):
resolution = (resolution, resolution)
x_resolution, y_resolution = resolution
width = int(np.rint((corners[2] - corners[0]) * 1.0
/ x_resolution + 1))
height = int(np.rint((corners[3] - corners[1]) * 1.0
/ y_resolution + 1))
area_extent = (corners[0] - x_resolution / 2,
corners[1] - y_resolution / 2,
corners[2] + x_resolution / 2,
corners[3] + y_resolution / 2)
return area_extent, width, height
def freeze(self, lonslats=None, resolution=None, shape=None, proj_info=None):
"""Create an AreaDefinition from this area with help of some extra info.
Parameters
----------
lonlats : SwathDefinition or tuple
The geographical coordinates to contain in the resulting area.
A tuple should be ``(lons, lats)``.
resolution:
the resolution of the resulting area.
shape:
the shape of the resulting area.
proj_info:
complementing parameters to the projection info.
Resolution and shape parameters are ignored if the instance is created
with the `optimize_projection` flag set to True.
"""
proj_dict = self._get_proj_dict()
projection = self._projection
if proj_info is not None:
# this is now our complete projection information
proj_dict.update(proj_info)
projection = proj_dict
if self.optimize_projection:
return lonslats.compute_optimal_bb_area(proj_dict)
if resolution is None:
resolution = self.resolution
if shape is None:
shape = self.shape
height, width = shape
shape = None if None in shape else shape
area_extent = self.area_extent
if not area_extent or not width or not height:
corners = self._compute_bound_centers(proj_dict, lonslats)
area_extent, width, height = self.compute_domain(corners, resolution, shape)
return AreaDefinition(self.area_id, self.description, '',
projection, width, height,
area_extent, self.rotation)
def _compute_bound_centers(self, proj_dict, lonslats):
lons, lats = self._extract_lons_lats(lonslats)
if hasattr(lons, 'compute'):
return self._compute_bound_centers_dask(proj_dict, lons, lats)
return self._compute_bound_centers_numpy(proj_dict, lons, lats)
def _compute_bound_centers_numpy(self, proj_dict, lons, lats):
# TODO: Do more dask-friendly things here
proj4 = Proj(proj_dict)
xarr, yarr = proj4(np.asarray(lons), np.asarray(lats))
xarr[xarr > 9e29] = np.nan
yarr[yarr > 9e29] = np.nan
xmin = np.nanmin(xarr)
xmax = np.nanmax(xarr)
ymin = np.nanmin(yarr)
ymax = np.nanmax(yarr)
x_passes_antimeridian = (xmax - xmin) > 355
epsilon = 0.1