-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilding2osm.py
2044 lines (1478 loc) · 61.5 KB
/
building2osm.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
# buildings2osm
# Converts buildings from Lantmäteriet to geosjon file for import to OSM.
# Usage: buildings2osm.py <municipality name> [geojson or gpkg input filename] [-heritage] [-split] [-original] [-verify] [-debug] [-noheritage]
# Creates geojson file with name "byggnader_2181_Sandviken.geojson" etc.
import sys
import time
import copy
import math
import statistics
import csv
import json
import os
import io
import base64
import urllib.request, urllib.error
import zipfile
import subprocess
version = "0.10.0"
debug = False # Add debugging / testing information
verify = False # Add tags for users to verify
original = False # Output polygons as in original data (no rectification/simplification)
precision = 7 # Number of decimals in coordinate output
snap_margin = 0.20 # Max margin for connecting building nodes/edges (meters)
angle_margin = 8.0 # Max margin around angle limits, for example around 90 degrees corners (degrees)
short_margin = 0.15 # Min length of short wall which will be removed if on "straight" line (meters)
corner_margin = 0.5 # Max length of short wall which will be rectified even if corner is outside of 90 +/- angle_margin (meters)
rectify_margin = 0.3 # Max relocation distance for nodes during rectification before producing information tag (meters)
simplify_curve_margin = 0.03 # Minimum tolerance for buildings with curves in simplification (meters)
simplify_line_margin = 0.05 # Minimum tolerance for buildings with lines in simplification (meters)
curve_margin_max = 40 # Max angle for a curve (degrees)
curve_margin_min = 0.3 # Min angle for a curve (degrees)
curve_margin_nodes = 3 # At least three nodes in a curve (number of nodes)
spike_margin = 170 # Max angle/bearing for spikes (degrees)
token_filename = "geotorget_token.txt" # Stored Geotorget credentials
token_folder = "~/downloads/" # Folder where token is stored, if not in current folder
# 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
# Format decimal number
def format_decimal(number):
if number:
number = "%.1f" % float(number)
return number.rstrip("0").rstrip(".")
else:
return ""
# Compute approximation of distance between two coordinates, (lat,lon), 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
# 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[0] == polygon[-1]:
lat_dist = math.pi * 6371000.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 int(area / 2.0)
else:
return 0
# Calculate centre of polygon, or of list of nodes
def polygon_centre (polygon):
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]
return (x / length, y / length)
# Return bearing in degrees of line between two points (longitude, latitude)
def bearing (point1, point2):
lon1, lat1, lon2, lat2 = map(math.radians, [point1[0], point1[1], point2[0], point2[1]])
dLon = lon2 - lon1
y = math.sin(dLon) * math.cos(lat2)
x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dLon)
angle = (math.degrees(math.atan2(y, x)) + 360) % 360
return angle
# Return the difference between two bearings.
# Negative degrees to the left, positive to the right.
def bearing_difference (bearing1, bearing2):
delta = (bearing2 - bearing1 + 360) % 360
if delta > 180:
delta = delta - 360
return delta
# Return the shift in bearing at a junction.
# Negative degrees to the left, positive to the right.
def bearing_turn (point1, point2, point3):
bearing1 = bearing(point1, point2)
bearing2 = bearing(point2, point3)
return bearing_difference(bearing1, bearing2)
# Rotate point with specified angle around axis point.
# https://gis.stackexchange.com/questions/246258/transforming-data-from-a-rotated-pole-lat-lon-grid-into-regular-lat-lon-coordina
def rotate_node (axis, r_angle, point):
r_radians = math.radians(r_angle) # *(math.pi/180)
tr_y = point[1] - axis[1]
tr_x = (point[0] - axis[0]) * math.cos(math.radians(axis[1]))
xrot = tr_x * math.cos(r_radians) - tr_y * math.sin(r_radians)
yrot = tr_x * math.sin(r_radians) + tr_y * math.cos(r_radians)
xnew = xrot / math.cos(math.radians(axis[1])) + axis[0]
ynew = yrot + axis[1]
return (xnew, ynew)
# Compute closest distance from point p3 to line segment [s1, s2].
# Works for short distances.
def line_distance(s1, s2, p3, get_point=False):
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
if not get_point:
return distance
# Project back to longitude/latitude
x4 = x4 / math.cos(y4)
lon = math.degrees(x4)
lat = math.degrees(y4)
return (lon, lat), distance
# Generate coordinates for circle with n nodes
def generate_circle(centre, radius, n):
cy = math.radians(centre[1])
cx = math.radians(centre[0]) * math.cos( cy )
r = radius / 6371000.0
polygon = []
for t in range(n + 1):
y = cy + r * math.sin(t * 2 * math.pi / n)
x = (cx + r * math.cos(t * 2 * math.pi / n))
lat = math.degrees(y)
lon = math.degrees(x / math.cos(cy))
polygon.append( ( round(lon, precision), round(lat, precision) ) )
return polygon
# 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
def hausdorff_distance (p1, p2):
N1 = len(p1) - 1
N2 = len(p2) - 1
# Shuffling for small lists disabled
# random.shuffle(p1)
# random.shuffle(p2)
cmax = 0
for i in range(N1):
no_break = True
cmin = 999999.9 # Dummy
for j in range(N2):
d = line_distance(p2[j], p2[j+1], p1[i])
if d < cmax:
no_break = False
break
if d < cmin:
cmin = d
if cmin < 999999.9 and cmin > cmax and no_break:
cmax = cmin
# return cmax
for i in range(N2):
no_break = True
cmin = 999999.9 # Dummy
for j in range(N1):
d = line_distance(p1[j], p1[j+1], p2[i])
if d < cmax:
no_break = False
break
if d < cmin:
cmin = d
if cmin < 999999.9 and cmin > cmax and no_break:
cmax = cmin
return cmax
# Simplify polygon, i.e. reduce nodes within epsilon distance.
# Ramer-Douglas-Peucker method: https://en.wikipedia.org/wiki/Ramer–Douglas–Peucker_algorithm
def simplify_polygon(polygon, epsilon):
dmax = 0.0
index = 0
for i in range(1, len(polygon) - 1):
d = line_distance(polygon[0], polygon[-1], polygon[i])
if d > dmax:
index = i
dmax = d
if dmax >= epsilon:
new_polygon = simplify_polygon(polygon[:index+1], epsilon)[:-1] + simplify_polygon(polygon[index:], epsilon)
else:
new_polygon = [polygon[0], polygon[-1]]
return new_polygon
# 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)
# Produce bbox for polygon
def get_bbox(polygon):
min_bbox = (min([ node[0] for node in polygon ]), min([ node[1] for node in polygon ]))
max_bbox = (max([ node[0] for node in polygon ]), max([ node[1] for node in polygon ]))
return min_bbox, max_bbox
# Determine overlap between bbox
def bbox_overlap(min_bbox1, max_bbox1, min_bbox2, max_bbox2):
return (min_bbox1[0] <= max_bbox2[0] and max_bbox1[0] >= min_bbox2[0]
and min_bbox1[1] <= max_bbox2[1] and max_bbox1[1] >= min_bbox2[1])
# Load dict of all municipalities
def load_municipalities():
url = "https://catalog.skl.se/rowstore/dataset/4c544014-8e8f-4832-ab8e-6e787d383752/json?_limit=400"
try:
file = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
sys.exit("\t*** Failed to load municiaplity names, HTTP error %i: %s\n\n" % (e.code, e.reason))
data = json.load(file)
file.close()
municipalities['00'] = "Sverige"
for municipality in data['results']:
ref = municipality['kommunkod']
if len(ref) < 4:
ref = "0" + ref
municipalities[ ref ] = municipality['kommun']
# Identify municipality name, unless more than one hit.
# Returns municipality number.
def get_municipality (parameter):
if parameter.isdigit() and parameter in municipalities:
return parameter
else:
found_ids = []
for mun_id, mun_name in iter(municipalities.items()):
if parameter.lower() == mun_name.lower():
return mun_id
elif parameter.lower() in mun_name.lower():
found_ids.append(mun_id)
if len(found_ids) == 1:
return found_ids[0]
elif not found_ids:
sys.exit("*** Municipality '%s' not found\n\n" % parameter)
else:
mun_list = [ "%s %s" % (mun_id, municipalities[ mun_id ]) for mun_id in found_ids ]
sys.exit("*** Multiple municipalities found for '%s' - please use full name:\n%s\n\n" % (parameter, ", ".join(mun_list)))
# Get stored Geotorget token or ask for credentials
def get_token():
filename = token_filename
if not os.path.isfile(filename):
test_filename = os.path.expanduser(token_folder + filename)
if os.path.isfile(test_filename):
filename = test_filename
if os.path.isfile(filename):
message ("Loading Geotorget credentials from file '%s'\n\n" % filename)
file = open(filename)
token = file.read()
file.close()
else:
message ("Please provide Geotorget login (you need approval for 'Byggnad Nedladdning, vektor') ...\n")
username = input("\tUser name: ")
password = input("\tPassword: ")
token = username + ":" + password
token = base64.b64encode(token.encode()).decode()
file = open(filename, "w")
file.write(token)
file.close()
message ("\tStoring credentials in file '%s'\n\n" % filename)
return token
# Load conversion json table from GitHub for tagging building types.
def load_building_types():
url = "https://raw.githubusercontent.com/NKAmapper/building2osm-Sweden/main/building_tags.json"
try:
file = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
sys.exit("\t*** Failed to load building types, HTTP error %i: %s\n\n" % (e.code, e.reason))
data = json.load(file)
file.close()
for row in data:
name = row['purpose']
if name == "Ospecificerad":
name += " " + row['object_type'].lower()
if not name:
name = row['object_type']
osm_tags = { 'building': 'yes' }
osm_tags.update(row['tags'])
building_types[ row['object_type'] + ";" + row['purpose'] ] = {
'name': name,
'tags': osm_tags
}
# Load heritage buildings
def load_heritage_buildings(save_heritage=False):
# Internal functions for converting upper case name to titled name using Swedish dictionary
def swedish_title(name):
# Deliver next word with proper capitlization and update word usage stats
def next_word(first, word):
if first or (word.lower() not in dictionary and "kyrk" not in word.lower() and "kapell" not in word.lower()):
if not first:
if word.lower() not in words:
words[ word.lower() ] = 0
words [ word.lower() ] += 1 # Update stats
return word.title()
else:
return word.lower()
# Identify each word and capitalize first character if not found in dictionary
new_name = ""
word = ""
first = True
for i, ch in enumerate(name):
if ch.isalpha():
word += ch
else:
if word:
new_name += next_word(first, word)
word = ""
first = False
new_name += ch
if ch in [";", "(", ")", ",", ".", "-", "/"]:
first = True
if word:
new_name += next_word(first, word)
new_name = new_name.replace("- Och ", "- och ").replace(" ", " ").strip()
return new_name
# Import GeoPandas for Geopackage loading
from geopandas import gpd
import warnings
warnings.filterwarnings(
action="ignore",
message=".*has GPKG application_id, but non conformant file extension.*"
)
message ("Loading heritage buildings from Riksantikvarieämbetet ...\n")
# Load Swedish dictionary to get upper/lowercase right (MIT license)
dictionary = set()
url = "https://raw.githubusercontent.com/martinlindhe/wordlist_swedish/refs/heads/master/swe_wordlist"
# url = "https://raw.githubusercontent.com/LordGurr/SwedishDictionary/refs/heads/main/en-US_User.dic"
try:
file = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
sys.exit("\t*** Failed to load Swedish dictionary, HTTP error %i: %s\n\n" % (e.code, e.reason))
for line in io.TextIOWrapper(file, encoding='utf-8'):
word = line.strip()
if word: # and word.lower() == word:
dictionary.add(word.lower())
file.close()
# Additional words not found in dictionary
dictionary.update(["de", "militärläger", "gravkoret", "vagnslider", "lave", "anten", "fiskeläge", "flygelbyggnaden",
"tygstationen", "mölla", "gravkor", "kungsgård", "byggningen", "fyrplats", "landsförsamlings",
"tröskvandring", "migrering", "tröskhus"])
if debug or verify:
message ("\tLoaded %i dictionary entries\n" % len(dictionary))
# Load hertiage buildings from Swedish National Heritage Board
url = "https://pub.raa.se/nedladdning/datauttag/bebyggelse/byggnader_kulthist_inv/byggnader_sverige.gpkg"
try:
gdf = gpd.read_file(url, layer="byggnader_sverige_point")
except urllib.error.HTTPError as e:
sys.exit("\t*** Failed to load heritage buildings, HTTP error %i: %s\n\n" % (e.code, e.reason))
gdf = gdf.to_crs("EPSG:4326") # Transform projection from EPSG:3006
gdf['senast_andrad'] = gdf['senast_andrad'].dt.strftime("%Y-%m-%d") # Fix type
features = []
words = {}
for feature in gdf.iterfeatures(na="drop", drop_id=True):
if "lagskydd_id" in feature['properties'] and "fast_byg_uuid" in feature['properties']:
if "namn" in feature['properties'] and feature['properties']['namn'].strip():
name = swedish_title(feature['properties']['namn'])
heritage_buildings[ feature['properties']['fast_byg_uuid'] ] = name # Store name/description only
feature['properties']['name'] = name
else:
heritage_buildings[ feature['properties']['fast_byg_uuid'] ] = ""
if save_heritage:
features.append(feature)
message ("\tLoaded %i heritage buildings for Sweden\n\n" % len(heritage_buildings))
if save_heritage:
feature_collection = {
'type': 'FeatureCollection',
'features': features
}
filename = "heritage_sweden.geojson",
file = open(filename, "w")
json.dump(feature_collection, file, indent=2, ensure_ascii=False)
file.close()
if debug:
file = open("heritage_words_sweden.txt", "w")
for word in sorted(words.items(), key=lambda item: item[1], reverse=True):
file.write("%3i %s\n" % (word[1], word[0]))
file.close()
message ("\tSaved building points in file '%s'\n" % filename)
# Load building polygons from Lantmäteriet Geotorget or from local file.
# Tag for OSM and include heritage information.
def load_buildings(municipality_id, filename=""):
message ("Load building polygons ...\n")
# Load GeoJSON file
if filename and ".geojson" in filename:
message ("\tLoading from file '%s' ...\n" % filename)
file = open(filename)
data = json.load(file)
file.close()
# Standardise geometry to Polygon
for feature in data['features']:
if feature['geometry']['type'] == "MultiPolygon":
coordinates = feature['geometry']['coordinates'][0] # One outer area only
elif feature['geometry']['type'] == "Polygon":
coordinates = feature['geometry']['coordinates']
elif feature['geometry']['type'] == "LineString":
coordinates = [ feature['geometry']['coordinates'] ]
else:
coordinates = []
if coordinates and len(coordinates[0]) > 3:
for i, polygon in enumerate(coordinates):
coordinates[ i ] = [ tuple(( round(node[0], precision), round(node[1], precision) )) for node in polygon ]
feature['geometry']['type'] = "Polygon"
feature['geometry']['coordinates'] = coordinates
buildings.append(feature)
# Load GeoPackage file
else:
# Import GeoPandas for Geopackage loading
from geopandas import gpd
import warnings
warnings.filterwarnings(
action="ignore",
message=".*has GPKG application_id, but non conformant file extension.*"
)
if filename:
# Load local GeoPackage file
message ("\tLoading file '%s' ...\n" % filename)
gdf = gpd.read_file(filename)
else:
# Load from Geotorget
message ("\tLoading from Lantmäteriet ...\n")
header = { 'Authorization': 'Basic ' + token }
url = "https://dl1.lantmateriet.se/byggnadsverk/byggnad_kn%s.zip" % municipality_id
filename = "byggnad_kn%s.gpkg" % municipality_id
request = urllib.request.Request(url, headers = header)
try:
file_in = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
message ("\t*** HTTP error %i: %s\n" % (e.code, e.reason))
if e.code == 401: # Unauthorized
message ("\t*** Wrong username (email) or password, or you need approval for 'Byggnad nedladdning, direkt' at Geotorget\n\n")
os.remove(token_filename)
sys.exit()
elif e.code == 403: # Blocked
sys.exit()
else:
return
zip_file = zipfile.ZipFile(io.BytesIO(file_in.read()))
file = zip_file.open(filename)
gdf = gpd.read_file(file)
file.close()
zip_file.close()
file_in.close()
# Transform to GeoJSON format
gdf = gdf.to_crs("EPSG:4326") # Transform projection from EPSG:3006
gdf['versiongiltigfran'] = gdf['versiongiltigfran'].dt.strftime("%Y-%m-%d") # Fix type
for feature in gdf.iterfeatures(na="drop", drop_id=True):
if isinstance(feature['geometry']['coordinates'][0][0], float): # LineString
coordinates = [ feature['geometry']['coordinates'] ]
elif isinstance(feature['geometry']['coordinates'][0][0][0], float): # Polygon
coordinates = feature['geometry']['coordinates']
elif isinstance(feature['geometry']['coordinates'][0][0][0][0], float): # Multipolygon
coordinates = feature['geometry']['coordinates'][0]
else:
coordinates = []
if coordinates and len(coordinates[0]) > 3:
feature['geometry']['coordinates'] = [ [ (round(node[0], precision), round(node[1], precision))
for node in polygon ] for polygon in coordinates ]
feature['geometry']['type'] = "Polygon"
buildings.append(feature)
# Iterate all buildings and assign tags
building_refs = {} # Index - list of buildings with same ref
not_found = [] # Purpose in dataset not defined
for building in buildings:
properties = building['properties']
tags = {}
# Get identifier, unique if house number added
ref = properties['objektidentitet']
tags['ref:lantmateriet:byggnad'] = ref
# house_ref = ""
# if "husnummer" in properties and properties['husnummer']:
# house_ref = str(int(properties['husnummer']))
# tags['ref:lantmateriet:byggnad'] += ":" + house_ref
# Determine building type and add building tag
building_type_list = []
for purpose in ['andamal1', 'andamal2' , 'andamal3', 'andamal4']:
if purpose in properties and properties[ purpose ]:
building_type = properties[ purpose ]
building_type_list.append(building_type)
if building_type not in building_types and building_type not in not_found:
not_found.append(building_type)
if not building_type_list and "objekttyp" in properties and properties['objekttyp']:
building_type = ( properties['objekttyp'] + ";" )
building_type_list = [ building_type ]
if building_type not in building_types and building_type not in not_found:
not_found.append(building_type)
tags['building'] = "yes"
if building_type_list:
for building_type in building_type_list:
if building_type in building_types:
tags.update(building_types[ building_type ]['tags'])
break
type_description = ", ".join([ building_types[ building_type ]['name']
for building_type in building_type_list if building_type in building_types ] )
if type_description:
tags['BTYPE'] = type_description
# Adjust building=* based on size
if (building['geometry']['type'] == "Polygon"
and "BTYPE" in tags
and tags['BTYPE'] in ["Småhus radhus", "Ekonomibyggnad", "Komplementbyggnad"]):
area = abs(polygon_area(building['geometry']['coordinates'][0]))
if tags['BTYPE'] in ["Ekonomibyggnad", "Komplementbyggnad"] and area < 15:
tags['building'] = "shed"
elif tags['BTYPE'] == "Ekonomibyggnad" and area > 100:
tags['building'] = "barn"
elif tags['BTYPE'] == "Småhus radhus" and area > 250:
tags['building'] = "terrace"
# Add extra information
names = []
for tag in ["byggnadsnamn1", "byggnadsnamn2", "byggnadsnamn3"]:
if tag in properties and properties[ tag ].strip():
name = properties[ tag ].replace(" ", " ").strip()
names.append(name)
name = name.lower()
if tags['building'] == "religious":
if "kyrka" in name:
tags['building'] = "church"
elif "kapell" in name:
tags['building'] = "chapel"
if names:
tags['name'] = names[0]
if len(names) > 1:
tags['alt_name'] = ";".join(names[1:])
if "versiongiltigfran" in properties and properties['versiongiltigfran']:
tags['DATE'] = properties['versiongiltigfran'][:10]
if "objektversion" in properties and properties['objektversion']:
tags['DATE'] += " v" + str(properties['objektversion'])
# if "ursprunglig_organisation" in properties and properties['ursprunglig_organisation']:
# tags['SOURCE'] = properties['ursprunglig_organisation'][0].upper() + properties['ursprunglig_organisation'][1:]
# if "huvudbyggnad" in properties and properties['huvudbyggnad'] == "Ja":
# tags['MAIN'] = "yes"
# Add heritage tags
if ref in heritage_buildings:
tags['heritage'] = "yes"
name = heritage_buildings[ ref ].lower()
if (name
and not ("name" in tags and name == tags['name'].lower())
and not ("alt_name" in tags and name == tags['alt_name'].lower())):
tags['description'] = heritage_buildings[ ref ]
if tags['building'] == "religious":
if "kyrka" in name:
tags['building'] = "church"
elif "kapell" in name:
tags['building'] = "chapel"
if "klockstapel" in name or "klocktorn" in name:
tags['building'] = "bell_tower"
building['properties'] = tags
# Mark if multiple buildings have same ref
if ref in building_refs:
if len(building_refs[ ref ]) == 1:
building_refs[ ref ][0]['properties']['MULTI'] = "yes"
building['properties']['MULTI'] = "yes"
building_refs[ ref ].append(building)
else:
building_refs[ ref ] = [ building ]
count_polygons = sum((building['geometry']['type'] == "Polygon") for building in buildings)
message ("\tLoaded %i building polygons\n" % count_polygons)
if not_found:
message ("\t*** Building type(s) not found: %s\n" % (", ".join(sorted([ purpose for purpose in not_found ]))))
verify_building_geometry()
# Check for duplicate nodes, "spike" nodes (sharp angles) and segments
def verify_building_geometry(check_short_segments=False):
# 1. Check for duplicate nodes
count_nodes = 0
for building in buildings:
for i, polygon in enumerate(building['geometry']['coordinates']):
if len(polygon) != len(set(polygon)) + 1:
new_polygon = []
last_node = None
for node in polygon:
if node != last_node:
new_polygon.append(node)
last_node = node
if new_polygon != polygon:
building['geometry']['coordinates'][ i ] = new_polygon
count_nodes += 1
# 2. Check for duplicate segments
count_segments = 0
for building in buildings:
for i, polygon in enumerate(building['geometry']['coordinates']):
if len(polygon) != len(set(polygon)) + 1:
found = True
new_polygon = polygon[1:]
while found and len(new_polygon) > 2: # Iterate until no adjustment
found = False
for j in range(1, len(new_polygon) - 1):
if new_polygon[ j - 1 ] == new_polygon[ j + 1 ]:
removed_nodes.add(new_polygon[ j ])
new_polygon = new_polygon[ : j - 1 ] + new_polygon[ j + 1 : ]
found = True
break
if not found:
# Special case: Duplicate segment wrapped around start/end of polygon
if new_polygon[-1] == new_polygon[1]:
removed_nodes.add(new_polygon[0])
new_polygon = new_polygon[1:-1]
found = True
elif new_polygon[-2] == new_polygon[0]:
removed_nodes.add(new_polygon[-1])
new_polygon = new_polygon[:-2]
found = True
if new_polygon:
new_polygon = [ new_polygon[-1] ] + new_polygon
if new_polygon != polygon:
building['geometry']['coordinates'][ i ] = new_polygon
count_segments += 1
# 3. Check for sharp angles ("spike" nodes)
count_spikes = 0
for building in buildings:
for i, polygon in enumerate(building['geometry']['coordinates']):
found = True
new_polygon = polygon[1:]
while found and len(new_polygon) > 2: # Iterate until no adjustment
found = False
for j in range(1, len(new_polygon) - 1):
if abs(bearing_turn(new_polygon[ j - 1 ], new_polygon[ j ], new_polygon[ j + 1 ])) > spike_margin:
removed_nodes.add(new_polygon[ j ])
new_polygon = new_polygon[ : j ] + new_polygon[ j + 1 : ]
found = True
break
if not found:
# Special case: Spike wrapped around start/end of polygon
if abs(bearing_turn(new_polygon[-1], new_polygon[0], new_polygon[1])) > spike_margin:
removed_nodes.add(new_polygon[0])
new_polygon = new_polygon[1:]
found = True
elif abs(bearing_turn(new_polygon[-2], new_polygon[-1], new_polygon[0])) > spike_margin:
removed_nodes.add(new_polygon[-1])
new_polygon = new_polygon[:-1]
found = True
if new_polygon:
new_polygon = [ new_polygon[-1] ] + new_polygon
if new_polygon != polygon:
building['geometry']['coordinates'][ i ] = new_polygon
building['properties']['VERIFY_SPIKE'] = "1"
count_spikes += 1
# 4. Check for short self-inersecting corners ("spike" corners)
count_corners = 0
for building in buildings:
for i, polygon in enumerate(building['geometry']['coordinates']):
found = True
new_polygon = polygon[1:]
while found and len(new_polygon) > 3: # Iterate until no adjustment
found = False
for j in range(2, len(new_polygon) - 1):
if new_polygon[ j - 2 ] == new_polygon[ j + 1 ] and distance(new_polygon[ j - 1 ], new_polygon[ j ]) < short_margin*2:
removed_nodes.update([ new_polygon[ j - 1 ], new_polygon[ j ] ])
new_polygon = new_polygon[ : j - 2 ] + new_polygon[ j + 1 : ]
found = True
break
if not found:
# Special case: Spike wrapped around start/end of polygon
if new_polygon[-1] == new_polygon[2] and distance(new_polygon[0], new_polygon[1]) < 2 * short_margin:
removed_nodes.update([ new_polygon[0], new_polygon[1] ])
new_polygon = new_polygon[2:-1]
found = True
elif new_polygon[-2] == new_polygon[1] and distance(new_polygon[-1], new_polygon[0]) < 2 * short_margin:
removed_nodes.update([ new_polygon[-1], new_polygon[0] ])
new_polygon = new_polygon[1:-2]
found = True
elif new_polygon[-3] == new_polygon[0] and distance(new_polygon[-2], new_polygon[-1]) < 2 * short_margin:
removed_nodes.update([ new_polygon[-2], new_polygon[-1] ])
new_polygon = new_polygon[:-3]
found = True
if new_polygon:
new_polygon = [ new_polygon[-1] ] + new_polygon
if new_polygon != polygon:
building['geometry']['coordinates'][ i ] = new_polygon
building['properties']['VERIFY_SPIKE'] = "2"
count_corners += 1
# 5. Remove very short segments