-
Notifications
You must be signed in to change notification settings - Fork 1
/
ClassificationFeature.pyt
687 lines (612 loc) · 25.5 KB
/
ClassificationFeature.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
#### Author: Zhi Huang
#### Organisation: Geoscience Australia
#### Email: [email protected]
#### Date: August 15, 2022
#### Python version: 3+
#### ArcGIS Pro: 2.6.4 and above
import arcpy
from arcpy import env
arcpy.CheckOutExtension("Spatial")
class Toolbox:
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Toolbox"
self.alias = "ClassifyFeatures"
# List of tool classes associated with this toolbox
# There are two tools. One tool is used to classify Bathymetric High features. The other is used to classify Bathymetric Low features.
self.tools = [
Classify_Bathymetric_High_Features_Tool,
Classify_Bathymetric_Low_Features_Tool,
]
# This tool is used to classify Bathymetric Low features based on their attributes.
class Classify_Bathymetric_Low_Features_Tool:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Classify Bathymetric Low Features Tool"
self.description = "Classify each Bathymetric Low feature according to the morphological classification scheme"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Bathymetric Low Features",
name="inFeatClass",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input",
)
# second parameter
param1 = arcpy.Parameter(
displayName="Output Features",
name="outFeatClass",
datatype="DEFeatureClass",
parameterType="Derived",
direction="Output",
)
param1.parameterDependencies = [param0.name]
# 3rd parameter
param2 = arcpy.Parameter(
displayName="Length_to_Width Ratio Threshold",
name="lwRatioT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param2.value = 8.0
# 4th parameter
param3 = arcpy.Parameter(
displayName="Head Depth Threshold (m)",
name="headDepthT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param3.value = 4000.0
# 5th parameter
param4 = arcpy.Parameter(
displayName="Mean Segment Slope Threshold Large (degree)",
name="meanSegmentSlopeT1",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param4.value = 7.0
# 6th parameter
param5 = arcpy.Parameter(
displayName="Head_to_Foot Depth Range Threshold (m)",
name="hfdepthRangeT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param5.value = 600.0
# 7th parameter
param6 = arcpy.Parameter(
displayName="Mean Segment Slope Threshold Small (degree)",
name="meanSegmentSlopeT2",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param6.value = 2.0
# 8th parameter
param7 = arcpy.Parameter(
displayName="Shape Circularity Threshold",
name="circularityT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param7.value = 0.5
parameters = [param0, param1, param2, param3, param4, param5, param6, param7]
return parameters
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, parameters, messages):
"""The source code of the tool."""
inFeatClass = parameters[0].valueAsText
outFeatClass = parameters[1].valueAsText
lwRatioT = float(parameters[2].valueAsText)
headDepthT = float(parameters[3].valueAsText)
meanSegmentSlopeT1 = float(parameters[4].valueAsText)
hfdepthRangeT = float(parameters[5].valueAsText)
meanSegmentSlopeT2 = float(parameters[6].valueAsText)
circularityT = float(parameters[7].valueAsText)
# make sure meanSegmentSlopeT2 is smaller than meanSegmentSlopeT1
if meanSegmentSlopeT2 > meanSegmentSlopeT1:
messages.addErrorMessage(
"Mean Segment Slope Threshold Small must be smaller than Mean Segment Slope Threshold Large!"
)
raise arcpy.ExecuteError
# enable helper
helper = helpers()
inFeatClass = helper.convert_backslach_forwardslach(inFeatClass)
# if the input feature class is selected from a drop-down list, the inFeatClass does not contain the full path
# In this case, the full path needs to be obtained from the map layer
if inFeatClass.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isFeatureLayer:
if inFeatClass == lyr.name:
inFeatClass = helper.convert_backslach_forwardslach(
lyr.dataSource
)
# check that the input feature class is in a correct format
vecDesc = arcpy.Describe(inFeatClass)
vecType = vecDesc.dataType
if (vecType != "FeatureClass") or (inFeatClass.rfind(".gdb") == -1):
messages.addErrorMessage(
"The input featureclass must be a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the input feature class is in a projected coordinate system
spatialReference = vecDesc.spatialReference
if spatialReference.type == "Geographic":
messages.addErrorMessage(
"Coordinate system of input featureclass is Geographic. A projected coordinate system is required!"
)
raise arcpy.ExecuteError
workspaceName = inFeatClass[0 : inFeatClass.rfind("/")]
env.workspace = workspaceName
env.overwriteOutput = True
fields = arcpy.ListFields(inFeatClass)
field_names = [f.name for f in fields]
# make sure all the required attributes exist in the input featureclass
attributeList = [
"featID",
"LengthWidthRatio",
"head_foot_depthRange",
"mean_width",
"profileSymmetry",
"profile_bottom_SlopeClass",
"profile_side_SlopeClass",
"headDepth",
"mean_segment_slope",
"mean_width_thickness_ratio",
"mean_thickness",
"width_distance_slope",
"width_distance_correlation",
"thick_distance_slope",
"thick_distance_correlation",
"Circularity",
]
attributeList = [
"featID",
"LengthWidthRatio",
"head_foot_depthRange",
"mean_width",
"profileSymmetry",
"profile_bottom_SlopeClass",
"profile_side_SlopeClass",
"headDepth",
"mean_segment_slope",
"Circularity",
]
for attribute in attributeList:
if attribute not in field_names:
messages.addErrorMessage(
"The input featureclass does not have "
+ attribute
+ " attribute. You have to calculate the attribute using the Attributes Tool!"
)
raise arcpy.ExecuteError
# check the 'Morphological_Feature' field exists
field = "Morphology_feature"
fieldType = "TEXT"
fieldLength = 200
if field in field_names:
arcpy.AddMessage(field + " exists and will be recalculated.")
else:
arcpy.AddField_management(
inFeatClass, field, fieldType, field_length=fieldLength
)
# loop through each feature
cursor = arcpy.UpdateCursor(inFeatClass)
for row in cursor:
# get attributes values
featID = row.getValue("featID")
arcpy.AddMessage("classifying featID: " + str(featID))
lwRatio = float(row.getValue("LengthWidthRatio"))
hfdepthRange = float(row.getValue("head_foot_depthRange"))
meanWidth = float(row.getValue("mean_width"))
profileSymmetry = row.getValue("profileSymmetry")
profileSymmetryL = profileSymmetry.split(",")
profileBottomClass = row.getValue("profile_bottom_SlopeClass")
profileBottomClassL = profileBottomClass.split(",")
profileSideClass = row.getValue("profile_side_SlopeClass")
profileSideClassL = profileSideClass.split(",")
headDepth = float(row.getValue("headDepth"))
meanSegmentSlope = float(row.getValue("mean_segment_slope"))
circularity = float(row.getValue("Circularity"))
# the bottom slope list combines profile's bottom slope and side slope (only when the profile is triangle)
slopeL = []
j = 0
while j < len(profileBottomClassL):
bottomSlope = profileBottomClassL[j]
sideSlope = profileSideClassL[j]
if bottomSlope == "no bottom": # triangle profile
slopeL.append(sideSlope)
else:
slopeL.append(bottomSlope)
j += 1
arcpy.AddMessage("slopeL: " + str(slopeL))
# bottom slope class count
flatSlopeCount = slopeL.count("flat")
gentleSlopeCount = slopeL.count("gentle")
moderateSlopeCount = slopeL.count("moderate")
steepSlopeCount = slopeL.count("steep")
# side slope class count
sFlatCount = profileSideClassL.count("flat")
sGentleCount = profileSideClassL.count("gentle")
sModerateCount = profileSideClassL.count("moderate")
sSteepCount = profileSideClassL.count("steep")
# profile symmetry class count
SymmCount = profileSymmetryL.count("Symmetric")
AsymmCount = profileSymmetryL.count("Asymmetric")
# classification of Bathymetric Low features starts here
# The classification rules are based on the morphological classification scheme. Please see the metadata of the tool for detailed description of the rules.
feature = "unclassified"
if lwRatio >= lwRatioT:
if abs(headDepth) >= headDepthT:
if (AsymmCount >= SymmCount) and (
steepSlopeCount + moderateSlopeCount
>= flatSlopeCount + gentleSlopeCount
):
feature = "Trench"
else:
feature = "Trough"
else:
if (meanSegmentSlope > meanSegmentSlopeT1) and (
sSteepCount + sModerateCount >= sFlatCount + sGentleCount
):
feature = "Gully"
else:
if (hfdepthRange >= hfdepthRangeT) and (
meanSegmentSlope >= meanSegmentSlopeT2
):
feature = "Canyon"
else:
feature = "Valley/Channel"
else:
sCount = sSteepCount + sModerateCount + sGentleCount + sFlatCount
if sCount == 0:
feature = "Depression"
elif (
(circularity >= circularityT)
and (sSteepCount >= sModerateCount)
and (sSteepCount >= sGentleCount)
and (sSteepCount >= sFlatCount)
):
feature = "Hole"
else:
feature = "Depression"
row.setValue(field, feature)
cursor.updateRow(row)
arcpy.AddMessage(feature)
del cursor, row
return
# This tool is used to classify Bathymetric High features based on their attributes
class Classify_Bathymetric_High_Features_Tool:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Classify Bathymetric High Features Tool"
self.description = "Classify each Bathymetric High feature according to the morphological classification scheme"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Bathymetric High Features",
name="inFeatClass",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input",
)
# second parameter
param1 = arcpy.Parameter(
displayName="Output Features",
name="outFeatClass",
datatype="DEFeatureClass",
parameterType="Derived",
direction="Output",
)
param1.parameterDependencies = [param0.name]
# 3rd parameter
param2 = arcpy.Parameter(
displayName="Ridge Length_to_Width Ratio Threshold",
name="ridge_lwRatioT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param2.value = 5.0
# 4th parameter
param3 = arcpy.Parameter(
displayName="Bank Minimum Depth Threshold (m)",
name="bank_minDepthT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param3.value = 200.0
# 5th parameter
param4 = arcpy.Parameter(
displayName="Bank Area Threshold (km^2)",
name="bank_areaT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param4.value = 1.0
# 6th parameter
param5 = arcpy.Parameter(
displayName="Plateau Area Threshold (km^2)",
name="plateau_areaT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param5.value = 100.0
# 7th parameter
param6 = arcpy.Parameter(
displayName="Hummock Depth Range Threshold (m)",
name="hummock_depthRangeT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param6.value = 10.0
# 8th parameter
param7 = arcpy.Parameter(
displayName="Hummock Area Threshold (m^2)",
name="hummock_areaT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param7.value = 1000.0
# 9th parameter
param8 = arcpy.Parameter(
displayName="Cone Circularity Threshold",
name="cone_circularityT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param8.value = 0.75
parameters = [
param0,
param1,
param2,
param3,
param4,
param5,
param6,
param7,
param8,
]
return parameters
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, parameters, messages):
"""The source code of the tool."""
inFeatClass = parameters[0].valueAsText
outFeatClass = parameters[1].valueAsText
ridge_lwRatioT = float(parameters[2].valueAsText)
bank_minDepthT = float(parameters[3].valueAsText)
bank_areaT = float(parameters[4].valueAsText)
plateau_areaT = float(parameters[5].valueAsText)
hummock_depthRangeT = float(parameters[6].valueAsText)
hummock_areaT = float(parameters[7].valueAsText)
cone_circularityT = float(parameters[8].valueAsText)
# enable helper functions
helper = helpers()
inFeatClass = helper.convert_backslach_forwardslach(inFeatClass)
# if the input feature class is selected from a drop-down list, the inFeatClass does not contain the full path
# In this case, the full path needs to be obtained from the map layer
if inFeatClass.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isFeatureLayer:
if inFeatClass == lyr.name:
inFeatClass = helper.convert_backslach_forwardslach(
lyr.dataSource
)
# check that the input feature class is in a correct format
vecDesc = arcpy.Describe(inFeatClass)
vecType = vecDesc.dataType
if (vecType != "FeatureClass") or (inFeatClass.rfind(".gdb") == -1):
messages.addErrorMessage(
"The input featureclass must be a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the input feature class is in a projected coordinate system
spatialReference = vecDesc.spatialReference
if spatialReference.type == "Geographic":
messages.addErrorMessage(
"Coordinate system of input featureclass is Geographic. A projected coordinate system is required!"
)
raise arcpy.ExecuteError
workspaceName = inFeatClass[0 : inFeatClass.rfind("/")]
env.workspace = workspaceName
env.overwriteOutput = True
fields = arcpy.ListFields(inFeatClass)
field_names = [f.name for f in fields]
# make sure all the required attributes exist in the input featureclass
attributeList = [
"featID",
"LengthWidthRatio",
"depthRange",
"profileShape",
"profile_top_SlopeClass",
"profile_side_SlopeClass",
"minDepth",
"mean_width",
"Circularity",
]
for attribute in attributeList:
if attribute not in field_names:
messages.addErrorMessage(
"The input featureclass does not have "
+ attribute
+ " attribute. You have to calculate the attribute using the Attributes Tool!"
)
raise arcpy.ExecuteError
# check the 'Morphological_Feature' field exists
field = "Morphology_feature"
fieldType = "TEXT"
fieldLength = 200
if field in field_names:
arcpy.AddMessage(field + " exists and will be recalculated.")
else:
arcpy.AddField_management(
inFeatClass, field, fieldType, field_length=fieldLength
)
# loop through each feature
cursor = arcpy.UpdateCursor(inFeatClass)
i = 1
for row in cursor:
featID = row.getValue("featID")
arcpy.AddMessage("classifying featID: " + str(featID))
# get attributes values
lwRatio = float(row.getValue("LengthWidthRatio"))
depthRange = float(row.getValue("depthRange"))
profileShape = row.getValue("profileShape")
profileShapeL = profileShape.split(",")
profileTopClass = row.getValue("profile_top_SlopeClass")
profileTopClassL = profileTopClass.split(",")
profileSideClass = row.getValue("profile_side_SlopeClass")
profileSideClassL = profileSideClass.split(",")
minDepth = float(row.getValue("minDepth"))
meanWidth = float(row.getValue("mean_width"))
area = float(row.getValue("Shape_Area"))
circularity = float(row.getValue("Circularity"))
# get profile shape class count
RegularCount = profileShapeL.count("Regular")
IrregularCount = profileShapeL.count("Irregular")
TriangleCount = profileShapeL.count("Triangle")
FlatCount = profileShapeL.count("Flat")
# if profile shape is a triangle, add its profile side slope class
triangle_sideSlopeL = []
k = 0
while k < len(profileShapeL):
pShape = profileShapeL[k]
sideSlope = profileSideClassL[k]
if pShape == "Triangle":
triangle_sideSlopeL.append(sideSlope)
k += 1
# triangle side slope count
moderateSlopeCountTriangle = triangle_sideSlopeL.count("moderate")
steepSlopeCountTriangle = triangle_sideSlopeL.count("steep")
# the top slope list combines profile's top slope and side slope (only when the profile is triangle)
slopeL = []
j = 0
while j < len(profileTopClassL):
topSlope = profileTopClassL[j]
sideSlope = profileSideClassL[j]
if topSlope == "no top": # triangle profile
slopeL.append(sideSlope)
else:
slopeL.append(topSlope)
j += 1
# top slope class count
flatSlopeCount = slopeL.count("flat")
gentleSlopeCount = slopeL.count("gentle")
moderateSlopeCount = slopeL.count("moderate")
steepSlopeCount = slopeL.count("steep")
# side slope class count
flatSlopeCountSide = profileSideClassL.count("flat")
gentleSlopeCountSide = profileSideClassL.count("gentle")
moderateSlopeCountSide = profileSideClassL.count("moderate")
steepSlopeCountSide = profileSideClassL.count("steep")
# classification of Bathymetric High features starts here
# The classification rules are based on the morphological classification scheme. Please see the metadata of the tool for detailed description of the rules.
feature = "unclassified"
if lwRatio >= ridge_lwRatioT:
feature = "Ridge"
elif depthRange >= 1000:
feature = "Seamount"
elif depthRange >= meanWidth:
feature = "Pinnacle"
elif (
(TriangleCount >= RegularCount)
and (TriangleCount >= IrregularCount)
and (TriangleCount >= FlatCount)
and (moderateSlopeCountTriangle + steepSlopeCountTriangle >= 1)
and (circularity >= cone_circularityT)
):
feature = "Cone"
elif (
(
flatSlopeCount
>= gentleSlopeCount + moderateSlopeCount + steepSlopeCount
)
and (abs(minDepth) <= bank_minDepthT)
and (area > bank_areaT * 1000000)
):
feature = "Bank"
elif (
(
flatSlopeCount
>= gentleSlopeCount + moderateSlopeCount + steepSlopeCount
)
and (moderateSlopeCountSide + steepSlopeCountSide >= 1)
and (area > plateau_areaT * 1000000)
):
feature = "Plateau"
elif depthRange >= 500:
if (
(RegularCount >= IrregularCount)
and (RegularCount >= TriangleCount)
and (RegularCount >= FlatCount)
):
feature = "Knoll"
else:
feature = "Hill"
elif (depthRange < hummock_depthRangeT) and (area < hummock_areaT):
feature = "Hummock"
else:
feature = "Mound"
row.setValue(field, feature)
cursor.updateRow(row)
arcpy.AddMessage(feature)
i += 1
del cursor, row
return
# define helper functions here
class helpers:
# This function converts backslach (accepted through the ArcGIS tool) to forwardslach (needed in python script) in a path
def convert_backslach_forwardslach(self, inText):
# inText: input path
inText = rf"{inText}"
if inText.find("\t"):
inText = inText.replace("\t", "\\t")
elif inText.find("\n"):
inText = inText.replace("\n", "\\n")
elif inText.find("\r"):
inText = inText.replace("\r", "\\r")
inText = inText.replace("\\", "/")
return inText