-
Notifications
You must be signed in to change notification settings - Fork 213
/
_crs.pyx
3123 lines (2723 loc) · 87.9 KB
/
_crs.pyx
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
import json
import re
import warnings
from collections import OrderedDict, namedtuple
from pyproj._compat cimport cstrdecode, cstrencode
from pyproj._datadir cimport pyproj_context_create, pyproj_context_destroy
from pyproj.aoi import AreaOfUse
from pyproj.crs.datum import CustomEllipsoid
from pyproj.crs.enums import CoordinateOperationType, DatumType
from pyproj.enums import ProjVersion, WktVersion
from pyproj.exceptions import CRSError
from pyproj.geod import pj_ellps
from pyproj.utils import NumpyEncoder
# This is for looking up the ellipsoid parameters
# based on the long name
cdef dict _PJ_ELLPS_NAME_MAP = {
ellps["description"]: ellps_id for ellps_id, ellps in pj_ellps.items()
}
cdef str decode_or_undefined(const char* instring):
pystr = cstrdecode(instring)
if pystr is None:
return "undefined"
return pystr
def is_wkt(str proj_string not None):
"""
.. versionadded:: 2.0.0
Check if the input projection string is in the Well-Known Text format.
Parameters
----------
proj_string: str
The projection string.
Returns
-------
bool: True if the string is in the Well-Known Text format
"""
cdef bytes b_proj_string = cstrencode(proj_string)
return proj_context_guess_wkt_dialect(NULL, b_proj_string) != PJ_GUESSED_NOT_WKT
def is_proj(str proj_string not None):
"""
.. versionadded:: 2.2.2
Check if the input projection string is in the PROJ format.
Parameters
----------
proj_string: str
The projection string.
Returns
-------
bool: True if the string is in the PROJ format
"""
return not is_wkt(proj_string) and "=" in proj_string
cdef _to_wkt(
PJ_CONTEXT* context,
PJ* projobj,
object version,
bint pretty,
):
"""
Convert a PJ object to a wkt string.
Parameters
----------
context: PJ_CONTEXT*
projobj: PJ*
wkt_out_type: PJ_WKT_TYPE
pretty: bool
Return
------
str or None
"""
# get the output WKT format
supported_wkt_types = {
WktVersion.WKT2_2015: PJ_WKT2_2015,
WktVersion.WKT2_2015_SIMPLIFIED: PJ_WKT2_2015_SIMPLIFIED,
WktVersion.WKT2_2018: PJ_WKT2_2019,
WktVersion.WKT2_2018_SIMPLIFIED: PJ_WKT2_2019_SIMPLIFIED,
WktVersion.WKT2_2019: PJ_WKT2_2019,
WktVersion.WKT2_2019_SIMPLIFIED: PJ_WKT2_2019_SIMPLIFIED,
WktVersion.WKT1_GDAL: PJ_WKT1_GDAL,
WktVersion.WKT1_ESRI: PJ_WKT1_ESRI
}
cdef PJ_WKT_TYPE wkt_out_type
wkt_out_type = supported_wkt_types[WktVersion.create(version)]
cdef const char* options_wkt[2]
cdef bytes multiline = b"MULTILINE=NO"
if pretty:
multiline = b"MULTILINE=YES"
options_wkt[0] = multiline
options_wkt[1] = NULL
cdef const char* proj_string
proj_string = proj_as_wkt(
context,
projobj,
wkt_out_type,
options_wkt,
)
CRSError.clear()
return cstrdecode(proj_string)
cdef _to_proj4(
PJ_CONTEXT* context,
PJ* projobj,
object version,
bint pretty,
):
"""
Convert the projection to a PROJ string.
Parameters
----------
context: PJ_CONTEXT*
projobj: PJ*
version: pyproj.enums.ProjVersion
The version of the PROJ string output.
pretty: bool
Returns
-------
str: The PROJ string.
"""
# get the output PROJ string format
supported_prj_types = {
ProjVersion.PROJ_4: PJ_PROJ_4,
ProjVersion.PROJ_5: PJ_PROJ_5,
}
cdef PJ_PROJ_STRING_TYPE proj_out_type
proj_out_type = supported_prj_types[ProjVersion.create(version)]
cdef const char* options[2]
cdef bytes multiline = b"MULTILINE=NO"
if pretty:
multiline = b"MULTILINE=YES"
options[0] = multiline
options[1] = NULL
# convert projection to string
cdef const char* proj_string
proj_string = proj_as_proj_string(
context,
projobj,
proj_out_type,
options,
)
CRSError.clear()
return cstrdecode(proj_string)
cdef tuple _get_concatenated_operations(
PJ_CONTEXT* context, PJ* concatenated_operation
):
"""
For a PJ* of type concatenated operation, get the operations
"""
cdef int step_count = proj_concatoperation_get_step_count(
context,
concatenated_operation,
)
cdef PJ* operation = NULL
cdef PJ_CONTEXT* sub_context = NULL
cdef int iii = 0
operations = []
for iii in range(step_count):
sub_context = pyproj_context_create()
operation = proj_concatoperation_get_step(
sub_context,
concatenated_operation,
iii,
)
operations.append(CoordinateOperation.create(sub_context, operation))
CRSError.clear()
return tuple(operations)
cdef PJ * _from_name(
PJ_CONTEXT* context,
str name_string,
str auth_name,
PJ_TYPE pj_type,
):
"""
Create an object from a name.
Parameters
----------
context: PJ_CONTEXT*
The context to use to create the object.
name_string: str
Name of object to create.
auth_name: str
The authority name to refine search.
If None, will search all authorities.
pj_type: PJ_TYPE
The type of PJ * to create.
Returns
-------
PJ *
"""
cdef PJ_TYPE[1] pj_types = [pj_type]
cdef char* c_auth_name = NULL
cdef bytes b_auth_name
if auth_name is not None:
b_auth_name = cstrencode(auth_name)
c_auth_name = b_auth_name
cdef PJ_OBJ_LIST *pj_list = proj_create_from_name(
context,
c_auth_name,
cstrencode(name_string),
<PJ_TYPE*>&pj_types,
1,
False,
1,
NULL,
)
if pj_list == NULL or proj_list_get_count(pj_list) <= 0:
proj_list_destroy(pj_list)
return NULL
cdef PJ* datum_pj = proj_list_get(context, pj_list, 0)
proj_list_destroy(pj_list)
return datum_pj
def _load_proj_json(str in_proj_json):
try:
return json.loads(in_proj_json)
except ValueError:
raise CRSError("Invalid JSON")
cdef class Axis:
"""
.. versionadded:: 2.0.0
Coordinate System Axis
Attributes
----------
name: str
abbrev: str
direction: str
unit_conversion_factor: float
unit_name: str
unit_auth_code: str
unit_code: str
"""
def __cinit__(self):
self.name = "undefined"
self.abbrev = "undefined"
self.direction = "undefined"
self.unit_conversion_factor = float("NaN")
self.unit_name = "undefined"
self.unit_auth_code = "undefined"
self.unit_code = "undefined"
def __str__(self):
return f"{self.abbrev}[{self.direction}]: {self.name} ({self.unit_name})"
def __repr__(self):
return (
f"Axis(name={self.name}, abbrev={self.abbrev}, "
f"direction={self.direction}, unit_auth_code={self.unit_auth_code}, "
f"unit_code={self.unit_code}, unit_name={self.unit_name})"
)
@staticmethod
cdef Axis create(PJ_CONTEXT* context, PJ* projobj, int index):
cdef Axis axis_info = Axis()
cdef const char * name = NULL
cdef const char * abbrev = NULL
cdef const char * direction = NULL
cdef const char * unit_name = NULL
cdef const char * unit_auth_code = NULL
cdef const char * unit_code = NULL
if not proj_cs_get_axis_info(
context,
projobj,
index,
&name,
&abbrev,
&direction,
&axis_info.unit_conversion_factor,
&unit_name,
&unit_auth_code,
&unit_code):
return None
axis_info.name = decode_or_undefined(name)
axis_info.abbrev = decode_or_undefined(abbrev)
axis_info.direction = decode_or_undefined(direction)
axis_info.unit_name = decode_or_undefined(unit_name)
axis_info.unit_auth_code = decode_or_undefined(unit_auth_code)
axis_info.unit_code = decode_or_undefined(unit_code)
return axis_info
cdef create_area_of_use(PJ_CONTEXT* context, PJ* projobj):
cdef double west = float("nan")
cdef double south = float("nan")
cdef double east = float("nan")
cdef double north = float("nan")
cdef const char * area_name = NULL
if not proj_get_area_of_use(
context,
projobj,
&west,
&south,
&east,
&north,
&area_name):
return None
return AreaOfUse(
west=west,
south=south,
east=east,
north=north,
name=decode_or_undefined(area_name),
)
cdef class Base:
def __cinit__(self):
self.projobj = NULL
self.context = NULL
self.name = "undefined"
self._scope = None
self._remarks = None
def __dealloc__(self):
"""destroy projection definition"""
if self.projobj != NULL:
proj_destroy(self.projobj)
if self.context != NULL:
pyproj_context_destroy(self.context)
cdef _set_base_info(self):
"""
Set the name of the PJ
"""
# get proj information
cdef const char* proj_name = proj_get_name(self.projobj)
self.name = decode_or_undefined(proj_name)
cdef const char* scope = proj_get_scope(self.projobj)
if scope != NULL and scope != "":
self._scope = scope
cdef const char* remarks = proj_get_remarks(self.projobj)
if remarks != NULL and remarks != "":
self._remarks = remarks
@property
def remarks(self):
"""
.. versionadded:: 2.4.0
Returns
-------
str:
Remarks about object.
"""
return self._remarks
@property
def scope(self):
"""
.. versionadded:: 2.4.0
Returns
-------
str:
Scope of object.
"""
return self._scope
def to_wkt(self, version=WktVersion.WKT2_2019, pretty=False):
"""
Convert the projection to a WKT string.
Version options:
- WKT2_2015
- WKT2_2015_SIMPLIFIED
- WKT2_2019
- WKT2_2019_SIMPLIFIED
- WKT1_GDAL
- WKT1_ESRI
Parameters
----------
version: pyproj.enums.WktVersion, default=pyproj.enums.WktVersion.WKT2_2019
The version of the WKT output.
pretty: bool, default=False
If True, it will set the output to be a multiline string.
Returns
-------
str
"""
return _to_wkt(self.context, self.projobj, version, pretty=pretty)
def to_json(self, bint pretty=False, int indentation=2):
"""
.. versionadded:: 2.4.0
Convert the object to a JSON string.
Parameters
----------
pretty: bool, default=False
If True, it will set the output to be a multiline string.
indentation: int, default=2
If pretty is True, it will set the width of the indentation.
Returns
-------
str
"""
cdef const char* options[3]
multiline = b"MULTILINE=NO"
if pretty:
multiline = b"MULTILINE=YES"
indentation_width = cstrencode(f"INDENTATION_WIDTH={indentation:.0f}")
options[0] = multiline
options[1] = indentation_width
options[2] = NULL
cdef const char* proj_json_string = proj_as_projjson(
self.context,
self.projobj,
options,
)
return cstrdecode(proj_json_string)
def to_json_dict(self):
"""
.. versionadded:: 2.4.0
Convert the object to a JSON dictionary.
Returns
-------
dict
"""
return json.loads(self.to_json())
def __str__(self):
return self.name
def __repr__(self):
return self.to_wkt(pretty=True)
def _is_exact_same(self, Base other):
return proj_is_equivalent_to_with_ctx(
self.context, self.projobj, other.projobj, PJ_COMP_STRICT) == 1
def _is_equivalent(self, Base other):
return proj_is_equivalent_to_with_ctx(
self.context, self.projobj, other.projobj, PJ_COMP_EQUIVALENT) == 1
def __eq__(self, other):
if not isinstance(other, Base):
return False
return self._is_equivalent(other)
def is_exact_same(self, other):
"""Compares projection objects to see if they are exactly the same."""
if not isinstance(other, Base):
return False
return self._is_exact_same(other)
cdef class _CRSParts(Base):
@classmethod
def from_user_input(cls, user_input):
"""
.. versionadded:: 2.5.0
Create cls from user input:
- PROJ JSON string
- PROJ JSON dict
- WKT string
- An authority string
- An EPSG integer code
- An iterable of ("auth_name", "auth_code")
- An object with a `to_json` method.
Parameters
----------
user_input: str, dict, int, Iterable[str, str]
Input to create cls.
Returns
-------
cls
"""
if isinstance(user_input, str):
prepared = cls.from_string(user_input)
elif isinstance(user_input, dict):
prepared = cls.from_json_dict(user_input)
elif isinstance(user_input, int) and hasattr(cls, "from_epsg"):
prepared = cls.from_epsg(user_input)
elif (
isinstance(user_input, (list, tuple))
and len(user_input) == 2
and hasattr(cls, "from_authority")
):
prepared = cls.from_authority(*user_input)
elif hasattr(user_input, "to_json"):
prepared = cls.from_json(user_input.to_json())
else:
raise CRSError(f"Invalid {cls.__name__} input: {user_input!r}")
return prepared
def __eq__(self, other):
try:
other = self.from_user_input(other)
except CRSError:
return False
return self._is_equivalent(other)
cdef dict _COORD_SYSTEM_TYPE_MAP = {
PJ_CS_TYPE_UNKNOWN: "unknown",
PJ_CS_TYPE_CARTESIAN: "cartesian",
PJ_CS_TYPE_ELLIPSOIDAL: "ellipsoidal",
PJ_CS_TYPE_VERTICAL: "vertical",
PJ_CS_TYPE_SPHERICAL: "spherical",
PJ_CS_TYPE_ORDINAL: "ordinal",
PJ_CS_TYPE_PARAMETRIC: "parametric",
PJ_CS_TYPE_DATETIMETEMPORAL: "datetimetemporal",
PJ_CS_TYPE_TEMPORALCOUNT: "temporalcount",
PJ_CS_TYPE_TEMPORALMEASURE: "temporalmeasure",
}
cdef class CoordinateSystem(_CRSParts):
"""
.. versionadded:: 2.2.0
Coordinate System for CRS
Attributes
----------
name: str
The name of the coordinate system.
"""
def __cinit__(self):
self._axis_list = None
def __init__(self):
raise RuntimeError("CoordinateSystem is not initializable.")
@staticmethod
cdef CoordinateSystem create(PJ_CONTEXT* context, PJ* coord_system_pj):
cdef CoordinateSystem coord_system = CoordinateSystem.__new__(CoordinateSystem)
coord_system.context = context
coord_system.projobj = coord_system_pj
cdef PJ_COORDINATE_SYSTEM_TYPE cs_type = proj_cs_get_type(
coord_system.context,
coord_system.projobj,
)
coord_system.name = _COORD_SYSTEM_TYPE_MAP[cs_type]
return coord_system
@property
def axis_list(self):
"""
Returns
-------
list[Axis]:
The Axis list for the coordinate system.
"""
if self._axis_list is not None:
return self._axis_list
self._axis_list = []
cdef int num_axes = 0
num_axes = proj_cs_get_axis_count(
self.context,
self.projobj
)
for axis_idx from 0 <= axis_idx < num_axes:
self._axis_list.append(
Axis.create(
self.context,
self.projobj,
axis_idx
)
)
return self._axis_list
@staticmethod
def from_string(str coordinate_system_string not None):
"""
.. versionadded:: 2.5.0
.. note:: Only works with PROJ JSON.
Create a Coordinate System from a string.
Parameters
----------
coordinate_system_string: str
Coordinate System string.
Returns
-------
CoordinateSystem
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* coordinate_system_pj = proj_create(
context,
cstrencode(coordinate_system_string)
)
if coordinate_system_pj == NULL or proj_cs_get_type(
context,
coordinate_system_pj,
) == PJ_CS_TYPE_UNKNOWN:
proj_destroy(coordinate_system_pj)
pyproj_context_destroy(context)
raise CRSError(
"Invalid coordinate system string: "
f"{coordinate_system_string}"
)
CRSError.clear()
return CoordinateSystem.create(context, coordinate_system_pj)
@staticmethod
def from_json_dict(dict coordinate_system_dict not None):
"""
.. versionadded:: 2.5.0
Create Coordinate System from a JSON dictionary.
Parameters
----------
coordinate_system_dict: str
Coordinate System dictionary.
Returns
-------
CoordinateSystem
"""
return CoordinateSystem.from_string(
json.dumps(coordinate_system_dict, cls=NumpyEncoder)
)
@staticmethod
def from_json(str coordinate_system_json_str not None):
"""
.. versionadded:: 2.5.0
Create Coordinate System from a JSON string.
Parameters
----------
coordinate_system_json_str: str
Coordinate System JSON string.
Returns
-------
CoordinateSystem
"""
return CoordinateSystem.from_json_dict(
_load_proj_json(coordinate_system_json_str)
)
def to_cf(self, bint rotated_pole=False):
"""
.. versionadded:: 3.0.0
This converts a :obj:`pyproj.crs.CoordinateSystem` axis
to a list of Climate and Forecast (CF) Version 1.8 dicts.
Parameters
----------
rotated_pole: bool, default=False
If True, the geographic coordinates are on a rotated pole grid.
This corresponds to the rotated_latitude_longitude grid_mapping_name.
Returns
-------
List[dict]:
CF-1.8 version of the CoordinateSystem.
"""
axis_list = self.to_json_dict()["axis"]
cf_params = []
def get_linear_unit(axis):
try:
return f'{axis["unit"]["conversion_factor"]} metre'
except TypeError:
return axis["unit"]
if self.name == "cartesian":
for axis in axis_list:
if axis["name"].lower() == "easting":
cf_axis = "X"
else:
cf_axis = "Y"
cf_params.append(dict(
axis=cf_axis,
long_name=axis["name"],
standard_name=f"projection_{cf_axis.lower()}_coordinate",
units=get_linear_unit(axis),
))
elif self.name == "ellipsoidal":
for axis in axis_list:
if axis["abbreviation"].upper() in ("D", "H"):
cf_params.append(dict(
standard_name="height_above_reference_ellipsoid",
long_name=axis["name"],
units=axis["unit"],
positive=axis["direction"],
axis="Z",
))
else:
if "longitude" in axis["name"].lower():
cf_axis = "X"
name = "longitude"
else:
cf_axis = "Y"
name = "latitude"
if rotated_pole:
cf_params.append(dict(
standard_name=f"grid_{name}",
long_name=f"{name} in rotated pole grid",
units="degrees",
axis=cf_axis,
))
else:
cf_params.append(dict(
standard_name=name,
long_name=f"{name} coordinate",
units=f'degrees_{axis["direction"]}',
axis=cf_axis,
))
elif self.name == "vertical":
for axis in axis_list:
cf_params.append(dict(
standard_name="height_above_reference_ellipsoid",
long_name=axis["name"],
units=get_linear_unit(axis),
positive=axis["direction"],
axis="Z",
))
return cf_params
cdef class Ellipsoid(_CRSParts):
"""
.. versionadded:: 2.0.0
Ellipsoid for CRS
Attributes
----------
name: str
The name of the ellipsoid.
is_semi_minor_computed: int
1 if True, 0 if False
semi_major_metre: float
The semi major axis in meters of the ellipsoid.
semi_minor_metre: float
The semi minor axis in meters of the ellipsoid.
inverse_flattening: float
The inverse flattening of the ellipsoid.
"""
def __cinit__(self):
# load in ellipsoid information if applicable
self.semi_major_metre = float("NaN")
self.semi_minor_metre = float("NaN")
self.is_semi_minor_computed = False
self.inverse_flattening = float("NaN")
def __init__(self):
raise RuntimeError(
"Ellipsoid can only be initialized like 'Ellipsoid.from_*()'."
)
@staticmethod
cdef Ellipsoid create(PJ_CONTEXT* context, PJ* ellipsoid_pj):
cdef Ellipsoid ellips = Ellipsoid.__new__(Ellipsoid)
ellips.context = context
ellips.projobj = ellipsoid_pj
cdef int is_semi_minor_computed = 0
proj_ellipsoid_get_parameters(
context,
ellipsoid_pj,
&ellips.semi_major_metre,
&ellips.semi_minor_metre,
&is_semi_minor_computed,
&ellips.inverse_flattening,
)
ellips.is_semi_minor_computed = is_semi_minor_computed == 1
ellips._set_base_info()
CRSError.clear()
return ellips
@staticmethod
def from_authority(str auth_name not None, code not None):
"""
.. versionadded:: 2.2.0
Create an Ellipsoid from an authority code.
Parameters
----------
auth_name: str
Name of the authority.
code: str or int
The code used by the authority.
Returns
-------
Ellipsoid
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = proj_create_from_database(
context,
cstrencode(auth_name),
cstrencode(str(code)),
PJ_CATEGORY_ELLIPSOID,
False,
NULL,
)
if ellipsoid_pj == NULL:
pyproj_context_destroy(context)
raise CRSError(f"Invalid authority or code ({auth_name}, {code})")
CRSError.clear()
return Ellipsoid.create(context, ellipsoid_pj)
@staticmethod
def from_epsg(code not None):
"""
.. versionadded:: 2.2.0
Create an Ellipsoid from an EPSG code.
Parameters
----------
code: str or int
The code used by the EPSG.
Returns
-------
Ellipsoid
"""
return Ellipsoid.from_authority("EPSG", code)
@staticmethod
def _from_string(str ellipsoid_string not None):
"""
Create an Ellipsoid from a string.
Examples:
- urn:ogc:def:ellipsoid:EPSG::7001
- ELLIPSOID["Airy 1830",6377563.396,299.3249646,
LENGTHUNIT["metre",1],
ID["EPSG",7001]]
Parameters
----------
ellipsoid_string: str
Ellipsoid string.
Returns
-------
Ellipsoid
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = proj_create(
context,
cstrencode(ellipsoid_string)
)
if ellipsoid_pj == NULL or proj_get_type(ellipsoid_pj) != PJ_TYPE_ELLIPSOID:
proj_destroy(ellipsoid_pj)
pyproj_context_destroy(context)
raise CRSError(
f"Invalid ellipsoid string: {ellipsoid_string}"
)
CRSError.clear()
return Ellipsoid.create(context, ellipsoid_pj)
@staticmethod
def from_string(str ellipsoid_string not None):
"""
.. versionadded:: 2.2.0
Create an Ellipsoid from a string.
Examples:
- urn:ogc:def:ellipsoid:EPSG::7001
- ELLIPSOID["Airy 1830",6377563.396,299.3249646,
LENGTHUNIT["metre",1],
ID["EPSG",7001]]
- WGS 84
Parameters
----------
ellipsoid_string: str
Ellipsoid string.
Returns
-------
Ellipsoid
"""
try:
return Ellipsoid._from_string(ellipsoid_string)
except CRSError as crs_err:
try:
return Ellipsoid.from_name(ellipsoid_string)
except CRSError:
raise crs_err
@staticmethod
def from_json_dict(dict ellipsoid_dict not None):
"""
.. versionadded:: 2.4.0
Create Ellipsoid from a JSON dictionary.
Parameters
----------
ellipsoid_dict: str
Ellipsoid dictionary.
Returns
-------
Ellipsoid
"""
return Ellipsoid._from_string(json.dumps(ellipsoid_dict, cls=NumpyEncoder))
@staticmethod
def from_json(str ellipsoid_json_str not None):
"""
.. versionadded:: 2.4.0
Create Ellipsoid from a JSON string.
Parameters
----------
ellipsoid_json_str: str
Ellipsoid JSON string.
Returns
-------
Ellipsoid
"""
return Ellipsoid.from_json_dict(_load_proj_json(ellipsoid_json_str))
@staticmethod
def _from_name(
str ellipsoid_name,
str auth_name,
):
"""
.. versionadded:: 2.5.0
Create a Ellipsoid from a name.
Parameters
----------
ellipsoid_name: str
Ellipsoid name.
auth_name: str
The authority name to refine search (e.g. 'EPSG').
If None, will search all authorities.
Returns
-------
Ellipsoid
"""
cdef PJ_CONTEXT* context = pyproj_context_create()
cdef PJ* ellipsoid_pj = _from_name(
context,
ellipsoid_name,
auth_name,
PJ_TYPE_ELLIPSOID,
)