-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAccessory_Tools.pyt
4720 lines (4268 loc) · 188 KB
/
Accessory_Tools.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: July 1, 2022
#### Python version: 3+
#### ArcGIS Pro: 2.6.4 and above
from datetime import datetime
import arcpy
import numpy as np
import pandas as pd
from arcpy import env
from arcpy.sa import *
from pandas.core.common import flatten
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 = "AccessoryTools"
# List of tool classes associated with this toolbox
# There are two tools. Merge Connected Features Tool merges polygon features that are connected through shared points or borders.
# Connect Nearby Linear Features Tool connects nearby linear bathymetric low features.
self.tools = [
Update_Features_Tool,
Merge_Connected_Features_Tool,
Connect_Nearby_Linear_Features_Tool,
Connect_Nearby_Linear_HF_Features_Tool,
]
# This tool merges overlapped features and update the feature boundary
class Update_Features_Tool:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Update Feature Boundary Tool"
self.description = "Merge overlapped features and update the feature boundary"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Datasets",
name="in_feature_set",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input",
multiValue=True,
)
# fourth parameter
param1 = arcpy.Parameter(
displayName="Output Features After Updating the Feature Boundaries",
name="dissolvedFeat",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output",
)
parameters = [param0, param1]
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."""
in_feature_set = parameters[0].valueAsText
dissolvedFeat = parameters[1].valueAsText
inFeats = in_feature_set.split(";")
# enable the helper functions
helper = helpers()
dissolvedFeat = helper.convert_backslach_forwardslach(dissolvedFeat)
inputs = []
# loop through the input datasets and get their full path
for inFeat in inFeats:
# if the input feature class is selected from a drop-down list, the inFeat does not contain the full path
# In this case, the full path needs to be obtained from the map layer
if inFeat.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isFeatureLayer:
if inFeat == lyr.name:
inFeat = helper.convert_backslach_forwardslach(
lyr.dataSource
)
# check that the input feature class is in a correct format
vecDesc = arcpy.Describe(inFeat)
vecType = vecDesc.dataType
if (vecType != "FeatureClass") or (
inFeat.rfind(".gdb") == -1
):
messages.addErrorMessage(
"The input featureclass must be a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
else:
inputs.append(inFeat)
# check that the output featureclass is in a correct format
if dissolvedFeat.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output featureclass must be nominated as a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# merge the input datasets
mergedFeat = "mergedFeat"
arcpy.management.Merge(inputs, mergedFeat)
arcpy.AddMessage("merge done")
# add a temporary field
fieldName = "temp"
fieldType = "LONG"
fields = arcpy.ListFields(mergedFeat)
field_names = [f.name for f in fields]
# check the 'temp' field exists
# if not, add it
if fieldName not in field_names:
arcpy.management.AddField(mergedFeat, fieldName, fieldType)
expression = "1"
arcpy.management.CalculateField(mergedFeat, fieldName, expression)
# dissolve to obtain updated boundaries
arcpy.management.Dissolve(
mergedFeat, dissolvedFeat, fieldName, "", "SINGLE_PART"
)
arcpy.AddMessage("dissolve done")
# delete temporary field and dataset
arcpy.management.DeleteField(dissolvedFeat, fieldName)
arcpy.management.Delete(mergedFeat)
return
# This tool merges polygon features that are connected through shared points or borders.
class Merge_Connected_Features_Tool:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Merge Connected Features Tool"
self.description = (
"Merge/dissolve polygon features that are connected by shared points"
)
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Polygon Features",
name="inFeat",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input",
)
# fourth parameter
param1 = arcpy.Parameter(
displayName="Output Features After Merging Features Connected by Shared Points",
name="dissolveFeat2",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output",
)
parameters = [param0, param1]
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."""
inFeat = parameters[0].valueAsText
dissolveFeat2 = parameters[1].valueAsText
# enable the helper functions
helper = helpers()
inFeat = helper.convert_backslach_forwardslach(inFeat)
dissolveFeat2 = helper.convert_backslach_forwardslach(dissolveFeat2)
# if the input feature class is selected from a drop-down list, the inFeat does not contain the full path
# In this case, the full path needs to be obtained from the map layer
if inFeat.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isFeatureLayer:
if inFeat == lyr.name:
inFeat = helper.convert_backslach_forwardslach(lyr.dataSource)
# check that the input feature class is in a correct format
vecDesc = arcpy.Describe(inFeat)
vecType = vecDesc.dataType
if (vecType != "FeatureClass") or (inFeat.rfind(".gdb") == -1):
messages.addErrorMessage(
"The input featureclass must be a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the output featureclass is in a correct format
if dissolveFeat2.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output featureclass after merging only features connected by shared point must be nominated as a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
workspaceName = inFeat[0 : inFeat.rfind("/")]
env.workspace = workspaceName
env.overwriteOutput = True
helper.addIDField(inFeat, "featID")
# Generate near table between individual input poygon features
itemList = []
outTable = "nearTable"
itemList.append(outTable)
location = "NO_LOCATION"
angle = "NO_ANGLE"
closest = "ALL"
searchRadius = "100 Meters"
arcpy.GenerateNearTable_analysis(
inFeat,
inFeat,
outTable,
search_radius=searchRadius,
location=location,
angle=angle,
closest=closest,
)
cursor = arcpy.SearchCursor(outTable)
inIDList = []
nearIDList = []
# obtain idLists for connected features which have nearest distance = 0
# for each input feature, identify its nearest feature with near_dist = 0 (e.g., connected features),
# inIDList: list of ids of individual input features that have connected features
# nearIDList: this list contains the ids of their nearest features
for row in cursor:
inID = row.getValue("IN_FID")
nearID = row.getValue("NEAR_FID")
nearDist = row.getValue("NEAR_DIST")
if nearDist == 0:
inIDList.append(inID)
nearIDList.append(nearID)
del cursor, row
# obtain the number of features that are connected
size = np.unique(np.asarray(inIDList)).size
if (
size == 0
): # if no features are connected, simply copy the input featureclass to the outputs
arcpy.AddMessage("There are not connected features")
arcpy.Copy_management(inFeat, dissolveFeat2)
else: # if there are connected features, do the followings
arcpy.AddMessage(str(size) + " total features are connected")
# call the helper function to generate a new list of featID
# the connected features will be assigned the same featID
featIDNewList = helper.findNewFeatIDs(inFeat, inIDList, nearIDList)
# update the featID field with the new ids
cursor = arcpy.UpdateCursor(inFeat)
i = 0
for row in cursor:
featIDNew = featIDNewList[i]
row.setValue("featID", featIDNew)
cursor.updateRow(row)
i += 1
del cursor, row
dissolveFeat = "dissolveFeat"
itemList.append(dissolveFeat)
# dissolve all connected features that have same featIDs
arcpy.Dissolve_management(inFeat, dissolveFeat, "featID")
helper.calculateFeatID(dissolveFeat)
# after converting dissolved features (multipart) to single-part features, the features connected
# by shared point(s) will be un-dissolved
# multipart to single-part
singlepartFeat = "dissolve_singlepart"
itemList.append(singlepartFeat)
arcpy.MultipartToSinglepart_management(dissolveFeat, singlepartFeat)
# get the feature counts of the input features, the multipart dissolved features, and the single-part dissolved features
inFeatCount = int(arcpy.GetCount_management(inFeat).getOutput(0))
dissolveFeatCount = int(
arcpy.GetCount_management(dissolveFeat).getOutput(0)
)
singlepartFeatCount = int(
arcpy.GetCount_management(singlepartFeat).getOutput(0)
)
if (
inFeatCount == singlepartFeatCount
): # if all connected features are connected by shared points, copy the multipart dissolved features to outputs
arcpy.AddMessage(
"They are "
+ str(size)
+ " features having shared point(s). They have thus been connected."
)
arcpy.Copy_management(dissolveFeat, dissolveFeat2)
elif (
dissolveFeatCount == singlepartFeatCount
): # if all connected features are connected by shared borders, copy the input features to outputs
arcpy.AddMessage(
"They are "
+ str(size)
+ " features having shared border(s); They have thus not been connected."
)
arcpy.Copy_management(inFeat, dissolveFeat2)
else: # if some features are connected by shared points and others are connected by shared borders,
# 1. copy the single-part dissolved features as the output featureclass after merging features shared by borders
# 2. call the helper function get a count of features sharing borders and generate output featureclass after merging sharing points
dissolveFeat1 = "dissolveFeat1"
itemList.append(dissolveFeat1)
arcpy.Copy_management(singlepartFeat, dissolveFeat1)
count = helper.mergeFeatures(
inFeat, dissolveFeat, dissolveFeat1, dissolveFeat2
)
count1 = size - count
arcpy.AddMessage(
"They are "
+ str(count)
+ " features having shared border(s). They have thus not been connected."
)
arcpy.AddMessage(
"They are "
+ str(count1)
+ " features having shared point(s). They have thus been connected."
)
helper.calculateFeatID(dissolveFeat2)
helper.deleteDataItems(itemList)
return
# This tool connects nearby linear bathymetric high features, based on one of the three algorithms.
# The features to be connected satitify need to satisfy a number of conditions based on distance and orientation.
class Connect_Nearby_Linear_Features_Tool:
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Connect Nearby Linear Features Tool"
self.description = "Connect nearby linear bathymetric high or low features that are certain distance apart and align at a similar orientation"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
# first parameter
param0 = arcpy.Parameter(
displayName="Input Bathymetric High/Low Features",
name="inFeat",
datatype="GPFeatureLayer",
parameterType="Required",
direction="Input",
)
# second parameter
param1 = arcpy.Parameter(
displayName="Distance Threshold",
name="distThreshold",
datatype="GPLinearUnit",
parameterType="Required",
direction="Input",
)
# third parameter
param2 = arcpy.Parameter(
displayName="Angle Threshold",
name="angleThreshold",
datatype="GPDouble",
parameterType="Required",
direction="Input",
)
# 4th parameter
param3 = arcpy.Parameter(
displayName="Distance Weight",
name="distWeight",
datatype="GPDouble",
parameterType="Required",
direction="Input",
)
param3.value = 1
# 5th parameter
param4 = arcpy.Parameter(
displayName="Angle Weight",
name="angleWeight",
datatype="GPDouble",
parameterType="Required",
direction="Input",
)
param4.value = 1
# 6th parameter
param5 = arcpy.Parameter(
displayName="Connection Algorithm",
name="conOption",
datatype="GPString",
parameterType="Required",
direction="Input",
)
param5.filter.type = "ValueList"
param5.filter.list = [
"Mid points on Minimum Bounding Rectangle",
"Most distant points on feature",
"Mid points and Most distant points",
]
param5.value = "Mid points on Minimum Bounding Rectangle"
# 7th parameter
param6 = arcpy.Parameter(
displayName="Area Threshold",
name="areaThreshold",
datatype="GPArealUnit",
parameterType="Optional",
direction="Input",
)
param6.value = "0 SquareMeters"
# 8th parameter
param7 = arcpy.Parameter(
displayName="Length_to_Width Ratio Threshold",
name="lwRatioT",
datatype="GPDouble",
parameterType="Optional",
direction="Input",
)
param7.value = 0.9
# 9th parameter
param8 = arcpy.Parameter(
displayName="Output Connected Features",
name="dissolveFeat",
datatype="DEFeatureClass",
parameterType="Required",
direction="Output",
)
# 10th parameter, used to hold temporaray files
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."""
inFeat = parameters[0].valueAsText
distThreshold = parameters[1].valueAsText
angleThreshold = parameters[2].valueAsText
distWeight = parameters[3].valueAsText
angleWeight = parameters[4].valueAsText
conOption = parameters[5].valueAsText
areaThreshold = parameters[6].valueAsText
lwRatioT = parameters[7].valueAsText
dissolveFeat = parameters[8].valueAsText
tempFolder = parameters[9].valueAsText
# enable helper function
helper = helpers()
inFeat = helper.convert_backslach_forwardslach(inFeat)
dissolveFeat = helper.convert_backslach_forwardslach(dissolveFeat)
tempFolder = helper.convert_backslach_forwardslach(tempFolder)
# if the input feature class is selected from a drop-down list, the inFeat does not contain the full path
# In this case, the full path needs to be obtained from the map layer
if inFeat.rfind("/") < 0:
aprx = arcpy.mp.ArcGISProject("CURRENT")
m = aprx.activeMap
for lyr in m.listLayers():
if lyr.isFeatureLayer:
if inFeat == lyr.name:
inFeat = helper.convert_backslach_forwardslach(lyr.dataSource)
# check that the input feature class is in a correct format
vecDesc = arcpy.Describe(inFeat)
vecType = vecDesc.dataType
if (vecType != "FeatureClass") or (inFeat.rfind(".gdb") == -1):
messages.addErrorMessage(
"The input featureclass must be a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
# check that the output featureclass is in a correct format
if dissolveFeat.rfind(".gdb") == -1:
messages.addErrorMessage(
"The output connected featureclass must be nominated as a feature class in a File GeoDatabase!"
)
raise arcpy.ExecuteError
distanceT = distThreshold.split(" ")[0] # distance value
linearUnit = distThreshold.split(" ")[1] # distance unit
if linearUnit == "Unknown":
messages.addErrorMessage("You cann't provide an unknown distance unit.")
raise arcpy.ExecuteError
# check that the valid weights have been entered
distWeight = float(distWeight)
angleWeight = float(angleWeight)
if (distWeight + angleWeight) == 0:
messages.addErrorMessage(
"You cann't assign a weight of zero to both distance and anlge!"
)
raise arcpy.ExecuteError
areaThresholdValue = areaThreshold.split(" ")[0]
areaUnit = areaThreshold.split(" ")[1]
if areaUnit == "Unknown":
messages.addErrorMessage("You cann't provide an unknown area unit.")
raise arcpy.ExecuteError
workspaceName = inFeat[0 : inFeat.rfind("/")]
env.workspace = workspaceName
env.overwriteOutput = True
fields = arcpy.ListFields(inFeat)
field_names = [f.name for f in fields]
# check the 'featID' field exists
# if not, add and calculate it
if "featID" not in field_names:
arcpy.AddMessage("Adding an unique featID...")
helper.addIDField(inFeat, "featID")
itemList = []
# generate bounding rectangle
MbrFeat = "bounding_rectangle"
itemList.append(MbrFeat)
arcpy.MinimumBoundingGeometry_management(
inFeat, MbrFeat, "RECTANGLE_BY_WIDTH", "NONE", "", "MBG_FIELDS"
)
# add/calculate anlge field to inFeat
field = "rectangle_Orientation"
inID = "featID"
joinID = "featID"
expression = "!" + MbrFeat + "." + "MBG_Orientation" + "!"
helper.addField(inFeat, MbrFeat, field, inID, joinID, expression)
field = "rectangle_Length"
inID = "featID"
joinID = "featID"
expression = "!" + MbrFeat + "." + "MBG_Length" + "!"
helper.addField(inFeat, MbrFeat, field, inID, joinID, expression)
field = "rectangle_Width"
inID = "featID"
joinID = "featID"
expression = "!" + MbrFeat + "." + "MBG_Width" + "!"
helper.addField(inFeat, MbrFeat, field, inID, joinID, expression)
field = "Length_Width_Ratio"
inID = "featID"
joinID = "featID"
expression = (
"!"
+ MbrFeat
+ "."
+ "MBG_Length"
+ "! / !"
+ MbrFeat
+ "."
+ "MBG_Width"
+ "!"
)
helper.addField(inFeat, MbrFeat, field, inID, joinID, expression)
# select a subset of input features to connect, based on the area threshold and length to width ratio threshold
# this is to speed up the process when there are a large number of input features
inFeat_selected1 = inFeat + "_selected1"
itemList.append(inFeat_selected1)
converter = helper.areaUnitConverter(areaUnit)
areaThreshold = converter * float(areaThresholdValue)
whereClause = (
"(Length_Width_Ratio >= "
+ str(lwRatioT)
+ ") And (Shape_Area >= "
+ str(areaThreshold)
+ ")"
)
arcpy.AddMessage(whereClause)
arcpy.Select_analysis(inFeat, inFeat_selected1, whereClause)
# generate the bounding rectangles for those selected features
MbrFeat1 = "bounding_rectangle1"
itemList.append(MbrFeat1)
arcpy.MinimumBoundingGeometry_management(
inFeat_selected1, MbrFeat1, "RECTANGLE_BY_WIDTH", "NONE", "", "MBG_FIELDS"
)
inFeatCount = int(arcpy.GetCount_management(inFeat_selected1).getOutput(0))
arcpy.AddMessage(str(inFeatCount) + " features selected for connection")
# generate direction points depending on the selected algorithm
# Three algorithms
# The 'Mid points on Minimum Bounding Rectangle' algorithm identifies the direction points (e.g., N and S)
# as the middle points on the corresponding sides of the minimum bounding rectangle (e.g., N side and S side).
# The 'Most distance points on feature" algorithm identifies the direction points (e.g., N and S)
# as the intercepted locations between the feature and the corresponding sides of the minimum bounding rectangle (e.g., N side and S side).
# The 'Mid points and Most distant points' algorithm generate two set of direction points, one set using Mid points option, the other set using Most distant option
# convert rectangle sides to lines
MbrLines1 = "MbrLines1"
itemList.append(MbrLines1)
arcpy.SplitLine_management(MbrFeat1, MbrLines1)
arcpy.AddMessage("MbrLines1 done")
# add these attributes to the MbrLines1
geometryFields = [
["bearing", "LINE_BEARING"],
["MidX", "CENTROID_X"],
["MidY", "CENTROID_Y"],
]
arcpy.CalculateGeometryAttributes_management(MbrLines1, geometryFields)
# add a field for the purpose of subsequent selection
fieldName = "angle_temp"
fieldType = "LONG"
fieldPrecision = 15
arcpy.AddField_management(MbrLines1, fieldName, fieldType, fieldPrecision)
expression = "!bearing! - !rectangle_Orientation!"
arcpy.CalculateField_management(MbrLines1, fieldName, expression)
# select a subset of the lines: two lines from each bounding rectanlge (either N and S or E and W)
MbrLines1_selected = "MbrLines1_selected"
itemList.append(MbrLines1_selected)
whereClause = "((angle_temp <> 0) And (angle_temp <> 180))"
arcpy.Select_analysis(MbrLines1, MbrLines1_selected, whereClause)
arcpy.AddMessage("MbrLines1 selection done")
# identify and assign these lines with directional flags
fieldName = "direction"
fieldType = "text"
fieldLength = 10
arcpy.AddField_management(
MbrLines1_selected, fieldName, fieldType, field_length=fieldLength
)
expression = "getDirection(round(!rectangle_Orientation!,2),!angle_temp!)"
codeblock = """
def getDirection(angle1,angle2):
if(angle1 >= 0) & (angle1 <= 45) & (angle2 == 90):
return 'N'
if(angle1 >= 0) & (angle1 <= 45) & (angle2 == 270):
return 'S'
if(angle1 > 45) & (angle1 <= 90) & (angle2 == 90):
return 'E'
if(angle1 > 45) & (angle1 <= 90) & (angle2 == 270):
return 'W'
if(angle1 > 45) & (angle1 <= 90) & (angle2 == -90):
return 'W'
if(angle1 > 90) & (angle1 <= 135) & (angle2 == 90):
return 'E'
if(angle1 > 90) & (angle1 <= 135) & (angle2 == -90):
return 'W'
if(angle1 > 135) & (angle1 <= 180) & (angle2 == 90):
return 'S'
if(angle1 > 135) & (angle1 <= 180) & (angle2 == -90):
return 'N'"""
arcpy.CalculateField_management(
MbrLines1_selected, fieldName, expression, "PYTHON_9.3", codeblock
)
# add and calculate an "angle" field
fieldName = "angle"
fieldType = "DOUBLE"
filedPrecision = 15
fieldScale = 6
arcpy.AddField_management(
MbrLines1_selected, fieldName, fieldType, fieldPrecision, fieldScale
)
expression = "!rectangle_Orientation!"
arcpy.CalculateField_management(
MbrLines1_selected, fieldName, expression, "PYTHON_9.3"
)
pointFeat = "pointFeat"
itemList.append(pointFeat)
# generate directional points featureclass(es) according to the selected algorithm
if conOption == "Mid points on Minimum Bounding Rectangle":
# MidX and MidY fields already given the coordinate of the middle point
arcpy.XYTableToPoint_management(
MbrLines1_selected, pointFeat, "MidX", "MidY", "#", MbrLines1_selected
)
fieldsToKept = ["featID", "angle", "direction"]
fieldsToDelete = []
fields = arcpy.ListFields(pointFeat)
for field in fields:
if not field.required:
if not field.name in fieldsToKept:
fieldsToDelete.append(field.name)
arcpy.DeleteField_management(pointFeat, fieldsToDelete)
elif conOption == "Most distant points on feature":
helper.getDirectionPoints(
inFeat_selected1, MbrLines1_selected, tempFolder, pointFeat
)
elif (
conOption == "Mid points and Most distant points"
): # generate two set of direction points, one set using Mid points option, the other set using Most distant option
pointFeat1 = "pointFeat1"
itemList.append(pointFeat1)
arcpy.XYTableToPoint_management(
MbrLines1_selected, pointFeat, "MidX", "MidY", "#", MbrLines1_selected
)
fieldsToKept = ["featID", "angle", "direction"]
fieldsToDelete = []
fields = arcpy.ListFields(pointFeat)
for field in fields:
if not field.required:
if not field.name in fieldsToKept:
fieldsToDelete.append(field.name)
arcpy.DeleteField_management(pointFeat, fieldsToDelete)
helper.getDirectionPoints(
inFeat_selected1, MbrLines1_selected, tempFolder, pointFeat1
)
arcpy.AddMessage("direction points done at " + str(datetime.now()))
# separate points based on directions
pointFeatN = pointFeat + "_N"
pointFeatS = pointFeat + "_S"
pointFeatE = pointFeat + "_E"
pointFeatW = pointFeat + "_W"
itemList.append(pointFeatN)
itemList.append(pointFeatS)
itemList.append(pointFeatE)
itemList.append(pointFeatW)
whereClause = "direction = 'N'"
arcpy.Select_analysis(pointFeat, pointFeatN, whereClause)
whereClause = "direction = 'S'"
arcpy.Select_analysis(pointFeat, pointFeatS, whereClause)
whereClause = "direction = 'E'"
arcpy.Select_analysis(pointFeat, pointFeatE, whereClause)
whereClause = "direction = 'W'"
arcpy.Select_analysis(pointFeat, pointFeatW, whereClause)
# For this combined option, generate another set of direction point features
if conOption == "Mid points and Most distant points":
pointFeatN1 = pointFeat1 + "_N"
pointFeatS1 = pointFeat1 + "_S"
pointFeatE1 = pointFeat1 + "_E"
pointFeatW1 = pointFeat1 + "_W"
itemList.append(pointFeatN1)
itemList.append(pointFeatS1)
itemList.append(pointFeatE1)
itemList.append(pointFeatW1)
whereClause = "direction = 'N'"
arcpy.Select_analysis(pointFeat1, pointFeatN1, whereClause)
whereClause = "direction = 'S'"
arcpy.Select_analysis(pointFeat1, pointFeatS1, whereClause)
whereClause = "direction = 'E'"
arcpy.Select_analysis(pointFeat1, pointFeatE1, whereClause)
whereClause = "direction = 'W'"
arcpy.Select_analysis(pointFeat1, pointFeatW1, whereClause)
# generate links based on the direction points
# For the combined option, create four sets of links
# For the other two options, just need to create one set of links
if conOption == "Mid points and Most distant points":
linksFeatWE = "linkWE"
linksFeatSN = "linkSN"
linksFeatWN = "linkWN"
linksFeatSE = "linkSE"
linksFeatSW = "linkSW"
linksFeatEN = "linkEN"
itemList.append(linksFeatWE)
itemList.append(linksFeatSN)
itemList.append(linksFeatWN)
itemList.append(linksFeatSE)
itemList.append(linksFeatSW)
itemList.append(linksFeatEN)
# This ArcGIS function create links from each origin to each destination
# Note that the tool parameter 'distance threshold' is used in the search_distance parameter to limit the number of destination points from each origin point
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatW,
pointFeatE,
linksFeatWE,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS,
pointFeatN,
linksFeatSN,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatW,
pointFeatN,
linksFeatWN,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS,
pointFeatE,
linksFeatSE,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS,
pointFeatW,
linksFeatSW,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatE,
pointFeatN,
linksFeatEN,
search_distance=distanceT,
distance_unit=linearUnit,
)
helper.calculateFeatIDAngle(linksFeatWE, pointFeatW, pointFeatE)
helper.calculateFeatIDAngle(linksFeatSN, pointFeatS, pointFeatN)
helper.calculateFeatIDAngle(linksFeatWN, pointFeatW, pointFeatN)
helper.calculateFeatIDAngle(linksFeatSE, pointFeatS, pointFeatE)
helper.calculateFeatIDAngle(linksFeatSW, pointFeatS, pointFeatW)
helper.calculateFeatIDAngle(linksFeatEN, pointFeatE, pointFeatN)
linksFeatW1E1 = "linkW1E1"
linksFeatS1N1 = "linkS1N1"
linksFeatW1N1 = "linkW1N1"
linksFeatS1E1 = "linkS1E1"
linksFeatS1W1 = "linkS1W1"
linksFeatE1N1 = "linkE1N1"
itemList.append(linksFeatW1E1)
itemList.append(linksFeatS1N1)
itemList.append(linksFeatW1N1)
itemList.append(linksFeatS1E1)
itemList.append(linksFeatS1W1)
itemList.append(linksFeatE1N1)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatW1,
pointFeatE1,
linksFeatW1E1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS1,
pointFeatN1,
linksFeatS1N1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatW1,
pointFeatN1,
linksFeatW1N1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS1,
pointFeatE1,
linksFeatS1E1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS1,
pointFeatW1,
linksFeatS1W1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatE1,
pointFeatN1,
linksFeatE1N1,
search_distance=distanceT,
distance_unit=linearUnit,
)
helper.calculateFeatIDAngle(linksFeatW1E1, pointFeatW1, pointFeatE1)
helper.calculateFeatIDAngle(linksFeatS1N1, pointFeatS1, pointFeatN1)
helper.calculateFeatIDAngle(linksFeatW1N1, pointFeatW1, pointFeatN1)
helper.calculateFeatIDAngle(linksFeatS1E1, pointFeatS1, pointFeatE1)
helper.calculateFeatIDAngle(linksFeatS1W1, pointFeatS1, pointFeatW1)
helper.calculateFeatIDAngle(linksFeatE1N1, pointFeatE1, pointFeatN1)
linksFeatWE1 = "linkWE1"
linksFeatSN1 = "linkSN1"
linksFeatWN1 = "linkWN1"
linksFeatSE1 = "linkSE1"
linksFeatSW1 = "linkSW1"
linksFeatEN1 = "linkEN1"
itemList.append(linksFeatWE1)
itemList.append(linksFeatSN1)
itemList.append(linksFeatWN1)
itemList.append(linksFeatSE1)
itemList.append(linksFeatSW1)
itemList.append(linksFeatEN1)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatW,
pointFeatE1,
linksFeatWE1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS,
pointFeatN1,
linksFeatSN1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatW,
pointFeatN1,
linksFeatWN1,
search_distance=distanceT,
distance_unit=linearUnit,
)
arcpy.analysis.GenerateOriginDestinationLinks(
pointFeatS,