forked from SciTools/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coord_systems.py
1679 lines (1384 loc) · 56.8 KB
/
coord_systems.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 Iris contributors
#
# This file is part of Iris and is released under the BSD license.
# See LICENSE in the root of the repository for full licensing details.
"""Definitions of coordinate systems."""
from abc import ABCMeta, abstractmethod
from functools import cached_property
import re
import warnings
import cartopy.crs as ccrs
import numpy as np
from iris._deprecation import warn_deprecated
import iris.warnings
def _arg_default(value, default, cast_as=float):
"""Apply a default value and type for an optional kwarg."""
if value is None:
value = default
value = cast_as(value)
return value
def _1or2_parallels(arg):
"""Accept 1 or 2 inputs as a tuple of 1 or 2 floats."""
try:
values_tuple = tuple(arg)
except TypeError:
values_tuple = (arg,)
values_tuple = tuple([float(x) for x in values_tuple])
nvals = len(values_tuple)
if nvals not in (1, 2):
emsg = "Allows only 1 or 2 parallels or secant latitudes : got {!r}"
raise ValueError(emsg.format(arg))
return values_tuple
def _float_or_None(arg):
"""Cast as float, except for allowing None as a distinct valid value."""
if arg is not None:
arg = float(arg)
return arg
class CoordSystem(metaclass=ABCMeta):
"""Abstract base class for coordinate systems."""
grid_mapping_name = None
def __eq__(self, other):
"""Override equality.
The `_globe` and `_crs` attributes are not compared because they are
cached properties and completely derived from other attributes. The
nature of caching means that they can appear on one object and not on
another despite the objects being identical, and them being completely
derived from other attributes means they will only differ if other
attributes that are being tested for equality differ.
"""
if self.__class__ != other.__class__:
return False
self_keys = set(self.__dict__.keys())
other_keys = set(other.__dict__.keys())
check_keys = (self_keys | other_keys) - {"_globe", "_crs"}
for key in check_keys:
try:
if self.__dict__[key] != other.__dict__[key]:
return False
except KeyError:
return False
return True
def __ne__(self, other):
# Must supply __ne__, Python does not defer to __eq__ for
# negative equality.
return not (self == other)
def xml_element(self, doc, attrs=None):
"""Perform default behaviour for coord systems."""
# attrs - optional list of (k,v) items, used for alternate output
xml_element_name = type(self).__name__
# lower case the first char
first_char = xml_element_name[0]
xml_element_name = xml_element_name.replace(first_char, first_char.lower(), 1)
coord_system_xml_element = doc.createElement(xml_element_name)
if attrs is None:
attrs = self.__dict__.items()
attrs = sorted(attrs, key=lambda attr: attr[0])
for name, value in attrs:
if isinstance(value, float):
value_str = "{:.16}".format(value)
elif isinstance(value, np.float32):
value_str = "{:.8}".format(value)
else:
value_str = "{}".format(value)
coord_system_xml_element.setAttribute(name, value_str)
return coord_system_xml_element
@staticmethod
def _ellipsoid_to_globe(ellipsoid, globe_default):
if ellipsoid is not None:
globe = ellipsoid.as_cartopy_globe()
else:
globe = globe_default
return globe
@abstractmethod
def as_cartopy_crs(self):
"""Return a cartopy CRS representing our native coordinate system."""
pass
@abstractmethod
def as_cartopy_projection(self):
"""Return a cartopy projection representing our native map.
This will be the same as the :func:`~CoordSystem.as_cartopy_crs` for
map projections but for spherical coord systems (which are not map
projections) we use a map projection, such as PlateCarree.
"""
pass
_short_datum_names = {
"OSGB 1936": "OSGB36",
"OSGB_1936": "OSGB36",
"WGS 84": "WGS84",
}
class GeogCS(CoordSystem):
"""A geographic (ellipsoidal) coordinate system.
A geographic (ellipsoidal) coordinate system, defined by the shape of
the Earth and a prime meridian.
"""
grid_mapping_name = "latitude_longitude"
def __init__(
self,
semi_major_axis=None,
semi_minor_axis=None,
inverse_flattening=None,
longitude_of_prime_meridian=None,
):
"""Create a new GeogCS.
Parameters
----------
semi_major_axis, semi_minor_axis : optional
Axes of ellipsoid, in metres. At least one must be given (see note
below).
inverse_flattening : optional
Can be omitted if both axes given (see note below). Default 0.0
longitude_of_prime_meridian : optional
Specifies the prime meridian on the ellipsoid, in degrees. Default 0.0
Notes
-----
If just semi_major_axis is set, with no semi_minor_axis or
inverse_flattening, then a perfect sphere is created from the given
radius.
If just two of semi_major_axis, semi_minor_axis, and inverse_flattening
are given the missing element is calculated from the formula:
:math:`flattening = (major - minor) / major`
Currently, Iris will not allow over-specification (all three ellipsoid
parameters).
After object creation, altering any of these properties will not update
the others. semi_major_axis and semi_minor_axis are used when creating
Cartopy objects.
Examples::
cs = GeogCS(6371229)
pp_cs = GeogCS(iris.fileformats.pp.EARTH_RADIUS)
airy1830 = GeogCS(semi_major_axis=6377563.396,
semi_minor_axis=6356256.909)
airy1830 = GeogCS(semi_major_axis=6377563.396,
inverse_flattening=299.3249646)
custom_cs = GeogCS(6400000, 6300000)
"""
# No ellipsoid specified? (0 0 0)
if (
(semi_major_axis is None)
and (semi_minor_axis is None)
and (inverse_flattening is None)
):
raise ValueError("No ellipsoid specified")
# Ellipsoid over-specified? (1 1 1)
if (
(semi_major_axis is not None)
and (semi_minor_axis is not None)
and (inverse_flattening is not None)
):
raise ValueError("Ellipsoid is overspecified")
# Perfect sphere (semi_major_axis only)? (1 0 0)
elif semi_major_axis is not None and (
semi_minor_axis is None and not inverse_flattening
):
semi_minor_axis = semi_major_axis
inverse_flattening = 0.0
# Calculate semi_major_axis? (0 1 1)
elif semi_major_axis is None and (
semi_minor_axis is not None and inverse_flattening is not None
):
semi_major_axis = -semi_minor_axis / (
(1.0 - inverse_flattening) / inverse_flattening
)
# Calculate semi_minor_axis? (1 0 1)
elif semi_minor_axis is None and (
semi_major_axis is not None and inverse_flattening is not None
):
semi_minor_axis = semi_major_axis - (
(1.0 / inverse_flattening) * semi_major_axis
)
# Calculate inverse_flattening? (1 1 0)
elif inverse_flattening is None and (
semi_major_axis is not None and semi_minor_axis is not None
):
if semi_major_axis == semi_minor_axis:
inverse_flattening = 0.0
else:
inverse_flattening = 1.0 / (
(semi_major_axis - semi_minor_axis) / semi_major_axis
)
# We didn't get enough to specify an ellipse.
else:
raise ValueError("Insufficient ellipsoid specification")
#: Major radius of the ellipsoid in metres.
self._semi_major_axis = float(semi_major_axis)
#: Minor radius of the ellipsoid in metres.
self._semi_minor_axis = float(semi_minor_axis)
#: :math:`1/f` where :math:`f = (a-b)/a`.
self._inverse_flattening = float(inverse_flattening)
self._datum = None
#: Describes 'zero' on the ellipsoid in degrees.
self.longitude_of_prime_meridian = _arg_default(longitude_of_prime_meridian, 0)
def _pretty_attrs(self):
attrs = [("semi_major_axis", self.semi_major_axis)]
if self.semi_major_axis != self.semi_minor_axis:
attrs.append(("semi_minor_axis", self.semi_minor_axis))
if self.longitude_of_prime_meridian != 0.0:
attrs.append(
(
"longitude_of_prime_meridian",
self.longitude_of_prime_meridian,
)
)
# An unknown crs datum will be treated as None
if self.datum is not None and self.datum != "unknown":
attrs.append(
(
"datum",
self.datum,
)
)
return attrs
def __repr__(self):
attrs = self._pretty_attrs()
# Special case for 1 pretty attr
if len(attrs) == 1 and attrs[0][0] == "semi_major_axis":
return "GeogCS(%r)" % self.semi_major_axis
else:
return "GeogCS(%s)" % ", ".join(["%s=%r" % (k, v) for k, v in attrs])
def __str__(self):
attrs = self._pretty_attrs()
# Special case for 1 pretty attr
if len(attrs) == 1 and attrs[0][0] == "semi_major_axis":
return "GeogCS({:.16})".format(self.semi_major_axis)
else:
text_attrs = []
for k, v in attrs:
if isinstance(v, float):
text_attrs.append("{}={:.16}".format(k, v))
elif isinstance(v, np.float32):
text_attrs.append("{}={:.8}".format(k, v))
else:
text_attrs.append("{}={}".format(k, v))
return "GeogCS({})".format(", ".join(text_attrs))
def xml_element(self, doc):
# Special output for spheres
attrs = self._pretty_attrs()
if len(attrs) == 1 and attrs[0][0] == "semi_major_axis":
attrs = [("earth_radius", self.semi_major_axis)]
return CoordSystem.xml_element(self, doc, attrs)
def as_cartopy_crs(self):
return self._crs
def as_cartopy_projection(self):
return ccrs.PlateCarree(
central_longitude=self.longitude_of_prime_meridian,
globe=self.as_cartopy_globe(),
)
def as_cartopy_globe(self):
return self._globe
@cached_property
def _globe(self):
"""A representation of this CRS as a Cartopy Globe.
Note
----
This property is created when required and then cached for speed. That
cached value is cleared when an assignment is made to a property of the
class that invalidates the cache.
"""
if self._datum is not None:
short_datum = _short_datum_names.get(self._datum, self._datum)
# Cartopy doesn't actually enact datums unless they're provided without
# ellipsoid axes, so only provide the datum
return ccrs.Globe(short_datum, ellipse=None)
else:
return ccrs.Globe(
ellipse=None,
semimajor_axis=self._semi_major_axis,
semiminor_axis=self._semi_minor_axis,
)
@cached_property
def _crs(self):
"""A representation of this CRS as a Cartopy CRS.
Note
----
This property is created when required and then cached for speed. That
cached value is cleared when an assignment is made to a property of the
class that invalidates the cache.
"""
return ccrs.Geodetic(self._globe)
def _wipe_cached_properties(self):
"""Wipes the cached properties on the object.
Wipes the cached properties on the object as part of any update to a
value that invalidates the cache.
"""
try:
delattr(self, "_crs")
except AttributeError:
pass
try:
delattr(self, "_globe")
except AttributeError:
pass
@property
def semi_major_axis(self):
if self._semi_major_axis is not None:
return self._semi_major_axis
else:
return self._crs.ellipsoid.semi_major_metre
@semi_major_axis.setter
def semi_major_axis(self, value):
"""Assign semi_major_axis.
Setting this property to a different value invalidates the current datum
(if any) because a datum encodes a specific semi-major axis. This also
invalidates the cached `cartopy.Globe` and `cartopy.CRS`.
"""
value = float(value)
if not np.isclose(self.semi_major_axis, value):
self._datum = None
self._wipe_cached_properties()
self._semi_major_axis = value
@property
def semi_minor_axis(self):
if self._semi_minor_axis is not None:
return self._semi_minor_axis
else:
return self._crs.ellipsoid.semi_minor_metre
@semi_minor_axis.setter
def semi_minor_axis(self, value):
"""Assign semi_minor_axis.
Setting this property to a different value invalidates the current datum
(if any) because a datum encodes a specific semi-minor axis. This also
invalidates the cached `cartopy.Globe` and `cartopy.CRS`.
"""
value = float(value)
if not np.isclose(self.semi_minor_axis, value):
self._datum = None
self._wipe_cached_properties()
self._semi_minor_axis = value
@property
def inverse_flattening(self):
if self._inverse_flattening is not None:
return self._inverse_flattening
else:
self._crs.ellipsoid.inverse_flattening
@inverse_flattening.setter
def inverse_flattening(self, value):
"""Assign inverse_flattening.
Setting this property to a different value does not affect the behaviour
of this object any further than the value of this property.
"""
wmsg = (
"Setting inverse_flattening does not affect other properties of "
"the GeogCS object. To change other properties set them explicitly"
" or create a new GeogCS instance."
)
warnings.warn(wmsg, category=iris.warnings.IrisUserWarning)
value = float(value)
self._inverse_flattening = value
@property
def datum(self):
if self._datum is None:
return None
else:
datum = self._datum
return datum
@datum.setter
def datum(self, value):
"""Assign datum.
Setting this property to a different value invalidates the current
values of the ellipsoid measurements because a datum encodes its own
ellipse. This also invalidates the cached `cartopy.Globe` and
`cartopy.CRS`.
"""
if self._datum != value:
self._semi_major_axis = None
self._semi_minor_axis = None
self._inverse_flattening = None
self._wipe_cached_properties()
self._datum = value
@classmethod
def from_datum(cls, datum, longitude_of_prime_meridian=None):
crs = super().__new__(cls)
crs._semi_major_axis = None
crs._semi_minor_axis = None
crs._inverse_flattening = None
#: Describes 'zero' on the ellipsoid in degrees.
crs.longitude_of_prime_meridian = _arg_default(longitude_of_prime_meridian, 0)
crs._datum = datum
return crs
class RotatedGeogCS(CoordSystem):
"""A coordinate system with rotated pole, on an optional :class:`GeogCS`."""
grid_mapping_name = "rotated_latitude_longitude"
def __init__(
self,
grid_north_pole_latitude,
grid_north_pole_longitude,
north_pole_grid_longitude=None,
ellipsoid=None,
):
"""Construct a coordinate system with rotated pole, on an optional :class:`GeogCS`.
Parameters
----------
grid_north_pole_latitude :
The true latitude of the rotated pole in degrees.
grid_north_pole_longitude :
The true longitude of the rotated pole in degrees.
north_pole_grid_longitude : optional
Longitude of true north pole in rotated grid, in degrees.
Defaults to 0.0.
ellipsoid : :class:`GeogCS`, optional
If given, defines the ellipsoid.
Examples
--------
::
rotated_cs = RotatedGeogCS(30, 30)
another_cs = RotatedGeogCS(30, 30,
ellipsoid=GeogCS(6400000, 6300000))
"""
#: The true latitude of the rotated pole in degrees.
self.grid_north_pole_latitude = float(grid_north_pole_latitude)
#: The true longitude of the rotated pole in degrees.
self.grid_north_pole_longitude = float(grid_north_pole_longitude)
#: Longitude of true north pole in rotated grid in degrees.
self.north_pole_grid_longitude = _arg_default(north_pole_grid_longitude, 0)
#: Ellipsoid definition (:class:`GeogCS` or None).
self.ellipsoid = ellipsoid
def _pretty_attrs(self):
attrs = [
("grid_north_pole_latitude", self.grid_north_pole_latitude),
("grid_north_pole_longitude", self.grid_north_pole_longitude),
]
if self.north_pole_grid_longitude != 0.0:
attrs.append(("north_pole_grid_longitude", self.north_pole_grid_longitude))
if self.ellipsoid is not None:
attrs.append(("ellipsoid", self.ellipsoid))
return attrs
def __repr__(self):
attrs = self._pretty_attrs()
result = "RotatedGeogCS(%s)" % ", ".join(["%s=%r" % (k, v) for k, v in attrs])
# Extra prettiness
result = result.replace("grid_north_pole_latitude=", "")
result = result.replace("grid_north_pole_longitude=", "")
return result
def __str__(self):
attrs = self._pretty_attrs()
text_attrs = []
for k, v in attrs:
if isinstance(v, float):
text_attrs.append("{}={:.16}".format(k, v))
elif isinstance(v, np.float32):
text_attrs.append("{}={:.8}".format(k, v))
else:
text_attrs.append("{}={}".format(k, v))
result = "RotatedGeogCS({})".format(", ".join(text_attrs))
# Extra prettiness
result = result.replace("grid_north_pole_latitude=", "")
result = result.replace("grid_north_pole_longitude=", "")
return result
def xml_element(self, doc):
return CoordSystem.xml_element(self, doc, self._pretty_attrs())
def _ccrs_kwargs(self):
globe = self._ellipsoid_to_globe(self.ellipsoid, None)
cartopy_kwargs = {
"central_rotated_longitude": self.north_pole_grid_longitude,
"pole_longitude": self.grid_north_pole_longitude,
"pole_latitude": self.grid_north_pole_latitude,
"globe": globe,
}
return cartopy_kwargs
def as_cartopy_crs(self):
return ccrs.RotatedGeodetic(**self._ccrs_kwargs())
def as_cartopy_projection(self):
return ccrs.RotatedPole(**self._ccrs_kwargs())
class TransverseMercator(CoordSystem):
"""A cylindrical map projection, with XY coordinates measured in metres."""
grid_mapping_name = "transverse_mercator"
def __init__(
self,
latitude_of_projection_origin,
longitude_of_central_meridian,
false_easting=None,
false_northing=None,
scale_factor_at_central_meridian=None,
ellipsoid=None,
):
"""Construct a TransverseMercator object.
Parameters
----------
latitude_of_projection_origin :
True latitude of planar origin in degrees.
longitude_of_central_meridian :
True longitude of planar origin in degrees.
false_easting : optional
X offset from planar origin in metres.
Defaults to 0.0.
false_northing : optional
Y offset from planar origin in metres.
Defaults to 0.0.
scale_factor_at_central_meridian : optional
Reduces the cylinder to slice through the ellipsoid
(secant form). Used to provide TWO longitudes of zero
distortion in the area of interest.
Defaults to 1.0 .
ellipsoid : :class:`GeogCS`, optional
If given, defines the ellipsoid.
Examples
--------
::
airy1830 = GeogCS(6377563.396, 6356256.909)
osgb = TransverseMercator(49, -2, 400000, -100000, 0.9996012717,
ellipsoid=airy1830)
"""
#: True latitude of planar origin in degrees.
self.latitude_of_projection_origin = float(latitude_of_projection_origin)
#: True longitude of planar origin in degrees.
self.longitude_of_central_meridian = float(longitude_of_central_meridian)
#: X offset from planar origin in metres.
self.false_easting = _arg_default(false_easting, 0)
#: Y offset from planar origin in metres.
self.false_northing = _arg_default(false_northing, 0)
#: Scale factor at the centre longitude.
self.scale_factor_at_central_meridian = _arg_default(
scale_factor_at_central_meridian, 1.0
)
#: Ellipsoid definition (:class:`GeogCS` or None).
self.ellipsoid = ellipsoid
def __repr__(self):
return (
"TransverseMercator(latitude_of_projection_origin={!r}, "
"longitude_of_central_meridian={!r}, false_easting={!r}, "
"false_northing={!r}, scale_factor_at_central_meridian={!r}, "
"ellipsoid={!r})".format(
self.latitude_of_projection_origin,
self.longitude_of_central_meridian,
self.false_easting,
self.false_northing,
self.scale_factor_at_central_meridian,
self.ellipsoid,
)
)
def as_cartopy_crs(self):
globe = self._ellipsoid_to_globe(self.ellipsoid, None)
return ccrs.TransverseMercator(
central_longitude=self.longitude_of_central_meridian,
central_latitude=self.latitude_of_projection_origin,
false_easting=self.false_easting,
false_northing=self.false_northing,
scale_factor=self.scale_factor_at_central_meridian,
globe=globe,
)
def as_cartopy_projection(self):
return self.as_cartopy_crs()
class OSGB(TransverseMercator):
"""A Specific transverse mercator projection on a specific ellipsoid."""
def __init__(self):
TransverseMercator.__init__(
self,
49,
-2,
400000,
-100000,
0.9996012717,
GeogCS(6377563.396, 6356256.909),
)
def as_cartopy_crs(self):
return ccrs.OSGB()
def as_cartopy_projection(self):
return ccrs.OSGB()
class Orthographic(CoordSystem):
"""An orthographic map projection."""
grid_mapping_name = "orthographic"
def __init__(
self,
latitude_of_projection_origin,
longitude_of_projection_origin,
false_easting=None,
false_northing=None,
ellipsoid=None,
):
"""Construct an Orthographic coord system.
Parameters
----------
latitude_of_projection_origin :
True latitude of planar origin in degrees.
longitude_of_projection_origin :
True longitude of planar origin in degrees.
false_easting : optional
X offset from planar origin in metres. Defaults to 0.0.
false_northing : optional
Y offset from planar origin in metres. Defaults to 0.0.
ellipsoid : :class:`GeogCS`, optional
If given, defines the ellipsoid.
"""
#: True latitude of planar origin in degrees.
self.latitude_of_projection_origin = float(latitude_of_projection_origin)
#: True longitude of planar origin in degrees.
self.longitude_of_projection_origin = float(longitude_of_projection_origin)
#: X offset from planar origin in metres.
self.false_easting = _arg_default(false_easting, 0)
#: Y offset from planar origin in metres.
self.false_northing = _arg_default(false_northing, 0)
#: Ellipsoid definition (:class:`GeogCS` or None).
self.ellipsoid = ellipsoid
def __repr__(self):
return (
"Orthographic(latitude_of_projection_origin={!r}, "
"longitude_of_projection_origin={!r}, "
"false_easting={!r}, false_northing={!r}, "
"ellipsoid={!r})".format(
self.latitude_of_projection_origin,
self.longitude_of_projection_origin,
self.false_easting,
self.false_northing,
self.ellipsoid,
)
)
def as_cartopy_crs(self):
globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe())
warnings.warn(
"Discarding false_easting and false_northing that are "
"not used by Cartopy.",
category=iris.warnings.IrisDefaultingWarning,
)
return ccrs.Orthographic(
central_longitude=self.longitude_of_projection_origin,
central_latitude=self.latitude_of_projection_origin,
globe=globe,
)
def as_cartopy_projection(self):
return self.as_cartopy_crs()
class VerticalPerspective(CoordSystem):
"""A vertical/near-side perspective satellite image map projection."""
grid_mapping_name = "vertical_perspective"
def __init__(
self,
latitude_of_projection_origin,
longitude_of_projection_origin,
perspective_point_height,
false_easting=None,
false_northing=None,
ellipsoid=None,
):
"""Construct a Vertical Perspective coord system.
Parameters
----------
latitude_of_projection_origin :
True latitude of planar origin in degrees.
longitude_of_projection_origin :
True longitude of planar origin in degrees.
perspective_point_height :
Altitude of satellite in metres above the surface of the
ellipsoid.
false_easting : optional
X offset from planar origin in metres. Defaults to 0.0.
false_northing : optional
Y offset from planar origin in metres. Defaults to 0.0.
ellipsoid : :class:`GeogCS`, optional
If given, defines the ellipsoid.
"""
#: True latitude of planar origin in degrees.
self.latitude_of_projection_origin = float(latitude_of_projection_origin)
#: True longitude of planar origin in degrees.
self.longitude_of_projection_origin = float(longitude_of_projection_origin)
#: Altitude of satellite in metres.
self.perspective_point_height = float(perspective_point_height)
# TODO: test if may be cast to float for proj.4
#: X offset from planar origin in metres.
self.false_easting = _arg_default(false_easting, 0)
#: Y offset from planar origin in metres.
self.false_northing = _arg_default(false_northing, 0)
#: Ellipsoid definition (:class:`GeogCS` or None).
self.ellipsoid = ellipsoid
def __repr__(self):
return (
"Vertical Perspective(latitude_of_projection_origin={!r}, "
"longitude_of_projection_origin={!r}, "
"perspective_point_height={!r}, "
"false_easting={!r}, false_northing={!r}, "
"ellipsoid={!r})".format(
self.latitude_of_projection_origin,
self.longitude_of_projection_origin,
self.perspective_point_height,
self.false_easting,
self.false_northing,
self.ellipsoid,
)
)
def as_cartopy_crs(self):
globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe())
return ccrs.NearsidePerspective(
central_latitude=self.latitude_of_projection_origin,
central_longitude=self.longitude_of_projection_origin,
satellite_height=self.perspective_point_height,
false_easting=self.false_easting,
false_northing=self.false_northing,
globe=globe,
)
def as_cartopy_projection(self):
return self.as_cartopy_crs()
class Geostationary(CoordSystem):
"""A geostationary satellite image map projection."""
grid_mapping_name = "geostationary"
def __init__(
self,
latitude_of_projection_origin,
longitude_of_projection_origin,
perspective_point_height,
sweep_angle_axis,
false_easting=None,
false_northing=None,
ellipsoid=None,
):
"""Construct a Geostationary coord system.
Parameters
----------
latitude_of_projection_origin :
True latitude of planar origin in degrees.
longitude_of_projection_origin :
True longitude of planar origin in degrees.
perspective_point_height :
Altitude of satellite in metres above the surface of the ellipsoid.
sweep_angle_axis : str
The axis along which the satellite instrument sweeps - 'x' or 'y'.
false_easting : optional
X offset from planar origin in metres. Defaults to 0.0.
false_northing : optional
Y offset from planar origin in metres. Defaults to 0.0.
ellipsoid : :class:`GeogCS`, optional
If given, defines the ellipsoid.
"""
#: True latitude of planar origin in degrees.
self.latitude_of_projection_origin = float(latitude_of_projection_origin)
if self.latitude_of_projection_origin != 0.0:
raise ValueError(
"Non-zero latitude of projection currently not supported by Cartopy."
)
#: True longitude of planar origin in degrees.
self.longitude_of_projection_origin = float(longitude_of_projection_origin)
#: Altitude of satellite in metres.
self.perspective_point_height = float(perspective_point_height)
# TODO: test if may be cast to float for proj.4
#: X offset from planar origin in metres.
self.false_easting = _arg_default(false_easting, 0)
#: Y offset from planar origin in metres.
self.false_northing = _arg_default(false_northing, 0)
#: The sweep angle axis (string 'x' or 'y').
self.sweep_angle_axis = sweep_angle_axis
if self.sweep_angle_axis not in ("x", "y"):
raise ValueError('Invalid sweep_angle_axis - must be "x" or "y"')
#: Ellipsoid definition (:class:`GeogCS` or None).
self.ellipsoid = ellipsoid
def __repr__(self):
return (
"Geostationary(latitude_of_projection_origin={!r}, "
"longitude_of_projection_origin={!r}, "
"perspective_point_height={!r}, false_easting={!r}, "
"false_northing={!r}, sweep_angle_axis={!r}, "
"ellipsoid={!r}".format(
self.latitude_of_projection_origin,
self.longitude_of_projection_origin,
self.perspective_point_height,
self.false_easting,
self.false_northing,
self.sweep_angle_axis,
self.ellipsoid,
)
)
def as_cartopy_crs(self):
globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe())
return ccrs.Geostationary(
central_longitude=self.longitude_of_projection_origin,
satellite_height=self.perspective_point_height,
false_easting=self.false_easting,
false_northing=self.false_northing,
globe=globe,
sweep_axis=self.sweep_angle_axis,
)
def as_cartopy_projection(self):
return self.as_cartopy_crs()
class Stereographic(CoordSystem):
"""A stereographic map projection."""
grid_mapping_name = "stereographic"
def __init__(
self,
central_lat,
central_lon,
false_easting=None,
false_northing=None,
true_scale_lat=None,
ellipsoid=None,
scale_factor_at_projection_origin=None,
):
"""Construct a Stereographic coord system.
Parameters
----------
central_lat : float
The latitude of the pole.
central_lon : float
The central longitude, which aligns with the y axis.
false_easting : float, optional
X offset from planar origin in metres.
false_northing : float, optional
Y offset from planar origin in metres.
true_scale_lat : float, optional
Latitude of true scale.
scale_factor_at_projection_origin : float, optional
Scale factor at the origin of the projection
ellipsoid : :class:`GeogCS`, optional
If given, defines the ellipsoid.
Notes
-----
It is only valid to provide one of true_scale_lat and