forked from OSGeo/PROJ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_db_from_esri.py
executable file
·2522 lines (2057 loc) · 115 KB
/
build_db_from_esri.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
###############################################################################
# $Id$
#
# Project: PROJ
# Purpose: Build SRS and coordinate transform database from ESRI database
# provided at https://github.com/Esri/projection-engine-db-doc
# (from the csv/ directory content)
# Author: Even Rouault <even.rouault at spatialys.com>
#
###############################################################################
# Copyright (c) 2018, Even Rouault <even.rouault at spatialys.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################
import argparse
import csv
import os
import re
import sqlite3
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Optional, List, Dict
parser = argparse.ArgumentParser()
parser.add_argument('esri_csv_dir', help='Path to ESRI CSV dir, typically the path '
'to the "csv" directory of a "git clone '
'https://github.com/Esri/projection-engine-db-doc',
type=Path)
parser.add_argument('proj_db', help='Path to current proj.db file', type=Path)
parser.add_argument('version', help='ArcMap version string, e.g. "ArcMap 10.8.1"')
parser.add_argument('date', help='ArcMap version date as a yyyy-MM-dd string, e.g. "2020-05-24"')
args = parser.parse_args()
path_to_csv = args.esri_csv_dir
proj_db = args.proj_db
version = args.version
date = args.date
conn = sqlite3.connect(proj_db)
cursor = conn.cursor()
all_sql = ["""INSERT INTO "metadata" VALUES('ESRI.VERSION', '{}');""".format(version),
"""INSERT INTO "metadata" VALUES('ESRI.DATE', '{}');""".format(date)]
manual_grids = """------------------
-- ESRI grid names
------------------
INSERT INTO grid_alternatives(original_grid_name,
proj_grid_name,
old_proj_grid_name,
proj_grid_format,
proj_method,
inverse_direction,
package_name,
url, direct_download, open_license, directory)
VALUES
('prvi','us_noaa_prvi.tif','prvi','GTiff','hgridshift',0,NULL,'https://cdn.proj.org/us_noaa_prvi.tif', 1, 1, NULL),
('portugal/DLX_ETRS89_geo','pt_dgt_DLx_ETRS89_geo.tif','DLX_ETRS89_geo.gsb','GTiff','hgridshift',0,NULL,'https://cdn.proj.org/pt_dgt_DLx_ETRS89_geo.tif',1,1,NULL),
('portugal/D73_ETRS89_geo','pt_dgt_D73_ETRS89_geo.tif','D73_ETRS89_geo.gsb','GTiff','hgridshift',0,NULL,'https://cdn.proj.org/pt_dgt_D73_ETRS89_geo.tif',1,1,NULL),
('netherlands/rdtrans2008','','rdtrans2008.gsb','NTv2','hgridshift',0,NULL,'https://salsa.debian.org/debian-gis-team/proj-rdnap/raw/upstream/2008/rdtrans2008.gsb',1,0,NULL),
('uk/OSTN15_NTv2','uk_os_OSTN15_NTv2_OSGBtoETRS.tif','OSTN15_NTv2_OSGBtoETRS.gsb','GTiff','hgridshift',1 -- reverse direction
,NULL,'https://cdn.proj.org/uk_os_OSTN15_NTv2_OSGBtoETRS.tif',1,1,NULL),
('canada/GS7783','ca_nrc_GS7783.tif','GS7783.GSB','GTiff','hgridshift',0,NULL,'https://cdn.proj.org/ca_nrc_GS7783.tif',1,1,NULL),
('c1hpgn', 'us_noaa_c1hpgn.tif', 'c1hpgn.gsb', 'GTiff', 'hgridshift', 0, NULL, 'https://cdn.proj.org/us_noaa_c1hpgn.tif', 1, 1, NULL),
('c2hpgn', 'us_noaa_c2hpgn.tif', 'c2hpgn.gsb', 'GTiff', 'hgridshift', 0, NULL, 'https://cdn.proj.org/us_noaa_c2hpgn.tif', 1, 1, NULL),
('spain/100800401','es_cat_icgc_100800401.tif','100800401.gsb','GTiff','hgridshift',0,NULL,'https://cdn.proj.org/es_cat_icgc_100800401.tif',1,1,NULL),
('australia/QLD_0900','au_icsm_National_84_02_07_01.tif','National_84_02_07_01.gsb','GTiff','hgridshift',0,NULL,'https://cdn.proj.org/au_icsm_National_84_02_07_01.tif',1,1,NULL), -- From https://www.dnrme.qld.gov.au/__data/assets/pdf_file/0006/105765/gday-21-user-guide.pdf: "Note that the Queensland grid QLD_0900.gsb produces identical results to the National AGD84 grid for the equivalent coverage."
('spain/PENR2009','es_ign_SPED2ETV2.tif',NULL,'GTiff','hgridshift',0,NULL,'https://cdn.proj.org/es_ign_SPED2ETV2.tif',1,1,NULL),
('spain/BALR2009','es_ign_SPED2ETV2.tif',NULL,'GTiff','hgridshift',0,NULL,'https://cdn.proj.org/es_ign_SPED2ETV2.tif',1,1,NULL),
('spain/peninsula','es_ign_SPED2ETV2.tif',NULL,'GTiff','hgridshift',0,NULL,'https://cdn.proj.org/es_ign_SPED2ETV2.tif',1,1,NULL),
('spain/baleares','es_ign_SPED2ETV2.tif',NULL,'GTiff','hgridshift',0,NULL,'https://cdn.proj.org/es_ign_SPED2ETV2.tif',1,1,NULL);
-- 'france/RGNC1991_IGN72GrandeTerre' : we have a 3D geocentric corresponding one: no need for mapping
-- 'france/RGNC1991_NEA74Noumea' : we have a 3D geocentric corresponding one: no need for mapping
"""
def escape_literal(x):
return x.replace("'", "''")
########################
map_extentname_to_auth_code = {}
esri_area_counter = 1
def find_extent(extentname, slat, nlat, llon, rlon):
global esri_area_counter
if extentname in map_extentname_to_auth_code:
return map_extentname_to_auth_code[extentname]
deg = b'\xC2\xB0'.decode('utf-8')
cursor.execute("SELECT auth_name, code FROM extent WHERE name = ? AND auth_name != 'ESRI'",
(extentname.replace('~', deg),))
row = cursor.fetchone()
if row is None:
cursor.execute(
"SELECT auth_name, code FROM extent WHERE auth_name != 'ESRI' AND south_lat = ? AND north_lat = ? AND west_lon = ? AND east_lon = ?", (slat, nlat, llon, rlon))
row = cursor.fetchone()
if row is None:
# print('unknown extent inserted: ' + extentname)
if float(rlon) > 180:
new_rlon = '%s' % (float(rlon) - 360)
print('Correcting rlon from %s to %s for %s' %
(rlon, new_rlon, extentname))
rlon = new_rlon
assert -90 <= float(slat) <= 90, (extentname,
slat, nlat, llon, rlon)
assert -90 <= float(nlat) <= 90, (extentname,
slat, nlat, llon, rlon)
assert float(nlat) > float(slat), (extentname, slat, nlat, llon, rlon)
assert -180 <= float(llon) <= 180, (extentname,
slat, nlat, llon, rlon)
assert -180 <= float(rlon) <= 180, (extentname,
slat, nlat, llon, rlon)
sql = """INSERT INTO "extent" VALUES('ESRI','%d','%s','%s',%s,%s,%s,%s,0);""" % (
esri_area_counter, escape_literal(extentname), escape_literal(extentname), slat, nlat, llon, rlon)
all_sql.append(sql)
map_extentname_to_auth_code[extentname] = [
'ESRI', '%d' % esri_area_counter]
esri_area_counter += 1
else:
auth_name = row[0]
code = row[1]
map_extentname_to_auth_code[extentname] = [auth_name, code]
return map_extentname_to_auth_code[extentname]
#################
def import_linunit():
with open(path_to_csv / 'pe_list_linunit.csv', 'rt') as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
nfields = len(header)
idx_wkid = header.index('wkid')
assert idx_wkid >= 0
idx_latestWkid = header.index('latestWkid')
assert idx_latestWkid >= 0
idx_name = header.index('name')
assert idx_name >= 0
idx_wkt2 = header.index('wkt2')
assert idx_wkt2 >= 0
idx_authority = header.index('authority')
assert idx_authority >= 0
while True:
try:
row = next(reader)
except StopIteration:
break
assert len(row) == nfields, row
latestWkid = row[idx_latestWkid]
authority = row[idx_authority]
esri_name = row[idx_name]
wkt = row[idx_wkt2]
assert wkt.startswith('LENGTHUNIT[') and wkt.endswith(']')
tokens = wkt[len('LENGTHUNIT['):len(wkt) - 1].split(',')
assert len(tokens) == 2
esri_conv_factor = float(tokens[1])
if authority == 'EPSG':
cursor.execute(
"SELECT name, conv_factor FROM unit_of_measure WHERE code = ? AND auth_name = 'EPSG'", (latestWkid,))
src_row = cursor.fetchone()
assert src_row, row
src_name = src_row[0]
epsg_conv_factor = src_row[1]
assert abs(esri_conv_factor - epsg_conv_factor) <= 1e-15 * epsg_conv_factor, (esri_name, esri_conv_factor, epsg_conv_factor)
if src_name != esri_name:
sql = """INSERT INTO alias_name VALUES('unit_of_measure','EPSG','%s','%s','ESRI');""" % (
latestWkid, escape_literal(esri_name))
all_sql.append(sql)
#################
map_spheroid_esri_name_to_auth_code = {}
def import_spheroid():
with open(path_to_csv / 'pe_list_spheroid.csv', 'rt') as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
nfields = len(header)
idx_wkid = header.index('wkid')
assert idx_wkid >= 0
idx_latestWkid = header.index('latestWkid')
assert idx_latestWkid >= 0
idx_name = header.index('name')
assert idx_name >= 0
idx_description = header.index('description')
assert idx_description >= 0
idx_wkt2 = header.index('wkt2')
assert idx_wkt2 >= 0
idx_authority = header.index('authority')
assert idx_authority >= 0
idx_deprecated = header.index('deprecated')
assert idx_deprecated >= 0
body_set = set()
while True:
try:
row = next(reader)
except StopIteration:
break
assert len(row) == nfields, row
code = row[idx_wkid]
latestWkid = row[idx_latestWkid]
authority = row[idx_authority]
esri_name = row[idx_name]
if authority == 'EPSG':
cursor.execute(
"SELECT name FROM ellipsoid WHERE code = ? AND auth_name = 'EPSG'", (latestWkid,))
src_row = cursor.fetchone()
assert src_row, row
src_name = src_row[0]
map_spheroid_esri_name_to_auth_code[esri_name] = [
'EPSG', latestWkid]
if src_name != esri_name:
sql = """INSERT INTO alias_name VALUES('ellipsoid','EPSG','%s','%s','ESRI');""" % (
code, escape_literal(esri_name))
all_sql.append(sql)
else:
assert authority.upper() == 'ESRI', row
wkt2 = row[idx_wkt2]
wkt2_tokens_re = re.compile(r'ELLIPSOID\[""?(.*?)""?,(-?[\d]+(?:\.[\d]*)?),(-?[\d]+(?:\.[\d]*)?),LENGTHUNIT\[""?(.*?)""?,(-?[\d]+(?:\.[\d]*)?)]]')
match = wkt2_tokens_re.match(wkt2)
assert match, wkt2
a = match.group(2)
rf = match.group(3)
length_unit = match.group(4)
unit_size = float(match.group(5))
assert length_unit == 'Meter', 'Unhandled spheroid unit: {}'.format(length_unit)
assert unit_size == 1, 'Unhandled spheroid unit size: {}'.format(unit_size)
description = row[idx_description]
deprecated = 1 if row[idx_deprecated] == 'yes' else 0
if esri_name not in map_spheroid_esri_name_to_auth_code:
map_spheroid_esri_name_to_auth_code[esri_name] = [
'ESRI', code]
if abs(float(a) - 6375000) > 0.01 * 6375000:
pos = esri_name.find('_19')
if pos < 0:
pos = esri_name.find('_20')
assert pos > 0
body_code = esri_name[0:pos]
if body_code not in body_set:
body_set.add(body_code)
sql = """INSERT INTO celestial_body VALUES('ESRI', '%s', '%s', %s);""" % (
body_code, body_code, a)
all_sql.append(sql)
body_auth = 'ESRI'
else:
body_auth = 'PROJ'
body_code = 'EARTH'
sql = """INSERT INTO ellipsoid VALUES('ESRI','%s','%s','%s','%s','%s',%s,'EPSG','9001',%s,NULL,%d);""" % (
code, esri_name, description, body_auth, body_code, a, rf, deprecated)
all_sql.append(sql)
########################
map_pm_esri_name_to_auth_code = {}
def import_prime_meridian():
with open(path_to_csv / 'pe_list_primem.csv', 'rt') as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
nfields = len(header)
idx_wkid = header.index('wkid')
assert idx_wkid >= 0
idx_latestWkid = header.index('latestWkid')
assert idx_latestWkid >= 0
idx_name = header.index('name')
assert idx_name >= 0
idx_description = header.index('description')
assert idx_description >= 0
idx_wkt2 = header.index('wkt2')
assert idx_wkt2 >= 0
idx_authority = header.index('authority')
assert idx_authority >= 0
idx_deprecated = header.index('deprecated')
assert idx_deprecated >= 0
while True:
try:
row = next(reader)
except StopIteration:
break
assert len(row) == nfields, row
code = row[idx_wkid]
latestWkid = row[idx_latestWkid]
authority = row[idx_authority]
esri_name = row[idx_name]
if authority == 'EPSG':
cursor.execute(
"SELECT name FROM prime_meridian WHERE code = ? AND auth_name = 'EPSG'", (latestWkid,))
src_row = cursor.fetchone()
assert src_row, row
src_name = src_row[0]
map_pm_esri_name_to_auth_code[esri_name] = ['EPSG', latestWkid]
if src_name != esri_name:
sql = """INSERT INTO alias_name VALUES('prime_meridian','EPSG','%s','%s','ESRI');""" % (
code, escape_literal(esri_name))
all_sql.append(sql)
else:
assert authority.upper() == 'ESRI', row
wkt2 = row[idx_wkt2]
wkt2_tokens_re = re.compile(r'PRIMEM\[""?(.*?)""?,(-?[\d]+(?:\.[\d]*)?),ANGLEUNIT\[""?(.*?)""?,(-?[\d]+(?:\.[\d]*)?)]]')
match = wkt2_tokens_re.match(wkt2)
assert match, wkt2
value = match.group(2)
angle_unit = match.group(3)
unit_size = float(match.group(4))
assert angle_unit == 'Degree', 'Unhandled prime meridian unit: {}'.format(angle_unit)
assert unit_size == 0.0174532925199433, 'Unhandled prime meridian unit size: {}'.format(unit_size)
deprecated = 1 if row[idx_deprecated] == 'yes' else 0
if esri_name not in map_pm_esri_name_to_auth_code:
map_pm_esri_name_to_auth_code[esri_name] = ['ESRI', code]
sql = """INSERT INTO "prime_meridian" VALUES('ESRI','%s','%s',%s,'EPSG','9110',%d);""" % (
code, esri_name, value, deprecated)
all_sql.append(sql)
########################
map_datum_esri_name_to_auth_code = {}
map_datum_esri_to_parameters = {}
def get_old_esri_name(s):
"""Massage datum/CRS name like old ESRI software did"""
# Needed for EPSG:8353 S_JTSK_JTSK03_Krovak_East_North
# Cf https://github.com/OSGeo/gdal/issues/7505
if '[' in s:
s = s.replace('-', '_')
s = s.replace('[', '')
s = s.replace(']', '')
# Not totally sure of below, so disable
if False:
s = s.replace('_(', '_').replace(')_', '_')
s = s.replace('.', '_')
s = s.replace('(', '_').replace(')', '_')
if s.endswith('_'):
s = s[0:-1]
return s
def import_datum():
with open(path_to_csv / 'pe_list_datum.csv', 'rt') as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
nfields = len(header)
idx_wkid = header.index('wkid')
assert idx_wkid >= 0
idx_latestWkid = header.index('latestWkid')
assert idx_latestWkid >= 0
idx_name = header.index('name')
assert idx_name >= 0
idx_description = header.index('description')
assert idx_description >= 0
idx_wkt2 = header.index('wkt2')
assert idx_wkt2 >= 0
idx_authority = header.index('authority')
assert idx_authority >= 0
idx_deprecated = header.index('deprecated')
assert idx_deprecated >= 0
while True:
try:
row = next(reader)
except StopIteration:
break
assert len(row) == nfields, row
code = row[idx_wkid]
latestWkid = row[idx_latestWkid]
authority = row[idx_authority]
esri_name = row[idx_name]
if authority == 'EPSG':
map_datum_esri_name_to_auth_code[esri_name] = [
'EPSG', latestWkid]
cursor.execute(
"SELECT name FROM geodetic_datum WHERE auth_name = 'EPSG' AND code = ?", (latestWkid,))
src_row = cursor.fetchone()
assert src_row, row
src_name = src_row[0]
if src_name != esri_name:
sql = """INSERT INTO alias_name VALUES('geodetic_datum','EPSG','%s','%s','ESRI');""" % (
code, escape_literal(esri_name))
all_sql.append(sql)
old_esri_name = get_old_esri_name(esri_name)
if old_esri_name != esri_name:
sql = """INSERT INTO alias_name VALUES('geodetic_datum','EPSG','%s','%s','ESRI');""" % (
code, escape_literal(old_esri_name))
all_sql.append(sql)
description = row[idx_description]
deprecated = 1 if row[idx_deprecated] == 'yes' else 0
map_datum_esri_to_parameters[code] = {
'esri_name': esri_name,
'description': description,
'deprecated': deprecated
}
else:
assert authority.upper() == 'ESRI', row
map_datum_esri_name_to_auth_code[esri_name] = [
'ESRI', code]
wkt2 = row[idx_wkt2]
wkt2_tokens_re = re.compile(
r'DATUM\[""?(.*?)""?,\s*ELLIPSOID\[""?(.*?)""?,\s*(-?[\d]+(?:\.[\d]*)?),\s*(-?[\d]+(?:\.[\d]*)?),\s*LENGTHUNIT\[""?(.*?)""?,\s*(-?[\d]+(?:\.[\d]*)?)]]]')
match = wkt2_tokens_re.match(wkt2)
ellps_name = match.group(2)
assert ellps_name in map_spheroid_esri_name_to_auth_code, (
ellps_name, row)
ellps_auth_name, ellps_code = map_spheroid_esri_name_to_auth_code[ellps_name]
description = row[idx_description]
deprecated = 1 if row[idx_deprecated] == 'yes' else 0
map_datum_esri_to_parameters[code] = {
'esri_name': esri_name,
'description': description,
'ellps_auth_name': ellps_auth_name,
'ellps_code': ellps_code,
'deprecated': deprecated
}
# We cannot write it since we lack the prime meridian !!! (and
# the area of use)
########################
map_geogcs_esri_name_to_auth_code = {}
def import_geogcs():
# Those 2 maps are used to fill the deprecation table
map_code_to_authority = {}
mapDeprecatedToNonDeprecated = {}
with open(path_to_csv / 'pe_list_geogcs.csv', 'rt') as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
nfields = len(header)
idx_wkid = header.index('wkid')
assert idx_wkid >= 0
idx_latestWkid = header.index('latestWkid')
assert idx_latestWkid >= 0
idx_name = header.index('name')
assert idx_name >= 0
idx_description = header.index('description')
assert idx_description >= 0
idx_wkt2 = header.index('wkt2')
assert idx_wkt2 >= 0
idx_authority = header.index('authority')
assert idx_authority >= 0
idx_deprecated = header.index('deprecated')
assert idx_deprecated >= 0
idx_areaname = header.index('areaname')
assert idx_areaname >= 0
idx_slat = header.index('slat')
assert idx_slat >= 0
idx_nlat = header.index('nlat')
assert idx_nlat >= 0
idx_llon = header.index('llon')
assert idx_llon >= 0
idx_rlon = header.index('rlon')
assert idx_rlon >= 0
datum_written = set()
# last 2 ones epoch,model are actually missing in most records...
assert nfields == 17
while True:
try:
row = next(reader)
except StopIteration:
break
assert len(row) in (nfields, nfields -2), (row, header, len(row), nfields)
code = row[idx_wkid]
latestWkid = row[idx_latestWkid]
authority = row[idx_authority]
esri_name = row[idx_name]
if code == latestWkid and authority.upper() == 'ESRI':
cursor.execute(
"SELECT name FROM geodetic_crs WHERE auth_name = 'EPSG' AND code = ?", (latestWkid,))
src_row = cursor.fetchone()
if src_row:
src_name = src_row[0]
modified_epsg_name = src_name.replace(' ', '_')
if modified_epsg_name.upper() == esri_name.upper() or modified_epsg_name.upper() + "_3D" == esri_name.upper() or modified_epsg_name.upper() + "_(3D)" == esri_name.upper():
print("GeogCRS ESRI:%s (%s) has the same name as EPSG:%s. Fixing authority to be EPSG" % (latestWkid, esri_name, latestWkid))
authority = "EPSG"
map_code_to_authority[code] = authority.upper()
if authority == 'EPSG':
map_geogcs_esri_name_to_auth_code[esri_name] = [
'EPSG', latestWkid]
cursor.execute(
"SELECT name FROM geodetic_crs WHERE auth_name = 'EPSG' AND code = ?", (latestWkid,))
src_row = cursor.fetchone()
assert src_row, row
src_name = src_row[0]
if src_name != esri_name:
sql = """INSERT INTO alias_name VALUES('geodetic_crs','EPSG','%s','%s','ESRI');""" % (
code, escape_literal(esri_name))
all_sql.append(sql)
old_esri_name = get_old_esri_name(esri_name)
if old_esri_name != esri_name:
sql = """INSERT INTO alias_name VALUES('geodetic_crs','EPSG','%s','%s','ESRI');""" % (
code, escape_literal(old_esri_name))
all_sql.append(sql)
else:
assert authority.upper() == 'ESRI', row
wkt2 = row[idx_wkt2]
wkt2_datum_re = re.compile(r'.*DATUM\[""?(.*?)""?.*')
match = wkt2_datum_re.match(wkt2)
assert match, wkt2
datum_name = match.group(1)
# strip datum out of wkt
wkt2 = re.sub(r'DATUM\[""?(.*?)""?,\s*ELLIPSOID\[""?(.*?)""?,\s*(-?[\d]+(?:\.[\d]*)?),\s*(-?[\d]+(?:\.[\d]*)?),\s*LENGTHUNIT\[""?(.*?)""?,\s*(-?[\d]+(?:\.[\d]*)?)]]],?', '', wkt2)
assert datum_name in map_datum_esri_name_to_auth_code, (
datum_name, row)
datum_auth_name, datum_code = map_datum_esri_name_to_auth_code[datum_name]
wkt2_datum_re = re.compile(r'.*PRIMEM\[""?(.*?)""?.*')
match = wkt2_datum_re.match(wkt2)
assert match, wkt2
pm_name = match.group(1)
# strip prime meridian out of wkt
wkt2 = re.sub(r'PRIMEM\[""?(.*?)""?,(-?[\d]+(?:\.[\d]*)?),ANGLEUNIT\[""?(.*?)""?,(-?[\d]+(?:\.[\d]*)?)]],?', '', wkt2)
assert pm_name in map_pm_esri_name_to_auth_code, (pm_name, row)
pm_auth_name, pm_code = map_pm_esri_name_to_auth_code[pm_name]
wkt2_angle_unit_re = re.compile(
r'.*ANGLEUNIT\[""?(.*?)""?,(-?[\d]+(?:\.[\d]*)?)].*')
match = wkt2_angle_unit_re.match(wkt2)
assert match, wkt2
angle_unit = match.group(1)
assert angle_unit in ('Degree', 'Grad'), 'Unhandled angle unit {}'.format(angle_unit)
is_degree = angle_unit == 'Degree'
is_grad = angle_unit == 'Grad'
assert is_degree or is_grad, row
cs_code = '6422' if is_degree else '6403'
if "CS[ellipsoidal,3]" in wkt2:
assert 'AXIS["Ellipsoidal height (h)",up,ORDER[3],LENGTHUNIT["Meter",1.0]' in wkt2
cs_code = '6423'
geodetic_crs_type = "geographic 3D"
else:
geodetic_crs_type = "geographic 2D"
deprecated = 1 if row[idx_deprecated] == 'yes' else 0
extent_auth_name, extent_code = find_extent(
row[idx_areaname], row[idx_slat], row[idx_nlat], row[idx_llon], row[idx_rlon])
if datum_auth_name == 'ESRI':
if datum_code not in datum_written:
datum_written.add(datum_code)
p = map_datum_esri_to_parameters[datum_code]
sql = """INSERT INTO "geodetic_datum" VALUES('ESRI','%s','%s','%s','%s','%s','%s','%s',NULL,NULL,NULL,NULL,NULL,%d);""" % (
datum_code, p['esri_name'], p['description'], p['ellps_auth_name'], p['ellps_code'], pm_auth_name, pm_code, p['deprecated'])
all_sql.append(sql)
sql = """INSERT INTO "usage" VALUES('ESRI', '%s_USAGE','geodetic_datum','ESRI','%s','%s','%s','%s','%s');""" % (datum_code, datum_code, extent_auth_name, extent_code, 'EPSG', '1024')
all_sql.append(sql)
p['pm_auth_name'] = pm_auth_name
p['pm_code'] = pm_code
map_datum_esri_to_parameters[datum_code] = p
else:
assert map_datum_esri_to_parameters[datum_code]['pm_auth_name'] == pm_auth_name, (
row, map_datum_esri_to_parameters[datum_code]['pm_auth_name'], pm_auth_name)
if map_datum_esri_to_parameters[datum_code]['pm_code'] != pm_code:
p = map_datum_esri_to_parameters[datum_code]
# Case of GCS_Voirol_Unifie_1960 and GCS_Voirol_Unifie_1960_Paris which use the same
# datum D_Voirol_Unifie_1960 but with different prime meridian
# We create an artificial datum to avoid that issue
datum_name += '_' + pm_name
datum_code += '_' + pm_name
datum_written.add(datum_code)
map_datum_esri_name_to_auth_code[datum_name] = [
'ESRI', latestWkid]
map_datum_esri_to_parameters[datum_code] = {
'esri_name': datum_name,
'description': p['description'] + ' with ' + pm_name + ' prime meridian',
'ellps_auth_name': p['ellps_auth_name'],
'ellps_code': p['ellps_code'],
'deprecated': p['deprecated']
}
sql = """INSERT INTO "geodetic_datum" VALUES('ESRI','%s','%s','%s','%s','%s','%s','%s',NULL,NULL,NULL,NULL,NULL,%d);""" % (
datum_code, p['esri_name'], p['description'], p['ellps_auth_name'], p['ellps_code'], pm_auth_name, pm_code, p['deprecated'])
all_sql.append(sql)
sql = """INSERT INTO "usage" VALUES('ESRI', '%s_USAGE','geodetic_datum','ESRI','%s','%s','%s','%s','%s');""" % (datum_code, datum_code, extent_auth_name, extent_code, 'EPSG', '1024')
all_sql.append(sql)
p['pm_auth_name'] = pm_auth_name
p['pm_code'] = pm_code
map_datum_esri_to_parameters[datum_code] = p
# We may have already the EPSG entry, so use it preferably
if esri_name not in map_geogcs_esri_name_to_auth_code:
map_geogcs_esri_name_to_auth_code[esri_name] = ['ESRI', code]
sql = f"""INSERT INTO "geodetic_crs" VALUES('ESRI','%s','%s',NULL,'{geodetic_crs_type}','EPSG','%s','%s','%s',NULL,%d);""" % (
code, esri_name, cs_code, datum_auth_name, datum_code, deprecated)
all_sql.append(sql)
sql = """INSERT INTO "usage" VALUES('ESRI', '%s_USAGE','geodetic_crs','ESRI','%s','%s','%s','%s','%s');""" % (code, code, extent_auth_name, extent_code, 'EPSG', '1024')
all_sql.append(sql)
if deprecated and code != latestWkid and code not in ('4305', '4812'): # Voirol 1960 no longer in EPSG
cursor.execute(
"SELECT name, deprecated FROM geodetic_crs WHERE auth_name = 'EPSG' AND code = ?", (latestWkid,))
src_row = cursor.fetchone()
assert src_row, (code, latestWkid)
_, deprecated = src_row
if not deprecated:
sql = """INSERT INTO "deprecation" VALUES('geodetic_crs','ESRI','%s','EPSG','%s','ESRI');""" % (
code, latestWkid)
all_sql.append(sql)
elif deprecated and code != latestWkid:
mapDeprecatedToNonDeprecated[code] = latestWkid
for code in mapDeprecatedToNonDeprecated:
replacement_code = mapDeprecatedToNonDeprecated[code]
if replacement_code in map_code_to_authority:
sql = """INSERT INTO "deprecation" VALUES('geodetic_crs','ESRI','%s','%s','%s','ESRI');""" % (
code, map_code_to_authority[replacement_code], replacement_code)
all_sql.append(sql)
########################
def parse_wkt(s, level):
if s[0] == '"':
return s
pos = s.find('[')
if pos < 0:
return s
return {s[0:pos]: parse_wkt_array(s[pos+1:-1], level + 1)}
def parse_wkt_array(s, level=0):
ar = []
in_string = False
cur_token = ''
indent_level = 0
for c in s:
if in_string:
if c == '"':
in_string = False
else:
cur_token += c
elif c == '"':
in_string = True
elif c == '[':
cur_token += c
indent_level += 1
elif c == ']':
cur_token += c
indent_level -= 1
assert indent_level >= 0
elif indent_level == 0 and c == ',':
ar.append(parse_wkt(cur_token, level + 1))
cur_token = ''
else:
cur_token += c
assert indent_level == 0
if cur_token:
ar.append(parse_wkt(cur_token, level + 1))
if level == 0:
return wkt_array_to_dict(ar)
else:
return ar
def wkt_array_to_dict(ar):
d = {}
for elt in ar:
assert isinstance(elt, dict), elt
assert len(elt) == 1
if 'PROJECTION' in elt:
assert len(elt['PROJECTION']) == 1, elt['PROJECTION']
assert 'PROJECTION' not in d
name = elt['PROJECTION'][0]
d['PROJECTION'] = name
elif 'CONVERSION' in elt:
d['CONVERSION'] = [elt['CONVERSION'][0], wkt_array_to_dict(elt['CONVERSION'][1:])]
elif 'COORDINATEOPERATION' in elt:
d['COORDINATEOPERATION'] = [elt['COORDINATEOPERATION'][0], wkt_array_to_dict(elt['COORDINATEOPERATION'][1:])]
elif 'SOURCECRS' in elt:
assert len(elt['SOURCECRS']) == 1, elt['SOURCECRS']
d['SOURCECRS'] = elt['SOURCECRS'][0]
elif 'TARGETCRS' in elt:
assert len(elt['TARGETCRS']) == 1, elt['TARGETCRS']
d['TARGETCRS'] = elt['TARGETCRS'][0]
elif 'VERTCRS' in elt:
d['VERTCRS'] = [elt['VERTCRS'][0], wkt_array_to_dict(elt['VERTCRS'][1:])]
elif 'VDATUM' in elt:
assert len(elt['VDATUM']) == 1, elt['VDATUM']
d['VDATUM'] = elt['VDATUM'][0]
elif 'CS' in elt:
assert len(elt['CS']) == 2, elt['CS']
d['CS'] = elt['CS']
elif 'AXIS' in elt:
assert len(elt['AXIS']) == 3
d['AXIS'] = [elt['AXIS'][0], elt['AXIS'][1], wkt_array_to_dict(elt['AXIS'][2:])]
elif 'DATUM' in elt:
d['DATUM'] = [elt['DATUM'][0], wkt_array_to_dict(elt['DATUM'][1:])]
elif 'METHOD' in elt:
assert len(elt['METHOD']) == 1, elt['METHOD']
d['METHOD'] = elt['METHOD'][0]
elif 'PARAMETERFILE' in elt:
assert len(elt['PARAMETERFILE']) == 1, elt['PARAMETERFILE']
d['PARAMETERFILE'] = elt['PARAMETERFILE'][0]
elif 'OPERATIONACCURACY' in elt:
assert len(elt['OPERATIONACCURACY']) == 1, elt['OPERATIONACCURACY']
d['OPERATIONACCURACY'] = elt['OPERATIONACCURACY'][0]
#elif 'ELLIPSOID' in elt:
# d['ELLIPSOID'] = [elt['ELLIPSOID'][0], wkt_array_to_dict(elt['ELLIPSOID'][1:])]
elif 'PARAMETER' in elt:
assert len(elt['PARAMETER']) >= 2, elt['PARAMETER']
name = elt['PARAMETER'][0]
assert name not in d
d[name] = elt['PARAMETER'][1] if len(elt['PARAMETER']) == 2 else elt['PARAMETER'][1:]
elif 'UNIT' in elt:
assert len(elt['UNIT']) == 2, elt['UNIT']
name = elt['UNIT'][0]
assert 'UNIT_NAME' not in d
d['UNIT_NAME'] = name
d['UNIT_VALUE'] = elt['UNIT'][1]
elif 'LENGTHUNIT' in elt:
assert len(elt['LENGTHUNIT']) == 2, elt['LENGTHUNIT']
name = elt['LENGTHUNIT'][0]
assert 'UNIT_NAME' not in d
d['UNIT_NAME'] = name
d['UNIT_VALUE'] = elt['LENGTHUNIT'][1]
else:
assert True
return d
########################
@dataclass
class CoordinateSystem:
"""
Encapsulates a coordinate system
"""
auth_name: str
code: str
@dataclass
class Unit:
"""
Encapsulates a WKT unit
"""
uom_auth_name: str
uom_code: str
cs: Optional[CoordinateSystem] = None
def get_wkt_unit(UNIT_NAME, UNIT_VALUE, is_rate=False) -> Unit:
cs = None
if UNIT_NAME == 'Meter':
uom_auth_name = 'EPSG'
uom_code = '1042' if is_rate else '9001'
cs = CoordinateSystem('EPSG', '4400')
assert UNIT_VALUE == '1.0', UNIT_VALUE
elif UNIT_NAME == 'Millimeter':
uom_auth_name = 'EPSG'
uom_code = '1027' if is_rate else '1025'
assert UNIT_VALUE == '0.001', UNIT_VALUE
elif UNIT_NAME == 'Chain':
uom_auth_name = 'EPSG'
assert not is_rate
uom_code = '9097'
cs = CoordinateSystem('ESRI', UNIT_NAME)
assert UNIT_VALUE == '20.1168', UNIT_VALUE
elif UNIT_NAME == 'Degree':
assert not is_rate
uom_auth_name = 'EPSG'
uom_code = '9102'
assert UNIT_VALUE == '0.0174532925199433', UNIT_VALUE
elif UNIT_NAME == 'Arcsecond':
uom_auth_name = 'EPSG'
uom_code = '1043' if is_rate else '9104'
assert UNIT_VALUE == '0.00000484813681109536', UNIT_VALUE
elif UNIT_NAME == 'Milliarcsecond':
uom_auth_name = 'EPSG'
uom_code = '1032' if is_rate else '1031'
assert UNIT_VALUE == '4.84813681109536e-09', UNIT_VALUE
elif UNIT_NAME == 'Grad':
assert not is_rate
uom_auth_name = 'EPSG'
uom_code = '9105'
assert UNIT_VALUE == '0.01570796326794897', UNIT_VALUE
elif UNIT_NAME == 'Foot':
assert not is_rate
uom_auth_name = 'EPSG'
uom_code = '9002'
cs = CoordinateSystem('EPSG', '4495')
assert UNIT_VALUE == '0.3048', UNIT_VALUE
elif UNIT_NAME == 'Foot_US':
assert not is_rate
uom_auth_name = 'EPSG'
uom_code = '9003'
cs = CoordinateSystem('EPSG', '4497')
assert UNIT_VALUE == '0.3048006096012192', UNIT_VALUE
elif UNIT_NAME == 'Yard_Indian_1937':
assert not is_rate
uom_auth_name = 'EPSG'
uom_code = '9085'
cs = CoordinateSystem('ESRI', UNIT_NAME)
assert UNIT_VALUE == '0.91439523', UNIT_VALUE
elif UNIT_NAME == 'Parts_Per_Million':
uom_auth_name = 'EPSG'
uom_code = '1041' if is_rate else '9202'
assert UNIT_VALUE == '0.000001', UNIT_VALUE
elif UNIT_NAME == 'Parts_Per_Billion':
uom_auth_name = 'EPSG'
uom_code = '1030' if is_rate else '1028'
assert UNIT_VALUE == '0.000000001', UNIT_VALUE
elif UNIT_NAME == 'Unity':
assert not is_rate
uom_auth_name = 'EPSG'
uom_code = '9201'
assert UNIT_VALUE == '1.0', UNIT_VALUE
else:
assert False, UNIT_NAME
if cs is not None and cs.auth_name == 'ESRI' and cs.code not in set_esri_cs_code:
sql = f"""INSERT INTO "coordinate_system" VALUES('ESRI','{cs.code}','Cartesian',2);"""
all_sql.append(sql)
sql = f"""INSERT INTO "axis" VALUES('ESRI','{2 * len(set_esri_cs_code) + 1}','Easting','E','east','ESRI','{cs.code}',1,'EPSG','{uom_code}');"""
all_sql.append(sql)
sql = f"""INSERT INTO "axis" VALUES('ESRI','{2 * len(set_esri_cs_code) + 2}','Northing','N','north','ESRI','{cs.code}',2,'EPSG','{uom_code}');"""
all_sql.append(sql)
set_esri_cs_code.add(cs.code)
return Unit(uom_auth_name=uom_auth_name,
uom_code=uom_code,
cs=cs)
class UnitType(Enum):
"""
WKT unit types
"""
Angle = 0
Length = 1
Scale = 2
STRING_TO_UNIT_TYPE = {
'ANGLEUNIT': UnitType.Angle,
'LENGTHUNIT': UnitType.Length,
'SCALEUNIT': UnitType.Scale
}
@dataclass
class ParameterValue:
"""
Encapsulates a WKT parameter value
"""
value: float
unit_type: UnitType
unit: Unit
def get_parameter_value(wkt_definition: List) -> ParameterValue: