-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSSURGO_Convert_to_Geodatabase.py
1667 lines (1521 loc) · 58.8 KB
/
SSURGO_Convert_to_Geodatabase.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 python3
# -*- coding: utf-8 -*-
"""
One of three scripts called by the Create gSSURGO File Geodatabase tool
from the RSS SSURGO Export Tool arctoolbox
This tool creates file geodatabse RSS database.
Created on: 09/19/2024
@author: Alexander Stum
@maintainer: Alexander Stum
@title: GIS Specialist & Soil Scientist
@organization: National Soil Survey Center, USDA-NRCS
@email: [email protected]
@modified 09/19/2024
@by: Alexnder Stum
@version: 1.1
# ---
The orginal tool this is based off of is from the ArcMap Desktop toolbox
ArcGIS Desktop Build RSS gdb: Create RSS DB by Map. This tool creates a
RSS databse which uses the gSSURGO template, but not vector features
are created. Each text file is imported and relationships and indices made.
ImportXMLWorkspaceDocument command requires Standard or Advanced license
"""
# Import system modules
import csv
import datetime
import gc
import itertools as it
import os
import platform
import shutil
import sys
import time
import traceback
import xml.etree.cElementTree as ET
from importlib import reload
from urllib.request import urlopen
from typing import Any, Callable, TypeVar
import arcpy
from arcpy import env
Tist = TypeVar("Tist", tuple, list)
states = {
'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas', 'AS': 'American Samoa',
'AZ': 'Arizona', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut',
'DC': 'District of Columbia', 'DE': 'Delaware', 'FL': 'Florida',
'GA': 'Georgia', 'GU': 'Guam', 'HI': 'Hawaii', 'IA': 'Iowa', 'ID': 'Idaho',
'IL': 'Illinois', 'IN': 'Indiana', 'KS': 'Kansas', 'KY': 'Kentucky',
'LA': 'Louisiana', 'MA': 'Massachusetts', 'MD': 'Maryland', 'ME': 'Maine',
'MI': 'Michigan', 'MN': 'Minnesota', 'MO': 'Missouri', 'MS': 'Mississippi',
'MT': 'Montana', 'NC': 'North Carolina', 'ND': 'North Dakota',
'NE': 'Nebraska', 'NH': 'New Hampshire', 'NJ': 'New Jersey',
'NM': 'New Mexico', 'NV': 'Nevada', 'NY': 'New York', 'OH': 'Ohio',
'OK': 'Oklahoma', 'OR': 'Oregon', 'PA': 'Pennsylvania',
'PRUSVI': "Puerto Rico and U.S. Virgin Islands", 'RI': 'Rhode Island',
'SC': 'South Carolina', 'SD': 'South Dakota', 'TN': 'Tennessee',
'TX': 'Texas', 'UT': 'Utah', 'VA': 'Virginia', 'VT': 'Vermont',
'WA': 'Washington', 'WI': 'Wisconsin', 'WV': 'West Virginia',
'WY': 'Wyoming'
}
class xml:
def __init__(self, aoi: str, path: str, gssurgo_v: str):
self.path = path
self.aoi = aoi
self.version = gssurgo_v
if self.version == '2.0':
path_i = self.path + '/gSSURGO2_'
else:
path_i = self.path + '/gSSURGO1_'
# Input XML workspace document used to create new gSSURGO schema in
# an empty geodatabase
if aoi == "Lower 48 States":
self.xml = path_i + "RSS_CONUS_AlbersNAD1983.xml"
elif aoi == "Hawaii":
self.xml = path_i + "Hawaii_AlbersWGS1984.xml"
elif aoi == "Alaska":
self.xml = path_i + "Alaska_AlbersNAD1983.xml"
elif aoi == "Puerto Rico and U.S. Virgin Islands":
self.xml = path_i + "PRUSVI_StateNAD83.xml"
else:
self.xml = path_i + "_Geographic_WGS1984.xml"
self.exist = os.path.isfile(self.xml)
def pyErr(func: str) -> str:
"""When a python exception is raised, this funciton formats the traceback
message.
Parameters
----------
func : str
The function that raised the python error exception
Returns
-------
str
Formatted python error message
"""
try:
etype, exc, tb = sys.exc_info()
tbinfo = traceback.format_tb(tb)[0]
tbinfo = '\t\n'.join(tbinfo.split(','))
msgs = (f"PYTHON ERRORS:\nIn function: {func}"
f"\nTraceback info:\n{tbinfo}\nError Info:\n\t{exc}")
return msgs
except:
return "Error in pyErr method"
def arcpyErr(func: str) -> str:
"""When an arcpy by exception is raised, this function formats the
message returned by arcpy.
Parameters
----------
func : str
The function that raised the arcpy error exception
Returns
-------
str
Formatted arcpy error message
"""
try:
etype, exc, tb = sys.exc_info()
line = tb.tb_lineno
msgs = (f"ArcPy ERRORS:\nIn function: {func}\non line: {line}"
f"\n\t{arcpy.GetMessages(2)}\n")
return msgs
except:
return "Error in arcpyErr method"
def funYield(
fn: Callable, iterSets: Tist, #[dict[str, Any]]
constSets: dict[str, Any]
) : # -> Generator[list[int, str]]
"""Iterativley calls a function as a generator
Parameters
----------
fn : Callable
The function to be called as a generator
iterSets : Tist[dict[str, Any],]
These dictionaries are a set of dynmaic variables for each iteration.
The keys must align with the ``fn`` parameters. The values the
arguments for the function call.
constSets : dict[str, Any]
This dictionary is composed of the static variables sent as
arguments to function call ``fn``.
The keys must align with the ``fn`` parameters.
Yields
------
Generator[int, str]
If successful, yields the value 0 and an empty string, otherwise
yields the value 2 with a string message. This generator can be
modified to yield the returned items from the function ``fn``.
"""
try:
fn_inputs = iter(iterSets)
# initialize first set of processes
outputs = {
fn(**params, **constSets): params
for params in it.islice(fn_inputs, len(iterSets))
}
# output, params = outputs.popitem()
yield [0, '']
except:
arcpy.AddWarning('Better luck next time')
func = sys._getframe().f_code.co_name
msgs = pyErr(func)
yield [2, msgs]
def createGDB(gdb_p: str, inputXML: xml) -> str:
"""Creates the SSURGO file geodatabase using an xml workspace file to
create tables, features, and relationships.
Parameters
----------
gdb_p : str
The path of the SSURGO file geodatabase to be created.
imputXML: xml
An xml class object that has information about the xml workspace to
template new file geodatabase.
Returns
-------
str
An empty string if successful, an error message if unsuccessful.
"""
try:
outputFolder = os.path.dirname(gdb_p)
gdb_n = os.path.basename(gdb_p)
if arcpy.Exists(gdb_p):
arcpy.AddMessage(f"\tDeleting existing file gdb {gdb_p}")
arcpy.management.Delete(gdb_p)
arcpy.AddMessage(f"\tCreating new geodatabase ({gdb_n}) in "
f"{outputFolder}\n")
arcpy.management.CreateFileGDB(outputFolder, gdb_n)
if not arcpy.Exists(gdb_p):
arcpy.AddError("Failed to create new geodatabase")
return False
# The following command will fail when the user only has a Basic license
arcpy.management.ImportXMLWorkspaceDocument(
gdb_p, inputXML.xml, "SCHEMA_ONLY"
)
env.workspace = gdb_p
tblList = arcpy.ListTables()
if len(tblList) < 50:
arcpy.AddError(f"Output geodatabase has only {len(tblList)} tables")
return False
return True
except arcpy.ExecuteError:
func = sys._getframe().f_code.co_name
arcpy.AddError(arcpyErr(func))
return False
except:
func = sys._getframe().f_code.co_name
arcpy.AddError(pyErr(func))
return False
def importCoint(
input_p: str,
gdb_p: str,
table_d: dict[list[str, str, list[tuple[int, str]]]],
) -> str:
"""Runs through each SSURGO download folder and imports the rows into the
specified cointerp table . This table has unique information from each
survey area. This funciton is only called for gSSURGO 1.0 builds.
Parameters
----------
input_p : str
Path to the SSRUGO downloads
gdb_p : str
Path of the SSURGO geodatabase
table_d : dict[list[str, str, list[tuple[int, str]]]]
Key is the Table Physical Name (gdb table name). Value is a list with
three elements, the text file base name, table label, and a list of
tuples with the column sequence and column name.
Returns
-------
str
An empty string if successful, otherwise and error message.
"""
try:
arcpy.env.workspace = gdb_p
csv.field_size_limit(2147483647)
table = 'cointerp'
tab_p = f"{gdb_p}/{table}"
cols = table_d[table][2]
# get fields in sequence order
cols.sort()
fields = [f[1] for f in cols]
iCur = arcpy.da.InsertCursor(tab_p, fields)
# Make file path for text file
txt_p = f"{input_p}/cinterp.txt"
if not os.path.exists(txt_p):
return f"{txt_p} does not exist"
csvReader = csv.reader(
open(txt_p, 'r'), delimiter='|', quotechar='"'
)
for row in csvReader:
if row[1] == row[4] or row[1] == "54955":
# Slice out excluded elements
row = row[:7] + row[11:13] + row[15:]
# replace empty sets with None
iCur.insertRow(tuple(v or None for v in row))
del csvReader, iCur
arcpy.AddMessage(f"\tSuccessfully populated {table}")
return 0 # None
except arcpy.ExecuteError:
try:
del iCur
except:
pass
try:
arcpy.AddError(f'While working with {txt_p} and {table}')
except:
pass
func = sys._getframe().f_code.co_name
arcpy.AddError(arcpyErr(func))
return 1 # arcpyErr(func)
except:
try:
del iCur
except:
pass
try:
arcpy.AddError(f'While working with {txt_p} and {table}')
except:
pass
func = sys._getframe().f_code.co_name
arcpy.AddError(pyErr(func))
return 1 # pyErr(func)
def importList(
input_p: str,
gdb_p: str,
table_d: dict[list[str, str, list[tuple[int, str]]]],
table: str
) -> int:
"""Runs through the tabular folder and imports the rows into the
specified ``table`` . These tables have unique information from each
survey area.
Parameters
----------
input_p : str
Path to the SSRUGO downloads
gdb_p : str
Path of the SSURGO geodatabase
table_d : dict[list[str, str, list[tuple[int, str]]]]
Key is the Table Physical Name (gdb table name). Value is a list with
three elements, the text file base name, table label, and a list of
tuples with the column sequence and column name.
table : str
Table that is being imported.
Returns
-------
int
An empty string if successful, otherwise and error message.
"""
try:
arcpy.env.workspace = gdb_p
csv.field_size_limit(2147483647)
txt = table_d[table][0]
cols = table_d[table][2]
tab_p = f"{gdb_p}/{table}"
# get fields in sequence order
cols.sort()
fields = [f[1] for f in cols]
iCur = arcpy.da.InsertCursor(tab_p, fields)
# Make file path for text file
txt_p = f"'{input_p}/{txt}.txt'"
# in some instances // can create special charaters with eval
txt_p = txt_p.replace('\\', '/')
# convert latent f strings
txt_p = eval("f" + txt_p)
if not os.path.exists(txt_p):
return f"{txt_p} does not exist"
csvReader = csv.reader(
open(txt_p, 'r'), delimiter='|', quotechar='"'
)
for row in csvReader:
# replace empty sets with None
iCur.insertRow(tuple(v or None for v in row))
del csvReader, iCur
arcpy.AddMessage(f"\tSuccessfully populated {table}")
return 0 # None
except arcpy.ExecuteError:
try:
del iCur
except:
pass
try:
arcpy.AddError(f'While working with {txt_p} and {table}')
except:
pass
func = sys._getframe().f_code.co_name
arcpy.AddError(arcpyErr(func))
return 1 # arcpyErr(func)
except:
try:
del iCur
except:
pass
try:
arcpy.AddError(f'While working with {txt_p} and {table}')
except:
pass
func = sys._getframe().f_code.co_name
arcpy.AddError(pyErr(func))
return 1 # pyErr(func)
def importSet(
input_p: str,
gdb_p: str,
table_d: dict[str, list[str, str, list[tuple[int, str]]]]
) -> str:
"""Runs through the tabular folder and compiles a set of unique
values to insert into respective tables. These tables are largely common
to all surveys but some states have rows unique to their surveys.
Parameters
----------
input_p : str
Path to the SSRUGO downloads
gdb_p : str
Path of the SSURGO geodatabase
table_d : dict[list[str, str, list[tuple[int, str]]]]
Key is the Table Physical Name (gdb table name). Value is a list with
three elements, the text file base name, table label, and a list of
tuples with the column sequence and column name.
Returns
-------
str
An empty string if successful, otherwise and error message.
"""
try:
csv.field_size_limit(2147483647)
# 'distsubinterpmd'
tabs_l = ['distinterpmd', 'sdvattribute', 'sdvfolderattribute']
arcpy.env.workspace = gdb_p
for table in tabs_l:
txt = table_d[table][0]
cols = table_d[table][2]
tab_p = f"{gdb_p}/{table}"
# get fields in sequence order
cols.sort()
fields = [f[1] for f in cols]
iCur = arcpy.da.InsertCursor(tab_p, fields)
row_s = set()
txt_p = f"{input_p}/{txt}.txt"
if not os.path.exists(txt_p):
return f"{txt_p} does not exist"
csvReader = csv.reader(
open(txt_p, 'r', encoding='utf8'),
delimiter = '|',
quotechar = '"'
)
for row in csvReader:
# replace empty sets with None
row_s.add(tuple(v or None for v in row))
for row in row_s:
iCur.insertRow(row)
del iCur
return ''
except arcpy.ExecuteError:
try:
del iCur
except:
pass
func = sys._getframe().f_code.co_name
return arcpy.AddError(arcpyErr(func))
except:
try:
arcpy.AddMessage(table)
# arcpy.AddMessage(cols)
# arcpy.AddMessage(txt)
# for i, e in enumerate(row):
# if e:
# size = len(e)
# else:
# size = 0
# arcpy.AddMessage(f"{fields[i]}: {size}")
del iCur
except:
pass
func = sys._getframe().f_code.co_name
return arcpy.AddError(pyErr(func))
def importSing(input_p: str, gdb_p: str) -> dict:
"""Import the tables that are common for each SSURGO download
Also creates a table dictionary that with the table information.
Parameters
----------
input_p : str
Path to the SSRUGO downloads
gdb_p : str
Path of the SSURGO geodatabase
Returns
-------
dict
Key is the Table Physical Name (gdb table name). Value is a list with
three elements, the text file base name, table label, and a list of
tuples with the column sequence and column name. If the function
returns in error the dictionary will return wiht the key 'Error'
and a message.
"""
try:
# First read in mdstattabs: mstab table into
# There should be 75 tables, 6 of which are spatial, so 69
# Then read tables from gdb
# Copy common tables and report unused
# Then import the common tables
tn = 69
csv.field_size_limit(2147483647)
tabs_common = [
'mdstattabcols', 'mdstatrshipdet', 'mdstattabs', 'mdstatrshipmas',
'mdstatdommas', 'mdstatidxmas', 'mdstatidxdet', 'mdstatdomdet',
'sdvfolder', 'sdvalgorithm'
]
arcpy.env.workspace = gdb_p
txt_p = f"{input_p}/mstab.txt"
if not os.path.exists(txt_p):
table_d = {'Error': (f"{txt_p} does not exist", '', [])}
return table_d
csvReader = csv.reader(
open(txt_p, 'r', encoding='utf8'), delimiter='|', quotechar='"'
)
# dict{Table Physical Name:
# [text file, Table Label, [(seq, column names)]]}
table_d = {t[0]: [t[4], t[2], []] for t in csvReader}
# Retrieve column names
txt_p = f"{input_p}/mstabcol.txt"
if not os.path.exists(txt_p):
table_d = {'Error': f"{txt_p} does not exist"}
return table_d
csvReader = csv.reader(
open(txt_p, 'r', encoding='utf8'), delimiter='|', quotechar='"'
)
for row in csvReader:
table = row[0]
if table in table_d:
# add tuple with sequence (as int to sort) and column name
table_d[table][2].append((int(row[1]), row[2]))
# Populate static tables
for table in tabs_common:
txt = table_d[table][0]
cols = table_d[table][2]
tab_p = f"{gdb_p}/{table}"
# get fields in sequence order
cols.sort()
fields = [f[1] for f in cols]
iCur = arcpy.da.InsertCursor(tab_p, fields)
txt_p = f"{input_p}/{txt}.txt"
if not os.path.exists(txt_p):
table_d = {'Error': f"{txt_p} does not exist"}
return table_d
csvReader = csv.reader(
open(txt_p, 'r', encoding='utf8'),
delimiter = '|',
quotechar='"'
)
for row in csvReader:
# replace empty sets with None
iCur.insertRow(tuple(v or None for v in row))
del iCur
# Populate the month table
months = [
(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'),
(5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'),
(9, 'September'), (10, 'October'), (11, 'November'),
(12, 'December')
]
month_p = f"{gdb_p}/month"
iCur = arcpy.da.InsertCursor(month_p, ['monthseq', 'monthname'])
for month in months:
iCur.insertRow(month)
del iCur
return table_d
except arcpy.ExecuteError:
try:
del iCur
except:
pass
try:
arcpy.AddError(f'While working with {txt_p} and {table}')
except:
pass
func = sys._getframe().f_code.co_name
table_d['Error'] = (arcpy.AddError(arcpyErr(func)), '', [])
return table_d
except:
try:
del iCur
except:
pass
try:
arcpy.AddError(f'While working with {txt_p} and {table}')
arcpy.AddError(f"{row= }")
except:
pass
func = sys._getframe().f_code.co_name
table_d['Error'] = (arcpy.AddError(arcpyErr(func)), '', [])
return table_d
def updateMetadata(gdb_p: str,
survey_i: str,
st: str,
fy: str
) -> list[str]:
""" Used for featureclass and geodatabase metadata. Does not do individual
tables. Reads and edits the original metadata object and then exports the
edited version back to the featureclass or geodatabase.
Parameters
----------
gdb_p : str
Path of the SSURGO geodatabase.
survey_i : str
Summary string of the Survey Area Version date by soil survey.
st : str
Abbreviation of the state
fy: str
Fiscal year of publication
Returns
-------
list[str]
Collection of messages, no messages means function was completely
successful.
"""
try:
msg = []
gdb_n = os.path.basename(gdb_p)
msgAppend = msg.append
states = {
'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas',
'AS': 'American Samoa', 'AZ': 'Arizona', 'CA': 'California',
'CO': 'Colorado', 'CT': 'Connecticut', 'DC': 'District of Columbia',
'DE': 'Delaware', 'FL': 'Florida', 'GA': 'Georgia', 'GU': 'Guam',
'HI': 'Hawaii', 'IA': 'Iowa', 'ID': 'Idaho', 'IL': 'Illinois',
'IN': 'Indiana', 'KS': 'Kansas', 'KY': 'Kentucky',
'LA': 'Louisiana', 'MA': 'Massachusetts', 'MD': 'Maryland',
'ME': 'Maine', 'MI': 'Michigan', 'MN': 'Minnesota',
'MO': 'Missouri', 'MS': 'Mississippi', 'MT': 'Montana',
'NC': 'North Carolina', 'ND': 'North Dakota', 'NE': 'Nebraska',
'NH': 'New Hampshire', 'NJ': 'New Jersey', 'NM': 'New Mexico',
'NV': 'Nevada', 'NY': 'New York', 'OH': 'Ohio', 'OK': 'Oklahoma',
'OR': 'Oregon', 'PA': 'Pennsylvania',
'PRUSVI': "Puerto Rico and U.S. Virgin Islands",
'RI': 'Rhode Island', 'SC': 'South Carolina', 'SD': 'South Dakota',
'TN': 'Tennessee', 'TX': 'Texas', 'UT': 'Utah', 'VA': 'Virginia',
'VT': 'Vermont', 'WA': 'Washington', 'WI': 'Wisconsin',
'WV': 'West Virginia', 'WY': 'Wyoming'
}
state = states[st]
# initial metadata exported from current target featureclass
meta_export = env.scratchFolder + f"/xxExport_{gdb_n}.xml"
# the metadata xml that will provide the updated info
meta_import = env.scratchFolder + f"/xxImport_{gdb_n}.xml"
# Cleanup XML files from previous runs
if os.path.isfile(meta_import):
os.remove(meta_import)
if os.path.isfile(meta_export):
os.remove(meta_export)
meta_src = arcpy.metadata.Metadata(gdb_p)
meta_src.exportMetadata(meta_export, 'FGDC_CSDGM')
# Set date strings for metadata, based upon today's date
d = datetime.date.today()
month = d.strftime("%B")
# ---- call getLastDate
tbl = gdb_p + "/SACATALOG"
sqlClause = [None, "ORDER BY SAVEREST DESC"]
sCur = arcpy.da.SearchCursor(
tbl, ['SAVEREST'], sql_clause = sqlClause
)
row = next(sCur)[0]
lastDate = row.strftime('%Y%m%d')
del sCur
# Parse exported XML metadata file
# Convert XML to tree format
tree = ET.parse(meta_export)
root = tree.getroot()
# new citeInfo has title.text, edition.text, serinfo/issue.text
for child in root.findall('idinfo/citation/citeinfo/'):
if child.tag == "title":
if child.text.find('xxSTATExx') >= 0:
child.text = child.text.replace('xxSTATExx', state)
if child.text.find('xxFYxx') >= 0:
child.text = child.text.replace('xxFYxx', fy)
# elif place_str != "":
# child.text = child.text + " - " + description
elif child.tag == "edition":
if child.text == 'xxFYxx':
child.text = fy
elif child.tag == "serinfo":
for subchild in child.iter('issue'):
if subchild.text == "xxFYxx":
subchild.text = fy
# Update place keywords
ePlace = root.find('idinfo/keywords/place')
for child in ePlace.iter('placekey'):
if child.text == "xxSTATExx":
child.text = state
elif child.text == "xxSURVEYSxx":
child.text = survey_i
# Update credits
eIdInfo = root.find('idinfo')
for child in eIdInfo.iter('datacred'):
# sCreds = child.text
if child.text.find("xxSTATExx") >= 0:
child.text = child.text.replace("xxSTATExx", state)
if child.text.find("xxFYxx") >= 0:
child.text = child.text.replace("xxFYxx", fy)
if child.text.find("xxTODAYxx") >= 0:
child.text = child.text.replace("xxTODAYxx", lastDate)
# Update Summary
idDescrip = root.find('idinfo/descript')
for child in idDescrip.iter('purpose'):
if child.text.find("xxFYxx") >= 0:
child.text = child.text.replace("xxFYxx", fy)
if child.text.find("xxMONTHxx") >= 0:
child.text = child.text.replace("xxMONTHxx", month)
if child.text.find("xxSTATExx") >= 0:
child.text = child.text.replace("xxSTATExx", state)
procDates = root.find('dataqual/lineage')
if not procDates is None:
for child in procDates.iter('procdate'):
sDate = child.text
if sDate.find('xxTODAYxx'):
child.text = lastDate
else:
msgAppend("Process date not found")
# create new xml file which will be imported,
# thereby updating the table's metadata
tree.write(
meta_import,
encoding = "utf-8",
xml_declaration = None,
default_namespace = None,
method = "xml"
)
# import updated metadata to the geodatabase feature
meta_src.importMetadata(meta_import, "FGDC_CSDGM")
meta_src.deleteContent('GPHISTORY')
meta_src.save()
# delete the temporary xml metadata files
if os.path.isfile(meta_import):
os.remove(meta_import)
# if os.path.isfile(meta_export):
# os.remove(meta_export)
del meta_src
return msg
except arcpy.ExecuteError:
try:
tree.write(
meta_import,
encoding = "utf-8",
xml_declaration = None,
default_namespace = None,
method = "xml"
)
meta_src.save()
del meta_src
except:
pass
func = sys._getframe().f_code.co_name
msgAppend(arcpy.AddError(arcpyErr(func)))
return msg
except:
try:
tree.write(
meta_import,
encoding = "utf-8",
xml_declaration = None,
default_namespace = None,
method = "xml"
)
meta_src.save()
del meta_src
except:
pass
func = sys._getframe().f_code.co_name
msgAppend(arcpy.AddError(pyErr(func)))
return msg
def gSSURGO(input_p: str,
gdb_p: str,
module_p: str,
gssurgo_v: str,
v: str,
st: str,
fy: int
) -> str:
"""This function is the backbone of the module.
It calls these functions to create and populate a SSURGO geodatabase:
1) ``CreateGDB`` to create a geodatabase using an xml template
2) ``importSing`` imports tabels that are idential in each SSURGO folder.
3) ``importSet`` imports tabels that are largely indentical, with some
novelty.
4) ``importList`` imports tabels with unique information to each SSURGO
dataset.
5) ``createTableRelationships`` Establishes relationships between tables
to other tables or spatial features.
6) ``updateMetadata`` Update the geodatabase and spatial features
metadata.
Parameters
----------
input_p : str
Directory locatoin of the SSURGO downloads.
gdb_p : str
The path of the SSURGO file geodatabase to be created.
module_p : str
The module tool directory with the xml files.
gssurgo_v : str
The gssurgo version
v : str
The tool version
st : str
State abreviation
fy : int
fiscal year of publication
Returns
-------
str
Returns an empty string if a SSURGO geogdatabase is successfully
created, otherwise returns an error message.
"""
try:
env.overwriteOutput= True
gdb_n = os.path.basename(gdb_p)
gdb_n = gdb_n.replace("-", "_")
date_format = "(%Y-%m-%d)"
# Get the XML Workspace Document appropriate for the specified aoi
# %% check 1
# ---- make xml
inputXML = xml("Lower 48 States", module_p, gssurgo_v)
if not inputXML.exist:
arcpy.AddError(" \nMissing xml file: " + inputXML.xml)
return False
# %% check 1
# ---- call createGDB
gdb_b = createGDB(gdb_p, inputXML)
if not gdb_b:
arcpy.AddMessage(f"Didn't successfully create {gdb_n}\n")
return False
# ---- call importSing
arcpy.SetProgressorLabel("Importing constant tables")
table_d = importSing(input_p, gdb_p)
if 'Error' in table_d:
arcpy.AddError(table_d['Error'])
return
arcpy.SetProgressorLabel("Importing table sets")
msg = importSet(input_p, gdb_p, table_d)
if msg:
arcpy.AddError(msg)
return
# Tables which are unique to each SSURGO soil survey area
arcpy.SetProgressorLabel("Importing unique tables")
tabs_uniq = [
'component', 'cosurfmorphhpp', 'legend', 'chunified','cocropyld',
'chtexturegrp', 'cosurfmorphss', 'coforprod', 'sacatalog',
'cosurfmorphgc', 'cotaxmoistcl', 'chtext', 'chconsistence',
'chtexture', 'copmgrp', 'cosoilmoist', 'mucropyld', 'chtexturemod',
'cotext', 'coecoclass', 'cosurfmorphmr', 'cosurffrags',
'cotreestomng', 'cosoiltemp', 'sainterp', 'chstructgrp',
'distlegendmd', 'copwindbreak', 'chdesgnsuffix', 'corestrictions',
'cotaxfmmin', 'chstruct', 'chfrags', 'coforprodo', 'distmd',
'mutext', 'legendtext', 'muaggatt', 'chorizon', 'cohydriccriteria',
'chpores', 'chaashto', 'coerosionacc', 'copm', 'comonth',
'muaoverlap', 'cotxfmother', 'mapunit', 'coeplants', 'laoverlap',
'cogeomordesc', 'codiagfeatures', 'cocanopycover'
]
# Exclude these cointerp columns
# interpll, interpllc, interplr, interplrc, interphh, interphhc
exclude_i = {8, 9, 10, 11, 14, 15}
table_d['cointerp'][2] = [
cols for cols in table_d['cointerp'][2] if cols[0] not in exclude_i
]
if gssurgo_v != '1.0':
tabs_uniq.remove('sainterp')
# If light, exclude interp rules, except NCCPI
else:
co_out = importCoint(input_p, gdb_p, table_d)
if co_out:
arcpy.AddError(co_out)
return False
# Create parameter dictionary with gdb table name and text file folder
paramSet = [
{'table': tab} for tab in tabs_uniq
]
constSet = {
'input_p': input_p,
'gdb_p': gdb_p,
'table_d': table_d
}
# threadCount = 1 #psutil.cpu_count() // psutil.cpu_count(logical=False)
# arcpy.AddMessage(f"{threadCount= }")
ti = time.time()
import_jobs = funYield(importList, paramSet, constSet)
for paramBack, output in import_jobs:
# for paramBack in paramSet:
# output = importList(**paramBack, **constSet)
try:
# if not output:
# arcpy.AddMessage(
# f"\tSuccessfully populated {paramBack['table']}"
# )
# else:
if output:
# arcpy.AddError(f"Failed to populate {paramBack['table']}")
arcpy.AddError(output)
return
except GeneratorExit:
arcpy.AddWarning("passed")
arcpy.AddWarning(f"{paramBack}")
arcpy.AddWarning(f"{output}")
pass
import_jobs.close()
del import_jobs
gc.collect()
# arcpy.AddMessage(f"time: {time.time() - ti}")
if not versionTab(input_p, gdb_p, gssurgo_v, v):
arcpy.AddWarning('Version table failed to populate successfully.')
if gssurgo_v != '1.0':
table_d['mdruleclass'] = ['NA', 'Rule Class Text Metadata', ()]
table_d['mdrule'] = ['NA', 'Interpretation Rules Metadata', ()]
table_d['mdinterp'] = ['NA', 'Interpretations Metadata', ()]
msg = schemaChange(
gdb_p, input_p, module_p, table_d)
# if msg:
# arcpy.AddWarning(msg)
# Create Indices
if not createIndices(gdb_p, module_p, gssurgo_v):
arcpy.AddWarning(
"Failed to create indices which may imparct efficient use of "
"database."
)
# Create table relationships and indexes
# ---- call createTableRelationships
rel_b = createTableRelationships(gdb_p)
if not rel_b:
return False
# Query the output SACATALOG table to get list of surveys that were
# exported to the gSSURGO
arcpy.AddMessage("\tUpdating metadata...")
tab_sac = f"{gdb_p}/sacatalog"
# Areasymbol and Survey Area Version Established
sCur = arcpy.da.SearchCursor(tab_sac, ["AREASYMBOL", "SAVEREST"])
export_query = [
(f"{ssa} {date_obj.strftime(date_format)}", f"'{ssa}'")
for ssa, date_obj in sCur
]
del sCur
# survey_i format: NM007 (2022-09-08)
# query_i format: 'NM007'
survey_i, query_i = map(','.join, zip(*export_query))
# Update metadata for the geodatabase and all featureclasses
arcpy.SetProgressorLabel("Updating metadata...")
msgs = updateMetadata(gdb_p, survey_i, st, str(fy))
if msgs:
for msg in msgs:
arcpy.AddError(msg)
arcpy.SetProgressorLabel("\tCompacting new database...")
arcpy.Compact_management(gdb_p)