forked from balrog-kun/osm-addr-tools
-
Notifications
You must be signed in to change notification settings - Fork 3
/
merger.py
1730 lines (1585 loc) · 60.8 KB
/
merger.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
#!/usr/bin/env python3.4
import argparse
import functools
import io
import itertools
import json
import logging
import sys
import typing
from collections import defaultdict, OrderedDict
import lxml.etree
import rtree
import shapely
import tqdm
from lxml.builder import E
from shapely.geometry import Point
import overpass
import utils.osmshapedb
from data.base import Address
from data.egeoportal import EGeoportal
from data.gisnet import GISNET
from data.gison import GISON
from data.gugik import GUGiK, GUGiK_GML
from data.impa import iMPA
from data.warszawaum import WarszawaUM
from osmdb import OsmDb, OsmDbEntry, get_soup_center, distance, simplified_shape_poland
from utils import osmshapedb
__log = logging.getLogger(__name__)
# depends FreeBSD
# portmaster graphics/py-pyproj devel/py-rtree devel/py-shapely www/py-beautifulsoup devel/py-lxml
# depeds Lubuntu:
# apt-get install python3-pyproj libspatialindex-dev python3-shapely python3-bs4 python3-lxml
# easy_install3 Rtree
# TODO: import admin_level=8 for area, and add addr:city if missing for addresses within that area
# (needs greater refactoring)
# TODO: check for alone addresses. Look for addresses that have greater minimal distance to greater than ?? avg*5?
# avg+stddev*3? http://en.wikipedia.org/wiki/Chauvenet%27s_criterion ?
# http://en.wikipedia.org/wiki/Peirce%27s_criterion ?
def create_property_funcs(field):
def getx(self):
return self._soup["tags"][field]
def setx(self, val):
self._soup["tags"][field] = val
def delx(self):
del self._soup["tags"][field]
return property(getx, setx, delx, "%s property" % (field,))
class Location(typing.NamedTuple):
lat: float
lon: float
class OsmAddress(Address):
__log = logging.getLogger(__name__).getChild("OsmAddress")
def __init__(self, soup, *args, **kwargs):
self._soup = soup
if "tags" not in self._soup:
self._soup["tags"] = {}
super(OsmAddress, self).__init__(*args, **kwargs)
self.state = None
self.ref_ways = []
self.osm_fixme = ""
# @formatter:off
housenumber = create_property_funcs("addr:housenumber")
postcode = create_property_funcs("addr:postcode")
street = create_property_funcs("addr:street")
city = create_property_funcs("addr:city")
sym_ul = create_property_funcs("addr:street:sym_ul")
simc = create_property_funcs("addr:city:simc")
source = create_property_funcs("source:addr")
id_ = create_property_funcs("ref:addr")
# @formatter:on
def __getitem__(self, key):
return self._soup[key]
@staticmethod
def from_soup(obj, location: shapely.geometry.Point = None, ways_for_node=None):
tags = dict((k, v.strip()) for (k, v) in obj.get("tags", {}).items())
if location is None:
loc = dict(zip(("lat", "lon"), get_soup_center(obj)))
else:
loc = {"lat": location.y, "lon": location.x}
ret = OsmAddress(
housenumber=tags.get("addr:housenumber", ""),
postcode=tags.get("addr:postcode", ""),
street=tags.get("addr:street", ""),
city=tags.get("addr:place", "")
if tags.get("addr:place")
else tags.get("addr:city", ""),
sym_ul=tags.get("addr:street:sym_ul", ""),
simc=tags.get("addr:city:simc", ""),
source=tags.get("source:addr", ""),
location=loc,
id_=tags.get("ref:addr", ""),
soup=obj,
)
ret.osm_fixme = tags.get("fixme", "")
if obj.get("action"):
ret.state = obj["action"]
if ways_for_node:
ret.ref_ways = ways_for_node.get(obj["id"], [])
if tags.get("addr:place") and tags.get("addr:city"):
# clear the data in OSM
ret.set_state("modify")
if tags.get("addr:city") and not tags.get("addr:street"):
# clear the data in OSM
ret.set_state("modify")
return ret
def get_fixme(self):
s1 = super(OsmAddress, self).get_fixme()
return ", ".join(x for x in (s1, self.osm_fixme) if x)
def set_state(self, val):
if val not in ("visible", "modify", "delete"):
raise ValueError("Unknown state %s" % val)
if val == "visible" and self.state not in ("modify", "delete"):
self.state = val
elif val == "modify" and self.state != "delete":
self.state = val
elif val == "delete":
if len(self.ref_ways) > 0:
self.state = "modify"
self.housenumber = ""
self.postcode = ""
self.street = ""
self.city = ""
self.sym_ul = ""
self.simc = ""
self.source = ""
self.id_ = ""
else:
self.state = val
else:
# mark change
self.state = self.state
@property
def center(self):
return Point(float(self.location["lon"]), float(self.location["lat"]))
def distance(self, other):
return distance(self.center, other.center)
@property
def objtype(self):
return self._soup["type"]
def _get_tag_val(self, key):
return self._soup.get("tags").get(key)
def _set_tag_val(self, key, val):
"""returns True if something was modified"""
n = self._soup["tags"].get(key)
if n == val.strip():
return False
self._soup["tags"][key] = val.strip()
return True
def _remove_tag(self, key):
if key in self._soup["tags"]:
del self._soup["tags"][key]
return True
return False
def shape(self):
raise NotImplementedError
@property
def osmid(self):
return "%s:%s" % (self.objtype, self._soup["id"])
@property
def osmid_tuple(self):
return (self.objtype, self._soup["id"])
def is_emuia_addr(self):
ret = False
if self.source:
ret |= "EMUIA" in self.source.upper()
source_addr = self._get_tag_val("source")
if source_addr:
ret |= "EMUIA" in source_addr.upper()
return ret
def only_address_node(self):
# return true, if its a node, has a addr:housenumber,
# and consists only of tags listed below
if self.objtype != "node":
return False
return self.housenumber and set(self._soup["tags"].keys()).issubset(
{
"addr:housenumber",
"addr:street",
"addr:street:sym_ul",
"addr:place",
"addr:city",
"addr:city:simc",
"addr:postcode",
"addr:country",
"teryt:sym_ul",
"teryt:simc",
"source",
"source:addr",
"fixme",
"addr:street:source",
"ref:addr",
}
)
def is_new(self):
return int(self._soup["id"]) < 0
def get_tag_soup(self):
return dict((k, v) for (k, v) in self._soup["tags"].items() if v)
def update_from(self, entry):
def update(tag_name):
old = getattr(self, tag_name)
new = getattr(entry, tag_name)
if new and old != new:
setattr(self, tag_name, new)
if old:
self.__log.debug("Updating %s from %s to %s", tag_name, old, new)
return True
return False
ret = False
for name in ("street", "city", "housenumber", "postcode"):
ret |= update(name)
# update without changing ret status, so adding these fields will not trigger a change in OSM
# but if there is something else added, this will get updated too
for name in ("sym_ul", "simc", "source", "id_"):
update(name)
if entry.get_fixme():
self.add_fixme(entry.get_fixme())
self.set_state("visible")
if ret:
self.set_state("modify")
return ret
def to_osm_soup(self):
def _remove_tag(tags, key):
if key in tags:
del tags[key]
return True
return False
def _set_tag_val(tags, key, value):
n = tags.get(key)
if n == value.strip():
return False
if value.strip():
tags[key] = value.strip()
return True
else:
if n:
del tags[key]
return True
else:
return False
s = self._soup
meta_kv = OrderedDict(
(k, str(v))
for (k, v) in sorted(s.items())
if k in ("id", "version", "timestamp", "changeset", "uid", "user")
)
# do not export ref:addr until the discussion will come to conclusion
tags = dict(
(k, v.strip())
for (k, v) in s.get("tags", {}).items()
if v.strip() and k != "ref:addr" and k != "addr:ref"
)
ret = False
if self.housenumber:
if self.street:
ret |= _remove_tag(tags, "addr:place")
else:
ret |= _set_tag_val(tags, "addr:place", self.city)
ret |= _remove_tag(tags, "addr:street")
# do not change value of ret - this value is always there, as self.city set this
_remove_tag(tags, "addr:city")
if self.get_fixme():
# presence of only fixme tag is not sufficient to send a change to OSM
_set_tag_val(tags, "fixme", self.get_fixme())
ret |= _set_tag_val(tags, "addr:postcode", self.postcode)
if ret or self.state == "modify":
if bool(tags.get("source")) and (
tags["source"] == self.source or "EMUIA" in tags["source"].upper()
):
_remove_tag(tags, "source")
meta_kv["action"] = "modify"
if self.state in ("delete", "modify"):
meta_kv["action"] = self.state
tags = tuple(
map(
lambda x: lxml.etree.Element(
"tag", attrib=OrderedDict((("k", x[0]), ("v", x[1])))
),
sorted(tags.items()),
)
)
if s["type"] == "node":
root = lxml.etree.Element(
"node",
attrib=OrderedDict(
(
("lat", "{:0.7f}".format(s["lat"])),
("lon", "{:0.7f}".format(s["lon"])),
)
+ tuple(meta_kv.items())
),
)
for i in tags:
root.append(i)
elif s["type"] == "way":
root = lxml.etree.Element("way", attrib=meta_kv)
for i in tags:
root.append(i)
for i in s["nodes"]: # not sorting nodes, as the order defines the way
root.append(root.makeelement("nd", attrib=OrderedDict({"ref": str(i)})))
elif s["type"] == "relation":
root = lxml.etree.Element("relation", attrib=meta_kv)
for i in tags:
root.append(i)
for i in s[
"members"
]: # not sorting relation memebers, as this might be important
root.append(
root.makeelement(
"member",
attrib=OrderedDict(
(
("ref", str(i["ref"])),
("type", i["type"]),
("role", i.get("role", "")),
)
),
)
)
else:
raise ValueError("Unsupported objtype: %s" % (s.objtype,))
return root
class Merger(object):
__log = logging.getLogger(__name__).getChild("Merger")
def __init__(
self,
impdata: typing.List[Address],
asis: osmshapedb.GeometryHandler,
terc: str,
source_addr: str,
):
self.impdata = impdata
for entry in self.impdata:
if not entry.source:
entry.source = source_addr
self.asis = asis
self._import_area_shape = (
Point(0, 0).buffer(400) if not terc else get_boundary_shape(terc)
)
self.imp_obj_by_id = dict(zip(itertools.count(), self.impdata))
self.imp_index = rtree.index.Index()
for (key, value) in self.imp_obj_by_id.items():
self.imp_index.insert(key, (value.center.y, value.center.x))
self.address_index = dict((x.get_index_key(), x) for x in self.impdata)
self._new_nodes: typing.List[OsmDbEntry] = []
self._updated_nodes: typing.List[OsmDbEntry] = []
self._soup_visible: typing.List[OsmDbEntry] = []
self._state_changes: typing.List[OsmDbEntry] = []
self._node_id = 0
self.pre_func = []
self.post_func = []
self.source_addr = source_addr
ways_for_node = defaultdict(list)
for way in filter(lambda x: x["type"] == "way", asis.elements):
for node in way["nodes"]:
ways_for_node[node].append(way["id"])
from_soup = functools.partial(OsmAddress.from_soup, ways_for_node=ways_for_node)
self.osmdb = OsmDb(
self.asis,
valuefunc=from_soup,
indexes={"address": lambda x: x.get_index_key(), "id": lambda x: x.osmid},
index_filter=lambda x: (
x["tags"].get("building", False) or x.entry.housenumber
)
and self._import_area_shape.contains(x.shape),
)
def create_index(self, message=""):
self.osmdb.update_index(message)
def merge(self):
self.__log.debug("Starting premerger functinos")
self._pre_merge()
self.create_index("[3/14]")
self.__log.debug("Starting merge functinos")
self._do_merge()
self.__log.debug("Starting postmerge functinos")
self._post_merge()
def set_state(self, node, value):
self._state_changes.append(node)
for i in node.ref_ways:
self._state_changes.append(self.osmdb.get_by_id("way", i))
node.set_state(value)
def _fix_wesola(self, entry):
if entry.get("tags", {}).get("addr:street", "").endswith(" (W)"):
entry["tags"]["addr:street"] = entry["tags"]["addr:street"][:-4]
self._state_changes.append(self.osmdb.get_by_id(entry["type"], entry["id"]))
def _pre_merge(self):
# for custom fixes
# for entry in self.asis['elements']:
# self._fix_wesola(entry)
def process(entry):
self._fix_similar_addr(entry)
tuple(map(lambda f: f(entry), self.pre_func))
for x in tqdm.tqdm(
self.impdata, desc="[2/14] Running pre-merge functions"
): # type: Address
if x.center.within(self._import_area_shape):
process(x)
def _fix_similar_addr(self, entry):
# look for near same address
# change street names to values from OSM
# change housenumbers to values from import
node = next(
(
x
for x in itertools.islice(
(
x
for x in self.osmdb.nearest(entry.center, num_results=100)
if x.housenumber
),
0,
10,
)
if entry.similar_to(x)
),
None,
)
if not node:
return
how_far = node.distance(entry)
if (
node
and node.street
and entry.street
and node.street != entry.street
and (
(node.objtype == "node" and how_far < 5.0)
or (
node.objtype == "way"
and (node.contains(entry.center) or how_far < 10.0)
)
)
):
# there is some similar address nearby but with different street name
if node.objtype == "node":
node.add_fixme("Street name in OSM: " + node.street)
node.entry.street = entry.street
self.set_state(node, "modify")
if (
node
and node.street == entry.street
and node.city == entry.city
and node.housenumber != entry.housenumber
and (
(node.objtype == "node" and how_far < 5.0)
or (
node.objtype == "way"
and (node.contains(entry.center) or how_far < 10.0)
)
)
):
# there is only difference in housenumber, that is similiar
if node.housenumber.upper() != entry.housenumber.upper():
clean = lambda x: x.upper().replace(" ", "")
if clean(node.housenumber) == clean(entry.housenumber) and len(
node.housenumber
) < len(entry.housenumber):
# difference only in spaces, no spaces in OSM do not change address in OSM
return
# if there are some other differences than in case, then add fixme
self.__log.info(
"Updating housenumber from %s to %s",
node.housenumber,
entry.housenumber,
)
entry.add_fixme("House number in OSM: %s" % (node.housenumber,))
# make this *always* visible, to verify, if OSM value is correct. Hope that entry will
# eventually get merged with node
self.set_state(node, "modify")
node.entry.housenumber = entry.housenumber
def _fix_obsolete_emuia(self, entry):
existing = self.osmdb.getbyaddress(entry.get_index_key())
if existing:
# we have something with this address in db
# sort by distance
emuia_nodes = sorted(
tuple(
filter(
lambda x: x.is_emuia_addr() and x.only_address_node(), existing
)
),
key=lambda x: x.distance(entry),
)
# update location of first node if from EMUiA
if emuia_nodes:
emuia_nodes[0].location = entry.location
# all the others mark for deletion
if len(emuia_nodes) > 1:
for node in emuia_nodes[1:]:
self.set_state(node, "delete")
def _do_merge(self):
for entry in tqdm.tqdm(self.impdata, desc="[4/14] Merging"): # type: Address
if entry.center.within(self._import_area_shape):
self._do_merge_one(entry)
def _do_merge_one(self, entry):
self.__log.debug("Processing address: %s", entry)
return any(
map(
lambda x: x(entry),
(
# first returning true will stop exection of the chain
self._do_merge_by_existing,
self._do_merge_by_within,
self._do_merge_by_nearest,
self._do_merge_create_point,
),
)
)
def _do_merge_by_existing(self, entry):
existing = tuple(
filter(
lambda x: self._import_area_shape.contains(x.center),
self.osmdb.getbyaddress(entry.get_index_key()),
)
)
self.__log.debug("Found %d same addresses", len(existing))
# create tuples (distance, entry) sorted by distance
existing = sorted(
map(lambda x: (x.distance(entry), x), existing), key=lambda x: x[0]
)
if existing:
# report duplicates
if len(existing) > 1:
self.__log.warning(
"More than one address node for %s. %s",
entry,
", ".join(
"Id: %s, dist: %sm" % (x[1].osmid, str(x[0])) for x in existing
),
)
if max(x[0] for x in existing) > 50:
for (dist, node) in existing:
if dist > 50:
if not (
(
node.objtype in ("way", "relation")
and node.buffered_shape(50).contains(entry.center)
)
or (
# if node is within other way/relation with the same address do not mark it if
# the way is not away more than 50 to avoid to many warnings
node.objtype == "node"
and any(
(
(
node.within(x.shape)
and x.buffered_shape(50).contains(
entry.center
)
)
for (_, x) in existing
if x.objtype in ("way", "relation")
)
)
)
):
# ignore the distance, if the point is within the node
self.__log.warning(
"Address (id=%s) %s is %d meters from imported point",
node.osmid,
entry,
dist,
)
node.add_fixme(
"Node is %d meters away from imported point" % dist
)
self.set_state(node, "visible")
if min(x[0] for x in existing) > 50:
if any(
map(
lambda x: x[1].objtype in ("way", "relation")
and x[1].contains(entry.center),
existing,
)
):
# if any of existing addresses is a way/relation within which we have our address
# then skip
pass
else:
self.__log.debug(
"Creating address node, as closest address is farther than 50m"
)
self._create_point(entry)
return True
building = next(
(
x
for (_, x) in existing
if x.objtype in ("way", "relation" and x.contains(entry.center))
),
None,
)
if building:
# there is existing building with same address that contains processed entry
building_center = (building.center.y, building.center.x) * 2
if (
len(
list(
itertools.islice(
(
x
for x in (
self.imp_obj_by_id[x]
for x in self.imp_index.nearest(
building_center, 20
)
)
if building.contains(x.center)
),
0,
2,
)
)
)
> 1
):
# we have more than one address within this building
# clear address from the building and create point
self._create_point(entry)
building._raw["tags"] = dict(
(
key,
""
if (key.startswith("addr:") or key == "source:addr")
else value,
)
for key, value in building._raw["tags"].items()
)
building.clear_fixme()
self.set_state(building, "modify")
return True
# update data only on first duplicate, rest - leave to OSM-ers
self._update_node(existing[0][1], entry)
return True
return False
def _do_merge_by_within(self, entry):
# look for building nearby
candidates_within = list(
itertools.islice(
(
x
for x in self.osmdb.nearest(entry.center, num_results=100)
if x.objtype in ("way", "relation") and x.contains(entry.center)
),
0,
10,
)
)
self.__log.debug(
"Found %d buildings containing address", len(candidates_within)
)
if candidates_within:
c = candidates_within[0]
if not c.housenumber:
# no address on way/relation -> add address
# create a point, will be merged with building later
self.__log.debug(
"Creating address node as building contains no address"
)
self._create_point(entry)
return True
else:
# WARNING - candidate has an address
if c.similar_to(entry) and c.street == entry.street:
self.__log.debug(
"Updating OSM address: %s with import %s", c.entry, entry
)
self._update_node(c, entry)
return True
else:
c_center = (c.center.y, c.center.x) * 2
if len(
list(
itertools.islice(
(
x
for x in (
self.imp_obj_by_id[x]
for x in self.imp_index.nearest(c_center, 20)
)
if c.contains(x.center)
),
0,
2,
)
)
) > 1 or not self.handle_one_street_name_change(c, entry):
if not c.get_index_key() in self.address_index:
# create address point from building only if the address on building is different
# than addresses in import
new_entry = self.osmdb.add_new(
{
"type": "node",
"id": self._get_node_id(),
"lat": c.center.y,
"lon": c.center.x,
"tags": dict(
(key, value)
for key, value in c._raw["tags"].items()
if key.startswith("addr:")
or key == "source:addr"
),
}
)
self._new_nodes.append(new_entry)
# remove address from building
c._raw["tags"] = dict(
(
key,
""
if (key.startswith("addr:") or key == "source:addr")
else value,
)
for key, value in c._raw["tags"].items()
)
c.clear_fixme()
self.set_state(c, "modify")
self._create_point(entry)
return True
return False
def _do_merge_by_nearest(self, entry):
candidates = list(self.osmdb.nearest(entry.center, num_results=10))
candidates_same = [
x
for x in candidates
if x.housenumber == entry.housenumber and x.distance(entry) < 2.0
]
if len(candidates_same) > 0:
# same location, both are an address, and have same housenumber, can't be coincidence,
# probably mapper changed something
for node in candidates_same:
found = False
if node.similar_to(entry):
found = True
self.__log.debug(
"Updating near node from: %s to %s", node.entry, entry
)
# as node.similar_to(entry) only changes in street might happened
node.add_fixme("Street name in OSM: " + node.street)
self._update_node(node, entry)
if found:
return True
if any(map(lambda x: x.housenumber and x.city, candidates_same)):
self.__log.info(
"Found probably same address node at (%s, %s). Skipping. Import address is: %s, osm addresses: %s",
entry.location["lon"],
entry.location["lat"],
entry,
", ".join(map(lambda x: str(x.entry), candidates_same)),
)
return True
candidates_same = [
x
for x in candidates
if all(
getattr(x, attr) == getattr(entry, attr)
for attr in ("city", "simc", "street", "sym_ul")
)
and x.distance(entry) < 2.0
]
if len(candidates_same) > 0:
# same location, both are address but different house numbers
# update house number in osm
for node in candidates_same:
self._update_node(node, entry)
return True
return False
def _do_merge_create_point(self, entry):
if not self._import_area_shape.contains(entry.center):
self.__log.warning("Imported address %s outside import borders", entry)
self._create_point(entry)
return True
def _update_node(self, node, entry):
self.__log.debug(
"Cheking if there is something to update for node %s, address: %s",
node.osmid,
node.entry,
)
if node.update_from(entry):
self.__log.debug("Updating node %s using %s", node.osmid, entry)
self._updated_nodes.append(node)
def _create_point(self, entry):
self.__log.debug("Creating new point")
soup = {
"type": "node",
"id": self._get_node_id(),
"lat": float(entry.location["lat"]),
"lon": float(entry.location["lon"]),
}
new = self.osmdb.add_new(soup)
new.update_from(entry)
self._new_nodes.append(new)
# TODO: check that soup gets address tags
# self.asis['elements'].append(soup)
def _mark_soup_visible(self, obj):
self._soup_visible.append(obj)
def _get_node_id(self):
self._node_id -= 1
return self._node_id
def _get_all_changed_nodes(self) -> typing.Tuple[OsmDbEntry]:
ret: typing.Dict[str, OsmDbEntry] = dict(
(x.osmid, x) for x in self._updated_nodes
)
ret.update(dict((x.osmid, x) for x in self._new_nodes))
self.__log.info("Modified objects: %d", len(ret))
ret.update(dict((x.osmid, x) for x in self._state_changes))
ret.update(
dict(
(x.osmid, x)
for x in self.osmdb.get_all_values()
if x.state in ("modify", "delete") and x.osmid not in ret.keys()
)
)
for (_id, i) in sorted(ret.items(), key=lambda x: x[0]):
if i in self._updated_nodes:
self.__log.debug("Processing updated node: %s", str(i.entry))
elif i in self._new_nodes:
self.__log.debug("Processing new node: %s", str(i.entry))
elif i.state in ("modify", "delete"):
self.__log.debug(
"Processing node - changed: %s, %s", i.state, str(i.entry)
)
return tuple(ret.values())
def _get_all_visible(self):
ret = dict((x.osmid, x) for x in self._soup_visible)
ret.update(
dict(
(x.osmid, x)
for x in self.osmdb.get_all_values()
if x.state == "visible" and x.osmid not in ret.keys()
)
)
return tuple(ret.values())
def _get_all_reffered_by(
self, lst: typing.Iterable[OsmDbEntry]
) -> typing.Iterable[OsmDbEntry]:
ret = set()
__referred_cache = dict()
def get_referred(
node, exclude_ids=()
) -> typing.Iterable[typing.Tuple[str, int]]:
referrers = __referred_cache.get(node.osmid)
if not referrers:
referrers = get_referred_cached(node, exclude_ids)
__referred_cache[node.osmid] = referrers
return referrers
def get_referred_cached(
node, exclude_ids=()
) -> typing.Iterable[typing.Tuple[str, int]]:
if node.osmid in exclude_ids:
return set()
if node["type"] == "node":
return set(
itertools.chain(
itertools.chain.from_iterable(
get_referred(self.osmdb.get_by_id("way", x), exclude_ids)
for x in node.ref_ways
if "way:{}".format(x) not in exclude_ids
),
(("node", node["id"]),),
)
)
if node["type"] == "nd":
return set(
itertools.chain(
itertools.chain.from_iterable(
get_referred(self.osmdb.get_by_id("way", x), exclude_ids)
for x in node.ref_ways
if "way:{}".format(x) not in exclude_ids
),
(("node", node["ref"]),),
)
)
if node["type"] == "way":
return itertools.chain(
itertools.chain.from_iterable(
get_referred(
self.osmdb.get_by_id("node", x),
exclude_ids=exclude_ids + ("way:{}".format(node["id"]),),
)
for x in node["nodes"]
),
(("way", node["id"]),),
)
if node["type"] == "member":
return get_referred(
self.osmdb.get_by_id(node["type"], int(node["ref"]))
)
if node["type"] == "relation":
return itertools.chain(
itertools.chain.from_iterable(
get_referred(self.osmdb.get_by_id(x["type"], int(x["ref"])))
for x in node["members"]
),
(("relation", node["id"]),),
)
raise ValueError("Unknown node type: %s" % node.name)
for i in tqdm.tqdm(lst, desc="[14/14] Generating output"):
ret = ret.union(get_referred(i))
return tuple(
map(
lambda x: self.osmdb.get_by_id(x[0], x[1]),
sorted(ret, key=lambda x: "%s:%s" % (x[0], x[1])),
)
)
def _post_merge(self):
# recreate index
self.create_index("[5/14]")
self.handle_street_name_changes()
self.create_index("[7/14]")
self.mark_not_existing()