-
Notifications
You must be signed in to change notification settings - Fork 1
/
Soil Data Development Toolbox.pyt
1888 lines (1706 loc) · 71.5 KB
/
Soil Data Development Toolbox.pyt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@version 0.2
"""
# https://pro.arcgis.com/en/pro-app/latest/arcpy/geoprocessing_and_python/a-template-for-python-toolboxes.htm
import arcpy
import json
import os
from urllib.request import urlopen
import re
from importlib import reload
from itertools import groupby
from arcpy.da import SearchCursor
def byKey(x, i: int=0):
"""Helper function that returns ith element from a Sequence
Parameters
----------
x : Sequence
Any indexable Sequence
i : int, optional
Index of element to be returned, by default 0
Returns
-------
Any
ith element from Sequence
"""
return x[i]
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
# self.label = "SDDT_test"
self.label = "SDDT"
self.alias = 'Soil Data Development Toolbox'
# List of tool classes associated with this toolbox
self.tools = [BulkD, buildFGDB, rasterize, valu1]#, aggregator]
class BulkD(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Bulk SSURGO Download"
self.description = (
"Bulk download of soil surveys from Web Soil Survey. User can "
"Query with wildcards ('_', '*') to query databases by Areasymbol,"
" provide soil survey layer, or geography with soil survey layer"
)
self.category = '1) Download'
self.options = [
'Query by Areasymbol',
'Query by Survey Name',
'By Soil Survey boundary layer',
'By Geography'
]
def getParameterInfo(self):
"""Define parameter definitions"""
# paramter 0
params = [arcpy.Parameter(
displayName="Output Folder",
name="outPath",
direction="Input",
parameterType="Required",
datatype="Folder"
)]
# paramter 1
params.append(arcpy.Parameter(
displayName="Selection Method",
name="option",
direction="Input",
parameterType="Required",
datatype="String"
))
params[1].filter.type = "ValueList"
params[1].filter.list = self.options
# paramter 2
params.append(arcpy.Parameter(
displayName="Areasymbol Search Criteria",
name="SSA_q",
direction="Input",
parameterType="Optional",
datatype="String",
))
# paramter 3
params.append(arcpy.Parameter(
displayName="Survey Name Search Criteria",
name="Areaname_q",
direction="Input",
parameterType="Optional",
datatype="String",
))
# paramter 4
params.append(arcpy.Parameter(
displayName="Soil Surveys",
name="SSAs",
direction="Input",
parameterType="Optional",
datatype="String",
multiValue=True
))
# paramter 5
params.append(arcpy.Parameter(
displayName="Auto-selected Soil Surveys Areas",
name="display",
direction="Output",
parameterType="Optional",
datatype="String",
enabled=False,
))
params[5].value = "None"
# parameter 6
params.append(arcpy.Parameter(
displayName="Reference Geography Layer",
name="geog_lyr",
direction="Input",
parameterType="Optional",
datatype="GPFeatureLayer",
enabled=False
))
params[6].filter.list = ["Polygon"]
# parameter 7
params.append(arcpy.Parameter(
displayName="Soil Survey Boundary Layer",
name="ssa_lyr",
direction="Input",
parameterType="Optional",
datatype="GPFeatureLayer",
enabled=False
))
params[7].filter.list = ["Polygon"]
# paramter 8
params.append(arcpy.Parameter(
displayName="Include Access Template with Download",
name="AccessBool",
direction="Input",
parameterType="Optional",
datatype="GPBoolean",
enabled=True,
))
params[8].value = False
# paramter 9
params.append(arcpy.Parameter(
displayName="Overwrite Existing",
name="OverwriteBool",
direction="Input",
parameterType="Optional",
datatype="GPBoolean",
enabled=True,
))
params[9].value = False
# Store choice lists when selection methods are changed
params.append(arcpy.Parameter(
displayName="by_sym",
name="by_sym",
direction="Input",
parameterType="Optional",
datatype="String",
multiValue=True,
enabled=False
))
params.append(arcpy.Parameter(
displayName="by_name",
name="by_name",
direction="Input",
parameterType="Optional",
datatype="String",
multiValue=True,
enabled=False
))
return params
def updateParameters(self, params):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
# Choice selection made
# Choice to provide Query
if params[1].altered and (params[1].value == self.options[0]):
params[2].enabled = True
params[3].enabled = False
params[4].enabled = True
params[6].enabled = False
params[7].enabled = False
elif params[1].altered and (params[1].value == self.options[1]):
params[2].enabled = False
params[3].enabled = True
params[4].enabled = True
params[6].enabled = False
params[7].enabled = False
# Choice to use Soil Survey layer
elif params[1].value == self.options[2]:
for i in range(2, 6):
params[i].enabled = False
params[6].enabled = False
params[7].enabled = True
# Choice to use a geography
elif params[1].valueAsText == self.options[3]:
for i in range(2, 5):
params[i].enabled = False
params[6].enabled = True
params[7].enabled = True
else:
for i in range(2, 8):
params[i].enabled = False
# Clear survey choice list
clearChoices = False
# Recreate survey choice list from query
refreshChoices = False
# If a query option selected and no query criteria specified
if ((params[1].value == self.options[0] and params[2].value is None)
or (params[1].value == self.options[1] and params[3].value is None)
):
clearChoices = True
refreshChoices = False
else:
# If new Areasymbol query entered
if (params[1].value == self.options[0]
and params[2].altered and not params[2].hasBeenValidated):
clearChoices = True
refreshChoices = True
# If new Areaname query entered
elif (params[1].value == self.options[1]
and params[3].altered and not params[3].hasBeenValidated):
clearChoices = True
refreshChoices = True
# User switched option back to query, restore form choice list
if params[1].altered and not params[1].hasBeenValidated:
if params[1].value == self.options[0] and params[2].value:
params[4].filter.list = params[10].filter.list
if params[1].value == self.options[1] and params[3].value:
params[4].filter.list = params[11].filter.list
if clearChoices:
# Clear the choice list
params[4].filter.list = []
params[4].values = []
if refreshChoices:
# Clear the choice list and create a new one
params[4].filter.list = []
params[4].values = []
if params[1].value == self.options[0]:
query_f = "AREASYMBOL"
query = params[2].value
else:
query_f = "AREANAME"
query = params[3].value
# Create empty value list
if query == "*":
# No filters at all
sQuery = (
"SELECT AREASYMBOL, AREANAME, CONVERT(varchar(10), "
"[SAVEREST], 126) AS SAVEREST FROM SASTATUSMAP "
"ORDER BY AREASYMBOL"
)
else:
# areasymbol filter
wc = query.replace('*', '%')
p1 = r"\w+\%\w+\*" # wild in middle and end
p2 = r"\%\w+\%w+" # wild beginning and middle
p3 = r"\%\w+\%" # sandwiched by wild
p4 = r"\w+\%\w+" # wild in the middle
p5 = r"\w+[%]" # wild at the end
p6 = r"[%]?\w+" # wild at beginning
p7 = r"\w+'" # just a word
pattern = '|'.join([p1, p2, p3, p4, p5, p6, p7])
wcc = re.findall(pattern, wc)
trunk = ("SELECT AREASYMBOL, AREANAME, CONVERT(varchar(10), "
"[SAVEREST], 126) AS SAVEREST FROM SASTATUSMAP WHERE "
f"{query_f} LIKE '{wcc[0]}'")
tail = " ORDER BY AREASYMBOL"
for ssa in wcc[1:]:
trunk += f" OR {query_f} LIKE '{ssa}'"
sQuery = trunk + tail
url = r'https://SDMDataAccess.sc.egov.usda.gov/Tabular/post.rest'
# Create request using JSON, return data as JSON
dRequest = dict()
dRequest["format"] = "JSON"
dRequest["query"] = sQuery
jData = json.dumps(dRequest)
# Send request to SDA Tabular service using urllib2 library
jData = jData.encode('ascii')
response = urlopen(url, jData)
jsonString = response.read()
# Convert the returned JSON string into a Python dictionary.
data = json.loads(jsonString)
del jsonString, jData, response
# Find data section (key='Table')
value_l = list()
if "Table" in data:
# Data as a list of lists. All values come back as string.
dataList = data["Table"]
# Iterate through dataList, reformat to create the menu choicelist
for rec in dataList:
areasym, areaname, date = rec
if not date is None:
date = date.split(" ")[0]
else:
date = "None"
value_l.append(f"{areasym}, {date}, {areaname}")
else:
# No data returned for this query
pass
# populate survey areas choicelist
if len(value_l) > 300:
params[4].enabled = False
params[5].enabled = True
params[4].value = value_l
else:
params[4].enabled = True
params[5].enabled = False
params[5].value = '\n'.join(value_l)
params[4].filter.list = value_l
if params[1].value == self.options[0]:
params[10].filter.list = value_l
if params[1].value == self.options[1]:
params[11].filter.list = value_l
return
def updateMessages(self, params):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
for i in range(10):
params[i].clearMessage()
# Check that crtical parameters are populated per the selected option
# Query criteria required and soil surveys selection made
if params[1].value == self.options[0]:
if not params[2].value:
params[2].setErrorMessage(
'Must provide a query statement to create '
'choice list of soil surveys.'
)
if not params[4].value:
params[4].setErrorMessage(
'Must make selection of soil surveys'
)
if params[1].value == self.options[1]:
if not params[3].value:
params[3].setErrorMessage(
'Must provide a query statement to create '
'choice list of soil surveys.'
)
if not params[4].value:
params[4].setErrorMessage(
'Must make selection of soil surveys'
)
# Provide ssa lyr
if (params[1].value != self.options[0]
and params[1].value != self.options[1]):
if not params[7].value:
params[7].setErrorMessage(
'Must select a Soil Survey Boundary Layer.'
)
# Provide geography
if params[1].value == self.options[3]:
if not params[6].value:
params[6].setErrorMessage(
'Must select a Reference Geography Layer.'
)
# Notifying user how many surveys have been auto-selected
if not params[4].enabled:
params[5].setWarningMessage((f"{len(params[4].filter.list)} "
"Soil Surveys selected"))
else:
params[5].clearMessage()
return
def execute(self, params, messages):
"""The source code of the tool."""
# by query
if (params[1].value == self.options[0]
or params[1].value == self.options[1]):
option = 1
ssa_l = params[4].values
ssa_lry = None
geog_lyr = None
# by ssa lry
elif params[1].value == self.options[2]:
option = 2
ssa_l = None
ssa_lry = params[7].value
geog_lyr = None
# by geog
else:
option = 3
ssa_l = None
ssa_lry = params[7].value
geog_lyr = params[6].value
# from sddt.download.query_download import main
import sddt.download.query_download
reload(sddt.download.query_download)
sddt.download.query_download.main([
params[0].valueAsText,
option,
ssa_l,
ssa_lry,
geog_lyr,
params[8].value,
params[9].value
])
return
def postExecute(self, parameters):
"""This method takes place after outputs are processed and
added to the display."""
return
class access_import(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Bulk Import into Access Template"
self.description = ("Import selected SSURGO datasets into Access Template. "
"database. It is not dependent on arcpy")
self.category = '2) Construct Databases'
def getParameterInfo(self):
"""Define parameter definitions"""
params = [arcpy.Parameter(displayName="Folder with SSURGO folders",
name="inputFolder",
direction="Input",
parameterType="Required",
datatype="Folder")
]
params.append(arcpy.Parameter(displayName="Soil Survey Directories",
name="SSAs",
direction="Input",
parameterType="Required",
datatype="String",
multiValue=True
)
)
params.append(arcpy.Parameter(displayName="Import Strategy",
name="strategy",
direction="Input",
parameterType="Required",
datatype="String")
)
params[2].filter.type = "ValueList"
params[2].filter.list = [
'Import into individual Default templates',
'Import into specified central template',
'Copy and import specified template in each'
]
params.append(arcpy.Parameter(displayName="Template database",
name="mdb",
direction="Input",
parameterType="Optional",
datatype="DEFile"
)
)
params[3].filter.list = ['mdb']
return params
def updateParameters(self, params):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if params[0].value is None:
params[1].filter.list = []
params[1].values = []
elif params[0].altered and not params[0].hasBeenValidated:
params[1].values = []
path = params[0].valueAsText
folders = list([f for f in os.listdir(path)
# if a directory
if os.path.isdir(os.path.join(path, f))
# and fits @@### pattern or soil_@@###
and re.match(r"[a-zA-Z]{2}[0-9]{3}", f.removeprefix('soil_'))])
params[1].filter.list = folders
if params[2].value == 'Import into individual Default templates':
params[3].enabled = False
else:
params[3].enabled = True
return
def updateMessages(self, params):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
if (params[2].value != 'Import into individual Default templates') and \
not params[3].value and params[0].value and params[2].value:
params[3].setErrorMessage('A template database must be specified')
else:
params[3].clearMessage()
return
def execute(self, params, messages):
"""The source code of the tool."""
# from sddt.download.query_download import main
import sddt.construct.access
reload(sddt.construct.access)
sddt.construct.access.main(params[0].valueAsText,
params[1].values,
params[2].value,
params[3].valueAsText)
return
def postExecute(self, parameters):
"""This method takes place after outputs are processed and
added to the display."""
return
class buildFGDB(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Create gSSURGO File Geodatabase"
self.description = (
"Create gSSURGO File Geodatabase from downloaded. SSURGO data"
)
self.category = '2) Construct Databases'
self.options = [
'Select from downloaded SSURGO datasets',
'By State(s)',
'By selected features in Soil Survey boundary layer',
'By Geography',
'Build CONUS database'
]
self.regions = [
"Alaska", "Hawaii", "Lower 48 States",
"Pacific Islands Area", "Puerto Rico and U.S. Virgin Islands",
"World"
]
# self.ssurgo_dirs = None
def isSSURGO(self, path):
# get list of directories in `path`
# which also fit @@### pattern or soil_@@###
# And contain a tabular and spatial sub-directory
dirs = [d.name.removeprefix('soil_')
for d in os.scandir(path)
if (d.is_dir()
and re.match(
r"[a-zA-Z]{2}[0-9]{3}",
d.name.removeprefix('soil_')
)
and os.path.exists(f"{d.path}/tabular")
and os.path.exists(f"{d.path}/spatial")
)]
return dirs
def getParameterInfo(self):
"""Define parameter definitions"""
# parameter 0
params = [arcpy.Parameter(
displayName="Folder with SSURGO Datasets",
name="inputFolder",
direction="Input",
parameterType="Required",
datatype="Folder"
)]
# paramter 1
params.append(arcpy.Parameter(
displayName="Select Build Option",
name="option",
direction="Input",
parameterType="Required",
datatype="String"
))
params[1].filter.type = "ValueList"
params[1].filter.list = self.options
# parameter 2
params.append(arcpy.Parameter(
displayName="Select Soil Surveys",
name="ssa_l",
direction="Input",
parameterType="Optional",
datatype="String",
multiValue=True,
enabled=False
))
# parameter 3
params.append(arcpy.Parameter(
displayName="Select State(s)",
name="state_l",
direction="Input",
parameterType="Optional",
datatype="String",
multiValue=True,
enabled=False
))
# parameter 4
params.append(arcpy.Parameter(
displayName="Soil Survey Boundary Layer",
name="ssa_lyr",
direction="Input",
parameterType="Optional",
datatype="GPFeatureLayer",
enabled=False
))
params[4].filter.list = ["Polygon"]
# parameter 5
params.append(arcpy.Parameter(
displayName="Reference Geography Layer",
name="geog_lyr",
direction="Input",
parameterType="Optional",
datatype="GPFeatureLayer",
enabled=False
))
params[5].filter.list = ["Polygon"]
# parameter 6
params.append(arcpy.Parameter(
displayName="Geographical Unit Symbol Field",
name="geog_fld",
direction="Input",
parameterType="Optional",
datatype="Field",
enabled=False
))
params[6].parameterDependencies = [params[5].name]
# parameter 7
params.append(arcpy.Parameter(
displayName="Create FGDBs for these Geographical Units",
name="geog_l",
direction="Input",
parameterType="Optional",
datatype="String",
multiValue=True,
enabled=False
))
# parameter 8
params.append(arcpy.Parameter(
displayName="Geographical Place Label",
name="geog_label",
direction="Input",
parameterType="Optional",
datatype="String",
enabled=False
))
# parameter 9
params.append(arcpy.Parameter(
displayName="Clip to selected geographies",
name="clip_b",
direction="Input",
parameterType="Optional",
datatype="GPBoolean",
enabled=False
))
params[9].value = False
# parameter 10
params.append(arcpy.Parameter(
displayName="Output SSURGO FGDB",
name="gdb_p",
direction="Output",
parameterType="Optional",
datatype="DEWorkspace",
enabled=False
))
params[10].filter.list = ["Local Database"]
# parameter 11
params.append(arcpy.Parameter(
displayName="Output Folder",
name="out_p",
direction="Input",
parameterType="Optional",
datatype="Folder",
enabled=False
))
# parameter 12
params.append(arcpy.Parameter(
displayName="Geographical Region",
name="proj_aoi",
direction="Input",
parameterType="Required",
datatype="String"
))
params[12].filter.type = "ValueList"
params[12].filter.list = self.regions
# parameter 13
params.append(arcpy.Parameter(
displayName="Create Valu1 & DominantComponent tables",
name="value1_b",
direction="Input",
parameterType="Required",
datatype="GPBoolean",
enabled=True
))
params[13].value = True
# parameter 14
params.append(arcpy.Parameter(
displayName="Concise gSSURGO",
name="concise_b",
direction="Input",
parameterType="Required",
datatype="GPBoolean",
enabled=True
))
params[14].value = True
# parameter 15
params.append(arcpy.Parameter(
displayName="gSSURGO Version",
name="gSSURGO_v",
direction="Input",
parameterType="Required",
datatype="String",
enabled=True
))
params[15].filter.type = "ValueList"
params[15].filter.list = ["gSSURGO traditional", "gSSURGO 2.0"]
return params
def updateParameters(self, params):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
# Input folder updated
if params[0].altered:# and not params[0].hasBeenValidated:
ssurgo_dirs = self.isSSURGO(params[0].valueAsText)
# self.ssurgo_dirs = self.isSSURGO(params[0].valueAsText)
# If Select by Download the survey choice needs updating
# if params[1].value == self.options[0]:
params[2].filter.list = ssurgo_dirs
# If by State, list of available states needs updating
# else:
states = {ssa[0:2].upper() for ssa in ssurgo_dirs}
states = list(states)
# Add PRVI if both present
if 'PR' in states and 'VI' in states:
states.append('PRVI')
states.sort()
params[3].filter.list = states
# Choice selection made
# Choice to Select from downloaded SSURGO data
if params[1].altered and (params[1].value == self.options[0]):
for i in range(3, 10):
params[i].enabled = False
params[2].enabled = True
params[10].enabled = True
params[11].enabled = False
# Choice to Select State(s)
elif params[1].altered and (params[1].value == self.options[1]):
for i in range(2, 11):
params[i].enabled = False
params[3].enabled = True
params[11].enabled = True
# Choice to use Soil Survey layer
elif params[1].value == self.options[2]:
for i in range(2, 10):
params[i].enabled = False
params[4].enabled = True
params[10].enabled = True
params[11].enabled = False
# Choice to use a geography
elif params[1].valueAsText == self.options[3]:
for i in range(2, 4):
params[i].enabled = False
for i in range(4, 9): # update to 10 if clip functionality added
params[i].enabled = True
params[11].enabled = True
params[10].enabled = False
# params[7].filter.list = []
# Choice build CONUS
elif params[1].valueAsText == self.options[4]:
for i in range(2, 10):
params[i].enabled = False
params[10].enabled = True
params[11].enabled = False
params[12].value = "Lower 48 States"
else:
for i in range(2, 10):
params[i].enabled = False
if params[6].altered and not params[6].hasBeenValidated:
params[7].value = []
sCur = SearchCursor(
params[5].valueAsText,
[params[6].valueAsText]
)
geogs = list({str(g) for g, in sCur})
params[7].filter.list = geogs
params[8].value = params[6].valueAsText
del sCur
# Enforce File gdb with gdb extension
if params[10].altered and not params[10].hasBeenValidated:
db_p = arcpy.Describe(params[10].value).CatalogPath
path, ext = os.path.splitext(db_p)
params[10].value = path + '.gdb'
return
def updateMessages(self, params):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
for i in range(11):
params[i].clearMessage()
# Filter features to have AREASYMBOL field
if (params[4].value and params[1].value == self.options[2]
and not arcpy.ListFields(params[4].value, 'AREASYMBOL', 'String')):
params[4].setErrorMessage(f"'{params[4].value.name}' does not have "
"an 'AREASYMBOL' field or it isn't a "
"String data type")
# Selected SSURGO folder has no valid datasets
if params[0].value and not params[2].filter.list:
params[0].setErrorMessage("No valid SSURGO datasets found in "
f"{params[0].valueAsText}")
if params[1].value == self.options[0]:
params[2].setWarningMessage("No options, try another folder.")
if params[1].value == self.options[1]:
params[3].setWarningMessage("No options, try another folder.")
# Check that crtical parameters are populated per the selected option
if params[1].value == self.options[0]:
if not params[2].value:
if params[2].message != "No options, try another folder.":
params[2].setErrorMessage(
'Must select at least one Soil Survey.'
)
if not params[10].value:
params[10].setErrorMessage('Must specify an output FGDB')
if params[1].value == self.options[1]:
if not params[3].value:
if params[3].message != "No options, try another folder.":
params[3].setErrorMessage(
'Must select at least one Soil Survey.'
)
elif not params[11].value:
params[11].setErrorMessage('Must specify an Output location')
if params[1].value == self.options[2]:
if not params[4].value:
params[4].setErrorMessage(
'Must select a Soil Survey Boundary Layer.'
)
if not params[10].value:
params[10].setErrorMessage('Must specify an output FGDB')
if params[1].value == self.options[3]:
if not params[4].value:
params[4].setErrorMessage(
'A Soil Survey reference layer needed.'
)
if not params[5].value:
params[5].setErrorMessage(
'Must select a Reference Geography Layer.'
)
elif not params[6].value:
params[6].setErrorMessage(
'Must select a Geographical Unit Field'
)
elif not params[7].value:
params[7].setErrorMessage(
'Must select at least one Geographical Unit'
)
elif not params[11].value:
params[11].setErrorMessage('Must specify an Output location')
if params[1].value == self.options[4]:
if not params[10].value:
params[10].setErrorMessage('Must specify an output FGDB')
# Have they downloaded all selected surveys?
# Future warning
# Make sure gdb isn't being specified within an exising gdb
if (params[10].value
and 'gdb' in arcpy.Describe(params[10].value).path):
params[10].setErrorMessage("Can't put a gdb in an existing gdb.")
return
def execute(self, params, messages):
"""The source code of the tool."""
# from sddt.download.query_download import main
if params[1].value == 'By State(s)':
option = 1
path = params[11].valueAsText
elif params[1].value == 'By Geography':
option = 3
path = params[11].valueAsText
elif 'SSURGO' in params[1].value:
option = 0
path = params[10].valueAsText
elif 'By selected features' in params[1].value:
option = 2
path = params[10].valueAsText
# build CONUS
else:
option = 4
path = params[10].valueAsText
import sddt.construct.fgdb
reload(sddt.construct.fgdb)
gdb_l = sddt.construct.fgdb.main([
params[0].valueAsText, # 0: input folder
option, # 1: option
params[2].valueAsText, # 2: survey list
params[3].valueAsText, # 3: state list
params[4].value, # 4: soil survey layer
params[5].valueAsText, # 5: geography layer
params[6].valueAsText, # 6: geography field
params[7].valueAsText, # 7: selected geographies
params[8].valueAsText, # 8: gdb label
params[9].value, # 9: Clip boolean
path, # 10: output path
params[12].valueAsText, # 11: AOI
params[14].value, # 12: Create Concise version boolean
params[15].value, # 13: SSURGO version
os.path.dirname(sddt.__file__) + "/construct" # 14: module path
])
# 12: Create Valu1 and Dominant Component tables
arcpy.AddMessage('\nBuilding Valu1 and Dominant Component tables.')
if params[13].value:
import sddt.construct.valu1
reload(sddt.construct.valu1)
v_success = {'both': [], 'dc': [], 'v': [], 'neither': []}
for gdb_p in gdb_l:
complete_b = sddt.construct.valu1.main([
gdb_p,
os.path.dirname(sddt.__file__) + "/construct"
])
if complete_b:
valu1_b = arcpy.Exists(gdb_p + "/Valu1")
domcom_b = arcpy.Exists(gdb_p + "/DominantComponent")
if valu1_b and domcom_b:
v_success['both'].append(gdb_p)
elif not valu1_b:
v_success['dc'].append(gdb_p)
elif not domcom_b:
v_success['v'].append(gdb_p)
else:
v_success['neither'].append(gdb_p)
else:
v_success['neither'].append(gdb_p)
nt = '\n\t'
if (both := v_success['both']):
arcpy.AddMessage(
"Both the Valu1 and DominantCompoent tables "
"were successfully created for these FGDBs:\n\t"
f"{nt.join(both)}"
)
if (dc := v_success['dc']):
arcpy.AddWarning(