-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathn50merge.py
2107 lines (1532 loc) · 62.5 KB
/
n50merge.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
# -*- coding: utf8
import urllib.request, urllib.parse, urllib.error
import json
import sys
import time
import copy
import math
import os.path
from xml.etree import ElementTree as ET
version = "1.3.0"
header = {"User-Agent": "nkamapper/n50osm"}
overpass_api = "https://overpass-api.de/api/interpreter" # Overpass endpoint
import_folder = "~/Jottacloud/osm/n50/" # Folder containing import highway files (current working folder tried first)
n50_parts = ['coastline', 'water', 'wood', 'landuse'] # Part names when splitting file
max_diff = 100 # Maximum permitted difference in meters when matching areas/lines
min_equal_area = 50 # Minimum percent Hausdorff hits within max_diff, for areas
min_equal_line = 30 # Minimum percent Hausdorff hits within max_diff, for lines
max_wood_merge = 10 # Maximum relation members when merging wood relations
max_node_match = 10000000 # Maximum number of matches between nodes (used by Hausdorff and swap_nodes)
debug = False
# Output message to console
def message (text):
sys.stderr.write(text)
sys.stderr.flush()
# Format time
def timeformat (sec):
if sec > 3600:
return "%i:%02i:%02i hours" % (sec / 3600, (sec % 3600) / 60, sec % 60)
elif sec > 60:
return "%i:%02i minutes" % (sec / 60, sec % 60)
else:
return "%i seconds" % sec
# Compute approximation of distance between two coordinates, (lon,lat), in meters
# Works for short distances
def distance (point1, point2):
lon1, lat1, lon2, lat2 = map(math.radians, [point1[0], point1[1], point2[0], point2[1]])
x = (lon2 - lon1) * math.cos( 0.5*(lat2+lat1) )
y = lat2 - lat1
return 6371000.0 * math.sqrt( x*x + y*y ) # Metres
# Compute closest distance from point p3 to line segment [s1, s2].
# Works for short distances.
def line_distance(s1, s2, p3):
x1, y1, x2, y2, x3, y3 = map(math.radians, [s1[0], s1[1], s2[0], s2[1], p3[0], p3[1]])
# Simplified reprojection of latitude
x1 = x1 * math.cos( y1 )
x2 = x2 * math.cos( y2 )
x3 = x3 * math.cos( y3 )
A = x3 - x1
B = y3 - y1
dx = x2 - x1
dy = y2 - y1
dot = (x3 - x1)*dx + (y3 - y1)*dy
len_sq = dx*dx + dy*dy
if len_sq != 0: # in case of zero length line
param = dot / len_sq
else:
param = -1
if param < 0:
x4 = x1
y4 = y1
elif param > 1:
x4 = x2
y4 = y2
else:
x4 = x1 + param * dx
y4 = y1 + param * dy
# Also compute distance from p to segment
x = x4 - x3
y = y4 - y3
distance = 6371000 * math.sqrt( x*x + y*y ) # In meters
'''
# Project back to longitude/latitude
x4 = x4 / math.cos(y4)
lon = math.degrees(x4)
lat = math.degrees(y4)
return (lon, lat, distance)
'''
return distance
# Test if line segments s1 and s2 are crossing.
# Segments have two nodes [(start.x, start.y), (end.x, end.y)].
# Source: https://en.wikipedia.org/wiki/Line–line_intersection#Given_two_points_on_each_line_segment
def crossing_lines (s1, s2):
d1x = s1[1][0] - s1[0][0] # end1.x - start1.x
d1y = s1[1][1] - s1[0][1] # end1.y - start1.y
d2x = s2[1][0] - s2[0][0] # end2.x - start2.x
d2y = s2[1][1] - s2[0][1] # end2.y - start2.y
D = d1x * d2y - d1y * d2x
if abs(D) < 0.0000000001: # s1 and s2 are parallel
return False
A = s1[0][1] - s2[0][1] # start1.y - start2.y
B = s1[0][0] - s2[0][0] # start1.x - start2.x
r1 = (A * d2x - B * d2y) / D
r2 = (A * d1x - B * d1y) / D
if r1 < 0 or r1 > 1 or r2 < 0 or r2 > 1:
return False
'''
# Compute intersection point
x = s1[0][0] + r1 * d1x
y = s1[0][1] + r1 * d1y
intersection = (x, y)
return (intersection)
'''
return True
# Calculate coordinate area of polygon in square meters
# Simple conversion to planar projection, works for small areas
# < 0: Clockwise
# > 0: Counter-clockwise
# = 0: Polygon not closed
def polygon_area (polygon):
if polygon and polygon[0] == polygon[-1]:
lat_dist = math.pi * 6371009.0 / 180.0
coord = []
for node in polygon:
y = node[1] * lat_dist
x = node[0] * lat_dist * math.cos(math.radians(node[1]))
coord.append((x,y))
area = 0.0
for i in range(len(coord) - 1):
area += (coord[i+1][0] - coord[i][0]) * (coord[i+1][1] + coord[i][1]) # (x2-x1)(y2+y1)
return area / 2.0
else:
return 0
# Calculate center of polygon nodes (simple average method)
# Note: If nodes are skewed to one side, the center will be skewed to the same side
def polygon_center (polygon):
if len(polygon) == 0:
return None
elif len(polygon) == 1:
return polygon[0]
length = len(polygon)
if polygon[0] == polygon[-1]:
length -= 1
x = 0
y = 0
for node in polygon[:length]:
x += node[0]
y += node[1]
x = x / length
y = y / length
return (x, y)
# Calculate new node with given distance offset in meters
# Works over short distances
def coordinate_offset (node, distance):
m = (1 / ((math.pi / 180.0) * 6378137.0)) # Degrees per meter
latitude = node[1] + (distance * m)
longitude = node[0] + (distance * m) / math.cos( math.radians(node[1]) )
return (longitude, latitude)
# Calculate Hausdorff distance, including reverse.
# Abdel Aziz Taha and Allan Hanbury: "An Efficient Algorithm for Calculating the Exact Hausdorff Distance"
# https://publik.tuwien.ac.at/files/PubDat_247739.pdf
# Amended for given maximum distance limit, to return percent of hits within given limit and to work for both polygons and lines.
def hausdorff_distance (polygon1, polygon2, limit = False, percent = False, polygon=False):
# Simplify polygons if needed due to size
if percent and len(polygon1) * len(polygon2) > max_node_match:
step = int(math.sqrt(max_node_match))
p1 = polygon1[: -1 : 1 + len(polygon1) // step ] + [ polygon1[-1] ]
p2 = polygon2[: -1 : 1 + len(polygon2) // step ] + [ polygon2[-1] ]
else:
p1 = polygon1
p2 = polygon2
# Start of function
count_hits = 0
N1 = len(p1)
N2 = len(p2)
if polygon:
end = 1
else:
end = 0
# Shuffling for small lists disabled
# random.shuffle(p1)
# random.shuffle(p2)
cmax = 0
for i in range(N1 - end):
no_break = True
cmin = 999999.9 # Dummy
for j in range(N2 - 1):
d = line_distance(p2[j], p2[j+1], p1[i])
if d < cmin:
cmin = d
if d < cmax and not percent:
no_break = False
break
if cmin < 999999.9 and cmin > cmax and no_break:
cmax = cmin
if limit:
if cmin < limit:
count_hits += 1
if not percent and cmax > limit:
return cmax
# return cmax
for i in range(N2 - end):
no_break = True
cmin = 999999.9 # Dummy
for j in range(N1 - 1):
d = line_distance(p1[j], p1[j+1], p2[i])
if d < cmin:
cmin = d
if d < cmax and not percent:
no_break = False
break
if cmin < 999999.9 and cmin > cmax and no_break:
cmax = cmin
if limit:
if cmin < limit:
count_hits +=1
if not percent and cmax > limit:
return cmax
if percent:
return [ cmax, 100.0 * count_hits / (N1 + N2 - 1 - end) ]
else:
return cmax
# Tests whether point (x,y) is inside a polygon
# Ray tracing method
def inside_polygon (point, polygon):
if polygon[0] == polygon[-1]:
x, y = point
n = len(polygon)
inside = False
p1x, p1y = polygon[0]
for i in range(n):
p2x, p2y = polygon[i]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xints = (y-p1y) * (p2x-p1x) / (p2y-p1y) + p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x, p1y = p2x, p2y
return inside
else:
return None
# Get name or id of municipality from GeoNorge api
def get_municipality_name (query):
if query.isdigit():
url = "https://ws.geonorge.no/kommuneinfo/v1/kommuner/" + query
else:
url = "https://ws.geonorge.no/kommuneinfo/v1/sok?knavn=" + urllib.parse.quote(query)
request = urllib.request.Request(url, headers=header)
try:
file = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
if e.code == 404: # Not found
sys.exit("\tMunicipality '%s' not found\n\n" % query)
else:
raise
if query.isdigit():
result = json.load(file)
file.close()
municipality_name = result['kommunenavnNorsk']
return (query, municipality_name)
else:
result = json.load(file)
file.close()
if result['antallTreff'] == 1:
municipality_id = result['kommuner'][0]['kommunenummer']
municipality_name = result['kommuner'][0]['kommunenavnNorsk']
return (municipality_id, municipality_name)
else:
municipalities = []
for municipality in result['kommuner']:
municipalities.append(municipality['kommunenummer'] + " " + municipality['kommunenavnNorsk'])
sys.exit("\tMore than one municipality found: %s\n\n" % ", ".join(municipalities))
# Get tags of OSM or N50 element
def get_tags(xml_element):
tags = {}
for tag in xml_element.findall("tag"):
tags[ tag.attrib['k'] ] = tag.attrib['v']
return tags
# Determine keywords used for matching
def get_topo_type(tags):
topo_type = set()
if "natural" in tags:
if tags['natural'] == "water" and "water" in tags and tags['water'] == "river":
topo_type.add("river")
elif tags['natural'] in ["coastline", "wood", "water", "wetland", "glacier"]:
topo_type.add(tags['natural'])
if "landuse" in tags:
if tags['landuse'] == "forest":
topo_type.add("wood")
elif tags['landuse'] == "meadow":
topo_type.add("farmland")
else:
topo_type.add(tags['landuse'])
if "waterway" in tags:
if tags['waterway'] == "riverbank":
topo_type.add("river")
elif tags['waterway'] in ["river", "stream"] and "tunnel" not in tags:
topo_type.add("stream")
if "place" in tags and tags['place'] in ["islet", "island"]:
topo_type.add("island")
return topo_type
# Build dict data structure from XML.
# Works for both N50 and OSM.
def prepare_data (root, tree, nodes, ways, relations):
# Create dict of nodes
# Each node is a tuple of (lon, lat), corresponding to GeoJSON format x,y
for node in root.iter("node"):
nodes[ node.attrib['id'] ] = {
'xml': node,
'coord':( float(node.attrib['lon']), float(node.attrib['lat']) ),
'parents': set(), # Built in next loop
'tags': get_tags(node)
}
# Create dict of ways
for way in root.iter("way"):
way_id = way.attrib['id']
way_nodes = []
way_coordinates = []
incomplete = False
tags = get_tags(way)
# Get way nodes + determine if way is complete
for node in way.iter("nd"):
node_id = node.attrib['ref']
way_nodes.append(node_id)
if node_id in nodes:
way_coordinates.append(nodes[node_id]['coord'])
nodes[ node_id ]['parents'].add(way_id)
if "boundary" in tags:
nodes[ node_id ]['boundary'] = True # Mark nodes used by boundaries
else:
incomplete = True
if incomplete:
# way_nodes = []
way_coordinates = []
ways[ way_id ] = {
'id': way_id,
'xml': way,
'incomplete': incomplete,
'nodes': way_nodes,
'coordinates': way_coordinates,
'parents': set(), # Built in next loop
'tags': tags,
'topo': get_topo_type(tags)
}
# Create dict of relations
for relation in root.iter("relation"):
relation_id = relation.attrib['id']
tags = get_tags(relation)
island = "place" in tags and tags['place'] in ["islet", "island"] # Identify relations which are islands
incomplete = False
members = []
for member in relation.iter("member"):
way_id = member.attrib['ref']
members.append(way_id)
if way_id in ways:
ways[ way_id ]['parents'].add(relation_id) # Incomplete members will be missing
if "boundary" in tags:
for node_id in ways[ way_id ]['nodes']:
if node_id in nodes:
nodes[ node_id ]['boundary'] = True # Mark nodes used by boundaries
else:
incomplete = True
if member.attrib['type'] in ["node", "relation"]:
if way_id in nodes:
nodes[ way_id ]['parents'].add(relation_id)
incomplete = True
if not incomplete and members: # Do not store incomplete relations
relations[ relation_id ] = {
'id': relation_id,
'xml': relation,
'members': members,
'tags': tags,
'topo': get_topo_type(tags),
'island': island
}
# Load relevant OSM elements for chosen municipality
def load_osm():
global osm_root, osm_tree
message ("Load existing OSM elements from Overpass ...\n")
if historic_id:
area_query = '[old_ref=%s]["was:place"=municipality]' % historic_id
else:
area_query = '[ref=%s][admin_level=7][place=municipality]' % municipality_id
query = ('[timeout:200];'
'(area%s;)->.a;'
'('
'nwr["natural"](area.a);'
'nwr["waterway"](area.a);'
'nwr["landuse"](area.a);'
'nwr["leisure"](area.a);'
'nwr["aeroway"](area.a);'
'nwr["seamark:type"="rock"](area.a);'
');'
'(._;>;<;);'
'out meta;' % area_query)
request = urllib.request.Request(overpass_api + "?data=" + urllib.parse.quote(query), headers=header)
try:
file = urllib.request.urlopen(request)
except urllib.error.HTTPError as err:
sys.exit("\n\t*** %s\n\n" % err)
data = file.read()
file.close()
osm_root = ET.fromstring(data)
osm_tree = ET.ElementTree(osm_root)
prepare_data (osm_root, osm_tree, osm_nodes, osm_ways, osm_relations)
message ("\tLoaded %i ways, %i relations\n" % (len(osm_ways), len(osm_relations)))
# Get and display top contributors
users = {}
for element in osm_root:
if "user" in element.attrib:
user = element.attrib['user']
if element.tag in ["way", "relation"]:
if user not in users:
users[ user ] = 0
users[ user ] += 1
sorted_users = sorted(users.items(), key=lambda x: x[1], reverse=True)
message ("\tTop contributors:\n")
for i, user in enumerate(sorted_users):
if user[1] > 10 and i < 10 or user[1] >= 100:
message ("\t\t%s (%i)\n" % (user[0], user[1]))
# Load N50 import file.
# The file should only contain new elements (negative id's).
def load_n50():
global n50_root, n50_tree
message ("Load N50 import file elements ...\n")
if os.path.isfile(filename):
file = open(filename)
message ("\tLoading '%s' from CURRENT working folder\n" % filename)
else:
file = open(os.path.expanduser(import_folder + filename))
message ("\tLoading '%s'\n" % import_folder + filename)
data = file.read()
file.close()
n50_root = ET.fromstring(data)
n50_tree = ET.ElementTree(n50_root)
prepare_data (n50_root, n50_tree, n50_nodes, n50_ways, n50_relations)
for element in n50_root:
if int(element.attrib['id']) > 0:
sys.exit("\t*** Please do not import existing OSM elements\n")
message ("\tLoaded %i ways, %i relations\n" % (len(n50_ways), len(n50_relations)))
# Filter elements according to given part (coastline, water, wood, landuse/other).
# Found elements are returned in 'found_elements' parameter (set).
def filter_parts (part, n50_elements, found_elements):
for element_id, element in iter(n50_elements.items()):
all_tags = element['xml'].findall('tag')
if all_tags != None:
for tag in all_tags:
key = tag.attrib['k']
value = tag.attrib['v']
if (part == "coastline" and (key == "natural" and value == "coastline" or key == "seamark:type")
or part == "water" and (key == "natural" and value in ["water", "wetland", "glacier"] or key == "waterway")
or part == "wood" and key == "natural" and value == "wood"
or part == "landuse" and key in ["landuse", "leisure", "aeroway"]):
found_elements.add(element_id)
break
# Split N50 import file into parts (coastline, water, wood, landuse/other).
def split_n50():
message ("Splitting N50 import file ...\n")
for part in n50_parts:
message ("\t%-9s: " % part.title())
relations = set()
ways = set()
nodes = set()
root = ET.Element("osm", version="0.6")
tree = ET.ElementTree(root)
# Identify elements to include
filter_parts(part, n50_relations, relations)
filter_parts(part, n50_ways, ways)
filter_parts(part, n50_nodes, nodes)
count_tagged_nodes = len(nodes) # Count before additional nodes are added
for relation in relations:
for member in n50_relations[ relation ]['members']:
ways.add(member)
# Collect additional elements for islands
if part in ["coastline", "water"]:
for relation_id, relation in iter(n50_relations.items()):
if relation['island']:
for member in relation['members']:
if member in ways:
relations.add(relation_id)
for island_member in relation['members']:
ways.add(island_member)
break
for way in ways:
for node in n50_ways[ way ]['nodes']:
nodes.add(node)
# Build output tree
for node in n50_root.iter("node"):
if node.attrib['id'] in nodes:
root.append(node)
for way in n50_root.iter("way"):
if way.attrib['id'] in ways:
root.append(way)
for relation in n50_root.iter("relation"):
if relation.attrib['id'] in relations:
root.append(relation)
# Generate file
root.set("generator", "n50merge v"+version)
root.set("upload", "false")
indent_tree(root)
part_filename = output_filename.replace("merged.osm", "") + part + ".osm"
tree.write(part_filename, encoding='utf-8', method='xml', xml_declaration=True)
message ("Saved %i elements to file '%s'\n" % (len(relations) + len(ways) + count_tagged_nodes, part_filename))
# Identify duplicate ways in existing OSM.
# Note: WIP. It identifies the ways but it does not merge.
def merge_osm():
message ("Merge OSM ways ...\n")
count = 0
count_down = len(osm_ways)
ways_list = list(osm_ways.keys())
for i, way_id1 in enumerate(ways_list):
message ("\r\t%i " % count_down)
way1 = osm_ways[ way_id1 ]
count_down -= 1
for way_id2 in ways_list[i+1:]:
way2 = osm_ways[ way_id2 ]
if (way1['coordinates'] == way2['coordinates'] or way1['coordinates'] == way2['coordinates'][::-1]) \
and not way1['incomplete'] and not way2['incomplete']:
count += 1
way1['xml'].append(ET.Element("tag", k="MATCH", v=way_id2))
way1['xml'].set("action", "modify")
message ("\r\tFound %i identical ways\n" % count)
# Merge tags from N50 element into OSM element, if there are no conflicts (e.g. natural=coastline + natural=wood).
def merge_tags (n50_xml, osm_xml):
n50_tags = {}
for tag in n50_xml.findall("tag"):
n50_tags[ tag.attrib['k'] ] = tag.attrib['v']
osm_tags = {}
for tag in osm_xml.findall("tag"):
key = tag.attrib['k']
value = tag.attrib['v']
osm_tags[ key ] = value
if key in n50_tags and value != n50_tags[key]:
return False
for key, value in iter(n50_tags.items()):
if key not in osm_tags or value != osm_tags[ key ]:
osm_xml.append(ET.Element("tag", k=key, v=value))
osm_xml.set("action", "modify")
return True
# Merge N50 elements with other N50 elements which have already been uploaded to OSM.
# Identical ways (with identical coordinates) will be merged.
# Relations will be merged if all members have been merged.
# Note that ways which differs only slightly (e.g. one more node, or a few centimeters off) will not be merged.
def merge_n50():
message ("Merge N50 with OSM ...\n")
lap_time = time.time()
count_ways = 0
count_down = len(n50_ways)
swap_nodes = {}
# Loop all N50 ways and match against all OSM ways
for n50_way_id in list(n50_ways.keys()):
n50_way = n50_ways[ n50_way_id ]
message ("\r\t%i " % count_down)
count_down -= 1
for osm_way_id, osm_way in iter(osm_ways.items()):
if n50_way['coordinates'] == osm_way['coordinates'] and not n50_way['incomplete'] and not osm_way['incomplete']:
# Check if conflicting tags, for example natural=water + natural=wood. Also update OSM tags.
if merge_tags(n50_way['xml'], osm_way['xml']):
# Swap ref if member in relations
for parent_id in n50_way['parents']:
if parent_id in n50_relations:
parent = n50_relations[ parent_id ]
for i, member in enumerate(parent['members'][:]):
if member == n50_way_id:
parent['members'][i] = osm_way_id
member_xml = parent['xml'].find("member[@ref='%s']" % n50_way_id)
member_xml.set("ref", osm_way_id)
# Mark nodes for swapping, in case nodes are used by other ways
for i in range(len(n50_way['nodes'])):
swap_nodes[ n50_way['nodes'][i] ] = osm_way['nodes'][i]
# Remove merged way from N50 xml
n50_root.remove(n50_way['xml'])
del n50_ways[ n50_way_id ]
count_ways += 1
break
message ("\r\t \r")
# Swap affected nodes
for way_id, way in iter(n50_ways.items()):
for i, node in enumerate(way['nodes'][:]):
if node in swap_nodes:
way['nodes'][i] = swap_nodes[ node ]
node_xml = way['xml'].find("nd[@ref='%s']" % node)
node_xml.set("ref", swap_nodes[ node])
# Delete N50 nodes which have been replaced, unless there is a tag conflict
'''
for n50_node_xml in n50_root.findall("node"): # List
n50_node_id = n50_node_xml.attrib['id']
if n50_node_id in swap_nodes:
if n50_node_xml.find("tag") != None:
osm_node_xml = osm_root.find("node[@id='%s']" % swap_nodes[ n50_node_id ])
if not merge_tags(n50_node_xml, osm_node_xml):
continue # Do not delete N50 node
del n50_nodes[ n50_node_id ]
n50_root.remove(n50_node_xml)
'''
for node in swap_nodes:
if n50_nodes[node]['xml'].find("tag") == None or not merge_tags(n50_node_xml, osm_node_xml):
n50_root.remove( n50_nodes[node]['xml'] )
del n50_nodes[ node ]
# Delete N50 relations which have been replaced by OSM relations, unless there is a tag conflict
count_relations = 0
for n50_relation_id in list(n50_relations.keys()):
n50_relation = n50_relations[ n50_relation_id ]
# Check if all members have been replaced, and compile set of possible OSM relations to check
all_parents = set()
for member in n50_relation['members']:
if member in osm_ways:
all_parents.update(osm_ways[ member ]['parents'])
else:
all_parents = set()
break
# Delete N50 relation if matching OSM relation is found, unless tag conflict
if all_parents:
for parent_id in all_parents:
if parent_id in osm_relations and set(osm_relations[ parent_id ]['members']) == set(n50_relation['members']):
if merge_tags(n50_relation['xml'], osm_relations[ parent_id ]['xml']):
n50_root.remove(n50_relation['xml'])
del n50_relations[ n50_relation_id ]
count_relations += 1
break
message ("\r\tSwapped %i ways, %i relations\n" % (count_ways, count_relations))
message ("\tRun time %s\n" % (timeformat(time.time() - lap_time)))
# Get bounding box for a list of coordinates
def get_bbox(coordinates):
min_bbox = ( min([point[0] for point in coordinates]), min([point[1] for point in coordinates]) )
max_bbox = ( max([point[0] for point in coordinates]), max([point[1] for point in coordinates]) )
return min_bbox, max_bbox
# Reorder members of OSM relations if needed.
# Necessary for correct manipulation of relation members.
# Check paramter if only for checking correct order, but no amendments.
def fix_relation_order(check = False):
count_fix = 0
for relation in osm_relations.values():
remaining_members = copy.copy(relation['members'])
member_patches = []
found = True
while remaining_members and found:
if osm_ways[ remaining_members[0] ]['incomplete']:
break
coordinates = copy.copy(osm_ways[ remaining_members[0] ]['coordinates'])
patch = [ remaining_members[0] ]
remaining_members.pop(0)
found = True
# Keep adding members as long as they match end-to-end
while found:
found = False
for member in remaining_members:
if not osm_ways[ member ]['incomplete']:
member_coordinates = osm_ways[ member ]['coordinates']
if coordinates[-1] == member_coordinates[0]:
patch.append(member)
coordinates.extend(member_coordinates[1:])
remaining_members.remove(member)
found = True
break
elif coordinates[-1] == member_coordinates[-1]:
patch.append(member)
coordinates.extend(list(reversed(member_coordinates))[1:])
remaining_members.remove(member)
found = True
break
if coordinates[0] == coordinates[-1]:
member_patches.append(patch)
found = True
if not remaining_members:
# Rearrange to get outer members first
i = 0
for patch in member_patches[:]:
role = relation['xml'].find("member[@ref='%s']" % patch[0]).attrib['role']
if role == "outer":
member_patches.remove(patch)
member_patches.insert(i, patch)
i += 1
new_member_order = [member for patch in member_patches for member in patch]
relation['order'] = True
if new_member_order != relation['members']:
if check:
relation['xml'].append(ET.Element("tag", k="ORDER", v="yes"))
count_fix += 1
continue
# Rearrange XML with correct order for each patch of members
i = 0
for patch in member_patches:
for member in patch:
member_xml = relation['xml'].find("member[@ref='%s']" % member)
relation['xml'].remove(member_xml)
relation['xml'].insert(i, member_xml)
i += 1
relation['members'] = new_member_order
relation['xml'].set("action", "modify")
count_fix += 1
else:
relation['order'] = False # Mark relation order has been checked
message ("\t%i relations reordered\n" % count_fix)
# Create list of tagged objects which are closed/ring to prepare for later matching and merging
def prepare_objects(ways, relations):
tagged_objects = []
# Get all ways which are closed rings
for way_id, way in iter(ways.items()):
if not way['incomplete']:
if way['tags'] and way['coordinates'][0] == way['coordinates'][-1]:
min_bbox, max_bbox = get_bbox(way['coordinates'])
tagged_object = {
'type': "way",
'id': way_id,
'xml': way['xml'],
'tags': way['tags'],
'topo': way['topo'],
'coordinates': way['coordinates'],
'center': polygon_center(way['coordinates']),
'area': abs(polygon_area(way['coordinates'])),
'border': False,
'min_bbox': min_bbox,
'max_bbox': max_bbox
}
if tagged_object['area'] > 0:
tagged_objects.append(tagged_object)
# Get all relations which are closed rings
for relation_id, relation in iter(relations.items()):
if (relation['tags']
and relation['members']
and not any(ways[ member ]['incomplete'] for member in relation['members'])
and not any("FIXME" in ways[ member ]['tags'] and ways[ member ]['tags']['FIXME'] == "Merge" for member in relation['members'])):
border = any("FIXME" in ways[ member ]['tags'] and ways[ member ]['tags']['FIXME'] == "Merge" for member in relation['members'])
# Get closed ring. Assuming outer ring starts with first member.