-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbuilding2osm.py
1435 lines (1025 loc) · 43 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 the Norwegian cadastral registry to geosjon file for import to OSM.
# Usage: buildings2osm.py <municipality name> [-original] [-verify] [-debug]
# Creates geojson file with name "bygninger_4222_Bykle.osm" etc.
import sys
import time
import copy
import math
import statistics
import csv
import json
import urllib.request
import zipfile
import subprocess
from io import TextIOWrapper
from io import BytesIO
from xml.etree import ElementTree as ET
import utm # From building2osm on GitHub
version = "0.7.0"
polygons = False # Load building polygons (currently unavailable from Kartverket)
verbose = False # Provides extra messages about polygon loading
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)
coordinate_decimals = 7 # Number of decimals in output
angle_margin = 8.0 # Max margin around angle limits, for example around 90 degrees corners (degrees)
short_margin = 0.20 # Min length of short wall which will be removed if on "straight" line (meters)
corner_margin = 1.0 # Max length of short wall which will be rectified even if corner is outside of 90 +/- angle_margin (meters)
rectify_margin = 0.2 # Max relocation distance for nodes during rectification before producing information tag (meters)
simplify_margin = 0.05 # Minimum tolerance for buildings with curves 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)
addr_margin = 100 # Max margin for matching address point with building centre, for building levels info (meters)
max_download = 10000 # Max features permitted for downloading by WFS per query
status_codes = {
'RA': 'Rammetillatelse',
'IG': 'Igangsettingstillatelse',
'MB': 'Midlertidig brukstillatelse',
'FA': 'Ferdigattest',
'TB': 'Bygning er tatt i bruk',
'MT': 'Meldingsak registrert',
'MF': 'Meldingsak fullført',
'GR': 'Bygning godkjent, revet eller brent',
'IP': 'Ikke pliktig registrert',
'FS': 'Fritatt for søknadsplikt'
}
# 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):
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
# 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
# Parse WKT coordinates and return polygon list of (longitude, latitude).
# Omit equal coordinates in sequence.
def parse_polygon(coord_text):
split_coord = coord_text.split(" ")
coordinates = []
last_node1 = (None, None)
last_node2 = (None, None)
for i in range(0, len(split_coord) - 1, 2):
lon = float(split_coord[i])
lat = float(split_coord[i+1])
node = (lon, lat)
if node != last_node1:
if node == last_node2:
coordinates.pop()
last_node1 = last_node2
else:
coordinates.append(node)
last_node2 = last_node1
last_node1 = node
return coordinates
# Transform url characters
def fix_url (url):
return url.replace("Æ","E").replace("Ø","O").replace("Å","A").replace("æ","e").replace("ø","o").replace("å","a").replace(" ", "_")
# Load conversion CSV table for tagging building types.
# Format in CSV: "key=value + key=value + ..."
def load_building_types():
url = "https://raw.githubusercontent.com/NKAmapper/building2osm/main/building_types.csv"
file = urllib.request.urlopen(url)
building_csv = csv.DictReader(TextIOWrapper(file, "utf-8"), fieldnames=["id", "name", "osm_tag"], delimiter=";")
next(building_csv)
for row in building_csv:
osm_tag = { 'building': 'yes' }
if row['osm_tag']:
tag_list = row['osm_tag'].replace(" ","").split("+")
for tag_part in tag_list:
tag_split = tag_part.split("=")
osm_tag[ tag_split[0] ] = tag_split[1]
building_types[ row['id'] ] = {
'name': row['name'],
'tags': osm_tag
}
file.close()
# Identify municipality name, unless more than one hit
# Returns municipality number, or input parameter if not found
def get_municipality (parameter):
if parameter.isdigit():
return parameter
else:
parameter = parameter
found_id = ""
duplicate = False
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():
if found_id:
duplicate = True
else:
found_id = mun_id
if found_id and not duplicate:
return found_id
else:
return parameter
# Load dict of all municipalities
def load_municipalities():
url = "https://ws.geonorge.no/kommuneinfo/v1/fylkerkommuner?filtrer=fylkesnummer%2Cfylkesnavn%2Ckommuner.kommunenummer%2Ckommuner.kommunenavnNorsk"
file = urllib.request.urlopen(url)
data = json.load(file)
file.close()
for county in data:
if county['fylkesnavn'] == "Oslo":
county['fylkesnavn'] = "Oslo fylke"
municipalities[ county['fylkesnummer'] ] = county['fylkesnavn']
for municipality in county['kommuner']:
municipalities[ municipality['kommunenummer'] ] = municipality['kommunenavnNorsk']
municipalities['2100'] = "Svalbard"
municipalities['00'] = "Norge"
# Load building polygons from WFS within given BBOX.
# Note: Max 10.000 buildings will be returned from WFS. No paging provided.
# Data parsed as text lines for performance reasons (very simple data structure)
def load_building_coordinates(municipality_id, min_bbox, max_bbox, level):
bbox_list = [str(min_bbox[1]), str(min_bbox[0]), str(max_bbox[1]), str(max_bbox[0])]
url = "https://wfs.geonorge.no/skwms1/wfs.inspire-bu-core2d?" + \
"service=WFS&version=2.0.0&request=GetFeature&srsName=EPSG:4326&typename=Building&bbox=" + ",".join(bbox_list)
# message ("\n\tQuery: %s\n\t" % url)
file_in = urllib.request.urlopen(url)
file = TextIOWrapper(file_in, "utf-8")
count_feature = 0
count_hits = 0
hit = False
for line in file:
ref_index = line.find("<bu-base:reference>")
if ref_index > 0:
ref_end = line.find("<", ref_index + 19 )
ref = line[ ref_index + 19 : ref_end ]
coordinates = []
count_feature += 1
if ref in buildings:
hit = True
count_hits += 1
else:
hit = False
ref_index = line.find("<gml:posList>")
if ref_index > 0:
ref_end = line.find("<", ref_index + 13 )
geo = line[ ref_index + 13 : ref_end ]
coordinates.append( parse_polygon(geo) )
if "</wfs:member>" in line:
if ref in buildings and coordinates:
buildings[ref]['geometry']['type'] = "Polygon"
buildings[ref]['geometry']['coordinates'] = coordinates
# buildings[ref]['centre'] = polygon_centre(coordinates[0])
file_in.close()
if verbose:
message ("Found %i, loaded %i buildings\n" % (count_hits, count_feature))
# If returned number of buildings is close to max WFS limit, then reload using smaller BBOX
count_load = 1
if count_feature > max_download - 10:
if verbose:
message ("%s*** Too many buildings in box, force split box and reloading" % ("\t" * level))
count_load += load_area(municipality_id, min_bbox, max_bbox, level, force_divide=True)
elif not verbose:
count_total_loaded = sum((building['geometry']['type'] == "Polygon") for building in buildings.values())
message ("\r\tLoading ... %6i " % count_total_loaded)
return count_load
# Recursively split municipality BBOX into smaller quadrants if needed to fit within WFS limit.
def load_area(municipality_id, min_bbox, max_bbox, level, force_divide):
# How many buildings from municipality within bbox?
count_load = 0
inside_box = 0
for building in buildings.values():
if min_bbox[0] <= building['centre'][0] < max_bbox[0] and \
min_bbox[1] <= building['centre'][1] < max_bbox[1]:
inside_box += 1
# How many buildings from neighbour municipalities within bbox?
neighbour_inside_box = 0
for building_node in neighbour_buildings:
if min_bbox[0] <= building_node[0] < max_bbox[0] and \
min_bbox[1] <= building_node[1] < max_bbox[1]:
neighbour_inside_box += 1
if verbose and not force_divide:
message("%sExpecting %i buildings + %i neighbours ... " % ("\t" * level, inside_box, neighbour_inside_box))
if inside_box == 0:
if verbose:
message ("\n")
return count_load
# Do actual loading of data
elif inside_box + neighbour_inside_box < 0.95 * max_download and not force_divide:
count_load += load_building_coordinates(municipality_id, min_bbox, max_bbox, level)
else:
# Split bbox to get fewer than 10.000 buildings within bbox
if verbose:
message ("\n%sSplit box\n" % ("\t" * level))
if distance((min_bbox[0], max_bbox[1]), max_bbox) > distance(min_bbox, (min_bbox[0], max_bbox[1])): # x longer than y
# Split x axis
half_x = 0.5 * (max_bbox[0] + min_bbox[0])
count_load += load_area(municipality_id, min_bbox, (half_x, max_bbox[1]), level + 1, force_divide=False)
count_load += load_area(municipality_id, (half_x, min_bbox[1]), max_bbox, level + 1, force_divide=False)
else:
# Split y axis
half_y = 0.5 * (max_bbox[1] + min_bbox[1])
count_load += load_area(municipality_id, min_bbox, (max_bbox[0], half_y), level + 1, force_divide=False)
count_load += load_area(municipality_id, (min_bbox[0], half_y), max_bbox, level + 1, force_divide=False)
return count_load
# Get municipality BBOX and kick off recursive splitting into smaller BBOX quadrants
def load_coordinates_municipality(municipality_id):
message ("Load building polygons ...\n")
message ("\tLoading ... ")
if municipality_id != "2100":
file = urllib.request.urlopen("https://ws.geonorge.no/kommuneinfo/v1/kommuner/" + municipality_id)
data = json.load(file)
file.close()
bbox = data['avgrensningsboks']['coordinates'][0]
else:
bbox = [[9.0, 74.0], [], [35.0, 81.0], []] # Svalbard
count_load = load_area(municipality_id, bbox[0], bbox[2], 1, force_divide=False) # Start with full bbox
# Adjust building tagging according to size
for building in buildings.values():
if building['geometry']['type'] == "Polygon" and "building" in building['properties'] and \
building['properties']['building'] in ["garage", "barn", "hotel"]:
area = abs(polygon_area(building['geometry']['coordinates'][0]))
if building['properties']['building'] == "garage" and area > 100:
building['properties']['building'] = "garages"
elif building['properties']['building'] in ["garage", "barn"] and area < 15:
building['properties']['building'] = "shed"
elif building['properties']['building'] == "barn" and area < 100:
building['properties']['building'] = "farm_auxiliary"
elif building['properties']['building'] == "hotel" and area < 100:
building['properties']['building'] = "cabin"
count_polygons = sum((building['geometry']['type'] == "Polygon") for building in buildings.values())
message ("\r\tLoaded %i building polygons with %i load queries\n" % (count_polygons, count_load))
# Get info about buildings from cadastral registry.
# To aid data fetching of building polygons from WFS + to be merged with polygons later.
# Function can also load building info from neighbour municipalities, to aid bbox splitting when loading building polygons.
def load_building_info(municipality_id, municipality_name, neighbour):
global max_download
# Namespace
ns_gml = 'http://www.opengis.net/gml/3.2'
ns_app = 'http://skjema.geonorge.no/SOSI/produktspesifikasjon/Matrikkelen-Bygningspunkt/20211101'
ns = {
'gml': ns_gml,
'app': ns_app
}
# Load file from GeoNorge
url = "https://nedlasting.geonorge.no/geonorge/Basisdata/MatrikkelenBygning/GML/Basisdata_%s_%s_25833_MatrikkelenBygning_GML.zip" \
% (municipality_id, municipality_name)
url = fix_url(url)
if not neighbour:
message ("Loading building information from cadastral registry ...\n")
# message ("\tFile: %s\n" % url)
in_file = urllib.request.urlopen(url)
zip_file = zipfile.ZipFile(BytesIO(in_file.read()))
# If building file is being updated at server, it will not be available
if len(zip_file.namelist()) == 0:
if neighbour:
max_download = 0.5 * max_download # Aim for less aggressive target since neighbour info will be incomplete
return 0
else:
message("\n\n*** Building information for %s not available, please try later\n\n" % municipality_name)
return 0
filename = zip_file.namelist()[0]
file = zip_file.open(filename)
tree = ET.parse(file)
file.close()
root = tree.getroot()
count = 0
not_found = []
for feature in root.iter('{%s}featureMember' % ns_gml):
count += 1
building = feature.find('app:Bygning', ns)
ref = building.find('app:bygningsnummer', ns).text
position = building.find("app:representasjonspunkt/gml:Point/gml:pos", ns).text
position_split = position.split()
x, y = float(position_split[0]), float(position_split[1])
[lat, lon] = utm.UtmToLatLon (x, y, 33, "N") # Reproject from UTM to WGS84
centre = ( round(lon, coordinate_decimals), round(lat, coordinate_decimals) )
if neighbour:
neighbour_buildings.append(centre) # We only need centre coordinates for neighbour municipalities
continue
building_type = building.find("app:bygningstype", ns).text
building_status = building.find("app:bygningsstatus", ns).text
feature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": centre
},
"properties": {
'ref:bygningsnr': ref,
'TYPE': "#" + building_type,
'STATUS': "#%s %s" % (building_status, status_codes[ building_status ])
},
'centre': centre
}
if building_type in building_types:
feature['properties']['TYPE'] = "#%s %s" % (building_type, building_types[ building_type ]['name'])
feature['properties'].update(building_types[ building_type ]['tags'])
elif building_type not in not_found:
not_found.append(building_type)
source_date = building.find("app:oppdateringsdato", ns)
if source_date is not None:
feature['properties']['DATE'] = source_date.text[:10]
heritage = building.find("app:harKulturminne", ns).text
if heritage == "true":
feature['properties']['heritage'] = "yes"
sefrak = building.find("app:sefrakIdent/app:SefrakIdent", ns)
if sefrak is not None:
sefrak = "%s-%s-%s" % (sefrak.find("app:sefrakKommune", ns).text,
sefrak.find("app:registreringskretsnummer", ns).text,
sefrak.find("app:huslopenummer", ns).text)
feature['properties']['SEFRAK'] = sefrak
# Establish link to all "bruksenhet" associated with building, for later updating building levels
for dwelling in building.findall("app:bruksenhet", ns):
dwelling_id = dwelling.find("app:Bruksenhet/app:bruksenhetId", ns)
if dwelling_id is not None:
dwellings[ dwelling_id.text ] = feature
if debug:
feature['properties']['DEBUG_CENTRE'] = str(centre[1]) + " " + str(centre[0])
buildings[ ref ] = feature
if not neighbour:
message("\tLoaded %i buildings\n" % count)
if not_found:
message ("\t*** Building type(s) not found: %s\n" % (", ".join(sorted(not_found))))
return count
# Load centre coordinate for all buildings in neighbour municipalities, to make bbox splitting more accurate when loading building polygons.
def load_neighbour_buildings(municipality_id):
if municipality_id != "2100": # Svalbard
message ("Load building points for neighbour municipalities ...\n")
# Load neighbour municipalities
file = urllib.request.urlopen("https://ws.geonorge.no/kommuneinfo/v1/kommuner/" + municipality_id + "/nabokommuner")
data = json.load(file)
file.close()
for municipality in data:
message ("\tLoading %s ... " % municipality['kommunenavnNorsk'])
count = load_building_info(municipality['kommunenummer'], municipality['kommunenavnNorsk'], neighbour=True)
message ("loaded %i buildings\n" % count)
message ("\tLoaded %i neighbour building points for reference\n" % len(neighbour_buildings))
# Load building level information from cadastral registry.
# Only for apartments.
def load_building_levels(municipality_id, municipality_name):
# Load file from GeoNorge
url = "https://nedlasting.geonorge.no/geonorge/Basisdata/MatrikkelenAdresseLeilighetsniva/CSV/Basisdata_%s_%s_4258_MatrikkelenAdresseLeilighetsniva_CSV.zip" \
% (municipality_id, municipality_name)
url = fix_url(url)
message ("Loading building level information from cadastral registry ...\n")
# message ("\tUrl: %s\n" % url)
in_file = urllib.request.urlopen(url)
zip_file = zipfile.ZipFile(BytesIO(in_file.read()))
if len(zip_file.namelist()) < 2:
message ("\n\t*** No apartment data available (you may try again later)\n\n")
return
csv_file = zip_file.open(zip_file.namelist()[1])
addr_table = csv.DictReader(TextIOWrapper(csv_file, "utf-8"), delimiter=";")
for row in addr_table:
if row['bruksenhetId'] in dwellings:
building = dwellings[ row['bruksenhetId'] ]
if "levels" not in building:
building['levels'] = {
'H': 0, # Main levels, all above ground
'U': 0, # Main levels, above ground on at least one side
'K': 0, # Underground levels
'L': 0 # Roof levels
}
# Update highest level if available
if row['bruksenhetsnummerTekst']:
level_type = row['bruksenhetsnummerTekst'][0]
level_number = int(row['bruksenhetsnummerTekst'][1:3])
building['levels'][ level_type ] = max(building['levels'][ level_type ], level_number)
csv_file.close()
zip_file.close()
in_file.close()
count = 0
for building in buildings.values():
if "levels" in building:
if building['levels']['H'] + building['levels']['U'] > 1:
# if building['properties']['building'] in ['apartments', 'residential', 'dormitory', 'terrace', 'semidetached_house', \
# 'civic', 'commercial', 'retail', 'office', 'house', 'farm', 'cabin'] :
building['properties']['building:levels'] = str(building['levels']['H'] + building['levels']['U'])
if building['levels']['L'] > 0:
building['properties']['roof:levels'] = str(building['levels']['L'])
count += 1
del building['levels']
message ("\tFound %i buildings with level information (>1 levels)\n" % count)
# Simplify polygon
# Remove redundant nodes, i.e. nodes on (almost) staight lines
def simplify_buildings():
message ("Simplify polygons ...\n")
message ("\tSimplification factor: %.2f m (curve), %i degrees (line)\n" % (simplify_margin, angle_margin))
# Make dict of all nodes with count of usage
count = 0
nodes = {}
for ref, building in iter(buildings.items()):
if building['geometry']['type'] == "Polygon":
for polygon in building['geometry']['coordinates']:
for node in polygon:
if node not in nodes:
nodes[ node ] = 1
else:
nodes[ node ] += 1
count += 1
message ("\t%i nodes used by more than one building\n" % count)
# Identify redundant nodes, i.e. nodes on an (almost) straight line
count = 0
for ref, building in iter(buildings.items()):
if building['geometry']['type'] == "Polygon" and ("rectified" not in building or building['rectified'] == "no"):
for polygon in building['geometry']['coordinates']:
# First discover curved walls, to keep more detail
curves = set()
curve = set()
last_bearing = 0
for i in range(1, len(polygon) - 1):
new_bearing = bearing_turn(polygon[i-1], polygon[i], polygon[i+1])
if math.copysign(1, last_bearing) == math.copysign(1, new_bearing) and curve_margin_min < abs(new_bearing) < curve_margin_max:
curve.add(i - 1)
curve.add(i)
curve.add(i + 1)
else:
if len(curve) > curve_margin_nodes + 1:
curves = curves.union(curve)
curve = set()
last_bearing = new_bearing
if len(curve) > curve_margin_nodes + 1:
curves = curves.union(curve)
if curves:
building['properties']['VERIFY_CURVE'] = str(len(curves))
count += 1
# Then simplify polygon
if curves:
# Light simplification for curved buildings
new_polygon = simplify_polygon(polygon, simplify_margin)
# Check if start node could be simplified
if line_distance(new_polygon[-2], new_polygon[1], new_polygon[0]) < simplify_margin:
new_polygon = new_polygon[1:-1] + [ new_polygon[1] ]
# building['properties']['VERIFY_SIMPLIFY_FIRST'] = "yes"
if len(new_polygon) < len(polygon):
building['properties']['VERIFY_SIMPLIFY_CURVE'] = str(len(polygon) - len(new_polygon))
for node in polygon:
if node not in new_polygon:
nodes[ node ] -= 1
else:
# Simplification for buildings without curves
last_node = polygon[-2]
for i in range(len(polygon) - 1):
angle = bearing_turn(last_node, polygon[i], polygon[i+1])
length = distance(polygon[i], polygon[i+1])
if (abs(angle) < angle_margin or \
length < short_margin and \
(abs(angle) < 40 or \
abs(angle + bearing_turn(polygon[i], polygon[i+1], polygon[(i+2) % (len(polygon)-1)])) < angle_margin) or \
length < corner_margin and abs(angle) < 2 * angle_margin):
nodes[ polygon[i] ] -= 1
if angle > angle_margin - 2:
building['properties']['VERIFY_SIMPLIFY_LINE'] = "%.1f" % abs(angle)
else:
last_node = polygon[i]
if debug or verify:
message ("\tIdentified %i buildings with curved walls\n" % count)
# Create set of nodes which may be deleted without conflicts
already_removed = len(remove_nodes)
for node in nodes:
if nodes[ node ] == 0:
remove_nodes.add(node)
# Remove nodes from polygons
count_building = 0
count_remove = 0
for ref, building in iter(buildings.items()):
if building['geometry']['type'] == "Polygon":
removed = False
for polygon in building['geometry']['coordinates']:
for node in polygon[:-1]:
if node in remove_nodes:
i = polygon.index(node)
polygon.pop(i)
count_remove += 1
removed = True
if i == 0:
polygon[-1] = polygon[0]
if removed:
count_building += 1
message ("\tRemoved %i redundant nodes in %i buildings\n" % (count_remove, count_building))
# Upddate corner dict
def update_corner(corners, wall, node, used):
if node not in corners:
corners[node] = {
'used': 0,
'walls': []
}
if wall:
wall['nodes'].append(node)
corners[node]['used'] += used
corners[node]['walls'].append(wall)
# Make square corners if possible.
# Based on method used by JOSM:
# https://josm.openstreetmap.de/browser/trunk/src/org/openstreetmap/josm/actions/OrthogonalizeAction.java
# The only input data required is the building dict, where each member is a standard geojson feature member.
# Supports single polygons, multipolygons (outer/inner) and group of connected buildings.
def rectify_buildings():
message ("Rectify building polygons ...\n")
message ("\tThreshold for square corners: 90 +/- %i degrees\n" % angle_margin)
message ("\tMinimum length of wall: %.2f meters\n" % short_margin)
# First identify nodes used by more than one way (usage > 1)
count = 0
nodes = {}
for ref, building in iter(buildings.items()):
if building['geometry']['type'] == "Polygon":
for polygon in building['geometry']['coordinates']:
for node in polygon[:-1]:
if node not in nodes:
nodes[ node ] = {
'use': 1,
'parents': [building]
}
else:
nodes[ node ]['use'] += 1
if building not in nodes[ node ]['parents']:
nodes[ node ]['parents'].append( building )
count += 1
building['neighbours'] = [ building ]
# Add list of neighbours to each building (other buildings which share one or more node)
for node in nodes.values():
if node['use'] > 1:
for parent in node['parents']:
for neighbour in node['parents']:
if neighbour not in parent['neighbours']:
parent['neighbours'].append(neighbour) # Including self
message ("\t%i nodes used by more than one building\n" % count)
# Then loop buildings and rectify where possible.
count_rectify = 0
count_not_rectify = 0
count_remove = 0
count = 0
for ref, building_test in iter(buildings.items()):
count += 1
message ("\r\t%i " % count)
if building_test['geometry']['type'] != "Polygon" or "rectified" in building_test:
continue
# 1. First identify buildings which are connected and must be rectified as a group
building_group = []
check_neighbours = building_test['neighbours'] # includes self
while check_neighbours:
for neighbour in check_neighbours[0]['neighbours']:
if neighbour not in building_group and neighbour not in check_neighbours:
check_neighbours.append(neighbour)
building_group.append(check_neighbours[0])
check_neighbours.pop(0)
if len(building_group) > 1:
building_test['properties']['VERIFY_GROUP'] = str(len(building_group))
# 2. Then build data structure for rectification process.
# "walls" will contain all (almost) straight segments of the polygons in the group.
# "corners" will contain all the intersection points between walls.
corners = {}
walls = []
conform = True # Will be set to False if rectification is not possible
for building in building_group:
building['ways'] = []
angles = []