-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathn50osm.py
3912 lines (2958 loc) · 125 KB
/
n50osm.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 zipfile
from io import BytesIO, TextIOWrapper
import json
import csv
import copy
import sys
import os
import time
import math
from xml.etree import ElementTree as ET
import utm
version = "2.1.1"
header = {"User-Agent": "nkamapper/n50osm"}
ssr_folder = "~/Jottacloud/osm/stedsnavn/" # Folder containing import SSR files (default folder tried first)
coordinate_decimals = 7 # Decimals in coordinate output
island_size = 100000 # Minimum square meters for place=island vs place=islet
lake_ele_size = 2000 # Minimum square meters for fetching elevation
max_stream_error = 1.0 # Minimum meters of elevation difference for turning direction of streams
simplify_factor = 0.2 # Threshold for simplification
max_combine_members = 10 # Maximum members for a wood feature to be combined
max_connected_area = 20 # Maximum area of ÅpentOmråde to be simplified (m2)
historic = {} # Get historic municipality, otherwise empty for current
debug = False # Include debug tags and unused segments
n50_tags = False # Include property tags from N50 in output
json_output = False # Output complete and unprocessed geometry in geojson format
elvis_output = False # Output NVE river/stream network in geojson format
elvis_centerline = False # Use river centerlines from Elvis (override any N50 centerlines)
border_output = True # Output municipality border
no_duplicate = True # Remove short river/stream duplicates along municipality boundary
turn_stream = True # Load elevation data to check direction of streams
lake_ele = True # Load elevation for lakes
get_name = True # Load SSR place names
get_nve = True # Load NVE lake and river data
merge_node = True # Merge common nodes at intersections
simplify = True # Simplify geometry lines
merge_grid = True # Merge polygon grids (wood and rivers)
data_categories = ["AdministrativeOmrader", "Arealdekke", "BygningerOgAnlegg", "Hoyde", "Restriksjonsomrader", "Samferdsel", "Stedsnavn"]
avoid_objects = [ # Object types to exclude from output
'ÅpentOmråde', 'Tregruppe', 'InnsjøMidtlinje', # Arealdekke
'GangSykkelveg', 'VegSenterlinje', 'Vegsperring', # Samferdsel
'Forsenkningskurve', 'Hjelpekurve', 'Høydekurve', # Hoyde
'PresentasjonTekst', # Stedsnavn
'Dataavgrensning'
]
auxiliary_objects = ['Arealbrukgrense', 'Dataavgrensning', 'FiktivDelelinje',
'InnsjøElvSperre', 'InnsjøInnsjøSperre', 'ElvBekkKant', 'ElveKant',
'Havflate', 'Innsjøkant', 'InnsjøkantRegulert', 'FerskvannTørrfallkant']
avoid_tags = [ # N50 properties to exclude from output (unless debug)
'oppdateringsdato', 'datafangstdato',
'målemetode', 'nøyaktighet'
]
object_sorting_order = [ # High priority will ensure ways in same direction
'Havflate', 'Innsjø', 'InnsjøRegulert', 'ElvBekk', 'Elv', 'FerskvannTørrfall', 'SnøIsbre',
'BymessigBebyggelse', 'Tettbebyggelse', 'Hyttefelt', 'Industriområde', 'Gravplass', 'Park',
'SportIdrettPlass', 'Alpinbakke', 'Golfbane', 'Lufthavn', 'Rullebane', 'Skytefelt',
'DyrketMark', 'Steinbrudd', 'Steintipp',' Myr', 'Skog'
]
segment_sorting_order = [ # High priority will ensure longer ways
'Kystkontur', 'HavInnsjøSperre', 'HavElvSperre',
'Innsjøkant', 'InnsjøkantRegulert', 'InnsjøInnsjøSperre', 'InnsjøElvSperre', 'ElvBekkKant', 'ElveKant', 'FerskvannTørrfallkant',
'Arealbrukgrense', 'FiktivDelelinje']
osm_tags = {
# AdministrativeOmrader
'Grunnlinjepunkt': { 'boundary': 'point' },
'Teiggrensepunkt': { 'boundary': 'marker' },
# Arealdekke
'Alpinbakke': { 'landuse': 'winter_sports', 'piste:type': 'downhill' }, # Later also area=yes for closed ways
'BymessigBebyggelse': { 'landuse': 'retail' },
'DyrketMark': { 'landuse': 'farmland' },
'Elv': { 'natural': 'water', 'water': 'river' },
'ElvBekk': { 'waterway': 'stream' }, # Retagged later if river or area
'ElvMidtlinje': { 'waterway': 'river' },
'FerskvannTørrfall': { 'natural': 'water', 'water': 'river', 'intermittent': 'yes' },
'Flomløpkant': { 'intermittent': 'yes' }, # Incomplete river objects; fix manually in JOSM
'Foss': { 'waterway': 'waterfall' },
'Golfbane': { 'leisure': 'golf_course' },
'Gravplass': { 'landuse': 'cemetery' },
'HavElvSperre': { 'natural': 'coastline' },
'HavInnsjøSperre': { 'natural': 'coastline' },
'Hyttefelt': { 'landuse': 'residential', 'residential': 'cabin' }, # Removed from 2023-11-20
'Industriområde': { 'landuse': 'industrial' },
'Innsjø': { 'natural': 'water' },
'InnsjøRegulert': { 'natural': 'water', 'water': 'reservoir' },
'KanalGrøft': { 'waterway': 'ditch' },
'Kystkontur': { 'natural': 'coastline' },
'Lufthavn': { 'aeroway': 'aerodrome' },
'Myr': { 'natural': 'wetland', 'wetland': 'bog' },
'Park': { 'leisure': 'park' },
'Rullebane': { 'aeroway': 'runway' },
'Skjær': { 'seamark:type': 'rock' },
'Skog': { 'natural': 'wood' },
'Skytefelt': { 'leisure': 'pitch', 'sport': 'shooting' },
'SnøIsbre': { 'natural': 'glacier' },
'SportIdrettPlass': { 'leisure': 'pitch' },
'Steinbrudd': { 'landuse': 'quarry'},
'Steintipp': { 'landuse': 'landfill' },
'Tettbebyggelse': { 'landuse': 'residential' },
# Samferdsel
'Barmarksløype': { 'highway': 'track' },
'Traktorveg': { 'highway': 'track' },
'Sti': { 'highway': 'path' },
# Hoyde
'Terrengpunkt': { 'natural': 'hill' },
'TrigonometriskPunkt': { 'man_made': 'survey_point', 'natural': 'hill' },
# Restriksjonsomrader
'Naturvernområde': { 'boundary': 'protected_area' },
'Allmenning': { 'boundary': 'protected_area', 'protect_class': '27'}, # Public land
# BygningerOgAnlegg
'Bygning': { 'building': 'yes' },
'Campingplass': { 'tourism': 'camp_site' },
'Dam': { 'waterway': 'dam' },
'Flytebrygge': { 'man_made': 'pier', 'floating': 'yes' },
'Gruve': { 'man_made': 'adit' }, # Could be shaft
'Hoppbakke': { 'piste:type': 'ski_jump' },
'KaiBrygge': { 'man_made': 'quay' },
'Ledning': { 'power': 'line' },
'LuftledningLH': { 'power': 'line' },
'Lysløype': { 'highway': 'track', 'lit': 'yes', 'trailblazed': 'yes' },
'MastTele': { 'man_made': 'mast', 'tower:type': 'communication' },
'Molo': { 'man_made': 'breakwater' },
'Navigasjonsinstallasjon': { 'man_made': 'lighthouse' }, # Only lighthouses, it seems
'Parkeringsområde': { 'amenity': 'parking' },
'Pir': { 'man_made': 'pier' },
'Reingjerde': { 'barrier': 'fence' },
'Rørgate': { 'man_made': 'pipeline' }, # Also "tømmerrenne"
'Skitrekk': { 'aerialway': 'drag_lift' }, # Could be other aerialway values
'Skytebaneinnretning': { 'leisure': 'pitch', 'sport': 'shooting' },
'Tank': { 'man_made': 'tank' },
'Taubane': { 'aerialway': 'cable_car' }, # Could be other aerial values, e.g. gondola, goods
'Tårn': { 'man_made': 'tower' }, # Any massive or substantial tower
'Vindkraftverk': { 'power': 'generator', 'generator:source': 'wind', 'generator:type': 'horizontal_axis' }
}
# OSM tagging; first special cases
def tag_object(feature_type, geometry_type, properties, feature):
tags = {}
missing_tags = set()
# First special object cases
if feature_type == "ElvBekk":
if geometry_type == "område":
tags['natural'] = "water"
tags['water'] = "river"
elif ("vannBredde" in properties and properties['vannBredde'] > "2"
or "vannbredde" in properties and properties['vannbredde'] > "2"): # >3 meter
tags['waterway'] = "river"
else:
tags['waterway'] = "stream"
elif feature_type == "KanalGrøft":
if ("vannBredde" in properties and properties['vannBredde'] > "2"
or "vannbredde" in properties and properties['vannbredde'] > "2"): # >3 meter
tags['waterway'] = "canal"
else:
tags['waterway'] = "ditch"
elif feature_type == "Skytefelt" and data_category == "Restriksjonsomrader": # Exception to Arealdekke
if "Sytefeltstatus" not in properties or properties['Skytefeltstatus'] == "I bruk":
tags['landuse'] = "military"
elif feature_type == "Bygning":
if "bygningstype" in properties:
if properties['bygningstype'] == "956": # Turisthytte
if "betjeningsgrad" in properties:
if properties['betjeningsgrad'] in ["B", "Betjent"]:
tags['tourism'] = "alpine_hut"
elif properties['betjeningsgrad'] == ["S", "Selvbetjent"]:
tags['tourism'] = "wilderness_hut"
elif properties['betjeningsgrad'] in ["U", "R", "Ubetjent", "Rastebu"]:
tags['amenity'] = "shelter"
tags['shelter_type'] = "basic_hut"
elif properties['betjeningsgrad'] in ["D", "Serveringshytte"]:
tags['amenity'] = "cafe"
tags['hiking'] = "yes"
elif properties['betjeningsgrad'] in ["G", "Gapahuk"]:
tags['amenity'] = "shelter"
tags['shelter_type'] = "lean_to"
if "hytteeier" in properties:
if properties['hytteeier'] == "1":
tags['operator'] = "DNT"
elif properties['hytteeier'] == "3":
tags['operator'] = "Fjellstyre"
elif properties['hytteeier'] == "4":
tags['operator'] = "Statskog"
elif properties['bygningstype'] in building_tags:
for key, value in iter(building_tags[ properties['bygningstype'] ].items()):
if geometry_type == "område" or key != "building": # or len(building_tags[ properties['bygningstype'] ]) > 1:
tags[ key ] = value
if geometry_type != "posisjon" and "building" not in tags:
tags['building'] = "yes" # No building tag for single nodes
elif feature_type == "Lufthavn":
if "lufthavntype" in properties and properties['lufthavntype'] == "H":
tags['aeroway'] = "heliport"
else:
tags['aeroway'] = "aerodrome"
if "trafikktype" in properties:
if properties['trafikktype'] == "I":
tags['aerodrome:type'] = "international"
elif properties['trafikktype'] == "N":
tags['aerodrome:type'] = "regional"
elif properties['trafikktype'] == "A":
tags['aerodrome:type'] = "airfield"
if "iataKode" in properties and properties['iataKode'] != "XXX":
tags['iata'] = properties['iataKode']
if "icaoKode" in properties and properties['icaoKode'] != "XXXX":
tags['icao'] = properties['icaoKode']
elif feature_type == "SportIdrettPlass" and geometry_type == "område":
if len(feature['coordinates']) > 1:
tags['leisure'] = "track"
# tags['area'] = "yes"
else:
tags['leisure'] = "pitch"
if "grensepunkttype" in properties and properties['grensepunkttype'] == "58": # Grenserøys
tags['man_made'] = "cairn"
if "grensepunktnummer" in properties and properties['grensepunktnummer']:
tags['ref'] = properties['grensepunktnummer']
# Then conversion dict
elif feature_type in osm_tags:
tags.update( osm_tags[feature_type] )
# Collect set of remaining object types not handled
elif feature_type not in avoid_objects and feature_type not in auxiliary_objects:
missing_tags.add(feature_type)
# Additional tagging based on object properties from GML
if "høyde" in properties:
tags['ele'] = properties['høyde'] # No decimals
if "lavesteRegulerteVannstand" in properties:
tags['ele:min'] = properties['lavesteRegulerteVannstand']
if "vatnLøpenummer" in properties:
tags['ref:nve:vann'] = properties['vatnLøpenummer']
if "navn" in properties:
tags['name'] = properties['navn']
if "fulltekst" in properties:
tags['name'] = properties['fulltekst']
if "stedsnummer" in properties:
tags['ssr:stedsnr'] = properties['stedsnummer']
if "merking" in properties and properties['merking'] == "JA":
tags['trailblazed'] = "yes"
if "verneform" in properties:
if properties['verneform'] in ["NP", "NPS"]:
tags['boundary'] = "national_park"
elif properties['verneform'] in ["LVO", "NM"]:
tags['boundary'] = "protected_area"
else:
tags['leisure'] = "nature_reserve"
if "grensepunkttype" in properties and properties['grensepunkttype'] == "58": # Grenserøys
tags['man_made'] = "cairn"
if "grensepunktnummer" in properties:
tags['ref'] = properties['grensepunktnummer']
if "grunnlinjepunktnummer" in properties:
tags['ref'] = properties['grunnlinjepunktnummer']
if "lengde" in properties and feature_type == "Hoppbakke":
tags['ref'] = "K" + properties['lengde']
return (tags, missing_tags)
# Output message
def message (output_text):
sys.stdout.write (output_text)
sys.stdout.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
# 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 * 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][1] - coord[i][1]) * (coord[i+1][0] + coord[i][0]) # (x2-x1)(y2+y1)
return int(area / 2.0)
else:
return 0
# Calculate coordinate area of multipolygon, i.e. excluding inner polygons
def multipolygon_area (multipolygon):
if type(multipolygon) is list and len(multipolygon) > 0 and type(multipolygon[0]) is list and \
multipolygon[0][0] == multipolygon[0][-1]:
area = polygon_area(multipolygon[0])
for patch in multipolygon[1:]:
inner_area = polygon_area(patch)
if inner_area:
area -= inner_area
else:
return None
return area
else:
return None
# Calculate centroid of polygon
# Source: https://en.wikipedia.org/wiki/Centroid#Of_a_polygon
def polygon_centroid (polygon):
if polygon[0] == polygon[-1]:
x = 0
y = 0
det = 0
for i in range(len(polygon) - 1):
d = polygon[i][0] * polygon[i+1][1] - polygon[i+1][0] * polygon[i][1]
det += d
x += (polygon[i][0] + polygon[i+1][0]) * d # (x1 + x2) (x1*y2 - x2*y1)
y += (polygon[i][1] + polygon[i+1][1]) * d # (y1 + y2) (x1*y2 - x2*y1)
return (x / (3.0 * det), y / (3.0 * det) )
else:
return None
# 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
# Test whether point (x,y) is inside a multipolygon, i.e. not inside inner polygons
def inside_multipolygon (point, multipolygon):
if type(multipolygon) is list and len(multipolygon) > 0 and type(multipolygon[0]) is list and \
multipolygon[0][0] == multipolygon[0][-1]:
inside = inside_polygon(point, multipolygon[0])
if inside:
for patch in multipolygon[1:]:
inside = (inside and not inside_polygon(point, patch))
if not inside:
break
return inside
else:
return None
# 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, get_point=False):
x1, y1, x2, y2, x3, y3 = map(math.radians, [s1[0], s1[1], s2[0], s2[1], p3[0], p3[1]]) # Note: (x,y)
# 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 get_point:
# Project back to longitude/latitude
x4 = x4 / math.cos(y4)
lon = math.degrees(x4)
lat = math.degrees(y4)
return (distance, (lon, lat))
else:
return distance
# Calculate shortest distance from node p to line.
def shortest_distance(p, line):
d_min = 999999.9 # Dummy
position = None
for i in range(len(line) - 1):
d = line_distance(line[i], line[i+1], p)
if d < d_min:
d_min = d
position = i
return (d_min, position)
# Calculate new node with given distance offset in meters
# Works over short distances
def coordinate_offset (node, distance):
m = (math.pi / 180.0) * 6378137.0 # Meters per degree, ca 111 km
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
# Optional arguments:
# - 'limit' will break early if distance is above the limit (meters)
# - 'oneway' = True will only test p1 against p2, not the reverse
# - 'hits' = True will return list of index to nodes which were within given 'limit'
def hausdorff_distance (p1, p2, limit = False, oneway = False, hits = False):
N1 = len(p1) # Subtract 1 for circular polygons
N2 = len(p2)
# Shuffling for small lists disabled
# random.shuffle(p1)
# random.shuffle(p2)
h = []
cmax = 0
for i in range(N1):
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 < cmax and not hits:
no_break = False
break
if d < cmin:
cmin = d
if cmin < 999999.9 and cmin > cmax and no_break:
cmax = cmin
if cmax > limit and limit and not hits:
return cmax
if cmin <= limit and hits:
h.append(i)
if oneway:
return cmax
if hits:
return h
for i in range(N2):
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 < cmax:
no_break = False
break
if d < cmin:
cmin = d
if cmin < 999999.9 and cmin > cmax and no_break:
cmax = cmin
if limit and cmax > limit:
return cmax
return cmax
# Identify bounds of line coordinates
# Returns lower left and upper right corners of square bounds + extra perimeter (in meters)
def get_bbox(coordinates, perimeter = 0):
if type(coordinates) is tuple:
patch = [ coordinates ]
elif type(coordinates[0]) is tuple:
patch = coordinates
else:
patch = coordinates[0]
min_node = list(patch[0])
max_node = copy.deepcopy(min_node)
for node in patch:
for i in [0,1]:
min_node[i] = min(min_node[i], node[i])
max_node[i] = max(max_node[i], node[i])
if perimeter > 0:
min_node = coordinate_offset(min_node, - perimeter)
max_node = coordinate_offset(max_node, + perimeter)
return [min_node, max_node]
# Add FIXME tags
def tag_fixme(tags, value):
if "FIXME" in tags:
tags['FIXME'] += "; " + value
else:
tags['FIXME'] = value
# Create feature with one point
def create_point (node, tags, gml_id = None, object_type = "Debug"):
entry = {
'object': object_type,
'type': 'Point',
'coordinates': node,
'members': [],
'tags': {},
'extras': {'objekttype': object_type}
}
if isinstance(tags, str):
entry['extras']['note'] = tags
elif object_type == "Debug":
entry['extras'].update(tags)
else:
entry['tags'].update(tags)
if gml_id:
entry['gml_id'] = gml_id
if debug or object_type != "Debug":
features.append(entry)
# Get list of coordinates from GML
# Each point is a tuple of (lon, lat), corresponding to GeoJSON format x,y
def parse_coordinates (coord_text):
global gml_id
parse_count = 0
split_coord = coord_text.split(" ")
coordinates = []
for i in range(0, len(split_coord) - 1, 2):
x = float(split_coord[i])
y = float(split_coord[i+1])
[lat, lon] = utm.UtmToLatLon (x, y, utm_zone, "N")
node = ( round(lon, coordinate_decimals), round(lat, coordinate_decimals) )
parse_count += 1
if not coordinates or node != coordinates[-1] or json_output:
coordinates.append(node)
else:
# message ("\t*** DELETED DUPLICATE NODE: %s %s\n" % (node, gml_id))
create_point(node, "deleted duplicate", gml_id=gml_id)
# Remove single outlayer node
if not json_output:
i = 0
while i < len(coordinates):
if i > 1 and coordinates[i] == coordinates[i - 2]:
# message ("\t*** DELETED ARTEFACT NODE: %s %s\n" % (coordinates[ i - 1 ], gml_id))
create_point(copy.deepcopy(coordinates[ i - 1 ]), "deleted artefact", gml_id=gml_id)
coordinates.pop(i)
coordinates.pop(i - 1)
i -= 1
else:
i += 1
if len(coordinates) > 2 and coordinates[0] == coordinates[-1] and coordinates[1] == coordinates[-2] :
# message ("\t*** DELETED ARTEFACT NODE: %s %s\n" % (coordinates[ 0 ], gml_id))
coordinates = coordinates[ 1: -1 ]
# if len(coordinates) == 1 and parse_count > 1:
# message ("\t*** SHORT WAY %s\n" % gml_id)
return coordinates
# Get current name or id of municipality from GeoNorge api
def get_present_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']
# municipality_bbox = [ result['avgrensningsboks']['coordinates'][0][0], result['avgrensningsboks']['coordinates'][0][2]]
# return (query, municipality_name, municipality_bbox)
return (query, municipality_name, None)
else:
result = json.load(file)
file.close()
if result['antallTreff'] == 1:
municipality_id = result['kommuner'][0]['kommunenummer']
municipality_name = result['kommuner'][0]['kommunenavnNorsk']
# municipality_bbox = [ result['kommuner'][0]['avgrensningsboks']['coordinates'][0][0], result['kommuner'][0]['avgrensningsboks']['coordinates'][0][2] ]
# return (municipality_id, municipality_name, municipality_bbox)
return (municipality_id, municipality_name, None)
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 municipality info, including for historic municiplaities
def get_municipality_name (query, get_historic=False):
# API below cuerrently do not support 2024 municipality reform
if not get_historic:
return get_present_municipality_name(query)
# Search by municipality ref or name
url = "https://ws.geonorge.no/kommunereform/v1/endringer/?sok=" + urllib.parse.quote(query.replace("-", " "))
request = urllib.request.Request(url, headers=header)
file = urllib.request.urlopen(request)
result1 = json.load(file)
file.close()
found = []
all_found = []
for municipality in result1['data']:
if get_historic == ("gyldigtil" in municipality) or get_historic and municipality['navn'] == "STAVANGER":
all_found.append(municipality)
if municipality['navn'] == query.upper() or municipality['id'] == query:
found.append(municipality)
if len(all_found) == 1:
found = all_found
# One municipality found
if len(found) == 1:
name = found[0]['navn'].title().replace(" I ", " i ").replace(" Og ", " og ")
ref = found[0]['id']
if not get_historic:
# One current match
return (ref, name, {})
else:
# Special case for Stavanger, not covered by API
if name == "Stavanger":
historic = {
'year': '2019',
'id': '1103',
'name': 'Stavanger'
}
return ("1103", "Stavanger", historic)
# Get associated current municipality
url = "https://ws.geonorge.no/kommunereform/v1/endringer/" + ref
request = urllib.request.Request(url, headers=header)
file = urllib.request.urlopen(request)
result2 = json.load(file)
file.close()
new_ref = result2['data']['erstattetav'][0]['id']
url = "https://ws.geonorge.no/kommunereform/v1/endringer/" + new_ref
request = urllib.request.Request(url, headers=header)
file = urllib.request.urlopen(request)
result3 = json.load(file)
file.close()
new_name = result2['data']['erstattetav'][0]['navn'].title().replace(" I ", " i ").replace(" Og ", " og ")
year = str(int(result2['data']['kommune']['gyldigtil'][:4]) - 1)
historic = {
'year': year,
'id': ref,
'name': name
}
if len(result3['data']['erstatter']) == 1:
sys.exit("Current N50 data for %s %s same as for historic %s %s in %s\n\n" % (new_ref, new_name, ref, name, year))
elif historic['year'] < "2018":
sys.exit("%s %s existed until %s, however historic N50 data not available before 2018\n\n" % (ref, name, year))
else:
return (new_ref, new_name, historic)
# More than one match
elif len(all_found) > 1:
municipalities = []
for municipality in all_found:
name = municipality['navn'].title().replace(" I ", " i ").replace(" Og ", " og ")
if name in ["Våler", "Herøy"] or get_historic and name in ["Bø", "Sande", "Os", "Nes"]:
name += " (%s)" % municipality['fylke'].title().replace(" Og ", " og ")
if "gyldigtil" in municipality:
name += " [%s]" % str(int(municipality['gyldigtil'][:4]) - 1)
municipalities.append(municipality['id'] + " " + name)
sys.exit("More than one municipality found: %s\n\n" % ", ".join(municipalities))
else:
sys.exit("Municipality '%s' not found\n\n" % query)
# 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"
request = urllib.request.Request(url, headers=header)
try:
file = urllib.request.urlopen(request)
except urllib.error.HTTPError as err:
message("\t\t*** %s\n" % err)
return
building_csv = csv.DictReader(TextIOWrapper(file, "utf-8"), fieldnames=["id", "name", "building_tag", "extra_tag"], delimiter=";")
next(building_csv)
for row in building_csv:
tag_string = (row['building_tag'] + "+" + row['extra_tag']).strip().strip("+")
if tag_string:
osm_tag = {}
tag_list = tag_string.replace(" ","").split("+")
for tag_part in tag_list:
tag_split = tag_part.split("=")
osm_tag[ tag_split[0] ] = tag_split[1]
building_tags[ row['id'] ] = osm_tag
file.close()
# Compute length based on coordinates (not in meters)
def simple_length (coord):
length = 0
for i in range(len(coord) - 2):
length += (coord[i+1][0] - coord[i][0])**2 + ((coord[i+1][1] - coord[i][1])**2) * 0.5
return length
# Clean Norwegian characters from filename
def clean_filename(filename):
return filename.replace("Æ","E").replace("Ø","O").replace("Å","A").replace("æ","e").replace("ø","o").replace("å","a").replace(" ", "_")
# Split patch if self-intersecting or touching polygon
def split_patch (coordinates):
for i in range(1, len(coordinates) - 1):
first = coordinates.index(coordinates[i])
if first < i:
result1 = split_patch( coordinates[ : first ] + coordinates[ i: ] )
result2 = split_patch( coordinates[ first : i + 1 ])
# message ("\t*** SPLIT SELF-INTERSECTING/TOUCHING POLYGON: %s\n" % str(coordinates[i]))
if simple_length(result1[0]) > simple_length(result2[0]):
result1.extend(result2)
return result1
else:
result2.extend(result1)
return result2
return [ coordinates ]
# Get all app properties from nested XML; recursive search
def get_property(top, ns_app):
properties = {}
if ns_app in top.tag:
tag = top.tag[ len(ns_app)+2 : ]
value = top.text
value = value.strip()
if value:
properties[tag] = value
for child in top:
properties.update(get_property(child, ns_app))
return properties
# Get feature data from XML
def parse_feature(feature):
geometry_type = None
properties = {} # Attributes provided from GML
for app in feature[0]:
# Get app properties/attributes
tag = app.tag[ len(ns_app)+2 : ]
if tag in ['posisjon', 'grense', 'område', 'senterlinje', 'geometri']:
geometry_type = tag
else:
properties.update(get_property(app, ns_app))
# Get geometry/coordinates
for geo in app:
# Point
if geo.tag == "{%s}Point" % ns_gml:
coord_type = "Point"
coordinates = parse_coordinates(geo[0].text)[0]
# LineString
elif geo.tag == "{%s}LineString" % ns_gml:
if geometry_type != "geometri":
coord_type = "LineString"
coordinates = parse_coordinates(geo[0].text)
else: