-
Notifications
You must be signed in to change notification settings - Fork 88
/
boundaries.py
executable file
·2241 lines (1830 loc) · 81.4 KB
/
boundaries.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 python
from __future__ import print_function
import errno
import os
import sys
import xml.sax
from xml.sax.handler import ContentHandler
import yaml
from lxml import etree
from subprocess import Popen, PIPE
# The following are only used by doctests, hence noqa
import shutil # noqa
from tempfile import mkdtemp, NamedTemporaryFile # noqa
from django.utils.six import StringIO
from django.utils.six.moves import urllib
with open(os.path.join(
os.path.dirname(__file__), '..', 'conf', 'general.yml')) as f:
config = yaml.load(f)
CACHE_VISITED = set()
# Suggested by http://stackoverflow.com/q/600268/223092
def mkdir_p(path):
"""Create a directory (and parents if necessary) like mkdir -p
For example:
>>> test_directory = mkdtemp()
>>> new_directory = os.path.join(test_directory, "foo", "bar")
>>> mkdir_p(new_directory)
>>> os.path.exists(new_directory)
True
>>> os.path.isdir(new_directory)
True
There should be no error if the directory already exists:
>>> mkdir_p(new_directory)
But if there is another error, e.g. permissions prevent the
directory from being created:
>>> os.chmod(new_directory, 0)
>>> new_subdirectory = os.path.join(new_directory, "baz")
>>> mkdir_p(new_subdirectory) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
OSError: [Errno 13] Permission denied: '/tmp/tmp64Q8MJ/foo/bar/baz'
Remove the temporary directory created for these doctests:
>>> os.chmod(new_directory, 0755)
>>> shutil.rmtree(test_directory)
"""
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise
def get_query_relation_and_dependents(element_type, element_id):
return """<osm-script timeout="3600">
<union into="_">
<id-query into="_" ref="%s" type="%s"/>
<recurse from="_" into="_" type="down"/>
</union>
<print from="_" limit="" mode="body" order="id"/>
</osm-script>
""" % (element_id, element_type)
def get_query_relations_and_ways(required_tags):
has_kv = "\n".join(' <has-kv k="%s" modv="" v="%s"/>' % (k, v)
for k, v in required_tags.items())
return """<osm-script timeout="3600">
<union into="_">
<query into="_" type="relation">
%s
</query>
<query into="_" type="way">
%s
</query>
</union>
<print from="_" limit="" mode="body" order="id"/>
</osm-script>""" % (has_kv, has_kv)
def get_from_overpass(query_xml, filename):
if config.get('LOCAL_OVERPASS'):
return get_osm3s(query_xml)
else:
if not os.path.exists(filename):
return get_remote(query_xml, filename)
return open(filename).read()
def get_osm3s(query_xml):
p = Popen(["osm3s_query",
"--concise",
"--db-dir=" + config['OVERPASS_DB_DIRECTORY']],
stdin=PIPE,
stdout=PIPE)
out, err = p.communicate(query_xml)
if p.returncode != 0:
raise Exception("The osm3s_query failed")
return out
def get_remote(query_xml, filename):
url = config['OVERPASS_SERVER']
values = {'data': query_xml}
encoded_values = urllib.parse.urlencode(values)
request = urllib.request.Request(url, encoded_values)
response = urllib.request.urlopen(request)
data = response.read()
with open(filename, "w") as fp:
fp.write(data)
return data
def get_cache_filename(element_type, element_id, cache_directory=None):
if cache_directory is None:
script_directory = os.path.dirname(os.path.abspath(__file__))
cache_directory = os.path.join(script_directory,
'..',
'data',
'new-cache')
element_id = int(element_id, 10)
subdirectory = "%03d" % (element_id % 1000,)
full_subdirectory = os.path.join(cache_directory,
element_type,
subdirectory)
mkdir_p(full_subdirectory)
basename = "%s-%d.xml" % (element_type, element_id)
return os.path.join(full_subdirectory, basename)
def get_name_from_tags(tags, element_type=None, element_id=None):
"""Given an OSMElement, return a readable name if possible
If there's a name tag (typically the local spelling of the
element), then use that:
>>> tags = {'name': 'Deutschland',
... 'name:en': 'Federal Republic of Germany'}
>>> get_name_from_tags(tags, 'relation', '51477')
'Deutschland'
Or fall back to the English name, if that's the only option:
>>> tags = {'name:en': 'Freedonia', 'relation': '345678'}
>>> get_name_from_tags(tags)
'Freedonia'
Otherwise, use the type and ID to form a readable name:
>>> get_name_from_tags({}, 'node', '65432')
'Unknown name for node with ID 65432'
Or if we've no information at all, just return 'Unknown':
>>> get_name_from_tags({})
'Unknown'
"""
if 'name' in tags:
return tags['name']
elif 'name:en' in tags:
return tags['name:en']
elif 'place_name' in tags:
return tags['place_name']
elif element_type and element_id:
return "Unknown name for %s with ID %s" % (element_type, element_id)
else:
return "Unknown"
def get_non_contained_elements(elements):
"""Filter elements, keeping only those which are not a member of another
As an example, you can do the following:
>>> top = Relation("13")
>>> sub = Relation("14")
>>> top.children.append((sub, ''))
>>> lone = Way("15")
>>> get_non_contained_elements([top, sub, lone])
[Relation(id="13", members=1), Way(id="15", nodes=0)]
"""
contained_elements = set([])
for e in elements:
if e.element_type == "relation":
for member, role in e:
contained_elements.add(member)
return [e for e in elements if e not in contained_elements]
class OSMElement(object):
def __init__(self, element_id, element_content_missing=False, element_type=None):
self.element_id = element_id
self.element_type = element_type or "BUG"
self.missing = element_content_missing
def __lt__(self, other):
return int(self.element_id, 10) < int(other.element_id, 10)
def __eq__(self, other):
"""Define equality of OSMElements as same (OSM) type and ID
For example, they should be equal even if one is of the base
class and one the subclass:
>>> missing = OSMElement('42', element_content_missing=True, element_type='node')
>>> real = Node('42')
>>> missing == real
True
But non-OSMElements aren't equal:
>>> real == ('node', '42')
False
And elements of different type aren't equal:
>>> real == Relation('42')
False
"""
if not isinstance(other, OSMElement):
return False
if self.element_type == other.element_type:
return self.element_id == other.element_id
return False
def __ne__(self, other):
"""Inequality is just the negation of equality
>>> Node('42') != Relation('42')
True
>>> Node('42') != Node('8')
True
"""
return not self.__eq__(other)
def __hash__(self):
return hash(self.element_id)
def name_id_tuple(self):
"""Return the OSM type and ID as a tuple
This is sometimes useful for a lower-memory representation of
elements. (Debatably - this should be considered for removal.)
FIXME: also should rename this to type_id_tuple
>>> n = Node('123456', latitude="52", longitude="0")
>>> n.tags['name'] = 'Cambridge'
>>> n.name_id_tuple()
('node', '123456')
"""
return (self.element_type, self.element_id)
def get_name(self):
"""Get a human-readable name for the element, if possible
>>> germany = Relation("51477")
>>> tags = {'name': 'Deutschland',
... 'name:en': 'Federal Republic of Germany'}
>>> germany.tags.update(tags)
>>> germany.get_name()
'Deutschland'
"""
return get_name_from_tags(self.tags, self.element_type, self.element_id)
@property
def element_content_missing(self):
return self.missing
@staticmethod
def make_missing_element(element_type, element_id):
"""Create an element for which we only know the type and ID
It is useful to be able to represent OSM elements that we've
just seen mentioned as members of relations, but haven't
actually parsed. You can use this static method to create a
node of such a type:
>>> OSMElement.make_missing_element('node', '42')
Node(id="42", missing)
>>> OSMElement.make_missing_element('way', '7')
Way(id="7", missing)
>>> OSMElement.make_missing_element('relation', '13')
Relation(id="13", missing)
>>> OSMElement.make_missing_element('other', '2')
Traceback (most recent call last):
...
Exception: Unknown element name 'other'
"""
if element_type == "node":
return Node(element_id, element_content_missing=True)
elif element_type == "way":
return Way(element_id, element_content_missing=True)
elif element_type == "relation":
return Relation(element_id, element_content_missing=True)
else:
raise Exception("Unknown element name '%s'" % (element_type,))
def __repr__(self):
"""A returns simple repr-style representation of the OSMElement
For example:
>>> OSMElement('23', element_type='node')
OSMElement(id="23", type="node")
>>> OSMElement('25', element_content_missing=True, element_type='relation')
OSMElement(id="25", type="relation", missing)
"""
if self.element_content_missing:
return 'OSMElement(id="%s", type="%s", missing)' % (self.element_id,
self.element_type)
else:
return 'OSMElement(id="%s", type="%s")' % (self.element_id,
self.element_type)
def get_missing_elements(self, to_append_to=None):
"""Return a list of element type, id tuples of missing elements
In the case of an element without children, this should either
return an empty list or a list with this element in it,
depending on whether it's marked as missing or not:
>>> missing = OSMElement('42', element_content_missing=True, element_type="node")
>>> missing.get_missing_elements()
[('node', '42')]
>>> present = OSMElement('42', element_type="node")
>>> present.get_missing_elements()
[]
If to_append_to is supplied, the missing elements should be
appended to that array, and the same array returned:
>>> l = []
>>> result = missing.get_missing_elements(l)
>>> l is result
True
>>> l
[('node', '42')]
"""
if to_append_to is None:
to_append_to = []
if self.element_content_missing:
to_append_to.append(self.name_id_tuple())
return to_append_to
@staticmethod
def xml_wrapping():
"""Get an XML element that OSM nodes/ways/relations can be added to
The returned object is an etree.Element, which can be
pretty-printed with etree.tostring:
>>> print(
... etree.tostring(OSMElement.xml_wrapping(),
... pretty_print=True), end='') # doctest: +NORMALIZE_WHITESPACE
<osm generator="mySociety Boundary Extractor" version="0.6">
<note>The data included in this document is from www.openstreetmap.org.
It has there been collected by a large group of contributors.
For individual attribution of each item please refer to
http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history</note>
</osm>
"""
osm = etree.Element("osm", attrib={"version": "0.6",
"generator": "mySociety Boundary Extractor"})
note = etree.SubElement(osm, "note")
note.text = (
"The data included in this document is from www.openstreetmap.org. "
"It has there been collected by a large group of contributors. "
"For individual attribution of each item please refer to "
"http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history")
return osm
def xml_add_tags(self, xml_element):
"""Add the tags from this OSM element to an XML element
>>> n = Node('42')
>>> n.tags.update({'name': 'Venezia',
... 'name:en': 'Venice'})
>>> xe = etree.Element('example')
>>> n.xml_add_tags(xe)
>>> print(etree.tostring(xe, pretty_print=True), end='')
<example>
<tag k="name" v="Venezia"/>
<tag k="name:en" v="Venice"/>
</example>
"""
for k, v in sorted(self.tags.items()):
etree.SubElement(xml_element, 'tag', attrib={'k': k, 'v': v})
class Node(OSMElement):
"""Represents an OSM node
You can create a complete node as follows:
>>> cambridge = Node("12345", latitude="52.205", longitude="0.119")
>>> cambridge
Node(id="12345", lat="52.205", lon="0.119")
Each node has a tags attribute as well:
>>> cambridge.tags['name:en'] = "Cambridge"
The tags can be seen with the .pretty() representation:
>>> print(cambridge.pretty(4))
node (12345) lat: 52.205, lon: 0.119
name:en => Cambridge
If you only know the ID of the node, but not its latitude or
longitude yet, you can create it as a 'missing' node with a
static method from OSMElement:
>>> missing = OSMElement.make_missing_element("node", "321")
>>> missing
Node(id="321", missing)
"""
def __init__(self, node_id, latitude=None, longitude=None, element_content_missing=False):
super(Node, self).__init__(node_id, element_content_missing, 'node')
self.lat = latitude
self.lon = longitude
self.tags = {}
def pretty(self, indent=0):
i = " " * indent
result = i + "node (%s) lat: %s, lon: %s" % (self.element_id, self.lat, self.lon)
for k, v in sorted(self.tags.items()):
result += "\n%s %s => %s" % (i, k, v)
return result
def lon_lat_tuple(self):
"""Return the latitude and longitude as a tuple of two strings
>>> n = Node("1234", latitude="52", longitude="0.5")
>>> n.lon_lat_tuple()
('0.5', '52')
"""
return (self.lon, self.lat)
def __repr__(self):
if self.element_content_missing:
return 'Node(id="%s", missing)' % (self.element_id)
else:
return 'Node(id="%s", lat="%s", lon="%s")' % (self.element_id,
self.lat,
self.lon)
def to_xml(self, parent_element=None, include_node_dependencies=False):
"""Generate an XML element representing this node
If parent_element is supplied, it is added to that element and
returned. If no parent_element is supplied, an OSM XML root
element is created, and the generated <node> element is added
to that.
>>> n = Node("1234", latitude="51.2", longitude="-0.2")
>>> parent = etree.Element('example')
>>> result = n.to_xml(parent_element=parent)
>>> parent is result
True
>>> print(etree.tostring(parent, pretty_print=True), end='')
<example>
<node id="1234" lat="51.2" lon="-0.2"/>
</example>
>>> full_result = n.to_xml()
>>> print(etree.tostring(full_result, pretty_print=True), end='') # doctest: +NORMALIZE_WHITESPACE
<osm generator="mySociety Boundary Extractor" version="0.6">
<note>The data included in this document is from www.openstreetmap.org.
It has there been collected by a large group of contributors.
For individual attribution of each item please refer to
http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history</note>
<node id="1234" lat="51.2" lon="-0.2"/>
</osm>
"""
if parent_element is None:
parent_element = OSMElement.xml_wrapping()
node = etree.SubElement(parent_element,
'node',
attrib={'id': self.element_id,
'lat': self.lat,
'lon': self.lon})
self.xml_add_tags(node)
return parent_element
class Way(OSMElement):
"""Represents an OSM way as returned via the Overpass API
You can create a Way object as follows:
>>> Way("314159265")
Way(id="314159265", nodes=0)
Or supply a list of nodes:
>>> top_left = Node("12", latitude="52", longitude="1")
>>> top_right = Node("13", latitude="52", longitude="2")
>>> bottom_right = Node("14", latitude="51", longitude="2")
>>> bottom_left = Node("15", latitude="51", longitude="1")
>>> ns = [top_left,
... top_right,
... bottom_right,
... bottom_left]
>>> unclosed = Way("314159265", ns)
>>> unclosed
Way(id="314159265", nodes=4)
You can iterate over the nodes:
>>> for n in unclosed:
... print(n)
Node(id="12", lat="52", lon="1")
Node(id="13", lat="52", lon="2")
Node(id="14", lat="51", lon="2")
Node(id="15", lat="51", lon="1")
Or test if a node is closed or not:
>>> unclosed.closed()
False
>>> nsc = ns + [top_left]
>>> closed = Way("98765", nodes=nsc)
>>> closed.closed()
True
"""
def __init__(self, way_id, nodes=None, element_content_missing=False):
super(Way, self).__init__(way_id, element_content_missing, 'way')
self.nodes = nodes or []
self.tags = {}
def __iter__(self):
for n in self.nodes:
yield n
def __len__(self):
"""Allow len(way) to return the number of nodes
For example:
>>> w = Way("1", nodes=[Node("12", latitude="52", longitude="1"),
... Node("13", latitude="52", longitude="2"),
... Node("14", latitude="51", longitude="2")])
>>> len(w)
3
"""
return len(self.nodes)
def __getitem__(self, val):
"""Allow access to nodes with array notation
For example:
>>> w = Way('76543', nodes=[Node("12", latitude="52", longitude="1"),
... Node("13", latitude="52", longitude="2"),
... Node("14", latitude="51", longitude="2")])
>>> w[2]
Node(id="14", lat="51", lon="2")
"""
return self.nodes.__getitem__(val)
def pretty(self, indent=0):
"""Generate a fuller string representation of this way
For example:
>>> w = Way('76543', nodes=[Node("12", latitude="52", longitude="1"),
... Node("13", latitude="52", longitude="2"),
... Node("14", latitude="51", longitude="1"),
... Node("15", latitude="51", longitude="2")])
>>> w.tags['random_key'] = 'some value or other'
>>> w.tags['boundary'] = 'administrative'
>>> print(w.pretty(2))
way (76543)
boundary => administrative
random_key => some value or other
node (12) lat: 52, lon: 1
node (13) lat: 52, lon: 2
node (14) lat: 51, lon: 1
node (15) lat: 51, lon: 2
"""
i = " " * indent
result = i + "way (%s)" % (self.element_id)
for k, v in sorted(self.tags.items()):
result += "\n%s %s => %s" % (i, k, v)
for node in self.nodes:
result += "\n" + node.pretty(indent + 2)
return result
@property
def first(self):
return self.nodes[0]
@property
def last(self):
return self.nodes[-1]
def closed(self):
return self.first == self.last
def join(self, other):
"""Try to join another way to this one.
This will succeed if they can be joined at either end, and
otherwise returns None.
As examples, consider joining two edges of a square in various
ways:
top_left -- top_right
| |
bottom_left -- bottom_right
In the examples below, we try to join the top edge to the
right in four distinct ways:
>>> top_left = Node("12", latitude="52", longitude="1")
>>> top_right = Node("13", latitude="52", longitude="2")
>>> bottom_right = Node("14", latitude="51", longitude="2")
>>> bottom_left = Node("15", latitude="51", longitude="1")
>>> top_cw = Way("3456", nodes=[top_left, top_right])
>>> right_cw = Way("1234", nodes=[top_right, bottom_right])
>>> bottom_cw = Way("6789", nodes=[bottom_right, bottom_left])
>>> joined = top_cw.join(right_cw)
>>> print(joined.pretty(2))
way (None)
node (12) lat: 52, lon: 1
node (13) lat: 52, lon: 2
node (14) lat: 51, lon: 2
>>> top_ccw = Way("4567", nodes=[top_right, top_left])
>>> joined = top_ccw.join(right_cw)
>>> print(joined.pretty(2))
way (None)
node (14) lat: 51, lon: 2
node (13) lat: 52, lon: 2
node (12) lat: 52, lon: 1
>>> right_ccw = Way("2345", nodes=[bottom_right, top_right])
>>> joined = top_ccw.join(right_ccw)
>>> print(joined.pretty(2))
way (None)
node (14) lat: 51, lon: 2
node (13) lat: 52, lon: 2
node (12) lat: 52, lon: 1
>>> joined = top_cw.join(right_ccw)
>>> print(joined.pretty(2))
way (None)
node (12) lat: 52, lon: 1
node (13) lat: 52, lon: 2
node (14) lat: 51, lon: 2
Closed ways cannot be joined, and throw exceptions as in these
examples:
>>> closed = Way("5678", nodes=[top_left,
... top_right,
... bottom_right,
... bottom_left,
... top_left])
>>> joined = closed.join(top_cw)
Traceback (most recent call last):
...
Exception: Trying to join a closed way to another
>>> closed = Way("5678", nodes=[top_left,
... top_right,
... bottom_right,
... bottom_left,
... top_left])
>>> joined = top_cw.join(closed)
Traceback (most recent call last):
...
Exception: Trying to join a way to a closed way
Finally, an exception is also thrown if there are no end
points in common between the two ways:
>>> top_cw.join(bottom_cw)
Traceback (most recent call last):
...
Exception: Trying to join two ways with no end point in common
"""
if self.closed():
raise Exception("Trying to join a closed way to another")
if other.closed():
raise Exception("Trying to join a way to a closed way")
if self.first == other.first:
new_nodes = list(reversed(other.nodes))[0:-1] + self.nodes
elif self.first == other.last:
new_nodes = other.nodes[0:-1] + self.nodes
elif self.last == other.first:
new_nodes = self.nodes[0:-1] + other.nodes
elif self.last == other.last:
new_nodes = self.nodes[0:-1] + list(reversed(other.nodes))
else:
raise Exception("Trying to join two ways with no end point in common")
return Way(None, new_nodes)
def bounding_box_tuple(self):
"""Returns a tuple of floats representing a bounding box of this Way
Each tuple is (min_lat, min_lon, max_lat, max_lon). If the
longitude of any node is less than -90 degrees, 360 is added
to every node, to deal with ways that cross the -180 degree
meridian.
>>> w = Way('76543', nodes=[Node("12", latitude="52", longitude="1"),
... Node("13", latitude="52", longitude="2"),
... Node("14", latitude="51", longitude="1"),
... Node("15", latitude="51", longitude="2")])
>>> w.bounding_box_tuple()
(51.0, 1.0, 52.0, 2.0)
As another example close to the -180 degree meridian, create a
closed way somewhere in Alaska:
>>> w = Way('76543', nodes=[Node("12", latitude="62", longitude="-149"),
... Node("13", latitude="62", longitude="-150"),
... Node("14", latitude="61", longitude="-149"),
... Node("15", latitude="61", longitude="-150")])
>>> w.bounding_box_tuple()
(61.0, 210.0, 62.0, 211.0)
"""
longitudes = [float(n.lon) for n in self]
latitudes = [float(n.lat) for n in self]
if any(x for x in longitudes if x < -90):
longitudes = [x + 360 for x in longitudes]
min_lon = min(longitudes)
max_lon = max(longitudes)
min_lat = min(latitudes)
max_lat = max(latitudes)
return (min_lat, min_lon, max_lat, max_lon)
def __repr__(self):
"""A returns simple repr-style representation of the Way
>>> Way('81')
Way(id="81", nodes=0)
>>> OSMElement.make_missing_element('way', '49')
Way(id="49", missing)
"""
if self.element_content_missing:
return 'Way(id="%s", missing)' % (self.element_id,)
else:
return 'Way(id="%s", nodes=%d)' % (self.element_id, len(self.nodes))
def get_missing_elements(self, to_append_to=None):
"""Return a list of element type, id tuples of missing elements
In the case of an element without children, this should either
return an empty list or a list with this element in it,
depending on whether it's marked as missing or not:
>>> nodes = [OSMElement.make_missing_element('node', '43'),
... Node('44'),
... Node('45'),
... OSMElement.make_missing_element('node', '46')]
>>> w = Way("42", nodes=nodes)
>>> w.get_missing_elements()
[('node', '43'), ('node', '46')]
>>> l = [('relation', '47')]
>>> result = w.get_missing_elements(l)
>>> l is result
True
>>> l
[('relation', '47'), ('node', '43'), ('node', '46')]
"""
to_append_to = OSMElement.get_missing_elements(self, to_append_to)
for node in self:
node.get_missing_elements(to_append_to)
return to_append_to
def to_xml(self, parent_element=None, include_node_dependencies=False):
"""Generate an XML element representing this way
If parent_element is supplied, it is added to that element and
returned. If no parent_element is supplied, an OSM XML root
element is created, and the generated <node> element is added
to that.
>>> w = Way('76543', nodes=[Node("12", latitude="52", longitude="1"),
... Node("13", latitude="52", longitude="2"),
... Node("14", latitude="51", longitude="1"),
... Node("15", latitude="51", longitude="2")])
>>> w.tags.update({'boundary': 'administrative',
... 'admin_level': '2'})
>>> xe = etree.Element('example')
>>> result = w.to_xml(xe)
>>> result is xe
True
>>> print(etree.tostring(xe, pretty_print=True), end='')
<example>
<way id="76543">
<nd ref="12"/>
<nd ref="13"/>
<nd ref="14"/>
<nd ref="15"/>
<tag k="admin_level" v="2"/>
<tag k="boundary" v="administrative"/>
</way>
</example>
Sometimes we'd like to output the nodes that are in a way at the same time:
>>> xe = etree.Element('example-with-nodes')
>>> w.to_xml(xe, include_node_dependencies=True) #doctest: +ELLIPSIS
<Element example-with-nodes at ...>
>>> print(etree.tostring(xe, pretty_print=True), end='')
<example-with-nodes>
<node id="12" lat="52" lon="1"/>
<node id="13" lat="52" lon="2"/>
<node id="14" lat="51" lon="1"/>
<node id="15" lat="51" lon="2"/>
<way id="76543">
<nd ref="12"/>
<nd ref="13"/>
<nd ref="14"/>
<nd ref="15"/>
<tag k="admin_level" v="2"/>
<tag k="boundary" v="administrative"/>
</way>
</example-with-nodes>
And the final option is to include the OSM XML boilerplate as well:
>>> result = w.to_xml()
>>> print(etree.tostring(result, pretty_print=True), end='') # doctest: +NORMALIZE_WHITESPACE
<osm generator="mySociety Boundary Extractor" version="0.6">
<note>The data included in this document is from www.openstreetmap.org.
It has there been collected by a large group of contributors.
For individual attribution of each item please refer to
http://www.openstreetmap.org/api/0.6/[node|way|relation]/#id/history</note>
<way id="76543">
<nd ref="12"/>
<nd ref="13"/>
<nd ref="14"/>
<nd ref="15"/>
<tag k="admin_level" v="2"/>
<tag k="boundary" v="administrative"/>
</way>
</osm>
"""
if parent_element is None:
parent_element = OSMElement.xml_wrapping()
if include_node_dependencies:
for node in self:
node.to_xml(parent_element, include_node_dependencies)
way = etree.SubElement(parent_element,
'way',
attrib={'id': self.element_id})
for node in self:
etree.SubElement(way, 'nd', attrib={'ref': node.element_id})
self.xml_add_tags(way)
return parent_element
def reconstruct_missing(self, parser, id_to_node):
"""Replace any missing nodes from the parser's cache or id_to_node
id_to_node should be a dictionary that maps IDs of nodes (as
strings) the complete Node object or None. parser should have
a method called get_known_or_fetch('node', element_id) which
will return None or the complete Node object, if the parser
can find it.
If any nodes could not be found from parser or id_to_node,
they are returned as a list. Therefore, if the way could be
completely reconstructed, [] will be returned.
>>> w = Way('76543', nodes=[Node("12", latitude="52", longitude="1"),
... OSMElement.make_missing_element('node', '13'),
... OSMElement.make_missing_element('node', '14'),
... Node("15", latitude="51", longitude="2")])
>>> class FakeParser:
... def get_known_or_fetch(self, element_type, element_id):
... if element_type != 'node':
... return None
... if element_id == "14":
... return Node("14", latitude="52.4", longitude="2.1")
... return None
>>> node_cache = {"13": Node("13", latitude="51.2", longitude="1.3"),
... "22": None}
>>> w.reconstruct_missing(FakeParser(), node_cache)
[]
>>> w = Way('76543', nodes=[Node("21", latitude="52", longitude="1"),
... OSMElement.make_missing_element('node', '22'),
... OSMElement.make_missing_element('node', '23'),
... Node("24", latitude="51", longitude="2")])
>>> w.reconstruct_missing(FakeParser(), node_cache)
[Node(id="22", missing), Node(id="23", missing)]
"""
still_missing = []
for i, node in enumerate(self.nodes):
if not node.element_content_missing:
continue
node_id = node.element_id
found_node = None
if node_id in id_to_node:
found_node = id_to_node[node_id]
else:
# Ask the parser to try to fetch it from its filesystem cache:
found_node = parser.get_known_or_fetch('node', node_id)
if (found_node is not None) and (not found_node.element_content_missing):
self.nodes[i] = found_node
else:
still_missing.append(node)
return still_missing
class Relation(OSMElement):
"""Represents an OSM relation as returned via the Overpass API"""
def __init__(self, relation_id, element_content_missing=False):
super(Relation, self).__init__(relation_id, element_content_missing, 'relation')
# A relation has an ordered list of children, which we store
# as a list of tuples. The first element of each tuple is a
# Node, Way or Relation, and the second is a "role" string.
self.children = []
self.tags = {}
def __iter__(self):
for c in self.children:
yield c
def __len__(self):
return len(self.children)
def __getitem__(self, val):
return self.children.__getitem__(val)
def add_member(self, new_member, role=''):
self.children.append((new_member, role))
def pretty(self, indent=0):
"""Generate a fuller string representation of this way
For example:
>>> r = Relation('98765')
>>> r.add_member(Node('76542', latitude="51.0", longitude="0.3"))
>>> r.add_member(Way('76543'))
>>> r.add_member(Way('76544'), role='inner')
>>> r.add_member(Way('76545'), role='inner')
>>> r.add_member(Way('76546'))