-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoolbox_script.py
More file actions
2039 lines (1795 loc) · 77 KB
/
toolbox_script.py
File metadata and controls
2039 lines (1795 loc) · 77 KB
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
import sys
import time
import traceback
import networkx as nx
from collections import Counter
from datetime import (date)
from difflib import get_close_matches
from functools import wraps
from qgis import processing
from qgis.PyQt.QtCore import (
QCoreApplication,
QVariant,
)
from qgis.analysis import QgsGeometrySnapper
from qgis.core import (
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsDistanceArea,
QgsFeature,
QgsFeatureRequest,
QgsFeatureSink,
QgsField,
QgsGeometry,
QgsMapLayer,
QgsPointXY,
QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingOutputString,
QgsProcessingParameterBoolean,
QgsProcessingParameterDefinition,
QgsProcessingParameterDistance,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterField,
QgsProcessingParameterNumber,
QgsProject,
QgsSpatialIndex,
QgsUnitTypes,
QgsVectorLayer,
QgsVectorLayerUtils,
QgsWkbTypes,
edit,
Qgis,
QgsRectangle,
QgsExpression,
QgsPoint,
QgsLineString
)
CONTEXT = None
FEEDBACK = None
START_TIME = None
DISTANCE_AREA = None
STEP = 0
TOTAL_STEPS = 34
class QgsProcessingCanceledException(Exception):
pass
def check_feedback():
if FEEDBACK.isCanceled():
raise QgsProcessingCanceledException("")
def cancel_on_entry(func):
@wraps(func)
def wrapper(*args, **kwargs):
if FEEDBACK.isCanceled():
raise QgsProcessingCanceledException("")
return func(*args, **kwargs)
return wrapper
def interrupt_on_cancel(func):
@wraps(func)
def wrapper(*args, **kwargs):
def tracer(frame, event, arg):
if event == 'line' and FEEDBACK.isCanceled():
raise QgsProcessingCanceledException("")
return tracer
sys.settrace(tracer)
try:
return func(*args, **kwargs)
finally:
sys.settrace(None)
return wrapper
class DisconnectedIslands(object):
def __init__(self, l, t):
self.layer = l
self.disconnected_islands_tolerance = t
def run(self, tolerance):
attr_idx = self.layer.fields().indexFromName("networkGrp")
if attr_idx == -1:
self.layer.startEditing()
self.layer.dataProvider().addAttributes([QgsField("networkGrp", QVariant.Int)])
self.layer.commitChanges()
attr_idx = self.layer.fields().indexFromName("networkGrp")
G = nx.Graph()
if tolerance == 0:
tolerance = self.disconnected_islands_tolerance
self.layer.startEditing()
for feat in self.layer.getFeatures():
check_feedback()
self.layer.changeAttributeValue(feat.id(), attr_idx, -1)
geom = feat.geometry()
QgsGeometry.convertToSingleType(geom)
if not geom.isNull():
line = geom.asPolyline()
for i in range(len(line) - 1):
check_feedback()
G.add_edges_from([((int(line[i][0] / tolerance), int(line[i][1] / tolerance)),
(int(line[i + 1][0] / tolerance), int(line[i + 1][1] / tolerance)),
{'fid': feat.id()})])
self.layer.commitChanges()
connected_components = list(G.subgraph(c) for c in nx.connected_components(G))
fid_comp = {}
for i, graph in enumerate(connected_components):
check_feedback()
for edge in graph.edges(data=True):
check_feedback()
fid_comp[edge[2].get('fid', None)] = i
count_map = {}
for v in fid_comp.values():
check_feedback()
count_map[v] = count_map.get(v, 0) + 1
isolated = [k for k, v in fid_comp.items() if count_map[v] == 1]
self.layer.selectByIds(isolated)
self.layer.startEditing()
for (fid, group) in fid_comp.items():
check_feedback()
self.layer.changeAttributeValue(fid, attr_idx, group)
self.layer.commitChanges()
return self.layer, [i for i in set(fid_comp.values()) if i > 0]
@cancel_on_entry
def run_alg(alg, params, delete_input=True, is_child_alg=True):
result = processing.run(
alg, {**params, 'OUTPUT': 'TEMPORARY_OUTPUT'},
is_child_algorithm=is_child_alg, context=CONTEXT
)
output = CONTEXT.getMapLayer(result['OUTPUT'])
if delete_input and params.get('INPUT'):
delete_layer(params["INPUT"])
return output
@cancel_on_entry
def flatten_collection(items):
for item in items:
check_feedback()
if isinstance(item, (list, tuple)):
yield from flatten_collection(item)
else:
yield item
@interrupt_on_cancel
def format_time():
sec = int(time.time() - START_TIME)
h, r = divmod(sec, 3600)
m, s = divmod(r, 60)
return f"(Time: {h:02}:{m:02}:{s:02})"
@interrupt_on_cancel
def iterate_step(amount=0):
global STEP
if amount > 0:
STEP += amount
else:
STEP += 1
@interrupt_on_cancel
def update_progress(changelog=""):
current_time = format_time()
iterate_step()
percent = int((STEP / TOTAL_STEPS) * 100)
FEEDBACK.setProgress(percent)
if changelog:
FEEDBACK.setProgressText(f"{changelog} {current_time}")
@interrupt_on_cancel
def add_unique_field(layer, name, type_):
if name not in [field.name() for field in layer.fields()]:
layer.dataProvider().addAttributes([QgsField(name, type_)])
layer.updateFields()
@interrupt_on_cancel
def copy_layer(layer, expr=""):
if expr != "":
return layer.materialize(QgsFeatureRequest().setFilterExpression(expr))
return layer.materialize(QgsFeatureRequest())
@interrupt_on_cancel
def delete_layer(layer):
if isinstance(layer, QgsMapLayer):
QgsProject.instance().removeMapLayer(layer.id())
del layer
@cancel_on_entry
def remove_features_by_expression(layer, expression):
with edit(layer):
for feature in layer.getFeatures(
QgsFeatureRequest().setFilterExpression(expression)
):
check_feedback()
layer.deleteFeature(feature.id())
@cancel_on_entry
def remove_feature_attribute_by_name(layer, attr_name):
index_from_name = layer.fields().indexFromName(attr_name)
if index_from_name != -1:
layer.dataProvider().deleteAttributes([index_from_name])
layer.updateFields()
@cancel_on_entry
def clean_layer(layer):
fix_geometries = ('native:fixgeometries', {'INPUT': {}, 'METHOD': 1})
remove_null_geometries = (
'native:removenullgeometries', {'INPUT': {}, 'REMOVE_EMPTY': False}
)
remove_duplicate_vertices = (
'native:removeduplicatevertices',
{'INPUT': {}, 'TOLERANCE': 1e-6, 'USE_Z_VALUE': False}
)
delete_duplicate_geometries = (
'native:deleteduplicategeometries', {'INPUT': {}}
)
clean_steps = [
fix_geometries, remove_null_geometries,
fix_geometries, remove_duplicate_vertices,
fix_geometries, delete_duplicate_geometries,
fix_geometries
]
for alg, params in clean_steps:
check_feedback()
params["INPUT"] = layer
layer = run_alg(alg, params)
return layer
@cancel_on_entry
def split_lines_by_points(
line_layer,
point_layer,
min_gap=0.0, # map units; 0 disables thinning
end_epsilon=1e-9): # map units; guards against endpoint splits
crs = line_layer.sourceCrs()
fields = line_layer.fields()
out = QgsVectorLayer(f"LineString?crs={crs.authid()}", "split_lines", "memory")
pr = out.dataProvider(); pr.addAttributes(fields); out.updateFields()
def uniq_positions(geom, pts):
# get monotonically increasing positions along the line, filtered
pos = []
for p in pts:
check_feedback()
q = geom.nearestPoint(QgsGeometry.fromPointXY(p))
d = geom.lineLocatePoint(q)
pos.append((d, QgsPointXY(q.asPoint())))
pos.sort(key=lambda t: t[0])
# drop points too close to ends
l = geom.length()
filtered = []
last_d = None
for d, pt in pos:
check_feedback()
if d is None or d <= end_epsilon or (l - d) <= end_epsilon:
continue
if last_d is None or (min_gap == 0.0) or abs(d - last_d) >= min_gap:
filtered.append((d, pt))
last_d = d
return [pt for _, pt in filtered]
# index points by bbox to reduce scans
pidx = QgsSpatialIndex(point_layer.getFeatures(),
flags=QgsSpatialIndex.FlagStoreFeatureGeometries)
req = QgsFeatureRequest()
new_feats = []
for lf in line_layer.getFeatures():
check_feedback()
g = lf.geometry()
if not g or g.isEmpty():
continue
# fetch all candidate points by bbox, no artificial buffers
cands = []
for pid in pidx.intersects(g.boundingBox()):
check_feedback()
pf = point_layer.getFeature(pid)
pg = pf.geometry()
if not pg or pg.isEmpty():
continue
# accept only points actually on/near the line via nearestPoint projection
p = pg.asPoint()
proj = g.nearestPoint(QgsGeometry.fromPointXY(p))
if proj is None or proj.isEmpty():
continue
cands.append(QgsPointXY(proj.asPoint()))
if not cands:
nf = QgsFeature(fields); nf.setAttributes(lf.attributes()); nf.setGeometry(g)
new_feats.append(nf); continue
split_pts = uniq_positions(g, cands)
parts = [g]
if split_pts:
# split sequentially; QGIS splitGeometry tolerates tiny duplicates
for pt in split_pts:
check_feedback()
nxt = []
for seg in parts:
check_feedback()
res, geoms, _ = seg.splitGeometry([pt], False)
if res == 0:
nxt.append(seg)
if geoms: nxt.extend(geoms)
else:
nxt.append(seg)
parts = nxt
for piece in parts:
check_feedback()
nf = QgsFeature(fields); nf.setAttributes(lf.attributes()); nf.setGeometry(piece)
new_feats.append(nf)
pr.addFeatures(new_feats); out.updateExtents()
return out
@cancel_on_entry
def get_internal_connected_features(layer):
# build spatial index
spatial_index = QgsSpatialIndex(
layer.getFeatures(),
flags=QgsSpatialIndex.FlagStoreFeatureGeometries
)
internal_feats = []
for feature in layer.getFeatures():
check_feedback()
geom = feature.geometry()
for neighbor_id in spatial_index.intersects(geom.boundingBox()):
check_feedback()
if feature.id() >= neighbor_id:
continue
neighbor = layer.getFeature(neighbor_id)
intersection = geom.intersection(neighbor.geometry())
if intersection and not intersection.isEmpty():
geom_vertices = list(geom.vertices())
if intersection.type() == QgsWkbTypes.PointGeometry:
for pt in intersection.asMultiPoint() \
if intersection.isMultipart() \
else [intersection.asPoint()]:
check_feedback()
pt_xy = QgsPointXY(pt)
if not (
pt_xy == QgsPointXY(geom_vertices[0])
or
pt_xy == QgsPointXY(geom_vertices[-1])
):
internal_feats.append(neighbor)
return internal_feats
@cancel_on_entry
def split_input_with_ncf_lines(bypass_split, layer, ncf_layer):
if not bypass_split:
# convert ncf layer from polygons to lines
ncf_lines_layer = run_alg(
"native:polygonstolines",
{"INPUT": ncf_layer},
False
)
update_progress("- Converted NCF polygons to lines")
# get intersection points between waterway lines and ncf lines
pts = run_alg(
"native:lineintersections", {
"INPUT": layer,
"INTERSECT": ncf_lines_layer,
"INPUT_FIELDS": [],
"INTERSECT_FIELDS": [],
"INPUT_FIELDS_PREFIX": "",
"INTERSECT_FIELDS_PREFIX": ""
}
)
update_progress("- Found intersection points between waterway lines and NCF polygons")
# split lines by points
layer = split_lines_by_points(
layer, pts
)
update_progress("- Split waterway lines at intersection points")
delete_layer(ncf_lines_layer)
else:
for count in range(3):
check_feedback()
update_progress()
return layer
@cancel_on_entry
def recalculate_feature_lengths(layer):
with edit(layer):
for feature in layer.getFeatures():
check_feedback()
feature["LenMiles"] = round(
DISTANCE_AREA.convertLengthMeasurement(
feature.geometry().length(), QgsUnitTypes.DistanceMiles
),
4
)
layer.updateFeature(feature)
update_progress("- Recalculated feature lengths")
@cancel_on_entry
def fix_link_types(layer, flagged):
link_types = [
"CPT", "Centerline", "Coastal-connect", "Inland",
"Great Lakes/St", "International", "Internat River"
]
joined_link_types = "'" + "', '".join(link_types) + "'"
link_type_expr = f"(LinkType NOT IN ({joined_link_types}) OR LinkType IS NULL) AND NOT Name ILIKE '%Manual Connection%'"
with edit(layer):
for feature in layer.getFeatures(
QgsFeatureRequest().setFilterExpression(link_type_expr)
):
check_feedback()
if feature["LinkType"] is None:
flagged.append((feature["Name"], "Null LinkType"))
continue
link_type = str(feature["LinkType"])
if 'lock' not in link_type.lower():
matches = get_close_matches(
link_type, link_types, n=1, cutoff=0.5
)
if matches:
feature["LinkType"] = matches[0]
layer.updateFeature(feature)
else:
flagged.append((feature["Name"], "Invalid LinkType"))
update_progress("- Fixed LinkType typos")
@cancel_on_entry
def get_geom_len_mi(geom):
return round(
DISTANCE_AREA.convertLengthMeasurement(
geom.length(), QgsUnitTypes.DistanceMiles
), 4
)
@cancel_on_entry
def remove_empty_and_short_geometries(layer, min_geom_length, protected_ids=None):
protected_ids = protected_ids or set()
with edit(layer):
for feature in layer.getFeatures():
check_feedback()
if feature.id() in protected_ids:
continue
g = feature.geometry()
if g.isNull() or g.isEmpty() or not feature.hasGeometry() or get_geom_len_mi(g) <= min_geom_length:
if not str(feature["Name"]).startswith('Manual Connection'):
layer.deleteFeature(feature.id())
update_progress("- Removed empty & very short geometries")
@cancel_on_entry
def snap_geometries_with_snapper(layer, tolerance_deg):
# make a static reference copy so snapping doesn't cascade while we edit
ref_layer = copy_layer(layer)
snapper = QgsGeometrySnapper(ref_layer)
# cache original geometries in case we want to guard against degenerates
feats = list(layer.getFeatures())
# EndPointPreferClosest == 5; only endpoints move, using closest-point mode
snapped_feats = snapper.snapFeatures(
feats,
tolerance_deg,
QgsGeometrySnapper.EndPointPreferClosest
)
# apply snapped geometries back onto the original layer
with edit(layer):
for f in snapped_feats:
check_feedback()
fid = f.id()
new_geom = f.geometry()
if not new_geom or new_geom.isEmpty():
# keep original if snapper somehow produced an empty geometry
continue
# guard against self-loops / collapsed lines in deg units
# (very small length -> keep original geometry instead)
if new_geom.length() < 1e-10:
continue
layer.changeGeometry(fid, new_geom)
delete_layer(ref_layer)
update_progress("- Snapped geometries")
return layer
@cancel_on_entry
def snap_geometries(layer, tolerance):
layer = run_alg(
"native:snapgeometries",
{
'INPUT': layer, "REFERENCE_LAYER": layer,
"TOLERANCE": tolerance, "BEHAVIOR": 6
})
update_progress("- Snapped geometries")
return layer
@cancel_on_entry
def reconnect_islands(layer, island_tol, snapping_tolerance):
default_island_tol = 0.000001
disconnected_islands = DisconnectedIslands(layer, default_island_tol)
disconnected_layer, islands = disconnected_islands.run(island_tol)
tolerance = snapping_tolerance
skipped_fids = set()
# helpers
def _near_dateline_deg(lon, deg_tol):
return abs(abs(lon) - 180.0) <= deg_tol
def _wrap_lon_diff_deg(lon1, lon2):
# minimal |Δλ| on a circle (degrees)
d = abs((lon1 - lon2 + 540.0) % 360.0 - 180.0)
return d
def _virtually_connected_across_dateline(isle_feat, seam_pts_main, deg_tol):
g = isle_feat.geometry()
if not g or g.isEmpty():
return False
for v1 in g.vertices():
check_feedback()
lon1, lat1 = float(v1.x()), float(v1.y())
if not _near_dateline_deg(lon1, deg_tol):
continue
for p2 in seam_pts_main:
check_feedback()
lon2, lat2 = p2.x(), p2.y()
if abs(lat1 - lat2) > deg_tol:
continue
if _wrap_lon_diff_deg(lon1, lon2) <= deg_tol:
return True
return False
while islands:
check_feedback()
mainland_feats = []
islands_set = set(islands)
island_groups = {gid: [] for gid in islands_set}
for f in disconnected_layer.getFeatures():
check_feedback()
grp = f["networkGrp"]
if grp == 0:
mainland_feats.append(f)
elif grp in islands_set and f.id() not in skipped_fids:
island_groups[grp].append(f)
active_islands = [gid for gid, feats in island_groups.items() if feats]
if not active_islands:
break
mainland_idx = QgsSpatialIndex(flags=QgsSpatialIndex.FlagStoreFeatureGeometries)
mainland_idx.addFeatures(mainland_feats)
mainland_vertices = {}
seam_pts_mainland = []
for mf in mainland_feats:
check_feedback()
mg = mf.geometry()
if not mg or mg.isEmpty():
continue
mainland_vertices.setdefault(mf.id(), [])
for v in mg.vertices():
check_feedback()
mainland_vertices[mf.id()].append(QgsPointXY(v))
x = float(v.x())
if _near_dateline_deg(x, tolerance):
seam_pts_mainland.append(QgsPointXY(x, float(v.y())))
with edit(disconnected_layer):
check_feedback()
new_features = []
island_vertices_cache = {}
for island in active_islands:
check_feedback()
island_group = island_groups.get(island, [])
if bool(seam_pts_mainland) and any(_virtually_connected_across_dateline(f, seam_pts_mainland, tolerance) for f in island_group):
skipped_fids.update(f.id() for f in island_group)
continue # do not create a connector, treat as connected on a globe
min_dist = float("inf")
closest_island_feat = None
closest_island_p = None
closest_main_p = None
for island_feat in island_group:
check_feedback()
nn_ids = mainland_idx.nearestNeighbor(island_feat.geometry(), 1, tolerance)
if not nn_ids:
continue
mainland_fid = nn_ids[0]
if island_feat.id() not in island_vertices_cache:
island_vertices_cache[island_feat.id()] = [
QgsPointXY(v) for v in island_feat.geometry().vertices()
]
island_points = island_vertices_cache.get(island_feat.id())
main_points = mainland_vertices.get(mainland_fid)
if not island_points or not main_points:
continue
if len(island_points) <= 1 or len(main_points) <= 1:
continue
for p1 in (island_points[0], island_points[-1]):
check_feedback()
for p2 in (main_points[0], main_points[-1]):
check_feedback()
d = DISTANCE_AREA.measureLine(p1, p2)
if d < min_dist:
min_dist = d
closest_island_feat = island_feat
closest_island_p = p1
closest_main_p = p2
if min_dist != float("inf") and closest_island_feat is not None:
connector = QgsFeature(disconnected_layer.fields())
connector.setGeometry(
QgsGeometry.fromPolylineXY([closest_island_p, closest_main_p])
)
connector.setAttributes(closest_island_feat.attributes())
new_features.append(connector)
if new_features:
disconnected_layer.addFeatures(new_features)
disconnected_layer, islands = disconnected_islands.run(island_tol)
tolerance += snapping_tolerance
remove_features_by_expression(disconnected_layer, "networkGrp = -1")
update_progress("- Reconnected disconnected islands (antimeridian-aware)")
return disconnected_layer
@cancel_on_entry
def fix_overlaps(layer):
spatial_index = QgsSpatialIndex(
layer.getFeatures(),
flags=QgsSpatialIndex.FlagStoreFeatureGeometries
)
checked = set()
with edit(layer):
for feature in layer.getFeatures():
check_feedback()
fid = feature.id()
feature_geom = feature.geometry()
neighbor_ids = spatial_index.intersects(feature_geom.boundingBox())
for neighbor_id in neighbor_ids:
check_feedback()
# skip already checked feature combos
if fid >= neighbor_id or (fid, neighbor_id) in checked:
continue
checked.add((fid, neighbor_id))
neighbor_geom = layer.getFeature(neighbor_id).geometry()
# create the geometry engine and prepare geometry
geom_engine = QgsGeometry.createGeometryEngine(
feature_geom.constGet()
)
geom_engine.prepareGeometry()
# check if there is a partial overlap
if geom_engine.overlaps(neighbor_geom.constGet()):
inter = feature_geom.intersection(neighbor_geom)
if inter and not inter.isEmpty():
trimmed = feature_geom.difference(inter)
if trimmed and not trimmed.isEmpty():
layer.changeGeometry(fid, trimmed)
# check if feature contains neighbor
if geom_engine.contains(neighbor_geom.constGet()):
layer.deleteFeature(neighbor_id)
# check if neighbor contains feature
if geom_engine.within(neighbor_geom.constGet()):
layer.deleteFeature(fid)
@cancel_on_entry
def fix_null_link_ids(layer, valid_link_ids):
for feat in layer.getFeatures(
QgsFeatureRequest().setFilterExpression("LinkId IS NULL")
):
check_feedback()
feat["LinkId"] = valid_link_ids.pop(0)
layer.updateFeature(feat)
update_progress("- Fixed null link ids")
@cancel_on_entry
def fix_nonsense_link_ids(layer, link_id_max, valid_link_ids):
invalid_link_id_range_expr = f"LinkId > {link_id_max} or LinkId < 1"
for feat in layer.getFeatures(
QgsFeatureRequest().setFilterExpression(
invalid_link_id_range_expr
)
):
check_feedback()
feat["LinkId"] = valid_link_ids.pop(0)
layer.updateFeature(feat)
update_progress("- Fixed nonsense link ids")
@cancel_on_entry
def fix_duplicate_link_ids(layer, valid_link_ids, raw_ids):
duplicate_ids = [
item for item, count in Counter(raw_ids).items() if count > 1
]
for dupe_id in duplicate_ids:
check_feedback()
equals_dupe_id_expr = f"LinkId = {dupe_id}"
for feat in list(
layer.getFeatures(
QgsFeatureRequest().setFilterExpression(
equals_dupe_id_expr
)
)
)[1:]:
check_feedback()
feat["LinkId"] = valid_link_ids.pop(0)
layer.updateFeature(feat)
update_progress("- Fixed duplicate link ids")
@cancel_on_entry
def fix_link_ids(layer):
link_id_max = layer.featureCount() * 2
raw_ids = list(
flatten_collection(QgsVectorLayerUtils.getValues(layer, "LinkId"))
)
used_ids = set(raw_ids)
valid_link_ids = list(set(range(1, link_id_max)) - used_ids)
with edit(layer):
# fix null link ids
fix_null_link_ids(layer, valid_link_ids)
# fix nonsense link ids
fix_nonsense_link_ids(layer, link_id_max, valid_link_ids)
# fix duplicate link ids
fix_duplicate_link_ids(layer, valid_link_ids, raw_ids)
@cancel_on_entry
def fix_feature_names(layer, channel_layer):
# 1) Build canonicalized name counts (trim + upper) to find duplicates robustly
name_counts = Counter()
for f in layer.getFeatures():
check_feedback()
n = f["Name"]
if n is not None:
s = str(n).strip()
if s:
name_counts[s.upper()] += 1
duplicate_set = {n for n, c in name_counts.items() if c > 1}
# 2) Single edit session: standardize, fix dupes, fill missing
with edit(layer):
for feature in layer.getFeatures():
check_feedback()
link_id = f"{int(feature['LinkId'])}"
cur_name = feature["Name"]
# Missing or empty name -> derive from channel_layer or fallback
if cur_name is None or not str(cur_name).strip():
sds_name, district_code = _infer_channel_name(feature, channel_layer)
if sds_name and district_code:
new_name = f"{sds_name} {district_code} {link_id}"
else:
new_name = f"FEATURE {link_id}"
else:
base = str(cur_name).strip().upper()
if base in duplicate_set:
new_name = f"{base} {link_id}"
else:
new_name = base
if new_name is not None and new_name != cur_name:
feature["Name"] = new_name
layer.updateFeature(feature)
update_progress("- Standardized feature names (trim/upper), de-duplicated with LinkId, filled null/empty")
@cancel_on_entry
def _infer_channel_name(feature, channel_layer):
"""
Returns (SDSFEATURENAME_UPPER, usaceDistrictCode_UPPER) or (None, None)
Uses bbox prefilter + precise intersects check.
"""
g = feature.geometry()
if g is None or g.isEmpty():
return None, None
request = QgsFeatureRequest().setFilterRect(g.boundingBox())
for overlap in channel_layer.getFeatures(request):
check_feedback()
og = overlap.geometry()
if og and not og.isEmpty() and g.intersects(og):
names = overlap.fields().names()
if "SDSFEATURENAME" in names and "usaceDistrictCode" in names:
sds_raw = overlap["SDSFEATURENAME"]
dist_raw = overlap["usaceDistrictCode"]
sds = str(sds_raw).strip().upper() if sds_raw is not None else None
dist = str(dist_raw).strip().upper() if dist_raw is not None else None
return sds if sds else None, dist if dist else None
return None, None
@cancel_on_entry
def set_ehydro_and_cpt_attributes(layer, ncf_layer):
add_unique_field(layer, "ChannelRea", QVariant.String)
idx = QgsSpatialIndex(ncf_layer.getFeatures(), flags=QgsSpatialIndex.FlagStoreFeatureGeometries)
chan_idx = layer.fields().indexFromName("ChannelRea")
depth_idx = layer.fields().indexFromName("DepthFt")
def get_len_mi(geom):
return DISTANCE_AREA.convertLengthMeasurement(
geom.length(), QgsUnitTypes.DistanceMiles
)
with edit(layer):
for line_feat in layer.getFeatures():
check_feedback()
line_geom = line_feat.geometry()
if line_geom is None or line_geom.isEmpty():
line_feat.setAttribute(chan_idx, None)
layer.updateFeature(line_feat)
continue
line_len_mi = get_len_mi(line_geom)
if line_len_mi <= 0.0:
line_feat.setAttribute(chan_idx, None)
layer.updateFeature(line_feat)
continue
best_feat = None
best_ratio = 0.0
# candidate polygons whose bbox intersects this line
cand_ids = idx.intersects(line_geom.boundingBox())
for fid in cand_ids:
check_feedback()
ncf_feat = ncf_layer.getFeature(fid)
poly_geom = ncf_feat.geometry()
if poly_geom is None or poly_geom.isEmpty():
continue
inter = poly_geom.intersection(line_geom)
if inter is None or inter.isEmpty():
continue
overlap_len_mi = get_len_mi(inter)
if overlap_len_mi <= 0.0:
continue
overlap_ratio = overlap_len_mi / line_len_mi
if overlap_ratio > best_ratio:
best_ratio = overlap_ratio
best_feat = ncf_feat
# Decide once per line, after examining all candidates
if best_feat is not None and best_ratio > 0.5:
try:
line_feat.setAttribute(chan_idx, best_feat["channelreachidpk"])
if depth_idx != -1:
line_feat.setAttribute(
depth_idx,
(best_feat["depthmaintained"] or 99)
)
except:
line_feat.setAttribute(chan_idx, best_feat["channelrea"])
if depth_idx != -1:
line_feat.setAttribute(
depth_idx,
(best_feat["depthmaint"] or 99)
)
else:
line_feat.setAttribute(chan_idx, None)
layer.updateFeature(line_feat)
update_progress("- Joined eHydro & CPT attributes by location (> 50% line overlap)")
@cancel_on_entry
def add_lat_lon_attributes(layer):
lat_lon_fields = [
QgsField("Latitude", QVariant.Double),
QgsField("Longitude", QVariant.Double)
]
layer.dataProvider().addAttributes(lat_lon_fields)
layer.updateFields()
with edit(layer):
for feature in layer.getFeatures():
check_feedback()
point = QgsPointXY(QgsGeometry.asPoint(feature.geometry()))
feature["Longitude"] = float('%.6f' % (point.x()))
feature["Latitude"] = float('%.6f' % (point.y()))
layer.updateFeature(feature)
update_progress("- Lat-lon attributes created & assigned to nodes")
@cancel_on_entry
def assign_international_link_depths(layer):
international_links_expr = "LinkType = 'International' or LinkType = 'Internat River'"
for feat in layer.getFeatures(
QgsFeatureRequest().setFilterExpression(
international_links_expr
)
):
check_feedback()
feat["DepthFt"] = 99
layer.updateFeature(feat)
@cancel_on_entry
def assign_all_other_link_depths(layer):
invalid_depth_values = [None, '', 0]
for feature in layer.getFeatures():
check_feedback()
if feature["DepthFt"] in invalid_depth_values:
neighbor_expr = (
f"(i = '{feature['i']}' OR "
f"j = '{feature['i']}' OR "
f"i = '{feature['j']}' OR "
f"j = '{feature['j']}') AND "
f"DepthFt IS NOT NULL AND "