-
Notifications
You must be signed in to change notification settings - Fork 2
/
SSURGO_Convert_to_Geodatabase.py
2950 lines (2275 loc) · 125 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
# SSURGO_Convert_to_Geodatabase.py
#
# ArcGIS 10.1 (10.2 mostly works except for automtically updating metadata)
#
# Steve Peaslee, National Soil Survey Center, Lincoln, Nebraska
#
# Purpose: allow batch appending of SSURGO soil shapefiles and soil attribute tables into a single file geodatabase (10.0).
# Requires input dataset structure to follow the NRCS standard for Geospatial data (eg. soil_ne109\spatial and soil_ne109/tabular)
#
# Merge order is based upon sorted extent coordinates
# For the attribute data, we use an XML workspace document to define FGDB schema and read the tables from the SSURGO template database.
# These xml files should reside in the same folder as this script. See the GetML function for more info.
#
# Things yet to do:
#
# 1. Update metadata for each XML workspace document
# 2. Test implementation of ITRF00 datum transformation
# 11-15-2013 Added 'bailout' if one of the input template database tables is not found
# 11-22-2013
# 12-09-2013 Added option for automatically inserting featureclass alias for ArcGIS 10.1 and above
#
# 12-13-2013 Changed datum transformation method to always use ITRF00
#
# 01-04-2014 Added tabular metadata and automated the inclusion of state name and soil survey areas to metadata.
# 01-08-2014 Still need to automate metadata dates and gSSURGO process steps
# 01-09-2014 Removed hard-coded path to XML metadata translator file to make it 10.2 compatible
# 2014-09-27
# 2014-10-31 Added text file import to this script. Need to clean this up and make
# it an option to the normal Access database import.
#
# In 2014, the folders within the WSS-SSURGO Download zipfiles were renamed to AREASYMBOL (uppercase)
# instead of soil_[AREASYMBOL]
# 2015-10-21 Modified tabular import to truncate string values to match field length
#
# 2015-11-13 Added import for metadata files so that up-to-date information will be used. These
# tables have information about tables, columns, relationships and domain values.
#
# 2015-12-08 Added check for SSURGO version number (schema version). Hardcoded as 2 for gSSURGO.
#
# 2015-12-15 Incorporated primary key unique value constraint on sdv* tables as is done for the Access databases.
#
# 2016-03-15 Tabular import now uses CP1252 so that csv import of ESIS data won't error.
#
# 2017-06-28 Problem with metadata import.
# arcpy.ExportMetadata_conversion (target, mdTranslator, mdExport)
# <class 'arcgisscripting.ExecuteError'>: Failed to execute. Parameters are not valid.
# ERROR 000584: Implementation of this Tool's Validate is invalid
#
# 2017-08-16 Added attribute index on rulekey, mrulekey for cointerp table.
# Need to remove DVD option from Transfer in XML Workspace document and
# replace with hard drive option.
# Offline media: External Drive
# Recording format: NTFS 3.0
# 2018-11-27. Fixed recent problem with relationshipclasses. Origin and destination tables were switched resulting in key-null errors if
# an attempt was made to delete any records.
# 2019-09-24. Remove the following columns from cointerp table and modified the .csv import:
#
# interpll
# interpllc
# interplr
# interplrc
# interphh
# interphhc
# 2020-03-30. Removed the above columns from the ImportTables function as well.
## ===================================================================================
class MyError(Exception):
pass
## ===================================================================================
def errorMsg():
try:
excInfo = sys.exc_info()
tb = excInfo[2]
tbinfo = traceback.format_tb(tb)[0]
theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n"
PrintMsg(theMsg, 2)
except:
PrintMsg("Unhandled error in errorMsg method", 2)
pass
## ===================================================================================
def PrintMsg(msg, severity=0):
# Adds tool message to the geoprocessor
#
#Split the message on \n first, so that if it's multiple lines, a GPMessage will be added for each line
try:
for string in msg.split('\n'):
#Add a geoprocessing message (in case this is run as a tool)
if severity == 0:
arcpy.AddMessage(string)
elif severity == 1:
arcpy.AddWarning(string)
elif severity == 2:
arcpy.AddError(" \n" + string)
except:
pass
## ===================================================================================
def Number_Format(num, places=0, bCommas=True):
try:
# Format a number according to locality and given places
locale.setlocale(locale.LC_ALL, "")
if bCommas:
theNumber = locale.format("%.*f", (places, num), True)
else:
theNumber = locale.format("%.*f", (places, num), False)
return theNumber
except:
errorMsg()
#PrintMsg("Unhandled exception in Number_Format function (" + str(num) + ")", 2)
return "???"
## ===================================================================================
def AddNewFields(outputShp, columnNames, columnInfo):
# TEMPORARY CODE
#
# Create the empty output table that will contain the data from Soil Data Access
#
# ColumnNames and columnInfo come from the Attribute query JSON string
# MUKEY would normally be included in the list, but it should already exist in the output featureclass
#
# Problem using temporary, IN_MEMORY table and JoinField with shapefiles to add new columns. Really slow performance.
try:
# Dictionary: SQL Server to FGDB
#PrintMsg(" \nAddNewFields function begins", 1)
dType = dict()
dType["int"] = "long"
dType["smallint"] = "short"
dType["bit"] = "short"
dType["varbinary"] = "blob"
dType["nvarchar"] = "text"
dType["varchar"] = "text"
dType["char"] = "text"
dType["datetime"] = "date"
dType["datetime2"] = "date"
dType["smalldatetime"] = "date"
dType["decimal"] = "double"
dType["numeric"] = "double"
dType["float"] ="double"
# numeric type conversion depends upon the precision and scale
dType["numeric"] = "float" # 4 bytes
dType["real"] = "double" # 8 bytes
# Iterate through list of field names and add them to the output table
i = 0
# ColumnInfo contains:
# ColumnOrdinal, ColumnSize, NumericPrecision, NumericScale, ProviderType, IsLong, ProviderSpecificDataType, DataTypeName
#PrintMsg(" \nFieldName, Length, Precision, Scale, Type", 1)
joinedFields = list() # new fields that need to be added to the output table
dataFields = list() # fields that need to be updated in the AttributeRequest function
outputTbl = os.path.join("IN_MEMORY", "Template")
#arcpy.CreateTable_management(os.path.dirname(outputTbl), os.path.basename(outputTbl))
# Get a list of fields that already exist in outputShp
outFields = arcpy.Describe(outputShp).fields
existingFields = [fld.name.lower() for fld in outFields]
# Using JoinField to add the NATMUSYM column to the outputTbl (but not the data)
#
for i, fldName in enumerate(columnNames):
# Get new field definition from columnInfo dictionary
vals = columnInfo[i].split(",")
length = int(vals[1].split("=")[1])
precision = int(vals[2].split("=")[1])
scale = int(vals[3].split("=")[1])
dataType = dType[vals[4].lower().split("=")[1]]
#if not fldName.lower() == "mukey":
# joinedFields.append(fldName)
if not fldName.lower() in existingFields:
# This is a new data field that needs to be added to the output table.
#arcpy.AddField_management(outputTbl, fldName, dataType, precision, scale, length) # add to IN_MEMORY table
arcpy.AddField_management(outputShp, fldName, dataType, precision, scale, length) # add direct to featureclass
joinedFields.append(fldName)
dataFields.append(fldName)
elif fldName.lower() in existingFields and fldName.lower() != "mukey":
# This is an existing data field in the output table.
dataFields.append(fldName)
elif fldName.lower() == "mukey":
#arcpy.AddField_management(outputTbl, fldName, dataType, precision, scale, length)
pass
if arcpy.Exists(outputTbl) and len(joinedFields) > 0:
#PrintMsg(" \nAdded these new fields to " + os.path.basename(outputShp) + ": " + ", ".join(joinedFields), 1)
#arcpy.JoinField_management(outputShp, "mukey", outputTbl, "mukey", joinedFields) # instead add directly to output featureclass
arcpy.Delete_management(outputTbl)
return dataFields
else:
#PrintMsg(" \nThese fields already exist in the output table: " + ", ".join(dataFields), 1)
arcpy.Delete_management(outputTbl)
return dataFields
except:
errorMsg()
return ["Error"]
## ===================================================================================
def GetSDMInfo(theURL, tblName):
# TEMPORARY CODE
#
# POST REST which uses urllib and JSON
#
# Send query to SDM Tabular Service, returning data in JSON format
try:
if theURL == "":
theURL = "https://sdmdataaccess.sc.egov.usda.gov"
sQuery = """SELECT TOP 1 * FROM """ + tblName
#PrintMsg(" \nRequesting tabular data for " + Number_Format(len(keyList), 0, True) + " soil survey areas...")
arcpy.SetProgressorLabel("Sending tabular request for " + tblName + " to Soil Data Access...")
if sQuery == "":
raise MyError, ""
# Tabular service to append to SDA URL
url = theURL + "/Tabular/SDMTabularService/post.rest"
dRequest = dict()
dRequest["format"] = "JSON+COLUMNNAME+METADATA"
dRequest["query"] = sQuery
#PrintMsg(" \nURL: " + url)
#PrintMsg("FORMAT: " + dRequest["FORMAT"])
#PrintMsg("QUERY: " + sQuery)
# Create SDM connection to service using HTTP
jData = json.dumps(dRequest)
# Send request to SDA Tabular service
req = urllib2.Request(url, jData)
resp = urllib2.urlopen(req)
#PrintMsg(" \nImporting attribute data...", 0)
#PrintMsg(" \nGot back requested data...", 0)
# Read the response from SDA into a string
jsonString = resp.read()
#PrintMsg(" \njsonString: " + str(jsonString), 1)
data = json.loads(jsonString)
del jsonString, resp, req
if not "Table" in data:
raise MyError, "Query failed to select anything: \n " + sQuery
dataList = data["Table"] # Data as a list of lists. Service returns everything as string.
arcpy.SetProgressorLabel("Adding new fields to output table...")
PrintMsg(" \nRequested data consists of " + Number_Format(len(dataList), 0, True) + " records", 0)
# Get column metadata from first two records
columnNames = dataList.pop(0)
columnInfo = dataList.pop(0)
if len(noMatch) > 0:
PrintMsg(" \nNo attribute data for mukeys: " + str(noMatch), 1)
arcpy.SetProgressorLabel("Finished importing attribute data")
PrintMsg(" \nImport complete... \n ", 0)
return True
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return False
except urllib2.HTTPError:
errorMsg()
PrintMsg(" \n" + sQuery, 1)
return False
except:
errorMsg()
return False
## ===================================================================================
def SetScratch():
# try to set scratchWorkspace and scratchGDB if null
# SYSTEMDRIVE
# APPDATA C:\Users\adolfo.diaz\AppData\Roaming
# USERPROFILE C:\Users\adolfo.diaz
try:
envVariables = os.environ
for var, val in envVariables.items():
PrintMsg("\tSystem: " + str(var) + ": " + str(val), 1)
environments = arcpy.ListEnvironments()
# Sort the environment names
environments.sort()
for ev in environments:
# Format and print each environment and its current setting.
# (The environments are accessed by key from arcpy.env.)
#PrintMsg("{0:<30}: {1}".format(environment, arcpy.env[environment]), 1)
PrintMsg("\tGP: " + ev + "\t" + str(env[ev]), 1)
if env.scratchWorkspace is None:
#PrintMsg("\tWarning. Scratchworkspace has not been set for the geoprocessing environment", 1)
env.scratchWorkspace = env.scratchFolder
PrintMsg("\nThe scratch geodatabase has been set to: " + str(env.scratchGDB), 1)
elif str(env.scratchWorkspace).lower().endswith("default.gdb"):
PrintMsg("\tChanging scratch geodatabase from Default.gdb", 1)
env.scratchWorkspace = env.scratchFolder
PrintMsg("\tTo: " + str(env.scratchGDB), 1)
#else:
# PrintMsg(" \nOriginal Scratch Geodatabase is OK: " + env.scratchGDB, 1)
if env.scratchGDB:
return True
else:
return False
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e) + " \n ", 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def SetOutputCoordinateSystem(inLayer, AOI):
#
# Not being used any more!
#
# The GetXML function is now used to set the XML workspace
# document and a single NAD1983 to WGS1984 datum transformation (ITRF00) is now being used.
#
# Below is a description of the 2013 settings
# Set a hard-coded output coordinate system (Geographic WGS 1984)
# Set an ESRI datum transformation method for NAD1983 to WGS1984
# Based upon ESRI 10.1 documentation and the methods that were used to
# project SDM featureclasses during the transition from ArcSDE to SQL Server spatial
#
# CONUS - NAD_1983_To_WGS_1984_5
# Hawaii and American Samoa- NAD_1983_To_WGS_1984_3
# Alaska - NAD_1983_To_WGS_1984_5
# Puerto Rico and U.S. Virgin Islands - NAD_1983_To_WGS_1984_5
# Other - NAD_1983_To_WGS_1984_1 (shouldn't run into this case)
try:
outputSR = arcpy.SpatialReference(4326) # GCS WGS 1984
# Get the desired output geographic coordinate system name
outputGCS = outputSR.GCS.name
# Describe the input layer and get the input layer's spatial reference, other properties
desc = arcpy.Describe(inLayer)
dType = desc.dataType
sr = desc.spatialReference
srType = sr.type.upper()
inputGCS = sr.GCS.name
# Print name of input layer and dataype
if dType.upper() == "FEATURELAYER":
#PrintMsg(" \nInput " + dType + ": " + desc.nameString, 0)
inputName = desc.nameString
elif dType.upper() == "FEATURECLASS":
#PrintMsg(" \nInput " + dType + ": " + desc.baseName, 0)
inputName = desc.baseName
else:
#PrintMsg(" \nInput " + dType + ": " + desc.name, 0)
inputName = desc.name
if outputGCS == inputGCS:
# input and output geographic coordinate systems are the same
# no datum transformation required
#PrintMsg(" \nNo datum transformation required", 0)
tm = ""
else:
# Different input and output geographic coordinate systems, set
# environment to unproject to WGS 1984, matching Soil Data Mart
tm = "WGS_1984_(ITRF00)_To_NAD_1983"
# These next two lines set the output coordinate system environment
arcpy.env.outputCoordinateSystem = outputSR
arcpy.env.geographicTransformations = tm
return True
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e) + " \n", 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def CreateSSURGO_DB(outputWS, inputXML, areasymbolList, aliasName):
# Create new 10.0 File Geodatabase using XML workspace document
#
try:
if not arcpy.Exists(inputXML):
PrintMsg(" \nMissing input file: " + inputXML, 2)
return False
outputFolder = os.path.dirname(outputWS)
gdbName = os.path.basename(outputWS)
if arcpy.Exists(os.path.join(outputFolder, gdbName)):
arcpy.Delete_management(os.path.join(outputFolder, gdbName))
PrintMsg(" \nCreating new geodatabase (" + gdbName + ") in " + outputFolder, 0)
env.XYResolution = "0.001 Meters"
env.XYTolerance = "0.01 Meters"
arcpy.CreateFileGDB_management(outputFolder, gdbName, "10.0")
# The following command will fail when the user only has a Basic license
arcpy.ImportXMLWorkspaceDocument_management(os.path.join(outputFolder, gdbName), inputXML, "SCHEMA_ONLY")
# Create indexes for cointerp here.
# If it works OK, incorporate these indexes into the xml workspace document
try:
pass
except:
PrintMsg(" \nUnable to index the cointerp table", 1)
if not arcpy.Exists(os.path.join(outputFolder, gdbName)):
raise MyError, "Failed to create new geodatabase"
env.workspace = os.path.join(outputFolder, gdbName)
tblList = arcpy.ListTables()
if len(tblList) < 50:
raise MyError, "Output geodatabase has only " + str(len(tblList)) + " tables"
# Alter aliases for featureclasses
if aliasName != "":
try:
arcpy.AlterAliasName("MUPOLYGON", "Map Unit Polygons - " + aliasName)
arcpy.AlterAliasName("MUPOINT", "Map Unit Points - " + aliasName)
arcpy.AlterAliasName("MULINE", "Map Unit Lines - " + aliasName)
arcpy.AlterAliasName("FEATPOINT", "Special Feature Points - " + aliasName)
arcpy.AlterAliasName("FEATLINE", "Special Feature Lines - " + aliasName)
arcpy.AlterAliasName("SAPOLYGON", "Survey Boundaries - " + aliasName)
except:
pass
arcpy.RefreshCatalog(outputFolder)
return True
except MyError, e:
PrintMsg(str(e), 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def GetTableList(outputWS):
# Query mdstattabs table to get list of input text files (tabular) and output tables
# This function assumes that the MDSTATTABS table is already present and populated
# in the output geodatabase per XML Workspace Document.
#
# Skip all 'MDSTAT' tables. They are static.
#
try:
tblList = list()
mdTbl = os.path.join(outputWS, "mdstattabs")
if not arcpy.Exists(outputWS):
raise MyError, "Missing output geodatabase: " + outputWS
if not arcpy.Exists(mdTbl):
raise MyError, "Missing mdstattabs table in output geodatabase"
else:
# got the mdstattabs table, create list
#mdFields = ('tabphyname','iefilename')
mdFields = ('tabphyname')
with arcpy.da.SearchCursor(mdTbl, mdFields) as srcCursor:
for rec in srcCursor:
tblName = rec[0]
if not tblName.startswith('mdstat') and not tblName in ('mupolygon', 'muline', 'mupoint', 'featline', 'featpoint', 'sapolygon'):
tblList.append(rec[0])
#PrintMsg(" \nTables to import: " + ", ".join(tblList), 0)
return tblList
except MyError, e:
PrintMsg(str(e), 2)
return []
except:
errorMsg()
return []
## ===================================================================================
def GetLastDate(inputDB):
# Get the most recent date 'YYYYMMDD' from SACATALOG.SAVEREST and use it to populate metadata
#
try:
tbl = os.path.join(inputDB, "SACATALOG")
today = ""
sqlClause = [None, "ORDER BY SAVEREST DESC"]
with arcpy.da.SearchCursor(tbl, ['SAVEREST'], sql_clause=sqlClause ) as cur:
for rec in cur:
lastDate = rec[0].strftime('%Y%m%d')
break
return lastDate
except MyError, e:
# Example: raise MyError("this is an error message")
PrintMsg(str(e) + " \n", 2)
return ""
except:
errorMsg()
return ""
## ===================================================================================
def GetTemplateDate(newDB, areaSym):
# Get SAVEREST date from previously existing Template database
# Use it to compare with the date from the WSS dataset
# If the existing database is same or newer, it will be kept and the WSS version skipped.
# This function is also used to test the output geodatabase to make sure that
# the tabular import process was successful.
#
try:
if not arcpy.Exists(newDB):
return 0
saCatalog = os.path.join(newDB, "SACATALOG")
dbDate = 0
whereClause = "UPPER(AREASYMBOL) = '" + areaSym.upper() + "'"
#PrintMsg(" \nWhereClause for sacatalog: " + areaSym, 1)
if arcpy.Exists(saCatalog):
with arcpy.da.SearchCursor(saCatalog, ("SAVEREST"), where_clause=whereClause) as srcCursor:
for rec in srcCursor:
dbDate = str(rec[0]).split(" ")[0]
del saCatalog
del newDB
return dbDate
else:
# unable to open SACATALOG table in existing dataset
return 0
except:
errorMsg()
return 0
## ===================================================================================
def SSURGOVersionTxt(tabularFolder):
# For future use. Should really create a new table for gSSURGO in order to implement properly.
#
# Get SSURGO version from the Template database "SYSTEM Template Database Information" table
# or from the tabular/version.txt file, depending upon which is being imported.
# Compare the version number (first digit) to a hardcoded version number which should
# be theoretically tied to the XML workspace document that accompanies the scripts.
try:
# Get SSURGOversion number from version.txt
versionTxt = os.path.join(tabularFolder, "version.txt")
if arcpy.Exists(versionTxt):
# read just the first line of the version.txt file
fh = open(versionTxt, "r")
txtVersion = int(fh.readline().split(".")[0])
fh.close()
return txtVersion
else:
# Unable to compare vesions. Warn user but continue
PrintMsg("Unable to find tabular file: version.txt", 1)
return 0
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return 0
except:
errorMsg()
return 0
## ===================================================================================
def SSURGOVersionDB(templateDB):
# For future use. Should really create a new table for gSSURGO in order to implement properly.
#
# Get SSURGO version from the Template database "SYSTEM Template Database Information" table
try:
if not arcpy.Exists(templateDB):
raise MyError, "Missing input database (" + newDB + ")"
systemInfo = os.path.join(templateDB, "SYSTEM - Template Database Information")
if arcpy.Exists(systemInfo):
# Get SSURGO Version from template database
dbVersion = 0
with arcpy.da.SearchCursor(systemInfo, "*", "") as srcCursor:
for rec in srcCursor:
if rec[0] == "SSURGO Version":
dbVersion = int(str(rec[2]).split(".")[0])
#PrintMsg("\tSSURGO Version from DB: " + dbVersion, 1)
del systemInfo
del templateDB
return dbVersion
else:
# Unable to open SYSTEM table in existing dataset
# Warn user but continue
raise MyError, "Unable to open 'SYSTEM - Template Database Information'"
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return 0
except:
errorMsg()
return 0
## ===============================================================================================================
def GetTableInfo(newDB):
# Adolfo's function
#
# Retrieve physical and alias names from MDSTATTABS table and assigns them to a blank dictionary.
# Stores physical names (key) and aliases (value) in a Python dictionary i.e. {chasshto:'Horizon AASHTO,chaashto'}
# Fieldnames are Physical Name = AliasName,IEfilename
try:
tblInfo = dict()
# Open mdstattabs table containing information for other SSURGO tables
theMDTable = "mdstattabs"
env.workspace = newDB
# Establishes a cursor for searching through field rows. A search cursor can be used to retrieve rows.
# This method will return an enumeration object that will, in turn, hand out row objects
if arcpy.Exists(os.path.join(newDB, theMDTable)):
fldNames = ["tabphyname","tablabel","iefilename"]
with arcpy.da.SearchCursor(os.path.join(newDB, theMDTable), fldNames) as rows:
for row in rows:
# read each table record and assign 'tabphyname' and 'tablabel' to 2 variables
physicalName = row[0]
aliasName = row[1]
importFileName = row[2]
# i.e. {chaashto:'Horizon AASHTO',chaashto}; will create a one-to-many dictionary
# As long as the physical name doesn't exist in dict() add physical name
# as Key and alias as Value.
#if not physicalName in tblAliases:
if not importFileName in tblInfo:
#PrintMsg("\t" + importFileName + ": " + physicalName, 1)
tblInfo[importFileName] = physicalName, aliasName
del theMDTable
return tblInfo
else:
# The mdstattabs table was not found
raise MyError, "Missing mdstattabs table"
return tblInfo
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return False
except:
errorMsg()
return dict()
## ===================================================================================
def ImportMDTables(newDB, dbList):
# Import as single set of metadata tables from first survey area's Access database
# These tables contain table information, relationship classes and domain values
# They have tobe populated before any of the other tables
#
# mdstatdomdet
# mdstatdommas
# mdstatidxdet
# mdstatidxmas
# mdstatrshipdet
# mdstatrshipmas
# mdstattabcols
# mdstattabs
try:
#PrintMsg(" \nImporting metadata tables from " + tabularFolder, 1)
# Create list of tables to be imported
tables = ['mdstatdommas', 'mdstatidxdet', 'mdstatidxmas', 'mdstatrshipdet', 'mdstatrshipmas', 'mdstattabcols', 'mdstattabs', 'mdstatdomdet']
accessDB = dbList[0] # source database for metadata table data
# Process list of text files
#
for table in tables:
arcpy.SetProgressorLabel("Importing " + table + "...")
inTbl = os.path.join(accessDB, table)
outTbl = os.path.join(newDB, table)
if arcpy.Exists(inTbl) and arcpy.Exists(outTbl):
# Create cursor for all fields to populate the current table
#
# For a geodatabase, I need to remove OBJECTID from the fields list
fldList = arcpy.Describe(outTbl).fields
fldNames = list()
fldLengths = list()
for fld in fldList:
if fld.type != "OID":
fldNames.append(fld.name.lower())
if fld.type.lower() == "string":
fldLengths.append(fld.length)
else:
fldLengths.append(0)
if len(fldNames) == 0:
raise MyError, "Failed to get field names for " + tbl
with arcpy.da.InsertCursor(outTbl, fldNames) as outcur:
incur = arcpy.da.SearchCursor(inTbl, fldNames)
# counter for current record number
iRows = 0
#try:
# Use csv reader to read each line in the text file
for row in incur:
# replace all blank values with 'None' so that the values are properly inserted
# into integer values otherwise insertRow fails
# truncate all string values that will not fit in the target field
newRow = list()
fldNo = 0
for val in row: # mdstatdomdet was having problems with this 'for' loop. No idea why.
fldLen = fldLengths[fldNo]
if fldLen > 0 and not val is None:
val = val[0:fldLen]
newRow.append(val)
fldNo += 1
try:
outcur.insertRow(newRow)
except:
raise MyError, "Error handling line " + Number_Format(iRows, 0, True) + " of " + txtPath
iRows += 1
if iRows < 63:
# the smallest table (msrmas.txt) currently has 63 records.
raise MyError, tbl + " has only " + str(iRows) + " records"
else:
raise MyError, "Required table '" + tbl + "' not found in " + newDB
return True
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def ImportMDTabular(newDB, tabularFolder, codePage):
# Import a single set of metadata text files from first survey area's tabular
# These files contain table information, relationship classes and domain values
# They have tobe populated before any of the other tables
#
# mdstatdomdet
# mdstatdommas
# mdstatidxdet
# mdstatidxmas
# mdstatrshipdet
# mdstatrshipmas
# mdstattabcols
# mdstattabs
#codePage = 'cp1252'
try:
#PrintMsg(" \nImporting metadata tables from " + tabularFolder, 1)
# Create list of text files to be imported
txtFiles = ['mstabcol', 'msrsdet', 'mstab', 'msrsmas', 'msdommas', 'msidxmas', 'msidxdet', 'msdomdet']
# Create dictionary containing text filename as key, table physical name as value
tblInfo = {u'mstabcol': u'mdstattabcols', u'msrsdet': u'mdstatrshipdet', u'mstab': u'mdstattabs', u'msrsmas': u'mdstatrshipmas', u'msdommas': u'mdstatdommas', u'msidxmas': u'mdstatidxmas', u'msidxdet': u'mdstatidxdet', u'msdomdet': u'mdstatdomdet'}
csv.field_size_limit(128000)
# Process list of text files
for txtFile in txtFiles:
# Get table name and alias from dictionary
if txtFile in tblInfo:
tbl = tblInfo[txtFile]
else:
raise MyError, "Required input textfile '" + txtFile + "' not found in " + tabularFolder
arcpy.SetProgressorLabel("Importing " + tbl + "...")
# Full path to SSURGO text file
txtPath = os.path.join(tabularFolder, txtFile + ".txt")
# continue import process only if the target table exists
if arcpy.Exists(tbl):
# Create cursor for all fields to populate the current table
#
# For a geodatabase, I need to remove OBJECTID from the fields list
fldList = arcpy.Describe(os.path.join(newDB, tbl)).fields
fldNames = list()
fldLengths = list()
for fld in fldList:
if fld.type != "OID":
fldNames.append(fld.name)
if fld.type.lower() == "string":
fldLengths.append(fld.length)
else:
fldLengths.append(0)
if len(fldNames) == 0:
raise MyError, "Failed to get field names for " + tbl
with arcpy.da.InsertCursor(os.path.join(newDB, tbl), fldNames) as cursor:
# counter for current record number
iRows = 1 # input textfile line number
if os.path.isfile(txtPath):
# Use csv reader to read each line in the text file
for rowInFile in csv.reader(open(txtPath, 'rb'), delimiter='|'):
# , quotechar="'"
# replace all blank values with 'None' so that the values are properly inserted
# into integer values otherwise insertRow fails
# truncate all string values that will not fit in the target field
newRow = list()
fldNo = 0
fixedRow = [x.decode(codePage) for x in rowInFile] # handle non-utf8 characters
#.decode('iso-8859-1').encode('utf8')
#fixedRow = [x.decode('iso-8859-1').encode('utf8') for x in rowInFile]
#fixedRow = [x.decode('iso-8859-1') for x in rowInFile]
for val in fixedRow: # mdstatdomdet was having problems with this 'for' loop. No idea why.
fldLen = fldLengths[fldNo]
if val == '':
val = None
elif fldLen > 0:
val = val[0:fldLen]
newRow.append(val)
fldNo += 1
try:
cursor.insertRow(newRow)
except:
raise MyError, "Error handling line " + Number_Format(iRows, 0, True) + " of " + txtPath
iRows += 1
if iRows < 63:
# msrmas.txt has the least number of records
raise MyError, tbl + " has only " + str(iRows) + " records. Check 'md*.txt' files in tabular folder"
else:
raise MyError, "Missing tabular data file (" + txtPath + ")"
else:
raise MyError, "Required table '" + tbl + "' not found in " + newDB
return True
except MyError, e:
# Example: raise MyError, "This is an error message"
PrintMsg(str(e), 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def ImportTables(outputWS, dbList, dbVersion):
#
# Import tables from an Access Template database. Does not require text files, but
# the Access database must be populated and it must reside in the tabular folder and
# it must be named 'soil_d_<AREASYMBOL>.mdb'
# Origin: SSURGO_Convert_to_Geodatabase.py
# Change: 4 columns exist in the .mdb cointerp table but have been removed from the gSSURGO template databases.
try:
tblList = GetTableList(outputWS)
# Something is slowing up the CONUS gSSURGO database creation at the end of this function. Could it be the
# relationshipclasses triggering new indexes?
arcpy.SetProgressorLabel("\tAdding additional relationships for sdv* tables...")
#arcpy.CreateRelationshipClass_management("sdvattribute", "sdvfolderattribute", "xSdvattribute_Sdvfolderattribute", "SIMPLE", "> SDV Folder Attribute Table", "< SDV Attribute Table", "NONE", "ONE_TO_MANY", "NONE", "attributekey", "attributekey", "","")
#PrintMsg(" --> zSdvfolder_Sdvfolderattribute", 1)
#arcpy.CreateRelationshipClass_management("sdvfolder", "sdvfolderattribute", "xSdvfolder_Sdvfolderattribute", "SIMPLE", "> SDV Folder Attribute Table", "< SDV Folder Table", "NONE", "ONE_TO_MANY", "NONE", "folderkey", "folderkey", "","")
if len(tblList) == 0:
raise MyError, "No tables found in " + outputWS
# Set up enforcement of unique keys for SDV tables
#
dIndex = dict() # dictionary storing field index for primary key of each SDV table
dKeys = dict() # dictionary containing a list of key values for each SDV table
dFields = dict() # dictionary containing list of fields for eacha SDV table
keyIndx = dict() # dictionary containing key field index number for each SDV table
keyFields = dict() # dictionary containing a list of key field names for each SDV table
keyFields['sdvfolderattribute'] = "attributekey"
keyFields['sdvattribute'] = "attributekey"
keyFields['sdvfolder'] = "folderkey"
keyFields['sdvalgorithm'] = "algorithmsequence"
sdvTables = ['sdvfolderattribute', 'sdvattribute', 'sdvfolder', 'sdvalgorithm']
for sdvTbl in sdvTables:
keyField = keyFields[sdvTbl]
fldList = arcpy.Describe(os.path.join(outputWS, sdvTbl)).fields
fldNames = list()
for fld in fldList:
if fld.type != "OID":
fldNames.append(fld.name.lower())
#dFields[sdvTbl] = fldNames # store list of fields for this SDV table