.
675 |
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
1 | python-osm
2 | original version by Rory McCann (http://blog.technomancy.org/)
3 | modified by Christoph Lupprich (http://www.stopbeingcarbon.com)
4 | modified and extended by Werner Hoch (http://www.h-renrew.de)
5 |
6 | == DESCRIPTION
7 |
8 | python-osm contains tools to read Open Street Map Data (*.osm).
9 | It is splitted into several python classes:
10 |
11 | src/pyosm.py:
12 | base class that contains the datamodel of osm. It parses the osm
13 | file or data and puts every osm-object into pythonobjects.
14 |
15 | src/multipolygon.py:
16 | analyzes a multipolygon relation and provides a node-in-polygon check.
17 | This class can export a polygon files for osmosis, too.
18 |
19 | src/osmdb.py:
20 | offers an api to read osm objects from large or large compressed osm files
21 | like the planet.
22 |
23 | tools/relation2gpx.py:
24 | Exports one or more relations into a gpx file. This tool can be used to
25 | create gpx tracks for your gps-unit or to create maps with routes.
26 |
27 | tools/osmhistory.py:
28 | With this tool you can get an old versions of osm-objects at a given
29 | timestamp. (experimental, use with care)
30 |
31 | see also: doc/index.html for more documentation.
32 |
--------------------------------------------------------------------------------
/TODO.txt:
--------------------------------------------------------------------------------
1 | * osmhistory: version id is wrong: setter method for pyosm
2 | * pbf-support
3 | * pbf object generator
4 | * osmdb: pbf-support
5 | * object generators for osmdb and bz2osmdb
6 |
7 | * relation2gpx: recursive relation support
--------------------------------------------------------------------------------
/doc/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | python-osm documentation
5 |
6 |
7 |
8 | python-osm documentation
9 | python-osm is a set of classes an tools for openstreetmap data and files.
10 |
11 | src/osm/pyosm
12 | This is the base class that contains the data model of python-osm.
13 | It also contains a xml parser to read osm files.
14 |
15 | When called on commandline with an osm file as argument, the class prints a statistic of the file.
16 |
17 |
18 | werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./pyosm.py Rottweil.osm
19 | filename: Rottweil.osm
20 | Nodes: 3020
21 | Ways: 6
22 | Relations: 1
23 | |
24 |
25 |
26 | src/osm/multipolygon.py
27 | This class can be used to work with multipolygon relations.
28 | Beside the commandline options you can perform node in multipolygon checks.
29 |
30 | multipolygon commandline
31 | When called on command line interface you can either check multipolygons for
32 | way gaps or create polygon files for osmosis.
33 |
34 |
35 | usage: multipolygon.py --relation=ID [options]
36 | load a multipolygon from the OSM-API or from an OSM file
37 | export osmosis boundary polygon or check the multipolygon for errors
38 | -h, --help: print this usage message
39 | -i, --infile: osmfile to load
40 | -r, --relation: multipolygon relation id
41 | -m, --osmosispolygon: outfile for osmosis boundary polygon
42 | -j, --josmfile: outfile for josm boundary
43 | |
44 |
45 |
46 | multipolygon commandline examples
47 | Load a multipolygon with the OSM api and check it.
48 |
49 |
50 | werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./multipolygon.py -r 1164629
51 | Multipolygon of Relation 1164629
52 | Outer Polygons (1):
53 | 1: 682 Nodes
54 | Inner Polygons (6):
55 | 1: 40 Nodes
56 | 2: 21 Nodes
57 | 3: 21 Nodes
58 | 4: 39 Nodes
59 | 5: 7 Nodes
60 | 6: 11 Nodes
61 | Open Outer Ways (0):
62 | Open Inner Ways (0):
63 | |
64 |
65 |
66 |
67 | To export relation with id=62578 as polygon file for osmosis:
68 |
69 |
70 | werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./multipolygon.py -r 62578 -m boundary.poly
71 | |
72 |
73 |
74 |
75 | To create an empty josmfile with the tiled bounds of the multipolygon with id=289122 as polygon:
76 |
77 |
78 | werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./multipolygon.py -r 289122 -j josmfile.xml
79 | |
80 |
81 |
82 | src/osm/osmdb.py
83 | see osmdb for a detailed description.
84 |
85 | tools/osmhistory.py
86 | see osmhistory for a detailed description.
87 |
88 | tools/relation2gpx.py
89 | A tool to download relations from the OSM API and create gpx files.
90 | Each relation becomes a track (trk) and each way a track segment
91 | trkseg.
92 | The segments are not ordered.
93 |
94 | relation2gpx.py commandline
95 |
96 |
97 | usage: relation2gpx.py [-o GPXFILE] -r relation1,relation2,...
98 | load relations from the OSM API and create gpx files
99 | -h, --help: print this help message
100 | -o, --outfile: specify the filename of the gpx file
101 | -r, --relations: comma seperated list of relations
102 | |
103 |
104 |
105 | relation2gpx.py examples
106 | Get relation 157289 (HW4 hiking route) and write it to default filename out.gpx
107 |
108 |
109 | werner@linux-g0e5:~/osm/src/python-osm/tools> ./relation2gpx.py -r 157289
110 | |
111 |
112 |
113 |
114 | Werner Hoch
115 |
116 |
117 | Last modified: Sat Oct 13 11:23:24 CEST 2012
118 |
119 |
120 |
121 |
--------------------------------------------------------------------------------
/doc/osmdb.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | osmdb: API for large OSM files
5 |
6 |
7 |
8 | osmdb: API for large OSM files
9 | osmdb.py provides an possibility to extract osm objects from large openstreetmap files.
10 | The osmdb modul can be used as CLI program as http server or as python module.
11 |
12 |
command line options
13 |
14 |
15 | osmdb.py Version 0.0.2
16 | -h, --help: print this help information
17 | --relations=outfile: split relations from input file
18 | --ways_relations=outfile: split ways and relations from input file
19 | --server=port: start a http-server with the given port
20 | Examples:
21 | osmdb.py --relations=out.osm.bz2 germany.osm.bz2
22 | osmdb.py --ways_relations=/dev/stdout planet-latest.osm
23 | osmdb.py --server=8888 germany.osm
24 | |
25 |
26 | The commandlines can be used to strip of the relations or the ways and realtions from a large
27 | osm or osm.bz2 file.
28 | This is usefull if you only need the relations of an osm file.
29 |
30 | http server api
31 | After starting an http server with the following commandline ...
32 |
33 |
34 | werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./osmdb.py --server=8888 germany.osm
35 | |
36 |
37 | ... you can access the osm file with http requests.
38 |
39 | Here's a list of all possible commands:
40 |
41 |
42 | nodes?nodes=id1,id2,...
43 | ways?ways=id1,id2,...
44 | relations?relations=id1,id2,...
45 | ways?ways=id1,id2,...&mode=full
46 | relations?relations=id1,id2,...&mode=full
47 | relations?relations=id1,id2,...&mode=recursive
48 | |
49 |
50 |
51 |
52 | To create http requests you can use the command line tool wget or any
53 | programming language you like.
54 | Here are some examples with wget:
55 |
56 |
57 |
58 | wget -Oosmdb_nodes.xml http://localhost:8888/nodes?nodes=437498388,437498385,180721525
59 |
60 | wget -Oosmdb_ways.xml http://localhost:8888/ways?ways=37426524,37426525,32466511
61 | wget -Oosmdb_ways_full.xml http://localhost:8888/ways?ways=37426524,37426525,32466511\&mode=full
62 |
63 | wget -Oosmdb_relation.xml http://localhost:8888/relations?relations=167920,131414
64 | wget -Oosmdb_relation_full.xml http://localhost:8888/relations?relations=1111111\&mode=full
65 | wget -Oosmdb_relation_recursive.xml http://localhost:8888/relations?relations=1111111\&mode=recursive
66 | |
67 |
68 |
69 | BTW: The relation 11111111 is the german boundary and it can be extracted from an uncompressed
70 | planet file in about 60 seconds. The resulting osm xml file contains 12 relations, 1172 ways and 54749 nodes.
71 |
72 |
73 | Werner Hoch
74 |
75 |
76 | Last modified: Sat Jan 7 19:56:41 CET 2012
77 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/doc/osmhistory.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | python-osm: osmhistory
5 |
6 |
7 |
8 | python-osm: osmhistory
9 |
10 | osmhistory.py is a tool that can retrieve object data from
11 | the OpenStreetMap API at a given timestamp.
12 |
13 | The current OSM API supports the download of the current version
14 | of an object (e.g. a relation) with a single API call or over the
15 | JOSM remote control.
16 |
17 |
18 |
19 |
20 | http://www.openstreetmap.org/api/0.6/relation/21628/full
21 | |
22 |
23 |
24 |
25 | OSM-history can do the same but at any given timestamp. Thus you
26 | can get OSM-objects from a month ago, one year ago, or just the
27 | day before something bad happened with the osm objects.
28 |
29 |
30 |
31 |
32 | ./osmhistory.py -r 21628 -t 2009-10-01 -o relation_21628_2009-10-01.osm
33 | |
34 |
35 |
36 |
37 | The command retrieves the relation 21628 at the
38 | timestamp 2009-10-01 and writes the output to the file
39 | relation_21628_2009-10-01.osm.
40 |
41 | In order to do that the script first searches (with a binary
42 | search) the matching version of the given OSM object. Then it
43 | collects all objects that are referenced by this object. e.g. a
44 | relation references other relations, ways and/or nodes. A way
45 | references nodes.
46 |
47 | All that objects are downloaded by the script, too. An example
48 | output of the script with the executed API calls looks like this:
49 |
50 |
51 |
52 |
53 | bisect:relation21628
54 | bisect:/api/0.6/relations?relations=21628
55 | bisect:/api/0.6/relation/21628/4
56 | bisect:/api/0.6/relation/21628/6
57 | bisect:/api/0.6/relation/21628/5
58 | bisect:way8022736
59 | bisect:/api/0.6/ways?ways=8022736
60 | bisect:/api/0.6/way/8022736/4
61 | bisect:/api/0.6/way/8022736/6
62 | bisect:/api/0.6/way/8022736/7
63 | bisect:way19736185
64 | bisect:/api/0.6/ways?ways=19736185
65 | [....]
66 | bisect:node59975181
67 | bisect:/api/0.6/nodes?nodes=59975181
68 | bisect:node362803235
69 | bisect:/api/0.6/nodes?nodes=362803235
70 | bisect:/api/0.6/node/362803235/4
71 | bisect:/api/0.6/node/362803235/2
72 | bisect:/api/0.6/node/362803235/3
73 | bisect:node500348455
74 | bisect:/api/0.6/nodes?nodes=500348455
75 | [...]
76 | |
77 |
78 |
79 |
80 | After retrieving the history, you can compare the current version
81 | of the object and the historic version. You can load the two
82 | versions into different layers with JOSM.
83 |
84 |
85 |
86 | new version in front of the old version |
87 | old version in front of the current version, zoomed in |
88 |
89 |
90 | |
91 | |
92 |
93 |
94 |
95 |
96 | As you can see on the left picture, the route of the relation has
97 | been changed. On the right picture, you can see the moved
98 | roundabout.
99 |
100 |
Revert the changes (experimental, not much tested)
101 |
102 | The historic version of the osm objects are prepared to revert the current osm object versions.
103 | To achieve this:
104 |
105 | - I've set the object version attribute to the version of the current object.
106 | - I've added an extra tag osmhistory:old_version_date at each modified object.
107 | The value of the tag contains the historic version and the date of that version.
108 |
109 |
110 | If you delete that tag, the you get exactly the historic
111 | object. JOSM will add an action=modify attribute and the version
112 | attribute gets incremented. The reverted object will be uploaded
113 | with the next commit.
114 |
115 | Example of the historic osm file:
116 |
117 |
118 |
119 | <node uid="110263" timestamp="2009-09-18T15:12:19Z" lon="9.5154672" visible="true" version="4" user="werner2101" lat="47.6790064" id="362803252">
120 | <tag k="osmhistory:old_version_date" v="2_2009-10-01"></tag>
121 | </node>
122 | <way uid="110263" timestamp="2009-09-18T15:12:22Z" visible="true" version="17" user="werner2101" id="4675294">
123 | <nd ref="29691653"></nd>
124 | <nd ref="362606768"></nd>
125 | [...]
126 | <tag k="maxspeed" v="50"></tag>
127 | <tag k="ref" v="K 7726"></tag>
128 | <tag k="highway" v="tertiary"></tag>
129 | <tag k="osmhistory:old_version_date" v="16_2009-10-01"></tag>
130 | </way>
131 | <relation uid="110263" timestamp="2009-09-18T15:12:23Z" visible="true" version="7" user="werner2101" id="21628">
132 | <member ref="4675294" role="" type="way"></member>
133 | <member ref="8022729" role="" type="way"></member>
134 | <member ref="8022735" role="" type="way"></member>
135 | [...]
136 | <tag k="operator" v="Bodenseekreis"></tag>
137 | <tag k="type" v="route"></tag>
138 | <tag k="route" v="road"></tag>
139 | <tag k="ref" v="K 7726"></tag>
140 | <tag k="osmhistory:old_version_date" v="5_2009-10-01"></tag>
141 | </relation>
142 | |
143 |
144 |
145 |
146 |
Integration into OSM API
147 |
148 | The current python implementation of that tool needs lots of api calls. Even if I could download
149 | more than one object of the current objects, the download and the binary search of older objects
150 | still produces lots of api calls. I'm not sure how long it would take to download large relations
151 | like the boundary of a country.
152 |
153 | If other osm users think that the tool is usefull, it's functionality should be included into
154 | the OSM api (which is written using Ruby on Rails).
155 |
156 |
157 | Werner Hoch
158 |
159 |
160 | Last modified: Tue Dec 29 12:27:50 CET 2009
161 |
162 |
163 |
164 |
--------------------------------------------------------------------------------
/doc/pictures/osmhistory_josm1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/werner2101/python-osm/f508807662f682bea574c57deac5ed202e92b357/doc/pictures/osmhistory_josm1.png
--------------------------------------------------------------------------------
/doc/pictures/osmhistory_josm2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/werner2101/python-osm/f508807662f682bea574c57deac5ed202e92b357/doc/pictures/osmhistory_josm2.png
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.core import setup
2 |
3 | setup(
4 | name = 'python-osm',
5 | version = '0.0.3',
6 | url = 'https://github.com/werner2101/python-osm',
7 | author = 'Werner Hoch',
8 | author_email = 'werner.ho@gmx.de',
9 | description = 'Provides model objects for OSM promitives and related tools',
10 | scripts = [
11 | 'tools/osmhistory.py',
12 | 'tools/relation2gpx.py'
13 | ],
14 | py_modules = ['osm.pyosm',
15 | 'osm.multipolygon',
16 | 'osm.osmdb',
17 | 'osm.utils'
18 | ],
19 | package_dir = {'osm': 'src/osm'},
20 | )
21 |
--------------------------------------------------------------------------------
/src/osm/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/werner2101/python-osm/f508807662f682bea574c57deac5ed202e92b357/src/osm/__init__.py
--------------------------------------------------------------------------------
/src/osm/multipolygon.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import sys
4 | import pyosm
5 | from utils import deg2num, num2deg
6 | import numpy
7 |
8 | try:
9 | #nxutils is only used in older matplotlib version (<1.2.x)
10 | import matplotlib.nxutils
11 | HAS_NXUTILS = True
12 | except:
13 | HAS_NXUTILS = False
14 | import matplotlib.path
15 |
16 |
17 | class multipolygon(object):
18 |
19 | def __init__(self, relation):
20 | self.relation = relation
21 | self.read_relation(self.relation)
22 |
23 | def read_relation(self, relation):
24 | """
25 | read the relation and prepare the multipolygon object.
26 | """
27 | members = self.recursive_members(relation)
28 |
29 | inner_ways = []
30 | outer_ways = []
31 | for obj,role in members:
32 | if type(obj) == pyosm.Way:
33 | if role in ['outer', '']:
34 | outer_ways.append(obj)
35 | elif role in ['inner']:
36 | inner_ways.append(obj)
37 | else:
38 | sys.stderr.write('Unknown role "%s" of way %i\n' % (role, obj.id))
39 | elif type(obj) == pyosm.Node:
40 | sys.stderr.write('Node obj in role "%s" of node %i\n' % (role, obj.id))
41 |
42 | self.inner_polygons, self.inner_ways = self.create_polygons(inner_ways)
43 | self.outer_polygons, self.outer_ways = self.create_polygons(outer_ways)
44 |
45 |
46 | def create_polygons(self, ways):
47 | """
48 | sort the osm ways to inner and outer polygon way list.
49 | Connect all osm ways that belongs together into single polygon ways.
50 | """
51 | ways = ways + [] ## list copy
52 | polygons = []
53 | open_ways = []
54 |
55 | endnodes = {}
56 | for w in ways:
57 | start = w.nodes[0]
58 | stop = w.nodes[-1]
59 | if start.id == stop.id:
60 | ## a closed way is a polygon
61 | polygons.append(w.nodes)
62 | continue
63 | if start.id in endnodes:
64 | endnodes[start.id].append(w)
65 | else:
66 | endnodes[start.id] = [w]
67 | if stop.id in endnodes:
68 | endnodes[stop.id].append(w)
69 | else:
70 | endnodes[stop.id] = [w]
71 |
72 | poly_nodes = []
73 |
74 | while endnodes:
75 | way = iter(endnodes.values()).__next__()[0]
76 | startway = way
77 | endway = way
78 | poly_nodes.extend(way.nodes)
79 | while True:
80 | startnode = poly_nodes[0]
81 | stopnode = poly_nodes[-1]
82 | if startnode == stopnode:
83 | endnodes.pop(startnode.id)
84 | polygons.append(poly_nodes)
85 | poly_nodes = []
86 | break
87 |
88 | if startway:
89 | ways = endnodes.pop(startnode.id)
90 | if len(ways) == 1:
91 | sys.stderr.write('open node %s of way %s\n' % (startnode.id, ways[0].id))
92 | startway = None
93 | continue
94 | elif len(ways) == 2:
95 | if ways[0] == startway:
96 | appendway = ways[1]
97 | else:
98 | appendway = ways[0]
99 | if appendway.nodes[-1] == startnode:
100 | poly_nodes = appendway.nodes + poly_nodes
101 | else:
102 | poly_nodes = appendway.nodes[::-1] + poly_nodes
103 | startway = appendway
104 | continue
105 | else:
106 | sys.stderr.write('node with more than 2 ways %s\n' % (startnode.id))
107 |
108 | if endway:
109 | ways = endnodes.pop(stopnode.id)
110 | if len(ways) == 1:
111 | sys.stderr.write('open node %s of way %s\n' % (stopnode.id, ways[0].id))
112 | endway = None
113 | continue
114 | elif len(ways) == 2:
115 | if ways[0] == endway:
116 | appendway = ways[1]
117 | else:
118 | appendway = ways[0]
119 | if appendway.nodes[0] == stopnode:
120 | poly_nodes = poly_nodes + appendway.nodes
121 | else:
122 | poly_nodes = poly_nodes + appendway.nodes[::-1]
123 | endway = appendway
124 | continue
125 | else:
126 | sys.stderr.write('node with more than 2 ways %s\n' % (stopnode.id))
127 |
128 | ## no way found to append
129 | open_ways.append(poly_nodes)
130 | poly_nodes = []
131 | break
132 |
133 | return polygons, open_ways
134 |
135 |
136 | def recursive_members(self, relation):
137 | """
138 | collect recursively all way/node members of a hierarchical multipolygon relation.
139 | returns a list of (obj,role) tuples of all member elements.
140 | """
141 | todo_stack = [relation]
142 | members = []
143 | recursive_relations = set()
144 |
145 | while todo_stack:
146 | current_relation = todo_stack.pop(0)
147 |
148 | if current_relation in recursive_relations:
149 | raise Exception('recursion loops in relation %i' % self.relation.id)
150 | recursive_relations.add(current_relation)
151 |
152 | for m in current_relation.members:
153 | obj, role = m
154 | if type(obj) == pyosm.Relation and role in ['inner','outer','']:
155 | todo_stack.append(obj)
156 | elif role in ['inner','outer','']:
157 | members.append(m)
158 | else: # drop all bad members like subarea, admin_centre
159 | pass
160 |
161 | return members
162 |
163 | def inside(self, nodes=[], points=[]):
164 | """
165 | check if the nodes from the nodes list are inside the multipolygon
166 | """
167 | if nodes:
168 | points = self.pointlist(nodes)
169 | matches = numpy.zeros(len(points))
170 | for outerpoly in self.outer_polygons:
171 | outerpoints = self.pointlist(outerpoly)
172 | if HAS_NXUTILS:
173 | matches = matches + matplotlib.nxutils.points_inside_poly(points, outerpoints)
174 | else:
175 | matches = matches + matplotlib.path.Path(outerpoints).contains_points(points)
176 | for innerpoly in self.inner_polygons:
177 | innerpoints = self.pointlist(innerpoly)
178 | if HAS_NXUTILS:
179 | matches = matches - matplotlib.nxutils.points_inside_poly(points, innerpoints)
180 | else:
181 | matches = matches - matplotlib.path.Path(innerpoints).contains_points(points)
182 | return matches
183 |
184 | def pointlist(self, nodes):
185 | """
186 | returns a list of (lon/lat) points of a given node list
187 | """
188 | points = []
189 | for node in nodes:
190 | points.append((float(node.lon), float(node.lat)))
191 | return points
192 |
193 | def write_osmosis_file(self, filename):
194 | """
195 | create a boundary polygon for osmosis
196 | """
197 | fid = open(filename, 'wt')
198 | n = 1
199 | fid.write('xxx\n')
200 | for op in self.outer_polygons:
201 | fid.write('%i\n' %(n))
202 | for node in op:
203 | fid.write('\t%s\t%s\n' %(node.lon, node.lat))
204 | fid.write('END\n')
205 | n += 1
206 |
207 | for ip in self.inner_polygons:
208 | fid.write('xxx\n')
209 | fid.write('!%i\n' %(n))
210 | for node in ip:
211 | fid.write('\t%f\t%f\n' %(node.lat, node.lon))
212 | fid.write('END\n')
213 | n += 1
214 | fid.write('END\n')
215 | fid.close()
216 |
217 | def write_josm_file(self, filename, tilezoom=14):
218 | """
219 | create a osm file for the editor JOSM, that only contains the download boundary
220 | information.
221 | Load the file in JOSM and update the data.
222 | Note: Please do not missuse this function to download large areas with josm
223 | """
224 | from shapely.geometry import LineString, Polygon
225 |
226 | f_out = open(filename,'w')
227 | f_out.write("\n")
228 | f_out.write("\n")
229 |
230 | for i, op in enumerate(self.outer_polygons):
231 | # create coordinate list and then a polygon
232 | plist = [(node.lat, node.lon) for node in op]
233 | outer_polygon = Polygon(LineString(plist))
234 |
235 | if not outer_polygon.is_valid:
236 | raise ValueError('outer polygon no %i is not valid' % (i+1))
237 |
238 | (minlat, minlon, maxlat, maxlon) = outer_polygon.bounds
239 | (x1, y2) = deg2num(minlat, minlon, tilezoom)
240 | (x2, y1) = deg2num(maxlat, maxlon, tilezoom)
241 |
242 | for ty in range(y1, y2 + 1):
243 | for tx in range(x1, x2 + 1):
244 | tile_rectangle = [num2deg(tx, ty, tilezoom),
245 | num2deg(tx+1, ty, tilezoom),
246 | num2deg(tx+1, ty+1, tilezoom),
247 | num2deg(tx, ty+1, tilezoom),
248 | num2deg(tx, ty, tilezoom)]
249 | tile_polygon = Polygon(tile_rectangle)
250 |
251 | if outer_polygon.contains(tile_polygon) or outer_polygon.intersects(tile_polygon):
252 | minlat = tile_rectangle[3][0]
253 | minlon = tile_rectangle[3][1]
254 | maxlat = tile_rectangle[1][0]
255 | maxlon = tile_rectangle[1][1]
256 |
257 | f_out.write(' \n' \
258 | % (minlat-0.0000001, minlon-0.0000001, maxlat+0.0000001, maxlon+0.0000001))
259 |
260 | f_out.write("\n")
261 | f_out.close
262 |
263 | def status(self):
264 | """
265 | print the status of the multipolygon file.
266 | * number and list of outer/inner polygons
267 | * number and list of unclosed outer and inner polygons
268 | """
269 |
270 | print ('Multipolygon of Relation %s' % (self.relation.id))
271 | name = self.relation.tags.get('name', '')
272 | if name:
273 | print (' Name-Tag: ', name)
274 | print (' Outer Polygons (%i):' % len(self.outer_polygons))
275 | for i, op in enumerate (self.outer_polygons):
276 | print (' %d: %d Nodes' %(i+1, len(op)))
277 |
278 | print (' Inner Polygons (%i):' % len(self.inner_polygons))
279 | for i, ip in enumerate (self.inner_polygons):
280 | print (' %d: %d Nodes' %(i+1, len(ip)))
281 |
282 | print (' Open Outer Ways (%i):' % len(self.outer_ways))
283 | for i, ow in enumerate (self.outer_ways):
284 | print (' %d: %d Nodes, id(Node[0])=%s, id(Node[-1])=%s' %(i+1, len(ow), ow[0].id, ow[-1].id))
285 |
286 | print (' Open Inner Ways (%i):' % len(self.inner_ways))
287 | for i, iw in enumerate (self.inner_ways):
288 | print (' %d: %d Nodes, id(Node[0])=%s, id(Node[-1])=%s' %(i+1, len(iw), iw[0].id, iw[-1].id))
289 |
290 |
291 | def usage():
292 | print ("usage: multipolygon.py --relation=ID [options]")
293 | print ("load a multipolygon from the OSM-API or from an OSM file")
294 | print ("export osmosis boundary polygon or check the multipolygon for errors")
295 | print ("-h, --help: print this usage message")
296 | print ("-i, --infile: osmfile to load")
297 | print ("-r, --relation: multipolygon relation id")
298 | print ("-m, --osmosispolygon: outfile for osmosis boundary polygon")
299 | print ("-j, --josmfile: outfile for josm boundary")
300 |
301 |
302 | #################### MAIN
303 | if __name__ == '__main__':
304 | import sys
305 | import getopt
306 | import urllib
307 |
308 | try:
309 | opts, args = getopt.getopt(sys.argv[1:], 'r:i:m:j:h',
310 | ['help', 'relation=', 'infile=', 'osmosispolygon=', 'josmfile='])
311 | except getopt.GetoptError:
312 | usage()
313 | sys.exit()
314 |
315 | mode = None
316 | infile = None
317 | osmosisfile = None
318 | josmfile = None
319 | relation = None
320 |
321 | for o, a in opts:
322 | if o in ['-i', '--infile']:
323 | infile = a
324 | elif o in ['-r', '--relation']:
325 | relation = a
326 | elif o in ['-m', '--osmosispolygon']:
327 | osmosisfile = a
328 | elif o in ['-j', '--josmfile']:
329 | josmfile = a
330 | elif o in ['-h', '--help']:
331 | usage()
332 | sys.exit()
333 |
334 | API='http://www.openstreetmap.org/api/0.6'
335 |
336 | if infile:
337 | osmobj = pyosm.OSMXMLFile(infile)
338 | elif relation:
339 | osmfile = urllib.urlopen('%s/relation/%s/full' %(API,relation))
340 | osmobj = pyosm.OSMXMLFile(osmfile)
341 | else:
342 | usage()
343 | sys.exit()
344 |
345 | mp = multipolygon(osmobj.relations[int(relation)])
346 |
347 | if osmosisfile:
348 | mp.write_osmosis_file(osmosisfile)
349 |
350 | elif josmfile:
351 | mp.write_josm_file(josmfile)
352 |
353 | else:
354 | mp.status()
355 |
356 |
357 |
--------------------------------------------------------------------------------
/src/osm/osmdb.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import sys, os
4 | import math, re
5 | import bz2
6 | import logging
7 | if sys.version_info < (3,0):
8 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
9 | else:
10 | from http.server import BaseHTTPRequestHandler, HTTPServer
11 | from xml.sax import handler, make_parser, parseString
12 |
13 | log = logging.getLogger(__name__)
14 | #################### CONSTANTS
15 | VERSION = "0.0.3"
16 |
17 | OSMHEAD = """""" \
18 | """"""
19 | OSMTAIL = """"""
20 |
21 | LOGGING = False
22 |
23 | #################### CLASSES
24 | class SubobjectHandler(handler.ContentHandler):
25 | """
26 | simple XML Handler for osm files that extracts nodes (nd) from ways
27 | and members from relations
28 | """
29 | def __init__(self):
30 | self.relations = set([])
31 | self.nodes = set([])
32 | self.ways = set([])
33 |
34 | def startElement(self, obj, attrs):
35 | if obj == 'nd':
36 | self.nodes.add(int(attrs['ref']))
37 | return
38 | elif obj == 'member':
39 | if attrs['type'] == 'relation':
40 | self.relations.add(int(attrs['ref']))
41 | elif attrs['type'] == 'way':
42 | self.ways.add(int(attrs['ref']))
43 | elif attrs['type'] == 'node':
44 | self.nodes.add(int(attrs['ref']))
45 |
46 | def endElement(self, obj):
47 | pass
48 |
49 |
50 | class Bisect(object):
51 | """
52 | Helper class for binary search processes.
53 | """
54 | def __init__(self, minindex, maxindex):
55 | self.min = minindex
56 | self.max = maxindex
57 | self.reset()
58 |
59 | def reset(self):
60 | """
61 | Setup the Bisect class or reset it to the starting stage.
62 | """
63 | self.increment = 2**int(math.log(self.max - self.min + 1, 2))
64 | self.cursor = self.min + self.increment - 1
65 | self.increment //= 2
66 | return self.cursor
67 |
68 | def up(self):
69 | """
70 | Move the cursor upwards in binary steps.
71 | """
72 | if not self.increment:
73 | return None
74 | self.cursor += self.increment
75 | self.increment //= 2
76 | while self.cursor > self.max:
77 | self.down()
78 | return self.cursor
79 |
80 | def down(self):
81 | """
82 | Move the cursor downwards in binary steps.
83 | """
84 | if not self.increment:
85 | return None
86 | self.cursor -= self.increment
87 | self.increment //= 2
88 | return self.cursor
89 |
90 | def __str__(self):
91 | return "Bisect: min=%i, max=%i, cursor=%i, increment=%i" \
92 | % (self.min, self.max, self.cursor, self.increment)
93 |
94 |
95 | class IndexBlock(object):
96 | """
97 | Artificial index object to store information about the content
98 | of an file index.
99 | """
100 | def __init__(self, fileindex):
101 | self.fileindex = fileindex
102 | self.first_type = None
103 | self.first_id = None
104 | self.valid = False
105 |
106 | def __str__(self):
107 | return "IndexBlock: fileindex=%s, first_type=%s, first_id=%s, valid=%s" \
108 | % (self.fileindex, self.first_type, self.first_id, self.valid)
109 |
110 | class OsmDb(object):
111 | """
112 | OsmDb offers random access to large osm files that cannot be loaded
113 | into memomry with the pyosm class.
114 | Basically it creates a file index on the fly and binary search system
115 | to find objects in large files really fast.
116 | """
117 | def __init__(self, filename):
118 | self.filename = filename
119 | self._index = []
120 |
121 | self._filesize = os.path.getsize(self.filename)
122 | self._filehandler = open(self.filename, 'rb')
123 | self._create_index()
124 | self._order = {'changeset': -1, 'node': 0, 'way': 1, 'relation': 2}
125 |
126 | def _create_index(self):
127 | """
128 | Allocate index blocks without validating them.
129 | """
130 | CNT = 100000
131 | self._index = [ IndexBlock( i * CNT ) for i in range(self._filesize // CNT - 1 ) ]
132 |
133 | def _validate(self, blk):
134 | """
135 | Find the first object element in the block and update the block index.
136 | Returns False if the block has no object item.
137 | """
138 | if blk.valid:
139 | return True
140 |
141 | self._filehandler.seek(blk.fileindex)
142 | while True:
143 | line = self._filehandler.readline()
144 | if line == False: ## EOF or Error
145 | return False
146 | else:
147 | for obj in ['node', 'way', 'relation','changeset']:
148 | if re.match('[ \t]*<%s id="[0-9]*" ' % obj, line):
149 | blk.first_type = obj
150 | blk.first_id = int(line.split('"')[1])
151 | blk.valid = True
152 | return True
153 |
154 | def _get_block(self, objtype, objid):
155 | """
156 | Search the index-block, that contains the given objtype and objid.
157 | This performs a binary search through the file.
158 | """
159 | bisect = Bisect(0, len(self._index)-1)
160 | blocknr = bisect.reset()
161 | while True:
162 | blk = self._index[blocknr]
163 | if not self._validate(blk):
164 | self._index.pop(blocknr)
165 | log.debug("bad block: %s" % blocknr)
166 | bisect = Bisect(0, len(self._index)-1)
167 | blocknr = bisect.reset()
168 | continue
169 |
170 | log.debug("bisect Nr=%s, seeking %s=%s" %(blocknr, objtype, objid), str(blk))
171 |
172 | res = cmp((self._order[objtype], objid),
173 | (self._order[blk.first_type], blk.first_id))
174 |
175 | if res < 0:
176 | if blocknr != 0 and self._index[blocknr-1].valid:
177 | blk2 = self._index[blocknr-1]
178 | if blk2.valid and ((self._order[objtype], objid) >= \
179 | (self._order[blk2.first_type], blk2.first_id)):
180 | return blk2
181 | blocknr = bisect.down()
182 | if blocknr == None: # blocknumber 0
183 | return blk
184 | elif res == 0: ## exact match (rare case)
185 | return blk
186 | else:
187 | if blocknr == len(self._index)-1:
188 | return blk
189 | blk2 = self._index[blocknr+1]
190 | if blk2.valid and ((self._order[objtype], objid) < \
191 | (self._order[blk2.first_type], blk2.first_id)):
192 | return blk
193 | blocknr = bisect.up()
194 |
195 | def _checkline(self, line, objtype, objid):
196 | if re.match('\s* lastid + 1000:
346 | blk = self._get_block(objtype, objid)
347 | self._filehandler.seek(blk.fileindex)
348 | lastid = objid
349 | while True:
350 | line = self._filehandler.readline()
351 | if not line:
352 | break
353 | ret = self._checkline(line, objtype, objid)
354 | if ret == -2:
355 | continue
356 | elif ret == -1:
357 | continue
358 | elif ret == 0:
359 | datalines.append(line)
360 | break
361 | elif ret == 1:
362 | line = ""
363 | lastid = objid - 10000
364 | break
365 | if not line:
366 | continue
367 | if line[-3:] == '/>\n':
368 | continue
369 | while True:
370 | line = self._filehandler.readline()
371 | datalines.append(line)
372 | if re.match('[ \t]*%s>' %objtype, line):
373 | break
374 | return ''.join(datalines)
375 |
376 |
377 | class Bz2Reader(object):
378 | """
379 | Helper class to access a bz2-compressed file like an uncompressed file.
380 | """
381 | def __init__(self, filehandler, bz2filehead, bz2filesize):
382 | self._filehandler = filehandler
383 | self.__filehead = bz2filehead
384 | self._filesize = bz2filesize
385 |
386 | def changeblock(self, bz2block):
387 | """
388 | Reset the reader cursor to another block index.
389 | """
390 | self.__blk = bz2block
391 | self.__bz2dc = bz2.BZ2Decompressor()
392 | self.__bz2dc.decompress(self.__filehead)
393 | self.__bz2cursor = self.__blk.fileindex
394 | self.__databuffer = ""
395 | self.__datacursor = 0
396 |
397 | def __readbz2(self, size):
398 | """
399 | Read data with the given size from the bz2-file.
400 | The size is defined in the compressed context of the bz2-file
401 | """
402 | self._filehandler.seek(self.__bz2cursor)
403 | if self.__bz2cursor == self._filesize - 5:
404 | return 'EOF'
405 | if self.__bz2cursor + size >= self._filesize - 5:
406 | size = self._filesize - self.__bz2cursor - 5
407 | datain = self._filehandler.read(size)
408 | while datain:
409 | try:
410 | self.__databuffer += self.__bz2dc.decompress(datain)
411 | except EOFError as msg:
412 | log.debug(msg, len(self.__bz2dc.unused_data))
413 | if len(self.__bz2dc.unused_data) > 4:
414 | log.debug("unused head", self.__bz2dc.unused_data[:4])
415 | datain = self.__bz2dc.unused_data
416 | self.__bz2dc = bz2.BZ2Decompressor()
417 | continue
418 | except Exception as msg:
419 | log.debug(msg)
420 | return False
421 | break
422 |
423 | self.__bz2cursor = self._filehandler.tell()
424 | return True
425 |
426 | def read(self, size):
427 | """
428 | Read the given number of bytes from the bz2-file
429 | The size is defined in uncompressed bytes.
430 | """
431 | while (len(self.__databuffer) - self.__datacursor) < size:
432 | res = self.__readbz2(size // 20)
433 | if res == 'EOF':
434 | data = self.__databuffer[self.__datacursor:]
435 | self.__databuffer = ""
436 | self.__datacusor = 0
437 | if data:
438 | return data
439 | else:
440 | return False
441 | if not res:
442 | return False
443 |
444 | data = self.__databuffer[self.__datacursor:self.__datacursor + size]
445 | self.__datacursor += size
446 |
447 | if self.__datacursor > 2*size:
448 | self.__databuffer = self.__databuffer[self.__datacursor:]
449 | self.__datacursor = 0
450 |
451 | return data
452 |
453 | def readline(self):
454 | """
455 | Read a line from the bz2reader
456 | """
457 | while True:
458 | ind = self.__databuffer.find('\n', self.__datacursor)
459 | if ind == -1:
460 | res = self.__readbz2(10000)
461 | if not res:
462 | return False
463 | elif res == 'EOF':
464 | return False
465 | else:
466 | line = self.__databuffer[self.__datacursor:ind]
467 | self.__datacursor = ind + 1
468 | break
469 |
470 | if self.__datacursor > 100000:
471 | self.__databuffer = self.__databuffer[self.__datacursor:]
472 | self.__datacursor = 0
473 | return line
474 |
475 |
476 | class Bz2OsmDb(OsmDb):
477 | """
478 | Bz2OsmDb offers random access to large bz2 compressed osm files that
479 | cannot be loaded into memomry with the pyosm class.
480 | Basically it creates a file index on the fly and binary search system
481 | to find objects in large files really fast.
482 | The API is identical to the OsmDb class.
483 | Note: This class cannot access multistream bz2 files
484 | see http://bugs.python.org/issue1625 for details
485 | """
486 | def __init__(self, bz2filename):
487 | self.bz2filename = bz2filename
488 | self._index = []
489 | self._order = {'changeset': -1, 'node': 0, 'way': 1, 'relation': 2}
490 | self._filesize = os.path.getsize(self.bz2filename)
491 | self._filehandler = open(self.bz2filename, 'rb')
492 | self._bz2_filehead = self._filehandler.read(4)
493 | log.debug("file head:", str(self._bz2_filehead))
494 |
495 | self._create_index()
496 | self._bz2reader = Bz2Reader(self._filehandler, self._bz2_filehead, self._filesize)
497 |
498 | def _create_index(self):
499 | """
500 | Create an index for the compressed osm file
501 | """
502 | BZ2_COMPRESSED_MAGIC = chr(0x31)+chr(0x41)+chr(0x59)+chr(0x26)+chr(0x53)+chr(0x59)
503 | READBLOCK_SIZE = 100000000
504 | log.debug("Bz2OsmDb: creating index")
505 | fin = self._filehandler
506 | block_nr = 0
507 | while True:
508 | cursor = 0
509 | fin.seek(block_nr * READBLOCK_SIZE)
510 | buf = fin.read(READBLOCK_SIZE+10)
511 | while True:
512 | found = buf.find(BZ2_COMPRESSED_MAGIC, cursor)
513 | if found == -1:
514 | break
515 | block = IndexBlock(block_nr * READBLOCK_SIZE + found)
516 | self._index.append(block)
517 | cursor = found + 2
518 | block_nr += 1
519 | if fin.tell() < block_nr * READBLOCK_SIZE:
520 | break
521 |
522 | log.debug("Bz2OsmDb: index complete: %d Blocks" % len(self._index))
523 |
524 | def _validate(self, blk):
525 | """
526 | Find the first object element in the block and update the block index.
527 | Returns False if the block has no object item.
528 | """
529 | if blk.valid:
530 | return True
531 |
532 | self._bz2reader.changeblock(blk)
533 | while True:
534 | line = self._bz2reader.readline()
535 | if line == False: ## EOF or Error
536 | return False
537 | else:
538 | for obj in ['node', 'way', 'relation','changeset']:
539 | if re.match('[ \t]*<%s id="[0-9]*" ' % obj, line):
540 | blk.first_type = obj
541 | blk.first_id = int(line.split('"')[1])
542 | blk.valid = True
543 | return True
544 |
545 | def write_relations(self, filename):
546 | """
547 | Write all relations of the osm fileobject to the given filename.
548 | If the filename ends with ".bz2", then the relations will be compressed.
549 | With filename=/dev/stdout you can get a stream of all realations.
550 | """
551 | log.debug("Bz2OsmDb: writing relations")
552 | OSMHEAD = """\n""" \
553 | """"""
554 | blk = self._get_block('relation', 0)
555 | self._bz2reader.changeblock(blk)
556 |
557 | if filename[-4:] == '.bz2':
558 | fout = bz2.BZ2File(filename, 'w')
559 | else:
560 | fout = open(filename, 'w')
561 |
562 | while True:
563 | line = self._bz2reader.readline()
564 | if re.match('[ \t]*\n""" \
584 | """"""
585 | blk = self._get_block('way', 0)
586 | self._bz2reader.changeblock(blk)
587 |
588 | if filename[-4:] == '.bz2':
589 | fout = bz2.BZ2File(filename, 'w')
590 | else:
591 | fout = open(filename, 'w')
592 |
593 | while True:
594 | line = self._bz2reader.readline()
595 | if re.match('[ \t]* lastid + 1000:
618 | blk = self._get_block(objtype, objid)
619 | self._bz2reader.changeblock(blk)
620 | lastid = objid
621 | while True:
622 | line = self._bz2reader.readline()
623 | if not line:
624 | break
625 | ret = self._checkline(line, objtype, objid)
626 | if ret == -2:
627 | continue
628 | if ret == -1:
629 | continue
630 | elif ret == 0:
631 | datalines.append(line)
632 | break
633 | elif ret == 1:
634 | line = ""
635 | break
636 | if not line:
637 | continue
638 | if line[-2:] == '/>': # object already complete
639 | continue
640 | while True:
641 | line = self._bz2reader.readline()
642 | datalines.append(line)
643 | if re.match('[ \t]*%s>' %objtype, line):
644 | break
645 | return '\n'.join(datalines) + '\n'
646 |
647 |
648 | class OSMHttpHandler(BaseHTTPRequestHandler):
649 | """
650 | HTTP handler URL commands from the HTTP server.
651 | """
652 | def print_help(self):
653 | self.send_response(404)
654 | self.send_header('Content-type', 'text/html')
655 | self.end_headers()
656 | self.wfile.write("OSMDB File interface
")
657 | self.wfile.write("=====================
")
658 | self.wfile.write("valid commands are:
")
659 | self.wfile.write(" nodes?nodes=id1,id2,...
")
660 | self.wfile.write(" ways?ways=id1,id2,...
")
661 | self.wfile.write(" relations?relations=id1,id2,...
")
662 | self.wfile.write(" ways?ways=id1,id2,...&mode=full
")
663 | self.wfile.write(" relations?relations=id1,id2,...&mode=full
")
664 | self.wfile.write(" relations?relations=id1,id2,...&mode=recursive")
665 | return
666 |
667 | def do_GET(self):
668 | print (self.path)
669 | osm = self.server.osmdb
670 | toks = self.path.split('?')
671 | if len(toks) != 2:
672 | self.print_help()
673 | return
674 | else:
675 | command = toks[0]
676 | kvs = toks[1].split('&')
677 | args = dict([kv.split('=',1) for kv in kvs])
678 | try:
679 | if command == '/nodes':
680 | nodes = [int(n) for n in args['nodes'].split(',')]
681 | data = osm.get_objects('node', nodes)
682 | elif command == '/ways':
683 | ways = [int(n) for n in args['ways'].split(',')]
684 | if args.get('mode','') == 'full':
685 | data = osm.get_objects_recursive('way', ways)
686 | else:
687 | data = osm.get_objects('way', ways)
688 | elif command == '/relations':
689 | relations = [int(n) for n in args['relations'].split(',')]
690 | if args.get('mode','') == 'full':
691 | data = osm.get_objects_recursive('relation', relations)
692 | elif args.get('mode','') == 'recursive':
693 | data = osm.get_objects_recursive('relation', relations, recursive=True)
694 | else:
695 | data = osm.get_objects('relation', relations)
696 | self.send_response(200)
697 | self.send_header('Content-type', 'text/xml')
698 | self.end_headers()
699 | self.wfile.write(OSMHEAD+'\n')
700 | self.wfile.write(data)
701 | self.wfile.write('')
702 | return
703 | except IOError:
704 | self.send_error(404,'File Not Found: %s' % self.path)
705 |
706 |
707 | ################### FUNCTIONS
708 | def runserver(port, osmdb):
709 | """
710 | Start the http-server with the given port and osmdb object.
711 | """
712 | try:
713 | server = HTTPServer(('', port), OSMHttpHandler)
714 | server.osmdb = osmdb
715 | print ('started httpserver...')
716 | server.serve_forever()
717 | except KeyboardInterrupt:
718 | print ('^C received, shutting down server')
719 | server.socket.close()
720 |
721 | def usage():
722 | print (sys.argv[0] + " Version " + VERSION)
723 | print (" -h, --help: print this help information")
724 | print (" --relations=outfile: split relations from input file")
725 | print (" --ways_relations=outfile: split ways and relations from input file")
726 | print (" --server=port: start a http-Server on Port")
727 | print ("Examples:")
728 | print (" osmdb.py --relations=out.osm.bz2 germany.osm.bz2")
729 | print (" osmdb.py --ways_relations=/dev/stdout planet-latest.osm")
730 | print (" osmdb.py --server=8888 germany.osm")
731 |
732 | #################### MAIN
733 | if __name__ == '__main__':
734 | import getopt
735 |
736 | try:
737 | opts, args = getopt.getopt(sys.argv[1:], 'h',
738 | ['relations=', 'ways_relations=', 'server=', 'help'])
739 | except getopt.GetoptError:
740 | usage()
741 | sys.exit()
742 |
743 |
744 | for o, a in opts:
745 | if o in ['--relations']:
746 | if len(args) != 1:
747 | usage()
748 | sys.exit(-1)
749 | outfile = a
750 | if os.path.splitext(args[0])[1] in ['.bz2','.BZ2']:
751 | osmdb = Bz2OsmDb(args[0])
752 | else:
753 | osmdb = OsmDb(args[0])
754 | osmdb.write_relations(outfile)
755 | sys.exit()
756 | elif o in ['--ways_relations']:
757 | if len(args) != 1:
758 | usage()
759 | sys.exit(-1)
760 | outfile = a
761 | if os.path.splitext(args[0])[1] in ['.bz2','.BZ2']:
762 | osmdb = Bz2OsmDb(args[0])
763 | else:
764 | osmdb = OsmDb(args[0])
765 | osmdb.write_ways_relations(outfile)
766 | sys.exit()
767 | elif o in ['--server']:
768 | if len(args) != 1:
769 | usage()
770 | sys.exit(-1)
771 | port = int(a)
772 | if os.path.splitext(args[0])[1] in ['.bz2','.BZ2']:
773 | osmdb = Bz2OsmDb(args[0])
774 | else:
775 | osmdb = OsmDb(args[0])
776 | runserver(port, osmdb)
777 | sys.exit()
778 | elif o in ['--help']:
779 | usage()
780 | sys.exit()
781 |
--------------------------------------------------------------------------------
/src/osm/pyosm.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # Original version by Rory McCann (http://blog.technomancy.org/)
3 | # Modifications by Christoph Lupprich (http://www.stopbeingcarbon.com)
4 | #
5 | import xml.sax.saxutils
6 | import numpy
7 | import logging
8 | log = logging.getLogger("pyosm")
9 |
10 |
11 | #################### CLASSES
12 | class Attributes(object):
13 | """
14 | common attributes for all object types
15 | """
16 | __slot__ = ['timestamp', 'uid', 'user', 'visible', 'version', 'changeset']
17 |
18 | def __init__(self, attrs):
19 | self.timestamp = attrs.get('timestamp','')
20 | self.version = attrs.get('version', '')
21 | self.changeset = attrs.get('changeset','')
22 | self.uid = attrs.get('uid','')
23 | self.user = attrs.get('user','')
24 | self.visible = attrs.get('visible','')
25 |
26 | def set_attr(self, name, value):
27 | if hasattr(self, name):
28 | setattr(self,name, value)
29 | else:
30 | raise KeyError
31 |
32 | def get(self, name, default=None):
33 | if hasattr(self, name):
34 | return getattr(self,name)
35 | else:
36 | return default
37 |
38 | def get_all(self):
39 | return {'timestamp': self.timestamp,
40 | 'version': self.version,
41 | 'changeset': self.changeset,
42 | 'uid': self.uid,
43 | 'user': self.user,
44 | 'visible': self.visible}
45 |
46 |
47 | class Node(object):
48 | __slot__ = ['id', 'lat', 'lon','__attrs', '__tags']
49 |
50 | def __init__(self, attrs, tags=None, load_tags=True, load_attrs=True):
51 | self.lon = 0.0
52 | self.lat = 0.0
53 | self.__attrs = None
54 | self.__tags = None
55 |
56 | self.id = int(attrs.pop('id'))
57 | if attrs.get('visible', '') != 'false':
58 | self.lon = float(attrs.pop('lon'))
59 | self.lat = float(attrs.pop('lat'))
60 |
61 | if load_attrs:
62 | self.__attrs = Attributes(attrs)
63 |
64 | if load_tags:
65 | self.__tags = tags
66 |
67 | def __getattr__(self, name):
68 | if name == 'tags':
69 | return self.__tags
70 | elif self.__attrs:
71 | return self.__attrs.get(name)
72 |
73 | def __getitem__(self, name):
74 | if name == 'lat':
75 | return self.lat
76 | elif name == 'lon':
77 | return self.lon
78 | elif name == 'id':
79 | return self.id
80 | elif name == 'tags':
81 | return self.__tags
82 |
83 | def __cmp__(self, other):
84 | cmp_ref = cmp(self.tags.get('ref',''), other.tags.get('ref',''))
85 | if cmp_ref:
86 | return cmp_ref
87 | cmp_name = cmp(self.tags.get('name',''), other.tags.get('name',''))
88 | if cmp_name:
89 | return cmp_name
90 | return cmp(self.id, other.id)
91 |
92 | def set_attr(self, name, value):
93 | self.__attrs.set_attr(name, value)
94 |
95 | def attributes(self):
96 | d = {'id': repr(self.id),
97 | 'lat': repr(self.lat),
98 | 'lon': repr(self.lon)}
99 | if self.__attrs:
100 | d.update(self.__attrs.get_all())
101 | return d
102 |
103 | def bbox(self, **kwargs):
104 | return (self.lat, self.lat, self.lon, self.lon)
105 |
106 | def __repr__(self):
107 | return "Node(attrs=%r, tags=%r)" % (self.attributes(), self.__tags)
108 |
109 |
110 | class Way(object):
111 | __slot__ = ['id', '__attrs','__tags','__nodes', 'osm_parent']
112 |
113 | def __init__(self, attrs, tags=None, nodes=None, osm_parent=None, load_tags=True, load_attrs=True, load_nodes=True):
114 | self.__nodes = None
115 | self.__attrs = None
116 | self.__tags = None
117 |
118 | self.id = int(attrs.pop('id'))
119 | self.osm_parent = osm_parent
120 |
121 | if load_nodes:
122 | self.__nodes = numpy.asarray(nodes, dtype='int64')
123 | if load_attrs:
124 | self.__attrs = Attributes(attrs)
125 | if load_tags:
126 | self.__tags = tags
127 |
128 | def __getattr__(self, name):
129 | if name == 'nodes':
130 | return self.osm_parent.get_nodes(self.__nodes)
131 | elif name == 'nodeids':
132 | return list(self.__nodes)
133 | elif name == 'tags':
134 | return self.__tags
135 | elif self.__attrs:
136 | return self.__attrs.get(name)
137 |
138 | def __getitem__(self, name):
139 | if name == 'id':
140 | return self.id
141 | elif name == 'nodes':
142 | return self.osm_parent.get_nodes(self.__nodes)
143 | elif name == 'nodeids':
144 | return list(self.__nodes)
145 | elif name == 'tags':
146 | return self.__tags
147 |
148 | def __cmp__(self, other):
149 | cmp_ref = cmp(self.tags.get('ref',''), other.tags.get('ref',''))
150 | if cmp_ref:
151 | return cmp_ref
152 | cmp_name = cmp(self.tags.get('name',''), other.tags.get('name',''))
153 | if cmp_name:
154 | return cmp_name
155 | return cmp(self.id, other.id)
156 |
157 | def set_attr(self, name, value):
158 | self.__attrs.set_attr(name, value)
159 |
160 | def attributes(self):
161 | d = {'id': repr(self.id)}
162 | if self.__attrs:
163 | d.update(self.__attrs.get_all())
164 | return d
165 |
166 | def distance(self):
167 | """
168 | returns the distance of the way in meters
169 | """
170 | if len(self.nodes) < 2:
171 | return 0.0
172 | lat = numpy.array([n.lat for n in self.nodes]) * numpy.pi / 180
173 | lon = numpy.array([n.lon for n in self.nodes]) * numpy.pi / 180
174 | lat1 = lat[:-1]
175 | lat2 = lat[1:]
176 | lon1 = lon[:-1]
177 | lon2 = lon[1:]
178 |
179 | #formula see: https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas
180 | dist = numpy.arctan(numpy.sqrt((numpy.cos(lat2)*numpy.sin(abs(lon1-lon2)))**2 + (numpy.cos(lat1)*numpy.sin(lat2) - numpy.sin(lat1)*numpy.cos(lat2)*numpy.cos(lon1-lon2))**2) / (numpy.sin(lat1)*numpy.sin(lat2) + numpy.cos(lat1)*numpy.cos(lat2)*numpy.cos(lon1-lon2)))
181 | return numpy.sum(dist) * 6372795
182 |
183 | def bbox(self, **kwargs):
184 | lat = [n.lat for n in self.nodes]
185 | lon = [n.lon for n in self.nodes]
186 | return min(lat), max(lat), min(lon), max(lon)
187 |
188 | def __repr__(self):
189 | return "Way(attrs=%r, tags=%r, nodes=%r)" % (self.attributes(), self.__tags, list(self.__nodes))
190 |
191 |
192 | class Relation(object):
193 | __slot__ = ['id', '__attrs','__tags','__members', 'osm_parent']
194 |
195 | def __init__(self, attrs, tags=None, members=None, osm_parent=None, load_tags=True, load_attrs=True, load_members=True):
196 | self.__members = None
197 | self.__attrs = None
198 | self.__tags = None
199 |
200 | self.id = int(attrs.pop('id'))
201 | self.osm_parent = osm_parent
202 |
203 | if load_members:
204 | self.__members = numpy.array(members, dtype=[('type','|S1'),('id','
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 |
--------------------------------------------------------------------------------
/tests/osmfiles/multipolygon1.osm:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/tests/test_multipolygon.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/python
2 | import os
3 | import sys
4 | import unittest
5 |
6 | srcDir = os.path.abspath('../src/osm')
7 | sys.path.insert(1, srcDir)
8 |
9 | import pyosm
10 | import multipolygon
11 |
12 |
13 | class OSMXMLFileTests(unittest.TestCase):
14 | def setUp(self):
15 | self.osm_file = 'osmfiles/multipolygon1.osm'
16 | self.osm = pyosm.OSMXMLFile(self.osm_file)
17 |
18 | def tearDown(self):
19 | pass
20 |
21 | def test_multipolygon(self):
22 | mp = multipolygon.multipolygon(self.osm.relations[179755])
23 | mp.status()
24 |
25 | def test_josmfile(self):
26 | mp = multipolygon.multipolygon(self.osm.relations[179755])
27 | mp.write_josm_file('testoutput/josmfile.xml')
28 |
29 | def test_osmosisfile(self):
30 | mp = multipolygon.multipolygon(self.osm.relations[179755])
31 | mp.write_osmosis_file('testoutput/josmfile.xml')
32 |
33 | def test_point_in_polygon(self):
34 | mp = multipolygon.multipolygon(self.osm.relations[179755])
35 | points = [(9.58533328102,47.66978302865),
36 | (9.58518367709,47.66978913432),
37 | (9.58497428566,47.66984484554),
38 | (9.58481320699,47.66985426283),
39 | (9.58466333116,47.66985520476),
40 | (9.58451372723,47.66986131043)]
41 | inside = mp.inside(points=points)
42 | self.assertAlmostEqual(inside.sum(), 4)
43 |
44 |
45 | if __name__ == '__main__':
46 | if not os.path.exists('testoutput'):
47 | os.mkdir('testoutput')
48 | unittest.main()
49 |
--------------------------------------------------------------------------------
/tests/test_osmdb:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #################### bz2osmdb commandlines
4 | echo TEST1
5 | echo "TEST1-----------------------" > test_osmdb_out.txt
6 | ../src/osm/osmdb.py --help >> test_osmdb_out.txt
7 |
8 | echo TEST2
9 | echo "TEST2-----------------------" >> test_osmdb_out.txt
10 | ../src/osm/osmdb.py --ways_relations=/dev/stdout ../../../osm_files/romania.osm.bz2| head >>test_osmdb_out.txt
11 |
12 | echo TEST3
13 | echo "TEST3-----------------------" >> test_osmdb_out.txt
14 | ../src/osm/osmdb.py --relations=/dev/stdout ../../../osm_files/romania.osm.bz2| head >>test_osmdb_out.txt
15 |
16 | echo TEST4
17 | echo "TEST4-----------------------" >> test_osmdb_out.txt
18 | ../src/osm/osmdb.py --relations=/dev/stdout ../../../osm_files/romania.osm.bz2| tail >>test_osmdb_out.txt
19 |
20 | #################### bz2osmdb server
21 | PORT=8888
22 | OSM_FILE=../../../osm_files/germany.osm.bz2
23 | ../src/osm/osmdb.py --server=$PORT $OSM_FILE &
24 | SERVER_PID=$!
25 | ## wait for server startup
26 | sleep 60
27 |
28 | wget -Obz2osmdb_nodes.xml http://localhost:$PORT/nodes?nodes=437498388,437498385,180721525
29 |
30 | wget -Obz2osmdb_ways.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511
31 | wget -Obz2osmdb_ways_full.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511\&mode=full
32 |
33 | wget -Obz2osmdb_relation.xml http://localhost:$PORT/relations?relations=167920,131414
34 | wget -Obz2osmdb_relation_full.xml http://localhost:$PORT/relations?relations=1111111\&mode=full
35 | wget -Obz2osmdb_relation_recursive.xml http://localhost:$PORT/relations?relations=1111111\&mode=recursive
36 |
37 | kill $SERVER_PID
38 |
39 | #################### osmdb commandlines
40 | OSM_FILE=/osm/germany.osm
41 |
42 | echo TEST5
43 | echo TEST5----------------------- >> test_osmdb_out.txt
44 | ../src/osm/osmdb.py --help >> test_osmdb_out.txt
45 |
46 | echo TEST5
47 | echo TEST5----------------------- >> test_osmdb_out.txt
48 | ../src/osm/osmdb.py --ways_relations=/dev/stdout $OSM_FILE | head >>test_osmdb_out.txt
49 |
50 | echo TEST6
51 | echo TEST6----------------------- >> test_osmdb_out.txt
52 | ../src/osm/osmdb.py --relations=/dev/stdout $OSM_FILE | head >>test_osmdb_out.txt
53 |
54 | #################### osmdb server
55 | PORT=8888
56 | ../src/osm/osmdb.py --server=$PORT $OSM_FILE &
57 | SERVER_PID=$!
58 | ## wait for server startup
59 | sleep 20
60 |
61 | wget -Oosmdb_nodes.xml http://localhost:$PORT/nodes?nodes=437498388,437498385,180721525
62 |
63 | wget -Oosmdb_ways.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511
64 | wget -Oosmdb_ways_full.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511\&mode=full
65 |
66 | wget -Oosmdb_relation.xml http://localhost:$PORT/relations?relations=167920,131414
67 | wget -Oosmdb_relation_full.xml http://localhost:$PORT/relations?relations=1111111\&mode=full
68 | wget -Oosmdb_relation_recursive.xml http://localhost:$PORT/relations?relations=1111111\&mode=recursive
69 |
70 | kill $SERVER_PID
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/tests/test_osmdb.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/python
2 | import os
3 | import sys
4 | import unittest
5 | import logging
6 |
7 | srcDir = os.path.abspath('../src/osm')
8 | sys.path.insert(1, srcDir)
9 |
10 | import osmdb
11 | log = logging.getLogger(__name__)
12 |
13 | class OsmDbTests(unittest.TestCase):
14 | def setUp(self):
15 | # local uncompressed file of the planet file
16 | log.info('load planet')
17 | self.db = osmdb.OsmDb('/store/osm/planet-latest.osm')
18 |
19 | def tearDown(self):
20 | pass
21 |
22 | def test_get_objects(self):
23 | #db = osmdb.Bz2OsmDb('/store/osm/files/australia.osm.bz2')
24 | #db = osmdb.OsmDb('/store/osm/files/australia.osm')
25 |
26 | log.info('Node: small id')
27 | ret = self.db.get_objects('node',[1])
28 | log.info(' return length %i', len(ret))
29 |
30 | log.info('Node: regular ids')
31 | ret = self.db.get_objects('node',[579259,579260])
32 | log.info(' return length %i', len(ret))
33 |
34 | log.info('Node: large ids')
35 | ret = self.db.get_objects('node',[12345678900])
36 | log.info(' return length %i', len(ret))
37 |
38 | log.info('Way: small id')
39 | ret = self.db.get_objects('way',[1])
40 | log.info(' return length %i', len(ret))
41 |
42 | log.info('Way: regular ids')
43 | ret = self.db.get_objects('way',[174372276,168734042])
44 | log.info(' return length %i', len(ret))
45 |
46 | log.info('Way: large ids')
47 | ret = self.db.get_objects('way',[12345678900])
48 | log.info(' return length %i', len(ret))
49 |
50 | log.info('Relation: small id')
51 | ret = self.db.get_objects('relation',[1])
52 | log.info(' return length %i', len(ret))
53 |
54 | log.info('Relation: regular ids')
55 | ret = self.db.get_objects('relation',[6188])
56 | log.info(' return length %i', len(ret))
57 |
58 | log.info('Relation: large ids')
59 | ret = self.db.get_objects('relation',[12345678900])
60 | log.info(' return length %i', len(ret))
61 |
62 | log.info('Relation: regular id, recursive call')
63 | ret = self.db.get_objects_recursive('relation',[6188], True)
64 | log.info(' return length %i', len(ret))
65 |
66 |
67 | class Bz2OsmDbTests(unittest.TestCase):
68 | def setUp(self):
69 | # local bz2 compressed file of australia file
70 | log.info('load australia')
71 | self.db = osmdb.Bz2OsmDb('/store/osm/files/australia.osm.bz2')
72 |
73 | def tearDown(self):
74 | pass
75 |
76 | def test_get_objects(self):
77 | log.info('Node: small id')
78 | ret = self.db.get_objects('node',[1])
79 | log.info(' return length %i', len(ret))
80 |
81 | log.info('Node: regular ids')
82 | ret = self.db.get_objects('node',[579259,579260])
83 | log.info(' return length %i', len(ret))
84 |
85 | log.info('Node: large ids')
86 | ret = self.db.get_objects('node',[12345678900])
87 | log.info(' return length %i', len(ret))
88 |
89 | log.info('Way: small id')
90 | ret = self.db.get_objects('way',[1])
91 | log.info(' return length %i', len(ret))
92 |
93 | log.info('Way: regular ids')
94 | ret = self.db.get_objects('way',[174372276,168734042])
95 | log.info(' return length %i', len(ret))
96 |
97 | log.info('Way: large ids')
98 | ret = self.db.get_objects('way',[12345678900])
99 | log.info(' return length %i', len(ret))
100 |
101 | log.info('Relation: small id')
102 | ret = self.db.get_objects('relation',[1])
103 | log.info(' return length %i', len(ret))
104 |
105 | log.info('Relation: regular ids')
106 | ret = self.db.get_objects('relation',[6188])
107 | log.info(' return length %i', len(ret))
108 |
109 | log.info('Relation: large ids')
110 | ret = self.db.get_objects('relation',[12345678900])
111 | log.info(' return length %i', len(ret))
112 |
113 | log.info('Relation: regular id, recursive call')
114 | ret = self.db.get_objects_recursive('relation',[6188], True)
115 | log.info(' return length %i', len(ret))
116 |
117 | if __name__ == '__main__':
118 | logging.basicConfig(level=logging.INFO)
119 | unittest.main()
120 |
--------------------------------------------------------------------------------
/tests/test_pyosm.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/python
2 | import os
3 | import sys
4 | import unittest
5 | import logging
6 |
7 | srcDir = os.path.abspath('../src/osm')
8 | sys.path.insert(1, srcDir)
9 | import pyosm
10 |
11 | log = logging.getLogger(__name__)
12 |
13 | class OSMXMLFileTests(unittest.TestCase):
14 | def setUp(self):
15 | self.osm_file = 'osmfiles/multipolygon1.osm'
16 | self.osm = pyosm.OSMXMLFile(self.osm_file)
17 |
18 | def tearDown(self):
19 | pass
20 |
21 | def test_osm_objects(self):
22 | self.osm.statistic()
23 | r = list(self.osm.relations.values())[-1]
24 | log.info('Single relation representation: %s', r)
25 | w = list(self.osm.ways.values())[-1]
26 | log.info('\nSingle way representation: %s', w)
27 | n = list(self.osm.nodes.values())[1]
28 | log.info('Single node representation: %s', n)
29 |
30 | log.info('Nodes of a Way: %s', w.nodes)
31 | log.info('Nodeids of a Way: %s', w.nodeids)
32 |
33 | log.info('Member Data of a Relation: %s', r.member_data)
34 | log.info('Members of a Relation: %s', r.members)
35 |
36 | def test_osm_itemgetter(self):
37 | log.info('relation item test:')
38 | r = list(self.osm.relations.values())[0] # get first relation
39 | for it in ['id','members','member_data','tags','bbox']:
40 | log.info(' %s=%s', it, r[it])
41 | log.info('way item test:')
42 | w = list(self.osm.ways.values())[0] # get first way
43 | for it in ['id','nodes','nodeids','tags','bbox']:
44 | log.info(' %s=%s', it, w[it])
45 | log.info('node item test:')
46 | n = list(self.osm.nodes.values())[0] # get first node
47 | for it in ['id','lat', 'lon','tags']:
48 | log.info(' %s=%s', it, n[it])
49 |
50 | def test_merge_write(self):
51 | osm2 = pyosm.OSMXMLFile(filename='osmfiles/josm_download.osm')
52 | log.info('osm2 stat befor merge')
53 | osm2.statistic()
54 | osm2.merge(self.osm)
55 | log.info('osm2 stat after merge')
56 | osm2.statistic()
57 | osm2.write('testoutput/result_merge_write.osm')
58 |
59 | def test_geometry(self):
60 | log.info('geometry tests:')
61 | w = list(self.osm.ways.values())[0] # get first way
62 | log.info(' distance way0: %f' % w.distance())
63 | log.info(' bbox way0: %s' % str(w.bbox()))
64 | r = list(self.osm.relations.values())[0] # get first relation
65 | log.info(' distance rel0: %f' % r.distance())
66 | log.info(' bbox rel0: %s' % str(r.bbox()))
67 | germany = pyosm.OSMXMLFile('osmfiles/germany_borders.osm')
68 | rb = germany.relations[1111111]
69 | log.info(' border bbox %s' % str(rb.bbox()))
70 | log.info(' border bbox %s' % str(rb.bbox(recursive=True)))
71 | log.info(' border length %f' % rb.distance())
72 | log.info(' border length recursive %f' % rb.distance(recursive=True))
73 | log.info(' border length recursive %f' % rb.distance(recursive=True, roles=['outer','']))
74 |
75 |
76 | if __name__ == '__main__':
77 | if not os.path.exists('testoutput'):
78 | os.mkdir('testoutput')
79 | logging.basicConfig(level=logging.INFO)
80 | unittest.main()
--------------------------------------------------------------------------------
/tools/osmhistory.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | import sys, os
3 | import re, math
4 | import urllib
5 | import httplib
6 |
7 | PYOSM_DIR = os.path.join(os.path.dirname(__file__), '../src')
8 | sys.path.append(PYOSM_DIR)
9 | from osm import pyosm
10 |
11 | VERSION = "0.0.2"
12 |
13 | #################### CONSTANTS
14 | URL='www.openstreetmap.org'
15 | API='/api/0.6'
16 |
17 | #################### FUNCTIONS
18 | def elementhistory(date, relations, ways, nodes):
19 | osmhist = pyosm.OSMXMLFile()
20 |
21 | ## working stacks for all object types
22 | relation_stack = set([int(r) for r in relations])
23 | way_stack = set([int(w) for w in ways])
24 | node_stack = set([int(n) for n in nodes])
25 |
26 | ## load recursively all missing relations
27 | while relation_stack:
28 | relid = relation_stack.pop()
29 | rel = bisect('relation', relid, date)
30 | osmhist.merge(rel)
31 | for mtype, mid, mrole in rel.relations[relid].member_data:
32 | if mtype == 'r':
33 | if mid not in osmhist.relations:
34 | relation_stack.add(mid)
35 | elif mtype == 'w':
36 | way_stack.add(mid)
37 | elif mtype == 'n':
38 | node_stack.add(mid)
39 | else:
40 | raise ValueError('Unknown member type: "%r"' % mtype)
41 |
42 | ## load all ways
43 | for wayid in way_stack:
44 | way = bisect('way', wayid, date)
45 | osmhist.merge(way)
46 | node_stack.update(way.ways[wayid].nodeids)
47 |
48 | ## load all nodes
49 | for nodeid in node_stack:
50 | node = bisect('node', nodeid, date)
51 | osmhist.merge(node)
52 |
53 | return osmhist
54 |
55 |
56 | def bisect(objtype, objid, date, maxversion=None ):
57 | conn = httplib.HTTPConnection(URL)
58 | osmobj = None
59 | minversion = 1
60 | log('bisect:' + objtype, objid)
61 | if not maxversion:
62 | url = '%s/%ss?%ss=%d' %(API, objtype, objtype, objid)
63 | else:
64 | url = '%s/%s/%d/%d' %(API, objtype, objid, maxversion)
65 |
66 | log(' bisect:', url)
67 |
68 | conn.request('GET', url)
69 | ans = conn.getresponse()
70 | content=ans.read()
71 | curr_osm = pyosm.OSMXMLFile(content=content)
72 | curr_obj = getobject(curr_osm, objtype, objid)
73 | newest_version = int(curr_obj.version)
74 |
75 | if curr_obj.timestamp < date:
76 | return curr_osm
77 |
78 | bysect_version = 2**int(math.log(int(curr_obj.version)-1,2))
79 | bysect_step = bysect_version
80 |
81 | while bysect_step:
82 | url = '%s/%s/%d/%d' %(API, objtype, objid, bysect_version)
83 | log(' bisect:', url)
84 | conn.request('GET', url)
85 | ans = conn.getresponse()
86 | bysect_osm = pyosm.OSMXMLFile(content=ans.read())
87 | bysect_obj = getobject(bysect_osm, objtype, objid)
88 |
89 | bysect_step = int(bysect_step / 2)
90 | if bysect_obj.timestamp < date:
91 | curr_osm = bysect_osm
92 | curr_obj = bysect_obj
93 | bysect_version += bysect_step
94 | while bysect_version >= newest_version and bysect_step:
95 | bysect_step = int(bysect_step / 2)
96 | bysect_version -= bysect_step
97 | else:
98 | bysect_version -= bysect_step
99 |
100 | if newest_version > int(curr_obj.version):
101 | curr_obj.tags['osmhistory:old_version_date'] = str(int(curr_obj.version)) + '_' + date
102 | curr_obj.set_attr('version', str(newest_version))
103 |
104 | conn.close()
105 | return curr_osm
106 |
107 | def getobject(osmobj, objtype, objid):
108 | if objtype == 'node':
109 | obj = osmobj.nodes[objid]
110 | elif objtype == 'way':
111 | obj = osmobj.ways[objid]
112 | elif objtype == 'relation':
113 | obj = osmobj.relations[objid]
114 | else:
115 | raise ValueError
116 |
117 | return obj
118 |
119 | def log(s, ss=''):
120 | if True:
121 | sys.stdout.write(str(s) + str(ss) + '\n')
122 |
123 |
124 | def usage():
125 | print sys.argv[0] + " Version " + VERSION
126 | print " -h, --help: print this help information"
127 | print " -t, --timestamp: date for the history. format: YYYY-MM-DD"
128 | print " -o, --outfile: filename for the output filename"
129 | print " -n, --nodes: comma separated list of node ids"
130 | print " -w, --ways: comma separated list of way ids"
131 | print " -r, --relations: comma separated list of relation ids"
132 | print "Examples:"
133 | print " osmhistory.py -t 2009-10-01 -w 13415127,26802382 -o foo.osm"
134 | print " osmhistory.py -t 2009-10-01 --relations=21328 -o rel_21628.osm"
135 | sys.exit()
136 |
137 | #################### MAIN
138 | if __name__ == '__main__':
139 | import getopt
140 |
141 | try:
142 | opts, args = getopt.getopt(sys.argv[1:], 'ht:o:r:w:n:',
143 | ['help', 'timestamp=', 'outfile=', 'relations=', 'ways=', 'nodes='])
144 | except getopt.GetoptError:
145 | usage()
146 |
147 | ## default values
148 | outfile = 'out.osm'
149 | nodes = []
150 | ways = []
151 | relations = []
152 |
153 | for o, a in opts:
154 | if o in ['-h', '--help']:
155 | usage()
156 | elif o in ['-t', '--timestamp']:
157 | if re.match('20[0-9]{2}-[0-9]{2}-[0-9]{2}$', a):
158 | date = a
159 | else:
160 | print 'Error: invalid date'
161 | usage()
162 | elif o in ['-o', '--outfile']:
163 | outfile = a
164 | elif o in ['-n', '--nodes']:
165 | if re.match('[1-9][0-9\,]*[0-9]$', a):
166 | nodes = a.split(',')
167 | else:
168 | print 'Error: invalid nodes list'
169 | usage()
170 | elif o in ['-w', '--ways']:
171 | if re.match('[1-9][0-9,]*[0-9]$', a):
172 | ways = a.split(',')
173 | else:
174 | print 'Error: invalid ways list'
175 | usage()
176 | elif o in ['-r', '--relations']:
177 | if re.match('[1-9][0-9,]*[0-9]$', a):
178 | relations = a.split(',')
179 | else:
180 | print 'Error: invalid relations list'
181 | usage()
182 |
183 | osm = elementhistory(date, relations, ways, nodes)
184 | osm.write(outfile)
185 |
186 |
187 |
188 |
--------------------------------------------------------------------------------
/tools/relation2gpx.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import sys, os
4 | import xml.dom.minidom
5 |
6 | PYOSM_DIR = os.path.join(os.path.dirname(__file__), '../src')
7 | sys.path.append(PYOSM_DIR)
8 | from osm import pyosm
9 |
10 | #################### CLASSES
11 | class osm_gpx_exporter(object):
12 | gpx_template = """
13 |
16 |
17 | osm_gpx_exporter
18 |
19 |
20 | """
21 |
22 | def __init__(self, gpx_filename):
23 | self.gpx_filename = gpx_filename
24 | self.init_gpx()
25 |
26 | def init_gpx(self):
27 | self.gpx_dom = xml.dom.minidom.parseString(self.gpx_template)
28 | self.gpx_root = self.gpx_dom.documentElement
29 |
30 | def append_relations(self, relations=[], recursive=True):
31 | """
32 | append an osm object to a gpx track
33 | relation --> track (trk)
34 | way --> track segment (trkseg)
35 | node --> track point (trkpt)
36 | """
37 | for rel in relations:
38 | trk = self.gpx_dom.createElement('trk')
39 | self.gpx_root.appendChild(trk)
40 | for m, role in rel.members:
41 | if type(m) != pyosm.Way:
42 | continue
43 | trkseg = self.gpx_dom.createElement('trkseg')
44 | trk.appendChild(trkseg)
45 | for node in m.nodes:
46 | trkpt = self.gpx_dom.createElement('trkpt')
47 | trkpt.setAttribute('lat', str(node.lat))
48 | trkpt.setAttribute('lon', str(node.lon))
49 | trkseg.appendChild(trkpt)
50 |
51 | def write(self):
52 | """
53 | export the gpx_dom into a file
54 | """
55 | open(self.gpx_filename,'wt').write(self.gpx_dom.toprettyxml(" "))
56 |
57 |
58 | #################### FUNCTIONS
59 | def usage():
60 | print "usage: relation2gpx.py [-o GPXFILE] -r relation1,relation2,..."
61 | print "load relations from the OSM API and create gpx files"
62 | print " -h, --help: print this help message"
63 | print " -o, --outfile: specify the filename of the gpx file"
64 | print " -r, --relations: commaseperated list of relations"
65 |
66 |
67 | #################### MAIN
68 | if __name__ == '__main__':
69 | import getopt
70 | import urllib
71 |
72 | try:
73 | opts, args = getopt.getopt(sys.argv[1:], 'o:r:',
74 | ['outfile=', 'relations='])
75 | except getopt.GetoptError:
76 | usage()
77 | sys.exit(1)
78 |
79 | outfile='out.gpx'
80 | relids = []
81 |
82 | for o, a in opts:
83 | if o in ['-o', '--outfile']:
84 | outfile = a
85 | elif o in ['-r', '--relations']:
86 | relids = a.split(',')
87 | elif o in ['-h', '--help']:
88 | usage()
89 | sys.exit()
90 |
91 | if not relids:
92 | usage()
93 | sys.exit(1)
94 |
95 | API='http://www.openstreetmap.org/api/0.6'
96 | gpx_exp = osm_gpx_exporter(outfile)
97 |
98 | for relid in relids:
99 | osmfile = urllib.urlopen('%s/relation/%s/full' %(API,relid))
100 | osmobj = pyosm.OSMXMLFile(osmfile)
101 | gpx_exp.append_relations(osmobj.relations.values())
102 |
103 | gpx_exp.write()
104 |
105 |
106 |
--------------------------------------------------------------------------------