forked from Riverscapes/ConfinementTool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Confinement_Toolbox.pyt
1523 lines (1278 loc) · 70.2 KB
/
Confinement_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
'''
Name: Stream and Valley Confinement Toolbox
Purpose: Tools for and calculating confinement on a stream
network or using a moving window along the stream network
Authors: Kelly Whitehead ([email protected])
South Fork Research, Inc
Seattle, Washington
Created: 2015-Jan-08
Version: 2.2.03
Released: 2017 AUG 01
Updated: 23/8/2018 - DDH - Removed redundant imports to Riverscapes module
DDH - Set parameter type to GPFeatureLayer so the function testLayerSelection() would actually do it's job.
DDH - Updated version number to .04
License: Free to use.
'''
# !/usr/bin/env python
# # Import Modules # #
from os import path, makedirs
import arcpy
from arcgis_package import ConfiningMargins, MovingWindow, ConfinementSegments
from Riverscapes import Riverscapes
# Version numbers
ConfinementToolReleaseVersion = "2.2.04"
ConfinementProjectVersion = "2.3"
path_lyr = path.join(path.dirname(path.realpath(__file__)),"lyr")
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Confinement Toolbox"
self.alias = 'ConfinementTB'
#self.description = "Tools for generating Valley Confinement."
# List of tool classes associated with this toolbox
# Not all tool classes are exposed
self.tools = [MovingWindowConfinementTool,SegmentedNetworkConfinementTool,ConfiningMarginTool,ConfinementProjectTool,LoadInputsTool]
#
# Tools
#
class ConfinementProjectTool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Create a New Confinement Project"
self.description = "Start a new Confinment Project. Tool Documentation: https://bitbucket.org/KellyWhitehead/geomorphic-network-and-analysis-toolbox/wiki/Tool_Documentation/MovingWindow"
self.canRunInBackground = False
self.category = "Confinement Project Management"
def getParameterInfo(self):
"""Define parameter definitions"""
param0 = arcpy.Parameter(
displayName="Project Name",
name="projectName",
datatype="GPString",
parameterType="Required",
direction="Input")
param1 = arcpy.Parameter(
displayName="Project Folder",
name="projectFolder",
datatype="DEWorkspace",
parameterType="Required",
direction="Input")
param1.filter.list = ["File System"]
paramBoolNewFolder = arcpy.Parameter(
displayName="Create New Project Folder?",
name="boolNewFolder",
datatype="GPBoolean",
parameterType="Optional",
direction="Input")
param2 = arcpy.Parameter(
displayName="User Name (Operator)",
name="metaOperator",
datatype="GPString",
parameterType="Optional",
direction="Input")
param3 = arcpy.Parameter(
displayName="Region",
name="metaRegion",
datatype="GPString",
parameterType="Optional",
direction="Input")
param3.filter.list = ["CRB"]
param4 = arcpy.Parameter(
displayName="Watershed (HUC 8 Name)",
name="metaWatershed",
datatype="GPString",
parameterType="Optional",
direction="Input")
#TODO add param4.filter.list = [], load and read from program.xml
params = [param0, param1, paramBoolNewFolder, param2, param3, param4]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, p, messages):
"""
Description:
The source code of the tool.
Updates:
15/8/18 - DDH - Useful messages added to inform user and help with debugging.
23/8/18 - DDH - Added error trapping.
"""
try:
projectFolder = p[1].valueAsText
if p[2].valueAsText == "true":
projectFolder = path.join(p[1].valueAsText,p[0].valueAsText)
makedirs(projectFolder)
arcpy.AddMessage("Project folder created.")
# Create Project file
newConfinementProject = Riverscapes.Project()
newConfinementProject.create(p[0].valueAsText, "Confinement", projectPath=projectFolder)
newConfinementProject.addProjectMetadata("Operator",p[3].valueAsText)
newConfinementProject.addProjectMetadata("Region",p[4].valueAsText)
newConfinementProject.addProjectMetadata("Watershed",p[5].valueAsText)
newConfinementProject.addProjectMetadata("ConfinementProjectVersion", ConfinementProjectVersion)
newConfinementProject.addProjectMetadata("ConfinementToolRelease", ConfinementToolReleaseVersion)
newConfinementProject.writeProjectXML()
arcpy.AddMessage("Project file " + newConfinementProject.xmlname + " created.")
return
except Exception as e:
arcpy.AddError("Error in Execute function: " + str(e))
class LoadInputsTool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Load Input Datasets"
self.description = "Load Input Datasets to a Confinement Project. "
self.canRunInBackground = False
self.category = "Confinement Project Management"
def getParameterInfo(self):
''' Description:
Define parameter definitions
Modified:
28/8/18 - DDH - Added 4th parameter and removed code making p1-p3 optional.
'''
p1 = paramStreamNetwork
p2 = paramChannelPolygon
p3 = paramValleyBottom
# Create an option buffer Parameter, the default will be zero metres, if the user changes
# this then the channel polygon will be buffered during the export to shapefile
p4 = arcpy.Parameter(name="paramBufferDistance",displayName="Buffer Channel Polygon (m)",direction="Input",datatype="GPLong",parameterType="Optional",enabled=True,multiValue=False)
p4.value = 0
params = [paramProjectXML,p1,p2,p3,p4]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, p):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
'''
Description:
Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation.
Modified:
28/8/18 - DDH - Check on sensible 4th parameter value, must be zero or greater.
'''
p = parameters[4]
if p.value < 0:
p.setErrorMessage("Negatives buffer distances are invalid, must be zero or greater!")
else:
p.clearMessage()
return
def execute(self, p, messages):
"""
Description:
The source code of the tool.
Updates:
23/8/18 - DDH - Error trapping and useful messages added to inform user and help with debugging.
23/8/18 - DDH - Removed redundant import from module os
28/8/18 - DDH - Added new code that will buffer the channel polygon as it stores it in the project
sub-folder, but only if buffer distance is greater than zero.
"""
try:
# Get a handle on project file (project.rs.xml)
newConfinementProject = Riverscapes.Project(p[0].valueAsText)
pathProject = arcpy.Describe(p[0].valueAsText).path
# Create Project Paths if they do not exist
pathInputs = pathProject + "\\Inputs"
if not arcpy.Exists(pathInputs):
makedirs(pathInputs)
arcpy.AddMessage("Inputs Subfolder created.")
# KMW - The following is a lot of repeated code for each input. It contains file and folder creation and copying, rather than using the project module to do this. This could be streamlined in the future, but
# is working at the moment.
if p[1].valueAsText: # Stream Network Input
pathStreamNetworks = pathInputs + "\\StreamNetworks"
nameStreamNetwork = arcpy.Describe(p[1].valueAsText).basename
if not arcpy.Exists(pathStreamNetworks):
makedirs(pathStreamNetworks)
arcpy.AddMessage("StreamNetworks Subfolder created.")
# Create stream network input sub folder
id_streamnetwork = Riverscapes.get_input_id(pathStreamNetworks, "StreamNetwork")
pathStreamNetworkID = path.join(pathStreamNetworks, id_streamnetwork)
makedirs(pathStreamNetworkID)
arcpy.AddMessage("Subfolder " + id_streamnetwork + " created.")
# Copy dataset to shapefile in input subfolder
arcpy.AddMessage("Copying stream network into its input folder...")
arcpy.FeatureClassToFeatureClass_conversion(p[1].valueAsText, pathStreamNetworkID, nameStreamNetwork)
newConfinementProject.addInputDataset(nameStreamNetwork,id_streamnetwork,path.join(path.relpath(pathStreamNetworkID, pathProject),nameStreamNetwork) + ".shp",p[1].valueAsText)
if p[2].valueAsText: # Channel Polygon
buffDist = p[4].value # This will be a long of 0 or greater
pathChannelPolygons = pathInputs + "\\ChannelPolygons"
nameChannelPolygon = arcpy.Describe(p[2].valueAsText).basename
if not arcpy.Exists(pathChannelPolygons):
makedirs(pathChannelPolygons)
arcpy.AddMessage("ChannelPolygons Subfolder created.")
# Create channel polygon input sub folder
id_channelpolygon = Riverscapes.get_input_id(pathChannelPolygons, "ChannelPolygon")
pathChannelPolygonID = path.join(pathChannelPolygons,id_channelpolygon)
makedirs(pathChannelPolygonID)
arcpy.AddMessage("Subfolder " + id_channelpolygon + " created.")
if buffDist == 0:
# Copy dataset to shapefile in input subfolder
arcpy.AddMessage("Copying channel polygon into its input folder...")
arcpy.FeatureClassToFeatureClass_conversion(p[2].valueAsText, pathChannelPolygonID, nameChannelPolygon)
else:
# Create a buffered version of channel dataset
arcpy.AddMessage("Buffering channel polygon into its input folder...")
outFC = path.join(pathChannelPolygonID, nameChannelPolygon)+ ".shp"
dist = str(buffDist) + " METERS"
arcpy.Buffer_analysis(p[2].valueAsText,outFC,dist,"FULL","ROUND","NONE","#","PLANAR")
newConfinementProject.addInputDataset(nameChannelPolygon,id_channelpolygon,path.join(path.relpath(pathChannelPolygonID, pathProject),nameChannelPolygon) + ".shp",p[2].valueAsText)
if p[3].valueAsText: # Valley Bottom
pathValleyBottoms = pathInputs + "\\ValleyBottoms"
nameValleyBottom = arcpy.Describe(p[3].valueAsText).basename
if not arcpy.Exists(pathValleyBottoms):
makedirs(pathValleyBottoms)
arcpy.AddMessage("ValleyBottoms Subfolder created.")
# Create valley bottom input sub folder
id_valleybottom = Riverscapes.get_input_id(pathValleyBottoms,"ValleyBottom")
pathValleyBottomID = path.join(pathValleyBottoms,id_valleybottom)
makedirs(pathValleyBottomID)
arcpy.AddMessage("Subfolder " + id_valleybottom + " created.")
# Copy dataset to shapefile in input subfolder
arcpy.AddMessage("Copying valley bottoms into its input folder...")
arcpy.FeatureClassToFeatureClass_conversion(p[3].valueAsText,pathValleyBottomID,nameValleyBottom)
newConfinementProject.addInputDataset(nameValleyBottom,id_valleybottom,path.join(path.relpath(pathValleyBottomID,pathProject),nameValleyBottom) + ".shp",p[3].valueAsText)
# Write new XML
newConfinementProject.writeProjectXML(p[0].valueAsText)
return
except Exception as e:
arcpy.AddError("Error in Execute function: " + str(e))
class LoadInputsFromProjectTool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Load Input Datasets From Other Projects"
self.description = "Load Input Datasets to a Confinement Project. "
self.canRunInBackground = False
self.category = "Confinement Project Management"
def getParameterInfo(self):
"""Define parameter definitions"""
p1_project = get_projectxml_param("Source GNAT Project for Stream Networks")
p1 = arcpy.Parameter("StreamNetwork", "Stream Networks", "Input", "GPString", "Optional", multiValue=True)
p1.filter.list = []
p2 = paramChannelPolygon
p2.enabled = False
p3_project = get_projectxml_param("Source VBET Project for Valley Bottom Polygon")
p3 = paramValleyBottom
p3.enabled = False
p3_project.enabled = False
params = [paramProjectXML,p1_project,p1,p2,p3_project,p3]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, p):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
# Todo better check for type of project (GNAT only) and if exists, and if empty datasets
if p[1].value:
if arcpy.Exists(p[1].valueAsText):
project_streamnetwork = Riverscapes.Project(p[1].valueAsText)
p[2].filter.list = []
filter_list = []
for realizationName, realization in project_streamnetwork.Realizations.iteritems():
filter_list.append(realizationName + " " +
realization.GNAT_StreamNetwork.name +
" (" + realization.GNAT_StreamNetwork.absolutePath(project_streamnetwork.projectPath) + ") [" +
realization.GNAT_StreamNetwork.guid + "]")
p[2].filter.list = filter_list
if p[4].value:
if arcpy.Exists(p[4].valuAsText):
project_vbet = Riverscapes.Project()
project_vbet.loadProjectXML(p[1].valueAsText)
filter_list = []
for realizationName, realization in project_vbet.Realizations.iteritems():
filter_list.append(realizationName + " " + realization.GNAT_StreamNetwork.name + " (" + realization.GNAT_StreamNetwork.absolutePath(project_vbet.projectPath) + ")")
p[4].filter.list = filter_list
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, p, messages):
"""The source code of the tool."""
ConfinementProject = Riverscapes.Project(p[0].valueAsText)
# Create Project Paths if they do not exist
pathInputs = ConfinementProject.projectPath + "\\Inputs"
if not arcpy.Exists(pathInputs):
makedirs(pathInputs)
# Stream Network Input
for value in p[2].valueAsText.split(";"):
stream_network = value[value.find("(") + 1:value.find(")") ]
pathStreamNetworks = pathInputs + "\\StreamNetworks"
nameStreamNetwork = arcpy.Describe(stream_network).basename
if not arcpy.Exists(pathStreamNetworks):
makedirs(pathStreamNetworks)
id_streamnetwork = Riverscapes.get_input_id(pathStreamNetworks, "StreamNetwork")
pathStreamNetworkID = path.join(pathStreamNetworks, id_streamnetwork)
makedirs(pathStreamNetworkID)
arcpy.FeatureClassToFeatureClass_conversion(stream_network, pathStreamNetworkID, nameStreamNetwork)
#ConfinementProject.addInputDataset(nameStreamNetwork,
# id_streamnetwork,
# path.join(path.relpath(pathStreamNetworkID,
# ConfinementProject.projectPath),
# nameStreamNetwork) + ".shp",
# p[1].valueAsText)
dataset = Riverscapes.Dataset()
dataset.create(nameStreamNetwork,
path.join(path.relpath(pathStreamNetworkID,ConfinementProject.projectPath)),
"StreamNetwork",
stream_network)
dataset.guid = value[value.find("[") + 1:value.find("]") - 1]
ConfinementProject.InputDatasets[id_streamnetwork] = dataset
# if p[2].valueAsText: # Channel Polygon
# pathChannelPolygons = pathInputs + "\\ChannelPolygons"
# nameChannelPolygon = arcpy.Describe(p[2].valueAsText).basename
# if not arcpy.Exists(pathChannelPolygons):
# makedirs(pathChannelPolygons)
# id_channelpolygon = Riverscapes.get_input_id(pathChannelPolygons, "ChannelPolygon")
# pathChannelPolygonID = path.join(pathChannelPolygons, id_channelpolygon)
# makedirs(pathChannelPolygonID)
# arcpy.FeatureClassToFeatureClass_conversion(p[2].valueAsText, pathChannelPolygonID, nameChannelPolygon)
# newConfinementProject.addInputDataset(nameChannelPolygon,
# id_channelpolygon,
# path.join(path.relpath(pathChannelPolygonID, pathProject),
# nameChannelPolygon) + ".shp",
# p[2].valueAsText)
if p[3].valueAsText: # Valley Bottom
pathValleyBottoms = pathInputs + "\\ValleyBottoms"
nameValleyBottom = arcpy.Describe(p[3].valueAsText).basename
if not arcpy.Exists(pathValleyBottoms):
makedirs(pathValleyBottoms)
id_valleybottom = Riverscapes.get_input_id(pathValleyBottoms, "ValleyBottom")
pathValleyBottomID = path.join(pathValleyBottoms, id_valleybottom)
makedirs(pathValleyBottomID)
arcpy.FeatureClassToFeatureClass_conversion(p[3].valueAsText, pathValleyBottomID, nameValleyBottom)
ConfinementProject.addInputDataset(nameValleyBottom,
id_valleybottom,
path.join(path.relpath(pathValleyBottomID, ConfinementProject.projectPath),
nameValleyBottom) + ".shp",
p[3].valueAsText)
# Write new XML
ConfinementProject.writeProjectXML(p[0].valueAsText)
return
###### Realizations ######
class ConfiningMarginTool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Confining Margins Tool"
self.description = "Determine the Confining Margins using the Stream Network, Channel Buffer Polygon, and Valley Bottom Polygon."
self.canRunInBackground = "False"
self.Category = 'Confinement Tools'
def getParameterInfo(self):
'''
Description:
Define parameter definitions
Updates: 5/9/18 - DDH - Added Filter by Length Parameter
'''
# 0
# paramProjectXML
#paramProjectXML.filter.list = ["xml"]
# 1 - Required as it sets the output names to their default names. If this parameter was not set then the output controls disable and don't allow you
# to enter a shapefile dataset name!
paramRealizationName = arcpy.Parameter(displayName="Confinement Realization Name", name="realizationName", datatype="GPString", parameterType="Required", direction="Input")
# 2
paramStreamNetwork = arcpy.Parameter(displayName="Input Stream Network", name="InputFCStreamNetwork", datatype="GPFeatureLayer", parameterType="Required", direction="Input")
paramStreamNetwork.filter.list = ["Polyline"]
paramValleyBottom = arcpy.Parameter(displayName="Input Valley Bottom Polygon", name="InputValleyBottomPolygon", datatype="GPFeatureLayer", parameterType="Required", direction="Input")
paramValleyBottom.filter.list = ["Polygon"]
paramChannelPolygon = arcpy.Parameter(displayName="Input Active Channel Polygon (Buffered Bankfull)", name="InputBankfullChannelPoly", datatype="GPFeatureLayer", parameterType="Required", direction="Input")
paramChannelPolygon.filter.list = ["Polygon"]
paramOutputRawConfiningState = arcpy.Parameter(displayName="Output Raw Confining State", name="outputRawConfiningState", datatype="DEFeatureClass", parameterType="Optional", direction="Output",)
paramOutputRawConfiningState.symbology = path.join(path_lyr,"") + "Raw_Confining_State.lyr"
paramOutputConfiningMargins = arcpy.Parameter(displayName="Output Confining Margins", name="fcOutputConfiningMargins", datatype="DEFeatureClass", parameterType="Optional", direction="Output")
paramOutputConfiningMargins.symbology = path.join(path_lyr,"") + "Confining_Margins.lyr"
paramFilterByLength = arcpy.Parameter(name="FilterByLength",displayName="Filter by Length (m)",direction="Input",datatype="GPDouble",parameterType="Required")
paramFilterByLength.value = 5 # Default value of 5m
# Note: Parameters common to all tools are defined from lines at end of code.
return [paramProjectXML,paramRealizationName,paramStreamNetwork,paramValleyBottom,paramChannelPolygon,paramFilterByLength,paramOutputRawConfiningState,paramOutputConfiningMargins,paramTempWorkspace]
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, p):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if p[0].altered:
if p[0].value and arcpy.Exists(p[0].valueAsText):
# Set Project Mode
p[6].enabled = "False"
p[7].enabled = "False"
p[6].parameterType = "Optional"
p[7].parameterType = "Optional"
currentProject = Riverscapes.Project(p[0].valueAsText)
# This section of code fails so has been commented out. It is trying to load a list of string values which are featureclass paths into
# a control that is expecting a FEATURECLASS with the filter set to a specific geometry type.
# We could make the control a GPString then this logic would work but then it messes up the LoadsInputTool. This problem stems
# from the odd behaviour of creating generic parameters at the end of the code.
#
# DDH - 15/8/18
## listInputDatasets = []
## for name,inputDataset in currentProject.InputDatasets.iteritems():
## listInputDatasets.append(inputDataset.absolutePath(currentProject.projectPath))
## p[2].filter.list = listInputDatasets
## p[3].filter.list = listInputDatasets
## p[4].filter.list = listInputDatasets
if p[1].altered:
if p[1].valueAsText:
realization_id = currentProject.get_next_realization_id()
p[6].value = path.join(currentProject.projectPath, "Outputs", realization_id) + "\\RawConfiningState.shp"
p[7].value = path.join(currentProject.projectPath, "Outputs", realization_id) + "\\ConfiningMargins.shp"
else:
p[6].enabled = "True"
p[7].enabled = "True"
p[6].parameterType = "Required"
p[7].parameterType = "Optional"
return
def updateMessages(self, parameters):
'''
Description:
Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation.
Updates: 5/9/18 - DDH - Added error check for filter by length parameter and updated parameter indices
'''
if parameters[0].valueAsText:
newConfinementProject = Riverscapes.Project(parameters[0].valueAsText)
for realization in newConfinementProject.Realizations:
if realization == parameters[1].valueAsText:
parameters[1].setErrorMessage("Realization " + parameters[1].valueAsText + " already exists.")
return
# Check if filter value is negative
if parameters[5].value < 0:
parameters[5].setErrorMessage("Negative filter lengths are invalid, must be zero or greater")
else:
parameters[5].clearMessage()
# Run a bunch a quality control tests on inputs and set any appropriate warnings
testProjected(parameters[2])
testProjected(parameters[3])
testProjected(parameters[4])
testMValues(parameters[2])
testMValues(parameters[3])
testMValues(parameters[4])
testLayerSelection(parameters[2])
testLayerSelection(parameters[3])
testLayerSelection(parameters[4])
testWorkspacePath(parameters[8])
return
def execute(self, p, messages):
'''
Description:
The source code of the tool.
Updates: 5/9/18 - DDH - Indices changed due to new filter by length parameter
'''
reload(ConfiningMargins)
# if in project mode, create workspaces as needed.
if p[0].valueAsText:
newConfinementProject = Riverscapes.Project(p[0].valueAsText)
if p[1].valueAsText:
realization_id = newConfinementProject.get_next_realization_id()
makedirs(path.join(newConfinementProject.projectPath, "Outputs", realization_id))
bOK = ConfiningMargins.main(p[2].valueAsText,p[3].valueAsText,p[4].valueAsText,p[5].value,p[6].valueAsText,p[7].valueAsText,getTempWorkspace(p[8].valueAsText),False) # If Not specified, in memory is used
if bOK:
# on success, rewrite xml file if in project mode
if p[0].valueAsText:
arcpy.AddMessage("... Updating project file")
newConfinementProject = Riverscapes.Project() # ConfinementProject.ConfinementProject()
newConfinementProject.loadProjectXML(p[0].valueAsText)
idStreamNetwork = newConfinementProject.get_dataset_id(p[2].valueAsText)
idValleyBottom = newConfinementProject.get_dataset_id(p[3].valueAsText)
idChannelPolygon = newConfinementProject.get_dataset_id(p[4].valueAsText)
# DDH - This line was causing tool to fail, after trying to follow logic I think this code was attempting retrieve a realization ID before it ever existed
# So I Commented it out and replaced it with the below line, this seems to be work, original code was newConfinementProject.Realizations[p[1].valueAsText].id
idRealization = realization_id
outputRawConfiningState = Riverscapes.Dataset()
outputRawConfiningState.create(arcpy.Describe(p[6].valueAsText).basename, path.join("Outputs", idRealization, "RawConfiningState" ) + ".shp")
outputConfiningMargins = Riverscapes.Dataset()
outputConfiningMargins.create(arcpy.Describe(p[7].valueAsText).basename, path.join("Outputs", idRealization, "ConfiningMargins") + ".shp")
newRealization = Riverscapes.ConfinementRealization()
newRealization.createConfinementRealization(p[1].valueAsText, idStreamNetwork, idValleyBottom, idChannelPolygon, outputConfiningMargins, outputRawConfiningState)
newRealization.productVersion = ConfinementToolReleaseVersion
newConfinementProject.addRealization(newRealization)
newConfinementProject.writeProjectXML()
else:
arcpy.AddError("Main processing algorithm failed, project file not updated!")
return
class ConfiningMarginTool2(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Confining Margins Tool (Linked Projects)"
self.description = "Determine the Confining Margins using the Stream Network, Channel Buffer Polygon, and Valley Bottom Polygon."
self.canRunInBackground = "False"
self.Category = 'Confinement Tools'
def getParameterInfo(self):
"""Define parameter definitions"""
paramConfinementProjectXML = get_projectxml_param("Confinement Project rs.xml file")
paramRealizationName = arcpy.Parameter(
displayName="Confinement Realization Name",
name="realizationName",
datatype="GPString",
parameterType="Optional",
direction="Input")
paramOutputRawConfiningState = arcpy.Parameter(
displayName="Output Raw Confining State",
name="outputRawConfiningState",
datatype="DEFeatureClass",
parameterType="Optional",
direction="Output")
paramOutputConfiningMargins = arcpy.Parameter(
displayName="Output Confining Margins",
name="fcOutputConfiningMargins",
datatype="DEFeatureClass",
parameterType="Optional",
direction="Output")
paramGNATProjectXML = get_projectxml_param("Source Project of Stream Network Layers (GNAT)","Link Inputs from Projects")
paramGNATLayerFinder = arcpy.Parameter(
displayName="Available Stream Networks",
name="strStreamNetwork",
datatype="GPString",
parameterType="Optional",
direction="Input",
category="Link Inputs from Projects")
paramActiveChannelProject = get_projectxml_param("Source Project of Active Channel Polygons", "Link Inputs from Projects")
paramACPLayerFinder = arcpy.Parameter(
displayName="Available Active Channel Polygons",
name="strChannelPolygon",
datatype="GPString",
parameterType="Optional",
direction="Input",
category="Link Inputs from Projects")
paramVBETProjectXML = get_projectxml_param("Source Project of Valley Bottom Polygons (VBET)","Link Inputs from Projects")
paramVBETLayerFinder = arcpy.Parameter(
displayName="Available VBET Polygons",
name="strVBET",
datatype="GPString",
parameterType="Optional",
direction="Input",
category="Link Inputs from Projects")
paramActiveChannelProject.enabled = "False"
paramACPLayerFinder.enabled = "False"
return [paramProjectXML, #0
paramRealizationName, #1
paramStreamNetwork, #2
paramChannelPolygon, #3
paramValleyBottom, #4
paramOutputRawConfiningState, #5
paramOutputConfiningMargins, #6
paramTempWorkspace, #7
paramGNATProjectXML, #8
paramGNATLayerFinder, #9
paramActiveChannelProject, #10
paramACPLayerFinder, #11
paramVBETProjectXML, #12
paramVBETLayerFinder] #13
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, p):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if p[0].altered:
if p[0].value and arcpy.Exists(p[0].valueAsText):
# Set Project Mode
p[5].enabled = "False"
p[6].enabled = "False"
p[5].parameterType = "Optional"
p[6].parameterType = "Optional"
currentProject = Riverscapes.Project(p[0].valueAsText)
# listInputDatasets = []
# for name, inputDataset in currentProject.InputDatasets.iteritems():
# listInputDatasets.append(inputDataset.absolutePath(currentProject.projectPath))
# p[2].filter.list = listInputDatasets
# p[3].filter.list = listInputDatasets
# p[4].filter.list = listInputDatasets
if p[1].altered:
if p[1].value:
p[5].value = path.join(currentProject.projectPath, "Outputs",
p[1].valueAsText) + "\\RawConfiningState.shp"
p[6].value = path.join(currentProject.projectPath, "Outputs",
p[1].valueAsText) + "\\ConfiningMargins.shp"
# TODO manage output folder if project mode
else:
p[5].enabled = "True"
p[6].enabled = "True"
p[5].parameterType = "Required"
p[6].parameterType = "Optional"
if p[8].altered:
if p[8].value:
if arcpy.Exists(p[8].valueAsText):
p[9].enabled = "True"
p[9].filter.list = []
GNATproject = Riverscapes.Project(p[8].valueAsText)
listGNATpaths = []
for realizationName, realization in GNATproject.Realizations.iteritems():
listGNATpaths.append(realizationName + " " + realization.GNAT_StreamNetwork.name +
" (" + realization.GNAT_StreamNetwork.absolutePath(GNATproject.projectPath) +
") [" + realization.GNAT_StreamNetwork.guid + "]")
for analysisName, analysis in realization.analyses.iteritems():
for dataset in analysis.outputDatasets.values():
listGNATpaths.append(realizationName + " " + analysisName + " (" +
dataset.absolutePath(GNATproject.projectPath) + ") [" +
dataset.guid + "]")
p[9].filter.list = listGNATpaths
else:
p[9].enabled = "False"
else:
p[9].enabled = "False"
if p[9].altered:
if p[9].value:
p[2].value = p[9].value[p[9].value.find("(") + 1:p[9].value.find(")") ]
p[9].enabled = "False"
if p[12].altered:
if p[12].value:
if arcpy.Exists(p[12].valueAsText):
p[13].enabled = "True"
p[13].filter.list = []
VBETproject = Riverscapes.Project(p[12].valueAsText)
listVBETpaths = []
for realizationName, realization in VBETproject.Realizations.iteritems():
# listVBETpaths.append(realizationName + " " + realization.GNAT_StreamNetwork.name +
# " (" + realization. .absolutePath(
# VBETproject.projectPath) +
# ") [" + realization..guid + "]")
for analysisName, analysis in realization.analyses.iteritems():
for dataset in analysis.outputDatasets.values():
strGUID = ""
if dataset.guid:
strGUID = " [" + dataset.guid + "]"
listVBETpaths.append(realizationName + " " + analysisName + " (" +
dataset.absolutePath(VBETproject.projectPath) + ")" + strGUID)
p[13].filter.list = listVBETpaths
else:
p[13].enabled = "False"
else:
p[13].enabled = "False"
if p[13].altered:
if p[13].value:
p[4].value = p[13].value[p[13].value.find("(") + 1:p[13].value.find(")")]
p[13].enabled = "False"
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
if parameters[0].valueAsText:
newConfinementProject = Riverscapes.Project(parameters[0].valueAsText)
for realization in newConfinementProject.Realizations:
if realization == parameters[1].valueAsText:
parameters[1].setErrorMessage("Realization " + parameters[1].valueAsText + " already exists.")
return
testProjected(parameters[2])
testProjected(parameters[3])
testProjected(parameters[4])
testMValues(parameters[2])
testMValues(parameters[3])
testMValues(parameters[4])
testLayerSelection(parameters[2])
testLayerSelection(parameters[3])
testLayerSelection(parameters[4])
testWorkspacePath(parameters[7])
return
def execute(self, p, messages):
"""The source code of the tool."""
reload(ConfiningMargins)
# if in project mode, create workspaces as needed.
if p[0].valueAsText:
newConfinementProject = Riverscapes.Project(p[0].valueAsText) # ConfinementProject.ConfinementProject()
if p[1].valueAsText:
makedirs(path.join(newConfinementProject.projectPath, "Outputs", p[1].valueAsText))
# Create Project Paths if they do not exist
pathInputs = newConfinementProject.projectPath + "\\Inputs"
if not arcpy.Exists(pathInputs):
makedirs(pathInputs)
if p[2].valueAsText and not p[9].valueAsText: # Stream Network Input
pathStreamNetworks = pathInputs + "\\StreamNetworks"
nameStreamNetwork = arcpy.Describe(p[2].valueAsText).basename
if not arcpy.Exists(pathStreamNetworks):
makedirs(pathStreamNetworks)
id_streamnetwork = Riverscapes.get_input_id(pathStreamNetworks, "StreamNetwork")
pathStreamNetworkID = path.join(pathStreamNetworks, id_streamnetwork)
makedirs(pathStreamNetworkID)
arcpy.FeatureClassToFeatureClass_conversion(p[1].valueAsText, pathStreamNetworkID, nameStreamNetwork)
newConfinementProject.addInputDataset(nameStreamNetwork,
id_streamnetwork,
path.join(path.relpath(pathStreamNetworkID,
newConfinementProject.projectPath),
nameStreamNetwork) + ".shp",
p[2].valueAsText)
if p[2].valueAsText and not p[11].valueAsText: # Channel Polygon
pathChannelPolygons = pathInputs + "\\ChannelPolygons"
nameChannelPolygon = arcpy.Describe(p[2].valueAsText).basename
if not arcpy.Exists(pathChannelPolygons):
makedirs(pathChannelPolygons)
id_channelpolygon = Riverscapes.get_input_id(pathChannelPolygons, "ChannelPolygon")
pathChannelPolygonID = path.join(pathChannelPolygons,id_channelpolygon)
makedirs(pathChannelPolygonID)
arcpy.FeatureClassToFeatureClass_conversion(p[2].valueAsText, pathChannelPolygonID, nameChannelPolygon)
newConfinementProject.addInputDataset(nameChannelPolygon,
id_channelpolygon,
path.join(path.relpath(pathChannelPolygonID, newConfinementProject.projectPath),
nameChannelPolygon) + ".shp",
p[2].valueAsText)
if p[3].valueAsText and not p[13].valueAsText: # Valley Bottom
pathValleyBottoms = pathInputs + "\\ValleyBottoms"
nameValleyBottom = arcpy.Describe(p[3].valueAsText).basename
if not arcpy.Exists(pathValleyBottoms):
makedirs(pathValleyBottoms)
id_valleybottom = Riverscapes.get_input_id(pathValleyBottoms,"ValleyBottom")
pathValleyBottomID = path.join(pathValleyBottoms,id_valleybottom)
makedirs(pathValleyBottomID)
arcpy.FeatureClassToFeatureClass_conversion(p[3].valueAsText,pathValleyBottomID,nameValleyBottom)
newConfinementProject.addInputDataset(nameValleyBottom,
id_valleybottom,
path.join(path.relpath(pathValleyBottomID,
newConfinementProject.projectPath),
nameValleyBottom) + ".shp",
p[3].valueAsText)
ConfiningMargins.main(p[2].valueAsText,
p[3].valueAsText,
p[4].valueAsText,
p[5].valueAsText,
p[6].valueAsText,
getTempWorkspace(p[7].valueAsText),
False) # If Not specified, in memory is used
# on success, rewrite xml file if in project mode
if p[0].valueAsText:
newConfinementProject = Riverscapes.Project() # ConfinementProject.ConfinementProject()
newConfinementProject.loadProjectXML(p[0].valueAsText)
idStreamNetwork = newConfinementProject.get_dataset_id(p[2].valueAsText)
idValleyBottom = newConfinementProject.get_dataset_id(p[3].valueAsText)
idChannelPolygon = newConfinementProject.get_dataset_id(p[4].valueAsText)
outputRawConfiningState = Riverscapes.Dataset()
outputRawConfiningState.create(arcpy.Describe(p[5].valueAsText).basename,
p[5].valueAsText) # TODO make this relative path
outputConfiningMargins = Riverscapes.Dataset()
outputConfiningMargins.create(arcpy.Describe(p[6].valueAsText).basename, p[6].valueAsText)
newRealization = Riverscapes.ConfinementRealization()
newRealization.createConfinementRealization(p[1].valueAsText,
idStreamNetwork,
idValleyBottom,
idChannelPolygon,
outputConfiningMargins,
outputRawConfiningState)
newConfinementProject.addRealization(newRealization)
newConfinementProject.writeProjectXML(p[0].valueAsText)
return
###### Analysis Tools ######
class MovingWindowConfinementTool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Moving Window Confinement"
self.description = "Calculate the Valley Confinement using moving windows."
self.category = 'Confinement Tools\\Analysis'
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# 0
# paramProjectXML
# 1
paramRealization = arcpy.Parameter(
displayName="Confinement Realization Name",
name="realizationName",
datatype="GPString",
parameterType="Optional",
direction="Input")
paramRealization.enabled = "False"
# 2
#paramAnalysisName
# 3
#paramStreamNetwork
# 4
paramFieldDissolve = arcpy.Parameter(
displayName="Dissolve Field (Stream Branch ID)",
name="fieldStreamID",
datatype="GPString",
parameterType="Required",
direction="Input")
paramFieldDissolve.filter.list = []
# 5
paramFieldConfiningState = arcpy.Parameter(
displayName="Confining State Field",
name="fieldConfinement",
datatype="GPString",
parameterType="Required",
direction="Input")
paramFieldConfiningState.filter.list = []
# 6
paramFieldConstriction = arcpy.Parameter(
displayName="Constriction State Field",
name="fieldConstriction",
datatype="GPString",
parameterType="Required",
direction="Input")
paramFieldConstriction.filter.list = []
# 7
paramSeedPointDistance = arcpy.Parameter(
displayName="Seed Point Distance",
name="dblSeedPointDistance",
datatype="GPDouble",
parameterType="Required",
direction="Input")
# paramSeedPointDistance.value = 50
# 8
paramWindowSizes = arcpy.Parameter(
displayName="Window Sizes",
name="inputWindowSizes",
datatype="GPDouble",
parameterType="Required",