-
Notifications
You must be signed in to change notification settings - Fork 3
/
Import_SSURGO_Datasets_into_FGDB_SSURGO_Refresh_Test.py
1506 lines (1159 loc) · 77.8 KB
/
Import_SSURGO_Datasets_into_FGDB_SSURGO_Refresh_Test.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
# Import_SSURGO_Datasets_into_FGDB_ArcGIS10
#
# Created 4/27/2012
#
# Adolfo Diaz, Region 10 GIS Specialist
# USDA - Natural Resources Conservation Service
# Madison, WI 53719
# adolfo.diaz@wi.usda.gov
# 608.662.4422 ext. 216
#
# Some subfunctions were modified from Steve Peaslee's "Setup_UpdateSurvey_Dev.py."
# Thanks to Steve for doing the leg work on some of these subfunctions.
#
# This script was tested using ArcGIS 10 SP4. No known issues were encountered.
#
# Purpose: Import multiple existing SSURGO datasets, spatial and tabular data, into one File Geodatabase.
#
# The "Import SSURGO Datasets into FGDB ArcGIS10" tool will import SSURGO spatial and tabular data into a File Geodatabase
# and establish the necessary relationships between tables and feature classes in order to query component and horizon
# data and spatially view the distribution of that data at the mapunit level. The output is a File Geodatabase
# that contains a feature dataset with 6 feature classes: MUPOLYGON, MUPOINT, MULINE, SAPOLYGON, FEATLINE
# and FEATPOINT. Acres will be calculated if the input Spatial Reference is projected and the linear units
# are feet or meters.
#
# Usage: +++++++++++++++++++++++++++++++++++++++++++++++++++++++
# 1) Name of New File Geodatabase:
# Name of the new File Geodatabase to create. This FGDB will contain the SSURGO spatial and tabular data.
#
# Any alphanumeric string may be entered as long as the first character is ALPHA. Special characters
# are not allowed in the name. Blank spaces will be converted to underscores.
#
# It is recommended that you use an intuitive name that will describe the extent of your output.
# ex) If your FGDB will contain every SSURGO dataset in Wisconsin than a logical name would be "WI_SSURGO".
#
# Today's date will be appended to the name of the FGDB in the form of YYYYMMDD.
# ex) "WI_SSURGO_20120301"
#
# If a FGDB of the same name, incuding the date, exists, then the tool will attempt to delete it.
# If deleting fails then the tool will exit.
# 2) Ouput Location:
# Location where the output File Geodatabase will be created. User may type in a full path in this
# field or browse to and select a folder.
#
# The tool will exit if the path is invalid.
# 3) Location where SSURGO datasets_reside:
# Browse to and select the parent directory that contains the SSURGO datasets you want imported
# into the output FGDB.
#
# SSURGO datasets must be structured the same as when they were received from the Soil Data Mart.
# SSURGO dataset folders that are altered will simply be skipped.
#
# If the Import Tabular Data option is checked, the tabular folder within the SSURGO dataset folder must
# be present. If the tabular folder is absent then ONLY the spatial data will be imported for that
# particular dataset.
# 4) Import Tabular Data (optional)
# When this option is selected, empty SSURGO attribute tables will be created in the output FGDB.
# The SSURGO text files will then be directly imported into their designated FGDB table. Text files do NOT
# need to be imported into a SSURGO Access template since the tool does not utilize a SSURGO dataset's template.
#
# The national 2002 SSURGO MS Access template database (Template DB version 34) will be used as to provide
# the necessary table and field parameters when creating the empty tables.
#
# Due to necessary reformatting of some text files, read AND write permissions are necessary in the SSURGO
# dataset parent directory.
#
# This option will also create relationships between tables and featureclasses and will store them in the
# output geodatabase. These can be used by ArcMap and other ArcGIS applications to query component and horizon
# information.
#
# Each relationship class name is prefixed by an "x" so that the listing in ArcCatalog will display tables and
# featureclasses on top and relationship classes last.
# 5) Output Coordinate System:
# Output Coordinate System that will define the feature dataset and, subsequently, the feature classes.
# Currently the tool only handles the following coordinate systems:
# NAD83 - UTM Zone
# NAD83 - State Plane (Meters or Feet)
# NAD83 - Geographic Coordinate System (GRS 1980.prj)
# NAD83 - USA Contiguous Albers Equal Area Conic USGS
# The tool does not support datum transformations. If a specific SSURGO dataset's datum differs from
# the input coordinate system than that SSURGO dataset will simply be skipped.
# 6) Clip Boundary (optional)
# Optional Polygon layer that will be used to clip the featureclasses in the output FGDB.
#
# The SAPOLYGON (Survey Area Polygon) feature class will not be clipped.
#
# The tool first determines if there is overlap between the SSURGO Soil Survey Area layer (soilsa_a_*)
# and the clip boundary. If overlap exists then the SSURGO dataset will be clipped, if necessary, before
# importing into the FGDB. If no overlap exists then the SSURGO dataset is simply skipped.
#
# If a SSURGO dataset is imported into the output FGDB and the Import Tabular Data option is checked,
# then the entire tabular data is imported, not just for the mapunits that were imported.
#
# If the clip boundary's coordinate system is different from the output coordinate system then the clip
# boundary will be projected. If the clip boundary contains multiple features then it will be dissolved
# into as a single part feature. The newly projected layer and the dissolve layer will be deleted once the
# tool has executed correctly.
#
# Depending on the size of your Soil Data Mart Library, you may want to isolate the SSURGO datasets of interest
# since the tool will inevitably determine if overlap exists between the clip boundary and every SSURGO dataset.
#
# UPDATED: 3/14/2012
# * removed much of the original code to import tabular data. Per Steve Peaslee's suggestion, I incorporate CSVreader
# module to open and read the SSURGO Text files.
# * Make better use of tuples and dictionaries by creating them early on and passing them thoughout the code rather
# create them every time I loope through a table.
#
# UPDATED: 4/27/2012
# * Add functionality to calculate acres
# * Add better error handling.
# * Had to remove "print" function from this script otherwise it would fail from toolbox.
#
# Updated 7/27/2012
# * BUG was found in the importTabular function that wouldn't properly clear rows.
# As a result, NULL values were being populated with the last value that wasn't NULL.
# deleting row cursor was added in line 1226 to assure a new line was started and not remain in memory
# UPDATED: 8/3/2012
# * BUG: Realized that if the extent boundary was a feature class within a feature dataset, the newly projected layer
# could not be written to the same feature dataset b/c its projection was not the same anymore. Modified the
# projectLayer to reproject dependent feature classess to the same geodatbase as a single feature class.
#
# UPDATED: 11/20/2012
# Eric Wolfbrandt was having inconsistent issues with the script. Sometimes it would execute correctly
# and other times it would fail. Steve Peaslee modified some of the code within the importTabular function
# to remove continue statements from within if statements. So many versions were created in an effort to
# troubleshoot this problem that I decided to print the version of the script in the log file.
#
# Last updated 10/24/2017
#
# Beginning of Functions
## ===================================================================================
def print_exception():
tb = sys.exc_info()[2]
l = traceback.format_tb(tb)
l.reverse()
tbinfo = "".join(l)
AddMsgAndPrint("\n\n----------ERROR Start-------------------",2)
AddMsgAndPrint("Traceback Info: \n" + tbinfo + "Error Info: \n " + str(sys.exc_type)+ ": " + str(sys.exc_value) + "",2)
AddMsgAndPrint("----------ERROR End-------------------- \n",2)
## ================================================================================================================
def AddMsgAndPrint(msg, severity=0):
# prints message to screen if run as a python script
# 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
#print msg
try:
f = open(textFilePath,'a+')
f.write(msg + "\n")
f.close
# Add a geoprocessing message (in case this is run as a tool)
if severity == 0:
arcpy.AddMessage(msg)
elif severity == 1:
arcpy.AddWarning(msg)
elif severity == 2:
arcpy.AddMessage(" ")
arcpy.AddError(msg)
except:
pass
## ================================================================================================================
def splitThousands(someNumber):
""" will determine where to put the thousand seperator if one is needed.
Input is an integer. Integer with or without thousands seperator is returned."""
try:
return re.sub(r'(\d{3})(?=\d)', r'\1,', str(someNumber)[::-1])[::-1]
except:
errorMsg()
return someNumber
## ================================================================================================================
def compareDatum(fc):
""" Return True if fc datum is either WGS84 or NAD83"""
try:
# Create Spatial Reference of the input fc. It must first be converted in to string in ArcGIS10
# otherwise .find will not work.
fcSpatialRef = str(arcpy.CreateSpatialReference_management("#",fc,"#","#","#","#"))
FCdatum_start = fcSpatialRef.find("DATUM") + 7
FCdatum_stop = fcSpatialRef.find(",", FCdatum_start) - 1
fc_datum = fcSpatialRef[FCdatum_start:FCdatum_stop]
# Create the GCS WGS84 spatial reference and datum name using the factory code
WGS84_sr = arcpy.SpatialReference(4326)
WGS84_datum = WGS84_sr.datumName
NAD83_datum = "D_North_American_1983"
# Input datum is either WGS84 or NAD83; return true
if fc_datum == WGS84_datum or fc_datum == NAD83_datum:
del fcSpatialRef,FCdatum_start,FCdatum_stop,fc_datum,WGS84_sr,WGS84_datum,NAD83_datum
return True
# Input Datum is some other Datum; return false
else:
del fcSpatialRef,FCdatum_start,FCdatum_stop,fc_datum,WGS84_sr,WGS84_datum,NAD83_datum
return False
except arcpy.ExecuteError:
AddMsgAndPrint(arcpy.GetMessages(2),2)
return False
except:
print_exception()
return False
## ================================================================================================================
def createFGDB(GDBname,outputFolder,spatialRef):
""" This function will Create a File Geodatabase. A Feature Dataset will be created if b_FD = True.
6 feature classes will be created using the SSURGO schema.
Return False if error occurs, True otherwise. """
try:
newFGDBpath = os.path.join(outputFolder,GDBname + ".gdb")
if arcpy.Exists(newFGDBpath):
arcpy.Delete_management(newFGDBpath)
arcpy.CreateFileGDB_management(outputFolder,GDBname)
AddMsgAndPrint("\nCreated File Geodatabase: " + newFGDBpath, 0)
if not createFeatureClasses(newFGDBpath,spatialRef):
return False
return True
except arcpy.ExecuteError:
AddMsgAndPrint(arcpy.GetMessages(2),2)
return False
except:
AddMsgAndPrint("Unhandled exception (createFGDB)", 2)
print_exception()
return False
## ================================================================================================================
def createFeatureClasses(newFGDBpath,spatialRef):
try:
#------------------------------------------------- Create a blank feature class to append soils into
arcpy.CreateFeatureclass_management(newFGDBpath,soilFC,"polygon","","DISABLED","DISABLED",spatialRef)
arcpy.AddField_management(newFGDBpath + os.sep + soilFC,"AREASYMBOL","TEXT","#","#","20")
arcpy.AddField_management(newFGDBpath + os.sep + soilFC,"SPATIALVER","DOUBLE","10","0")
arcpy.AddField_management(newFGDBpath + os.sep + soilFC,"MUSYM","TEXT","#","#","6")
arcpy.AddField_management(newFGDBpath + os.sep + soilFC,"MUKEY","TEXT","#","#","30")
AddMsgAndPrint("\tCreated Feature Class: " + soilFC + " -----> Mapunit Polygon Layer" ,0)
if not bSTATSGO:
#------------------------------------------------- Create a blank feature class to append SSA boundary to
arcpy.CreateFeatureclass_management(newFGDBpath,soilSaFC,"polygon","","DISABLED","DISABLED",spatialRef)
arcpy.AddField_management(newFGDBpath + os.sep + soilSaFC,"AREASYMBOL","TEXT","#","#","20")
arcpy.AddField_management(newFGDBpath + os.sep + soilSaFC,"SPATIALVER","DOUBLE","10","0")
arcpy.AddField_management(newFGDBpath + os.sep + soilSaFC,"LKEY","TEXT","#","#","30")
AddMsgAndPrint("\tCreated Feature Class: " + soilSaFC + " -----> Survey Boundary Layer",0)
#------------------------------------------------- Create a blank feature class to append SSURGO point features to
arcpy.CreateFeatureclass_management(newFGDBpath,featPointFC,"point","","DISABLED","DISABLED",spatialRef)
arcpy.AddField_management(newFGDBpath + os.sep + featPointFC,"AREASYMBOL","TEXT","#","#","20")
arcpy.AddField_management(newFGDBpath + os.sep + featPointFC,"SPATIALVER","DOUBLE","10","0")
arcpy.AddField_management(newFGDBpath + os.sep + featPointFC,"FEATSYM","TEXT","#","#","3")
arcpy.AddField_management(newFGDBpath + os.sep + featPointFC,"FEATKEY","TEXT","#","#","30")
AddMsgAndPrint("\tCreated Feature Class: " + featPointFC + " -----> Special Feature Point Layer",0)
#------------------------------------------------- Create a blank feature class to append SSURGO line features to
arcpy.CreateFeatureclass_management(newFGDBpath,featLineFC,"polyline","","DISABLED","DISABLED",spatialRef)
arcpy.AddField_management(newFGDBpath + os.sep + featLineFC,"AREASYMBOL","TEXT","#","#","20")
arcpy.AddField_management(newFGDBpath + os.sep + featLineFC,"SPATIALVER","DOUBLE","10","0")
arcpy.AddField_management(newFGDBpath + os.sep + featLineFC,"FEATSYM","TEXT","#","#","3")
arcpy.AddField_management(newFGDBpath + os.sep + featLineFC,"FEATKEY","TEXT","#","#","30")
AddMsgAndPrint("\tCreated Feature Class: " + featLineFC + " -----> Special Feature Line Layer",0)
#------------------------------------------------- Create a blank feature class to append SSURGO Mapunit line features to
arcpy.CreateFeatureclass_management(newFGDBpath,muLineFC,"polyline","","DISABLED","DISABLED",spatialRef)
arcpy.AddField_management(newFGDBpath + os.sep + muLineFC,"AREASYMBOL","TEXT","#","#","20")
arcpy.AddField_management(newFGDBpath + os.sep + muLineFC,"SPATIALVER","DOUBLE","10","0")
arcpy.AddField_management(newFGDBpath + os.sep + muLineFC,"MUSYM","TEXT","#","#","6")
arcpy.AddField_management(newFGDBpath + os.sep + muLineFC,"MUKEY","TEXT","#","#","30")
AddMsgAndPrint("\tCreated Feature Class: " + muLineFC + " -----> Mapunit Line Layer",0)
#------------------------------------------------- Create a blank feature class to append SSURGO Mapunit point features to
arcpy.CreateFeatureclass_management(newFGDBpath,muPointFC,"point","","DISABLED","DISABLED",spatialRef)
arcpy.AddField_management(newFGDBpath + os.sep + muPointFC,"AREASYMBOL","TEXT","#","#","20")
arcpy.AddField_management(newFGDBpath + os.sep + muPointFC,"SPATIALVER","DOUBLE","10","0")
arcpy.AddField_management(newFGDBpath + os.sep + muPointFC,"MUSYM","TEXT","#","#","6")
arcpy.AddField_management(newFGDBpath + os.sep + muPointFC,"MUKEY","TEXT","#","#","30")
AddMsgAndPrint("\tCreated Feature Class: " + muPointFC + " -----> Mapunit Point Layer",0)
return True
except arcpy.ExecuteError:
AddMsgAndPrint(arcpy.GetMessages(2),2)
return False
except:
AddMsgAndPrint("Unhandled exception (createFeatureClasses)", 2)
print_exception()
return False
## ===============================================================================================================
def GetTableAliases(ssurgoTemplateLoc, tblAliases):
""" 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:
# Open mdstattabs table containing information for other SSURGO tables
theMDTable = "mdstattabs"
env.workspace = ssurgoTemplateLoc
# 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(ssurgoTemplateLoc + os.sep + theMDTable):
nameOfFields = ["tabphyname","tablabel","iefilename"]
rows = arcpy.da.SearchCursor(ssurgoTemplateLoc + os.sep + theMDTable,nameOfFields)
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 tblAliases.has_key(physicalName):
tblAliases[physicalName] = (aliasName,importFileName)
del physicalName
del aliasName
del importFileName
del theMDTable
del nameOfFields
del rows
del row
return tblAliases
else:
# The mdstattabs table was not found
AddMsgAndPrint("\nMissing \"mdstattabs\" table", 2)
return tblAliases
except arcpy.ExecuteError:
AddMsgAndPrint(arcpy.GetMessages(2),2)
return tblAliases
except:
AddMsgAndPrint("Unhandled exception (GetTableAliases)", 2)
print_exception()
return tblAliases
## ===============================================================================================================
def importTabularData(tabularFolder, tblAliases, queue):
""" This function will import the SSURGO .txt files from the tabular folder.
tabularFolder is the absolute path to the tabular folder.
tblAliases is a list of the physical name of the .txt file along with the Alias name.
Return False if error occurs, true otherwise. there is a list of files that will not be
imported under "doNotImport". If the tabular folder is empty or there are no text files
the survey will be skipped."""
try:
env.workspace = FGDBpath
# Loops through the keys in the tblAliases dict() and puts the 2nd value
# (iefilename) and key (tabphyname) in a list. The list is then sorted
# so that SSURGO text files can be imported in alphabetical sequence.
GDBTables = tblAliases.keys()
GDBTables.sort()
# Do not import the following SSURGO text files. Most are metadata text files that are
# used within the access template and/or SDV. No need to import them into GDB.
## doNotImport = ["msdomdet","msdommas","msidxdet","msidxmas","msrsdet",
## "msrsmas","mstab","mstabcol","version"]
doNotImport = ["month"]
# if the tabular directory is empty return False
if len(os.listdir(tabularFolder)) < 1:
AddMsgAndPrint("\t\tTabular Folder is Empty!",1)
return False
# Static Metadata Table that records the metadata for all columns of all tables
# that make up the tabular data set.
mdstattabsTable = env.workspace + os.sep + "mdstattabs"
AddMsgAndPrint("\n\tImporting Tabular Data for: " + SSA,0)
# set progressor object which allows progress information to be passed for every merge complete
arcpy.SetProgressor("step", "Importing Tabular Data for " + SSA + ": " + str(queue) + ' of ' + str(total), 0, len(GDBTables), 1)
# For each item in sorted keys
for GDBtable in GDBTables:
# Metadata tables only have to be imported once b/c they are national tables.
if GDBtable.find('mds') > -1 or GDBtable.find('distinterpmd') > -1:
if int(arcpy.GetCount_management(os.path.join(FGDBpath,GDBtable)).getOutput(0)) > 0:
continue
# physicalName (tablabel,iefilename)
# i.e. {chaashto:'Horizon AASHTO',chaashto}
x = tblAliases[GDBtable]
# Alias Name: tablabel field (Table Label field)
# x[0] = Horizon AASHTO
aliasName = x[0]
# Import Export File Name: iefilename
# x[1] = chaashto
iefileName = x[1]
if not iefileName in doNotImport:
# Absolute Path to SSURGO text file
txtPath = tabularFolder + os.sep + iefileName + ".txt"
# continue if SSURGO text file exists.
if os.path.exists(txtPath):
# Next 4 lines are strictly for printing formatting to figure out the spacing between.
# the short and full name. 8 is the max num of chars from the txt tables + 2 = 10
# Played around with numbers until I liked the formatting.
theTabLength = 20 - len(iefileName)
theTab = " " * theTabLength
theAlias = theTab + "(" + aliasName + ")"
theRecLength = " " * (48 - len(aliasName))
del theTabLength, theTab
# Continue if the text file contains values. Not Empty file
if os.path.getsize(txtPath) > 0:
# Put all the field names in a list; used to initiate insertCursor object
fieldList = arcpy.Describe(GDBtable).fields
nameOfFields = []
fldLengths = list()
for field in fieldList:
if field.type != "OID":
nameOfFields.append(field.name)
if field.type.lower() == "string":
fldLengths.append(field.length)
else:
fldLengths.append(0)
del fieldList, field
# The csv file might contain very huge fields, therefore increase the field_size_limit:
# Exception thrown with IL177 in legend.txt. Not sure why, only 1 record was present
csv.field_size_limit(sys.maxsize)
# Number of records in the SSURGO text file
textFileRecords = sum(1 for row in csv.reader(open(txtPath, 'rb'), delimiter='|', quotechar='"'))
# Initiate Cursor to add rows
cursor = arcpy.da.InsertCursor(GDBtable,nameOfFields)
# counter for number of records successfully added; used for reporting
numOfRowsAdded = 0
reader = csv.reader(open(txtPath, 'rb'), delimiter='|', quotechar='"')
try:
# Return a reader object which will iterate over lines in txtPath
for rowInFile in reader:
""" Cannot use this snippet of code b/c some values have exceeded their field lengths; need to truncate"""
# replace all blank values with 'None' so that the values are properly inserted
# into integer values otherwise insertRow fails
# newRow = [None if value =='' else value for value in rowInFile]
newRow = list() # list containing the values that make up a specific row
fldNo = 0 # list position to reference the field lengths in order to compare
for value in rowInFile:
fldLen = fldLengths[fldNo]
if value == '':
value = None
elif fldLen > 0:
value = value[0:fldLen]
newRow.append(value)
fldNo += 1
cursor.insertRow(newRow)
numOfRowsAdded += 1
del newRow
except:
AddMsgAndPrint("\n\t\tError inserting record in table: " + GDBtable,2)
AddMsgAndPrint("\t\t\tRecord # " + str(numOfRowsAdded + 1),2)
AddMsgAndPrint("\t\t\tValue: " + str(newRow),2)
print_exception()
AddMsgAndPrint("\t\t--> " + iefileName + theAlias + theRecLength + " Records Added: " + str(splitThousands(numOfRowsAdded)),0)
# compare the # of rows inserted with the number of valid rows in the text file.
if numOfRowsAdded != textFileRecords:
AddMsgAndPrint("\t\t\t Incorrect # of records inserted into: " + GDBtable, 2 )
AddMsgAndPrint("\t\t\t\t TextFile records: " + str(textFileRecords),2)
AddMsgAndPrint("\t\t\t\t Records Inserted: " + str(numOfRowsAdded),2)
del GDBtable, x, aliasName, iefileName, txtPath, theAlias, theRecLength, nameOfFields, textFileRecords, rowInFile, numOfRowsAdded, cursor, reader
else:
AddMsgAndPrint("\t\t--> " + iefileName + theAlias + theRecLength + " Records Added: 0",0)
else:
AddMsgAndPrint("\t\t--> " + iefileName + " does NOT exist in tabular folder.....SKIPPING ",2)
arcpy.SetProgressorPosition()
# Resets the progressor back to is initial state
arcpy.ResetProgressor()
arcpy.SetProgressorLabel(" ")
del GDBTables, doNotImport, mdstattabsTable
return True
except arcpy.ExecuteError:
AddMsgAndPrint(arcpy.GetMessages(2),2)
AddMsgAndPrint("\tImporting Tabular Data Failed for: " + SSA,2)
return False
except csv.Error, e:
AddMsgAndPrint('\nfile %s, line %d: %s' % (txtPath, reader.line_num, e))
AddMsgAndPrint("\tImporting Tabular Data Failed for: " + SSA,2)
print_exception()
return False
except IOError as (errno, strerror):
AddMsgAndPrint("\nI/O error({0}): {1}".format(errno, strerror) + " File: " + txtPath + "\n",2)
AddMsgAndPrint("\tImporting Tabular Data Failed for: " + SSA,2)
print_exception()
return False
except:
AddMsgAndPrint("\nUnhandled exception (importTabularData) \n", 2)
AddMsgAndPrint("\tImporting Tabular Data Failed for: " + SSA,2)
print_exception()
return False
## ===============================================================================================================
def CreateTableRelationships(tblAliases):
""" Create relationship classes between standalone attribute tables.
Relate parameters are pulled from the mdstatrhipdet and mdstatrshipmas tables,
thus it is required that the tables must have been copied from the template database.
Test option of getting aliases from original template database vs. output database
set workspace to original template database
env.workspace = InputDB
or
set workspace to output database.....This script uses output database as workspace
WAIT, take that back. Using the GDB as a workspace creates locks. Specifically, the
MakeQueryTable tool creates .rd and .sr locks that are only deleted if Arc is restarted.
Currently use the ssurgoTemplate to create a query table so that it doesn't lock the .GDB
Subfunction is written by Steve Peaslee and modified by Adolfo Diaz. """
#
#Modified From Steve Peaslee's Setup_UpdateSurvey
env.workspace = ssurgoTemplate
AddMsgAndPrint("\n------------------------------------------------------------------------------------------------------- ",1)
AddMsgAndPrint("Verifying relationships:\n",1)
# set progressor object which allows progress information to be passed for every relationship complete
if arcpy.Exists(ssurgoTemplate + os.sep + "mdstatrshipdet") and arcpy.Exists(ssurgoTemplate + os.sep + "mdstatrshipmas"):
try:
# Create new Table View to contain results of join between relationship metadata tables
fld1 = "mdstatrshipmas.ltabphyname"
fld2 = "mdstatrshipdet.ltabphyname"
fld3 = "mdstatrshipmas.rtabphyname"
fld4 = "mdstatrshipdet.rtabphyname"
fld5 = "mdstatrshipmas.relationshipname"
fld6 = "mdstatrshipdet.relationshipname"
# GDB format
SQLtxt = "" + fld1 + " = " + fld2 + " AND " + fld3 + " = " + fld4 + " AND " + fld5 + " = " + fld6 + ""
# ssurgoTemplate Format (.mdb)
#SQLtxt = "[" + fld1 + "] = [" + fld2 + "] AND [" + fld3 + "] = [" + fld4 + "] AND [" + fld5 + "] = [" + fld6 + "]"
# Create in-memory table view to supply parameters for each relationshipclasses (using SSURGO 2.0 mdstatrshipdet and mdstatrshipmas tables)
inputTables = ssurgoTemplate + os.sep + "mdstatrshipdet;" + ssurgoTemplate + os.sep + "mdstatrshipmas"
queryTableName = "RelshpInfo"
# Use this one for env.workspace = FGDBpath: includes objectID but I don't think it is needed
#fieldsList = "mdstatrshipdet.OBJECTID OBJECTID;mdstatrshipdet.ltabphyname LTABPHYNAME;mdstatrshipdet.rtabphyname RTABPHYNAME;mdstatrshipdet.relationshipname RELATIONSHIPNAME;mdstatrshipdet.ltabcolphyname LTABCOLPHYNAME;mdstatrshipdet.rtabcolphyname RTABCOLPHYNAME;mdstatrshipmas.cardinality CARDINALITY"
fieldsList = "mdstatrshipdet.ltabphyname LTABPHYNAME;mdstatrshipdet.rtabphyname RTABPHYNAME;mdstatrshipdet.relationshipname RELATIONSHIPNAME;mdstatrshipdet.ltabcolphyname LTABCOLPHYNAME;mdstatrshipdet.rtabcolphyname RTABCOLPHYNAME;mdstatrshipmas.cardinality CARDINALITY"
arcpy.MakeQueryTable_management(inputTables, queryTableName, "NO_KEY_FIELD", "", fieldsList, SQLtxt)
if not arcpy.Exists(queryTableName):
AddMsgAndPrint("\nFailed to create metadata table required for creation of relationshipclasses",2)
return False
# Fields in RelshpInfo table view
# OBJECTID, LTABPHYNAME, RTABPHYNAME, RELATIONSHIPNAME, LTABCOLPHYNAME, RTABCOLPHYNAME, CARDINALITY
# Open table view and step through each record to retrieve relationshipclass parameters
rows = arcpy.SearchCursor(queryTableName)
arcpy.SetProgressor("step", "Verifying Tabular Relationships", 0, int(arcpy.GetCount_management(ssurgoTemplate + os.sep + "mdstatrshipdet").getOutput(0)), 1)
arcpy.SetProgressorLabel("Verifying Tabular Relationships")
recNum = 0
env.workspace = FGDBpath
for row in rows:
# Get relationshipclass parameters from current table row
# Syntax for CreateRelationshipClass_management (origin_table, destination_table,
# out_relationship_class, relationship_type, forward_label, backward_label,
# message_direction, cardinality, attributed, origin_primary_key,
# origin_foreign_key, destination_primary_key, destination_foreign_key)
#
#AddMsgAndPrint("Reading record " + str(recNum), 1)
originTable = row.LTABPHYNAME
destinationTable = row.RTABPHYNAME
originTablePath = FGDBpath + os.sep + row.LTABPHYNAME
destinationTablePath = FGDBpath + os.sep + row.RTABPHYNAME
# Use table aliases for relationship labels
relName = "x" + originTable.capitalize() + "_" + destinationTable.capitalize()
originPKey = row.LTABCOLPHYNAME
originFKey = row.RTABCOLPHYNAME
# create Forward Label i.e. "> Horizon AASHTO Table"
if tblAliases.has_key(destinationTable):
fwdLabel = "> " + tblAliases.get(destinationTable)[0] + " Table"
else:
fwdLabel = destinationTable + " Table"
AddMsgAndPrint("Missing key: " + destinationTable, 2)
# create Backward Label i.e. "< Horizon Table"
if tblAliases.has_key(originTable):
backLabel = "< " + tblAliases.get(originTable)[0] + " Table"
else:
backLabel = "< " + originTable + " Table"
AddMsgAndPrint("Missing key: " + originTable, 2)
theCardinality = row.CARDINALITY.upper().replace(" ", "_")
# Check if origin and destination tables exist
if arcpy.Exists(originTablePath) and arcpy.Exists(destinationTablePath):
# The following 6 lines are for formatting only
formatTab1 = 15 - len(originTable)
formatTabLength1 = " " * formatTab1 + "--> "
formatTab2 = 19 - len(destinationTable)
formatTabLength2 = " " * formatTab2 + "--> "
formatTab3 = 12 - len(str(theCardinality))
formatTabLength3 = " " * formatTab3 + "--> "
# relationship already exists; print out the relationship name
if arcpy.Exists(relName):
AddMsgAndPrint("\t" + originTable + formatTabLength1 + destinationTable + formatTabLength2 + theCardinality + formatTabLength3 + relName, 0)
# relationship does not exist; create it and print out
else:
arcpy.CreateRelationshipClass_management(originTablePath, destinationTablePath, relName, "SIMPLE", fwdLabel, backLabel, "NONE", theCardinality, "NONE", originPKey, originFKey, "","")
AddMsgAndPrint("\t" + originTable + formatTabLength1 + destinationTable + formatTabLength2 + theCardinality + formatTabLength3 + relName, 0)
# delete formatting variables
del formatTab1, formatTabLength1, formatTab2, formatTabLength2, formatTab3, formatTabLength3
else:
AddMsgAndPrint(" <-- " + relName + ": Missing input tables (" + originTable + " or " + destinationTable + ")", 0)
del originTable, destinationTable, originTablePath, destinationTablePath, relName, originPKey, originFKey, fwdLabel, backLabel, theCardinality
recNum = recNum + 1
arcpy.SetProgressorPosition() # Update the progressor position
arcpy.ResetProgressor() # Resets the progressor back to is initial state
arcpy.SetProgressorLabel(" ")
del fld2, fld1, fld3, fld4, fld5, fld6, SQLtxt, inputTables, fieldsList, queryTableName, rows, row, recNum
# Establish Relationship between tables and Spatial layers
# The following lines are for formatting only
formatTab1 = 15 - len(soilFC)
formatTabLength1 = " " * formatTab1 + "--> "
AddMsgAndPrint("\nCreating Relationships between spatial feature classes and tables:", 1)
# Relationship between MUPOLYGON --> Mapunit Table
if not arcpy.Exists("xSpatial_MUPOLYGON_Mapunit"):
arcpy.CreateRelationshipClass_management(FGDBpath + os.sep + soilFC, FGDBpath + os.sep + "mapunit", FGDBpath + os.sep + "xSpatial_MUPOLYGON_Mapunit", "SIMPLE", "> Mapunit Table", "< MUPOLYGON_Spatial", "NONE","ONE_TO_ONE", "NONE","MUKEY","mukey", "","")
AddMsgAndPrint("\t" + soilFC + formatTabLength1 + "mapunit" + " --> " + "ONE_TO_ONE" + " --> " + "xSpatial_MUPOLYGON_Mapunit", 0)
# Relationship between MUPOLYGON --> Mapunit Aggregate Table
if not arcpy.Exists("xSpatial_MUPOLYGON_Muaggatt"):
arcpy.CreateRelationshipClass_management(FGDBpath + os.sep + soilFC, FGDBpath + os.sep + "muaggatt", FGDBpath + os.sep + "xSpatial_MUPOLYGON_Muaggatt", "SIMPLE", "> Mapunit Aggregate Table", "< MUPOLYGON_Spatial", "NONE","ONE_TO_ONE", "NONE","MUKEY","mukey", "","")
AddMsgAndPrint("\t" + soilFC + formatTabLength1 + "muaggatt" + " --> " + "ONE_TO_ONE" + " --> " + "xSpatial_MUPOLYGON_Muaggatt", 0)
if not bSTATSGO:
# Relationship between SAPOLYGON --> Legend Table
if not arcpy.Exists("xSpatial_SAPOLYGON_Legend"):
arcpy.CreateRelationshipClass_management(FGDBpath + os.sep + soilSaFC, FGDBpath + os.sep + "legend", FGDBpath + os.sep + "xSpatial_SAPOLYGON_Legend", "SIMPLE", "> Legend Table", "< SAPOLYGON_Spatial", "NONE","ONE_TO_ONE", "NONE","LKEY","lkey", "","")
AddMsgAndPrint("\t" + soilSaFC + formatTabLength1 + "legend" + " --> " + "ONE_TO_ONE" + " --> " + "xSpatial_SAPOLYGON_Legend", 0)
# Relationship between MULINE --> Mapunit Table
if not arcpy.Exists("xSpatial_MULINE_Mapunit"):
arcpy.CreateRelationshipClass_management(FGDBpath + os.sep + muLineFC, FGDBpath + os.sep + "mapunit", FGDBpath + os.sep + "xSpatial_MULINE_Mapunit", "SIMPLE", "> Mapunit Table", "< MULINE_Spatial", "NONE","ONE_TO_ONE", "NONE","MUKEY","mukey", "","")
AddMsgAndPrint("\t" + muLineFC + " --> mapunit" + " --> " + "ONE_TO_ONE" + " --> " + "xSpatial_MULINE_Mapunit", 0)
# Relationship between MUPOINT --> Mapunit Table
if not arcpy.Exists("xSpatial_MUPOINT_Mapunit"):
arcpy.CreateRelationshipClass_management(FGDBpath + os.sep + muPointFC, FGDBpath + os.sep + "mapunit", FGDBpath + os.sep + "xSpatial_MUPOINT_Mapunit", "SIMPLE", "> Mapunit Table", "< MUPOINT_Spatial", "NONE","ONE_TO_ONE", "NONE","MUKEY","mukey", "","")
AddMsgAndPrint("\t" + muPointFC + " --> mapunit" + " --> " + "ONE_TO_ONE" + " --> " + "xSpatial_MUPOINT_Mapunit", 0)
# Relationship between FEATLINE --> Featdesc Table
if not arcpy.Exists("xSpatial_FEATLINE_Featdesc"):
arcpy.CreateRelationshipClass_management(FGDBpath + os.sep + featLineFC, FGDBpath + os.sep + "featdesc", FGDBpath + os.sep + "xSpatial_FEATLINE_Featdesc", "SIMPLE", "> Featdesc Table", "< FEATLINE_Spatial", "NONE","ONE_TO_ONE", "NONE","FEATKEY","featkey", "","")
AddMsgAndPrint("\t" + featLineFC + " --> featdesc" + " --> " + "ONE_TO_ONE" + " --> " + "xSpatial_FEATLINE_Featdesc", 0)
# Relationship between FEATPOINT --> Featdesc Table
if not arcpy.Exists("xSpatial_FEATPOINT_Featdesc"):
arcpy.CreateRelationshipClass_management(FGDBpath + os.sep + featPointFC, FGDBpath + os.sep + "featdesc", FGDBpath + os.sep + "xSpatial_FEATPOINT_Featdesc", "SIMPLE", "> Featdesc Table", "< FEATPOINT_Spatial", "NONE","ONE_TO_ONE", "NONE","FEATKEY","featkey", "","")
AddMsgAndPrint("\t" + featPointFC + formatTabLength1 + "featdesc" + " --> " + "ONE_TO_ONE" + " --> " + "xSpatial_FEATPOINT_Featdesc", 0)
del formatTab1, formatTabLength1
AddMsgAndPrint("\nSuccessfully Created Table Relationships", 0)
return True
except arcpy.ExecuteError:
AddMsgAndPrint(arcpy.GetMessages(2),2)
return False
except:
print_exception()
return False
else:
AddMsgAndPrint("\tMissing at least one of the relationship metadata tables", 2)
return False
## ===============================================================================================================
def updateAliasNames(fgdbPath, GDBname):
""" Update the alias name of every feature class in the RTSD including the project record.
i.e. alias name for MUPOLYGON = Region 10 - Mapunit Polygon """
try:
aliasUpdate = 0
if GDBname.rfind("_") > 0:
aliasName = GDBname[:GDBname.rfind("_")].replace("_"," ")
else:
aliasName = "SSURGO"
if arcpy.Exists(os.path.join(fgdbPath,'FEATLINE')):
arcpy.AlterAliasName(os.path.join(fgdbPath,'FEATLINE'), aliasName + " - Special Feature Lines") #FEATLINE
aliasUpdate += 1
if arcpy.Exists(os.path.join(fgdbPath,'FEATPOINT')):
arcpy.AlterAliasName(os.path.join(fgdbPath,'FEATPOINT'), aliasName + " - Special Feature Points") #FEATPOINT
aliasUpdate += 1
if arcpy.Exists(os.path.join(fgdbPath,'MUPOLYGON')):
arcpy.AlterAliasName(os.path.join(fgdbPath,'MUPOLYGON'), aliasName + " - Mapunit Polygon") #MUPOLYGON
aliasUpdate += 1
if arcpy.Exists(os.path.join(fgdbPath,'SAPOLYGON')):
arcpy.AlterAliasName(os.path.join(fgdbPath,'SAPOLYGON'), aliasName + " - Survey Area Polygon") #SAPOLYGON
aliasUpdate += 1
if arcpy.Exists(os.path.join(fgdbPath,'MULINE')):
arcpy.AlterAliasName(os.path.join(fgdbPath,'MULINE'), aliasName + " - Mapunit Line") #MULINE
aliasUpdate += 1
if arcpy.Exists(os.path.join(fgdbPath,'MUPOINT')):
arcpy.AlterAliasName(os.path.join(fgdbPath,'MUPOINT'), aliasName + " - Mapunit Point") #MUPOINT
aliasUpdate += 1
if aliasUpdate == 6:
return True
else:
return False
except arcpy.ExecuteError:
AddMsgAndPrint(arcpy.GetMessages(2),2)
return False
except:
print_exception()
return False
## ===============================================================================================================
def addAttributeIndex(table,fieldList,verbose=True):
""" Attribute indexes can speed up attribute queries on feature classes and tables.
This function adds an attribute index(es) for the fields passed to the table that
is passed in. This function takes in 2 parameters:
1) Table - full path to an existing table or feature class
2) List of fields that exist in table
This function will make sure an existing index is not associated with that field.
Does not return anything."""
try:
# Make sure table exists. - Just in case
if not arcpy.Exists(table):
AddMsgAndPrint("\nAttribute index cannot be created for: " + os.path.basename(table) + " TABLE DOES NOT EXIST",2)
return False
else:
if verbose:
AddMsgAndPrint("\n\tAdding Attribute Indexes to Table: " + os.path.basename(table))
numOfFields = len(fieldList)
arcpy.SetProgressor("step", "Adding Attribute Indexes to Table: " + os.path.basename(table), 0, numOfFields, 1)
# iterate through every field
for fieldToIndex in fieldList:
if verbose:
arcpy.SetProgressorLabel("Adding Attribute Indexes to Table: " + os.path.basename(table) + " - Field: " + fieldToIndex)
# Make sure field exists in table - Just in case
if not len(arcpy.ListFields(table,"*" + fieldToIndex))>0:
if verbose:
AddMsgAndPrint("\t\tAttribute index cannot be created for: " + fieldToIndex + ". FIELD DOES NOT EXIST",2)
arcpy.SetProgressorPosition()
continue
# list of indexes (attribute and spatial) within the table that are
# associated with the field or a field that has the field name in it.
# Important to inspect all associated fields b/c they could be using
# a differently named index
existingIndexes = arcpy.ListIndexes(table,"*" + fieldToIndex)
bFieldIndexExists = False
# check existing indexes to see if fieldToIndex is already associated
# with an index
if existingIndexes > 0:
# iterate through the existing indexes looking for a field match
for index in existingIndexes:
associatedFlds = index.fields
# iterate through the fields associated with existing index.
# Should only be 1 field since multiple fields are not allowed
# in a single FGDB.
for fld in associatedFlds:
# Field is already part of an existing index - Notify User
if fld.name == fieldToIndex:
if verbose:
AddMsgAndPrint("\t\tAttribute Index for " + fieldToIndex + " field already exists",1)
arcpy.SetProgressorPosition()
bFieldIndexExists = True
# Field is already part of an existing index - Proceed to next field
if bFieldIndexExists:
break
# Attribute field index does not exist. Add one.
if not bFieldIndexExists:
newIndex = "IDX_" + fieldToIndex
# UNIQUE setting is not used in FGDBs - comment out
arcpy.AddIndex_management(table,fieldToIndex,newIndex,"#","ASCENDING")
if verbose:
AddMsgAndPrint("\t\tSuccessfully added attribute index for " + fieldToIndex)
arcpy.SetProgressorPosition()
except:
print_exception()
return False
## ================================================================ Main Body ===========================================================
# Import modules
import arcpy, sys, string, os, time, datetime, re, csv, traceback, shutil
from arcpy import env
if __name__ == '__main__':
""" -------------------------------------------------------------------------------------------------------------------Input Arguments"""
# Parameter # 1: (Required) Name of new file geodatabase to create
#GDBname = "Test"
GDBname = arcpy.GetParameterAsText(0)
# Parameter # 2: (Required) Input Directory where the new FGDB will be created.
#outputFolder = r'K:\SSURGO_FY16\WSS\test'
outputFolder = arcpy.GetParameterAsText(1)
# Parameter # 3: (Required) Input Directory where the original SDM spatial and tabular data exist.
#sdmLibrary = r'G:\2014_SSURGO_Region10'
sdmLibrary = arcpy.GetParameterAsText(2)
# Parameter # 4: list of SSA datasets to be proccessed
#surveyList = ['soils_ia001','soils_ia005']
surveyList = arcpy.GetParameter(3)
# Parameter # 5: (Required) Import SSURGO tabular data into FGDB (boolean)
# True = Both Spatial and Tabular data will be imported to FGDB
# False = Only Spatial Data will be imported to FGDB
#b_importTabularData = True
b_importTabularData = arcpy.GetParameter(4)
# Parameter # 6: (Optional) Input Spatial Reference. Only Spatial References with WGS84 or NAD83 Datums are allowed.
#spatialRef = r'C:\Users\adolfo.diaz\AppData\Roaming\ESRI\Desktop10.1\ArcMap\Coordinate Systems\USA_Contiguous_Albers_Equal_Area_Conic_USGS_version.prj'
spatialRef = arcpy.GetParameterAsText(5)
# Parameter # 7 - Boolean indicating that STATSGO data will be appended
bSTATSGO = arcpy.GetParameter(6)
#bSTATSGO = True
# SSURGO FGDB template that contains empty SSURGO Tables and relationships
# and will be copied over to the output location
ssurgoTemplate = os.path.dirname(sys.argv[0]) + os.sep + "SSURGO_Table_Template.gdb"
if b_importTabularData and not os.path.exists(ssurgoTemplate):
AddMsgAndPrint("\n SSURGO_Table_Template.gdb does not exist in " + os.path.dirname(sys.argv[0]),2)
exit()
from datetime import datetime
startTime = datetime.now()
env.overwriteOutput = True
# --------------------------------------------------------------------------------------Set Booleans
# Set boolean for the presence of an extent boundary; True if present, False if absent
# Set boolean for Import Tabular Option; True to Import, False to ignore importing.
# The entire Main code in a try statement....Let the fun begin!
try:
import datetime
textFilePath = outputFolder + os.sep + GDBname + "_" + str(datetime.date.today()).replace("-","") + "_Log.txt"
# process each selected soil survey
AddMsgAndPrint("\nValidating " + str(len(surveyList)) + " selected surveys...", 0)
""" ---------------------------------------------------------------------------------------------------------- Create necessary File Geodatabase"""
# Create new File Geodatabase, Feature Dataset and Feature Classes.
# SSURGO layer Name
soilFC = "MUPOLYGON"
muLineFC = "MULINE"
muPointFC = "MUPOINT"
soilSaFC = "SAPOLYGON"
featPointFC = "FEATPOINT"
featLineFC = "FEATLINE"
FGDBpath = os.path.join(outputFolder,GDBname + ".gdb")
FGDBpath = r'D:\Joe\MN.gdb\FD'
# Importing tabular data was selected; Copy SSURGO Table FGDB template to output folder. Create Feature Classes
if b_importTabularData:
if arcpy.Exists(FGDBpath):
arcpy.Delete_management(FGDBpath)
arcpy.Copy_management(ssurgoTemplate,FGDBpath)
AddMsgAndPrint("\nCreated File Geodatabase: " + FGDBpath,0)
if not createFeatureClasses(FGDBpath,spatialRef):
AddMsgAndPrint("\nFailed to Initiate File Geodatabase. Exiting!",2)
exit()