-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupplementary-contours.pyt
1611 lines (1244 loc) · 56.6 KB
/
supplementary-contours.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
# -*- coding: utf-8 -*-
# Automated generation of supplementary contours
# 2017-2019 Timofey Samsonov and Dmitry Walther, Lomonosov Moscow State University
#
# Naming convention: function arguments with underscore prefix (_) indicate arcpy Raster objects:
# width_raster - this is a string path to a raster (e.g. 'in_memory/raster' or 'D:/Folder/raster.tif')
# _width_raster - this is a Raster wrapper around the same object, possibly obtained by arcpy.Raster(width_raster)
import arcpy, numpy, os, sys
import math
from arcpy.sa import *
can_use_cpp = True
if sys.version_info[:2] == (2, 7): # ArcGIS for Desktop 10.3+, Python 2.7
try:
import WidthEstimator
except:
can_use_cpp = False
elif sys.version_info[:2] == (3, 6): # ArcGIS Pro, Python 3.6
try:
import WidthEstimator3 as WidthEstimator
except:
can_use_cpp = False
class Toolbox(object):
def __init__(self):
self.label = "Supplementary Contours"
self.alias = ""
# List of tool classes associated with this toolbox
self.tools = [Centrality, RegionWidth, RegionBorders,
WidthCentralityMask, SupplementaryContours, SupplementaryContoursFull]
class Centrality(object):
def __init__(self):
self.label = "Centrality"
self.description = "Calculate centrality raster"
self.canRunInBackground = True
def getParameterInfo(self):
in_lines = arcpy.Parameter(
displayName="Input lines",
name="in_lines",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input")
out_raster = arcpy.Parameter(
displayName="Output centrality raster",
name="out_raster",
datatype="DERasterDataset",
parameterType="Required",
direction="Output")
cell_size = arcpy.Parameter(
displayName="Output cell size",
name="cell_size",
datatype="GPDouble",
parameterType="Required",
direction="Input")
snap_raster = arcpy.Parameter(
displayName="Snap raster",
name="snap_raster",
datatype=["GPRasterLayer"],
parameterType="Optional",
direction="Input")
parameters = [in_lines, out_raster, cell_size, snap_raster]
return parameters
def isLicensed(self):
# try:
# if arcpy.CheckExtension("Spatial") != "Available":
# raise Exception
# except Exception:
# return False # tool cannot be executed
return True
def updateParameters(self, parameters):
return
def updateMessages(self, parameters):
return
def calculate_centrality(self, in_lines, out_raster, cell_size, _snap_raster):
def_snap_raster = arcpy.env.snapRaster
def_extent = arcpy.env.extent
if (_snap_raster is not None):
arcpy.env.snapRaster = _snap_raster
arcpy.env.extent = _snap_raster.extent
in_dist = EucDistance(in_lines, '', cell_size)
arcpy.env.snapRaster = in_dist
# compute geometric parameters
lleft = arcpy.Point(in_dist.extent.XMin, in_dist.extent.YMin)
crs = in_dist.spatialReference
id_field = arcpy.ListFields(in_lines)[0].name
# TODO: check whether using the first field is reliable
alloc = EucAllocation(in_lines, cell_size=cell_size, source_field=id_field)
alloc_regions = "in_memory/alloc_regions"
arcpy.RasterToPolygon_conversion(alloc, alloc_regions)
alloc_lines = "in_memory/alloc_lines"
arcpy.PolygonToLine_management(alloc_regions, alloc_lines)
alloc_lines_lyr = "alloc_lines_lyr"
arcpy.MakeFeatureLayer_management(alloc_lines, alloc_lines_lyr, '"LEFT_FID" <> -1')
in_lines_r = "in_memory/in_lines_r"
arcpy.PolylineToRaster_conversion(in_lines,
id_field,
in_lines_r,
cellsize=cell_size)
in_lines_0 = Con(IsNull(in_lines_r), -1, in_lines_r)
max = arcpy.GetRasterProperties_management(in_lines_r, "MAXIMUM")
cost = Reclassify(in_lines_0,
reclass_field="Value",
remap=RemapRange([[-1, -1, 1],
[0, max, "NODATA"]]))
centr_dist = CostDistance(alloc_lines_lyr, cost)
centr_null = in_dist / (in_dist + centr_dist)
output = CreateConstantRaster(0, "Float", cell_size, centr_null)
# TODO: put mosaic directly into the folder
arcpy.Mosaic_management(centr_null, output, "MAXIMUM")
arcpy.CopyRaster_management(output, out_raster)
arcpy.env.snapRaster = def_snap_raster
arcpy.env.extent = def_extent
def execute(self, parameters, messages):
in_lines = parameters[0].valueAsText
out_raster = parameters[1].valueAsText
cell_size = float(parameters[2].valueAsText.replace(",","."))
snap_raster = parameters[3].valueAsText
self.calculate_centrality(in_lines, out_raster, cell_size, arcpy.Raster(snap_raster))
# TODO: overlay width inside closed empty supplementary contours
class RegionWidth(object):
def __init__(self):
self.label = "Region width"
self.description = "Calculate raster of region width"
self.canRunInBackground = True
def getParameterInfo(self):
in_features = arcpy.Parameter(
displayName="Input features",
name="in_features",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input")
out_raster = arcpy.Parameter(
displayName="Output region width raster",
name="out_raster",
datatype="DERasterDataset",
parameterType="Required",
direction="Output")
cell_size = arcpy.Parameter(
displayName="Output cell size",
name="cell_size",
datatype="GPDouble",
parameterType="Required",
direction="Input")
snap_raster = arcpy.Parameter(
displayName="Snap raster",
name="snap_raster",
datatype=["GPRasterLayer"],
parameterType="Optional",
direction="Input")
interest = arcpy.Parameter(
displayName="Regions of interest",
name="interest",
datatype="GPString",
parameterType="Required",
direction="Input")
interest.value = 'ALL'
interest.filter.list = ['ALL', 'INSIDE POLYGONS', 'OUTSIDE POLYGONS']
mode = arcpy.Parameter(
displayName="Computation mode",
name="mode",
datatype="GPString",
parameterType="Required",
direction="Input")
mode.filter.list = ['CPP', 'PYTHON']
if (can_use_cpp):
mode.value = 'CPP'
else:
mode.value = 'PYTHON'
mode.enabled = False
parameters = [in_features, out_raster, cell_size, snap_raster, interest, mode]
return parameters
def isLicensed(self):
# try:
# if arcpy.CheckExtension("Spatial") != "Available":
# raise Exception
# except Exception:
# return False # tool cannot be executed
return True
def updateParameters(self, parameters):
return
def updateMessages(self, parameters):
return
# this function performs at least 10 times faster than the one below
def calculate_width_circles_cpp(self, npdist, cell_size, nodata = -1):
nrow = npdist.shape[0]
ncol = npdist.shape[1]
npwid = numpy.full((nrow, ncol), 0)
return WidthEstimator.estimate_width(npdist, npwid, cell_size, nodata)
def calculate_width_circles(self, npdist, cell_size, nodata = -1):
N = npdist.shape[0] # row number
M = npdist.shape[1] # column number
output = numpy.full((N, M), 0)
for i in range(N):
for j in range(M):
radius = npdist[i, j]
if (radius == nodata):
continue
w = int(math.ceil(radius/cell_size)) # calculate kernel radius (rounded)
k = range(-w, w+1) # calculate kernel indices
idx = numpy.meshgrid(k, k) # generate coordinate matrices
flt = (idx[0]**2 + idx[1]**2 <= w**2) # filter by distance
x = idx[0][flt] + i
y = idx[1][flt] + j
flt_xy = (x >= 0) * (x < N) * (y >= 0) * (y < M) # filter by domain
x = x[flt_xy]
y = y[flt_xy]
flt_distance = output[x, y] < radius*2 # filter by values
x = x[flt_distance]
y = y[flt_distance]
output[x, y] = radius * 2
return output
def call(self, in_features, out_raster, cell_size, _snap_raster, interest, mode):
obstacles = "in_memory/obstacles"
frame = "in_memory/frame"
arcpy.MinimumBoundingGeometry_management(in_features, frame, "ENVELOPE", "ALL")
buffers = 'in_memory/buffers'
desc = arcpy.Describe(in_features)
if desc.shapeType == 'Polygon':
arcpy.PolygonToLine_management(in_features, obstacles)
if interest == 'INSIDE POLYGONS':
arcpy.Buffer_analysis(in_features, buffers, cell_size)
arcpy.env.mask = buffers
elif interest == 'OUTSIDE POLYGONS':
arcpy.Buffer_analysis(in_features, buffers, -cell_size)
inv_buffers = 'in_memory/inv_buffers'
arcpy.Erase_analysis(frame, buffers, inv_buffers)
arcpy.env.mask = inv_buffers
elif desc.shapeType == 'Polyline':
arcpy.CopyFeatures_management(in_features, obstacles)
elif desc.shapeType == 'Point':
arcpy.Buffer_analysis(in_features, buffers, 0.5 * cell_size)
arcpy.PolygonToLine_management(buffers, obstacles)
else:
return
if interest != 'INSIDE_POLYGONS':
frame_lines = "in_memory/lines"
arcpy.PolygonToLine_management(frame, frame_lines)
arcpy.Append_management(frame_lines, obstacles, schema_type='NO_TEST')
# calculate distance raster
def_snap_raster = arcpy.env.snapRaster
def_extent = arcpy.env.extent
if (_snap_raster is not None):
arcpy.env.snapRaster = _snap_raster
arcpy.env.extent = _snap_raster.extent
dist = EucDistance(obstacles, '', cell_size)
npdist = arcpy.RasterToNumPyArray(dist, nodata_to_value=-1)
# execute width calculation
width = self.calculate_width_circles_cpp(npdist, cell_size, -1) if mode == 'CPP' \
else self.calculate_width_circles(npdist, cell_size, -1)
# convert to georeferenced raster
lleft = arcpy.Point(dist.extent.XMin, dist.extent.YMin)
out = arcpy.NumPyArrayToRaster(width, lleft, cell_size, cell_size, -1)
arcpy.DefineProjection_management(out, dist.spatialReference)
if interest == 'INSIDE POLYGONS':
ExtractByMask(out, in_features).save(out_raster)
elif interest == 'OUTSIDE POLYGONS':
inv_features = 'in_memory/inv_features'
arcpy.Erase_analysis(frame, in_features, inv_features)
ExtractByMask(out, inv_features).save(out_raster)
else:
out.save(out_raster)
arcpy.env.snapRaster = def_snap_raster
arcpy.env.extent = def_extent
def execute(self, parameters, messages):
in_features = parameters[0].valueAsText
out_raster = parameters[1].valueAsText
cell_size = float(parameters[2].valueAsText.replace(",","."))
snap_raster = parameters[3].valueAsText
interest = parameters[4].valueAsText
mode = parameters[5].valueAsText
self.call(in_features, out_raster, cell_size, snap_raster, interest, mode)
class RegionBorders(object):
def __init__(self):
self.label = "Region borders"
self.description = "Generate region borders"
self.canRunInBackground = True
def getParameterInfo(self):
in_raster = arcpy.Parameter(
displayName="Input elevation raster",
name="in_raster",
datatype=["GPRasterLayer"],
parameterType="Required",
direction="Input")
out_features = arcpy.Parameter(
displayName="Output region borders feature class",
name="out_features",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output")
contour_interval=arcpy.Parameter(
displayName="Contour interval",
name="contour_interval",
datatype="GPDouble",
parameterType="Required",
direction="Input")
base_contour=arcpy.Parameter(
displayName="Base contour level",
name="base_contour",
datatype="GPDouble",
parameterType="Required",
direction="Input")
base_contour.value = 0.0
parameters = [in_raster, out_features, contour_interval, base_contour]
return parameters
def isLicensed(self):
# try:
# if arcpy.CheckExtension("Spatial") != "Available":
# raise Exception
# except Exception:
# return False # tool cannot be executed
return True
def updateParameters(self, parameters):
return
def updateMessages(self, parameters):
return
def execute(self, parameters, messages):
in_raster = parameters[0].valueAsText
out_features = parameters[1].valueAsText
contour_interval = float(parameters[2].valueAsText.replace(",","."))
base_contour = float(parameters[3].valueAsText.replace(",","."))
main_contours = "in_memory/main_contours"
Contour(in_raster, main_contours, contour_interval, base_contour, 1)
# Add fields
arcpy.AddField_management(main_contours, "Type", "TEXT", field_length=13)
arcpy.CalculateField_management(main_contours, "Type", "'Regular'", "PYTHON", "")
addbaselevel = contour_interval / 2
addcontours = "in_memory/additional_contours"
Contour(in_raster, addcontours, contour_interval, addbaselevel, 1)
# Add fields
arcpy.AddField_management(addcontours, "Type", "TEXT", field_length=13)
arcpy.CalculateField_management(addcontours, "Type", "'Supplementary'", "PYTHON", "")
addclosed = "in_memory/addclosed"
arcpy.FeatureToPolygon_management(addcontours, addclosed, "", "ATTRIBUTES", "")
addclosedlayer = "addclosedlayer"
arcpy.MakeFeatureLayer_management(addclosed, addclosedlayer)
arcpy.SelectLayerByLocation_management(addclosedlayer, 'CONTAINS', main_contours,
"#", "NEW_SELECTION", "INVERT")
arcpy.SelectLayerByLocation_management(addclosedlayer, 'COMPLETELY_CONTAINS', addcontours,
"#", "SUBSET_SELECTION", "INVERT")
seladdclosed = "in_memory/selclosed"
arcpy.CopyFeatures_management(addclosedlayer, seladdclosed)
addlayer = "addlayer"
arcpy.MakeFeatureLayer_management(addcontours, addlayer)
arcpy.SelectLayerByLocation_management(addlayer,
'SHARE_A_LINE_SEGMENT_WITH',
seladdclosed)
# generate obstacles
frame = "in_memory/frame"
arcpy.MinimumBoundingGeometry_management(main_contours, frame, "ENVELOPE", "ALL")
arcpy.PolygonToLine_management(frame, out_features)
# Add fields
arcpy.AddField_management(out_features, "Type", "TEXT", field_length=13)
arcpy.CalculateField_management(out_features, "Type", "'Boundary'", "PYTHON", "")
arcpy.Append_management([main_contours, addlayer], out_features, schema_type='NO_TEST')
class WidthCentralityMask(object):
def __init__(self):
self.label = "Width-centrality mask"
self.description = "Generate width-centrality mask"
self.canRunInBackground = True
def getParameterInfo(self):
in_width_raster = arcpy.Parameter(
displayName="Input region width raster",
name="in_width_raster",
datatype=["GPRasterLayer"],
parameterType="Required",
direction="Input")
in_centrality_raster = arcpy.Parameter(
displayName="Input centrality raster",
name="in_centrality_raster",
datatype=["GPRasterLayer"],
parameterType="Required",
direction="Input")
out_raster = arcpy.Parameter(
displayName="Output width-centrality mask raster",
name="out_raster",
datatype="DERasterDataset",
parameterType="Required",
direction="Output")
width_min = arcpy.Parameter(
displayName="Region width (minimal)",
name="width_min",
datatype="GPDouble",
parameterType="Required",
direction="Input")
width_min.value = 0.25
width = arcpy.Parameter(
displayName="Region width (optimal)",
name="width",
datatype="GPDouble",
parameterType="Required",
direction="Input")
width.value = 0.5
width_max = arcpy.Parameter(
displayName="Region width (maximal)",
name="width_max",
datatype="GPDouble",
parameterType="Required",
direction="Input")
width_max.value = 0.75
centrality_min = arcpy.Parameter(
displayName="Centrality (minimal)",
name="centrality_min",
datatype="GPDouble",
parameterType="Required",
direction="Input")
centrality_min.value = 0.4
centrality = arcpy.Parameter(
displayName="Centrality (optimal)",
name="centrality",
datatype="GPDouble",
parameterType="Required",
direction="Input")
centrality.value = 0.8
absolute = arcpy.Parameter(
displayName="Set width parameters in projection units (absolute values)",
name="absolute",
datatype="GPBoolean",
parameterType="Required",
direction="Input")
absolute.value = 'false'
parameters = [in_width_raster, in_centrality_raster, out_raster,
width_min, width, width_max, centrality_min, centrality, absolute]
return parameters
def isLicensed(self):
# try:
# if arcpy.CheckExtension("Spatial") != "Available":
# raise Exception
# except Exception:
# return False # tool cannot be executed
return True
def updateParameters(self, parameters):
return
def updateMessages(self, parameters):
return
def calculate_mask(self, npwidth, npcentr, wmin, wopt, wmax, cmin, copt):
N = npwidth.shape[0] # row number
M = npwidth.shape[1] # column number
output = numpy.zeros((N, M))
k1 = (copt - cmin) / (wopt - wmin)
b1 = cmin - wmin * k1
k2 = (1 - copt) / (wmax - wopt)
b2 = copt - wopt * k2
for i in range(N):
for j in range(M):
w = npwidth[i, j]
c = npcentr[i, j]
flag = 1
if w < wmin:
flag = 1
elif w < wopt:
flag = 2 if c <= w * k1 + b1 else 1
elif w < wmax:
flag = 3 if c <= w * k2 + b2 else 1
else:
flag = 4
output[i, j] = flag
return output
def execute(self, parameters, messages):
in_width_raster = parameters[0].valueAsText
in_centrality_raster = parameters[1].valueAsText
out_raster = parameters[2].valueAsText
rwmin = float(parameters[3].valueAsText.replace(",", "."))
rwopt = float(parameters[4].valueAsText.replace(",","."))
rwmax = float(parameters[5].valueAsText.replace(",","."))
cmin = float(parameters[6].valueAsText.replace(",","."))
copt = float(parameters[7].valueAsText.replace(",","."))
absolute = parameters[8].valueAsText
width = arcpy.Raster(in_width_raster)
centr = arcpy.Raster(in_centrality_raster)
npwidth = arcpy.RasterToNumPyArray(width)
npcentr = arcpy.RasterToNumPyArray(centr)
wmax = 1
if absolute == 'false':
wmax = numpy.amax(npwidth)
arcpy.AddMessage('NORMALIZING THREHOLDS ON\n-- max(W) = ' + str(wmax))
wopt = rwopt * wmax
wmin = rwmin * wmax
wmax = rwmax * wmax
npmask = self.calculate_mask(npwidth, npcentr, wmin, wopt, wmax, cmin, copt)
lleft = arcpy.Point(width.extent.XMin, width.extent.YMin)
cell_size = width.meanCellWidth
arcpy.env.snapRaster = width
arcpy.env.extent = width.extent
out = arcpy.NumPyArrayToRaster(npmask, lleft, cell_size)
arcpy.DefineProjection_management(out, width.spatialReference)
out.save(out_raster)
class SupplementaryContours(object):
def __init__(self):
self.label = "Supplementary contours"
self.description = "Generate regular, index and supplementary contours from elevation, region width and centrality rasters."
self.canRunInBackground = True
self.params = arcpy.GetParameterInfo()
def getParameterInfo(self):
in_raster = arcpy.Parameter(
displayName="Input elevation raster",
name="in_raster",
datatype=["GPRasterLayer"],
parameterType="Required",
direction="Input")
in_width_raster = arcpy.Parameter(
displayName="Input region width raster",
name="in_width_raster",
datatype=["GPRasterLayer"],
parameterType="Required",
direction="Input")
in_centrality_raster = arcpy.Parameter(
displayName="Input centrality raster",
name="in_centrality_raster",
datatype=["GPRasterLayer"],
parameterType="Required",
direction="Input")
out_features = arcpy.Parameter(
displayName="Output contours feature class",
name="out_features",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output")
contour_interval=arcpy.Parameter(
displayName="Contour interval",
name="contour_interval",
datatype="GPDouble",
parameterType="Required",
direction="Input")
base_contour=arcpy.Parameter(
displayName="Base contour level",
name="base_contour",
datatype="GPDouble",
parameterType="Required",
direction="Input")
base_contour.value = 0.0
index_contour = arcpy.Parameter(
displayName="Index contour label (each)",
name="index_contour",
datatype="GPLong",
parameterType="Required",
direction="Input")
index_contour.value = 5
index_contour.filter.type = "Range"
index_contour.filter.list = [2, 10]
closed_width_avg = arcpy.Parameter(
displayName="Closed contour width (average)",
name="closed_width_avg",
datatype="GPDouble",
parameterType="Required",
direction="Input")
closed_width_avg.value = 0.125
width_min = arcpy.Parameter(
displayName="Region width (minimal)",
name="width_min",
datatype="GPDouble",
parameterType="Required",
direction="Input")
width_min.value = 0.25
width=arcpy.Parameter(
displayName="Region width (optimal)",
name="width",
datatype="GPDouble",
parameterType="Required",
direction="Input")
width.value = 0.5
width_max = arcpy.Parameter(
displayName="Region width (maximal)",
name="width_max",
datatype="GPDouble",
parameterType="Required",
direction="Input")
width_max.value = 0.75
centrality_min = arcpy.Parameter(
displayName="Centrality (minimal)",
name="centrality_min",
datatype="GPDouble",
parameterType="Required",
direction="Input")
centrality_min.value = 0.4
centrality=arcpy.Parameter(
displayName="Centrality (optimal)",
name="centrality",
datatype="GPDouble",
parameterType="Required",
direction="Input")
centrality.value = 0.8
centrality_ext = arcpy.Parameter(
displayName="Centrality (extension)",
name="centrality_ext",
datatype="GPDouble",
parameterType="Required",
direction="Input")
centrality_ext.value = 0.8
min_gap=arcpy.Parameter(
displayName="Gap length (maximal)",
name="min_gap",
datatype="GPDouble",
parameterType="Required",
direction="Input")
min_gap.value = 1.0
min_len=arcpy.Parameter(
displayName="Segment length (minimal)",
name="min_len",
datatype="GPDouble",
parameterType="Required",
direction="Input")
min_len.value = 1.0
ext_len = arcpy.Parameter(
displayName="Extension length",
name="ext_len",
datatype="GPDouble",
parameterType="Required",
direction="Input")
ext_len.value = 1.0
extend = arcpy.Parameter(
displayName="Extend to defined centrality",
name="extend",
datatype="GPBoolean",
parameterType="Required",
direction="Input")
extend.value = 'true'
absolute = arcpy.Parameter(
displayName="Set width and length parameters in projection units (absolute values)",
name="absolute",
datatype="GPBoolean",
parameterType="Required",
direction="Input")
absolute.value = 'false'
mode = arcpy.Parameter(
displayName="Region width computation mode",
name="mode",
datatype="GPString",
parameterType="Required",
direction="Input")
mode.filter.list = ['CPP', 'PYTHON']
if (can_use_cpp):
mode.value = 'CPP'
else:
mode.value = 'PYTHON'
mode.enabled = False
parameters = [in_raster, in_width_raster, in_centrality_raster, out_features,
contour_interval, base_contour, index_contour,
closed_width_avg, width_min, width, width_max,
centrality_min, centrality, centrality_ext,
min_gap, min_len, ext_len, extend, absolute, mode]
return parameters
def isLicensed(self):
# try:
# if arcpy.CheckExtension("Spatial") != "Available":
# raise Exception
# except Exception:
# return False # tool cannot be executed
return True
def updateParameters(self, parameters):
return
def updateMessages(self, parameters):
return
def calculate_length(self, list1, flaglist):
list2 = []
n = 1
s = 0
idx = range(len(flaglist) - 1)
for i in idx:
if flaglist[i] == flaglist[i + 1]:
n = n + 1
s = s + list1[i + 1]
else:
s = s + list1[i + 1] * 0.5
while n > 0:
list2.append(s)
n = n - 1
s = list1[i + 1] * 0.5
n = 1
while n > 0:
list2.append(s)
n = n - 1
return list2
def extend_segments(self, list1, flaglist, ext_len, coordinateslist, lowerLeft, cell_size,
npcentr, npwidth, width_min, centrality_ext):
N = len(coordinateslist)
ni = npwidth.shape[0]
i1 = 0
i2 = 0
while i2 < N - 1:
if flaglist[i2] == flaglist[i2 + 1]:
i2 += 1
elif flaglist[i2] == 1:
d = 0
i0 = i1 - 1
imax = i0
cmax = 0
while d <= ext_len:
ci = ni - int((coordinateslist[i0][1] - lowerLeft.Y) / cell_size) - 1
cj = int((coordinateslist[i0][0] - lowerLeft.X) / cell_size)
c = npcentr[ci, cj]
w = npwidth[ci, cj]
if w <= width_min or i0 == 0:
cmax = 1
imax = i0
break
else:
# find the highest centrality in length
if c >= centrality_ext and c > cmax:
imax = i0
cmax = c
i0 -= 1
d += list1[i0]
if cmax > 0:
while imax < i1:
flaglist[imax] = 1
imax += 1
d = 0
i3 = i2 + 1
imax = i0
cmax = 0
while d <= ext_len:
ci = ni - int((coordinateslist[i3][1] - lowerLeft.Y) / cell_size) - 1
cj = int((coordinateslist[i3][0] - lowerLeft.X) / cell_size)
c = npcentr[ci, cj]
w = npwidth[ci, cj]
if w <= width_min or i3 == N - 1:
cmax = 1
imax = i3
break
else:
# find the highest centrality in length
if c >= centrality_ext and c > cmax:
imax = i3
cmax = c
i3 += 1
d += list1[i3]
if cmax > 0:
while imax > i2:
flaglist[imax] = 1
imax -= 1
i2 = i3
i2 += 1
i1 = i2
else:
i2 += 1
i1 = i2
return flaglist
# TODO: do not filter or extend, if parameters are set to 1 or 0
# TODO: prohibit filling of the terminal gaps in non-closed contours (?)
def filter_vertices(self, addlayer, _widthRaster, _centrRaster, width, width_min, width_max,
closed_width_avg, min_gap, min_len, ext_len, centrality, centrality_min, centrality_ext, extend):
cell_size = _widthRaster.meanCellWidth
lowerLeft = arcpy.Point(_widthRaster.extent.XMin, _widthRaster.extent.YMin)
crs = _widthRaster.spatialReference # TODO: remove?
npwidth = arcpy.RasterToNumPyArray(_widthRaster)
npcentr = arcpy.RasterToNumPyArray(_centrRaster)
k1 = (centrality - centrality_min) / (width - width_min)
b1 = centrality_min - width_min * k1
k2 = (1 - centrality) / (width_max - width)
b2 = centrality - width * k2
cursor = arcpy.da.SearchCursor(addlayer, ['SHAPE@', 'Id', 'Contour'])
fc_list = [] # Feature coordinates list
ff_list = [] # Feature flag list
fi_list = [] # Feature id list
fh_list = [] # Feature height list
ni = npwidth.shape[0]
# filter by width and centrality
for row in cursor:
if row[0] != None:
for part in row[0].getPart():
flaglist = []
coordinateslist = []
for pnt in part:
coordinateslist.append([pnt.X, pnt.Y])
# Nearest neighbor interpolation
i = ni - int((pnt.Y - lowerLeft.Y) / cell_size) - 1
j = int((pnt.X - lowerLeft.X) / cell_size)
w = npwidth[i, j]
c = npcentr[i, j]
flag = 0
if w < width_min:
flag = 0
elif w < width: