-
Notifications
You must be signed in to change notification settings - Fork 3
/
SSURGO_shoehorn_v2_9_3.py
1102 lines (998 loc) · 49.3 KB
/
SSURGO_shoehorn_v2_9_3.py
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 -*-
"""
# Respond to Null geometries in input
# Removed PringMsg function
# identify and highlight incongruencies in MUPOLYGON to SAPOLYGON
# 2.9
1) modified Douglas-Peucker functions rdpi and rdps to deal with vertex rich
single arc loops
2) In Tweezer, modified so 3-vertex arcs can be generalized
# 2.8c
1) Updated handling of edit tracking fields
2) Added snapping of boundary nodes to survery boundaries VERTEX and EDGE for sparse areas
# 2.9.1
1) removed arc.env arguments from the BCore function, seems that causes error
calling those in parallel environments.
# 2.9.2
1) Warning message from BCore function if error in BNodes2
2) In BNodes function added search distance = to Boundary Tolerance parameter
to select polygons that are shy of the boundary due to imperfect fit
3) Changed how arcpy Arrays are packaged in ShapeUp, it wasn't pulling out
inner rings in Pro 2.9 and its faster to feed straight list comprehnesions
to arcpy.Array instead of other arrays.
# 2.9.3
1) Added main function
"""
# import modules
import arcpy
import sys
import os
import xlwt
import math
import time
import warnings # psutil
import multiprocessing as mp
import numpy as np
import Shoehorn_multi2_9_3
import importlib
importlib.reload(Shoehorn_multi2_9_3)
from Shoehorn_multi2_9_3 import *
warnings.filterwarnings("ignore")
#%% Functions
def get_install_path():
"""
Return 64bit python install path from registry (if installed and registered),
otherwise fall back to current 32bit process install path.
"""
if sys.maxsize > 2**32:
return sys.exec_prefix # We're running in a 64bit process
# We're 32 bit so see if there's a 64bit install
path = r'SOFTWARE\Python\PythonCore\2.7'
from winreg import OpenKey, QueryValue
from winreg import HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY
try:
with OpenKey(HKEY_LOCAL_MACHINE, path, 0, KEY_READ | KEY_WOW64_64KEY) as key:
# We have a 64bit install, so return that.
return QueryValue(key, "InstallPath").strip(os.sep)
except:
return sys.exec_prefix # No 64bit, so return 32bit path
# https://www.e-education.psu.edu/geog489/node/2263
def rdpi(M, epsilon=0, hopper={}):
"""Helper function for rdps function, implementing Douglas-Peucker Method."""
try:
if not hopper:
hopper = {0: M.shape[0] - 1}
dump = np.ones(M.shape[0], np.bool)
while hopper:
i, f = hopper.popitem()
start, end = M[(i, f),]
vec = end - start
dists = np.absolute(np.cross(vec, start - M[i:f + 1,])) / np.linalg.norm(vec)
imax = np.argmax(dists)
dmax = dists[imax]
imax += i
if dmax > epsilon:
if imax - i > 1:
hopper[i] = imax
if f - imax > 1:
hopper[imax] = f
else:
dump[i + 1:f,] = False
return dump
except:
arcpy.AddError(f"{M}")
arcpy.AddError(f"initial {i} and final {f}")
arcpy.AddError(f"start {start} and end {end}")
raise
def rdps(M, E=1):
"""Implementation of the Douglas-Peuker Methodology."""
try:
close = np.ones(M.shape[0], np.bool)
# offset by 2
v = M[2:,] - M[:-2,]
dist = np.abs(np.cross(v, M[:-2,] - M[1:-1])) / np.linalg.norm(v, axis=1)
close[1:-1] = dist >= E
inrow = ~(close[1:] | close[:-1])
if inrow.any():
contigI = np.ones(M.shape[0], np.bool)
contigI[1:-1] = inrow[:-1] | inrow[1:] # is there a neighbor?
contig = np.where(contigI[1:-1])[0] + 1
# realm of contiguous occurences
neigh = set(range(contig[0] - 1, contig[-1] + 2))
inter = neigh - set(contig)
iS = [j for j in inter if j + 1 in contig]
fS = [i + 1 for i in contig if i + 1 in inter]
if (len(fS) < 2) and (fS[0] > dist.size): # if enclosed
far = np.argmax(dist) +1
iS.append(far)
fS.append(far)
iS.sort()
fS.sort()
dump = rdpi(M, E, dict(zip(iS, fS)))
close[contigI] = dump[contigI]
return M[close,]
except:
arcpy.AddError(f"{dict(zip(iS,fS))}")
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
raise
def BNodes(SA_, MU, nodes, dec):
try:
# ======= Variables ==========
MU_ = "in_memory/MU_outline"
MU_o = "MU_outer"
MU_d = "in_memory/MU_d"
Point = arcpy.Point
PG = arcpy.PointGeometry
arcpy.management.SelectLayerByLocation(MU,
"INTERSECT",
SA_)
# search_distance = BT) #,
# None, "SUBSET_SELECTION")
arcpy.PolygonToLine_management(MU, MU_)
arcpy.MakeFeatureLayer_management(MU_, MU_o, "LEFT_FID = -1")
arcpy.management.SelectLayerByLocation(MU_o,
"INTERSECT",
SA_)
# search_distance = BT) #,
# None, "SUBSET_SELECTION")
MU_d = arcpy.analysis.PairwiseDissolve(MU_o,
arcpy.Geometry(),
"RIGHT_FID",
None,
"MULTI_PART")
points = {(round(p.X, dec), round(p.Y, dec))
for G in MU_d
for P in G
for p in [P[0], P[-1]]} # for the for the last and first points
nodePot = tuple((PG(Point(x, y)) for x, y in points))
arcpy.CopyFeatures_management(tuple(nodePot), nodes)
except:
arcpy.AddError("Error in BNodes function: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
raise
def BNodes2(MU, nodes, areas, dec, pCores):
try:
#======= Variables ==========
nodeS = set() # []
update = nodeS.update # .append
Point = arcpy.Point
PG = arcpy.PointGeometry
pool = None
result = None
arcpy.env.parallelProcessingFactor = 2 # threads
mp.set_executable(os.path.join(get_install_path(), 'pythonw.exe'))
pool = mp.Pool(pCores)
result = [pool.apply_async(BCore, args=(A, MU, dec), callback=update)
for A in areas]
# arcpy.AddMessage(str(result[0].get()))
pool.close()
pool.join()
arcpy.env.parallelProcessingFactor = pCores
# arcpy.AddMessage(f'New Nodes: {len(nodeS)}')
nodePot = tuple((PG(Point(x, y)) for x, y in nodeS))
# arcpy.AddMessage(f'New Nodes: {len(nodePot)}')
arcpy.CopyFeatures_management(nodePot, nodes)
except:
if pool:
pool.close()
if result:
arcpy.AddWarning(str(result[0].get()))
arcpy.AddError("Error in BNodes2 function: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
raise
#% Tweezer: removal of acute angles
def tweezer(arcs, inter, v0, MUpoly_, N, cutV, weakEggs ,min_angle, dec, polys):
try:
###Localize function calls
frombuffer = np.frombuffer
arccos = np.arccos
concatenate = np.concatenate
Point = arcpy.Point
f64 = np.float64
Round = np.round
ein = np.einsum
sqrt = np.sqrt
eS = '...i,...i'
eS2 = 'ij,ij->i'
eS2t = 'ijk,ijk->ij'
shapes = {}
cut = [[], []]
node_c = []
v3 = np.zeros((N, 3, 2), dtype=f64) # 2nd from coordinates
### Remove acute angles along arc lengths
sCur = arcpy.da.SearchCursor(MUpoly_, ['SHAPE@', 'OID@'])
for geom, fid in sCur:
((NiH, v3iH, RLiH), (NiT, v3iT, RLiT)) = arcs[fid]
wkb = geom.WKB # spit out coords in binary
# Assumes single part polylines
npGeom = Round(frombuffer(wkb[18:], dtype=f64), decimals=dec)
npGeom = npGeom.reshape((npGeom.size//2, 2)) # pair up x,y coords
# Ralfs law, inner1d computes cross product of an array of vectors
# angle = arccos((v1.v2)/(|v1||v2|))
# sqrt(ein(eS2, v1, v1)) is eqivalent to ((v1*v1).sum(axis=1))**.5
# https://math.stackexchange.com/questions/11346/how-to-compute-the-angle-between-two-vectors-expressed-in-the-spherical-coordina
# https://stackoverflow.com/questions/9171158/how-do-you-get-the-magnitude-of-a-vector-in-numpy
# Create an array of vector pairs
v1 = npGeom[:-2, ] - npGeom[1:-1, ]
v2 = npGeom[2:, ] - npGeom[1:-1, ]
angles = arccos(ein(eS, v1, v2) / sqrt(ein(eS2, v1, v1)) /
sqrt(ein(eS2, v2, v2)))
acuteI = angles > min_angle
# Find all vertices less than min angle
newCore = npGeom[1:-1, ][acuteI]
if (newCore.size // 2 > 1) or ((NiH != NiT) and newCore.size):
if RLiT + 1: # Not along survey boundary
# Snap Nodes
newGeom = concatenate((v0[NiH], newCore, v0[NiT]), axis=0)
newGeom = rdps(newGeom)
shapes[fid] = newGeom
if (~acuteI).any():
# the rejects
cut[0] += list(npGeom[1:-1, ][~acuteI])
cut[1] += list(angles[~acuteI])
else:
# Snap Nodes
newGeom = concatenate((v0[NiH], npGeom[1:-1], v0[NiT]), axis=0)
shapes[fid] = newGeom
v3[NiH, v3iH] = newGeom[1, ] # vertex second from start
v3[NiT, v3iT] = newGeom[-2, ] # vertex second from last
elif NiH != NiT: # only were two vertices
newGeom = concatenate((v0[NiH], v0[NiT]), axis=0) # npGeom[1:-1]
shapes[fid] = newGeom
v3[NiH, v3iH] = newGeom[1, ] # vertex second from start
v3[NiT, v3iT] = newGeom[-2, ] # vertex second from last
else: # line collapsed to point
arcpy.AddMessage(f"fid {fid} line segment has collapsed")
inter[NiH] = 0 # Prevent manipulation of involved Nodes
polys[RLiH][0].remove((fid, 1))
if not polys[RLiH][0]:
polys.pop(RLiH)
weakEggs['Tweezer'].append(str(RLiH))
if RLiT+1:
polys[RLiT][0].remove((fid, -1))
# If polygon as no other arcs, remove it
if not polys[RLiT][0]:
polys.pop(RLiT)
weakEggs['Tweezer'].append(str(RLiT))
### arc-Node position
# Calculate Angles at Nodes 3 positions
angles = np.zeros((N, 3, 1), dtype=np.float32)
v3v = v3-v0
angles[:, 0, 0] = arccos(ein(eS, v3v[:, 1, :], v3v[:, 2, :]) /
sqrt(ein(eS2, v3v[:, 1, :], v3v[:, 1, :])) /
sqrt(ein(eS2, v3v[:, 2, :], v3v[:, 2, :])))
angles[:, 1, 0] = arccos(ein(eS, v3v[:, 0, :], v3v[:, 2, :]) /
sqrt(ein(eS2, v3v[:, 0, :], v3v[:, 0, :])) /
sqrt(ein(eS2, v3v[:, 2, :], v3v[:, 2, :])))
angles[:, 2, 0] = arccos(ein(eS, v3v[:, 0, :], v3v[:, 1, :]) /
sqrt(ein(eS2, v3v[:, 0, :], v3v[:, 0, :])) /
sqrt(ein(eS2, v3v[:, 1, :], v3v[:, 1, :])))
acute = angles < min_angle
acute[0, :, :] = False
### Realign acute Nodes
# Realign arcs incident to acute angels at Nodes
if acute.any():
# Where a Node is involved with only ONE acute angle and only three
# arcs and not on border
LookUp = (acute.sum(axis=1) == 1).reshape((N)) & (inter == 3).T
if LookUp.any():
acuteI = np.where(LookUp) # Node ID's involved with acute angle
nn = acuteI[0].shape[0] # Number of actue angles
# L = np.zeros((nn, 3, 1), dtype=np.float32)
# Lengths of vectors
# arcpy.AddMessage(str(acuteI.shape))
# arcpy.AddMessage(str(acuteI))
L = sqrt(ein(eS2t, v3v[acuteI[0],:,:], v3v[acuteI[0],:,:])).reshape([nn, 3, 1])
# arcpy.AddMessage(str(L.shape))
# L[:, 0, :] = sqrt(ein(eS2, v3v[acuteI, 0, :], v3v[acuteI, 0, :])).T
# L[:, 1, :] = sqrt(ein(eS2, v3v[acuteI, 1, :], v3v[acuteI, 1, :])).T
# L[:, 2, :] = sqrt(ein(eS2, v3v[acuteI, 2, :], v3v[acuteI, 2, :])).T
pos = np.ones((nn, 3, 1), dtype=np.int8)*-1
# position of the acute angle, When evaluating Nodes with 3
# vectors, there can only be one acute angle
back = np.argmin(angles[acuteI], axis=1)
# vector position of back vector
pos[range(nn), (back[:, 0])] = back
i0 = np.where(back == 0)[0]
i1 = np.where(back == 1)[0]
i2 = np.where(back == 2)[0]
# Determine longest vector forming acute angle
pos[i0, (np.argmax(L[i0, 1:, 0], axis=1)+1), 0] = 3
pos[i1, (np.argmax(L[i1][:, (0, 2), 0], axis=1)*2), 0] = 3
pos[i2, (np.argmax(L[i2, : -1, 0], axis=1)), 0] = 3
# Record acute angle
iCur = arcpy.da.InsertCursor(cutV, ['SHAPE@', 'angle', 'type'])
for i in acuteI[0]:
p = arcpy.PointGeometry(Point(*v0[i, 0, :]))
theta = angles[i, :, :].min()
if theta < min_angle:
deg = float(np.rad2deg(theta))
iCur.insertRow([p, deg, 'Node'])
del iCur
# for each arc involved with Nodes
for fid, HTi in zip(*np.where(np.isin(arcs['Ni'], acuteI[0]))):
(Ni, v3i, RLi) = arcs[fid, HTi]
npGeom = shapes[fid]
ii = np.where(acuteI[0] == Ni)[0] # relative index
if not HTi: # If head-Node involved with acute angle
if pos[ii, v3i] == -1: # short arc, remove first point
newGeom = npGeom[1:]
# long arc, remove first, add short
elif pos[ii, v3i] > 2:
# newGeom = npGeom[1:]
# get point from v3 and position from pos
yy = np.where(pos[ii] == -1)[1]
p = v3[Ni, yy]
newGeom = concatenate((p, npGeom[1:]), axis=0)
else: # back arc
yy = np.where(pos[ii] == -1)[1]
p = v3[Ni, yy]
newGeom = concatenate((p, npGeom), axis=0)
else: # If tail-Node involved with acute angle
if pos[ii, v3i] == -1: # short arc, remove first point
newGeom = npGeom[:-1]
# long arc, remove first, add short
elif pos[ii, v3i] > 2:
# newGeom = npGeom[:-1]
# get point from v3 and position from pos
yy = np.where(pos[ii] == -1)[1]
p = v3[Ni, yy]
newGeom = concatenate((npGeom[:-1], p), axis=0)
else:
yy = np.where(pos[ii] == -1)[1]
p = v3[Ni, yy]
newGeom = concatenate((npGeom, p), axis=0)
if newGeom.shape[0] > 2 or \
(newGeom.shape[0] == 2 and not
(newGeom[0, :] == newGeom[1, :]).all()):
shapes[fid] = newGeom
else:
((NiH, v3iH, RLiH), (NiT, v3iT, RLiT)) = arcs[fid]
polys[RLiH][0].remove((fid, 1))
node_c.append((NiH, NiT))
if not polys[RLiH][0]:
polys.pop(RLiH)
weakEggs['Tweezer'].append(str(RLiH))
if RLiT+1:
polys[RLiT][0].remove((fid, -1))
# If polygon as no other arcs, remove it
if not polys[RLiT][0]:
polys.pop(RLiT)
weakEggs['Tweezer'].append(str(RLiT))
### Wrap up
if node_c: # Snaps Node references where arcs have collapsed
for N1, N2 in node_c:
arcs['Ni'][arcs['Ni'] == N1] = N2
arcs['Ni'][arcs['Ni'] == N2] = N1
if cut:
iCur = arcpy.da.InsertCursor(cutV, ['SHAPE@', 'angle', 'type'])
try:
for xy, theta in zip(cut[0], cut[1]):
p = arcpy.PointGeometry(Point(*xy))
if theta < min_angle:
deg = float(np.rad2deg(theta))
iCur.insertRow([p, deg, 'vertex'])
del iCur
except:
arcpy.AddWarning('Adding to cut_vertices failed')
arcpy.AddWarning(str(xy)+' '+str(deg)+' vertex')
del iCur
pass
return (shapes, weakEggs)
except:
arcpy.AddError("Tweezer: Unexpected error on line: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
raise
def Reassemble(
iCur, arcs, polys, shapes, weakEggs, badEggs, pCores, areaSym, SFDS,
edit
):
count = 0
postV = 0
newShape = []
update = newShape.append
arcpy.env.parallelProcessingFactor = 2 # threads
mp.set_executable(os.path.join(get_install_path(), 'pythonw.exe'))
pool = mp.Pool(pCores)
### Assemble Polygons
try:
for FID, [ai, mu] in polys.items():
try:
# subset of arcs; a sub copy more efficient that searching
# entire arcs and they're sorted in ai order
# a0 is tuple of arc ID's; a1 tuple of the arc position in 'arcs'
a0, a1 = zip(*((i, (j-1)//-2) for i, j in ai))
parcs = arcs[a0, :]
parcs2 = arcs[a0, a1]
pool.apply_async(ShapeUp,
args=(parcs, parcs2, ai,
{k: shapes[k] for k in a0}, mu, FID),
callback=update)
except:
arcpy.AddWarning(f"Failure rassembling polygon {FID}")
badEggs['Reassembly'].append(str(FID))
pool.close()
pool.join()
arcpy.env.parallelProcessingFactor = pCores
### Insert Polygons
insertRow = iCur.insertRow
for mu, poly in newShape:
if mu is not None:
insertRow([areaSym, mu, poly])
count += 1
postV += poly.pointCount
else:
if poly[0] > 0:
weakEggs['Reassembly'].append(str(poly[0]))
else:
badEggs['Reassembly'].append(str(poly[0] * -1))
del arcs, shapes
return postV, count, weakEggs, badEggs
except:
try:
if newShape:
salvage = tuple((polygon for mu, polygon in newShape if mu))
if salvage:
t = str(int(time.time()))
salvaged = os.path.join(SFDS, 'salvaged' + t)
arcpy.CopyFeatures_management(salvage, salvaged)
arcpy.AddWarning(f"Something didn't working during reassembly. \
See shoehorn_FDS/{salvaged} to see how far it got.")
edit.stopOperation()
edit.stopEditing(False)
except:
None
arcpy.AddError("Unexpected error on line: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
raise
# %% Main
def main():
try:
######################
#======= Parameters ==========
MUin = arcpy.GetParameterAsText(0)
areaField = arcpy.GetParameterAsText(1)
muField = arcpy.GetParameterAsText(2)
RTSD = arcpy.GetParameterAsText(3)
areas = arcpy.GetParameter(4)
insert = arcpy.GetParameter(5)
MUout = arcpy.GetParameterAsText(6)
degrees = arcpy.GetParameter(7)
# Needs to be xls
excel_n = arcpy.GetParameterAsText(8).split('.')[0]
excel_p = ("%r" % arcpy.GetParameterAsText(9)).replace("'", "")
excel = os.path.join(excel_p, excel_n+'.xls')
retain = arcpy.GetParameter(10)
BT = arcpy.GetParameter(11)
# %%% Variables
start = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
gdb = os.path.dirname(RTSD)
SFDS_n = "shoehorn_FDS"
SFDS = os.path.join(gdb, SFDS_n)
min_angle = np.deg2rad(degrees)
nSurvs = len(areas)
f = 100/(nSurvs*3)
SAR = os.path.join(RTSD, 'SAPOLYGON')
SAR_L = "SAR_Layer" #RTSD SAPOLYGONS
SAR_L2 = "SAR_Layer2" #RTSD SAPOLYGONS
SAR_L4 = "SAR_Layer4"
SARline = "in_memory/SApoly"
SARline_L = "SARline_layer"
SARsplit_m = "in_memory/SARsplit_multi"
SARsplit = os.path.join(SFDS, "SARsplit") #delete in first round
SARstart = "in_memory/SARstart"
SAmis = "MU2SA_off"
SA1_ = "in_memory/SA1"
SA1_L = "SA1_L"
MUbase = os.path.basename(MUin)
MU = os.path.join(RTSD, 'MUPOLYGON')
MUR_L = "RTSD_layer"
survey = "MUsurvey"
mid = "in_memory/mid"
mid_L = "mid_layer"
nodes = "in_memory/nodes"
kNodes = "in_memory/keyNodes"
nNodes = "in_memory/newNodes"
bNodes = os.path.join(SFDS,'BoundaryNodes')
bound_L = "Boundary_Layer"
MUinter = "MUinter"
MUinter_L = "MUinter_L"
MUsplit = "in_memory/MUsplit"
MUpoly_L = "MUpolyline_layer"
ends = "in_memory/End_ends" #
starts = "in_memory/Start_ends" #
TheEnd = "in_memory/The_Ends"
# Nodes = "Nodes" #Need delete
arcpy.env.workspace = RTSD
if not retain:
MUpoly = "in_memory/MU_poly2line"
# NodeArc = "in_memory/Node2Arc"
MUpoly_ = "in_memory/MU_poly2line_sp"
else:
TheEnd = "The_Ends"
MUpoly = "MU_poly2line"
# NodeArc = "Node2Arc"
MUpoly_ = "MU_poly2line_sp"
kNodes = "keyNodes"
nNodes = "newNodes"
SARline = "SApoly"
MUsplit = "musplit"
if arcpy.ListFeatureClasses(kNodes):
arcpy.Delete_management(kNodes)
if arcpy.ListFeatureClasses(nNodes):
arcpy.Delete_management(nNodes)
failed = set()
cutV = "amended_vertices"
weakE = "Collapsed"
badE = "polygon_errors"
weakEggs = {'Tweezer':[],'Reassembly':[],'Cluster Tolerance':[]}
badEggs = {'Exception':[],'Reassembly':[]}
# %%% General Setup
arcpy.AddMessage("Shoehorn Version 2.9.3")
# threads = psutil.cpu_count()/psutil.cpu_count(False)
# keep in mind this actually returns threads, not cores
cores = os.cpu_count()
# Leaves one physical core free, assuming two threads per core
pCores = cores//2 - 1
# pCores = str((cores-4)/cores*100)+'%'
arcpy.env.parallelProcessingFactor = pCores
arcpy.env.overwriteOutput = True
MUD = arcpy.Describe(MUin).spatialReference
XYRin = MUD.XYResolution
XYTin = MUD.XYTolerance
fD = arcpy.Describe(RTSD)
XYR = fD.spatialReference.XYResolution
XYT = fD.spatialReference.XYTolerance
if XYR != 0.1 and XYT < 0.2:
arcpy.AddWarning("Your RTSD was not created with current xy-resolution of 0.1 meters!")
arcpy.AddWarning("Make sure you have the most current SSURGO_QA toolbox\n.")
raise
if fD.spatialReference.name != MUD.name:
arcpy.AddWarning("Input Feature Class and output Feature Dataset have different projections")
sr = fD.spatialReference
arcpy.env.workspace = gdb
sfds = arcpy.ListDatasets(SFDS_n, feature_type='Feature')
if not sfds:
arcpy.CreateFeatureDataset_management(gdb, SFDS_n, sr)
if arcpy.ListFeatureClasses(cutV):
arcpy.Delete_management(cutV)
if arcpy.ListFeatureClasses(bNodes):
arcpy.Delete_management(bNodes)
arcpy.CreateFeatureclass_management(SFDS, cutV, "POINT", '', '', '', sr)
cutV = os.path.join(SFDS, cutV)
arcpy.AddField_management(cutV, 'angle', 'FLOAT')
arcpy.AddField_management(cutV, 'type', 'TEXT', field_length=10)
dec = int(math.log10(XYR)//-1)
textStyle = xlwt.easyxf(num_format_str='Text')
intStyle = xlwt.easyxf(num_format_str='0')
perStyle = xlwt.easyxf(num_format_str='0.0%')
hdr = ['areasym', 'prePoly', 'postPoly', 'preVertex', 'postVertex', 'proVertex']
wb = xlwt.Workbook()
ws = wb.add_sheet('Diet Summary')
for cell, hdr in enumerate(hdr):
ws.write(0, cell, hdr, textStyle)
if insert:
mud = arcpy.Describe(MU)
if mud.editorTrackingEnabled and mud.istimeInUTC:
MUout = os.path.join(RTSD, 'MUPOLYGON')
createTimeField = mud.createdAtFieldName
else:
createTimeField = [f.name for f in mud.Fields
if ('creat' in f.name.lower())
and ('date' in f.name.lower())
and (f.type == 'Date')]
if len(createTimeField) > 1:
t = str(int(time.time()))
MUout = MUbase + t
insert = False
arcpy.AddWarning("Tracking was not enabled and more than one potential \
creation date field discovered and the output \
can't be inserted directly into RTSD MUPOLYGON")
arcpy.AddWarning('The output feature will be saved as' + MUout)
elif len(createTimeField) == 0:
t = str(int(time.time()))
MUout = MUbase + t
insert = False
arcpy.AddWarning("Tracking was not enabled and a potential \
creation date field was not discovered and the output \
can't be inserted directly into RTSD MUPOLYGON")
arcpy.AddWarning('The output feature will be saved as' + MUout)
else:
MUout = os.path.join(RTSD, 'MUPOLYGON')
createTimeField = createTimeField[0]
arcpy.management.EnableEditorTracking(MU, None, createTimeField)
arcpy.AddWarning(f"Editor tracking has bee been enabled with the \
{createTimeField} field activated")
except:
arcpy.AddError("Failed in General Setup")
arcpy.AddError("Unexpected error on line: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
sys.exit(1)
# %%% Boundary Nodes
try:
arcpy.SetProgressor('default', 'Creating Boundary Nodes')
arcpy.env.XYResolution = XYR
arcpy.env.XYTolerance = XYT
T = 10*XYR
if not BT:
BT = T*2**.5
if not insert:
oe = arcpy.ListFeatureClasses(MUout)
if oe:
arcpy.AddWarning(MUout+" already exists, note this tool will add polygons to it")
else:
arcpy.CreateFeatureclass_management(SFDS, MUout, "POLYGON",
'', '', '', sr)
arcpy.AddField_management(MUout, 'AREASYMBOL', 'TEXT',
field_length=20)
arcpy.AddField_management(MUout, 'MUSYM', 'TEXT', field_length=6)
q = "AREASYMBOL IN ('"+"','".join(areas)+"')"
q2 = "AREASYMBOL NOT IN ('"+"','".join(areas)+"')"
# Suveys of interest
arcpy.MakeFeatureLayer_management(SAR, SAR_L, q)
# All surveys except of interest
arcpy.MakeFeatureLayer_management(SAR, SAR_L2, q2)
arcpy.SelectLayerByLocation_management(SAR_L2, 'BOUNDARY_TOUCHES', SAR_L,
selection_type='NEW_SELECTION')
with arcpy.da.SearchCursor(SAR_L2, 'AREASYMBOL') as sCur:
rNeigh = {a for a, in sCur}
q3 = "AREASYMBOL IN ('"+"','".join(rNeigh)+"')" # Neighboirng survey areas
arcpy.MakeFeatureLayer_management(MU, MUR_L, q3)
# surveys of interest and neigh
arcpy.env.workspace = SFDS
if int(arcpy.GetCount_management(MUR_L).getOutput(0)):
# Get outsie outlines of the surveys of interest
arcpy.PolygonToLine_management(SAR_L, SA1_)
arcpy.MakeFeatureLayer_management(SA1_, SA1_L, "LEFT_FID = -1")
# Get all oulines of neighbors and surveys of interest
q4 = "AREASYMBOL IN ('"+"','".join(rNeigh | set(areas))+"')"
arcpy.MakeFeatureLayer_management(SAR, SAR_L4, q4)
arcpy.PolygonToLine_management(SAR_L4, SARline, "IGNORE_NEIGHBORS")
# Boundary nodes around neighbors
BNodes(SA1_L, MUR_L, kNodes, dec)
# Boundary Nodes along input
BNodes2(MUin, nNodes, areas, dec, pCores)
# Needed to snap nodes between selected surveys
arcpy.analysis.PairwiseIntegrate(nNodes, BT)
arcpy.Snap_edit(nNodes, [[kNodes, 'VERTEX', BT]])
arcpy.Snap_edit(nNodes, [[SA1_, 'VERTEX', BT]])
arcpy.Snap_edit(nNodes, [[SA1_, 'EDGE', BT]])
pointMerge = [kNodes, nNodes, SARstart]
else:
arcpy.PolygonToLine_management(SAR_L, SARline, "IGNORE_NEIGHBORS")
BNodes2(MUin, nNodes, areas, dec, pCores)
pointMerge = [nNodes, SARstart]
# arcpy.PolygonToLine_management(SAR_L, SARline, 'IGNORE_NEIGHBORS')
arcpy.FeatureVerticesToPoints_management(SARline, SARstart, 'START')
arcpy.Merge_management(pointMerge, nodes)
arcpy.PairwiseDissolve_analysis(nodes, bNodes, None, None, "SINGLE_PART")
arcpy.SplitLineAtPoint_management(SARline, bNodes, SARsplit_m, BT * 2**0.5)
arcpy.MultipartToSinglepart_management(SARsplit_m, SARsplit)
arcpy.Delete_management(MUR_L)
arcpy.AddMessage("Processing {} surveys.".format(nSurvs))
except:
arcpy.AddError("Failed while creating Boundary Nodes")
arcpy.AddError("Unexpected error on line: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
sys.exit(1)
# %%% By survey area
for rowID, areaSym in enumerate(areas):
status = rowID*3
rowID += 2
arcpy.AddMessage('______________________________________')
msg = "Survey {} of {}: geoprocessing".format(status//3+1, nSurvs)
arcpy.SetProgressor('step', msg)
arcpy.SetProgressorPosition(int(f*status))
arcpy.AddMessage('{}: Survey {} of {}'.format(areaSym, status//3+1, nSurvs))
arcpy.Delete_management('in_memory/')
arcpy.MakeFeatureLayer_management(MUin, survey,
areaField+" = '{}'".format(areaSym))
ws.write(rowID, 0, areaSym, textStyle)
ws.write(rowID, 1, int(arcpy.GetCount_management(survey)[0]), intStyle)
# arcpy.Integrate_management(survey,T) #collapse slivers and self-intersections per OGC
# %%%% Geoprocessing
try:
q = "AREASYMBOL = '" + areaSym + "'"
arcpy.PolygonToLine_management(survey, MUpoly)
arcpy.MakeFeatureLayer_management(MUpoly, MUpoly_L, "RIGHT_FID = -1")
if arcpy.GetCount_management(MUpoly_L).getOutput(0):
uCur = arcpy.da.UpdateCursor(MUpoly_L, ['RIGHT_FID', 'LEFT_FID'])
for RF, LF in uCur:
uCur.updateRow([LF, -1])
del uCur
arcpy.MakeFeatureLayer_management(MUpoly, MUpoly_L, "LEFT_FID = -1")
arcpy.MakeFeatureLayer_management(SARsplit, SARline_L, q)
arcpy.MakeFeatureLayer_management(bNodes, bound_L)
arcpy.management.SelectLayerByLocation(bound_L, "WITHIN_A_DISTANCE",
SARline_L, T)
arcpy.Snap_edit(MUpoly_L, [[bound_L, 'VERTEX', BT]])
# arcpy.Snap_edit(MUpoly_L, [[bound_L, 'EDGE', BT]])
arcpy.SplitLineAtPoint_management(MUpoly_L, bound_L, MUsplit, BT)
arcpy.FeatureVerticesToPoints_management(MUsplit, mid, "MID")
arcpy.analysis.SpatialJoin(SARline_L, mid , MUinter, "JOIN_ONE_TO_ONE",
"KEEP_ALL", '', "CLOSEST", BT)
arcpy.MakeFeatureLayer_management(MUpoly, MUpoly_L,
"LEFT_FID <> -1 AND LEFT_FID<>RIGHT_FID")
mapping='LEFT_FID "LEFT_FID" true true false 4 Long 0 0, First, #,\
MUpolyline_layer, LEFT_FID, -1, -1, MUinter, LEFT_FID, -1, -1;\
RIGHT_FID "RIGHT_FID" true true false 4 Long 0 0,First, #,\
MUpolyline_layer, RIGHT_FID,-1, -1,MUinter, RIGHT_FID, -1, -1'
arcpy.management.Merge([MUpoly_L, MUinter], MUpoly_, mapping)
arcpy.FeatureVerticesToPoints_management(MUpoly_, starts, "START")
arcpy.FeatureVerticesToPoints_management(MUpoly_, ends, "END")
arcpy.AddField_management(ends, 'tail', "SHORT")
arcpy.AddField_management(starts, 'tail', "SHORT")
arcpy.CalculateField_management(ends, "tail", "1")
arcpy.Merge_management(ends+";"+starts, TheEnd)
arcpy.Snap_edit(TheEnd, [[bound_L, 'VERTEX', BT]])
arcpy.Delete_management(bound_L)
arcpy.Delete_management(SARline_L)
except:
arcpy.AddError("Failed while Geoprocessing inputs")
arcpy.AddError("Unexpected error on line: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
sys.exit(1)
# %%%%Relational Data Structures
# Arcs collated by MUPOLYGON Ojbject ID
try:
sCur = arcpy.da.SearchCursor(MUpoly_, 'OID@')
oid = {ID for ID, in sCur}
if not oid:
arcpy.AddWarning('Survey {} has no features! Skipping!'.format(areaSym))
failed.add(areaSym)
continue
n = max(oid)+1
# Row 0 of inter, v3,v0, & arcs are dummy rows as there are no FID=0.
# Computationally leaner than FID-1
# number of intersections (Nodes)
N = int(arcpy.GetCount_management(TheEnd).getOutput(0))//2+1
# indexed by MUpoly_: Node fid, v3 position (realtive intersection ID),
# Right then Left FID, head then tail
arcs = np.zeros((n, 2), dtype=([('Ni', '<i4'), ('v3i', '<i4'),
('RLi', '<i4')]))
polys = {}
# Tally of the number of intersecting arcs at a Node, used in tweezer
inter = np.zeros((N), dtype=np.int8)
# Node coordinates, used in tweezer
v0 = np.zeros((N, 1, 2), dtype=np.float64)
#### Populating the arcs array, the key relational table
# TARGET_FID: Node ID, ORIG_FID: MUpolyline fid (arc id)
Round = np.round
Ndex = {}
Nid = 1
sCur = arcpy.da.SearchCursor(TheEnd, ['SHAPE@XY', 'ORIG_FID',
'RIGHT_FID', 'LEFT_FID', 'tail'])
try:
for xy, Ai, Ri, Li, t in sCur:
strxy = str(xy)
if strxy in Ndex:
Ni = Ndex[strxy]
else:
Nid += 1
Ndex[strxy] = Nid
Ni = Nid
v0[Ni] = Round(xy, dec)
i = inter[Ni] # number of intersections
I = (abs(i) >= 2)*2 or abs(i) # v3 index, constrained 0-2. If greater than 2, cap at 2
if not t:
inter[Ni] += i >= 0 or -1 # add boolean True or demerit 1
arcs[Ai, 0] = (Ni, I, Ri)
if Ri in polys:
polys[Ri][0].append((Ai, 1))
else:
polys[Ri] = [[(Ai, 1)], '']
elif Li+1:
inter[Ni] += i >= 0 or -1
arcs[Ai, 1] = (Ni, I, Li)
if Li in polys:
polys[Li][0].append((Ai, -1))
else:
polys[Li] = [[(Ai, -1)], '']
else: # Node on border
arcs[Ai, 1] = (Ni, I, Li)
inter[Ni] = abs(inter[Ni])*-1
except:
if not Li:
arcpy.AddError("It is likely the input soil polygon feature is incongruent with the transactional SAPOLYGON feature")
arcpy.AddError("Either amend the input soil polygon feature or update the transactaional SAPOLYGON feature.")
arcpy.MakeFeatureLayer_management(MUinter, MUinter_L, "'LEFT_FID' IS NULL")
arcpy.CopyFeatures_management(MUinter_L, SAmis)
arcpy.AddError(f"See feature {SAmis} to see where they're incongruent")
sys.exit(1)
del sCur, Ndex
N = Nid+1
inter = inter[:N]
v0 = v0[:N, :, :]
sCur = arcpy.da.SearchCursor(survey, ['OID@', muField, 'SHAPE@'])
preV = 0
for FID, mu, shp in sCur:
if FID in polys:
polys[FID][1] = mu
else:
weakEggs['Cluster Tolerance'].append(str(FID))
try: # Catch null geometries
preV += shp.pointCount
except:
arcpy.AddMessage("Null geometries in input removed")
weakEggs['Cluster Tolerance'].append(str(FID))
polys.pop(FID)
except:
arcpy.AddError("Failed while setting up Relational Tabels")
arcpy.AddError("Unexpected error on line: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
raise
# %%%% Msg
msg = "Survey {} of {}: Tweezer & Diet".format(status//3+1,nSurvs)
arcpy.SetProgressor('step',msg)
arcpy.SetProgressorPosition(int(f*status+f))
# shapes is a dictionary, polyline FID: polyline geometry (arc)
shapes, weakEggs = tweezer(arcs, inter, v0, MUpoly_, N, cutV, weakEggs,
min_angle, dec, polys)
# P = arcpy.Point
# allLines = [arcpy.Polyline(arcpy.Array([P(*p) for p in line])) for line in shapes.values()]
# arcpy.management.CopyFeatures(allLines, 'allLines')
msg = "Survey {} of {}: Reassmbling polygons".format(status//3+1, nSurvs)
arcpy.SetProgressor('step', msg)
arcpy.SetProgressorPosition(int(f * (status+2)))
# %%%% Call Tweezer & Reassemble
if insert:
try:
edit = arcpy.da.Editor(os.path.dirname(RTSD))
edit.startEditing(True, True)
edit.startOperation()
iCur = arcpy.da.InsertCursor(MUout, [areaField, muField, 'SHAPE@'])
postV, count, weakEggs, badEggs = Reassemble(
iCur, arcs, polys, shapes, weakEggs, badEggs, pCores,
areaSym, SFDS, edit
)
del iCur
edit.stopOperation()
edit.stopEditing(True)
except:
arcpy.AddError("Failed during Reassembly")
arcpy.SetProgressorLabel("Undoing changes")
edit.stopOperation()
edit.stopEditing(False)
q = "AREASYMBOL IN ('"+"','".join(areas)+"')"
q += f" AND {createTimeField} >= timestamp '{start}'"
arcpy.MakeFeatureLayer_management(MUout, MUR_L, q)
arcpy.DeleteFeatures_management(MUR_L)
arcpy.AddError("Unexpected error on line: " +
str(sys.exc_info()[-1].tb_lineno))
arcpy.AddError("\n" + str(sys.exc_info()[0]))
arcpy.AddError("\n" + str(sys.exc_info()[1]))
raise
else:
iCur = arcpy.da.InsertCursor(MUout, [areaField, muField, 'SHAPE@'])
postV, count, weakEggs, badEggs = Reassemble(
iCur, arcs, polys, shapes, weakEggs, badEggs, pCores,
areaSym, SFDS, edit
)
del iCur
# %%%% Msg
arcpy.SetProgressor('step', msg)
arcpy.SetProgressorPosition(int(f*(status+3)))
arcpy.AddMessage("Survey completed")
ws.write(rowID, 3, preV, intStyle)
ws.write(rowID, 4, postV, intStyle)
ws.write(rowID, 5, (preV-postV)/preV, perStyle)
ws.write(rowID, 2, count, intStyle)
# %%% Wrap-up
try: