-
Notifications
You must be signed in to change notification settings - Fork 3
/
tierFunctions.py
2677 lines (2220 loc) · 132 KB
/
tierFunctions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import required modules and extensions
import arcpy
import os
import math
import numpy
import fnmatch
import tempfile
from arcpy.sa import *
arcpy.CheckOutExtension('Spatial')
arcpy.CheckOutExtension('3D')
# --integrated width function--
# calculates integrated width
# as: [polygon area] / [sum(centerline lengths)]
def intWidth_fn(polygon, centerline):
arrPoly = arcpy.da.FeatureClassToNumPyArray(polygon, ['SHAPE@AREA'])
arrPolyArea = arrPoly['SHAPE@AREA'].sum()
arrCL = arcpy.da.FeatureClassToNumPyArray(centerline, ['SHAPE@LENGTH'])
arrCLLength = arrCL['SHAPE@LENGTH'].sum()
intWidth = round(arrPolyArea / arrCLLength, 1)
return intWidth
def guAttributes(units, bfw, dem, tmp_thalwegs, bfSlope, bfSlope_Smooth, evpath, **myVars):
fields = arcpy.ListFields(units)
keep = ['ValleyUnit', 'UnitShape', 'UnitForm', 'GU', 'GUKey', 'FlowUnit']
drop = []
for field in fields:
if not field.required and field.name not in keep and field.type <> 'Geometry':
drop.append(field.name)
if len(drop) > 0:
arcpy.DeleteField_management(units, drop)
# add attribute fields to tier units shapefile
nfields = [('UnitID', 'SHORT', ''), ('ForceType', 'TEXT', '25'), ('ForceElem', 'TEXT', '25'), ('ForceHyd', 'TEXT', '15'),
('Perimeter', 'DOUBLE', ''), ('ElongRatio', 'DOUBLE', ''), ('Morphology', 'TEXT', '20'),
('Position', 'TEXT', '20'), ('Orient', 'DOUBLE', ''), ('OrientCat', 'TEXT', '15'),
('bfSlope', 'DOUBLE', ''), ('bfSlopeSm', 'DOUBLE', ''), ('bedSlope', 'DOUBLE', '')]
for nfield in nfields:
arcpy.AddField_management(units, nfield[0], nfield[1], '', '', nfield[2])
if not 'Area' in [f.name for f in arcpy.ListFields(units)]:
arcpy.AddField_management(units, 'Area', 'DOUBLE')
if 'OnThalweg' in [f.name for f in arcpy.ListFields(units)]:
arcpy.DeleteField_management(units, ['OnThalweg'])
print "Calculating tier 3 GU attributes..."
# create unit id field to make sure joins correctly execute
# populate area, perimeter attribute fields
print '...unit area, perimeter...'
fields = ['OID@', 'UnitID', 'SHAPE@Area', 'Area', 'SHAPE@LENGTH', 'Perimeter', 'ForceType', 'ForceElem', 'ForceHyd']
with arcpy.da.UpdateCursor(units, fields) as cursor:
for row in cursor:
row[1] = row[0]
row[3] = row[2]
row[5] = row[4]
row[6] = 'NA'
row[7] = 'NA'
row[8] = 'NA'
cursor.updateRow(row)
print "...unit length, width, length to width ratio and orientation..."
# calculate unit length, width, orientation (i.e., angle) using minimum bounding polygon
unit_minbound = arcpy.MinimumBoundingGeometry_management(units, 'in_memory/units_minbound', 'RECTANGLE_BY_WIDTH', '', '', 'MBG_FIELDS')
# add attribute fields to minimum bounding units
nfields = [('Width', 'DOUBLE', ''), ('Length', 'DOUBLE', ''), ('LtoWRatio', 'DOUBLE', ''),
('bfwRatio', 'DOUBLE', ''), ('unitOrient', 'DOUBLE', '')]
for nfield in nfields:
arcpy.AddField_management(unit_minbound, nfield[0], nfield[1], '', '', nfield[2])
fields = ['Area', 'MBG_Length', 'MBG_Orientation', 'Width', 'Length', 'unitOrient', 'LtoWRatio', 'bfwRatio']
with arcpy.da.UpdateCursor(unit_minbound, fields) as cursor:
for row in cursor:
row[4] = row[1]
row[3] = row[0] / row[4]
row[6] = row[4] / row[3]
if row[2] > 90.0:
row[5] = row[2] - 180
else:
row[5] = row[2]
row[7] = row[3] / bfw
cursor.updateRow(row)
arcpy.JoinField_management(units, 'UnitID', unit_minbound, 'UnitID', ['Length', 'Width', 'LtoWRatio', 'bfwRatio', 'unitOrient'])
print "...unit orientation relative to centerline..."
# calculate centerline orientation for each unit
# a. create points at regular interval (bfw) along bankfull centerlines
# run seperatly for each centerline
cl_pts = arcpy.CreateFeatureclass_management('in_memory', 'cl_pts', 'POINT', '', 'DISABLED', 'DISABLED', dem)
arcpy.AddField_management(cl_pts, 'UID', 'LONG')
arcpy.AddField_management(cl_pts, 'lineDist', 'DOUBLE')
search_fields = ['SHAPE@', 'OID@']
insert_fields = ['SHAPE@', 'UID', 'lineDist']
distance = bfw
with arcpy.da.SearchCursor(os.path.join(myVars['workspace'], myVars['bfCL']), search_fields) as search:
with arcpy.da.InsertCursor(cl_pts, insert_fields) as insert:
for row in search:
try:
line_geom = row[0]
length = float(line_geom.length)
count = distance
oid = int(1)
while count <= length:
point = line_geom.positionAlongLine(count, False)
insert.insertRow((point, oid, count))
oid += 1
count += distance
except Exception as e:
arcpy.AddMessage(str(e.message))
# b. split bankfull centerline at centerline interval points
bfcl_split = arcpy.SplitLineAtPoint_management(os.path.join(myVars['workspace'], myVars['bfCL']), cl_pts, 'in_memory/bfcl_split', '0.1 Meters')
# d. get centerline segment oreintation using minimum bounding geometry
cl_minbound = arcpy.MinimumBoundingGeometry_management(bfcl_split, 'in_memory/cl_minbound', 'RECTANGLE_BY_WIDTH', '', '', 'MBG_FIELDS')
arcpy.AddField_management(cl_minbound, 'clOrient', 'DOUBLE')
fields = ['MBG_Orientation', 'clOrient']
with arcpy.da.UpdateCursor(cl_minbound, fields) as cursor:
for row in cursor:
if row[0] > 90.0:
row[1] = row[0] - 180
else:
row[1] = row[0]
cursor.updateRow(row)
arcpy.JoinField_management(bfcl_split, 'FID', cl_minbound, 'ORIG_FID', ['clOrient'])
# c. create unit polygon centroids
unit_centroid = arcpy.FeatureToPoint_management(units, 'in_memory/unit_centroid', 'INSIDE')
# d. find centerline segment that is closest to unit centroid and join to unit polygon
arcpy.Near_analysis(unit_centroid, bfcl_split)
arcpy.JoinField_management(unit_centroid, 'NEAR_FID', bfcl_split, 'FID', ['clOrient'])
arcpy.JoinField_management(units, 'FID', unit_centroid, 'ORIG_FID', ['clOrient'])
# e. find orientation of unit relative to centerline (unit orientation - centerline orientation)
fields = ['unitOrient', 'clOrient', 'Orient']
with arcpy.da.UpdateCursor(units, fields) as cursor:
for row in cursor:
row[2] = float(row[0]) - float(row[1])
cursor.updateRow(row)
arcpy.DeleteField_management(units, ['unitOrient', 'clOrient'])
with arcpy.da.UpdateCursor(units, ['Orient', 'OrientCat']) as cursor:
for row in cursor:
if abs(row[0]) >= 75 and abs(row[0]) <= 105:
row[1] = 'Transverse'
elif abs(row[0]) <= 15 or abs(row[0]) >= 165:
row[1] = 'Longitudinal'
else:
row[1] = 'Diagonal'
cursor.updateRow(row)
# --calculate unit elongation ratio--
print '...elongation ratio...'
# get long axis minimum bounding geometry using convex hull
fields = ['Area', 'Length', 'ElongRatio', 'Morphology']
with arcpy.da.UpdateCursor(units, fields) as cursor:
for row in cursor:
row[2] = (2 * (math.sqrt(row[0] / 3.14159))) / row[1]
if row[2] < 0.6:
row[3] = 'Elongated'
cursor.updateRow(row)
# --calculate unit position--
print '...unit position...'
onEdge_buffer = arcpy.Buffer_analysis('edge_lyr', 'in_memory/onEdge_buffer', 0.05 * bfw)
nearEdge_buffer = arcpy.Buffer_analysis('edge_lyr', 'in_memory/nearEdge_buffer', 0.1 * bfw)
edge_units = arcpy.SpatialJoin_analysis(onEdge_buffer, units, 'in_memory/tmp_edge_units', 'JOIN_ONE_TO_MANY',
'',
'', 'INTERSECT')
edge_tbl = arcpy.Frequency_analysis(edge_units, 'tbl_edge_units.dbf', ['UnitID'])
arcpy.AddField_management(edge_tbl, 'onEdge', 'SHORT')
arcpy.CalculateField_management(edge_tbl, 'onEdge', '!FREQUENCY!', 'PYTHON_9.3')
arcpy.JoinField_management(units, 'UnitID', edge_tbl, 'UnitID', ['onEdge'])
edge_units2 = arcpy.SpatialJoin_analysis(nearEdge_buffer, units, 'in_memory/tmp_edge_units', 'JOIN_ONE_TO_MANY',
'',
'', 'INTERSECT')
edge_tbl2 = arcpy.Frequency_analysis(edge_units2, 'tbl_edge_units2.dbf', ['UnitID'])
arcpy.AddField_management(edge_tbl2, 'nearEdge1', 'SHORT')
arcpy.CalculateField_management(edge_tbl2, 'nearEdge1', '!FREQUENCY!', 'PYTHON_9.3')
arcpy.JoinField_management(units, 'UnitID', edge_tbl2, 'UnitID', ['nearEdge1'])
# arcpy.SelectLayerByAttribute_management('edge_lyr', 'NEW_SELECTION', """ "midEdge" = 'Yes' """)
# arcpy.SelectLayerByLocation_management('units_lyr', 'INTERSECT', 'edge_lyr', '', 'NEW_SELECTION')
#
# with arcpy.da.UpdateCursor('units_lyr', ['onEdge', 'nearEdge1']) as cursor:
# for row in cursor:
# if row[0] > 0:
# row[0] = row[0] - 1
# if row[1] > 0:
# row[1] = row[1] - 1
# cursor.updateRow(row)
arcpy.SelectLayerByAttribute_management('edge_lyr', 'CLEAR_SELECTION')
arcpy.AddField_management(units, 'nearEdge', 'SHORT')
with arcpy.da.UpdateCursor(units, ['onEdge', 'nearEdge1', 'nearEdge']) as cursor:
for row in cursor:
if row[0] < 1:
row[0] = 0
if row[1] < 1:
row[1] = 0
row[2] = abs(row[0] - row[1])
cursor.updateRow(row)
fields = ['onEdge', 'nearEdge', 'Position']
with arcpy.da.UpdateCursor(units, fields) as cursor:
for row in cursor:
if row[0] == 1:
row[2] = 'Margin Attached'
elif row[0] >= 2:
row[2] = 'Channel Spanning'
elif row[1] == 1:
row[2] = 'Margin Detached'
else:
row[2] = 'Mid Channel'
cursor.updateRow(row)
arcpy.DeleteField_management(units, ['onEdge', 'nearEdge1', 'nearEdge'])
# --calculate thalweg intersection--
print '...thalweg intersection...'
unit_thalweg_ch = arcpy.SpatialJoin_analysis(units, tmp_thalwegs, 'in_memory/unit_thalwegs_ch', 'JOIN_ONE_TO_MANY', '', '', 'INTERSECT')
channelDict = {} # create a dictionary for unit/thalweg channel
thalwegDict = {} # create a dictionary for unit/thalweg type
with arcpy.da.SearchCursor(unit_thalweg_ch, ['UnitID', 'Channel', 'ThalwegTyp']) as cursor:
for row in cursor:
unitid = row[0]
channel = str(row[1])
thalwegtype = str(row[2])
if not row[1] == None: # if channel field isn't blank/empty
if unitid not in channelDict: # if the unit id isn't in the dict, add it along with the channel
channelDict[unitid] = [channel]
else:
if channel not in channelDict[unitid]: # if the channel isn't in the dictionary with the unit id key, append to the list
channelDict[unitid].append(channel)
if unitid not in thalwegDict: # if the unit id isn't in the dict, add it along with the thalweg
thalwegDict[unitid] = [thalwegtype]
else:
if thalwegtype not in thalwegDict[unitid]: # if the channel isn't in the dictionary with the unit id key, append to the list
thalwegDict[unitid].append(thalwegtype)
else:
channelDict[unitid] = ['None']
thalwegDict[unitid] = ['None']
arcpy.AddField_management(units, 'ThalwegCh', 'TEXT', '', '', 50)
arcpy.AddField_management(units, 'ThalwegTyp', 'TEXT', '', '', 50)
with arcpy.da.UpdateCursor(units, ['UnitID', 'ThalwegCh', 'ThalwegTyp']) as cursor:
for row in cursor:
unitid = row[0]
row[1] = ', '.join(channelDict[unitid])
row[2] = ', '.join(thalwegDict[unitid])
cursor.updateRow(row)
thalweg_ct = arcpy.Statistics_analysis(unit_thalweg_ch, 'in_memory/thalweg_ct', 'Join_Count SUM', 'UnitID')
arcpy.AddField_management(thalweg_ct, 'ThalwegCt', 'SHORT')
with arcpy.da.UpdateCursor(thalweg_ct, ['SUM_Join_Count', 'ThalwegCt']) as cursor:
for row in cursor:
row[1] = row[0]
cursor.updateRow(row)
arcpy.JoinField_management(units, 'UnitID', thalweg_ct, 'UnitID', 'ThalwegCt')
# ----------------------------------------------------------
# Attribute bankfull surface slope
print '...bankfull surface slope...'
# get mean value for each unit
ZonalStatisticsAsTable(units, 'UnitID', bfSlope, 'tbl_bfSlope.dbf', 'DATA', 'MEAN')
# join mean value back to units shp
arcpy.JoinField_management(units, 'UnitID', 'tbl_bfSlope.dbf', 'UnitID', 'MEAN')
fields = ['MEAN', 'bfSlope']
with arcpy.da.UpdateCursor(units, fields) as cursor:
for row in cursor:
row[1] = row[0]
cursor.updateRow(row)
arcpy.DeleteField_management(units, ['MEAN'])
# ----------------------------------------------------------
# Attribute smoothed bankfull surface slope
# get mean value for each unit
ZonalStatisticsAsTable(units, 'UnitID', bfSlope_Smooth, 'tbl_bfSlope_Smooth.dbf', 'DATA', 'MEAN')
# join mean value back to units shp
arcpy.JoinField_management(units, 'UnitID', 'tbl_bfSlope_Smooth.dbf', 'UnitID', 'MEAN')
fields = ['MEAN', 'bfSlopeSm']
with arcpy.da.UpdateCursor(units, fields) as cursor:
for row in cursor:
row[1] = row[0]
cursor.updateRow(row)
arcpy.DeleteField_management(units, ['MEAN'])
# ----------------------------------------------------------
# Attribute mean slope
print '...mean bed slope...'
# get mean value for each unit
ZonalStatisticsAsTable(units, 'UnitID', os.path.join(evpath, 'slope_inCh_' + os.path.basename(
os.path.join(myVars['workspace'], myVars['inDEM']))), 'tbl_slope.dbf', 'DATA', 'MEAN')
# join mean value back to units shp
arcpy.JoinField_management(units, 'UnitID', 'tbl_slope.dbf', 'UnitID', 'MEAN')
fields = ['MEAN', 'bedSlope']
with arcpy.da.UpdateCursor(units, fields) as cursor:
for row in cursor:
row[1] = row[0]
cursor.updateRow(row)
arcpy.DeleteField_management(units, ['MEAN'])
return (units)
# --tier 1 function--
# classifies tier 1 units
# valley units: in-channel, out-of-channel
# flow units: submerged, emergent, high
def tier1(**myVars):
print 'Starting Tier 1 classification...'
# create temporary workspace
tmp_dir = tempfile.mkdtemp()
# environment settings
arcpy.env.workspace = tmp_dir # set workspace to temporary workspace
arcpy.env.overwriteOutput = True # set to overwrite output
# import required rasters
dem = Raster(os.path.join(myVars['workspace'], myVars['inDEM']))
# define raster environment settings
desc = arcpy.Describe(dem)
arcpy.env.extent = desc.Extent
arcpy.env.outputCoordinateSystem = desc.SpatialReference
arcpy.env.cellSize = desc.meanCellWidth
# check if evidence layer and output folders exits, if not create them
folder_list = ['EvidenceLayers', 'Output']
for folder in folder_list:
if not os.path.exists(os.path.join(myVars['workspace'], folder)):
os.makedirs(os.path.join(myVars['workspace'], folder))
# create gut run folder and set output path
if myVars['runFolderName'] != 'Default' and myVars['runFolderName'] != '':
outpath = os.path.join(myVars['workspace'], 'Output', myVars['runFolderName'])
else:
runFolders = fnmatch.filter(next(os.walk(os.path.join(myVars['workspace'], 'Output')))[1], 'Run_*')
if len(runFolders) >= 1:
runNum = int(max([i.split('_', 1)[1] for i in runFolders])) + 1
else:
runNum = 1
outpath = os.path.join(myVars['workspace'], 'Output', 'Run_%03d' % runNum)
os.makedirs(outpath)
# set evidence layers output path
evpath = os.path.join(myVars['workspace'], 'EvidenceLayers')
# ----------------------------------
# calculate reach-level metrics
# ----------------------------------
# --calculate integrated bankfull width--
bfw = intWidth_fn(os.path.join(myVars['workspace'], myVars['bfPolyShp']), os.path.join(myVars['workspace'],myVars['bfCL']))
# --------------------------
# tier 1 evidence layers
# --------------------------
print '...deriving evidence layers...'
# --bankfull channel raster--
if not os.path.exists(os.path.join(evpath, 'bfCh.tif')):
print '...deriving bankfull channel raster...'
bf_raw = arcpy.PolygonToRaster_conversion(os.path.join(myVars['workspace'], myVars['bfPolyShp']), 'FID', 'in_memory/tmp_bfCh', 'CELL_CENTER') # convert bankfull channel polygon to raster
outCon = Con(IsNull(bf_raw), 0, 1) # set cells inside/outside bankfull channel polygon to 1/0
bf = ExtractByMask(outCon, dem) # clip to dem
bf.save(os.path.join(evpath, 'bfCh.tif')) # save output
else:
bf = Raster(os.path.join(evpath, 'bfCh.tif'))
# -------------------------
# tier 1 classifcation
# -------------------------
print '...classifying valley units...'
# convert bankfull channel raster to polygon
valley_units = arcpy.RasterToPolygon_conversion(bf, 'in_memory/valley_units', 'NO_SIMPLIFY', 'VALUE')
# covert units from multipart to singlepart polygons
valley_units_sp = arcpy.MultipartToSinglepart_management(valley_units, 'in_memory/valley_units_sp')
# create and attribute 'ValleyID' and 'ValleyUnit' fields
arcpy.AddField_management(valley_units_sp, 'ValleyID', 'SHORT')
arcpy.AddField_management(valley_units_sp, 'ValleyUnit', 'TEXT', '', '', 20)
ct = 1
with arcpy.da.UpdateCursor(valley_units_sp, ['ValleyID', 'GRIDCODE', 'ValleyUnit']) as cursor:
for row in cursor:
row[0] = ct
if row[1] == 0:
row[2] = 'Out-of-Channel'
else:
row[2] = 'In-Channel'
ct += 1
cursor.updateRow(row)
print '...classifying flow units...'
# add flow type field and attribute high and emergent classes using valley unit shp
flowtype_units_raw = arcpy.CopyFeatures_management(valley_units_sp, 'in_memory/flowtype_units_raw')
arcpy.AddField_management(flowtype_units_raw, 'FlowUnit', 'TEXT', '', '', 12)
with arcpy.da.UpdateCursor(flowtype_units_raw, ['ValleyUnit', 'FlowUnit']) as cursor:
for row in cursor:
if row[0] == 'Out-of-Channel':
row[1] = 'High'
else:
row[1] = 'Emergent'
cursor.updateRow(row)
# add flow type field and attribute submerged class using water extent shp
wPoly = arcpy.CopyFeatures_management(os.path.join(myVars['workspace'], myVars['wPolyShp']), 'in_memory/wPoly')
arcpy.AddField_management(wPoly, 'FlowUnit', 'TEXT', '', '', 12)
with arcpy.da.UpdateCursor(wPoly, ['FlowUnit']) as cursor:
for row in cursor:
row[0] = 'Submerged'
cursor.updateRow(row)
# create flow type polygon by updating/merging shps
flowtype_units = arcpy.Update_analysis(flowtype_units_raw, wPoly, 'in_memory/flowtype_units')
# intersect flow type polygon with valley units
t1_units_raw = arcpy.Intersect_analysis([valley_units_sp, flowtype_units], 'in_memory/t1_units_raw', 'ALL')
# covert units from multipart to singlepart polygons
t1_units_sp = arcpy.MultipartToSinglepart_management(t1_units_raw, 'in_memory/t1_units_sp')
# add and calculate unit area field
arcpy.AddField_management(t1_units_sp, 'Area', 'DOUBLE')
with arcpy.da.UpdateCursor(t1_units_sp, ['SHAPE@AREA', 'Area']) as cursor:
for row in cursor:
row[1] = row[0]
cursor.updateRow(row)
# find tiny units (area < 0.05 * bfw) and merge with unit that shares longest border
t1_units_sp_lyr = arcpy.MakeFeatureLayer_management(t1_units_sp, 't1_units_sp_lyr')
arcpy.SelectLayerByAttribute_management(t1_units_sp_lyr, 'NEW_SELECTION', '"Area" < ' + str(0.05 * bfw))
t1_units = arcpy.Eliminate_management(t1_units_sp_lyr, 'in_memory/t1_units', "LENGTH")
# add and populate flow unit id field
arcpy.AddField_management(t1_units, 'FlowID', 'SHORT')
ct = 1
with arcpy.da.UpdateCursor(t1_units, ['FlowID']) as cursor:
for row in cursor:
row[0] = ct
ct += 1
cursor.updateRow(row)
# remove unnecessary fields
fields = arcpy.ListFields(t1_units)
keep = ['OBJECTID', 'Shape', 'ValleyID', 'ValleyUnit', 'FlowUnit', 'FlowID', 'Area']
drop = [x.name for x in fields if x.name not in keep]
arcpy.DeleteField_management(t1_units, drop)
# save tier 1 output
arcpy.CopyFeatures_management(t1_units, os.path.join(outpath, 'Tier1.shp'))
# clear temporary workspace
print '...removing intermediary surfaces...'
arcpy.Delete_management("in_memory")
arcpy.Delete_management(tmp_dir)
print '...done with Tier 1 classification.'
# --tier 2 function--
# classifies tier 2 units
# unit shape: concavity, planar, convexity
# unit form: bowl, bowl transition, trough, plane, mound transition, mound, wall
def tier2(**myVars):
print 'Starting Tier 2 classification...'
# clear temporary workspace
arcpy.Delete_management("in_memory")
# create temporary workspace
tmp_dir = tempfile.mkdtemp()
# environment settings
arcpy.env.workspace = tmp_dir # set workspace to temporary workspace
arcpy.env.overwriteOutput = True # set to overwrite output
# set evidence layers output path
evpath = os.path.join(myVars['workspace'], 'EvidenceLayers')
# set gut run output path
if myVars['runFolderName'] != 'Default' and myVars['runFolderName'] != '':
outpath = os.path.join(myVars['workspace'], 'Output', myVars['runFolderName'])
else:
runFolders = fnmatch.filter(next(os.walk(os.path.join(myVars['workspace'], 'Output')))[1], 'Run_*')
runNum = int(max([i.split('_', 1)[1] for i in runFolders]))
outpath = os.path.join(myVars['workspace'], 'Output', 'Run_%03d' % runNum)
# import required rasters
dem = Raster(os.path.join(myVars['workspace'], myVars['inDEM']))
bf = Raster(os.path.join(myVars['workspace'], 'EvidenceLayers/bfCh.tif')) # created in 'tier1' module
# define raster environment settings
desc = arcpy.Describe(dem)
arcpy.env.extent = desc.Extent
arcpy.env.outputCoordinateSystem = desc.SpatialReference
arcpy.env.cellSize = desc.meanCellWidth
# check thalweg shp to see if it contains 'Channel' and 'ThalwegType' fields
# if not, add fields and attribute both as 'Main'
if not 'Channel' in [f.name for f in arcpy.ListFields(os.path.join(myVars['workspace'], myVars['thalwegShp']))]:
arcpy.AddField_management(os.path.join(myVars['workspace'], myVars['thalwegShp']), 'Channel', 'TEXT', '', '', 15)
with arcpy.da.UpdateCursor(os.path.join(myVars['workspace'], myVars['thalwegShp']), 'Channel') as cursor:
for row in cursor:
row[0] = 'Main'
cursor.updateRow(row)
if not 'ThalwegTyp' in [f.name for f in arcpy.ListFields(os.path.join(myVars['workspace'], myVars['thalwegShp']))]:
arcpy.AddField_management(os.path.join(myVars['workspace'], myVars['thalwegShp']), 'ThalwegTyp', 'TEXT', '', '', 15)
with arcpy.da.UpdateCursor(os.path.join(myVars['workspace'], myVars['thalwegShp']), 'ThalwegTyp') as cursor:
for row in cursor:
row[0] = 'Main'
cursor.updateRow(row)
# check bankfull centerline shp to see if it contains 'Channel' field
# if not, add field and attribute as 'Main' also add 'CLID' field a populate iteratively
if not 'Channel' in [f.name for f in arcpy.ListFields(os.path.join(myVars['workspace'], myVars['bfCL']))]:
arcpy.AddField_management(os.path.join(myVars['workspace'], myVars['bfCL']), 'Channel', 'TEXT', '', '', 15)
arcpy.AddField_management(os.path.join(myVars['workspace'], myVars['bfCL']), 'CLID', 'SHORT')
ct = 1
with arcpy.da.UpdateCursor(os.path.join(myVars['workspace'], myVars['bfCL']), ['Channel', 'CLID']) as cursor:
for row in cursor:
row[0] = 'Main'
row[1] = ct
ct += 1
cursor.updateRow(row)
# ----------------------------------
# calculate reach-level metrics
# ----------------------------------
# --calculate integrated bankfull and wetted widths--
bfw = intWidth_fn(os.path.join(myVars['workspace'], myVars['bfPolyShp']), os.path.join(myVars['workspace'], myVars['bfCL']))
ww = intWidth_fn(os.path.join(myVars['workspace'], myVars['wPolyShp']), os.path.join(myVars['workspace'], myVars['wCL']))
print '...integrated bankfull width: ' + str(bfw) + ' m...'
print '...integrated wetted width: ' + str(ww) + ' m...'
# --calculate gradient, sinuosity, thalweg ratio--
# check thalweg to see if it contains 'Length' field if not add field
tmp_thalweg = arcpy.CopyFeatures_management(os.path.join(myVars['workspace'], myVars['thalwegShp']), 'in_memory/tmp_thalweg')
if not 'Length' in [f.name for f in arcpy.ListFields(tmp_thalweg)]:
arcpy.AddField_management(tmp_thalweg, 'Length', 'DOUBLE')
# calculate/re-calculate length field
with arcpy.da.UpdateCursor(tmp_thalweg, ['SHAPE@LENGTH', 'Length']) as cursor:
for row in cursor:
row[1] = round(row[0], 3)
cursor.updateRow(row)
# create feature layer for 'Main' thalweg
arcpy.MakeFeatureLayer_management(tmp_thalweg, 'thalweg_lyr', """ "ThalwegTyp" = 'Main' """)
# get 'Main' thalweg length
maxLength = float([row[0] for row in arcpy.da.SearchCursor('thalweg_lyr', ("Length"))][0])
# convert thalweg ends to points
thalweg_pts = arcpy.FeatureVerticesToPoints_management('thalweg_lyr', 'in_memory/thalweg_pts', "BOTH_ENDS")
# calculate straight line distance between thalweg end points
arcpy.PointDistance_analysis(thalweg_pts, thalweg_pts, 'tbl_thalweg_dist.dbf')
straightLength = round(arcpy.SearchCursor('tbl_thalweg_dist.dbf', "", "", "", 'DISTANCE' + " D").next().getValue('DISTANCE'), 3)
# extract demZ values for each thalweg end point
ExtractMultiValuesToPoints(thalweg_pts, [[dem, 'demZ']])
maxZ = round(arcpy.SearchCursor(thalweg_pts, "", "", "", 'demZ' + " D").next().getValue('demZ'), 3)
minZ = round(arcpy.SearchCursor(thalweg_pts, "", "", "", 'demZ' + " A").next().getValue('demZ'), 3)
# sum lengths of all thalwegs in thalweg shp
totalLength = sum((row[0] for row in arcpy.da.SearchCursor(tmp_thalweg, ['Length'])))
# calculate gradient,sinuosity, and thalweg ratio
gradient = round(((maxZ - minZ) / maxLength) * 100, 3)
sinuosity = round(maxLength / straightLength, 3)
thalwegRatio = round(totalLength / maxLength, 3)
print '...reach gradient: ' + str(gradient) + ' percent...'
print '...reach sinuosity: ' + str(sinuosity) + '...'
print '...thalweg ratio: ' + str(thalwegRatio) + '...'
# -----------------------------
# tier 2 functions
# -----------------------------
# --tier 2 raster to polygon function--
# takes each form raster, converts to polygon, adds/populates fields
# filters by area, and merges into single shapefile
def ras2poly_fn(Mound, Plane, Bowl, Trough, Saddle, Wall, **kwargs):
shpList = []
formDict = locals()
formDict.update(kwargs)
for key, value in formDict.iteritems():
if key in ['Mound', 'Plane', 'Bowl', 'Trough', 'Saddle', 'Wall', 'MoundPlane', 'TroughBowl']:
if int(arcpy.GetRasterProperties_management(value, "ALLNODATA").getOutput(0)) < 1:
tmp_fn = 'in_memory/' + str(key) + '_raw'
arcpy.RasterToPolygon_conversion(value, tmp_fn, 'NO_SIMPLIFY', 'VALUE')
arcpy.AddField_management(tmp_fn, 'ValleyUnit', 'TEXT', '', '', 20)
arcpy.AddField_management(tmp_fn, 'UnitShape', 'TEXT', '', '', 15)
arcpy.AddField_management(tmp_fn, 'UnitForm', 'TEXT', '', '', 20)
with arcpy.da.UpdateCursor(tmp_fn, ['ValleyUnit', 'UnitShape', 'UnitForm']) as cursor:
for row in cursor:
row[0] = 'In-Channel'
row[2] = str(key)
if row[2] == 'Plane':
row[1] = 'Planar'
elif row[2] == 'Mound':
row[1] = 'Convexity'
elif row[2] == 'Saddle':
row[1] = 'Convexity'
elif row[2] == 'Wall':
row[1] = 'Planar'
elif row[2] == 'Bowl':
row[1] = 'Concavity'
elif row[2] == 'MoundPlane':
row[1] = 'Convexity'
row[2] = 'Mound Transition'
elif row[2] == 'TroughBowl':
row[1] = 'Concavity'
row[2] = 'Bowl Transition'
else:
row[1] = 'Planar'
cursor.updateRow(row)
shp_fn = 'in_memory/' + str(key)
arcpy.Dissolve_management(tmp_fn, shp_fn, ['ValleyUnit', 'UnitShape', 'UnitForm'], '', 'SINGLE_PART', 'UNSPLIT_LINES')
shpList.append(shp_fn)
# merge all forms except saddles and walls (we want to 'stamp' these on top)
mergeList = [i for i in shpList if i not in ('in_memory/Saddle', 'in_memory/Wall')]
units_merge = arcpy.Merge_management(mergeList, 'in_memory/units_merge')
# update merged units with saddles (if classified) and walls
if 'in_memory/Saddle' in shpList:
units_update = arcpy.Update_analysis(units_merge, 'in_memory/Saddle', 'in_memory/units_update')
units_update2 = arcpy.Update_analysis('in_memory/units_update', 'in_memory/Wall', 'in_memory/units_update2')
units_sp = arcpy.MultipartToSinglepart_management(units_update2, 'in_memory/units_sp')
else:
units_update = arcpy.Update_analysis(units_merge, 'in_memory/Wall', 'in_memory/units_update2')
units_sp = arcpy.MultipartToSinglepart_management(units_update, 'in_memory/units_sp')
# add and calculate area field
arcpy.AddField_management(units_sp, 'Area', 'DOUBLE')
with arcpy.da.UpdateCursor(units_sp, ['SHAPE@AREA', 'Area']) as cursor:
for row in cursor:
row[1] = row[0]
cursor.updateRow(row)
# filter out tiny units (area < 0.1 * bfw) by merging with unit that shares longest border #ToDo: Ask NK/JW if we want to use the oonfig area thresh here instead
# run 2x
units_sp_lyr = arcpy.MakeFeatureLayer_management(units_sp, 'units_sp_lyr')
arcpy.SelectLayerByAttribute_management(units_sp_lyr, 'NEW_SELECTION', """ ("UnitForm" IN ('Bowl', 'Trough', 'Plane', 'Mound', 'Saddle', 'Wall') AND "Area" < """ + str(0.1 * bfw) + """) OR ("UnitForm" IN ('Bowl Transition', 'Mound Transition') AND "Area" <= 0.1) """)
units_elim = arcpy.Eliminate_management(units_sp_lyr, 'in_memory/units_elim', "LENGTH")
units_elim_lyr = arcpy.MakeFeatureLayer_management(units_elim, 'units_elim_lyr')
arcpy.SelectLayerByAttribute_management(units_elim_lyr, 'NEW_SELECTION', """ ("UnitForm" IN ('Bowl', 'Trough', 'Plane', 'Mound', 'Saddle', 'Wall') AND "Area" < """ + str(0.1 * bfw) + """) OR ("UnitForm" IN ('Bowl Transition', 'Mound Transition') AND "Area" <= 0.1) """)
tmp_units = arcpy.Eliminate_management(units_elim_lyr, 'in_memory/tmp_units', "LENGTH")
# create form and unit id fields and update area field
arcpy.AddField_management(tmp_units, 'FormID', 'SHORT')
arcpy.AddField_management(tmp_units, 'UnitID', 'SHORT')
ct = 1
with arcpy.da.UpdateCursor(tmp_units, ['FormID', 'SHAPE@AREA', 'Area', 'UnitID']) as cursor:
for row in cursor:
row[0] = ct
row[2] = row[1]
row[3] = row[0]
ct += 1
cursor.updateRow(row)
# remove unnecessary fields
fields = arcpy.ListFields(tmp_units)
keep = ['ValleyUnit', 'UnitShape', 'UnitForm', 'Area', 'FormID', 'UnitID']
drop = []
for field in fields:
if not field.required and field.name not in keep and field.type <> 'Geometry':
drop.append(field.name)
if len(drop) > 0:
arcpy.DeleteField_management(tmp_units, drop)
# save tier 2 output
if 'in_memory/MoundPlane' in shpList:
arcpy.CopyFeatures_management(tmp_units, os.path.join(outpath, 'Tier2_InChannel.shp'))
else:
arcpy.CopyFeatures_management(tmp_units, os.path.join(outpath, 'Tier2_InChannel_Discrete.shp'))
# remove temporary form sps
shpList.extend([tmp_units])
for shp in shpList:
arcpy.Delete_management(shp)
# ---------------------------------
# tier 2 evidence layers
# ---------------------------------
print '...deriving evidence layers...'
# --mean dem--
if not os.path.exists(os.path.join(evpath, os.path.splitext(os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM'])))[0] + '_mean.tif')):
neigh = NbrRectangle(bfw * 0.1, bfw * 0.1, 'MAP') # set neighborhood size
meanDEM = FocalStatistics(dem, neigh, 'MEAN', 'DATA') # calculate mean z
outMeanDEM = ExtractByMask(meanDEM, dem) # clip focal result to dem
outMeanDEM.save(os.path.join(evpath, os.path.splitext(os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM'])))[0] + '_mean.tif')) # save output
else:
outMeanDEM = Raster(os.path.join(evpath, os.path.splitext(os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM'])))[0] + '_mean.tif'))
# --in channel mean dem--
if not os.path.exists(os.path.join(evpath, 'inCh_' + os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM'])))):
inCh = SetNull(bf, 1, '"VALUE" = 0') # set cells outside the bankfull channel to null
inChDEM = inCh * outMeanDEM # multiply be mean (smoothed) dem
inChDEM.save(os.path.join(evpath, 'inCh_' + os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM'])))) # save output
else:
inChDEM = Raster(os.path.join(evpath, 'inCh_' + os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM']))))
# --in channel mean dem slope--
if not os.path.exists(os.path.join(evpath, 'slope_inCh_' + os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM'])))):
inChDEMSlope = Slope(inChDEM, 'DEGREE') # calculate slope (in degrees) for in-channel portion of the dem
inChDEMSlope.save(os.path.join(evpath, 'slope_inCh_' + os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM'])))) # save output
else:
inChDEMSlope = Raster(os.path.join(evpath, 'slope_inCh_' + os.path.basename(os.path.join(myVars['workspace'], myVars['inDEM']))))
# --residual topography--
if not os.path.exists(os.path.join(evpath, 'resTopo.tif')):
neigh2 = NbrRectangle(bfw, bfw, 'MAP') # set neighborhood size
trendDEM = FocalStatistics(inChDEM, neigh2, 'MEAN', 'DATA') # calculate mean z for smoothed dem
resTopo = inChDEM - trendDEM # calculate difference between in channel dem and the trend dem
resTopo.save(os.path.join(evpath, 'resTopo.tif')) # save output
else:
resTopo = Raster(os.path.join(evpath, 'resTopo.tif'))
# --normalized fill--
if not os.path.exists(os.path.join(evpath, 'resDepth.tif')):
rFill = Fill(inChDEM) # fill the in-channel dem
resDepth = (rFill - inChDEM) # difference fill and in-channel dem
resDepth.save(os.path.join(evpath, 'resDepth.tif')) # save output
else:
resDepth = Raster(os.path.join(evpath, 'resDepth.tif'))
# --channel margin--
if not os.path.exists(os.path.join(evpath, 'chMargin.tif')):
# remove any water extent polygons < 5% of the total polygon area
wPolyElim = arcpy.EliminatePolygonPart_management(os.path.join(myVars['workspace'], myVars['wPolyShp']), 'in_memory/wPolyElim', 'PERCENT', '', 5, 'ANY')
# erase (exclude) water extent polygon from bankfull polygon
polyErase = arcpy.Erase_analysis(os.path.join(myVars['workspace'], myVars['bfPolyShp']), wPolyElim, 'in_memory/polyErase', '')
# buffer the output by 10% of the integrated wetted width
polyBuffer = arcpy.Buffer_analysis(polyErase, 'in_memory/polyBuffer', 0.1 * ww, 'FULL')
# clip the output to the bankfull polygon
arcpy.Clip_analysis(polyBuffer, os.path.join(myVars['workspace'], myVars['bfPolyShp']), 'in_memory/chMarginPoly')
# convert the output to a raster
cm_raw = arcpy.PolygonToRaster_conversion('in_memory/chMarginPoly', 'FID', 'in_memory/chMargin_raw', 'CELL_CENTER', 'NONE')
# set all cells to value of 1
cm = Con(cm_raw, 1, "VALUE" >= 0)
# save the output
cm.save(os.path.join(evpath, 'chMargin.tif'))
else:
cm = Raster(os.path.join(evpath, 'chMargin.tif'))
print '...saddle contours...'
# --saddle contours--
if myVars['createSaddles'] == 'Yes':
thalweg_basename = os.path.splitext(os.path.basename(os.path.join(myVars['workspace'], myVars['thalwegShp'])))[0]
if not os.path.exists(os.path.join(evpath, 'contourNodes_' + thalweg_basename + '.shp')):
# create contours
#
if bfw < 12.0:
contours = Contour(outMeanDEM, 'in_memory/contours', 0.1)
else:
contours = Contour(outMeanDEM, 'in_memory/contours', 0.2)
# b. clean up contours (i.e., fill contour gaps)
# clip contour shp to bankfull polygon
contour_clip = arcpy.Clip_analysis(contours, os.path.join(myVars['workspace'], myVars['bfPolyShp']), 'in_memory/contours_clip')
# convert contour shp from multipart to singlepart feature
contour_sp = arcpy.MultipartToSinglepart_management(contour_clip, 'in_memory/contours_sp')
# create feature layer from singlepart contours
line_lyr = arcpy.MakeFeatureLayer_management(contour_sp, "contour_lyr")
# delete very short contours
with arcpy.da.UpdateCursor(line_lyr, "SHAPE@LENGTH") as cursor:
for row in cursor:
if row[0] <= 0.2:
cursor.deleteRow()
# convert bankfull polygon to line and merge with contours
bankfull_line = arcpy.FeatureToLine_management([os.path.join(myVars['workspace'], myVars['bfPolyShp'])], 'in_memory/bankfull_line')
contours_bankfull_merge = arcpy.Merge_management([line_lyr, bankfull_line], 'in_memory/contours_bankfull_merge')
# create points at contour endpoints
end_points = arcpy.FeatureVerticesToPoints_management(contours_bankfull_merge, 'in_memory/contours_bankfull_merge_ends', 'BOTH_ENDS')
# delete end points that intersect > 1 contour line - only want points that fall on end of a line
end_points_join = arcpy.SpatialJoin_analysis(end_points, contours_bankfull_merge, 'in_memory/end_points_join', 'JOIN_ONE_TO_ONE', 'KEEP_ALL', '', 'INTERSECT')
with arcpy.da.UpdateCursor(end_points_join, ['Join_Count']) as cursor:
for row in cursor:
if row[0] > 1:
cursor.deleteRow()
# find and delete end points that are identical since these are 'false' end point on closed contours
identical_tbl = arcpy.FindIdentical_management(end_points_join, 'in_memory/identical_tbl', ['Shape'], '', '', 'ONLY_DUPLICATES')
identical_list = [row[0] for row in arcpy.da.SearchCursor(identical_tbl, ['IN_FID'])]
oid_fn = arcpy.Describe(end_points_join).OIDFieldName
with arcpy.da.UpdateCursor(end_points_join, [oid_fn]) as cursor:
for row in cursor:
if row[0] in identical_list:
cursor.deleteRow()
# assign unique 'endID' field
arcpy.AddField_management(end_points_join, 'endID', 'SHORT')
fields = ['endID']
ct = 1
with arcpy.da.UpdateCursor(end_points_join, fields) as cursor:
for row in cursor:
row[0] = ct
ct += 1
cursor.updateRow(row)
# find nearest end point to each end point
arcpy.Near_analysis(end_points_join, end_points_join)
endDict = {} # create end point dictionary
with arcpy.da.SearchCursor(end_points_join, [oid_fn, 'endID']) as cursor:
for row in cursor:
endDict[row[0]] = row[1]
# rename/calculate near end id field to logical name
arcpy.AddField_management(end_points_join, 'nearEndID', 'SHORT')
arcpy.AddField_management(end_points_join, 'nearDist', 'DOUBLE')
arcpy.AddField_management(end_points_join, 'strContour', 'TEXT')
with arcpy.da.UpdateCursor(end_points_join, ['NEAR_FID', 'nearEndID', 'Contour', 'strContour', 'NEAR_DIST', 'nearDist']) as cursor:
for row in cursor:
row[1] = endDict[row[0]]
row[3] = str(row[2])
row[5] = row[4]
cursor.updateRow(row)
# remove unnecessary fields from previous join operations
fields = arcpy.ListFields(end_points_join)
keep = ['endID', 'Contour', 'nearEndID', 'nearDist', 'strContour']
drop = []
for field in fields:
if not field.required and field.name not in keep and field.type <> 'Geometry':
drop.append(field.name)
arcpy.DeleteField_management(end_points_join, drop)
# make end point feature layer for selection operations
end_points_lyr = arcpy.MakeFeatureLayer_management(end_points_join, 'end_points_lyr')
# group end point pairs that fall on contour gaps
# pair criteria:
# - must be nearest points to each other
# - must share the same contour value
# - can't be further than 1 meter from each other
arcpy.AddField_management(end_points_lyr, 'endIDGroup', 'SHORT')
groupIndex = 1
with arcpy.da.UpdateCursor(end_points_lyr, ['SHAPE@', 'strContour', 'endID', 'nearEndID', 'endIDGroup', 'nearDist']) as cursor:
for row in cursor:
arcpy.SelectLayerByAttribute_management(end_points_lyr, "NEW_SELECTION", "endID = %s" % row[3])
arcpy.SelectLayerByAttribute_management(end_points_lyr, "SUBSET_SELECTION", "strContour = '%s'" % row[1])
arcpy.SelectLayerByAttribute_management(end_points_lyr, "ADD_TO_SELECTION", "endID = %s" % row[2])
result = arcpy.GetCount_management(end_points_lyr)
count = int(result.getOutput(0))
if count > 1:
if row[4] > 0:
pass
elif row[5] > 0.25 * bfw: # ToDo: May want to expose this threshold or set as some multiple of cell size
pass
else:
arcpy.CalculateField_management(end_points_lyr, 'endIDGroup', groupIndex, 'PYTHON_9.3')
groupIndex += 1
# delete end points that aren't part of group (i.e., that weren't on contour gap)
with arcpy.da.UpdateCursor(end_points_join, ['endIDGroup']) as cursor:
for row in cursor:
if row[0] <= 0.0:
cursor.deleteRow()
# create line connecting each end point pair
gap_lines = arcpy.PointsToLine_management(end_points_join, 'in_memory/gap_lines', 'endIDGroup')
# merge contour gap lines with contours
contours_gap_merge = arcpy.Merge_management([line_lyr, gap_lines], 'in_memory/contours_gap_merge')
# dissolve all lines that are touching into single line
contours_repaired = arcpy.Dissolve_management(contours_gap_merge, 'in_memory/contours_repaired', '', '', '', 'UNSPLIT_LINES')
arcpy.CopyFeatures_management(contours_repaired, os.path.join(evpath, 'DEM_Contours.shp'))
# c. merge repaired lines with bankfull line
contours_bankfull_merge2 = arcpy.Merge_management([contours_repaired, bankfull_line], 'in_memory/contours_bankfull_merge2')
# d. close contour lines by extending to bankfull line
arcpy.ExtendLine_edit(contours_bankfull_merge2, "1.0 Meters", "EXTENSION")
# e. add unique contour line id field 'ContourID'
arcpy.AddField_management(contours_bankfull_merge2, 'ContourID', 'SHORT')
ct = 1
with arcpy.da.UpdateCursor(contours_bankfull_merge2, ['ContourID']) as cursor:
for row in cursor:
row[0] = ct
ct += 1
cursor.updateRow(row)
# f. convert contour lines to polygon and clip to bankfull polygon
contour_poly_raw = arcpy.FeatureToPolygon_management(contours_bankfull_merge2, 'in_memory/raw_contour_poly')
contour_poly_clip = arcpy.Clip_analysis(contour_poly_raw, os.path.join(myVars['workspace'], myVars['bfPolyShp']), 'in_memory/contour_polygons_clip')
# g. create nodes at contour [line] - thalweg intersection
arcpy.CopyFeatures_management(os.path.join(myVars['workspace'], myVars['thalwegShp']), 'in_memory/thalweg')
contour_nodes_mpart = arcpy.Intersect_analysis(['in_memory/thalweg', contours_bankfull_merge2], 'in_memory/contour_nodes_mpart', 'NO_FID', '', 'POINT')
contour_nodes = arcpy.MultipartToSinglepart_management(contour_nodes_mpart, 'in_memory/contour_nodes')
# h. add unique node id field
arcpy.AddField_management(contour_nodes, 'NodeID', 'SHORT')
ct = 1
with arcpy.da.UpdateCursor(contour_nodes, 'NodeID') as cursor:
for row in cursor:
row[0] = ct
ct += 1
cursor.updateRow(row)
# i. extract dem z values to contour nodes
ExtractMultiValuesToPoints(contour_nodes, [[outMeanDEM, 'elev']], 'NONE')
# j. calculate flowline distance for each contour node
arcpy.AddField_management('in_memory/thalweg', 'ThID', 'SHORT')
arcpy.AddField_management('in_memory/thalweg', 'From_', 'DOUBLE')
arcpy.AddField_management('in_memory/thalweg', 'To_', 'DOUBLE')
fields = ['SHAPE@LENGTH', 'From_', 'To_', 'ThID']
ct = 1
with arcpy.da.UpdateCursor('in_memory/thalweg', fields) as cursor:
for row in cursor:
row[1] = 0.0
row[2] = row[0]
row[3] = ct
ct += 1
cursor.updateRow(row)
arcpy.CreateRoutes_lr('in_memory/thalweg', 'ThID', 'in_memory/thalweg_route', 'TWO_FIELDS', 'From_', 'To_')
route_tbl = arcpy.LocateFeaturesAlongRoutes_lr(contour_nodes, 'in_memory/thalweg_route', 'ThID', float(desc.meanCellWidth), os.path.join(evpath, 'tbl_Routes.dbf'), 'RID POINT MEAS')
arcpy.JoinField_management(contour_nodes, 'NodeID', route_tbl, 'NodeID', ['MEAS'])
arcpy.JoinField_management(contour_nodes, 'NodeID', route_tbl, 'NodeID', ['RID'])
contour_nodes_join = arcpy.SpatialJoin_analysis(contour_nodes, contours, 'in_memory/contour_nodes_join', 'JOIN_ONE_TO_MANY', 'KEEP_ALL', '', 'INTERSECT')
# k. sort contour nodes by flowline distance (in downstream direction)
contour_nodes_sort = arcpy.Sort_management(contour_nodes_join, 'in_memory/contour_nodes_sort', [['RID', 'DESCENDING'],['MEAS', 'DESCENDING']])
# l. re-calculate node id so they are in ascending order starting at upstream boundary
ct = 1
with arcpy.da.UpdateCursor(contour_nodes_sort, ['NodeID']) as cursor:
for row in cursor:
row[0] = ct
ct += 1
cursor.updateRow(row)
# m. calculate elevation difference btwn contour nodes in DS direction
arcpy.AddField_management(contour_nodes_sort, 'adj_elev', 'DOUBLE')
arcpy.AddField_management(contour_nodes_sort, 'diff_elev', 'DOUBLE')
arcpy.AddField_management(contour_nodes_sort, 'dist', 'DOUBLE')
arcpy.AddField_management(contour_nodes_sort, 'riff_pair', 'SHORT')
arcpy.AddField_management(contour_nodes_sort, 'riff_dir', 'TEXT', '', '', 5)
#idList = [row[0] for row in arcpy.da.SearchCursor(contour_nodes_sort, ['RID'])]
ridList = set(row[0] for row in arcpy.da.SearchCursor(contour_nodes_sort, ['RID']))
for rid in ridList:
contour_nodes_lyr = arcpy.MakeFeatureLayer_management(contour_nodes_sort, 'contour_nodes_sort_lyr')
arcpy.SelectLayerByAttribute_management(contour_nodes_lyr, "NEW_SELECTION", "RID = %s" % str(rid))
fields = ['elev', 'adj_elev', 'diff_elev', 'riff_pair', 'riff_dir', 'ContourID', 'MEAS', 'dist']
distList = []
elevList = []
contourList = []
index = 0