-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlayer.py
executable file
·1665 lines (1544 loc) · 70.5 KB
/
layer.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 -*-
"""Application layers"""
import os
import math
import re
from collections import defaultdict
import logging
from qgis.core import *
from PyQt4.QtCore import QVariant
import hgwnames
import osm
import setup
import translate
from report import instance as report
log = logging.getLogger(setup.app_name + "." + __name__)
BUFFER_SIZE = 512
is_inside = lambda f1, f2: \
f2.geometry().contains(f1.geometry()) or f2.geometry().overlaps(f1.geometry())
get_attributes = lambda feat: \
dict([(i, feat[i]) for i in range(len(feat.fields().toList()))])
class Point(QgsPoint):
"""Extends QgsPoint with some utility methods"""
def __init__(self, arg1, arg2=None):
if arg2 is None:
super(Point, self).__init__(arg1[0], arg1[1])
else:
super(Point, self).__init__(arg1, arg2)
def boundingBox(self, radius):
"""Returns a bounding box of 2*radius centered in point."""
return QgsRectangle(self.x() - radius, self.y() - radius,
self.x() + radius, self.y() + radius)
def get_angle(self, geom):
"""
For the vertex in a geometry nearest to this point, give the angle
between its adjacent vertexs.
Args:
geom (QgsGeometry): Geometry to test.
Returns:
(float) Angle between the vertex and their adjacents,
"""
(point, ndx, ndxa, ndxb, dist) = geom.closestVertex(self)
va = geom.vertexAt(ndxa) # previous vertex
vb = geom.vertexAt(ndxb) # next vertex
angle = abs(point.azimuth(va) - point.azimuth(vb))
return angle
def get_corner_context(self, geom, acute_thr=setup.acute_thr,
straight_thr=setup.straight_thr, cath_thr=setup.dist_thr):
"""
For the vertex in a geometry nearest to this point, give context to
determine if it is a corner (the angle differs by more than straight_thr
of 180 and if the distance from the vertex to the segment formed by
their adjacents is greater than cath_thr).
Args:
geom (QgsGeometry): Geometry to test.
acute_thr (float): Acute angle threshold.
straight_thr (float): Straight angle threshold.
cath_thr (float): Cathetus threshold.
Returns:
(float) Angle between the vertex and their adjacents.
(bool) True if the angle is too low (< acute_thr).
(bool) True for a corner
(float) Distance from the vertex to the segment formed by their adjacents.
"""
(point, ndx, ndxa, ndxb, dist) = geom.closestVertex(self)
va = geom.vertexAt(ndxa) # previous vertex
vb = geom.vertexAt(ndxb) # next vertex
angle = abs(point.azimuth(va) - point.azimuth(vb))
a = abs(va.azimuth(point) - va.azimuth(vb))
h = math.sqrt(va.sqrDist(point))
c = abs(h * math.sin(math.radians(a)))
is_corner = abs(180 - angle) > straight_thr and c > cath_thr
is_acute = angle < acute_thr if angle < 180 else 360 - angle < acute_thr
return (angle, is_acute, is_corner, c)
def get_spike_context(self, geom, acute_thr=setup.acute_inv,
straight_thr=setup.straight_thr, threshold=setup.dist_inv):
"""
For the vertex in a geometry nearest to this point, give context to
determine if its a zig-zag or a spike. It's a zig-zag if both the angles
of this vertex and the closest adjacents are acute. It's a spike if the
angle of this vertex is acute and the angle of the closest vertex is
not straight.
Args:
geom (QgsGeometry): Geometry to test.
acute_thr (float): Acute angle threshold.
straight_thr (float): Straight angle threshold.
threshold (float): # Filter for angles.
Returns:
(float) angle_v = angle between the vertex and their adjacents.
(float) angle_a = angle between the closest adjacent and their adjacents.
(int) ndx = index of the vertex
(int) ndxa = index of the closest adjacent
(bool) is_acute = True if the angle is too low (< acute_thr).
(bool) is_zigzag = True if both angle_v and angle_a are acute and
the distance from va to the segment v-vb is lower than threshold.
(bool) is_spike = True if is_acute and angle_a is not straight and
the distance from va to the segment v-vb is lower than threshold.
(QgsPoint) vx = projection of va over the segment v-vb.
"""
(v, ndx, ndxa, ndxb, dist) = geom.closestVertex(self)
va = geom.vertexAt(ndxa) # previous vertex
vb = geom.vertexAt(ndxb) # next vertex
angle_v = abs(v.azimuth(va) - v.azimuth(vb))
is_acute = angle_v < acute_thr if angle_v < 180 else 360 - angle_v < acute_thr
if not is_acute:
return angle_v, None, ndx, None, is_acute, False, False, None
dist_a = math.sqrt(va.sqrDist(v))
dist_b = math.sqrt(vb.sqrDist(v))
if dist_a > dist_b: # set va as the closest adjacent
vc = va
dist_c = dist_a
va = vb
dist_a = dist_b
ndxa = ndxb
vb = vc
dist_b = dist_c
angle_a = Point(va).get_angle(geom)
c = abs(math.sin(math.radians(angle_v))) * dist_a
is_zigzag = angle_a < acute_thr and c < threshold
is_spike = abs(180 - angle_a) > straight_thr and c < threshold
if is_zigzag:
return angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, None
gamma = abs(90 + angle_v - angle_a)
dx = abs(dist_a * (math.cos(math.radians(angle_v)) \
+ math.tan(math.radians(gamma)) * math.sin(math.radians(angle_v))))
x = v.x() + (vb.x() - v.x()) * dx / dist_b
y = v.y() + (vb.y() - v.y()) * dx / dist_b
vx = QgsPoint(x, y)
return angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx
class BaseLayer(QgsVectorLayer):
"""Base class for application layers"""
def __init__(self, path, baseName, providerLib = "ogr"):
super(BaseLayer, self).__init__(path, baseName, providerLib)
self.writer = self.dataProvider()
self.rename={}
self.resolve={}
self.reference_matchs={}
self.keep = False
@staticmethod
def create_shp(name, crs, fields=QgsFields(), geom_type=QGis.WKBMultiPolygon):
writer = QgsVectorFileWriter(name, 'UTF-8', fields, geom_type, crs, 'ESRI Shapefile')
if writer.hasError() != QgsVectorFileWriter.NoError:
msg = _("Error when creating shapefile: '%s'") % writer.errorMessage()
raise IOError(msg)
return writer
@staticmethod
def delete_shp(path):
QgsVectorFileWriter.deleteShapeFile(path)
path = os.path.splitext(path)[0] + '.cpg'
if os.path.exists(path):
os.remove(path)
def copy_feature(self, feature, rename=None, resolve=None):
"""
Return a copy of feature renaming attributes or resolving xlink references.
Args:
feature (QgsFeature): Source feature
rename (dict): Translation of attributes names
resolve (dict): xlink reference fields
Examples:
With this:
>>> rename = {'spec': 'specification'}
>>> resolve = {
... 'PD_id': ('component_href', '[\w\.]+PD[\.0-9]+'),
... 'TN_id': ('component_href', '[\w\.]+TN[\.0-9]+'),
... 'AU_id': ('component_href', '[\w\.]+AU[\.0-9]+')
... }
You get:
>>> original_attributes = ['localId', 'specification', 'component_href']
>>> original_values = [
... '38.012.1.12.0295603CS6109N',
... 'Parcel',
... '(3:#ES.SDGC.PD.38.012.38570,#ES.SDGC.TN.38.012.1,#ES.SDGC.AU.38.012)'
... ]
>>> final_attributes = ['localId', 'spec', 'PD_id', 'TN_id', 'AU_id']
>>> final_values = [
... '38.012.1.12.0295603CS6109N',
... 'Parcel',
... 'ES.SDGC.PD.38.012.38570',
... 'ES.SDGC.TN.38.012.1',
... 'ES.SDGC.AU.38.012'
... ]
"""
rename = rename if rename is not None else self.rename
resolve = resolve if resolve is not None else self.resolve
if self.pendingFields().isEmpty():
self.writer.addAttributes(feature.fields().toList())
self.updateFields()
dst_ft = QgsFeature(self.pendingFields())
dst_ft.setGeometry(feature.geometry())
src_attrs = [f.name() for f in feature.fields()]
for field in self.pendingFields().toList():
dst_attr = field.name()
if dst_attr in resolve:
(src_attr, reference_match) = resolve[dst_attr]
match = re.search(reference_match, feature[src_attr])
if match:
dst_ft[dst_attr] = match.group(0)
else:
src_attr = dst_attr
if dst_attr in rename:
src_attr = rename[dst_attr]
if src_attr in src_attrs:
dst_ft[dst_attr] = feature[src_attr]
return dst_ft
def append(self, layer, rename=None, resolve=None, query=None, **kwargs):
"""Copy all features from layer.
Args:
layer (QgsVectorLayer): Source layer
rename (dict): Translation of attributes names
resolve (dict): xlink reference fields
query (func): function with args feature and kwargs that returns
a boolean deciding if each feature will be included or not
kwargs: aditional arguments for query function
Examples:
>>> query = lambda feat, kwargs: feat['foo']=='bar'
Will copy only features with a value 'bar' in the field 'foo'.
>>> query = lambda feat, kwargs: layer.is_inside(feat, kwargs['zone'])
Will copy only features inside zone.
See also copy_feature().
"""
self.setCrs(layer.crs())
total = 0
to_add = []
for feature in layer.getFeatures():
if not query or query(feature, kwargs):
to_add.append(self.copy_feature(feature, rename, resolve))
total += 1
if len(to_add) > BUFFER_SIZE:
self.writer.addFeatures(to_add)
to_add = []
if len(to_add) > 0:
self.writer.addFeatures(to_add)
if total:
log.debug (_("Loaded %d features in '%s' from '%s'"), total,
self.name(), layer.name())
def reproject(self, target_crs=None):
"""Reproject all features in this layer to a new CRS.
Args:
target_crs (QgsCoordinateReferenceSystem): New CRS to apply.
"""
if target_crs is None:
target_crs = QgsCoordinateReferenceSystem(4326)
crs_transform = QgsCoordinateTransform(self.crs(), target_crs)
to_change = {}
for feature in self.getFeatures():
geom = QgsGeometry(feature.geometry())
geom.transform(crs_transform)
to_change[feature.id()] = geom
if len(to_change) > BUFFER_SIZE:
self.writer.changeGeometryValues(to_change)
to_change = {}
if len(to_change) > 0:
self.writer.changeGeometryValues(to_change)
self.setCrs(target_crs)
self.updateExtents()
if self.writer.storageType() == 'ESRI Shapefile':
path = self.writer.dataSourceUri().split('|')[0]
path = os.path.splitext(path)[0]
if os.path.exists(path + '.prj'):
os.remove(path + '.prj')
if os.path.exists(path + '.qpj'):
os.remove(path + '.qpj')
log.debug(_("Reprojected the '%s' layer to '%s' CRS"),
self.name(), target_crs.description())
def join_field(self, source_layer, target_field_name, join_field_name,
field_names_subset, prefix = ""):
"""
Replaces qgis table join mechanism becouse I'm not able to work with it
in standalone script mode (without GUI).
Args:
source_layer (QgsVectorLayer): Source layer.
target_field_name (str): Join field in the target layer.
join_fieldsName (str): Join field in the source layer.
field_names_subset (list): List of field name strings for the target layer.
prefix (str): An optional prefix to add to the target fields names
"""
fields = []
target_attrs = [f.name() for f in self.pendingFields()]
for attr in field_names_subset:
field = source_layer.pendingFields().field(attr)
field.setName(prefix + attr)
if field.name() not in target_attrs:
if field.length() > 254:
field.setLength(254)
fields.append(field)
self.writer.addAttributes(fields)
self.updateFields()
source_values = {}
for feature in source_layer.getFeatures():
source_values[feature[join_field_name]] = \
{attr: feature[attr] for attr in field_names_subset}
total = 0
to_change = {}
for feature in self.getFeatures():
attrs = {}
for attr in field_names_subset:
fieldId = feature.fieldNameIndex(prefix + attr)
value = None
if feature[target_field_name] in source_values:
value = source_values[feature[target_field_name]][attr]
attrs[fieldId] = value
to_change[feature.id()] = attrs
total += 1
if len(to_change) > BUFFER_SIZE:
self.writer.changeAttributeValues(to_change)
to_change = {}
if len(to_change) > 0:
self.writer.changeAttributeValues(to_change)
if total:
log.debug(_("Joined '%s' to '%s'"), source_layer.name(),
self.name())
def translate_field(self, field_name, translations, clean=True):
"""
Transform the values of a field
Args:
field_name (str): Name of the field to transform
translations (dict): A dictionary used to transform field values
clean (bool): If true (default), delete features without translation
"""
to_clean = []
field_ndx = self.pendingFields().fieldNameIndex(field_name)
if field_ndx >= 0:
to_change = {}
for feat in self.getFeatures():
value = feat[field_name]
if value in translations and translations[value] != '':
new_value = translations[value]
feat[field_name] = new_value
to_change[feat.id()] = get_attributes(feat)
elif clean:
to_clean.append(feat.id())
self.writer.changeAttributeValues(to_change)
if len(to_clean):
self.writer.deleteFeatures(to_clean)
return len(to_clean)
def get_index(self):
"""Returns a QgsSpatialIndex of all features in this layer (overpass
QGIS exception for void layers)"""
if self.featureCount() > 0:
return QgsSpatialIndex(self.getFeatures())
else:
return QgsSpatialIndex()
def bounding_box(self):
bbox = None
for f in self.getFeatures():
if bbox is None:
bbox = f.geometry().boundingBox()
else:
bbox.combineExtentWith(f.geometry().boundingBox())
if bbox:
p1 = QgsGeometry().fromPoint(Point(bbox.xMinimum(), bbox.yMinimum()))
p2 = QgsGeometry().fromPoint(Point(bbox.xMaximum(), bbox.yMaximum()))
target_crs = QgsCoordinateReferenceSystem(4326)
crs_transform = QgsCoordinateTransform(self.crs(), target_crs)
p1.transform(crs_transform)
p2.transform(crs_transform)
bbox = [p1.asPoint().y(), p1.asPoint().x(), p2.asPoint().y(), p2.asPoint().x()]
bbox = '{:.8f},{:.8f},{:.8f},{:.8f}'.format(*bbox)
return bbox
def export(self, path, driver_name="ESRI Shapefile", overwrite=True):
"""Write layer to file
Args:
path (str): Path of the output file
driver_name (str): Defaults to ESRI Shapefile.
overwrite (bool): Defaults to True
"""
if os.path.exists(path) and overwrite:
if driver_name == 'ESRI Shapefile':
QgsVectorFileWriter.deleteShapeFile(path)
else:
os.remove(path)
return QgsVectorFileWriter.writeAsVectorFormat(self, path, "utf-8",
self.crs(), driver_name) == QgsVectorFileWriter.NoError
def to_osm(self, tags_translation=translate.all_tags, data=None, upload='never'):
"""
Export this layer to an Osm data set
Args:
tags_translation (function): Function to translate fields to tags.
By defaults convert all fields.
data (Osm): OSM data set to append. By default creates a new one.
upload (str): upload attribute of the osm dataset, default 'never'
Returns:
Osm: OSM data set
"""
if data is None:
data = osm.Osm(upload)
nodes = ways = relations = 0
else:
nodes = len(data.nodes)
ways = len(data.ways)
relations = len(data.relations)
for feature in self.getFeatures():
geom = feature.geometry()
e = None
if geom.wkbType() == QGis.WKBPolygon:
pol = geom.asPolygon()
if len(pol) == 1:
e = data.Way(pol[0])
else:
e = data.Polygon(pol)
elif geom.wkbType() == QGis.WKBMultiPolygon:
e = data.MultiPolygon(geom.asMultiPolygon())
elif geom.wkbType() == QGis.WKBPoint:
e = data.Node(geom.asPoint())
else:
msg = _("Detected a %s geometry in the '%s' layer") % \
(geom.wkbType(), self.name())
log.warning(msg)
report.warnings.add(msg)
if e: e.tags.update(tags_translation(feature))
for (key, value) in setup.changeset_tags.items():
data.tags[key] = value
if self.source_date:
data.tags['source:date'] = self.source_date
log.debug(_("Loaded %d nodes, %d ways, %d relations from '%s' layer"),
len(data.nodes) - nodes, len(data.ways) - ways,
len(data.relations) - relations, self.name())
return data
def search(self, expression):
"""Returns a features iterator for this search expression"""
exp = QgsExpression(expression)
request = QgsFeatureRequest(exp)
return self.getFeatures(request)
def count(self, expression):
"""Returns number of features for this search expression"""
exp = QgsExpression(expression)
request = QgsFeatureRequest(exp)
count = 0
for f in self.getFeatures(request):
count += 1
return count
class PolygonLayer(BaseLayer):
"""Base class for polygon layers"""
def __init__(self, path, baseName, providerLib = "ogr"):
super(PolygonLayer, self).__init__(path, baseName, providerLib)
self.dup_thr = setup.dup_thr # Distance in meters to merge nearest vertex.
self.cath_thr = setup.dist_thr # Threshold in meters for cathetus reduction
self.straight_thr = setup.straight_thr # Threshold in degrees from straight angle to delete a vertex
self.dist_thr = setup.dist_thr # Threshold for topological points.
@staticmethod
def get_multipolygon(feature):
"""Returns feature geometry always as a multipolgon"""
if isinstance(feature, QgsFeature):
geom = feature.geometry()
else:
geom = feature
if geom.wkbType() == QGis.WKBPolygon:
return [geom.asPolygon()]
return geom.asMultiPolygon()
@staticmethod
def get_vertices_list(feature):
"""Returns list of all distinct vertices in feature geometry"""
return [point for part in PolygonLayer.get_multipolygon(feature) \
for ring in part for point in ring[0:-1]]
@staticmethod
def get_outer_vertices(feature):
"""Returns list of all distinct vertices in feature geometry outer rings"""
return [point for part in PolygonLayer.get_multipolygon(feature) \
for point in part[0][0:-1]]
@staticmethod
def merge_adjacent_features(group):
"""Combine all geometries in group of features"""
geom = group[0].geometry()
for p in group[1:]:
geom = geom.combine(p.geometry())
return geom
def get_area(self):
"""Returns total area"""
return sum([f.geometry().area() for f in self.getFeatures()])
def explode_multi_parts(self, request=QgsFeatureRequest()):
"""
Creates a new WKBPolygon feature for each part of any WKBMultiPolygon
feature in request. This avoid relations with may 'outer' members in
OSM data set. From this moment, localId will not be a unique identifier
for buildings.
"""
to_clean = []
to_add = []
for feature in self.getFeatures(request):
geom = feature.geometry()
if geom.wkbType() == QGis.WKBMultiPolygon:
for part in geom.asMultiPolygon():
feat = QgsFeature(feature)
feat.setGeometry(QgsGeometry.fromPolygon(part))
to_add.append(feat)
to_clean.append(feature.id())
if to_clean:
self.writer.deleteFeatures(to_clean)
self.writer.addFeatures(to_add)
log.debug(_("%d multi-polygons splited into %d polygons in "
"the '%s' layer"), len(to_clean), len(to_add),
self.name())
report.values['multipart_geoms_' + self.name()] = len(to_clean)
report.values['exploded_parts_' + self.name()] = len(to_add)
def get_parents_per_vertex_and_geometries(self):
"""
Returns:
(dict) parent fids for each vertex, (dict) geometry for each fid.
"""
parents_per_vertex = defaultdict(list)
geometries = {}
for feature in self.getFeatures():
geom = QgsGeometry(feature.geometry())
geometries[feature.id()] = geom
for point in self.get_vertices_list(feature):
parents_per_vertex[point].append(feature.id())
return (parents_per_vertex, geometries)
def get_adjacents_and_geometries(self):
"""
Returns:
(list) groups of adjacent polygons
"""
parents_per_vertex, geometries = self.get_parents_per_vertex_and_geometries()
adjs = []
for (point, parents) in parents_per_vertex.items():
if len(parents) > 1:
for fid in parents:
geom = geometries[fid]
(point, ndx, ndxa, ndxb, dist) = geom.closestVertex(point)
next = geom.vertexAt(ndxb)
parents_next = parents_per_vertex[next]
common = set(x for x in parents if x in parents_next)
if len(common) > 1:
adjs.append(common)
adjs = list(adjs)
groups = []
while adjs:
group = set(adjs.pop())
lastlen = -1
while len(group) > lastlen:
lastlen = len(group)
for adj in adjs[:]:
if len({p for p in adj if p in group}) > 0:
group |= adj
adjs.remove(adj)
groups.append(group)
return (groups, geometries)
def topology(self):
"""For each vertex in a polygon layer, adds it to nearest segments."""
threshold = self.dist_thr # Distance threshold to create nodes
dup_thr = self.dup_thr
straight_thr = self.straight_thr
tp = 0
td = 0
if log.getEffectiveLevel() <= logging.DEBUG:
debshp = DebugWriter("debug_topology.shp", self)
geometries = {f.id(): QgsGeometry(f.geometry()) for f in self.getFeatures()}
index = self.get_index()
to_change = {}
nodes = set()
for (gid, geom) in geometries.items():
for point in frozenset(self.get_outer_vertices(geom)):
if point not in nodes:
area_of_candidates = Point(point).boundingBox(threshold)
fids = index.intersects(area_of_candidates)
for fid in fids:
g = QgsGeometry(geometries[fid])
(p, ndx, ndxa, ndxb, dist_v) = g.closestVertex(point)
(dist_s, closest, vertex) = g.closestSegmentWithContext(point)
va = g.vertexAt(ndxa)
vb = g.vertexAt(ndxb)
note = ""
if dist_v == 0:
dist_a = va.sqrDist(point)
dist_b = vb.sqrDist(point)
if dist_a < dup_thr**2:
g.deleteVertex(ndxa)
note = "dupe refused by isGeosValid"
if g.isGeosValid():
note = "Merge dup. %.10f %.5f,%.5f->%.5f,%.5f" % \
(dist_a, va.x(), va.y(), point.x(), point.y())
nodes.add(p)
nodes.add(va)
td += 1
if dist_b < dup_thr**2:
g.deleteVertex(ndxb)
note = "dupe refused by isGeosValid"
if g.isGeosValid():
note = "Merge dup. %.10f %.5f,%.5f->%.5f,%.5f" % \
(dist_b, vb.x(), vb.y(), point.x(), point.y())
nodes.add(p)
nodes.add(vb)
td += 1
elif dist_v < dup_thr**2:
g.moveVertex(point.x(), point.y(), ndx)
note = "dupe refused by isGeosValid"
if g.isGeosValid():
note = "Merge dup. %.10f %.5f,%.5f->%.5f,%.5f" % \
(dist_v, p.x(), p.y(), point.x(), point.y())
nodes.add(p)
td += 1
elif dist_s < threshold**2 and closest != va and closest != vb:
va = g.vertexAt(vertex)
vb = g.vertexAt(vertex - 1)
angle = abs(point.azimuth(va) - point.azimuth(vb))
note = "Topo refused by angle: %.2f" % angle
if abs(180 - angle) <= straight_thr:
note = "Topo refused by insertVertex"
if g.insertVertex(point.x(), point.y(), vertex):
note = "Topo refused by isGeosValid"
if g.isGeosValid():
note = "Add topo %.6f %.5f,%.5f" % \
(dist_s, point.x(), point.y())
tp += 1
if note.startswith('Merge') or note.startswith('Add'):
to_change[fid] = g
geometries[fid] = g
if note and log.getEffectiveLevel() <= logging.DEBUG:
debshp.add_point(point, note)
if len(to_change) > BUFFER_SIZE:
self.writer.changeGeometryValues(to_change)
to_change = {}
if len(to_change) > 0:
self.writer.changeGeometryValues(to_change)
if td:
log.debug(_("Merged %d close vertices in the '%s' layer"), td,
self.name())
report.values['vertex_close_' + self.name()] = td
if tp:
log.debug(_("Created %d topological points in the '%s' layer"),
tp, self.name())
report.values['vertex_topo_' + self.name()] = tp
def delete_invalid_geometries(self):
"""
Delete invalid geometries testing if any of it acute angle vertex could
be deleted.
Also removes zig-zag and spike vertex (see Point.get_spike_context).
"""
if log.getEffectiveLevel() <= logging.DEBUG:
fpath = os.path.join(os.path.dirname(self.writer.dataSourceUri()),
'debug_notvalid.shp')
debshp = QgsVectorFileWriter(fpath, 'UTF-8', QgsFields(),
QGis.WKBPolygon, self.crs(), 'ESRI Shapefile')
debshp2 = DebugWriter("debug_spikes.shp", self)
to_change = {}
to_clean = []
to_move = {}
rings = 0
zz = 0
spikes = 0
geometries = {f.id(): QgsGeometry(f.geometry()) for f in self.getFeatures()}
for fid, geom in geometries.items():
badgeom = False
for i, ring in enumerate(geom.asPolygon()):
if badgeom: break
skip = False
for n, v in enumerate(ring[0:-1]):
angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \
Point(v).get_spike_context(geom)
if skip or not is_acute:
skip = False
continue
g = QgsGeometry().fromPolygon([ring])
f = QgsFeature(QgsFields())
f.setGeometry(QgsGeometry(g))
g.deleteVertex(n)
if not g.isGeosValid() or g.area() < setup.min_area:
if i > 0:
rings += 1
geom.deleteRing(i)
to_change[fid] = geom
geometries[fid] = geom
if log.getEffectiveLevel() <= logging.DEBUG:
debshp.addFeature(f)
else:
badgeom = True
to_clean.append(fid)
if fid in to_change: del to_change[fid]
if log.getEffectiveLevel() <= logging.DEBUG:
debshp.addFeature(f)
break
if len(ring) > 4: # (can delete vertexs)
va = geom.vertexAt(ndxa)
if is_zigzag:
g = QgsGeometry(geom)
if ndxa > ndx:
g.deleteVertex(ndxa)
g.deleteVertex(ndx)
skip = True
else:
g.deleteVertex(ndx)
g.deleteVertex(ndxa)
valid = g.isGeosValid()
if valid:
geom = g
zz += 1
to_change[fid] = g
geometries[fid] = geom
if log.getEffectiveLevel() <= logging.DEBUG:
debshp2.add_point(va, 'zza %d %d %d %f' % (fid, ndx, ndxa, angle_a))
debshp2.add_point(v, 'zz %d %d %d %s' % (fid, ndx, len(ring), valid))
elif is_spike:
g = QgsGeometry(geom)
to_move[va] = vx #!
g.moveVertex(vx.x(), vx.y(), ndxa)
g.deleteVertex(ndx)
valid = g.isGeosValid()
if valid:
spikes += 1
skip = ndxa > ndx
geom = g
to_change[fid] = g
geometries[fid] = geom
if log.getEffectiveLevel() <= logging.DEBUG:
debshp2.add_point(vx, 'vx %d %d' % (fid, ndx))
debshp2.add_point(va, 'va %d %d %d %f' % (fid, ndx, ndxa, angle_a))
debshp2.add_point(v, 'v %d %d %d %s' % (fid, ndx, len(ring), valid))
if to_move:
for fid, geom in geometries.items():
if fid in to_clean: continue
n = 0
v = geom.vertexAt(n)
while v != QgsPoint(0, 0):
if v in to_move:
g = QgsGeometry(geom)
vx = to_move[v]
if log.getEffectiveLevel() <= logging.DEBUG:
debshp2.add_point(v, 'mv %d %d' % (fid, n))
debshp2.add_point(vx, 'mvx %d %d' % (fid, n))
g.moveVertex(vx.x(), vx.y(), n)
if g.isGeosValid():
geom = g
to_change[fid] = g
n += 1
v = geom.vertexAt(n)
if to_change:
self.writer.changeGeometryValues(to_change)
if rings:
log.debug(_("Deleted %d invalid ring geometries in the '%s' layer"),
rings, self.name())
report.values['geom_rings_' + self.name()] = rings
if to_clean:
self.writer.deleteFeatures(to_clean)
log.debug(_("Deleted %d invalid geometries in the '%s' layer"),
len(to_clean), self.name())
report.values['geom_invalid_' + self.name()] = len(to_clean)
if zz:
log.debug(_("Deleted %d zig-zag vertices in the '%s' layer"), zz,
self.name())
report.values['vertex_zz_' + self.name()] = zz
if spikes:
log.debug(_("Deleted %d spike vertices in the '%s' layer"), spikes,
self.name())
report.values['vertex_spike_' + self.name()] = spikes
def simplify(self):
"""
Reduces the number of vertices in a polygon layer according to:
* Delete vertex if the angle with its adjacents is near of the straight
angle for less than 'straight_thr' degrees in all its parents.
* Delete vertex if the distance to the segment formed by its parents is
less than 'cath_thr' meters.
"""
if log.getEffectiveLevel() <= logging.DEBUG:
debshp = DebugWriter("debug_simplify.shp", self)
killed = 0
to_change = {}
# Clean non corners
(parents_per_vertex, geometries) = self.get_parents_per_vertex_and_geometries()
for pnt, parents in parents_per_vertex.items():
point = Point(pnt)
# Test if this vertex is a 'corner' in any of its parent polygons
for fid in parents:
geom = geometries[fid]
(angle, is_acute, is_corner, cath) = point.get_corner_context(geom)
debmsg = "angle=%.1f, is_acute=%s, is_corner=%s, cath=%.4f" % (angle,
is_acute, is_corner, cath)
if is_corner: break
msg = "Keep"
if not is_corner:
killed += 1 # delete the vertex from all its parents.
for fid in frozenset(parents):
g = QgsGeometry(geometries[fid])
(__, ndx, __, __, __) = g.closestVertex(point)
(ndxa, ndxb) = g.adjacentVertices(ndx)
v = g.vertexAt(ndx)
va = g.vertexAt(ndxa)
vb = g.vertexAt(ndxb)
invalid_ring = (v == va or v == vb or va == vb)
g.deleteVertex(ndx)
msg = "Refused"
if g.isGeosValid() and not invalid_ring:
parents.remove(fid)
geometries[fid] = g
to_change[fid] = g
msg = "Deleted"
if log.getEffectiveLevel() <= logging.DEBUG:
debshp.add_point(point, msg + ' ' + debmsg)
if to_change:
self.writer.changeGeometryValues(to_change)
log.debug(_("Simplified %d vertices in the '%s' layer"), killed,
self.name())
report.values['vertex_simplify_' + self.name()] = killed
def merge_adjacents(self):
"""Merge polygons with shared segments"""
(groups, geometries) = self.get_adjacents_and_geometries()
to_clean = []
to_change = {}
count_adj = 0
count_com = 0
for group in groups:
group = list(group)
count_adj += len(group)
geom = geometries[group[0]]
for fid in group[1:]:
geom = geom.combine(geometries[fid])
if geom.isMultipart():
for i, part in enumerate(geom.asMultiPolygon()):
g = QgsGeometry.fromPolygon(part)
to_change[group[i]] = g
count_com += 1
to_clean += group[i+1:]
else:
to_change[group[0]] = geom
to_clean += group[1:]
count_com += 1
if to_clean:
self.writer.changeGeometryValues(to_change)
self.writer.deleteFeatures(to_clean)
log.debug(_("%d adjacent polygons merged into %d polygons in the '%s' "
"layer"), count_adj, count_com, self.name())
def clean(self):
"""Delete invalid geometries and close vertices, add topological points
and simplify vertices."""
self.delete_invalid_geometries()
self.topology()
self.simplify()
class ParcelLayer(BaseLayer):
"""Class for cadastral parcels"""
def __init__(self, path="Polygon", baseName="cadastralparcel",
providerLib="memory", source_date=None):
super(ParcelLayer, self).__init__(path, baseName, providerLib)
if self.pendingFields().isEmpty():
self.writer.addAttributes([
QgsField('localId', QVariant.String, len=254),
QgsField('label', QVariant.String, len=254),
])
self.updateFields()
self.rename = {'localId': 'inspireId_localId'}
self.source_date = source_date
class ZoningLayer(PolygonLayer):
"""Class for cadastral zoning"""
def __init__(self, pattern='{}', path="Polygon", baseName="cadastralzoning",
providerLib="memory", source_date=None):
super(ZoningLayer, self).__init__(path, baseName, providerLib)
if self.pendingFields().isEmpty():
self.writer.addAttributes([
QgsField('localId', QVariant.String, len=254),
QgsField('label', QVariant.String, len=254),
QgsField('level', QVariant.String, len=254),
QgsField('levelName', QVariant.String, len=254),
])
self.updateFields()
self.rename = {'localId': 'inspireId_localId'}
self.source_date = source_date
self.task_number = 0
self.task_pattern = pattern
def set_tasks(self):
"""Assings a unique task label to each zone by overriding splited
multiparts and merged adjacent zones"""
to_change = {}
for i, zone in enumerate(self.getFeatures()):
zone['label'] = self.task_pattern.format(i + 1)
attr = get_attributes(zone)
to_change[zone.id()] = attr
self.writer.changeAttributeValues(to_change)
def append(self, layer, level=None):
"""Append features of layer with levelName 'M' for rustic or 'P' for urban"""
self.setCrs(layer.crs())
total = 0
to_add = []
multi = 0
final = 0
for feature in layer.getFeatures():
if level == None or level == feature['levelName'][3]:
feat = self.copy_feature(feature)
geom = feature.geometry()
if geom.wkbType() == QGis.WKBMultiPolygon:
for part in geom.asMultiPolygon():
f = QgsFeature(feat)
f.setGeometry(QgsGeometry.fromPolygon(part))
to_add.append(f)
final += 1
multi += 1
else:
to_add.append(feat)
total += 1
if len(to_add) > BUFFER_SIZE:
self.writer.addFeatures(to_add)
to_add = []
if len(to_add) > 0:
self.writer.addFeatures(to_add)
if total:
log.debug (_("Loaded %d features in '%s' from '%s'"), total,
self.name(), layer.name())
if multi:
log.debug(_("%d multi-polygons splited into %d polygons in "
"the '%s' layer"), multi, final, self.name())
def export_poly(self, filename):
"""Export as polygon file for Osmosis"""
mun = self.merge_adjacent_features([f for f in self.getFeatures()])
mun = self.get_multipolygon(mun)
with open(filename, 'w') as fo:
fo.write('admin_boundary\n')
i = 0
for part in mun:
for j, ring in enumerate(part):
i += 1
prefix = '!' if j > 0 else ''
fo.write(prefix + str(i) + '\n')
for p in ring:
fo.write('%f %f\n' % (p.x(), p.y()))
fo.write('END\n')
fo.write('END\n')
return
class AddressLayer(BaseLayer):
"""Class for address"""
def __init__(self, path="Point", baseName="address", providerLib="memory",
source_date=None):
super(AddressLayer, self).__init__(path, baseName, providerLib)
if self.pendingFields().isEmpty():
self.writer.addAttributes([
QgsField('localId', QVariant.String, len=254),