source: subversion/applications/routing/pyroute/loadOsm.py @ 5311

Last change on this file since 5311 was 5311, checked in by ojw, 12 years ago

Specify the form of transport (cycle, car, foot, horse, etc) when asking
for a route

File size: 4.7 KB
Line 
1#!/usr/bin/python
2#----------------------------------------------------------------
3# load OSM data file into memory
4#
5#------------------------------------------------------
6# Usage:
7#   data = LoadOsm(filename)
8# or:
9#   loadOsm.py filename.osm
10#------------------------------------------------------
11# Copyright 2007, Oliver White
12#
13# This program is free software: you can redistribute it and/or modify
14# it under the terms of the GNU General Public License as published by
15# the Free Software Foundation, either version 3 of the License, or
16# (at your option) any later version.
17#
18# This program is distributed in the hope that it will be useful,
19# but WITHOUT ANY WARRANTY; without even the implied warranty of
20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21# GNU General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License
24# along with this program.  If not, see <http://www.gnu.org/licenses/>.
25#------------------------------------------------------
26# Changelog:
27#  2007-11-04  OJW  Modified from pyroute.py
28#  2007-11-05  OJW  Multiple forms of transport
29#------------------------------------------------------
30import sys
31from xml.sax import make_parser, handler
32
33class LoadOsm(handler.ContentHandler):
34  """Parse an OSM file looking for routing information, and do routing with it"""
35  def __init__(self, filename, storeMap = 0):
36    """Initialise an OSM-file parser"""
37    self.routing = {}
38    self.routeTypes = ('cycle','car','train','foot','horse')
39    for routeType in self.routeTypes:
40      self.routing[routeType] = {}
41    self.nodes = {}
42    self.ways = []
43    self.storeMap = storeMap
44    parser = make_parser()
45    parser.setContentHandler(self)
46    parser.parse(filename)
47  def report(self):
48    """Display some info about the loaded data"""
49    report = "Loaded %d nodes,\n" % len(self.nodes.keys())
50    report = report + "%d ways, and...\n" % len(self.ways)
51    for routeType in self.routeTypes:
52      report = report + " %d %s routes\n" % ( \
53        len(self.routing[routeType].keys()),
54        routeType)
55    return(report)
56
57  def startElement(self, name, attrs):
58    """Handle XML elements"""
59    if name in('node','way','relation'):
60      self.tags = {}
61      self.waynodes = []
62      if name == 'node':
63        """Nodes need to be stored"""
64        id = int(attrs.get('id'))
65        lat = float(attrs.get('lat'))
66        lon = float(attrs.get('lon'))
67        self.nodes[id] = (lat,lon)
68    elif name == 'nd':
69      """Nodes within a way -- add them to a list"""
70      self.waynodes.append(int(attrs.get('ref')))
71    elif name == 'tag':
72      """Tags - store them in a hash"""
73      k,v = (attrs.get('k'), attrs.get('v'))
74      if not k in ('created_by'):
75        self.tags[k] = v
76 
77  def endElement(self, name):
78    """Handle ways in the OSM data"""
79    if name == 'way':
80      highway = self.tags.get('highway', '')
81      railway = self.tags.get('railway', '')
82      oneway = self.tags.get('oneway', '')
83      reversible = not oneway in('yes','true','1')
84   
85      # Calculate what vehicles can use this route
86      access = {}
87      access['cycle'] = highway in ('primary','secondary','tertiary','unclassified','minor','cycleway','residential', 'service')
88      access['car'] = highway in ('motorway','trunk','primary','secondary','tertiary','unclassified','minor','residential', 'service')
89      access['train'] = railway in('rail','light_rail','subway')
90      access['foot'] = access['cycle'] or highway in('footway','steps')
91      access['horse'] = highway in ('track','unclassified','bridleway')
92     
93      # Store routing information
94      last = -1
95      for i in self.waynodes:
96        if last != -1:
97          #print "%d -> %d & v.v." % (last, i)
98          for routeType in self.routeTypes:
99            if(access[routeType]):
100              self.addLink(last, i, routeType)
101              if reversible:
102                self.addLink(i, last, routeType)
103        last = i
104     
105      # Store map information
106      if(self.storeMap):
107        wayType = self.WayType(self.tags)
108        if(wayType):
109          self.ways.append({ \
110            't':wayType,
111            'n':self.waynodes})
112
113  def WayType(self, tags):
114    # Look for a variety of tags (priority order - first one found is used)
115    for key in ('highway','railway','waterway','natural'):
116      value = tags.get('highway', '')
117      if value:
118        return(value)
119    return('')
120   
121  def addLink(self,fr,to, routeType):
122    """Add a routeable edge to the scenario"""
123    try:
124      if to in self.routing[routeType][fr]:
125        return
126      self.routing[routeType][fr].append(to)
127    except KeyError:
128      self.routing[routeType][fr] = [to]
129     
130# Parse the supplied OSM file
131if __name__ == "__main__":
132  print "Loading data..."
133  data = LoadOsm(sys.argv[1], True)
134  print data.report()
Note: See TracBrowser for help on using the repository browser.