-
Notifications
You must be signed in to change notification settings - Fork 3
/
GenerateSpecialFeatures.py
818 lines (616 loc) · 39 KB
/
GenerateSpecialFeatures.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
#-------------------------------------------------------------------------------
# Name: Generate Feature File
# Purpose: Read SSURGO spatial special features and points and output a text 'feature' file required by the staging server
#
# Author: Chad Ferguson
# Geospatial Analyst
# USDA-NRCS
# National Cooperative Soil Survey
# Mid-Atalntic and Carribean Regional Office
# Raleigh, NC
# charles.ferguson@nc.usda.gov
# 919.873.2137
#
#
# Created: 07/22/2013
#
#11/19/2013
# added functionality to sort the order in which soil survey areas are processed(alphabetically)
# removed restriction where featsyms of length !=3 to account for adhoc features
# added message to console and report if no special features are found, alerting user and reminding that an empty feature file is still created
# added option to delete empty feature files generated by script
#12/16/2013
# removed option to delete empty feature files -- obsolete
# added functionality to further filter input directories to only those where length is 5, first 2 char are alpha and last 3 are numeric
# tool will now execute on all input directories, if error is thrown tool will skip to next directory. error messages are accumulated and displayed/written to report
# all directories, files that are successfully validated will have a feature file written irregardless of the presence of a point, line, existing feature file
#08/01/2014
#added the check to see if there were any folders that had the SSURGO convention(state abbreviation ###) that did not have all the required _a, _b, _c, _d, _l,_p files
#and were thus invisible to the validation and not processed
# ==========================================================================================
# Updated 2/1/2020 - Adolfo Diaz
#
# - Updated and Tested for ArcGIS Pro 2.5.2 and python 3.6
# - Validation Code was updated to conform with proper indentation
# - All cursors were updated to arcpy.da
# - Added code to remove layers from an .aprx rather than simply deleting them
# - Updated AddMsgAndPrint to remove ArcGIS 10 boolean and gp function
# - Updated errorMsg() Traceback functions slightly changed for Python 3.6.
# - Added parallel processing factor environment
# - swithced from sys.exit() to exit()
# - All gp functions were translated to arcpy
# - Every function including main is in a try/except clause
# - Main code is wrapped in if __name__ == '__main__': even though script will never be
# used as independent library.
# - Normal messages are no longer Warnings unnecessarily.
#-------------------------------------------------------------------------------
# ===============================================================================================================
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:
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 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 sfDict():
try:
spfeatD = {'BLO':('Blowout','A saucer, cup, or trough-shaped depression formed by wind erosion on a pre-existing dune or other sand deposit, especially in an area of shifting sand or loose soil or where protective vegetation is disturbed or destroyed. The adjoining accumulation of sand derived from the depression, where recognizable, is commonly included. Blowouts are commonly small. Typically__to__acres.'),
'BPI':('Borrow pit','An open excavation from which soil and underlying material have been removed, usually for construction purposes. Typically__to__acres.'),
'CLA':('Clay spot','A spot where the surface texture is silty clay or clay in areas where the surface layer of the soils in the surrounding map unit is sandyloam, loam, silt loam, or coarser. Typically__to__acres.'),
'DEP':('Depression, closed','A shallow, saucer-shaped area that is slightly lower on the landscape than the surrounding area and that does not have a natural outlet for surface drainage. Typically__to__acres.'),
'ESB':('Escarpment, bedrock','A relatively continuous and steep slope or cliff, produced by erosion or faulting, that breaks the general continuity of more gently sloping land surfaces. Exposed material is hard or soft bedrock.'),
'ESO':('Escarpment, nonbedrock','A relatively continuous and steep slope or cliff, which generally is produced by erosion but can be produced by faulting, that breaks the continuity of more gently sloping land surfaces. Exposed earthy material is nonsoil or very shallow soil.'),
'GPI':('Gravel pit','An open excavation from which soil and underlying material have been removed and used, without crushing, as a source of sand or gravel. Typically__to__acres.'),
'GRA':('Gravelly spot','A spot where the surface layer has more than 35 percent, by volume, rock fragments that are mostly less than 3 inches in diameter in an area that has less than 15 percent rock fragments. Typically__to__acres.'),
'GUL':('Gully','A small, steep-sided channel caused by erosion and cut in unconsolidated materials by concentrated but intermittent flow of water. The distinction between a gully and a rill is one of depth. A gully generally is an obstacle to farm machinery and is too deep to be obliterated by ordinary tillage whereas a rill is of lesser depth and can be smoothed over by ordinary tillage.'),
'LDF':('Landfill','An area of accumulated waste products of human habitation, either above or below natural ground level. Typically__to__acres.'),
'LAV':('Lava flow','A solidified, commonly lobate body of rock formed through lateral, surface outpouring of molten lava from a vent or fissure. Typically__to__acres.'),
'LVS':('Levee','An embankment that confines or controls water, especially one built along the banks of a river to prevent overflow onto lowlands.'),
'MAR':('Marsh or swamp','A water saturated, very poorly drained area that is intermittently or permanently covered by water. Sedges, cattails, and rushes are the dominate vegetation in marshes, and trees or shrubs are the dominant vegetation in swamps. Not used in map units where the named soils are poorly drained or very poorly drained. Typically__to__acres.'),
'MPI':('Mine or quarry','An open excavation from which soil and underlying material have been removed and in which bedrock is exposed. Also denotes surface openings to underground mines. Typically__to__acres.'),
'MIS':('Miscellaneous water','Small, constructed bodies of water that are used for industrial, sanitary, or mining applications and that contain water most of the year. Typically__to__acres.'),
'WAT':('Perennial water','Small, natural or constructed lakes, ponds, or pits that contain water most of the year. Typically__to__acres.'),
'ROC':('Rock outcrop','An exposure of bedrock at the surface of the earth. Not used where the named soils of the surrounding map unit are shallow overbedrock or where "Rock outcrop" is a named component of the map unit. Typically__to__acres.'),
'SAL':('Saline spot','An area where the surface layer has an electrical conductivity of 8 mmhos/cm more than the surface layer of the named soils in the surrounding map unit. The surface layer of the surrounding soils has an electrical conductivity of 2 mmhos/cm or less.Typically__to__acres.'),
'SAN':('Sandy spot','A spot where the surface layer is loamy fine sand or coarser in areas where the surface layer of the named soils in the surrounding map unit is very fine sandy loam or finer. Typically__to__acres.'),
'ERO':('Severely eroded spot','An area where, on the average, 75 percent or more of the original surface layer has been lost because of accelerated erosion. Not used in map units in which "severely eroded", "very severely eroded", or "gullied" is part of the map unit name. Typically__to__acres.'),
'SLP':('Short, steep slope','A narrow area of soil having slopes that are at least two slope classes steeper than the slope class of the surrounding map unit.'),
'SNK':('Sinkhole','A closed, circular or elliptical depression, commonly funnel shaped, characterized by subsurface drainage and formed either by dissolution of the surface of underlying bedrock (e.g., limestone, gypsum, or salt) or by collapse of underlying caves within bedrock. Complexes of sinkholes in carbonate-rock terrain are the main components of karst topography. Typically__to__acres.'),
'SLI':('Slide or slip','A prominent landform scar or ridge caused by fairly recent mass movement or descent of earthy material resulting from failure of earth or rock under shear stress along one or several surfaces. Typically__to__acres.'),
'SOD':('Sodic spot','An area where the surface layer has a sodium adsorption ratio that is at least 10 more than that of the surface layer of the named soils in the surrounding map unit. The surface layer of the surrounding soils has a sodium adsorption ratio of 5 or less. Typically__to__acres.'),
'SPO':('Spoil area','A pile of earthy materials, either smoothed or uneven, resulting from human activity. Typically__to__acres.'),
'STN':('Stony spot','A spot where 0.01 to 0.1 percent of the soil surface is covered by rock fragments that are more than 10 inches in diameter in areas where the surrounding soil has no surface stones. Typically__to__acres.'),
'STV':('Very stony spot','A spot where 0.1 to 3.0 percent of the soil surface is covered by rock fragments that are more than 10 inches in diameter in areas where the surface of the surrounding soil is covered by less than 0.01 percent stones. Typically__to__acres.'),
'WET':('Wet spot','A somewhat poorly drained to very poorly drained area that is at least two drainage classes wetter than the named soils in the surrounding map unit. Typically__to__ acres.')}
return True, spfeatD
except:
# some type of error, return False
errorMsg()
return False, 'Unhandled error in sfDict'
#======================================================================================================================================
def spatialValidator(inPoint, inLine):
try:
svErr = list()
if not inPoint == 'p':
descP = arcpy.Describe(inPoint)
if not descP.shapeType == 'Point':
svErr.append(os.path.basename(inPoint) + 'is not point geometry')
pfldLst = ['FEATSYM', 'AREASYMBOL']
for eFld in pfldLst:
if eFld not in [str(field.name) for field in descP.fields]:
svErr.append = 'Missing at least 1 required field (AREASYM, FEATSYM) in the spatial data for ' + eKey
areaSymPLst= list(set([str(row[0]) for row in arcpy.da.SearchCursor(inPoint, "AREASYMBOL")]))
pCount = int(arcpy.GetCount_management(inPoint).getOutput(0))
localPointLst = list(set([str(row[0]) for row in arcpy.da.SearchCursor(inPoint, "FEATSYM")]))
localPointLst.sort()
del pfldLst
if inPoint == 'p':
localPointLst = []
pCount = 0
areaSymPLst = []
if not inLine == 'l':
descL = arcpy.Describe(inLine)
if not descL.shapeType == 'Polyline':
svErr.append(os.path.basename(inLine) + 'is not line geometry')
lfldLst = ['FEATSYM', 'AREASYMBOL']
for eFld in lfldLst:
if eFld not in [str(field.name) for field in descL.fields]:
svErr.append = 'Missing at least 1 required field (AREASYM, FEATSYM) in the spatial data for ' + eKey
areaSymLLst = list(set([str(row[0]) for row in arcpy.da.SearchCursor(inLine, "AREASYMBOL")]))
lCount = int(arcpy.GetCount_management(inLine).getOutput(0))
localLineLst = list(set([str(row[0]) for row in arcpy.da.SearchCursor(inLine, "FEATSYM")]))
localLineLst.sort()
del lfldLst
if inLine == 'l':
localLineLst = []
lCount = 0
areaSymLLst = []
areaSymLst = list(set(areaSymPLst + areaSymLLst))
if len(areaSymLst) > 1:
svErr.append('More than 1 AREASYMBOL found in spatial data for ' + eKey)
#AddMsgAndPrint(svArSyMsg, 1)
## return False, 'Too many areasymbols encountered in the special feature file(s)', None, None, None, None, None
specFeatLst = list(set(localPointLst + localLineLst))
return True, specFeatLst, localPointLst, localLineLst, pCount, lCount, areaSymLst, svErr
except:
errorMsg()
return False, 'Unhandled error in spatialValidator while processing ' + eKey + ', Reprocessing Required', None, None, None, None, areaSymLst, None
#======================================================================================================================================
def txtValidator(xstTxt, areaSymLst):
AddMsgAndPrint(areaSymLst)
totalError = 0
try:
tvErr = list()
with open(xstTxt, 'r') as chkTXT:
countLine = 0
lines = chkTXT.readlines()
for line in lines:
countLine = countLine + 1
lineLst = line.split('|')
if line.count('"') != 10:
lcMsg = ('Missing quotation mark(s) error on line ' + str(countLine) + ' in ' + xstTxt)
tvErr.append(lcMsg)
#AddMsgAndPrint(lcMsg + '\n', 1)
totalError = totalError + 1
elif ' ' in line:
xspMsg = 'Found multiple space error on line ' + str(countLine) + ' in ' + xstTxt
tvErr.append(xspMsg)
#AddMsgAndPrint(xspMsg + '\n', 1)
totalError = totalError + 1
elif line[1:6] not in areaSymLst:
asMsg = 'AREASYMBOL mismatch between text file and spatial, line ' + str(countLine) + ' in ' + xstTxt
tvErr.append(asMsg)
#AddMsgAndPrint(asMsg + '\n', 1)
totalError = totalError + 1
elif len(lineLst) != 6:
pipeMsg = 'Missing element or pipe on line ' + str(countLine) + ' in ' + xstTxt
tvErr.append(pipeMsg)
#AddMsgAndPrint( pipeMsg + '\n', 1)
totalError = totalError + 1
elif len(lineLst[0]) != 7:
asLenMsg = 'Incorrect length for AREASYMBOL on line ' + str(countLine) + ' in ' + xstTxt
tvErr.append(asLenMsg)
#AddMsgAndPrint( asMsg + '\n', 1)
totalError = totalError + 1
#ADHOC FEATSYM are not necessarily 3 characters
#elif len(lineLst[2]) != 5:
#AddMsgAndPrint( '\nIncorrect length for FEATSYM on line ' + str(countLine) + ' in ' + xstTxt, 1)
chkTXT.close()
return True, tvErr
except:
# some type of error, return False
errorMsg()
return False, 'Unhandled error in txtValidator while processing' + eKey + ', Reprocessing Required'
#========================================================================================================
def txtLst(xstTxt):
try:
xstTxtLst = []
with open(xstTxt, 'r') as chkTXT:
lines = chkTXT.readlines()
for line in lines:
pipeOne = line.find('|')
pipeTwo = line.find('|', pipeOne + 1)
pipeThree = line.find('|', pipeTwo + 1)
tStr = line[pipeTwo + 2:pipeThree - 1]
xstTxtLst.append(tStr)
chkTXT.close()
xstTxtLst= list(set(xstTxtLst))
return True, xstTxtLst
except:
errorMsg()
return False, 'Unhandled error in txtLst while processing ' + xstTxt + ', Reprocessing Required'
#========================================================================================================
def crossCheck(xstTxt):
try:
#get the comprehensive set of all special features in the point and line spatial layers
comprehensiveSet = set(spatialValidator(inPoint, inLine)[1])
#get the set of features identified in the existing special points text file
txtSet = set(txtLst(xstTxt)[1])
#new set with existing spatial features but no counter part in the existing text
spatialVoid = comprehensiveSet.difference(txtSet)
#new set with features identified in the text file but have no spatial features digitized
txtVoid = txtSet.difference(comprehensiveSet)
return True, spatialVoid, txtVoid
except:
errorMsg()
return False, 'Unhandled error in crossCheck, Reprocessing Required', None
#========================================================================================================
def fileUpdater(xstTxt):
import bisect
try:
#get the generic dictionary SOI 37A
spfeatD = sfDict()[1]
#get the results from cross check to find out if there needs to be any additions/deletion
areaSymLst = spatialValidator(inPoint, inLine)[6]
spatialVoidLst = list(crossCheck(xstTxt)[1])
txtVoid = (crossCheck(xstTxt)[2])
spatialVoidLst.sort()
#create a list of the existing points from the special points text file to house the existing points and find entries in
#the existing special points text file that do not exist spatiallly and get rid of them.
existsLst = []
with open(xstTxt, 'r') as f:
for line in f.readlines():
first = line.find('|')
second = line.find('|', first + 1)
third = line.find('|', second + 1)
fourth = line.find('|', third + 1)
fifth = line.find('|', fourth + 1)
existsLst.append(line[0:first] + line[second:fifth])
f.close()
existsLst.sort()
noPtLst = []
for eVal in txtVoid:
for i in existsLst:
if i[9:12].upper() == eVal.upper():
noPtLst.append(i[9:12].upper())
existsLst.remove(i)
#create a list for the spatial points that are not identified in the existing special features text (spatialVoidLst) and format the items to match tmpLst (no SPATIALVER and FEATKEY)
withDefLst = []
noDefLst =[]
updateLst = []
for eVal in spatialVoidLst:
updateTxt = '"' + areaSymLst[0] + '"|"' + eVal + '"|'
if eVal in spfeatD:
featName = spfeatD.get(eVal)[0]
featDesc = spfeatD.get(eVal)[1]
updateTxt = updateTxt + '"'+ featName + '"|"' + featDesc + '"'
withDefLst.append(eVal)
#arcpy.AddWarning('\n\nThe feature ' + eVal + ' was found in the spatial data but WAS NOT found in the existing special features text file.\nA generic definition was added from SOI-37A. Please review and edit accordingly.\n\n')
else:
noDefLst.append(eVal)
updateTxt = updateTxt + '"FEATNAME"|"FEATDESC"'
#arcpy.AddWarning('\n\nThe feature ' + eVal + ' was found in the spatial data but WAS NOT found in the existing special features text file.\nThere is no corresponding entry on the SOI37A.\nA "FEATNAME" and "FEATDESC" placeholder was added. Please review and edit accordingly.\n\n')
updateLst.append(updateTxt)
#evaluate the new existsLst to find out where items from the updateLst need to be placed in order to make it alphabetically correct
for lVal in updateLst:
i = bisect.bisect_right(existsLst, lVal)
existsLst.insert(i, lVal)
outLoc = inSpatialDir + os.sep + eKey + os.sep
#arcpy.AddMessage(outLoc)
#create the new 'features.txt' file
with open(outLoc + 'feature', 'w') as f:
for eItem in existsLst:
f.write(eItem + '\n')
f.close()
return True, noPtLst, withDefLst, noDefLst
except:
# some type of error, return False
errorMsg()
return False, 'Unhandled error in fileUpdater, Reprocessing Required', None, None
#========================================================================================================
def fileGenerator():
try:
areaSymLst = sv6
#areaSymLst = spatialValidator(inPoint, inLine)[6]
#write the file from the list
outLoc = inSpatialDir + os.sep + eKey + os.sep
outFeature = outLoc + os.sep + 'feature'
#get the generic dictionary SOI 37A
spfeatD = sfDict()[1]
#get the list of all the specialfeatures
getCompLst = sv1
#arcpy.AddMessage(getCompLst)
getCompLst.sort()
containerLst = []
withDefLst = []
if len(getCompLst) != 0:
for eVal in getCompLst:
updateTxt = '"' + areaSymLst[0] + '"|"' + eVal + '"|'
if eVal in spfeatD:
#add the SOI 37A generic descriptions if available
withDefLst.append(eVal)
updateDesc = spfeatD.get(eVal)
featName = updateDesc[0]
featDesc = updateDesc[1]
updateTxt = updateTxt + '"'+ featName + '"|"' + featDesc + '"'
else:
#add place holders that need updating
updateTxt = updateTxt + '"FEATNAME"|"FEATDESC"'
containerLst.append(updateTxt)
containerLst.sort()
with open(outFeature, 'w') as f:
for eVal in containerLst:
f.write(eVal + '\n')
f.close()
else:
with open(outFeature, 'w') as f:
pass
f.close()
return True, withDefLst
except:
errorMsg()
return False, 'Unhandled error in fileGenerator, Reprocessing Required'
#========================================================================================================
import sys, os, arcpy, time, getpass, fnmatch, shutil, traceback
#Parameters
inSpatialDir = sys.argv[1]
ssaSym = sys.argv[2]
inTxtDir = sys.argv[3]
crossCLst = list()
if os.path.isdir(inSpatialDir):
pntlLst = os.listdir(inSpatialDir)
for e in pntlLst:
if os.path.isdir(inSpatialDir + os.sep + e) and len(e) == 5 and not e[:2].isdigit() and e[2:].isdigit():
crossCLst.append(e.lower())
#a container to accumulate dict keys that successfully get a feature file
execLst = list()
AddMsgAndPrint(' \n \n ')
sep = '-'*100
try:
with open(inSpatialDir + os.sep + 'QA_Special_Features_Report.txt', 'w') as f:
start = time.strftime("%a, %d %b %Y %H:%M:%S")
f.write("\n################################################################################################################\n")
f.write('Executing \"Generate Special Features\" tool\n')
f.write('User Name: ' + getpass.getuser() + '\n')
f.write('Date Executed: ' + start + '\n')
f.write('User Parameters:\n')
f.write('\tInput folder containing spatial data: ' + inSpatialDir + '\n')
f.write('\tInput folder containing existing feature files: ' + inTxtDir + '\n')
f.write("################################################################################################################\n\n")
qaDict = {}
txtDict = {}
targetLst =[]
paramSSA = str(arcpy.GetParameterAsText(1))
paramLst = list(paramSSA.split(';'))
paramLst.sort()
arcpy.SetProgressor('step', 'Creating feature file...', 0, len(paramLst), 1)
for eSSA in paramLst:
featPath = list()
pPath = inSpatialDir + os.sep + eSSA + os.sep + eSSA +'_p.shp'
lPath = inSpatialDir + os.sep + eSSA + os.sep + eSSA +'_l.shp'
if os.path.isfile(pPath):
featPath.append(pPath)
else:
featPath.append('p')
if os.path.isfile(lPath):
featPath.append(lPath)
else:
featPath.append('l')
if not eSSA.upper() in qaDict:
qaDict[eSSA.upper()] = featPath
del featPath
del eSSA
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#check type of existing feature file workspace and build a doctionary of paths {NC001:E:\GIS\NRCS\National_Special_Features/soilsf_t_nc001.txt}
if inTxtDir != "#":
desc = arcpy.Describe(inTxtDir)
txtType = desc.dataElementType.upper()
if txtType == 'DEFOLDER':
for dirpath, dirnames, filenames in os.walk(inTxtDir):
for filename in filenames:
tFile = os.path.join(dirpath, filename)
if fnmatch.fnmatch(tFile, '*soilsf_t_*.txt'):
#areasymbol will be the key
keyName = os.path.basename(tFile)[9:14]
if keyName.upper() not in txtDict:
txtDict[keyName.upper()] = [tFile]
elif txtType == 'DEWORKSPACE':
#create a textfile of the featdesc table whose format mimics a feature file
#accumulate the areasymbols in a list
aSymLst = list()
with open(os.path.dirname(inTxtDir) + os.sep + 'FEATDESC.txt', 'w') as ff:
with arcpy.da.SearchCursor(inTxtDir + os.sep + 'featdesc', ["*"]) as rows:
for row in rows:
ff.write('"' + str(row[1]) + '"|' + str(row[0]) + '|"' + str(row[2]) + '"|"' + str(row[3]) + '"|"' + str(row[4]) +'"|"ZZZ"' + '\n')
aSymLst.append(str(row[1]).lower())
#create a unique list of areasymbols
uLst = list(set(aSymLst))
uLst.sort()
ff.close()
#make temp location to write files to
sfTmpDir = os.path.dirname(inTxtDir) + os.sep + 'sfTmpDir'
if os.path.exists(sfTmpDir):
shutil.rmtree(sfTmpDir)
os.mkdir(sfTmpDir)
else:
os.mkdir(sfTmpDir)
#for each areasymbol iterate over the featdesc.txt file, grab the corresponding features and make a new special features file
for eVal in uLst:
with open(os.path.dirname(inTxtDir) + os.sep + 'FEATDESC.txt', 'r') as ff:
with open(sfTmpDir + os.sep + 'soilsf_t_' + eVal.lower() + '.txt', 'w') as o:
for line in ff.readlines():
if line.find(eVal.upper()) != -1:
o.write(line)
o.close()
ff.close()
for dirpath, dirnames, filenames in os.walk(sfTmpDir):
for filename in filenames:
tFile = os.path.join(dirpath, filename)
if fnmatch.fnmatch(tFile, '*soilsf_t_*.txt'):
#areasymbol will be the key
keyName = os.path.basename(tFile)[9:14]
if keyName.upper() not in txtDict:
txtDict[keyName.upper()] = [tFile]
#merge the dictionaries containing the paths to the points and line qaDict and the path to text files, using the areasymbol key
compDict = {}
for eKey in qaDict:
if eKey in txtDict:
compDict[eKey] = qaDict[eKey] + txtDict[eKey]
else: compDict[eKey] = qaDict[eKey]
sCount = len(compDict)
cCount = 0
#start chuggin'.......
for eKey in sorted(compDict.keys()):
AddMsgAndPrint(' \n \nProcessing for: ' + eKey + '\n')
arcpy.SetProgressorLabel('Processing for: ' + eKey)
arcpy.SetProgressorPosition()
valLst = compDict[eKey]
inPoint = valLst[0]
inLine = valLst[1]
if len(valLst) == 3:
xstTxt = valLst[2]
f.write('\n\n\nProcessing special features for: ' + eKey.upper() + '\n')
f.write(sep +'\n')
#we should never see the following inPoint and inLine msgs as the tool validation code will not include directories that don't have them
if inPoint == 'p':
noPtMsg = 'No special feature point file submitted for ' + eKey.upper()
f.write('\t' + noPtMsg + '\n')
AddMsgAndPrint(noPtMsg, 1)
if inLine == 'l':
noLnMsg = 'No special feature line file submitted for ' + eKey.upper()
f.write('\t' + noLnMsg + '\n')
AddMsgAndPrint(noLnMsg, 1)
#return True, specFeatLst, localPointLst, localLineLst, pCount, lCount, areaSymLst, svErr
sv0, sv1, sv2, sv3, sv4, sv5, sv6, sv7 = spatialValidator(inPoint, inLine)
if sv0:
ftCnt = sv4 + sv5
areaSymLst = sv6
f.write('\tSpecial Feature Point Count: ' + str(sv4) + '\n')
for p in sv2:
f.write('\t\t'+ p + '\n')
f.write('\tSpecial Feature Line Count: ' + str(sv5) + '\n')
for l in sv3:
f.write('\t\t'+ l + '\n')
f.write('\tMessages:\n')
#we should never see the following inPoint and inLine msgs as the tool validation code will not include directories that don't have them
if valLst[0] != 'p' or valLst[1] != 'l':
if ftCnt == 0:
emptyFeaturesMsg = 'Spatial files exist for ' + eKey + ' and there are no digitized features. An empty feature file WILL be written\n'
AddMsgAndPrint(emptyFeaturesMsg, 1)
f.write('\t\t' + '***WARNING***: '+ emptyFeaturesMsg + '\n')
if len(valLst) == 3:
if valLst[0] == 'p' and valLst[1] == 'l':
matchMsg = 'An existing feature file was submitted for ' + eKey + ': ' + valLst[2] + ' but no digitized features were found.' \
' An EMPTY feature file WILL be written.\n'
f.write('\t\t' + '***WARNING***: ' + matchMsg)
AddMsgAndPrint(matchMsg + '\n', 1 )
if len(sv7)!=0:
for svMsg in sv7:
f.write('\t\t***WARNING***: '+ svMsg + '\n')
AddMsgAndPrint('***WARNING***: ' + svMsg, 2)
AddMsgAndPrint('ADDRESS ERRORS FOR ' + eKey + ' AND REPROCESS', 2)
f.write('\t\tADDRESS ERRORS FOR ' + eKey + ' AND REPROCESS')
else:
svError = sv1
f.write('\t\t' + '!!!FAILURE!!!: ' + svError + '\n')
AddMsgAndPrint(sv1, 2)
if len(valLst) == 3 and ftCnt != 0:
if len(sv7) == 0:
tv0, tv1 = txtValidator(xstTxt, areaSymLst)
if tv0:
if len(tv1) != 0:
for tvMsg in tv1:
f.write('\t\t' + '***WARNING***: ' + tvMsg + '\n')
AddMsgAndPrint('***WARNING***: ' + tvMsg , 2)
AddMsgAndPrint('ADDRESS ERRORS FOR ' + eKey + ' AND REPROCESS', 2)
else:
tvMsg = tv1
AddMsgAndPrint('!!!FAILURE!!!: ' + tvMsg, 2)
f.write('\t\t!!!FAILURE!!!: ' + tvMsg)
if len(tv1) == 0:
tL0, tL1 = txtLst(xstTxt)
if tL0:
pass
else:
tLMsg = tL1
AddMsgAndPrint(tLMsg, 2)
f.write('\t\t!!!FAILURE!!!: ' + tlMsg)
if len(tL1) == 0:
cC0, cC1, cC2 = crossCheck(xstTxt)
if cC0:
pass
else:
ccMsg = cC1
AddMsgAndPrint(ccMsg, 2)
f.write('\t\t!!!FAILURE!!!: ' + ccMsg)
if len(sv7) == 0 and len(tv1) == 0:
fU0, fU1, fU2, fU3 = fileUpdater(xstTxt)
if fU0:
#for no errors = exact match between spatial features and existing special features text file (soilsf_t_xx000.txt)
if len(fU1) + len(fU2) + len(fU3) == 0:
fuMsg = ('<<<SUCCESS>>>: Generated the feature file using the ' + os.path.basename(xstTxt) + '. ALL FILES IN SYNC\n ')
f.write('\t\t' + fuMsg)
AddMsgAndPrint(fuMsg, 0)
cCount = cCount + 1
execLst.append(eKey.lower())
else:
if len(fU1) > 0:
noPtMsg ='***WARNING***: ' + ','.join(fU1) + ' were found in the existing ' + os.path.basename(xstTxt) + ' file with no matching spatial feature. They are not included the output feature file.'
AddMsgAndPrint(noPtMsg, 1)
f.write('\t\t' + noPtMsg + '\n')
if len(fU2) > 0:
withDefMsg = '***WARNING***: ' +','.join(fU2) + ' were found in the spatial data but not in the ' + os.path.basename(xstTxt) + ' file. A generic definition has been added for these features. MANUAL EDITS LIKELY.'
AddMsgAndPrint(withDefMsg, 1)
f.write('\t\t' + withDefMsg + '\n')
if len(fU3) > 0:
noDefMsg = '***WARNING***: ' + ','.join(fU3) + ' were found in the spatial data but not in the ' + os.path.basename(xstTxt) + ' file. A FEATNAME and FEATDESC place holder was added. MANUAL EDITS REQUIRED.'
AddMsgAndPrint(noDefMsg, 1)
f.write('\t\t' + noDefMsg + '\n')
cCount = cCount + 1
fuMsgWarn = ('<<<SUCCESS>>>: Generated the feature file using the ' + os.path.basename(xstTxt) + '. REVIEW WARNINGS\n ')
f.write('\t\t' + fuMsgWarn)
AddMsgAndPrint(fuMsgWarn, 1)
execLst.append(eKey.lower())
f.write('\n\n')
else:
fuMsg = fU1
AddMsgAndPrint('!!!FAILURE!!!: ' + fuMsg, 2)
f.write('\t\t!!!FAILURE!!!: ' + fuMsg)
else:
if len(sv7) == 0:
fG0, fG1 = fileGenerator()
if fG0:
fGMsg = '<<<SUCCESS>>>: Generated the feature file for '+ eKey + ' using generic feature definitions if available. MANUAL EDITS LIKELY. \n '
AddMsgAndPrint(fGMsg, 1)
f.write('\t\t' + fGMsg)
execLst.append(eKey.lower())
f.write('\n\n')
cCount = cCount + 1
else:
fGMsg = fG1
AddMsgAndPrint('!!!FAILURE!!!: ' + fG1, 1)
f.write('\t\t!!!FAILURE!!!: ' + fG1)
f.write("################################################################################################################\n\nSUMMARY:\n\n")
cntMsg = str(sCount) + ' survey areas submitted and ' + str(cCount) + ' feature files generated\n'
AddMsgAndPrint(cntMsg, 1)
f.write('\t' + cntMsg)
paramSet = set(paramLst)
execSet = set(execLst)
fLst = list(paramSet.symmetric_difference(execSet))
if len(fLst) > 0:
failMsg = 'The following surveys were submitted but did not execute successfully: ' + ','.join(fLst)
AddMsgAndPrint(failMsg, 2)
f.write('\t' + failMsg)
if not len(crossCLst) == len(paramLst):
cCset = set(crossCLst)
unAvLst = list(cCset.difference(paramSet))
unAvLst.sort()
AddMsgAndPrint(' \n ')
#if len(unAvLst)>0:
unAvMsg = ('The following folders found in the Input Spatial Features Folder appear to be SSURGO directories but are missing required files and were not available to the tool: \n \n' +'\t' + ','.join(unAvLst))
AddMsgAndPrint(unAvMsg, 1)
f.write('\n\t' + unAvMsg)
f.close()
try:
if txtType == 'DEWORKSPACE':
os.remove(os.path.dirname(inTxtDir) + os.sep + 'FEATDESC.txt')
shutil.rmtree(sfTmpDir)
except:
pass
AddMsgAndPrint(' \n \n')
except:
errorMsg()