/
crs.py
2057 lines (1763 loc) · 61.7 KB
/
crs.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
"""
This module interfaces with PROJ to produce a pythonic interface
to the coordinate reference system (CRS) information.
"""
# pylint: disable=too-many-lines
import json
import re
import threading
import warnings
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from pyproj._crs import (
_CRS,
AreaOfUse,
AuthorityMatchInfo,
Axis,
CoordinateOperation,
CoordinateSystem,
Datum,
Ellipsoid,
PrimeMeridian,
_load_proj_json,
is_proj,
is_wkt,
)
from pyproj.crs._cf1x8 import (
_GEOGRAPHIC_GRID_MAPPING_NAME_MAP,
_GRID_MAPPING_NAME_MAP,
_INVERSE_GEOGRAPHIC_GRID_MAPPING_NAME_MAP,
_INVERSE_GRID_MAPPING_NAME_MAP,
_horizontal_datum_from_params,
_try_list_if_string,
)
from pyproj.crs.coordinate_operation import ToWGS84Transformation
from pyproj.crs.coordinate_system import Cartesian2DCS, Ellipsoidal2DCS, VerticalCS
from pyproj.enums import ProjVersion, WktVersion
from pyproj.exceptions import CRSError
from pyproj.geod import Geod
_RE_PROJ_PARAM = re.compile(
r"""
\+ # parameter starts with '+' character
(?P<param>\w+) # capture parameter name
\=? # match both key only and key-value parameters
(?P<value>\S+)? # capture all characters up to next space (None if no value)
\s*? # consume remaining whitespace, if any
""",
re.X,
)
class CRSLocal(threading.local):
"""
Threading local instance for cython CRS class.
For more details, see:
https://github.com/pyproj4/pyproj/issues/782
"""
def __init__(self):
self.crs = None # Initialises in each thread
super().__init__()
def _prepare_from_dict(projparams: dict, allow_json: bool = True) -> str:
if not isinstance(projparams, dict):
raise CRSError("CRS input is not a dict")
# check if it is a PROJ JSON dict
if "proj" not in projparams and "init" not in projparams and allow_json:
return json.dumps(projparams)
# convert a dict to a proj string.
pjargs = []
for key, value in projparams.items():
# the towgs84 as list
if isinstance(value, (list, tuple)):
value = ",".join([str(val) for val in value])
# issue 183 (+ no_rot)
if value is None or str(value) == "True":
pjargs.append(f"+{key}")
elif str(value) == "False":
pass
else:
pjargs.append(f"+{key}={value}")
return _prepare_from_string(" ".join(pjargs))
def _prepare_from_proj_string(in_crs_string: str) -> str:
in_crs_string = re.sub(r"[\s+]?=[\s+]?", "=", in_crs_string.lstrip())
# make sure the projection starts with +proj or +init
starting_params = ("+init", "+proj", "init", "proj")
if not in_crs_string.startswith(starting_params):
kvpairs: List[str] = []
first_item_inserted = False
for kvpair in in_crs_string.split():
if not first_item_inserted and (kvpair.startswith(starting_params)):
kvpairs.insert(0, kvpair)
first_item_inserted = True
else:
kvpairs.append(kvpair)
in_crs_string = " ".join(kvpairs)
# make sure it is the CRS type
if "type=crs" not in in_crs_string:
if "+" in in_crs_string:
in_crs_string += " +type=crs"
else:
in_crs_string += " type=crs"
# look for EPSG, replace with epsg (EPSG only works
# on case-insensitive filesystems).
in_crs_string = in_crs_string.replace("+init=EPSG", "+init=epsg").strip()
if in_crs_string.startswith(("+init", "init")):
warnings.warn(
"'+init=<authority>:<code>' syntax is deprecated. "
"'<authority>:<code>' is the preferred initialization method. "
"When making the change, be mindful of axis order changes: "
"https://pyproj4.github.io/pyproj/stable/gotchas.html"
"#axis-order-changes-in-proj-6",
FutureWarning,
stacklevel=2,
)
return in_crs_string
def _prepare_from_string(in_crs_string: str) -> str:
if not isinstance(in_crs_string, str):
raise CRSError("CRS input is not a string")
if not in_crs_string:
raise CRSError(f"CRS string is empty or invalid: {in_crs_string!r}")
if "{" in in_crs_string:
# may be json, try to decode it
try:
crs_dict = json.loads(in_crs_string, strict=False)
except ValueError as err:
raise CRSError("CRS appears to be JSON but is not valid") from err
if not crs_dict:
raise CRSError("CRS is empty JSON")
in_crs_string = _prepare_from_dict(crs_dict)
elif is_proj(in_crs_string):
in_crs_string = _prepare_from_proj_string(in_crs_string)
return in_crs_string
def _prepare_from_authority(auth_name: str, auth_code: Union[str, int]):
return f"{auth_name}:{auth_code}"
def _prepare_from_epsg(auth_code: Union[str, int]):
return _prepare_from_authority("epsg", auth_code)
def _is_epsg_code(auth_code: Any) -> bool:
if isinstance(auth_code, int):
return True
if isinstance(auth_code, str) and auth_code.isnumeric():
return True
if hasattr(auth_code, "shape") and auth_code.shape == ():
return True
return False
class CRS:
"""
A pythonic Coordinate Reference System manager.
.. versionadded:: 2.0.0
See: :c:func:`proj_create`
The functionality is based on other fantastic projects:
* `rasterio <https://github.com/mapbox/rasterio/blob/c13f0943b95c0eaa36ff3f620bd91107aa67b381/rasterio/_crs.pyx>`_ # noqa: E501
* `opendatacube <https://github.com/opendatacube/datacube-core/blob/83bae20d2a2469a6417097168fd4ede37fd2abe5/datacube/utils/geometry/_base.py>`_ # noqa: E501
Attributes
----------
srs: str
The string form of the user input used to create the CRS.
"""
def __init__(self, projparams: Any = None, **kwargs) -> None:
"""
Initialize a CRS class instance with:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
- An EPSG integer code [i.e. 4326]
- A tuple of ("auth_name": "auth_code") [i.e ('epsg', '4326')]
- An object with a `to_wkt` method.
- A :class:`pyproj.crs.CRS` class
Example usage:
>>> from pyproj import CRS
>>> crs_utm = CRS.from_user_input(26915)
>>> crs_utm
<Projected CRS: EPSG:26915>
Name: NAD83 / UTM zone 15N
Axis Info [cartesian]:
- E[east]: Easting (metre)
- N[north]: Northing (metre)
Area of Use:
- name: North America - 96°W to 90°W and NAD83 by country
- bounds: (-96.0, 25.61, -90.0, 84.0)
Coordinate Operation:
- name: UTM zone 15N
- method: Transverse Mercator
Datum: North American Datum 1983
- Ellipsoid: GRS 1980
- Prime Meridian: Greenwich
<BLANKLINE>
>>> crs_utm.area_of_use.bounds
(-96.0, 25.61, -90.0, 84.0)
>>> crs_utm.ellipsoid
ELLIPSOID["GRS 1980",6378137,298.257222101,
LENGTHUNIT["metre",1],
ID["EPSG",7019]]
>>> crs_utm.ellipsoid.inverse_flattening
298.257222101
>>> crs_utm.ellipsoid.semi_major_metre
6378137.0
>>> crs_utm.ellipsoid.semi_minor_metre
6356752.314140356
>>> crs_utm.prime_meridian
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]]
>>> crs_utm.prime_meridian.unit_name
'degree'
>>> crs_utm.prime_meridian.unit_conversion_factor
0.017453292519943295
>>> crs_utm.prime_meridian.longitude
0.0
>>> crs_utm.datum
DATUM["North American Datum 1983",
ELLIPSOID["GRS 1980",6378137,298.257222101,
LENGTHUNIT["metre",1]],
ID["EPSG",6269]]
>>> crs_utm.coordinate_system
CS[Cartesian,2],
AXIS["(E)",east,
ORDER[1],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]],
AXIS["(N)",north,
ORDER[2],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]]
>>> print(crs_utm.coordinate_operation.to_wkt(pretty=True))
CONVERSION["UTM zone 15N",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",-93,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",0.9996,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",500000,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",0,
LENGTHUNIT["metre",1],
ID["EPSG",8807]],
ID["EPSG",16015]]
>>> crs = CRS(proj='utm', zone=10, ellps='WGS84')
>>> print(crs.to_wkt(pretty=True))
PROJCRS["unknown",
BASEGEOGCRS["unknown",
DATUM["Unknown based on WGS84 ellipsoid",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1],
ID["EPSG",7030]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]]],
CONVERSION["UTM zone 10N",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",-123,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",0.9996,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",500000,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",0,
LENGTHUNIT["metre",1],
ID["EPSG",8807]],
ID["EPSG",16010]],
CS[Cartesian,2],
AXIS["(E)",east,
ORDER[1],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]],
AXIS["(N)",north,
ORDER[2],
LENGTHUNIT["metre",1,
ID["EPSG",9001]]]]
>>> geod = crs.get_geod()
>>> f"+a={geod.a:.0f} +f={geod.f:.8f}"
'+a=6378137 +f=0.00335281'
>>> crs.is_projected
True
>>> crs.is_geographic
False
"""
projstring = ""
if projparams:
if isinstance(projparams, _CRS):
projstring = projparams.srs
elif _is_epsg_code(projparams):
projstring = _prepare_from_epsg(projparams)
elif isinstance(projparams, str):
projstring = _prepare_from_string(projparams)
elif isinstance(projparams, dict):
projstring = _prepare_from_dict(projparams)
elif isinstance(projparams, (list, tuple)) and len(projparams) == 2:
projstring = _prepare_from_authority(*projparams)
elif hasattr(projparams, "to_wkt"):
projstring = projparams.to_wkt() # type: ignore
else:
raise CRSError(f"Invalid CRS input: {projparams!r}")
if kwargs:
projkwargs = _prepare_from_dict(kwargs, allow_json=False)
projstring = _prepare_from_string(" ".join((projstring, projkwargs)))
self.srs = projstring
self._local = CRSLocal()
if isinstance(projparams, _CRS):
self._local.crs = projparams
else:
self._local.crs = _CRS(self.srs)
@property
def _crs(self):
"""
Retrieve the Cython based _CRS object for this thread.
"""
if self._local.crs is None:
self._local.crs = _CRS(self.srs)
return self._local.crs
@classmethod
def from_authority(cls, auth_name: str, code: Union[str, int]) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from an authority name and authority code
Parameters
----------
auth_name: str
The name of the authority.
code : int or str
The code used by the authority.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_authority(auth_name, code))
@classmethod
def from_epsg(cls, code: Union[str, int]) -> "CRS":
"""Make a CRS from an EPSG code
Parameters
----------
code : int or str
An EPSG code.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_epsg(code))
@classmethod
def from_proj4(cls, in_proj_string: str) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from a PROJ string
Parameters
----------
in_proj_string : str
A PROJ string.
Returns
-------
CRS
"""
if not is_proj(in_proj_string):
raise CRSError(f"Invalid PROJ string: {in_proj_string}")
return cls.from_user_input(_prepare_from_proj_string(in_proj_string))
@classmethod
def from_wkt(cls, in_wkt_string: str) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from a WKT string
Parameters
----------
in_wkt_string : str
A WKT string.
Returns
-------
CRS
"""
if not is_wkt(in_wkt_string):
raise CRSError(f"Invalid WKT string: {in_wkt_string}")
return cls.from_user_input(_prepare_from_string(in_wkt_string))
@classmethod
def from_string(cls, in_crs_string: str) -> "CRS":
"""
Make a CRS from:
Initialize a CRS class instance with:
- PROJ string
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
Parameters
----------
in_crs_string : str
An EPSG, PROJ, or WKT string.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_string(in_crs_string))
def to_string(self) -> str:
"""
.. versionadded:: 2.2.0
Convert the CRS to a string.
It attempts to convert it to the authority string.
Otherwise, it uses the string format of the user
input to create the CRS.
Returns
-------
str
"""
auth_info = self.to_authority(min_confidence=100)
if auth_info:
return ":".join(auth_info)
return self.srs
@classmethod
def from_user_input(cls, value: Any, **kwargs) -> "CRS":
"""
Initialize a CRS class instance with:
- PROJ string
- Dictionary of PROJ parameters
- PROJ keyword arguments for parameters
- JSON string with PROJ parameters
- CRS WKT string
- An authority string [i.e. 'epsg:4326']
- An EPSG integer code [i.e. 4326]
- A tuple of ("auth_name": "auth_code") [i.e ('epsg', '4326')]
- An object with a `to_wkt` method.
- A :class:`pyproj.crs.CRS` class
Parameters
----------
value : obj
A Python int, dict, or str.
Returns
-------
CRS
"""
if isinstance(value, cls):
return value
return cls(value, **kwargs)
def get_geod(self) -> Optional[Geod]:
"""
Returns
-------
pyproj.geod.Geod:
Geod object based on the ellipsoid.
"""
if self.ellipsoid is None:
return None
return Geod(
a=self.ellipsoid.semi_major_metre,
rf=self.ellipsoid.inverse_flattening,
b=self.ellipsoid.semi_minor_metre,
)
@classmethod
def from_dict(cls, proj_dict: dict) -> "CRS":
"""
.. versionadded:: 2.2.0
Make a CRS from a dictionary of PROJ parameters.
Parameters
----------
proj_dict : str
PROJ params in dict format.
Returns
-------
CRS
"""
return cls.from_user_input(_prepare_from_dict(proj_dict))
@classmethod
def from_json(cls, crs_json: str) -> "CRS":
"""
.. versionadded:: 2.4.0
Create CRS from a CRS JSON string.
Parameters
----------
crs_json: str
CRS JSON string.
Returns
-------
CRS
"""
return cls.from_user_input(_load_proj_json(crs_json))
@classmethod
def from_json_dict(cls, crs_dict: dict) -> "CRS":
"""
.. versionadded:: 2.4.0
Create CRS from a JSON dictionary.
Parameters
----------
crs_dict: dict
CRS dictionary.
Returns
-------
CRS
"""
return cls.from_user_input(json.dumps(crs_dict))
def to_dict(self) -> dict:
"""
.. versionadded:: 2.2.0
Converts the CRS to dictionary of PROJ parameters.
.. warning:: You will likely lose important projection
information when converting to a PROJ string from
another format. See: https://proj.org/faq.html#what-is-the-best-format-for-describing-coordinate-reference-systems # noqa: E501
Returns
-------
dict:
PROJ params in dict format.
"""
proj_string = self.to_proj4()
if proj_string is None:
return {}
def _parse(val):
if val.lower() == "true":
return True
if val.lower() == "false":
return False
try:
return int(val)
except ValueError:
pass
try:
return float(val)
except ValueError:
pass
return _try_list_if_string(val)
proj_dict = {}
for param in _RE_PROJ_PARAM.finditer(proj_string):
key, value = param.groups()
if value is not None:
value = _parse(value)
if value is not False:
proj_dict[key] = value
return proj_dict
def to_cf(
self,
wkt_version: Union[WktVersion, str] = WktVersion.WKT2_2019,
errcheck: bool = False,
) -> dict:
"""
.. versionadded:: 2.2.0
This converts a :obj:`pyproj.crs.CRS` object
to a Climate and Forecast (CF) Grid Mapping Version 1.8 dict.
:ref:`build_crs_cf`
Parameters
----------
wkt_version: str or pyproj.enums.WktVersion
Version of WKT supported by CRS.to_wkt.
Default is :attr:`pyproj.enums.WktVersion.WKT2_2019`.
errcheck: bool, default=False
If True, will warn when parameters are ignored.
Returns
-------
dict:
CF-1.8 version of the projection.
"""
# pylint: disable=too-many-branches
cf_dict: Dict[str, Any] = {"crs_wkt": self.to_wkt(wkt_version)}
# handle bound CRS
if (
self.is_bound
and self.coordinate_operation
and self.coordinate_operation.towgs84
and self.source_crs
):
sub_cf: Dict[str, Any] = self.source_crs.to_cf(
wkt_version=wkt_version,
errcheck=errcheck,
)
sub_cf.pop("crs_wkt")
cf_dict.update(sub_cf)
cf_dict["towgs84"] = self.coordinate_operation.towgs84
return cf_dict
# handle compound CRS
if self.is_compound:
for sub_crs in self.sub_crs_list:
sub_cf = sub_crs.to_cf(wkt_version=wkt_version, errcheck=errcheck)
sub_cf.pop("crs_wkt")
cf_dict.update(sub_cf)
return cf_dict
# handle vertical CRS
if self.is_vertical:
vert_json = self.to_json_dict()
if "geoid_model" in vert_json:
cf_dict["geoid_name"] = vert_json["geoid_model"]["name"]
if self.datum:
cf_dict["geopotential_datum_name"] = self.datum.name
return cf_dict
# write out datum parameters
if self.ellipsoid:
cf_dict.update(
semi_major_axis=self.ellipsoid.semi_major_metre,
semi_minor_axis=self.ellipsoid.semi_minor_metre,
inverse_flattening=self.ellipsoid.inverse_flattening,
)
cf_dict["reference_ellipsoid_name"] = self.ellipsoid.name
if self.prime_meridian:
cf_dict["longitude_of_prime_meridian"] = self.prime_meridian.longitude
cf_dict["prime_meridian_name"] = self.prime_meridian.name
# handle geographic CRS
if self.geodetic_crs:
cf_dict["geographic_crs_name"] = self.geodetic_crs.name
if self.is_geographic:
if self.coordinate_operation:
cf_dict.update(
_INVERSE_GEOGRAPHIC_GRID_MAPPING_NAME_MAP[
self.coordinate_operation.method_name.lower()
](self.coordinate_operation)
)
if self.datum:
cf_dict["horizontal_datum_name"] = self.datum.name
else:
cf_dict["grid_mapping_name"] = "latitude_longitude"
return cf_dict
# handle projected CRS
if self.is_projected and self.datum:
cf_dict["horizontal_datum_name"] = self.datum.name
coordinate_operation = None
if not self.is_bound and self.is_projected:
coordinate_operation = self.coordinate_operation
cf_dict["projected_crs_name"] = self.name
coordinate_operation_name = (
None
if not coordinate_operation
else coordinate_operation.method_name.lower().replace(" ", "_")
)
if coordinate_operation_name not in _INVERSE_GRID_MAPPING_NAME_MAP:
if errcheck:
if coordinate_operation:
warnings.warn(
"Unsupported coordinate operation: "
f"{coordinate_operation.method_name}"
)
else:
warnings.warn("Coordinate operation not found.")
return {"crs_wkt": self.to_wkt(wkt_version)}
cf_dict.update(
_INVERSE_GRID_MAPPING_NAME_MAP[coordinate_operation_name](
coordinate_operation
)
)
return cf_dict
@staticmethod
def from_cf(
in_cf: dict,
ellipsoidal_cs: Any = None,
cartesian_cs: Any = None,
vertical_cs: Any = None,
) -> "CRS":
"""
.. versionadded:: 2.2.0
.. versionadded:: 3.0.0 ellipsoidal_cs, cartesian_cs, vertical_cs
This converts a Climate and Forecast (CF) Grid Mapping Version 1.8
dict to a :obj:`pyproj.crs.CRS` object.
:ref:`build_crs_cf`
Parameters
----------
in_cf: dict
CF version of the projection.
ellipsoidal_cs: Any, optional
Input to create an Ellipsoidal Coordinate System.
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or an Ellipsoidal Coordinate System created from :ref:`coordinate_system`.
cartesian_cs: Any, optional
Input to create a Cartesian Coordinate System.
Anything accepted by :meth:`pyproj.crs.CoordinateSystem.from_user_input`
or :class:`pyproj.crs.coordinate_system.Cartesian2DCS`.
vertical_cs: Any, optional
Input to create a Vertical Coordinate System accepted by
:meth:`pyproj.crs.CoordinateSystem.from_user_input`
or :class:`pyproj.crs.coordinate_system.VerticalCS`
Returns
-------
CRS
"""
# pylint: disable=too-many-branches
unknown_names = ("unknown", "undefined")
if "crs_wkt" in in_cf:
return CRS(in_cf["crs_wkt"])
if "spatial_ref" in in_cf: # for previous supported WKT key
return CRS(in_cf["spatial_ref"])
grid_mapping_name = in_cf.get("grid_mapping_name")
if grid_mapping_name is None:
raise CRSError("CF projection parameters missing 'grid_mapping_name'")
# build datum if possible
datum = _horizontal_datum_from_params(in_cf)
# build geographic CRS
try:
geographic_conversion_method: Optional[
Callable
] = _GEOGRAPHIC_GRID_MAPPING_NAME_MAP[grid_mapping_name]
except KeyError:
geographic_conversion_method = None
geographic_crs_name = in_cf.get("geographic_crs_name")
if datum:
geographic_crs: CRS = GeographicCRS(
name=geographic_crs_name or "undefined",
datum=datum,
ellipsoidal_cs=ellipsoidal_cs,
)
elif geographic_crs_name and geographic_crs_name not in unknown_names:
geographic_crs = CRS(geographic_crs_name)
if ellipsoidal_cs is not None:
geographic_crs_json = geographic_crs.to_json_dict()
geographic_crs_json[
"coordinate_system"
] = CoordinateSystem.from_user_input(ellipsoidal_cs).to_json_dict()
geographic_crs = CRS(geographic_crs_json)
else:
geographic_crs = GeographicCRS(ellipsoidal_cs=ellipsoidal_cs)
if grid_mapping_name == "latitude_longitude":
return geographic_crs
if geographic_conversion_method is not None:
return DerivedGeographicCRS(
base_crs=geographic_crs,
conversion=geographic_conversion_method(in_cf),
ellipsoidal_cs=ellipsoidal_cs,
)
# build projected CRS
try:
conversion_method = _GRID_MAPPING_NAME_MAP[grid_mapping_name]
except KeyError:
raise CRSError(
f"Unsupported grid mapping name: {grid_mapping_name}"
) from None
projected_crs = ProjectedCRS(
name=in_cf.get("projected_crs_name", "undefined"),
conversion=conversion_method(in_cf),
geodetic_crs=geographic_crs,
cartesian_cs=cartesian_cs,
)
# build bound CRS if exists
bound_crs = None
if "towgs84" in in_cf:
bound_crs = BoundCRS(
source_crs=projected_crs,
target_crs="WGS 84",
transformation=ToWGS84Transformation(
projected_crs.geodetic_crs, *_try_list_if_string(in_cf["towgs84"])
),
)
if "geopotential_datum_name" not in in_cf:
return bound_crs or projected_crs
# build Vertical CRS
vertical_crs = VerticalCRS(
name="undefined",
datum=in_cf["geopotential_datum_name"],
geoid_model=in_cf.get("geoid_name"),
vertical_cs=vertical_cs,
)
# build compound CRS
return CompoundCRS(
name="undefined", components=[bound_crs or projected_crs, vertical_crs]
)
def cs_to_cf(self) -> List[dict]:
"""
.. versionadded:: 3.0.0
This converts all coordinate systems (cs) in the CRS
to a list of Climate and Forecast (CF) Version 1.8 dicts.
:ref:`build_crs_cf`
Returns
-------
List[dict]:
CF-1.8 version of the coordinate systems.
"""
cf_axis_list = []
def rotated_pole(crs):
try:
return (
crs.coordinate_operation
and crs.coordinate_operation.method_name.lower()
in _INVERSE_GEOGRAPHIC_GRID_MAPPING_NAME_MAP
)
except KeyError:
return False
if self.type_name == "Temporal CRS" and self.datum:
datum_json = self.datum.to_json_dict()
origin = datum_json.get("time_origin", "1875-05-20").strip().rstrip("zZ")
if len(origin) == 4:
origin = f"{origin}-01-01"
axis = self.axis_info[0]
cf_temporal_axis = {
"standard_name": "time",
"long_name": "time",
"calendar": (
datum_json.get("calendar", "proleptic_gregorian")
.lower()
.replace(" ", "_")
),
"axis": "T",
}
unit_name = axis.unit_name.lower().replace("calendar", "").strip()
# no units for TemporalDateTime
if unit_name:
cf_temporal_axis["units"] = f"{unit_name} since {origin}"
cf_axis_list.append(cf_temporal_axis)
if self.coordinate_system:
cf_axis_list.extend(
self.coordinate_system.to_cf(rotated_pole=rotated_pole(self))
)
elif self.is_bound and self.source_crs and self.source_crs.coordinate_system:
cf_axis_list.extend(
self.source_crs.coordinate_system.to_cf(
rotated_pole=rotated_pole(self.source_crs)
)
)
else:
for sub_crs in self.sub_crs_list:
cf_axis_list.extend(sub_crs.cs_to_cf())
return cf_axis_list
def is_exact_same(self, other: Any) -> bool:
"""
Check if the CRS objects are the exact same.
Parameters
----------
other: Any
Check if the other CRS is the exact same to this object.
If the other object is not a CRS, it will try to create one.
On Failure, it will return False.
Returns
-------
bool
"""
try:
other = CRS.from_user_input(other)
except CRSError:
return False
return self._crs.is_exact_same(other._crs)
def equals(self, other: Any, ignore_axis_order: bool = False) -> bool:
"""
.. versionadded:: 2.5.0
Check if the CRS objects are equivalent.
Parameters
----------
other: Any
Check if the other object is equivalent to this object.
If the other object is not a CRS, it will try to create one.
On Failure, it will return False.
ignore_axis_order: bool, default=False
If True, it will compare the CRS class and ignore the axis order.
Returns
-------
bool
"""
try:
other = CRS.from_user_input(other)
except CRSError:
return False
return self._crs.equals(other._crs, ignore_axis_order=ignore_axis_order)
@property
def geodetic_crs(self) -> Optional["CRS"]:
"""
.. versionadded:: 2.2.0
Returns
-------
CRS:
The geodeticCRS / geographicCRS from the CRS.
"""
return (
None
if self._crs.geodetic_crs is None
else self.__class__(self._crs.geodetic_crs)
)
@property
def source_crs(self) -> Optional["CRS"]:
"""
The base CRS of a BoundCRS or a DerivedCRS/ProjectedCRS,
or the source CRS of a CoordinateOperation.
Returns