-
Notifications
You must be signed in to change notification settings - Fork 1
/
BathymetricLow.pyt
1587 lines (1425 loc) · 61.8 KB
/
BathymetricLow.pyt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#### Author: Zhi Huang
#### Organisation: Geoscience Australia
#### Email: [email protected]
#### Date: August 15, 2022
#### Python version: 3+
#### ArcGIS Pro: 2.6.4 and above
import math
import warnings
from datetime import datetime
import arcpy
import numpy as np
from arcpy.sa import *
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 = "BathymetricLow"
# List of tool classes associated with this toolbox
# There are three tools in this toolset used to map Bathymetric High features.
self.tools = [TPIToolLow, Openness_Low_Tool, TPI_CI_Low_Tool]
# TPIToolLow uses Topographic Position Index (TPI) technique to map Bathymetric Low features
class TPIToolLow:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "TPI Tool Bathymetric Low"
self.description = "Cacluate TPI and generate an output Featureclass"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Bathymetry Raster",
name="bathyRas",
datatype="GPRasterLayer",
parameterType="Required",
direction="Input",
)
# second parameter
param1 = arcpy.Parameter(
displayName="Output TPI Raster",
name="tpiRas",
datatype="DERasterDataset",
parameterType="Required",
direction="Output",
)
# third parameter
param2 = arcpy.Parameter(
displayName="Output Feature",
name="outFeat",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output",
)
# fourth parameter
param3 = arcpy.Parameter(
displayName="Area Threshold",
name="areaThreshold",
datatype="GPArealUnit",
parameterType="Required",
direction="Input",
)
# fifth parameter
param4 = arcpy.Parameter(
displayName="TPI Circle Radius (unit: cell)",
name="tpiRadius",
datatype="GPLong",
parameterType="Required",
direction="Input",
)
param4.value = 3
# sixth parameter
param5 = arcpy.Parameter(
displayName="TPI STD Scale",
name="tpiSTDScale",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param5.value = 1.0
# seventh parameter
param6 = arcpy.Parameter(
displayName="Temporary Workspace",
name="tempWS",
datatype="DEWorkspace",
parameterType="required",
direction="Input",
)
param6.defaultEnvironmentName = "workspace"
parameters = [param0, param1, param2, param3, param4, param5, param6]
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."""
bathyRas = parameters[0].valueAsText
tpiRas = parameters[1].valueAsText
outFeat = parameters[2].valueAsText
areaThreshold = parameters[3].valueAsText
tpiRadius = parameters[4].valueAsText
tpiSTDScale = parameters[5].valueAsText
tempWS = parameters[6].valueAsText
# enable the helper function
helper = helpers()
bathyRas = helper.convert_backslach_forwardslach(bathyRas)
tpiRas = helper.convert_backslach_forwardslach(tpiRas)
outFeat = helper.convert_backslach_forwardslach(outFeat)
tempWS = helper.convert_backslach_forwardslach(tempWS)
# if the input bathyRas is selected from a drop-down list, the bathyRas does not contain the full path
# In this case, the full path needs to be obtained from the map layer
if bathyRas.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isRasterLayer:
if bathyRas == lyr.name:
bathyRas = helper.convert_backslach_forwardslach(lyr.dataSource)
# check that the input bathymetry grid is in a correct format
rasDesc = arcpy.Describe(bathyRas)
rasFormat = rasDesc.format
if rasFormat != "FGDBR":
messages.addErrorMessage(
"The input bathymetry raster must be a raster dataset in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the input bathymetry grid is in a projected coordinate system
spatialReference = rasDesc.spatialReference
if spatialReference.type == "Geographic":
messages.addErrorMessage(
"Coordinate system of input bathymetry grid is Geographic. A projected coordinate system is required!"
)
raise arcpy.ExecuteError
# check that the output TPI grid must be in a correct format
if tpiRas.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output TPI raster must be nominated as a raster dataset in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the output featureclass must be in a correct format
if outFeat.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output featureclass must be nominated as a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the temporary workspace must be in a correct format
if tempWS.rfind(".gdb") == -1:
messages.addErrorMessage(
"The temporary workspace must be nominated as a File GeoDatabase!"
)
raise arcpy.ExecuteError
workspaceName = bathyRas[0 : bathyRas.rfind("/")]
workspaceName1 = tpiRas[0 : tpiRas.rfind("/")]
workspaceName2 = outFeat[0 : outFeat.rfind("/")]
areaThresholdValue = areaThreshold.split(" ")[0]
areaUnit = areaThreshold.split(" ")[1]
# waterproof some unusal errors
if tpiRas == outFeat:
messages.addErrorMessage(
"The output TPI raster and output Featureclass cannot have the same name in the same workspace!"
)
raise arcpy.ExecuteError
if (
(tempWS == workspaceName)
or (tempWS == workspaceName1)
or (tempWS == workspaceName2)
):
messages.addErrorMessage(
"The temporary workspace must be different from the input/output workspace(s)."
)
raise arcpy.ExecuteError
if areaUnit == "Unknown":
messages.addErrorMessage("You cann't provide an unknown area unit.")
raise arcpy.ExecuteError
arcpy.env.workspace = workspaceName
arcpy.env.overwriteOutput = True
# call the helper function to calculate TPI and generate output Bathymetric Low features
helper.TPI_Tool_Low(
tempWS,
bathyRas,
tpiRas,
outFeat,
areaThresholdValue,
areaUnit,
tpiRadius,
tpiSTDScale,
)
return
# Openness_Low_Tool uses Openness technique to map Bathymetric Low features
class Openness_Low_Tool:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Openness Tool Bathymetric Low"
self.description = (
"Cacluate Positive Openness and generate an output Featureclass"
)
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Bathymetry Raster",
name="bathyRas",
datatype="GPRasterLayer",
parameterType="Required",
direction="Input",
)
# second parameter
param1 = arcpy.Parameter(
displayName="Output Positive Openness Raster",
name="poRas",
datatype="DERasterDataset",
parameterType="Required",
direction="Output",
)
# third parameter
param2 = arcpy.Parameter(
displayName="Output Feature",
name="outFeat",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output",
)
# fourth parameter
param3 = arcpy.Parameter(
displayName="Area Threshold",
name="areaThreshold",
datatype="GPArealUnit",
parameterType="Required",
direction="Input",
)
# fifth parameter
param4 = arcpy.Parameter(
displayName="Openness Circle Radius (unit: cell)",
name="poRadius",
datatype="GPLong",
parameterType="Required",
direction="Input",
)
param4.value = 3
# sixth parameter
param5 = arcpy.Parameter(
displayName="PO STD Scale Large",
name="poSTDScaleLarge",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param5.value = 2.0
# seventh parameter
param6 = arcpy.Parameter(
displayName="PO STD Scale Small",
name="poSTDScaleSmall",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param6.value = 1.0
# eighth parameter
param7 = arcpy.Parameter(
displayName="Temporary Workspace",
name="tempWS",
datatype="DEWorkspace",
parameterType="required",
direction="Input",
)
param7.defaultEnvironmentName = "workspace"
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."""
# enable the helper function
helper = helpers()
bathyRas = parameters[0].valueAsText
poRas = parameters[1].valueAsText
outFeat = parameters[2].valueAsText
areaThreshold = parameters[3].valueAsText
poRadius = parameters[4].valueAsText
poSTDScaleLarge = parameters[5].valueAsText
poSTDScaleSmall = parameters[6].valueAsText
tempWS = parameters[7].valueAsText
bathyRas = helper.convert_backslach_forwardslach(bathyRas)
poRas = helper.convert_backslach_forwardslach(poRas)
outFeat = helper.convert_backslach_forwardslach(outFeat)
tempWS = helper.convert_backslach_forwardslach(tempWS)
if bathyRas.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isRasterLayer:
if bathyRas == lyr.name:
bathyRas = helper.convert_backslach_forwardslach(lyr.dataSource)
# check that the input bathymetry grid is in a correct format
rasDesc = arcpy.Describe(bathyRas)
rasFormat = rasDesc.format
if rasFormat != "FGDBR":
messages.addErrorMessage(
"The input bathymetry raster must be a raster dataset in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the input bathymetry grid is in a projected coordinate system
spatialReference = rasDesc.spatialReference
if spatialReference.type == "Geographic":
messages.addErrorMessage(
"Coordinate system of input bathymetry grid is Geographic. A projected coordinate system is required!"
)
raise arcpy.ExecuteError
# check that the output TPI grid must be in a correct format
if poRas.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output PO raster must be nominated as a raster dataset in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the output featureclass must be in a correct format
if outFeat.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output featureclass must be nominated as a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the temporary workspace must be in a correct format
if tempWS.rfind(".gdb") == -1:
messages.addErrorMessage(
"The temporary workspace must be nominated as a File GeoDatabase!"
)
raise arcpy.ExecuteError
workspaceName = bathyRas[0 : bathyRas.rfind("/")]
workspaceName1 = poRas[0 : poRas.rfind("/")]
workspaceName2 = outFeat[0 : outFeat.rfind("/")]
areaThresholdValue = areaThreshold.split(" ")[0]
areaUnit = areaThreshold.split(" ")[1]
# waterproof some unusal errors
if poRas == outFeat:
messages.addErrorMessage(
"The output Positive Openness raster and output Featureclass cannot have the same name in the same workspace!"
)
raise arcpy.ExecuteError
if (
(tempWS == workspaceName)
or (tempWS == workspaceName1)
or (tempWS == workspaceName2)
):
messages.addErrorMessage(
"The temporary workspace must be different from the input/output workspace(s)."
)
raise arcpy.ExecuteError
if areaUnit == "Unknown":
messages.addErrorMessage("You cann't provide an unknown area unit.")
raise arcpy.ExecuteError
arcpy.env.workspace = workspaceName
arcpy.env.overwriteOutput = True
# call the helper function to calculate openness and generate Bathymetric Low features
helper.opennessLow(
tempWS,
bathyRas,
poRas,
outFeat,
areaThresholdValue,
areaUnit,
poRadius,
poSTDScaleLarge,
poSTDScaleSmall,
messages,
)
return
# TPI_CI_Low_Tool use TPI and convergence index (CI) techniques to map Bathymetric Low features
class TPI_CI_Low_Tool:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "TPI CI Tool Bathymetric Low"
self.description = "Cacluate TPI, CI and generate an output Featureclass"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Bathymetry Raster",
name="bathyRas",
datatype="GPRasterLayer",
parameterType="Required",
direction="Input",
)
# second parameter
param1 = arcpy.Parameter(
displayName="Output TPI Raster",
name="tpiRas",
datatype="DERasterDataset",
parameterType="Required",
direction="Output",
)
# third parameter
param2 = arcpy.Parameter(
displayName="Output CI Raster",
name="ciRas",
datatype="DERasterDataset",
parameterType="Required",
direction="Output",
)
# fourth parameter
param3 = arcpy.Parameter(
displayName="Output Feature",
name="outFeat",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output",
)
# fifth parameter
param4 = arcpy.Parameter(
displayName="Area Threshold",
name="areaThreshold",
datatype="GPArealUnit",
parameterType="Required",
direction="Input",
)
# sixth parameter
param5 = arcpy.Parameter(
displayName="TPI Circle Radius (unit: cell)",
name="tpiRadius",
datatype="GPLong",
parameterType="Required",
direction="Input",
)
param5.value = 3
# seven parameter
param6 = arcpy.Parameter(
displayName="TPI STD Scale",
name="tpiSTDScale",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param6.value = 1.0
# eight parameter
param7 = arcpy.Parameter(
displayName="CI STD Scale",
name="ciSTDScale",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param7.value = 1.0
# nineth parameter
param8 = arcpy.Parameter(
displayName="Temporary Workspace",
name="tempWS",
datatype="DEWorkspace",
parameterType="required",
direction="Input",
)
param8.defaultEnvironmentName = "workspace"
# tenth parameter
param9 = arcpy.Parameter(
displayName="Temporary Folder",
name="tempFolder",
datatype="DEFolder",
parameterType="required",
direction="Input",
)
parameters = [
param0,
param1,
param2,
param3,
param4,
param5,
param6,
param7,
param8,
param9,
]
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."""
# enable the helper functions
helper = helpers()
bathyRas = parameters[0].valueAsText
tpiRas = parameters[1].valueAsText
ciRas = parameters[2].valueAsText
outFeat = parameters[3].valueAsText
areaThreshold = parameters[4].valueAsText
tpiRadius = parameters[5].valueAsText
tpiSTDScale = parameters[6].valueAsText
ciSTDScale = parameters[7].valueAsText
tempWS = parameters[8].valueAsText
tempFolder = parameters[9].valueAsText
bathyRas = helper.convert_backslach_forwardslach(bathyRas)
tpiRas = helper.convert_backslach_forwardslach(tpiRas)
ciRas = helper.convert_backslach_forwardslach(ciRas)
outFeat = helper.convert_backslach_forwardslach(outFeat)
tempWS = helper.convert_backslach_forwardslach(tempWS)
tempFolder = helper.convert_backslach_forwardslach(tempFolder)
if bathyRas.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isRasterLayer:
if bathyRas == lyr.name:
bathyRas = helper.convert_backslach_forwardslach(lyr.dataSource)
# check that the input bathymetry grid is in a correct format
rasDesc = arcpy.Describe(bathyRas)
rasFormat = rasDesc.format
if rasFormat != "FGDBR":
messages.addErrorMessage(
"The input bathymetry raster must be a raster dataset in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the input bathymetry grid is in a projected coordinate system
spatialReference = rasDesc.spatialReference
if spatialReference.type == "Geographic":
messages.addErrorMessage(
"Coordinate system of input bathymetry grid is Geographic. A projected coordinate system is required!"
)
raise arcpy.ExecuteError
# check that the output TPI grid must be in a correct format
if tpiRas.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output TPI raster must be nominated as a raster dataset in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the output CI grid must be in a correct format
if ciRas.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output CI raster must be nominated as a raster dataset in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the output featureclass must be in a correct format
if outFeat.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output featureclass must be nominated as a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the temporary workspace must be in a correct format
if tempWS.rfind(".gdb") == -1:
messages.addErrorMessage(
"The temporary workspace must be nominated as a File GeoDatabase!"
)
raise arcpy.ExecuteError
workspaceName = bathyRas[0 : bathyRas.rfind("/")]
workspaceName1 = tpiRas[0 : tpiRas.rfind("/")]
workspaceName2 = ciRas[0 : ciRas.rfind("/")]
workspaceName3 = outFeat[0 : outFeat.rfind("/")]
areaThresholdValue = areaThreshold.split(" ")[0]
areaUnit = areaThreshold.split(" ")[1]
# waterproof some unusual errors
if (outFeat == tpiRas) or (outFeat == ciRas):
messages.addErrorMessage(
"The output CI and TPI rasters cannot have the same name as the output Featureclass in the same workspace!"
)
raise arcpy.ExecuteError
if (
(tempWS == workspaceName)
or (tempWS == workspaceName1)
or (tempWS == workspaceName2)
or (tempWS == workspaceName3)
):
messages.addErrorMessage(
"The temporary workspace must be different from the input/output workspace(s)."
)
raise arcpy.ExecuteError
if areaUnit == "Unknown":
messages.addErrorMessage("You cann't provide an unknown area unit.")
raise arcpy.ExecuteError
arcpy.env.workspace = workspaceName
arcpy.env.overwriteOutput = True
# call the helper function to calculate TPI and CI, and map Bathymetric Low features
helper.TPI_CI_Low(
tempWS,
bathyRas,
tpiRas,
ciRas,
outFeat,
areaThresholdValue,
areaUnit,
tpiRadius,
tpiSTDScale,
ciSTDScale,
tempFolder,
)
return
# helper functions are defined below
class helpers:
# This function converts comma decimal separator (e.g., European standard) to dot (e.g.,US, UK and Australian standard)
def convertDecimalSeparator(self, inText):
# inText: input string representing a decimal number
textList = inText.split(",")
inText1 = textList[0] + "." + textList[1]
return inText1
# 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
# This function calculate TPI values from a bathymetry grid
def calculateTPI(self, bathy, radius, tpiRas):
# bathy: input bathymetry grid
# radius: the input radius value of a circle window
# tpiRas: output TPI grid
time1 = datetime.now()
neighborhood = NbrCircle(radius, "CELL")
outFocal = FocalStatistics(bathy, neighborhood, "MEAN", "DATA")
# TPI equals to the difference between the value of the centre cell and the mean value of its neighbourhood
outMinus = Minus(bathy, outFocal)
outMinus.save(tpiRas)
arcpy.AddMessage("TPI is done")
time2 = datetime.now()
diff = time2 - time1
arcpy.AddMessage("took " + str(diff) + " to generate TPI.")
return
# This function selects part of the raster based on a threshold value
def selectRaster(self, inRas, outRas, threshold, sign, value=1):
# inRas: input raster
# outRas: output raster
# threshold: input threshold value used to select the inRas
# sign: sign as part of the selection condition
# value: the new raster value assigned to the part of the raster that satisfies the condition
if sign == ">=":
conDo = Con((Raster(inRas) >= threshold), value)
elif sign == "<=":
conDo = Con((Raster(inRas) <= threshold), value)
conDo.save(outRas)
# This function deletes all intermediate data items
def deleteDataItems(self, inDataList):
# inDataList: a list of data items to be deleted
if len(inDataList) == 0:
arcpy.AddMessage("no data item in the list")
else:
for item in inDataList:
arcpy.AddMessage("Deleting " + item)
arcpy.Delete_management(item)
return
# This function deletes all unnecessary fields from the input featureclass
def deleteFields(self, inFeat):
# inFeat: input featureclass
fields = arcpy.ListFields(inFeat)
fieldList = []
for field in fields:
if not field.required:
fieldList.append(field.name)
arcpy.DeleteField_management(inFeat, fieldList)
# This function calculates a converter value for the input area unit. The base unit is "SquareKilometers".
def areaUnitConverter(self, inAreaUnit):
# inAreaUnit: input Area Unit
if inAreaUnit == "Acres":
converter = 0.00404686
elif inAreaUnit == "Ares":
converter = 0.0001
elif inAreaUnit == "Hectares":
converter = 0.01
elif inAreaUnit == "SquareCentimeters":
converter = 0.0000000001
elif inAreaUnit == "SquareDecimeters":
converter = 0.00000001
elif inAreaUnit == "SquareMeters":
converter = 0.000001
elif inAreaUnit == "SquareFeet":
converter = 0.000000092903
elif inAreaUnit == "SquareInches":
converter = 0.00000000064516
elif inAreaUnit == "SquareKilometers":
converter = 1
elif inAreaUnit == "SquareMiles":
converter = 2.58999
elif inAreaUnit == "SquareMillimeters":
converter = 0.000000000001
elif inAreaUnit == "SquareYards":
converter = 0.00000083613
return converter
# This function calculates positive or negative openness value from the batymetry grid
def calculateOpenness(
self, bathyRas, radius, opennessParameter, outRas, tempWS, messages
):
# bathyRas: input bathymetry grid
# radius: radius value of the analysis window
# opennessParameter: determine whether to calculate positive or negative openness
# outRas: output openness grid
# tempWS: temporary workspace
# messages: to handle error messages
## most of the codes are taken from the "Openness" tool in the "ArcGeomorphometry Tools" python toolbox
## with the following modifications: 1) the analysis radius (window size) now accepts all positive integer values not limited to odd numbers only
## 2) the border areas are now processed properly instead of being left blank
## 3) modify some codes to work in later versions of python and numpy module
time1 = datetime.now()
radius = int(radius)
# the radius in the diagonal directions
radius1 = int(np.round(radius / np.sqrt(2)))
# Describe input raster
descData = arcpy.Describe(bathyRas)
dataPath = descData.path
cellSize = descData.meanCellHeight
extent = descData.Extent
height = descData.height
width = descData.width
xmin = extent.XMin
ymin = extent.YMin
spatialReference = descData.spatialReference
if spatialReference.type == "Geographic":
messages.addErrorMessage(
" *** Coordinate system of input bathymetry grid is Geographic. A projected coordinate system is required. ***"
)
raise arcpy.ExecuteError
pnt = arcpy.Point(xmin, ymin)
# Load DEM into numpy float32 array
rasterDEMArray = arcpy.RasterToNumPyArray(bathyRas)
# Check window size
if radius > rasterDEMArray.shape[-1]:
messages.addErrorMessage(" *** Analysis window is too long. ***")
raise arcpy.ExecuteError
# calculate elevation angles within roughly circular search window (clockwise from N=0º)
outShape = rasterDEMArray.shape
outArray = np.zeros(outShape, dtype=np.float32)
# the new array extends the loaded DEM array with a width of the radius from all four borders, so that the border areas of the loaded DEM can be processed properly
rasterDEMArray1 = np.arange(
(rasterDEMArray.shape[0] + 2 * radius)
* (rasterDEMArray.shape[1] + 2 * radius)
).reshape(
rasterDEMArray.shape[0] + 2 * radius, rasterDEMArray.shape[1] + 2 * radius
)
rasterDEMArray1 = np.zeros_like(rasterDEMArray1, dtype=float)
rasterDEMArray1[:] = np.nan
rasterDEMArray1[
radius : rasterDEMArray.shape[0] + radius,
radius : rasterDEMArray.shape[1] + radius,
] = rasterDEMArray
del rasterDEMArray # to release memory
# set temporal arrays
tempArray = np.zeros_like(outArray)
# arrayList holds the temporal arrays, so that we can calculate np.nanmean()
arrayList = []
shiftsList = [
(x, y)
for x in range(-radius, radius + 1)
for y in range(-radius, radius + 1)
]
# calculate elevation angles within roughly circular search window (clockwise from N=0º)
for direction in range(0, 360, 45):
if direction == 0:
shiftsListD = filter(lambda arr: arr[0] < 0 and arr[1] == 0, shiftsList)
elif direction == 45:
shiftsListD = filter(
lambda arr: arr[1] < radius1 + 1
and arr[0] == -arr[1]
and arr[1] > 0,
shiftsList,
)
elif direction == 90:
shiftsListD = filter(lambda arr: arr[0] == 0 and arr[1] > 0, shiftsList)
elif direction == 135:
shiftsListD = filter(
lambda arr: arr[1] < radius1 + 1
and arr[0] == arr[1]
and arr[0] > 0,
shiftsList,
)
elif direction == 180:
shiftsListD = filter(lambda arr: arr[0] > 0 and arr[1] == 0, shiftsList)
elif direction == 225:
shiftsListD = filter(
lambda arr: arr[0] < radius1 + 1
and arr[0] == -arr[1]
and arr[0] > 0,
shiftsList,
)
elif direction == 270:
shiftsListD = filter(lambda arr: arr[0] == 0 and arr[1] < 0, shiftsList)
elif direction == 315:
shiftsListD = filter(
lambda arr: -arr[1] < radius1 + 1
and arr[0] == arr[1]
and arr[0] < 0,
shiftsList,
)
if opennessParameter == "positiveOpenness": # calculate positive openness
tempArray.fill(-9999.9)
for dx, dy in shiftsListD:
xstop = -radius + dx or None
ystop = -radius + dy or None
angleArray = (
rasterDEMArray1[radius + dx : xstop, radius + dy : ystop]
- rasterDEMArray1[radius:-radius, radius:-radius]
) / (math.hypot(dx, dy) * cellSize)
angleArray[np.isnan(angleArray)] = -999999.9
tempArray = np.maximum(tempArray, angleArray)
tempArray = np.where(tempArray < -9999, np.nan, tempArray)
arrayList.append(90 - np.degrees(np.arctan(tempArray)))
elif opennessParameter == "negativeOpenness": # calculate negative openness
tempArray.fill(9999.9)
for dx, dy in shiftsListD:
xstop = -radius + dx or None
ystop = -radius + dy or None
angleArray = (
rasterDEMArray1[radius + dx : xstop, radius + dy : ystop]
- rasterDEMArray1[radius:-radius, radius:-radius]
) / (math.hypot(dx, dy) * cellSize)
angleArray[np.isnan(angleArray)] = -999999.9
tempArray = np.minimum(tempArray, angleArray)
tempArray = np.where(tempArray < -9999, np.nan, tempArray)
arrayList.append(90 + np.degrees(np.arctan(tempArray)))
del rasterDEMArray1
del tempArray
# np.stack() requires numpy version 1.10.0 or higher
stacked_array = np.stack(arrayList)
with warnings.catch_warnings():
# ignore runtime warning
warnings.simplefilter("ignore", category=RuntimeWarning)
outArray = np.nanmean(stacked_array, axis=0)
# Create new output calculated raster, set spatial coordinates and save
# if the raster is more than 5000 cells in either X or Y directions, split the raster into blocks
blocksize = 5000
if (width <= blocksize) and (height <= blocksize):
newRaster = arcpy.NumPyArrayToRaster(
outArray, pnt, cellSize, cellSize, -9999
)
if spatialReference.name != "Unknown":
arcpy.DefineProjection_management(newRaster, spatialReference)
# Set nodata where nodata in the input DEM
newRaster = SetNull(IsNull(bathyRas), newRaster)
newRaster.save(outRas)
del outArray
else:
itemList = []
xList = []
yList = []
for x in range(0, width, blocksize):
xList.append(x)
for y in range(0, height, blocksize):
yList.append(y)
xList.append(width)
yList.append(height)
i = 0
j = len(yList) - 1
k = 0
while i < len(xList) - 1:
while j > 0:
arr = outArray[yList[j - 1] : yList[j], xList[i] : xList[i + 1]]
hh = arr.shape[0]
ww = arr.shape[1]
pnt = arcpy.Point(xmin, ymin)
newRaster = arcpy.NumPyArrayToRaster(
arr, pnt, cellSize, cellSize, -9999
)
ras = tempWS + "/" + "tempRas" + str(k)
itemList.append(ras)
newRaster.save(ras)
if spatialReference.name != "Unknown":
arcpy.DefineProjection_management(ras, spatialReference)
ymin = ymin + hh * cellSize
j -= 1
k += 1
xmin = xmin + ww * cellSize
i += 1
j = len(yList) - 1
ymin = extent.YMin
del outArray