-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAddAttributesFunctions.py
More file actions
4722 lines (4218 loc) · 178 KB
/
Copy pathAddAttributesFunctions.py
File metadata and controls
4722 lines (4218 loc) · 178 KB
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
"""
Author: Zhi Huang
Organisation: Geoscience Australia
Email: Zhi.Huang@ga.gov.au
Last update: June 04, 2024
Python version: 3+
ArcGIS Pro: 2.6.4 and above """
import math
import os
import sys
from datetime import datetime
import arcpy
import numpy as np
import pandas as pd
from arcpy import env
from arcpy.sa import *
from multiprocessing import Pool
import multiprocessing
from importlib import reload
import HelperFunctions
##arcpy.CheckOutExtension("Spatial")
# All the helper functions are defined here
# This function executes the multiprocessing to calculate the shape attributes for the bathymetric high features
def execute_shape_BH(argList, n_cpu):
# argList: a list of a list of arguments to be passed for multiprocessing
# n_cpu: number of cpu logical processors used for multiprocessing (each processor runs one independent process)
arcpy.AddMessage(
"Will open multiple python windows for processing. Please do not close them! They will close when finish."
)
# use python window instead of ArcGIS Pro application for the multiprocessing
multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'python.exe'))
arcpy.AddMessage("nCPU:" + str(n_cpu))
# doing multiprocessing here
with Pool(n_cpu) as pool:
results = pool.map(add_shape_attributes_high_function, argList)
arcpy.AddMessage("multiprocessing done all")
# This function executes the multiprocessing to calculate the shape attributes for the bathymetric low features
def execute_shape_BL(argList, n_cpu):
# argList: a list of a list of arguments to be passed for multiprocessing
# n_cpu: number of cpu logical processors used for multiprocessing (each processor runs one independent process)
arcpy.AddMessage(
"Will open multiple python windows for processing. Please do not close them! They will close when finish."
)
multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'python.exe'))
arcpy.AddMessage("nCPU:" + str(n_cpu))
# doing multiprocessing here
with Pool(n_cpu) as pool:
results = pool.map(add_shape_attributes_low_function, argList)
arcpy.AddMessage("multiprocessing done all")
# This function executes the multiprocessing to calculate the profile attributes for the bathymetric high features
def execute_profile_BH(argList, n_cpu):
# argList: a list of a list of arguments to be passed for multiprocessing
# n_cpu: number of cpu logical processors used for multiprocessing (each processor runs one independent process)
arcpy.AddMessage(
"Will open multiple python windows for processing. Please do not close them! They will close when finish."
)
multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'python.exe'))
arcpy.AddMessage("nCPU:" + str(n_cpu))
# doing multiprocessing here
with Pool(n_cpu) as pool:
results = pool.map(add_profile_attributes_high_function, argList)
arcpy.AddMessage("multiprocessing done all")
# This function executes the multiprocessing to calculate the profile attributes for the bathymetric low features
def execute_profile_BL(argList, n_cpu):
# argList: a list of a list of arguments to be passed for multiprocessing
# n_cpu: number of cpu logical processors used for multiprocessing (each processor runs one independent process)
arcpy.AddMessage(
"Will open multiple python windows for processing. Please do not close them! They will close when finish."
)
multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'python.exe'))
arcpy.AddMessage("nCPU:" + str(n_cpu))
# doing multiprocessing here
with Pool(n_cpu) as pool:
results = pool.map(add_profile_attributes_low_function, argList)
arcpy.AddMessage("multiprocessing done all")
# This function executes the multiprocessing to calculate the topographic attributes for the bathymetric high features
def execute_topographic_BH(argList, n_cpu):
# argList: a list of a list of arguments to be passed for multiprocessing
# n_cpu: number of cpu logical processors used for multiprocessing (each processor runs one independent process)
arcpy.AddMessage(
"Will open multiple python windows for processing. Please do not close them! They will close when finish."
)
# use python window instead of ArcGIS Pro application for the multiprocessing
multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'python.exe'))
arcpy.AddMessage("nCPU:" + str(n_cpu))
# doing multiprocessing here
with Pool(n_cpu) as pool:
results = pool.map(add_topographic_attributes_high_function, argList)
arcpy.AddMessage("multiprocessing done all")
# This function executes the multiprocessing to calculate the topographic attributes for the bathymetric low features
def execute_topographic_BL(argList, n_cpu):
# argList: a list of a list of arguments to be passed for multiprocessing
# n_cpu: number of cpu logical processors used for multiprocessing (each processor runs one independent process)
arcpy.AddMessage(
"Will open multiple python windows for processing. Please do not close them! They will close when finish."
)
# use python window instead of ArcGIS Pro application for the multiprocessing
multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'python.exe'))
arcpy.AddMessage("nCPU:" + str(n_cpu))
# doing multiprocessing here
with Pool(n_cpu) as pool:
results = pool.map(add_topographic_attributes_low_function, argList)
arcpy.AddMessage("multiprocessing done all")
# This function calculates the topographic attributes for the bathymetric high features
def add_topographic_attributes_high_function(arg):
""" pass a list of arguments"""
workspaceName = arg[0]
tempFolder = arg[1]
inFeat = arg[2]
inBathy = arg[3]
slpGrid = arg[4]
saGrid = arg[5]
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
print("Spatial Analyst license checked out successfully.")
else:
print("Spatial Analyst license is unavailable.")
# calling individual functions to calculate the topographic features
calculateTopographicBH(workspaceName, tempFolder, inFeat, inBathy, slpGrid, saGrid)
arcpy.CheckInExtension("Spatial")
return
# This function calculates the topographic attributes for the bathymetric low features
def add_topographic_attributes_low_function(arg):
""" pass a list of arguments"""
workspaceName = arg[0]
tempFolder = arg[1]
inFeat = arg[2]
headFeat = arg[3]
footFeat = arg[4]
inBathy = arg[5]
slpGrid = arg[6]
saGrid = arg[7]
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
print("Spatial Analyst license checked out successfully.")
else:
print("Spatial Analyst license is unavailable.")
# calling individual functions to calculate the topographic features
calculateTopographicBL(workspaceName, tempFolder, inFeat, headFeat, footFeat, inBathy, slpGrid, saGrid)
arcpy.CheckInExtension("Spatial")
return
# This function calculates the shape attributes for the bathymetric high features
def add_shape_attributes_high_function(arg):
""" pass a list of arguments"""
workspaceName = arg[0]
tempFolder = arg[1]
inFeat = arg[2]
inBathy = arg[3]
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
print("Spatial Analyst license checked out successfully.")
else:
print("Spatial Analyst license is unavailable.")
# calling individual functions to calculate the shape features
calculateCompactness(inFeat)
calculateCircularity_Convexity_Solidity(workspaceName, inFeat)
calculateSinuosity_LwR(workspaceName, tempFolder, inFeat, inBathy)
arcpy.CheckInExtension("Spatial")
return
# This function calculates the shape attributes for the bathymetric low features
def add_shape_attributes_low_function(arg):
""" pass a list of arguments"""
workspaceName = arg[0]
tempFolder = arg[1]
inFeat = arg[2]
headFeat = arg[3]
footFeat = arg[4]
inBathy = arg[5]
additionalOption = arg[6]
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
print("Spatial Analyst license checked out successfully.")
else:
print("Spatial Analyst license is unavailable.")
# calling individual functions to calculate the shape features
calculateCompactness(inFeat)
calculateCircularity_Convexity_Solidity(workspaceName, inFeat)
calculateSinuosity_LwR_WdR_Slopes(workspaceName, tempFolder, inFeat, inBathy, headFeat, footFeat, additionalOption)
arcpy.CheckInExtension("Spatial")
return
# This function calculates the profile attributes for the bathymetric high features
def add_profile_attributes_high_function(arg):
""" pass a list of arguments"""
workspaceName = arg[0]
tempFolder = arg[1]
inFeat = arg[2]
inBathy = arg[3]
areaT = arg[4]
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
print("Spatial Analyst license checked out successfully.")
else:
print("Spatial Analyst license is unavailable.")
# calling individual functions to calculate the shape features
calculateProfileBH(workspaceName, tempFolder, inFeat, inBathy, areaT)
arcpy.CheckInExtension("Spatial")
return
# This function calculates the profile attributes for the bathymetric low features
def add_profile_attributes_low_function(arg):
""" pass a list of arguments"""
workspaceName = arg[0]
tempFolder = arg[1]
inFeat = arg[2]
inBathy = arg[3]
areaT = arg[4]
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
print("Spatial Analyst license checked out successfully.")
else:
print("Spatial Analyst license is unavailable.")
# calling individual functions to calculate the shape features
calculateProfileBL(workspaceName, tempFolder, inFeat, inBathy, areaT)
arcpy.CheckInExtension("Spatial")
return
# This function splits each polygon in the featureclass into multiple sub-polygons along its long axis
def splitPolygon(workspace, inFeatClass, MbrFeatClass, splitFeatClass):
# workspace: location of workspace
# inFeatClass: input Bathymetric High (Low) features
# MbrFeatClass: input bounding rectangle featureclass
# splitFeatClass: output featureclass containing the splitted features
mergeList = []
itemList = []
inFeat = workspace + "/" + "selection"
MbrFeat = workspace + "/" + "MBR_selection"
itemList.append(MbrFeat)
itemList.append(inFeat)
MbrPoints = workspace + "/" + "bounding_rectangle_points"
itemList.append(MbrPoints)
fishnetFeat = workspace + "/" + "fishnet"
itemList.append(fishnetFeat)
# loop through each polygon
cursor1 = arcpy.SearchCursor(inFeatClass)
i = 1
for row1 in cursor1:
if i % 100 == 1:
arcpy.management.Compact(workspace)
arcpy.AddMessage("Compacted the geodatabase")
time1 = datetime.now()
featID = row1.getValue("featID")
MbrL = row1.getValue("rectangle_Length")
MbrW = row1.getValue("rectangle_Width")
whereClause = '"featID" = ' + str(featID)
arcpy.AddMessage("working on featID: " + str(featID))
# select one polygon and its bounding polygon
arcpy.analysis.Select(inFeatClass, inFeat, whereClause)
arcpy.analysis.Select(workspace + "/" + MbrFeatClass, MbrFeat, whereClause)
arcpy.AddMessage("selection done")
# convert bounding rectangle to points
arcpy.management.FeatureVerticesToPoints(MbrFeat, MbrPoints, "ALL")
arcpy.AddMessage("bounding to points done")
# add x and y
arcpy.management.AddXY(MbrPoints)
arcpy.AddMessage("Add x and y done")
# get x and y values for the starting and ending points
cursor = arcpy.SearchCursor(MbrPoints)
row = cursor.next()
start_x = row.getValue("POINT_X")
start_y = row.getValue("POINT_Y")
row = cursor.next()
end_x = row.getValue("POINT_X")
end_y = row.getValue("POINT_Y")
del cursor, row
# create fishnet
# Set coordinate system of the output fishnet as the input dataset
env.outputCoordinateSystem = arcpy.Describe(MbrFeat).spatialReference
# Set the origin of the fishnet
originCoordinate = str(start_x) + " " + str(start_y)
# Set the orientation
yAxisCoordinate = str(end_x) + " " + str(end_y)
# Set the number of rows and columns together with origin and opposite corner
# determine the size of each cell (sub-polygon) based on the length of bounding rectangle (unit: metre)
if MbrL > 10000:
numRows = int(MbrL / 200) + 1
elif MbrL > 1000:
numRows = int(MbrL / 100) + 1
elif MbrL > 50:
numRows = int(MbrL / 50) + 1
else:
numRows = 2
cellSizeWidth = MbrW
cellSizeHeight = MbrL / numRows
numColumns = 1
oppositeCorner = "#"
# Create a point label feature class
labels = "NO_LABELS"
# Extent is set by origin and opposite corner - no need to use a template fc
templateExtent = "#"
# Each output cell will be a polygon
geometryType = "POLYGON"
arcpy.management.CreateFishnet(
fishnetFeat,
originCoordinate,
yAxisCoordinate,
cellSizeWidth,
cellSizeHeight,
numRows,
numColumns,
oppositeCorner,
labels,
templateExtent,
geometryType,
)
arcpy.AddMessage("Fishnet done")
# intersect
intersectOut1 = workspace + "/" + "intersectOut" + str(featID)
itemList.append(intersectOut1)
mergeList.append(intersectOut1)
inFeats = [inFeat, fishnetFeat]
arcpy.analysis.Intersect(inFeats, intersectOut1)
arcpy.AddMessage("intersect done")
time2 = datetime.now()
diff = time2 - time1
arcpy.AddMessage("took " + str(diff) + " to split this polygon.")
i += 1
del cursor1, row1
# merge all features together
arcpy.management.Merge(mergeList, splitFeatClass)
arcpy.AddMessage("merge done")
HelperFunctions.deleteDataItems(itemList)
# This functions calculates Compactness
def calculateCompactness(inFeatClass):
# inFeatClass: input Bathymetry High (Low) features
fieldType = "DOUBLE"
fieldPrecision = 15
fieldScale = 6
fields = arcpy.ListFields(inFeatClass)
field_names = [f.name for f in fields]
fieldName = "Compactness"
if fieldName in field_names:
arcpy.AddMessage(fieldName + " exists and will be recalculated")
else:
arcpy.management.AddField(
inFeatClass, fieldName, fieldType, fieldPrecision, fieldScale
)
# This is the compactness equation
expression = (
"4*math.pi*"
+ "!"
+ "SHAPE_AREA"
+ "!"
+ "/"
+ "!"
+ "SHAPE_LENGTH"
+ "!"
+ "/"
+ "!"
+ "SHAPE_LENGTH"
+ "!"
)
arcpy.management.CalculateField(
inFeatClass, fieldName, expression, "PYTHON3"
)
arcpy.AddMessage(fieldName + " added and calculated")
# This function calculates Circularity, Convexity and Solidity
def calculateCircularity_Convexity_Solidity(workspace, inFeatClass):
# workspace: the location of the workspace
# inFeatClass: input Bathymetry High (Low) features
itemList = []
fieldType = "DOUBLE"
fieldPrecision = 15
fieldScale = 6
fields = arcpy.ListFields(inFeatClass)
field_names = [f.name for f in fields]
env.workspace = workspace
env.overwriteOutput = True
# generate bounding convex hull
chFeat = "convex_hull"
itemList.append(chFeat)
arcpy.management.MinimumBoundingGeometry(
inFeatClass, chFeat, "CONVEX_HULL", "NONE", "", "MBG_FIELDS"
)
# add area and perimeter fields of chFeat to inFeatClass
field = "convexhull_Area"
inID = "featID"
joinID = "featID"
expression = "!" + chFeat + "." + "SHAPE_AREA" + "!"
HelperFunctions.addField(inFeatClass, chFeat, field, inID, joinID, expression)
field = "convexhull_Perimeter"
expression = "!" + chFeat + "." + "SHAPE_LENGTH" + "!"
HelperFunctions.addField(inFeatClass, chFeat, field, inID, joinID, expression)
arcpy.AddMessage("two convex hull fields added")
fieldList = ["Circularity", "Convexity", "Solidity"]
for fieldName in fieldList:
if fieldName in field_names:
arcpy.AddMessage(fieldName + " exists and will be recalculated")
else:
arcpy.management.AddField(
inFeatClass, fieldName, fieldType, fieldPrecision, fieldScale
)
if fieldName == "Circularity":
# Circularity equation
expression = (
"4*math.pi*"
+ "!"
+ "SHAPE_AREA"
+ "!"
+ "/"
+ "!"
+ "convexhull_Perimeter"
+ "!"
+ "/"
+ "!"
+ "convexhull_Perimeter"
+ "!"
)
elif fieldName == "Convexity":
# Convexity equation
expression = (
"!"
+ "convexhull_Perimeter"
+ "!"
+ "/"
+ "!"
+ "SHAPE_LENGTH"
+ "!"
)
elif fieldName == "Solidity":
# Solidity equation
expression = (
"!" + "SHAPE_AREA" + "!" + "/" + "!" + "convexhull_Area" + "!"
)
arcpy.management.CalculateField(
inFeatClass, fieldName, expression, "PYTHON3"
)
arcpy.AddMessage(" Circularity, Convexity and Solidity added and calculated")
HelperFunctions.deleteDataItems(itemList)
# This functions calculates sinuosity, length to width ratio,
# and other shape attributes for the Bathymetric High features
def calculateSinuosity_LwR(workspace, tempFolder, inFeatClass, inBathy):
# workspace: the location of the workspace
# tempFolder: the location of the temporary folder
# inFeatClass: input Bathymetry High (Low) features
# inBathy: input bathymetry grid
env.workspace = workspace
env.overwriteOutput = True
time1 = datetime.now()
itemList = []
fieldType = "DOUBLE"
fieldPrecision = 15
fieldScale = 6
fields = arcpy.ListFields(inFeatClass)
field_names = [f.name for f in fields]
# generate bounding rectangle
MbrFeatClass = "bounding_rectangle"
itemList.append(MbrFeatClass)
arcpy.management.MinimumBoundingGeometry(
inFeatClass, MbrFeatClass, "RECTANGLE_BY_WIDTH", "NONE", "", "MBG_FIELDS"
)
# add MBG_LENGTH, MBG_WIDTH AND MBG_ORIENTATION to inFeatClass
field = "rectangle_Length"
inID = "featID"
joinID = "featID"
expression = "!" + MbrFeatClass + "." + "MBG_Length" + "!"
HelperFunctions.addField(inFeatClass, MbrFeatClass, field, inID, joinID, expression)
field = "rectangle_Width"
expression = "!" + MbrFeatClass + "." + "MBG_Width" + "!"
HelperFunctions.addField(inFeatClass, MbrFeatClass, field, inID, joinID, expression)
field = "rectangle_Orientation"
expression = "!" + MbrFeatClass + "." + "MBG_Orientation" + "!"
HelperFunctions.addField(inFeatClass, MbrFeatClass, field, inID, joinID, expression)
arcpy.AddMessage("three bounding rectangle fields added")
fieldList = [
"head_foot_length",
"sinuous_length",
"Sinuosity",
"mean_width",
"LengthWidthRatio",
]
for fieldName in fieldList:
if fieldName in field_names:
arcpy.AddMessage(fieldName + " exists and will be recalculated")
else:
arcpy.management.AddField(
inFeatClass, fieldName, fieldType, fieldPrecision, fieldScale
)
# call the helper function to split each polygon in the inFeatClass into multiple polygons
splitFeatClass = workspace + "/" + "inFeatClass_splitted"
itemList.append(splitFeatClass)
splitPolygon(workspace, inFeatClass, MbrFeatClass, splitFeatClass)
arcpy.AddMessage("inFeatClass splitted")
# convert polygon to line
lineFeatClass1 = workspace + "/" + "lineFeatClass1"
itemList.append(lineFeatClass1)
arcpy.management.PolygonToLine(splitFeatClass, lineFeatClass1)
arcpy.AddMessage("polygon to line done")
# selection
lineFeatClass2 = workspace + "/" + "lineFeatClass2"
itemList.append(lineFeatClass2)
whereClause = "LEFT_FID <> -1"
arcpy.analysis.Select(lineFeatClass1, lineFeatClass2, whereClause)
arcpy.AddMessage("selection done")
# spatial join
lineFeatClass3 = workspace + "/" + "lineFeatClass3"
itemList.append(lineFeatClass3)
arcpy.analysis.SpatialJoin(
lineFeatClass2,
inFeatClass,
lineFeatClass3,
"JOIN_ONE_TO_ONE",
"KEEP_ALL",
"#",
"WITHIN",
)
arcpy.AddMessage("spatial join done")
# summary statistics
outTab1 = "outTab1"
itemList.append(outTab1)
statsField = [["Shape_Length", "SUM"]]
caseField = ["RIGHT_FID", "featID"]
arcpy.analysis.Statistics(lineFeatClass3, outTab1, statsField, caseField)
outTab2 = "outTab2"
itemList.append(outTab2)
statsField = [["SUM_Shape_Length", "MEAN"]]
caseField = "featID"
arcpy.analysis.Statistics(outTab1, outTab2, statsField, caseField)
arcpy.AddMessage("summary statistics done")
# add mean_width field
field = "mean_width"
inID = "featID"
joinID = "featID"
expression = "!" + "outTab2" + "." + "MEAN_SUM_Shape_Length" + "!"
HelperFunctions.addField(inFeatClass, outTab2, field, inID, joinID, expression)
arcpy.AddMessage("add mean_width field done")
# convert feature vertices to points
inFeatVertices = workspace + "/" + "inFeatVertices"
itemList.append(inFeatVertices)
arcpy.management.FeatureVerticesToPoints(inFeatClass, inFeatVertices, "ALL")
arcpy.AddMessage("feature vertices to points done")
# add x and y
arcpy.management.AddXY(inFeatVertices)
arcpy.AddMessage("Add x and y done")
# export table as csv file
csvFile1 = tempFolder + "/inFile1.csv"
itemList.append(csvFile1)
# delete schema.ini which may contains incorrect data types (2023-04-20)
schemaFile = tempFolder + "/" + "schema.ini"
if os.path.isfile(schemaFile):
os.remove(schemaFile)
# delete not required fields (2023-06-20)
fieldsToKeep = ["featID", "rectangle_Orientation", "POINT_X", "POINT_Y"]
HelperFunctions.keepSelectedFields(inFeatVertices, fieldsToKeep)
arcpy.AddMessage("delete fields done")
arcpy.management.CopyRows(inFeatVertices, csvFile1)
arcpy.AddMessage("export to first csv done")
# read the csv file as a pandas data frame, add dtype parameter (2023-06-20)
# this is to prevent mix type warning and potentially improve efficiency in reading a large csv file
dtypeD = {
"OBJECTID": np.int64,
"featID": np.int64,
"rectangle_Orientation": np.float64,
"POINT_X": np.float64,
"POINT_Y": np.float64,
}
testDF1 = pd.read_csv(csvFile1, sep=",", header=0, dtype=dtypeD)
testDF1.set_index("OBJECTID", inplace=True)
headfootList = []
ids = np.unique(testDF1.featID)
# loop through each feature which contains a number of points
# The idea is to find a point representing 'head' (or first)
# and a point representing 'foot' (or last) of the feature
for id in ids:
x = testDF1.loc[testDF1.featID == id]
angle = round(x.rectangle_Orientation.values[0], 2)
arcpy.AddMessage(angle)
if (angle >= 45) & (angle <= 135):
y1 = x.loc[x.POINT_X == x.POINT_X.min()]
y2 = x.loc[x.POINT_X == x.POINT_X.max()]
for i in y1.index:
headfootList.append(i)
for i in y2.index:
headfootList.append(i)
else:
y1 = x.loc[x.POINT_Y == x.POINT_Y.min()]
y2 = x.loc[x.POINT_Y == x.POINT_Y.max()]
for i in y1.index:
headfootList.append(i)
for i in y2.index:
headfootList.append(i)
# generate 'head' and 'foot' featureclass
text = "("
for i in headfootList:
text = text + str(i) + ","
text = text[0:-1] + ")"
whereClause = "OBJECTID IN " + text
pointFeat1 = workspace + "/" + "pointFeat1"
itemList.append(pointFeat1)
arcpy.analysis.Select(inFeatVertices, pointFeat1, whereClause)
arcpy.AddMessage("selection done")
# extract bathy values to points
# expand inBathy
inFocal = inBathy + "_focal"
itemList.append(inFocal)
outFocalStat = FocalStatistics(
inBathy, NbrRectangle(3, 3, "CELL"), "MEAN", "DATA"
)
outFocalStat.save(inFocal)
inRasterList = [[inBathy, "depth"], [inFocal, "depth1"]]
ExtractMultiValuesToPoints(pointFeat1, inRasterList, "NONE")
arcpy.AddMessage("extract bathy values done")
# export table as csv file
csvFile2 = tempFolder + "/inFile2.csv"
itemList.append(csvFile2)
# delete schema.ini which may contains incorrect data types (2023-04-20)
schemaFile = tempFolder + "/" + "schema.ini"
if os.path.isfile(schemaFile):
os.remove(schemaFile)
# modified the codes as below to fix a weird error when running the tools in ArcGIS Pro Python command window (2025-08-05)
pointFeat2 = workspace + "/" + "pointFeat2"
itemList.append(pointFeat2)
arcpy.management.Copy(pointFeat1, pointFeat2)
arcpy.management.CopyRows(pointFeat2, csvFile2)
arcpy.AddMessage("export to second csv done")
# read the csv file as a pandas data frame, add dtype parameter (2023-06-20)
dtypeD = {
"OBJECTID": np.int64,
"featID": np.int64,
"rectangle_Orientation": np.float64,
"POINT_X": np.float64,
"POINT_Y": np.float64,
"depth": np.float64,
"depth1": np.float64,
}
testDF2 = pd.read_csv(csvFile2, sep=",", header=0, dtype=dtypeD)
testDF2.set_index("OBJECTID", inplace=True)
# if depth has nan, replace them with depth1
depthList = testDF2.loc[testDF2.depth.isnull(), "depth1"]
if depthList.size > 0:
testDF2.loc[testDF2.depth.isnull(), "depth"] = depthList
# get 'head' (first) and 'foot' (last) of each feature
ids = np.unique(testDF2.featID)
firstList = []
lastList = []
for id in ids:
x = testDF2.loc[testDF2.featID == id]
angle = round(x.rectangle_Orientation.values[0], 2)
if (angle >= 45) & (angle <= 135):
y1 = x.loc[x.POINT_X == x.POINT_X.min()]
depth1 = y1.depth.max()
y2 = x.loc[x.POINT_X == x.POINT_X.max()]
depth2 = y2.depth.max()
if depth1 > depth2:
z1 = y1.loc[y1.depth == depth1]
z2 = y2.loc[y2.depth == y2.depth.min()]
firstList.append(z1.index.values[0])
lastList.append(z2.index.values[0])
else:
z1 = y1.loc[y1.depth == y1.depth.min()]
z2 = y2.loc[y2.depth == depth2]
firstList.append(z1.index.values[0])
lastList.append(z2.index.values[0])
else:
y1 = x.loc[x.POINT_Y == x.POINT_Y.min()]
depth1 = y1.depth.max()
y2 = x.loc[x.POINT_Y == x.POINT_Y.max()]
depth2 = y2.depth.max()
if depth1 > depth2:
z1 = y1.loc[y1.depth == depth1]
z2 = y2.loc[y2.depth == y2.depth.min()]
firstList.append(z1.index.values[0])
lastList.append(z2.index.values[0])
else:
z1 = y1.loc[y1.depth == y1.depth.min()]
z2 = y2.loc[y2.depth == depth2]
firstList.append(z1.index.values[0])
lastList.append(z2.index.values[0])
# generate first points featureclass
text = "("
for i in firstList:
text = text + str(i) + ","
text = text[0:-1] + ")"
whereClause = "OBJECTID IN " + text
firstFeatClass = workspace + "/" + "firstPoints"
itemList.append(firstFeatClass)
arcpy.analysis.Select(pointFeat1, firstFeatClass, whereClause)
# generate last points featureclass
text = "("
for i in lastList:
text = text + str(i) + ","
text = text[0:-1] + ")"
whereClause = "OBJECTID IN " + text
lastFeatClass = workspace + "/" + "lastPoints"
itemList.append(lastFeatClass)
arcpy.analysis.Select(pointFeat1, lastFeatClass, whereClause)
arcpy.AddMessage("generate first and last points features done")
# polygon to point
pointFeat2 = workspace + "/" + "pointFeat2"
itemList.append(pointFeat2)
# Use FeatureToPoint function to find a point inside each part
arcpy.management.FeatureToPoint(splitFeatClass, pointFeat2, "CENTROID")
arcpy.AddMessage("feature to point done")
# sort the points
pointFeat2_1 = workspace + "/" + "pointFeat2_1"
itemList.append(pointFeat2_1)
pointFeat2_2 = workspace + "/" + "pointFeat2_2"
itemList.append(pointFeat2_2)
arcpy.management.Sort(pointFeat2, pointFeat2_1, [["ORIG_FID", "ASCENDING"]])
arcpy.management.Sort(pointFeat2, pointFeat2_2, [["ORIG_FID", "DESCENDING"]])
# add x and y
arcpy.management.AddXY(pointFeat2_1)
arcpy.management.AddXY(pointFeat2_2)
arcpy.AddMessage("Add x and y done")
# merge the first point, the centre points of each sub-polygon, then the last point
mergedFeats = [firstFeatClass, pointFeat2_1, lastFeatClass]
mergedFeat1_1 = workspace + "/" + "merged_points1_1"
itemList.append(mergedFeat1_1)
arcpy.management.Merge(mergedFeats, mergedFeat1_1)
mergedFeats = [firstFeatClass, pointFeat2_2, lastFeatClass]
mergedFeat1_2 = workspace + "/" + "merged_points1_2"
itemList.append(mergedFeat1_2)
arcpy.management.Merge(mergedFeats, mergedFeat1_2)
arcpy.AddMessage("merged done")
# point to line
lineFeat1_1 = "curveLine1"
itemList.append(lineFeat1_1)
lineField = "featID"
sortField = "OBJECTID"
# Execute PointsToLine
arcpy.management.PointsToLine(mergedFeat1_1, lineFeat1_1, lineField, sortField)
# If the above function fails silently, call my own replicated function
if arcpy.Exists(lineFeat1_1):
arcpy.AddMessage(lineFeat1_1 + " exists")
else:
myPointsToLine(mergedFeat1_1, lineFeat1_1, lineField, tempFolder)
lineFeat1_2 = "curveLine2"
itemList.append(lineFeat1_2)
lineField = "featID"
sortField = "OBJECTID"
# Execute PointsToLine
arcpy.management.PointsToLine(mergedFeat1_2, lineFeat1_2, lineField, sortField)
# If the above function fails silently, call my own replicated function
if arcpy.Exists(lineFeat1_2):
arcpy.AddMessage(lineFeat1_2 + " exists")
else:
myPointsToLine(mergedFeat1_2, lineFeat1_2, lineField, tempFolder)
arcpy.AddMessage("points to curve line done")
# merge curvelines
# We do not know which curveline is the true curveline connecting the points in correct order.
# Thus we merge the two curvelines together and select the one with shorter length, which is the correct one
mergedFeats = [lineFeat1_1, lineFeat1_2]
mergedCurveFeat = workspace + "/" + "merged_curves"
itemList.append(mergedCurveFeat)
arcpy.management.Merge(mergedFeats, mergedCurveFeat)
arcpy.AddMessage("merged curves done")
# summary statistics
# in order to select the shorter curveline
outTab3 = "outTab3"
itemList.append(outTab3)
statsField = [["Shape_Length", "MIN"]]
caseField = ["featID"]
arcpy.analysis.Statistics(mergedCurveFeat, outTab3, statsField, caseField)
# merge to create a straight line connecting the first
# and last point in order to calculate the straight length (head to foot length)
mergedFeats = [firstFeatClass, lastFeatClass]
mergedFeat2 = workspace + "/" + "merged_points2"
itemList.append(mergedFeat2)
arcpy.management.Merge(mergedFeats, mergedFeat2)
arcpy.AddMessage("merged done")
# point to line
lineFeat2 = "straightLine"
itemList.append(lineFeat2)
lineField = "featID"
sortField = "OBJECTID"
# Execute PointsToLine
arcpy.management.PointsToLine(mergedFeat2, lineFeat2, lineField, sortField)
# If the above function fails silently, call my own replicated function
if arcpy.Exists(lineFeat2):
arcpy.AddMessage(lineFeat2 + " exists")
else:
myPointsToLine(mergedFeat2, lineFeat2, lineField, tempFolder)
arcpy.AddMessage("points to straight line done")
# add sinuous_length field
field = "sinuous_length"
inID = "featID"
joinID = "featID"
expression = "!" + "outTab3" + "." + "MIN_Shape_Length" + "!"
HelperFunctions.addField(inFeatClass, outTab3, field, inID, joinID, expression)
arcpy.AddMessage("add sinuous_length field done")
# add head_foot_length field
field = "head_foot_length"
inID = "featID"
joinID = "featID"
expression = "!" + "straightLine" + "." + "Shape_Length" + "!"
HelperFunctions.addField(inFeatClass, lineFeat2, field, inID, joinID, expression)
arcpy.AddMessage("add heat_foot_length field done")
field = "Sinuosity"
expression = "!sinuous_length! / !head_foot_length!"
arcpy.management.CalculateField(inFeatClass, field, expression, "PYTHON3")
arcpy.AddMessage("calculate Sinuosity field done")
field = "LengthWidthRatio"
expression = "!sinuous_length! / !mean_width!"
arcpy.management.CalculateField(inFeatClass, field, expression, "PYTHON3")
arcpy.AddMessage("calculate LengthWidthRatio field done")
HelperFunctions.deleteDataItems(itemList)
arcpy.AddMessage("data deletion done")
time2 = datetime.now()
diff = time2 - time1
arcpy.AddMessage("took " + str(diff) + " to have all attributes generated.")
# This function calculates mean_segment_slope attribute.
# mean_segment_slope: A number of linear segments are created by connecting the head,
# each point of minimum depth on a profile, and the foot.
# The slopes of the segments are calculated and averaged as this mean_segment_slope value.
def calculate_segmentSlope(
inFeat, inTab, dissolveLineFeat, headFeat, footFeat, outFeat
):
# inFeat: input point featureclass represents points along the cross-feature profiles,
# each point must have a depth value
# inTab: input table that has some statistical values calculated from inFeat
# dissolveLineFeat: the name of the line featureclass resulted from dissolving the inLineFeat
# headFeat: input head feature
# footFeat: input foot feature
# outFeat: output point featureclass represents the start and end points of line segments
itemList = []
# for each profile, select a point with the minimum depth
# the outFeat is the output also used in the Near_analysis function that follow this function
field = "min_depth"
inID = "RIGHT_FID"
joinID = "RIGHT_FID"
expression = "!" + inTab + "." + "MIN_RASTERVALU" + "!"
HelperFunctions.addField(inFeat, inTab, field, inID, joinID, expression)
outFeat2 = "inFeat_selected"
itemList.append(outFeat2)
whereClause = '"RASTERVALU" = "min_depth"'
arcpy.analysis.Select(inFeat, outFeat2, whereClause)
arcpy.management.Copy(outFeat2, outFeat)
# count the number of profiles
noLines = int(arcpy.management.GetCount(dissolveLineFeat).getOutput(0))
if noLines < 2: # only one profile
# get head depth
cursor = arcpy.SearchCursor(headFeat)
row = cursor.next()
headX = row.getValue("POINT_X")
headY = row.getValue("POINT_Y")
headDepth = row.getValue("depth1")
del row, cursor
# get foot depth
cursor = arcpy.SearchCursor(footFeat)
row = cursor.next()
footX = row.getValue("POINT_X")
footY = row.getValue("POINT_Y")
footDepth = row.getValue("depth1")
del row, cursor
# calculate distance between head and foot
distance = calculateDistance(headX, headY, footX, footY)
# calculate slope between head and foot as the mean_segment_slope
meanSlope = abs(calculateSlope(footDepth, headDepth, distance))
else:
# each feature in outFeat2 represents one or multiple points that have the minimum depth along a profile
# multiple points along a profile may have the same depth value as the minimum depth
# in this case, only one point is selected by compiling an ids_tobeDeleted list
# add and calculate field
# sort
outFeat3 = "outFeat2_sorted"
itemList.append(outFeat3)
sortField = [["RIGHT_FID", "Descending"]]
arcpy.management.Sort(outFeat2, outFeat3, sortField)
# get a list of ids and fids
cursor = arcpy.SearchCursor(outFeat3)
idList = []
fidList = []
for row in cursor:
idV = row.getValue("OBJECTID")
fidV = row.getValue("RIGHT_FID")
idList.append(idV)
fidList.append(fidV)
del cursor, row
ids_tobeDeleted = []
i = 0
while i < len(idList):
fidV = fidList[i]
if i == len(idList) - 1:
break
else:
idV1 = idList[i + 1]
fidV1 = fidList[i + 1]
if fidV == fidV1: