-
Notifications
You must be signed in to change notification settings - Fork 3
/
QA_ExportShapefiles.py
1102 lines (847 loc) · 40.9 KB
/
QA_ExportShapefiles.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
# ---------------------------------------------------------------------------
# QA_ExportShapefiles.py
# Created on: May 2013
# Author: Adolfo.Diaz
# GIS Specialist
# National Soil Survey Center
# USDA - NRCS
# e-mail: adolfo.diaz@usda.gov
# phone: 608.662.4422 ext. 216
#
# Purpose: Export a set of geodatabase featureclasses to SSURGO shapefiles
#
# Soil Data Mart database used the following datum transformation methods to
# move the vector layers from NAD1983 to WGS1984 using ArcGIS 9.x?:
# Output Coordinate System set to "WGS 1984.prj"
# CONUS - NAD_1983_To_WGS_1984_5
# Hawaii - NAD_1983_To_WGS_1984_3
# Alaska - NAD_1983_To_WGS_1984_5
# ---------------------------------------------------------------------------
# QA_ExportShapefiles.py
# Created on: May 2013
# Author: Adolfo.Diaz
# GIS Specialist
# National Soil Survey Center
# USDA - NRCS
# e-mail: adolfo.diaz@usda.gov
# phone: 608.662.4422 ext. 216
#
# Puerto Rico and U.S. Virgin Islands - NAD_1983_To_WGS_1984_1
#
# 07-24-2013 Requires all 5 SSURGO featureclasses to be present in the input workspace for
# the export process to execute. This currently includes the 'Survey Boundary' which is
# somewhat controversial.
#
# 07-23-2013 Removed SPATIALVER and SPATIALVERSION fields from export shapefiles
# 07-21-2013 All 5 exported featureclasses are checked for fully populated AREASYMBOLs
# 07-20-2013 Added shapefile schema check and attribute check for the primary attribute field
#
# 07-09-2013 Original coding
#
# 11/13/2013
# Modified to work with Regional Spatial Geodatabase
# Requires all 6 SSURGO feature classes to be present within a Feature dataset.
# v 1.1 (aks)
# 1) Cleaned up refernces to input featur class by hardening path so
# the tool will no longer will pull in arbitrary MUPOLYGON features
# from map legend.
# 2) Replaced FeatureClassToFeatureClass with ExportFeatures
# 3) added arcpyErr and pyErr functions, but didn't replace references
# of AddMsgAndPrint
# ===============================================================================================================
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
try:
f = open(textFilePath,'a+')
f.write(msg + "\n")
f.close
del f
print(msg)
#for string in msg.split('\n'):
#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.AddError("\n" + msg)
except:
pass
def arcpyErr(func):
try:
etype, exc, tb = sys.exc_info()
line = tb.tb_lineno
msgs = (
f"ArcPy ERRORS:\nIn function: {func} on line: "
f"{line}\n{arcpy.GetMessages(2)}\n"
)
return msgs
except:
return "Error in arcpyErr method"
def pyErr(func):
try:
etype, exc, tb = sys.exc_info()
tbinfo = traceback.format_tb(tb)[0]
msgs = (
"PYTHON ERRORS:\nTraceback info:\nIn function: "
f"{func}\n{tbinfo}\nError Info:\n{exc}"
)
return msgs
except:
return "Error in pyErr method"
# ================================================================================================================
def errorMsg():
try:
exc_type, exc_value, exc_traceback = sys.exc_info()
theMsg = "\t" + traceback.format_exception(exc_type, exc_value, exc_traceback)[1] + "\n\t" + traceback.format_exception(exc_type, exc_value, exc_traceback)[-1]
if theMsg.find("exit") > -1:
AddMsgAndPrint("\n\n")
pass
else:
AddMsgAndPrint(theMsg,2)
except:
AddMsgAndPrint("Unhandled error in unHandledException method", 2)
pass
## ================================================================================================================
def logBasicSettings():
# record basic user inputs and settings to log file for future purposes
import getpass, time
f = open(textFilePath,'a+')
f.write("\n################################################################################################################\n")
f.write("Executing \"Export SSURGO Shapefiles\" tool\n")
f.write("User Name: " + getpass.getuser() + "\n")
f.write("Date Executed: " + time.ctime() + "\n")
f.write("User Parameters:\n")
f.write("\tFile Geodatabase Feature Dataset: " + inLoc + "\n")
f.write("\tExport Folder: " + outLoc + "\n")
#f.write("\tArea of Interest: " + AOI + "\n")
f.close
del f
## ===================================================================================
def SSURGOFieldInfo():
# Creates a dictionary containing SSURGO shapefile field info required for
# the Staging Server. Dictionary will be made of the SSURGO data type (KEY) and
# field attribute information (VALUES). The dictionary will be returned.
# No errors should occur.
# Not sure
try:
# establish dictionary
ssurgoFields = dict()
# --- MUPOLYGON dict ----
fldDesc = list()
fldDesc.append(("FID",4,0,0,"OID"))
fldDesc.append(("Shape",0,0,0,"Geometry"))
fldDesc.append(("AREASYMBOL",20,0,0,"String"))
fldDesc.append(("MUSYM",6,0,0,"String"))
#fldDesc.append(("MUKEY",30,0,0,"String"))
ssurgoFields["Map unit polygons"] = fldDesc
# --- SAPOLYGON dict ----
fldDesc = list()
fldDesc.append(("FID",4,0,0,"OID"))
fldDesc.append(("Shape",0,0,0,"Geometry"))
fldDesc.append(("AREASYMBOL",20,0,0,"String"))
#fldDesc.append(("LKEY",30,0,0,"String"))
ssurgoFields["Survey area polygons"] = fldDesc
# --- MUPOINT dict ----
fldDesc = list()
fldDesc.append(("FID",4,0,0,"OID"))
fldDesc.append(("Shape",0,0,0,"Geometry"))
fldDesc.append(("AREASYMBOL",20,0,0,"String"))
fldDesc.append(("MUSYM",6,0,0,"String"))
#fldDesc.append(("MUKEY",30,0,0,"String"))
ssurgoFields["Map unit points"] = fldDesc
# --- MULINE dict ----
fldDesc = list()
fldDesc.append(("FID",4,0,0,"OID"))
fldDesc.append(("Shape",0,0,0,"Geometry"))
fldDesc.append(("AREASYMBOL",20,0,0,"String"))
fldDesc.append(("MUSYM",6,0,0,"String"))
#fldDesc.append(("MUKEY",30,0,0,"String"))
ssurgoFields["Map unit lines"] = fldDesc
# --- FEATLINE dict ----
fldDesc = list()
fldDesc.append(("FID",4,0,0,"OID"))
fldDesc.append(("Shape",0,0,0,"Geometry"))
fldDesc.append(("AREASYMBOL",20,0,0,"String"))
fldDesc.append(("FEATSYM",3,0,0,"String"))
#fldDesc.append(("FEATKEY",30,0,0,"String"))
ssurgoFields["Feature lines"] = fldDesc
# --- FEATPOINT dict ----
fldDesc = list()
fldDesc.append(("FID",4,0,0,"OID"))
fldDesc.append(("Shape",0,0,0,"Geometry"))
fldDesc.append(("AREASYMBOL",20,0,0,"String"))
fldDesc.append(("FEATSYM",3,0,0,"String"))
#fldDesc.append(("FEATKEY",30,0,0,"String"))
ssurgoFields["Feature points"] = fldDesc
return ssurgoFields
except:
errorMsg()
return ssurgoFields
## ===================================================================================
def GetExportLayers(inLoc):
# Create and return a list of valid SSURGO featureclasses found in the workspace.
# Ideally 6 feature classes would be returned (MUPOLYGON, MUPOINT, MULINE, FEATLINE,
# FEATPOINT, SAPOLYGON). SAPOLYGON will be ignored since it will be regenerated and
try:
# list that contains valid SSURGO feature classes
exportList = list()
desc = arcpy.da.Describe(inLoc)
env.workspace = inLoc
# ?????? I think we should force input workspace to be feature dataset!!!!
# List all the feature classes if input is a feature dataset. Typical case
if desc['dataType'].upper() == "FEATUREDATASET":
# set workspace environment to the geodatabase instead of FD
env.workspace = os.path.dirname(inLoc)
listFC = arcpy.ListFeatureClasses("*","All",desc['baseName'])
# feature classes are independent ---- May want to get rid of this one!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
else:
listFC = arcpy.ListFeatureClasses("*")
AddMsgAndPrint("\nChecking input featureclasses for " + inLoc + " ("+ desc['dataType'] + ")")
# feature classes found in workspace
if len(listFC) > 0:
# Look at each featureclass in the workspace.
# Check each featureclass to make sure there is only one instance of each SSURGO type
dCount = {'Map unit polygons':'0','Map unit points':'0','Map unit lines':'0','Feature lines':'0','Feature points':'0','Survey area polygons':'0'}
# list that contains missing SSURGO feature classes
missingList = list()
# Go through each fc in the workspace and determine what SSURGO layer it is
for fc in listFC:
# ignore any feature class that begins with "QA_". These are outputs of the QA tools.
if fc[0:3] != "QA_":
# Get SSURGO data type and fileName ('_a.shp, _b.shp, _l.shp...) fileName is not used here.
ssurgoType, fileName = GetFCType(f"{inLoc}/{fc}", "")
if ssurgoType in dCount:
# switch the 0 to a 1 for the ssurgo layer in the dCount dictionary
dCount[ssurgoType] = int(dCount[ssurgoType]) + 1
# add the fc to the export list
exportList.append(fc)
else:
# Not a standard SSURGO data layer, skip it
pass
# Check each SSURGO dataType in dictionary to make sure that there are no duplicates or omissisions
for lyr, iCnt in dCount.items():
# SSURGO layer is missing
if int(iCnt) == 0:
AddMsgAndPrint("\tMissing input featureclass for " + lyr, 2)
missingList.append(lyr)
# There are duplicate SSURGO layers
elif int(iCnt) > 1:
AddMsgAndPrint("\tInput workspace contains " + str(iCnt) + " possible duplicate featureclasses for '" + lyr + "'", 2)
return list() # return blank list
if len(missingList) > 0:
AddMsgAndPrint("\tMissing the following SSURGO data layers: " + ",".join(missingList), 2)
return list() # return blank list
else:
if len(exportList) == 6:
layerList = ("SAPOLYGON","MUPOLYGON","MULINE","MUPOINT","FEATLINE","FEATPOINT")
for layer in exportList:
if not layer in layerList:
return exportList
return layerList
else:
return exportList
else:
# No input featureclasses found in the selected workspace
# This shouldn't happen if the tool validation code is working
AddMsgAndPrint("\n\tNo featureclasses found in " + inLoc, 2)
return list()
except:
errorMsg()
return list()
## ===================================================================================
def GetFCType(fc_path, theAS):
# Determine SSURGO layer name using featuretype and table fields
# Return string identifying SSURGO data type and shapefilename prefix
# ssurgoType = Mapunit Polygon
# fileName = "wi025_a.shp"
# Return two empty strings in case of error
try:
featureType = ""
ssurgoType = ""
fileName = ""
fc_name = os.path.basename(fc_path)
# 2nd measure to exclude layers that begin with "QA_"
if fc_name[0:3] != "QA_":
theDescription = arcpy.da.Describe(fc_path)
featType = theDescription['shapeType']
# Look for AREASYMBOL field, must be present
if not FindField(fc_path, "AREASYMBOL"):
AddMsgAndPrint("\t" + fc_name + " is missing 'AREASYMBOL' field (GetFCName)", 2)
return ssurgoType, fileName
# Look for MUSYM field
if FindField(fc_path, "MUSYM"):
hasMusym = True
# fc is MUPOLYGON
if featType == "Polygon":
ssurgoType = "Map unit polygons"
fileName = theAS + "_a.shp"
return ssurgoType, fileName
# fc is MULINE
elif featType == "Polyline" or featType == "Line":
ssurgoType = "Map unit lines"
fileName = theAS + "_c.shp"
return ssurgoType, fileName
# fc is MUPOINT
elif featType == "Point" or featType == "Multipoint":
ssurgoType = "Map unit points"
fileName = theAS + "_d.shp"
return ssurgoType, fileName
# fc has MUSYM but not valid SSURGO layer
else:
AddMsgAndPrint("\t" + fc_name + " is an unidentified " + featType + " featureclass with an MUSYM field (GetFCName)",2)
return ssurgoType, fileName
else:
hasMusym = False
# Look for FEATSYM field
if FindField(fc_path, "FEATSYM"):
hasFeatsym = True
# fc is FEATLINE
if featType in ("Polyline", "Line"):
ssurgoType = "Feature lines"
fileName = theAS + "_l.shp"
return ssurgoType, fileName
# fc is FEATPOINT
elif featType in ("Point", "Multipoint"):
ssurgoType = "Feature points"
fileName = theAS + "_p.shp"
return ssurgoType, fileName
# fc has featsym but not valid SSURGO layer
else:
AddMsgAndPrint("\t" + fc_name + " is an unidentified " + featType + " featureclass with an FEATSYM field (GetFCName)",2)
return ssurgoType, fileName
else:
hasFeatsym = False
# Survey Area Boundary
if not (hasMusym) and not (hasFeatsym):
# No MUSYM present, no FEATSYM present and Polygon, must be SAPOLYGON
if featType == "Polygon":
ssurgoType = "Survey area polygons"
fileName = theAS + "_b.shp"
return ssurgoType, fileName
else:
AddMsgAndPrint("\t" + fc_name + " is an unidentified " + featType + " featureclass with no MUSYM or FEATSYM field (GetFCName)", 2)
return ssurgoType, fileName
except:
errorMsg()
return "", ""
## ===================================================================================
def FindField(fc_path, fldName):
# Look for specified attribute field (fldName) in target featureclass (fc)
# return True if attribute field was found
# return False if attribute field was not found
try:
bFound = False
desc = arcpy.da.Describe(fc_path)
fldList = desc['fields']
for fld in fldList:
if fld.baseName.upper() == fldName.upper():
bFound = True
break
return bFound
except:
errorMsg()
return False
## ===================================================================================
def CheckAttributes(fc_path, ssurgoType):
# check to make sure the primary attribute fields are populated
# with data and no NULL records exist.
# Return False if fc contains empty records, True otherwise.
try:
# Set target fieldname and data type (normally text or string)
# _a, _c, _d shapefile
if ssurgoType in ("Map unit polygons","Map unit points","Map unit lines"):
fldName = "MUSYM"
# _p, _l shapefile
elif ssurgoType in ("Feature points","Feature lines"):
fldName = "FEATSYM"
# _b shapefile
elif ssurgoType == "Survey area polygons":
fldName = "AREASYMBOL"
# if fc has features, check for NULLS or spaces
if int(arcpy.GetCount_management(fc_path).getOutput(0)) > 0:
# Adds field delimiters to a field name to use in SQL queries
qFld = arcpy.AddFieldDelimiters(fc_path, fldName)
# query to filter blank or NULL values
sQuery = qFld + " IS NULL OR TRIM(LEADING ' ' FROM " + qFld + ") = '' OR " + qFld + " LIKE '% %'"
# return a list of OIDs for features that are blank/NULL
fields = ["OID@"]
values = [row[0] for row in arcpy.da.SearchCursor(fc_path, (fields), sQuery)]
# Report any blank values
if len(values) > 0:
AddMsgAndPrint("\tMissing " + str(len(values)) + " " + fldName + " value(s) in " + os.path.basename(fc_path) + " layer:",2)
for value in values:
AddMsgAndPrint("\t\tObjectID: {0}".format(value),2)
return False
else:
return True
# fc has no records
else:
return True
except:
errorMsg()
return False
#### ===================================================================================
##def CheckAreasymbol(fc):
## # Make sure that the input featureclass has fully populated AREASYMBOL
##
## try:
## # evaluate fc if it has features
## if int(arcpy.GetCount_management(fc).getOutput(0)) > 0:
##
## # Adds field delimiters to a field name to for use in SQL queries
## qFld = arcpy.AddFieldDelimiters(fc, "AREASYMBOL")
##
## # query to filter blank or NULL values
## sQuery = qFld + "IS NULL OR TRIM(LEADING ' ' FROM " + qFld + ") = ''"
##
## # return a list of OIDs for features that are blank/NULL
## fields = ["OID@"]
## values = [row[0] for row in arcpy.da.SearchCursor(fc, (fields), sQuery)]
##
## # Report any blank values
## if len(values) > 0:
## AddMsgAndPrint("\tMissing AREASYMBOL value(s) in " + os.path.basename(fc) + " layer:",2)
##
## for value in values:
## print("\t\tObjectID: {0}".format(value))
##
## return False
##
## else:
## return True
##
## # fc has no records
## else:
## return True
##
## except:
## errorMsg()
## return False
## ===================================================================================
def Number_Format(num, places=0, bCommas=True):
# returns a formatted number according to current locality and given places
# commas will be inserted if bCommas is True
# returns the input num if error is raised
try:
#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()
return num
## ===================================================================================
def SetOutputCoordinateSystem(fc_path):
# This function will compare the geographic coord sys of the inLayer to
# the spatial reference 4326 (GCS_WGS_1984). If they are different then
# an ESRI datum transformation method will be applied based on the geographic
# extent the user chose. The output coordinate system (4326) and geographic
# transformation environment variable will be set. Return True if everything
# worked, False otherwise.
#
# CONUS - NAD_1983_To_WGS_1984_5
# Hawaii - 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_1
# Other - NAD_1983_To_WGS_1984_1 (shouldn't run into this case)
try:
#---------- Gather Spatial Reference info ----------------------------
# Create the GCS WGS84 spatial reference using the factory code
outputSR = arcpy.SpatialReference(4326)
# Name of geographic coordinate system GCS_WGS_1984
outputGCS = outputSR.GCS.name
# input spatial reference
desc = arcpy.da.Describe(fc_path)
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":
inputName = desc['nameString']
elif dType.upper() == "FEATURECLASS":
inputName = desc['baseName']
else:
inputName = desc['name']
# -----------
# input and output geographic coordinate systems are the same
# no datum transformation method required
if outputGCS == inputGCS:
AddMsgAndPrint("\nNo datum transformation required")
#tm = ""
else:
AddMsgAndPrint("\tUsing datum transformation method 'WGS_1984_(ITRF00)_To_NAD_1983' \n ")
""" COMMENTED THIS OUT AND HARD CODED THE TRANSFORMATION TO ITRF00 """
##
## # More than likely input will be GCS_North_American_1983 and will
## # require datum transformation. Select datum transformation based
## # on user input.
## else:
##
## if AOI == "CONUS":
## tm = "NAD_1983_To_WGS_1984_5"
##
## elif AOI == "Alaska":
## tm = "NAD_1983_To_WGS_1984_5"
##
## elif AOI == "Hawaii":
## tm = "NAD_1983_To_WGS_1984_3"
##
## elif AOI == "Puerto Rico and U.S. Virgin Islands":
## tm = "NAD_1983_To_WGS_1984_5"
##
## elif AOI == "Other":
## tm = "NAD_1983_To_WGS_1984_1"
## AddMsgAndPrint("\nWarning! No coordinate shift is being applied", 0)
##
## else:
## raise MyError, "Invalid geographic region (" + AOI + ")"
# Set the output coordinate system environment
arcpy.env.outputCoordinateSystem = outputSR # GCS_WGS_1984
arcpy.env.geographicTransformations = "WGS_1984_(ITRF00)_To_NAD_1983" # Transformation Method
# Prompt user of the datum transformation being used
#if tm != "":
#AddMsgAndPrint("\n\tUsing datum transformation method 'WGS_1984_(ITRF00)_To_NAD_1983' \n ", 1)
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 GetFieldInfo(fc_path, ssurgoType, oldFields):
# Create and return FieldMapping object containing valid SSURGO fields. Fields
# that are not part of SSURGO will not be included.
try:
# Dictionary containing valid fields for SSURGO layers
dFieldInfo = dict()
dFieldInfo["Map unit polygons"] = ['AREASYMBOL','MUSYM']
dFieldInfo["Map unit points"] = ['AREASYMBOL','MUSYM']
dFieldInfo["Map unit lines"] = ['AREASYMBOL','MUSYM']
dFieldInfo["Feature lines"] = ['AREASYMBOL','FEATSYM']
dFieldInfo["Feature points"] = ['AREASYMBOL','FEATSYM']
dFieldInfo["Survey area polygons"] = ['AREASYMBOL']
# assign fields based on the ssurgoType (i.e. "Map unit points")
outFields = dFieldInfo[ssurgoType]
# Create required FieldMappings object and add the fc table as a
# FieldMap object
fms = arcpy.FieldMappings()
fms.addTable(fc_path)
# loop through each field in FieldMappings object
for fm in fms.fieldMappings:
# Field object containing the properties for the field (aliasName...)
outFld = fm.outputField
# Name of the field
fldName = outFld.name
# remove field from FieldMapping object if it is 'OID' or 'Geometry'
# or not in dFieldInfo dictionary (SSURGO schema)
if not fldName in outFields:
fms.removeFieldMap(fms.findFieldMapIndex(fldName))
for fldName in outFields:
newFM = fms.getFieldMap(fms.findFieldMapIndex(fldName))
fms.removeFieldMap(fms.findFieldMapIndex(fldName))
fms.addFieldMap(newFM)
return fms
except:
errorMsg()
fms = arcpy.FieldMappings()
return fms
## ===================================================================================
def CheckFieldInfo(outFC, ssurgoSchema):
# Compare the new output shapefile table design with the SSURGO standard as
# defined in the 'SSURGOFieldInfo' function
try:
fields = arcpy.da.Describe(outFC)['fields']
inSchema = []
for fld in fields:
inSchema.append((fld.baseName, fld.length, fld.precision, fld.scale, fld.type))
if inSchema == ssurgoSchema:
return True
else:
AddMsgAndPrint("Schema mismatch problem with " + outFC + " attribute table", 2)
AddMsgAndPrint("-----------------------------------------------------",2)
AddMsgAndPrint("\tOutput ShapeFile: " + str(inSchema), 2)
AddMsgAndPrint("\n\tSSURGO Standard: " + str(ssurgoSchema), 2)
return False
except:
errorMsg()
return False
## ===================================================================================
def CreateSSA(fc_out,loc,AS):
# Create Survey Area Boundary by dissolving Mapunit Polygon layer.
# Returns False if no features were generated after the dissolve or if
# _b layer already exists, otherwise return True.
try:
# path to the Soil Survey Area boundary shapefile export
SSApath = os.path.join(loc, AS.lower() + "_b.shp")
# return false if shapefile already exists
if env.overwriteOutput == False and arcpy.Exists(SSApath):
AddMsgAndPrint("Output shapefile (" + os.path.basename(SSApath) + ") already exists", 2)
return False
arcpy.Dissolve_management(
fc_out, SSApath, "AREASYMBOL", "", "SINGLE_PART"
)
# Notify user of the amount of SSA features exported
ssaCnt = int(arcpy.GetCount_management(SSApath).getOutput(0))
if ssaCnt < 1:
AddMsgAndPrint("\n\t" + os.path.basename(SSApath) + " has no features",2)
return False
else:
AddMsgAndPrint("\tSurvey area polygons: " + Number_Format(ssaCnt, 0, True) + " features exported", 0)
del SSApath
del ssaCnt
return True
except:
errorMsg()
return False
## ===================================================================================
def GetLayerExtent(layer):
try:
desc = arcpy.Describe(layer)
layerExtent = []
layerExtent.append(desc.extent.XMin)
layerExtent.append(desc.extent.XMax)
layerExtent.append(desc.extent.YMax)
layerExtent.append(desc.extent.YMin)
if len(layerExtent) == 4:
#arcpy.AddMessage(" ")
AddMsgAndPrint("\tSurvey Bounding Coordinates: ",0)
AddMsgAndPrint("\t\tWest_Bounding_Coordinate: " + str(layerExtent[0]),0)
AddMsgAndPrint("\t\tEast_Bounding_Coordinate: " + str(layerExtent[1]),0)
AddMsgAndPrint("\t\tNorth_Bounding_Coordinate: " + str(layerExtent[2]),0)
AddMsgAndPrint("\t\tSouth_Bounding_Coordinate: " + str(layerExtent[3]) + "\n ",0)
else:
return False
#AddMsgAndPrint("\n\tCould not determine Spatial Domain of " + os.path.basename(layer)
del layerExtent
return True
except:
errorMsg()
return False
## ===================================================================================
def GetFolderSize(start_path):
try:
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return Number_Format(float(total_size)/1048576,1,False)
except:
errorMsg()
return 0
## ===================================================================================
def ProcessSurveyArea(inLoc, exportList, outLoc, theAS, ssurgoFields, msg):
# Check each layer in the workspace. If it's a valid SSURGO layer, export it
# to a WGS 1984 shapefile.
# Skips any featureclass whose name begins with 'QA_'
try:
# Create final output folder for the output shapefiles, if it doesn't exist
if not arcpy.Exists(os.path.join(outLoc, theAS.lower())):
arcpy.CreateFolder_management(outLoc, theAS.lower())
else:
AddMsgAndPrint("\t" + theAS.lower() + " Folder Exists; Contents will be overwritten\n",1)
# directory path to the export folder
surveyLoc = os.path.join(outLoc, theAS.lower())
sQuery = '"AREASYMBOL" = ' + "'" + theAS + "'"
# How many unique point and linear features exist
uniqueSpecFeatureCount = 0
uniquefeatList = list()
# for each valid SSURGO layer in workspace export the Areasymbol as a shapefile
layerCount = 0
# Establish progressor object which allows progress info to be passed to dialog box.
arcpy.SetProgressor("step", " ", 0, len(exportList), 1)
for fc in exportList:
arcpy.SetProgressorLabel("\nExporting Soil Survey: " + theAS + " " + str(msg))
layerCount += 1
fc_path = f"{inLoc}/{fc}"
# Get SSURGO data type ('Mapunit Polygon') and fileName ('wi025_a.shp)
ssurgoType, fileName = GetFCType(fc_path, theAS.lower())
oldFields = arcpy.Describe(fc_path).fields
# ++++++++++++++++++++++++++
# Do not export the SSA from the fc layer. The SSA boundary
# will instead be dissolved from the Mapunit Polygon Layer
# Comment out next 2 lines if SSA is ever exported directly
# from Survey Area Boundary Layer
if ssurgoType == "Survey area polygons":
continue
# evaluate and return only valid SSURGO fields
fldInfo = GetFieldInfo(fc_path, ssurgoType, oldFields)
# process if more than 1 field was returned
if fldInfo.fieldCount > 0:
# path to the export shapefile
outFC = os.path.join(surveyLoc, fileName)
# return false if shapefile already exists
if env.overwriteOutput == False and arcpy.Exists(outFC):
AddMsgAndPrint("Output shapefile (" + outFC + ") already exists", 2)
return False
# Convert areasymbol selection to a shapefile
arcpy.conversion.ExportFeatures(
fc_path,
f"{surveyLoc}/{fileName}",
sQuery,
field_mapping=fldInfo
)
# Failed to export shapefile
if not arcpy.Exists(outFC):
AddMsgAndPrint("Failed to create output shapefile (" + outFC + ")", 2)
return False
# if there are features in layer check the schema and attribute field
iCnt = int(arcpy.GetCount_management(outFC).getOutput(0))
if iCnt > 0:
# Check output shapefile schema
if not CheckFieldInfo(outFC, ssurgoFields[ssurgoType]):
# arcpy.Delete_management(surveyLoc)
return False
# Check primary attribute field for missing values
if not CheckAttributes(outFC, ssurgoType):
# arcpy.Delete_management(surveyLoc)
return False
# Tally and gather unique special feature points and line
if ssurgoType == "Feature points" or ssurgoType == "Feature lines":
fields = ["FEATSYM"]
with arcpy.da.SearchCursor(outFC,fields) as cursor:
for row in cursor:
if not row[0] in uniquefeatList:
uniquefeatList.append(row[0])
uniqueSpecFeatureCount += 1
del fields
AddMsgAndPrint("\t" + ssurgoType + " exported: " + Number_Format(iCnt, 0, True), 0)
else:
AddMsgAndPrint("\t" + ssurgoType + " exported: " + Number_Format(iCnt, 0, True), 0)
#arcpy.Delete_management(outFC)
# Create survey boundary if _a layer by dissolving it
if ssurgoType == "Map unit polygons" and not CreateSSA(outFC,surveyLoc,theAS):
# arcpy.Delete_management(surveyLoc)
return False
# strictly formatting
if layerCount == 6:
AddMsgAndPrint("\n",0)
del outFC, iCnt
# failed to get field info
else:
return False
del ssurgoType, fileName, oldFields, fldInfo
arcpy.SetProgressorPosition()
arcpy.ResetProgressor()
# Report the # of unique features and list them if there are any
uniquefeatList.sort()
if uniqueSpecFeatureCount > 0:
#arcpy.AddMessage(" ")
AddMsgAndPrint("\t" + "Unique Special Feature Count: " + Number_Format(uniqueSpecFeatureCount, 0, True))
for feat in uniquefeatList:
AddMsgAndPrint("\t" + feat)
# Report out extent of SAPOLYGON layer
if not GetLayerExtent(os.path.join(surveyLoc,theAS.lower() + "_b.shp")):
AddMsgAndPrint("\n\tCould not determine Spatial Domain of " + os.path.basename(layer) + "\n",2)
folderSize = GetFolderSize(surveyLoc)
AddMsgAndPrint("\t" + "Directory Size: " + str(folderSize) + " MB",0)
# remove all .xml files
for file in os.listdir(surveyLoc):
if file.endswith('.xml'):
os.remove(os.path.join(surveyLoc, file))
return True
except:
errorMsg()
return False
# ========================================= Main Body ================================================
import string, os, sys, traceback, locale, arcpy
from arcpy import env
if __name__ == '__main__':
try:
v = '1.1'
arcpy.AddMessage(f"version: {v}")
# 4 Script arguments...
inLoc = arcpy.GetParameterAsText(0) # input workspace or featuredataset
outLoc = arcpy.GetParameterAsText(1) # output folder where shapefiles will be placed
asList = arcpy.GetParameter(2) # List of Areasymbol values to beexported from the geodatabase
arcpy.env.parallelProcessingFactor = "75%"
arcpy.env.overwriteOutput = True
# path to textfile that will log messages
textFilePath = outLoc + os.sep + "SSURGO_export.txt"
# record basic user inputs and settings to log file for future purposes
logBasicSettings()
# Set workspace to the input geodatabase or featuredataset
env.workspace = inLoc