SUMO - Simulation of Urban MObility
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
NIImporter_OpenStreetMap.cpp
Go to the documentation of this file.
1 /****************************************************************************/
10 // Importer for networks stored in OpenStreetMap format
11 /****************************************************************************/
12 // SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
13 // Copyright (C) 2001-2014 DLR (http://www.dlr.de/) and contributors
14 /****************************************************************************/
15 //
16 // This file is part of SUMO.
17 // SUMO is free software: you can redistribute it and/or modify
18 // it under the terms of the GNU General Public License as published by
19 // the Free Software Foundation, either version 3 of the License, or
20 // (at your option) any later version.
21 //
22 /****************************************************************************/
23 
24 
25 // ===========================================================================
26 // included modules
27 // ===========================================================================
28 #ifdef _MSC_VER
29 #include <windows_config.h>
30 #else
31 #include <config.h>
32 #endif
33 #include <algorithm>
34 #include <set>
35 #include <functional>
36 #include <sstream>
37 #include <limits>
41 #include <utils/common/ToString.h>
45 #include <netbuild/NBEdge.h>
46 #include <netbuild/NBEdgeCont.h>
47 #include <netbuild/NBNode.h>
48 #include <netbuild/NBNodeCont.h>
49 #include <netbuild/NBNetBuilder.h>
50 #include <netbuild/NBOwnTLDef.h>
56 #include <utils/xml/XMLSubSys.h>
57 #include "NILoader.h"
59 
60 #ifdef CHECK_MEMORY_LEAKS
61 #include <foreign/nvwa/debug_new.h>
62 #endif // CHECK_MEMORY_LEAKS
63 
64 // ---------------------------------------------------------------------------
65 // static members
66 // ---------------------------------------------------------------------------
68 
70 
71 // ===========================================================================
72 // Private classes
73 // ===========================================================================
74 
78 public:
79  bool operator()(const Edge* e1, const Edge* e2) const {
80  if (e1->myHighWayType != e2->myHighWayType) {
81  return e1->myHighWayType > e2->myHighWayType;
82  }
83  if (e1->myNoLanes != e2->myNoLanes) {
84  return e1->myNoLanes > e2->myNoLanes;
85  }
86  if (e1->myNoLanesForward != e2->myNoLanesForward) {
87  return e1->myNoLanesForward > e2->myNoLanesForward;
88  }
89  if (e1->myMaxSpeed != e2->myMaxSpeed) {
90  return e1->myMaxSpeed > e2->myMaxSpeed;
91  }
92  if (e1->myIsOneWay != e2->myIsOneWay) {
93  return e1->myIsOneWay > e2->myIsOneWay;
94  }
95  return e1->myCurrentNodes > e2->myCurrentNodes;
96  }
97 };
98 
99 // ===========================================================================
100 // method definitions
101 // ===========================================================================
102 // ---------------------------------------------------------------------------
103 // static methods
104 // ---------------------------------------------------------------------------
106 
107 
108 void
110  NIImporter_OpenStreetMap importer;
111  importer.load(oc, nb);
112 }
113 
114 
116 
117 
119  // delete nodes
120  for (std::set<NIOSMNode*, CompareNodes>::iterator i = myUniqueNodes.begin(); i != myUniqueNodes.end(); i++) {
121  delete *i;
122  }
123  // delete edges
124  for (std::map<SUMOLong, Edge*>::iterator i = myEdges.begin(); i != myEdges.end(); ++i) {
125  delete(*i).second;
126  }
127 }
128 
129 
130 void
132  // check whether the option is set (properly)
133  if (!oc.isSet("osm-files")) {
134  return;
135  }
136  // preset types
137  // for highways
138  NBTypeCont& tc = nb.getTypeCont();
139  SUMOReal const WIDTH = NBEdge::UNSPECIFIED_WIDTH;
140  tc.insert("highway.motorway", 3, (SUMOReal)(160. / 3.6), 13, WIDTH, SVC_IGNORING, true);
141  tc.insert("highway.motorway_link", 1, (SUMOReal)(80. / 3.6), 12, WIDTH, SVC_IGNORING, true);
142  tc.insert("highway.trunk", 2, (SUMOReal)(100. / 3.6), 11, WIDTH); // !!! 130km/h?
143  tc.insert("highway.trunk_link", 1, (SUMOReal)(80. / 3.6), 10, WIDTH);
144  tc.insert("highway.primary", 2, (SUMOReal)(100. / 3.6), 9, WIDTH);
145  tc.insert("highway.primary_link", 1, (SUMOReal)(80. / 3.6), 8, WIDTH);
146  tc.insert("highway.secondary", 2, (SUMOReal)(100. / 3.6), 7, WIDTH);
147  tc.insert("highway.secondary_link", 1, (SUMOReal)(80. / 3.6), 6, WIDTH);
148  tc.insert("highway.tertiary", 1, (SUMOReal)(80. / 3.6), 6, WIDTH);
149  tc.insert("highway.tertiary_link", 1, (SUMOReal)(80. / 3.6), 5, WIDTH);
150  tc.insert("highway.unclassified", 1, (SUMOReal)(80. / 3.6), 5, WIDTH);
151  tc.insert("highway.residential", 1, (SUMOReal)(50. / 3.6), 4, WIDTH); // actually, maybe one lane for parking would be nice...
152  tc.insert("highway.living_street", 1, (SUMOReal)(10. / 3.6), 3, WIDTH);
153  tc.insert("highway.service", 1, (SUMOReal)(20. / 3.6), 2, WIDTH, SVC_DELIVERY);
154  tc.insert("highway.track", 1, (SUMOReal)(20. / 3.6), 1, WIDTH);
155  tc.insert("highway.services", 1, (SUMOReal)(30. / 3.6), 1, WIDTH); // service area i.e. on a motorway
156  tc.insert("highway.unsurfaced", 1, (SUMOReal)(30. / 3.6), 1, WIDTH); // unofficial value, used outside germany
157 
158  tc.insert("highway.pedestrian", 1, (SUMOReal)(30. / 3.6), 1, WIDTH, SVC_PEDESTRIAN, true);
159  tc.insert("highway.path", 1, (SUMOReal)(10. / 3.6), 1, WIDTH, SVC_PEDESTRIAN, true);
160  tc.insert("highway.bridleway", 1, (SUMOReal)(10. / 3.6), 1, WIDTH, SVC_BICYCLE); // no horse stuff
161  tc.insert("highway.cycleway", 1, (SUMOReal)(20. / 3.6), 1, WIDTH, SVC_BICYCLE);
162  tc.insert("highway.footway", 1, (SUMOReal)(10. / 3.6), 1, WIDTH, SVC_PEDESTRIAN, true);
163  tc.insert("highway.step", 1, (SUMOReal)(5. / 3.6), 1, WIDTH, SVC_PEDESTRIAN, true); // additional
164  tc.insert("highway.steps", 1, (SUMOReal)(5. / 3.6), 1, WIDTH, SVC_PEDESTRIAN, true); // :-) do not run too fast
165  tc.insert("highway.stairs", 1, (SUMOReal)(5. / 3.6), 1, WIDTH, SVC_PEDESTRIAN, true); // additional
166  tc.insert("highway.bus_guideway", 1, (SUMOReal)(30. / 3.6), 1, WIDTH, SVC_BUS);
167  tc.insert("highway.raceway", 2, (SUMOReal)(300. / 3.6), 14, WIDTH, SVC_VIP);
168  tc.insert("highway.ford", 1, (SUMOReal)(10. / 3.6), 1, WIDTH, SVC_ARMY);
169 
170  // for railways
171  const bool oneWay = oc.getBool("osm.railway.oneway-default");
172  tc.insert("railway.rail", 1, (SUMOReal)(300. / 3.6), 15, WIDTH, SVC_RAIL, oneWay);
173  tc.insert("railway.tram", 1, (SUMOReal)(100. / 3.6), 15, WIDTH, SVC_TRAM, oneWay);
174  tc.insert("railway.light_rail", 1, (SUMOReal)(100. / 3.6), 15, WIDTH, SVC_RAIL_URBAN, oneWay); // might also correspond to higher standard trams
175  tc.insert("railway.subway", 1, (SUMOReal)(100. / 3.6), 15, WIDTH, SVC_RAIL_URBAN, oneWay);
176  tc.insert("railway.preserved", 1, (SUMOReal)(100. / 3.6), 15, WIDTH, SVC_RAIL, oneWay);
177 
178 
179  /* Parse file(s)
180  * Each file is parsed twice: first for nodes, second for edges. */
181  std::vector<std::string> files = oc.getStringVector("osm-files");
182  // load nodes, first
183  NodesHandler nodesHandler(myOSMNodes, myUniqueNodes, oc.getBool("osm.elevation"));
184  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
185  // nodes
186  if (!FileHelpers::isReadable(*file)) {
187  WRITE_ERROR("Could not open osm-file '" + *file + "'.");
188  return;
189  }
190  nodesHandler.setFileName(*file);
191  PROGRESS_BEGIN_MESSAGE("Parsing nodes from osm-file '" + *file + "'");
192  if (!XMLSubSys::runParser(nodesHandler, *file)) {
193  return;
194  }
196  }
197  // load edges, then
198  EdgesHandler edgesHandler(myOSMNodes, myEdges);
199  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
200  // edges
201  edgesHandler.setFileName(*file);
202  PROGRESS_BEGIN_MESSAGE("Parsing edges from osm-file '" + *file + "'");
203  XMLSubSys::runParser(edgesHandler, *file);
205  }
206 
207  /* Remove duplicate edges with the same shape and attributes */
208  if (!oc.getBool("osm.skip-duplicates-check")) {
209  PROGRESS_BEGIN_MESSAGE("Removing duplicate edges");
210  if (myEdges.size() > 1) {
211  std::set<const Edge*, CompareEdges> dupsFinder;
212  for (std::map<SUMOLong, Edge*>::iterator it = myEdges.begin(); it != myEdges.end();) {
213  if (dupsFinder.count(it->second) > 0) {
214  WRITE_MESSAGE("Found duplicate edges. Removing " + toString(it->first));
215  delete it->second;
216  myEdges.erase(it++);
217  } else {
218  dupsFinder.insert(it->second);
219  it++;
220  }
221  }
222  }
224  }
225 
226  /* Mark which nodes are used (by edges or traffic lights).
227  * This is necessary to detect which OpenStreetMap nodes are for
228  * geometry only */
229  std::map<SUMOLong, int> nodeUsage;
230  // Mark which nodes are used by edges (begin and end)
231  for (std::map<SUMOLong, Edge*>::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) {
232  Edge* e = (*i).second;
233  assert(e->myCurrentIsRoad);
234  for (std::vector<SUMOLong>::const_iterator j = e->myCurrentNodes.begin(); j != e->myCurrentNodes.end(); ++j) {
235  if (nodeUsage.find(*j) == nodeUsage.end()) {
236  nodeUsage[*j] = 0;
237  }
238  nodeUsage[*j] = nodeUsage[*j] + 1;
239  }
240  }
241  // Mark which nodes are used by traffic lights
242  for (std::map<SUMOLong, NIOSMNode*>::const_iterator nodesIt = myOSMNodes.begin(); nodesIt != myOSMNodes.end(); ++nodesIt) {
243  if (nodesIt->second->tlsControlled) {
244  // If the key is not found in the map, the value is automatically
245  // initialized with 0.
246  nodeUsage[nodesIt->first] += 1;
247  }
248  }
249  /* Instantiate edges
250  * Only those nodes in the middle of an edge which are used by more than
251  * one edge are instantiated. Other nodes are considered as geometry nodes. */
252  NBNodeCont& nc = nb.getNodeCont();
254  for (std::map<SUMOLong, Edge*>::iterator i = myEdges.begin(); i != myEdges.end(); ++i) {
255  Edge* e = (*i).second;
256  assert(e->myCurrentIsRoad);
257  if (e->myCurrentNodes.size() < 2) {
258  WRITE_WARNING("Discarding way '" + toString(e->id) + "' because it has only " +
259  toString(e->myCurrentNodes.size()) + " node(s)");
260  continue;
261  }
262  // build nodes;
263  // - the from- and to-nodes must be built in any case
264  // - the in-between nodes are only built if more than one edge references them
265  NBNode* currentFrom = insertNodeChecking(*e->myCurrentNodes.begin(), nc, tlsc);
266  NBNode* last = insertNodeChecking(*(e->myCurrentNodes.end() - 1), nc, tlsc);
267  int running = 0;
268  std::vector<SUMOLong> passed;
269  for (std::vector<SUMOLong>::iterator j = e->myCurrentNodes.begin(); j != e->myCurrentNodes.end(); ++j) {
270  passed.push_back(*j);
271  if (nodeUsage[*j] > 1 && j != e->myCurrentNodes.end() - 1 && j != e->myCurrentNodes.begin()) {
272  NBNode* currentTo = insertNodeChecking(*j, nc, tlsc);
273  running = insertEdge(e, running, currentFrom, currentTo, passed, nb);
274  currentFrom = currentTo;
275  passed.clear();
276  }
277  }
278  if (running == 0) {
279  running = -1;
280  }
281  insertEdge(e, running, currentFrom, last, passed, nb);
282  }
283 
284  // load relations (after edges are built since we want to apply
285  // turn-restrictions directly to NBEdges)
286  RelationHandler relationHandler(myOSMNodes, myEdges);
287  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
288  // relations
289  relationHandler.setFileName(*file);
290  PROGRESS_BEGIN_MESSAGE("Parsing relations from osm-file '" + *file + "'");
291  XMLSubSys::runParser(relationHandler, *file);
293  }
294 }
295 
296 
297 NBNode*
299  NBNode* node = nc.retrieve(toString(id));
300  if (node == 0) {
301  NIOSMNode* n = myOSMNodes.find(id)->second;
302  Position pos(n->lon, n->lat, n->ele);
303  if (!NBNetBuilder::transformCoordinates(pos, true)) {
304  WRITE_ERROR("Unable to project coordinates for node " + toString(id) + ".");
305  return 0;
306  }
307  node = new NBNode(toString(id), pos);
308  if (!nc.insert(node)) {
309  WRITE_ERROR("Could not insert node '" + toString(id) + "').");
310  delete node;
311  return 0;
312  }
313  n->node = node;
314  if (n->tlsControlled) {
315  // ok, this node is a traffic light node where no other nodes
316  // participate
317  // @note: The OSM-community has not settled on a schema for differentiating between fixed and actuated lights
319  NBOwnTLDef* tlDef = new NBOwnTLDef(toString(id), node, 0, type);
320  if (!tlsc.insert(tlDef)) {
321  // actually, nothing should fail here
322  delete tlDef;
323  throw ProcessError("Could not allocate tls '" + toString(id) + "'.");
324  }
325  }
326  }
327  return node;
328 }
329 
330 
331 int
333  const std::vector<SUMOLong>& passed, NBNetBuilder& nb) {
334  NBNodeCont& nc = nb.getNodeCont();
335  NBEdgeCont& ec = nb.getEdgeCont();
336  NBTypeCont& tc = nb.getTypeCont();
338  // patch the id
339  std::string id = toString(e->id);
340  if (from == 0 || to == 0) {
341  WRITE_ERROR("Discarding edge " + id + " because the nodes could not be built.");
342  return index;
343  }
344  if (index >= 0) {
345  id = id + "#" + toString(index);
346  } else {
347  index = 0;
348  }
349  if (from == to) {
350  // in the special case of a looped way split again using passed
351  assert(passed.size() >= 2);
352  std::vector<SUMOLong> geom(passed);
353  geom.pop_back(); // remove to-node
354  NBNode* intermediate = insertNodeChecking(geom.back(), nc, tlsc);
355  index = insertEdge(e, index, from, intermediate, geom, nb);
356  geom.clear();
357  return insertEdge(e, index, intermediate, to, geom, nb);
358  }
359  const int newIndex = index + 1;
360 
361  // convert the shape
362  PositionVector shape;
363  shape.push_back(from->getPosition());
364  for (std::vector<SUMOLong>::const_iterator i = passed.begin(); i != passed.end(); ++i) {
365  NIOSMNode* n = myOSMNodes.find(*i)->second;
366  Position pos(n->lon, n->lat, n->ele);
367  if (!NBNetBuilder::transformCoordinates(pos, true)) {
368  WRITE_ERROR("Unable to project coordinates for edge " + id + ".");
369  }
370  shape.push_back_noDoublePos(pos);
371  }
372  shape.push_back_noDoublePos(to->getPosition());
373 
374  std::string type = e->myHighWayType;
375  if (!tc.knows(type)) {
376  if (myUnusableTypes.count(type) > 0) {
377  return newIndex;
378  } else if (myKnownCompoundTypes.count(type) > 0) {
379  type = myKnownCompoundTypes[type];
380  } else {
381  // this edge has a type which does not yet exist in the TypeContainer
383  std::vector<std::string> types;
384  while (tok.hasNext()) {
385  std::string t = tok.next();
386  if (tc.knows(t)) {
387  if (std::find(types.begin(), types.end(), t) == types.end()) {
388  types.push_back(t);
389  }
390  } else if (tok.size() > 1) {
391  WRITE_WARNING("Discarding unknown compound \"" + t + "\" in type \"" + type + "\" (first occurence for edge \"" + id + "\").");
392  }
393  }
394  if (types.size() == 0) {
395  WRITE_WARNING("Discarding unusable type \"" + type + "\" (first occurence for edge \"" + id + "\").");
396  myUnusableTypes.insert(type);
397  return newIndex;
398  } else {
399  const std::string newType = joinToString(types, "|");
400  if (tc.knows(newType)) {
401  myKnownCompoundTypes[type] = newType;
402  type = newType;
403  } else if (myKnownCompoundTypes.count(newType) > 0) {
404  type = myKnownCompoundTypes[newType];
405  } else {
406  // build a new type by merging all values
407  int numLanes = 0;
408  SUMOReal maxSpeed = 0;
409  int prio = 0;
411  SUMOReal sidewalkWidth = NBEdge::UNSPECIFIED_WIDTH;
412  bool defaultIsOneWay = false;
413  SVCPermissions permissions = 0;
414  for (std::vector<std::string>::iterator it = types.begin(); it != types.end(); it++) {
415  numLanes = MAX2(numLanes, tc.getNumLanes(*it));
416  maxSpeed = MAX2(maxSpeed, tc.getSpeed(*it));
417  prio = MAX2(prio, tc.getPriority(*it));
418  defaultIsOneWay &= tc.getIsOneWay(*it);
419  permissions |= tc.getPermissions(*it);
420  width = MAX2(width, tc.getWidth(*it));
421  sidewalkWidth = MAX2(sidewalkWidth, tc.getSidewalkWidth(*it));
422  }
423  if (width != NBEdge::UNSPECIFIED_WIDTH) {
424  width = MAX2(width, SUMO_const_laneWidth);
425  }
426  WRITE_MESSAGE("Adding new type \"" + type + "\" (first occurence for edge \"" + id + "\").");
427  tc.insert(newType, numLanes, maxSpeed, prio, permissions, width, defaultIsOneWay, sidewalkWidth);
428  myKnownCompoundTypes[type] = newType;
429  type = newType;
430  }
431  }
432  }
433  }
434 
435  // otherwise it is not an edge and will be ignored
436  bool ok = true;
437  int numLanesForward = tc.getNumLanes(type);
438  int numLanesBackward = tc.getNumLanes(type);
439  SUMOReal speed = tc.getSpeed(type);
440  bool defaultsToOneWay = tc.getIsOneWay(type);
441  SVCPermissions permissions = tc.getPermissions(type);
442  const bool addSidewalk = (tc.getSidewalkWidth(type) != NBEdge::UNSPECIFIED_WIDTH);
443  // check directions
444  bool addForward = true;
445  bool addBackward = true;
446  if (e->myIsOneWay == "true" || e->myIsOneWay == "yes" || e->myIsOneWay == "1" || (defaultsToOneWay && e->myIsOneWay != "no" && e->myIsOneWay != "false" && e->myIsOneWay != "0")) {
447  addBackward = false;
448  }
449  if (e->myIsOneWay == "-1" || e->myIsOneWay == "reverse") {
450  // one-way in reversed direction of way
451  addForward = false;
452  addBackward = true;
453  }
454  if (e->myIsOneWay != "" && e->myIsOneWay != "false" && e->myIsOneWay != "no" && e->myIsOneWay != "true" && e->myIsOneWay != "yes" && e->myIsOneWay != "-1" && e->myIsOneWay != "1" && e->myIsOneWay != "reverse") {
455  WRITE_WARNING("New value for oneway found: " + e->myIsOneWay);
456  }
457  // if we had been able to extract the number of lanes, override the highway type default
458  if (e->myNoLanes > 0) {
459  if (addForward && !addBackward) {
460  numLanesForward = e->myNoLanes;
461  } else if (!addForward && addBackward) {
462  numLanesBackward = e->myNoLanes;
463  } else {
464  if (e->myNoLanesForward > 0) {
465  numLanesForward = e->myNoLanesForward;
466  } else if (e->myNoLanesForward < 0) {
467  numLanesForward = e->myNoLanes + e->myNoLanesForward;
468  } else {
469  numLanesForward = (int)std::ceil(e->myNoLanes / 2.0);
470  }
471  numLanesBackward = e->myNoLanes - numLanesForward;
472  // sometimes ways are tagged according to their physical width of a single
473  // lane but they are intended for traffic in both directions
474  numLanesForward = MAX2(1, numLanesForward);
475  numLanesBackward = MAX2(1, numLanesBackward);
476  }
477  } else if (e->myNoLanes == 0) {
478  WRITE_WARNING("Skipping edge '" + id + "' because it has zero lanes.");
479  ok = false;
480  }
481  // if we had been able to extract the maximum speed, override the type's default
482  if (e->myMaxSpeed != MAXSPEED_UNGIVEN) {
483  speed = (SUMOReal)(e->myMaxSpeed / 3.6);
484  }
485  if (speed <= 0) {
486  WRITE_WARNING("Skipping edge '" + id + "' because it has speed " + toString(speed));
487  ok = false;
488  }
489  if (ok) {
491  if (addForward) {
492  assert(numLanesForward > 0);
493  NBEdge* nbe = new NBEdge(StringUtils::escapeXML(id), from, to, type, speed, numLanesForward, tc.getPriority(type),
494  tc.getWidth(type), NBEdge::UNSPECIFIED_OFFSET, shape, StringUtils::escapeXML(e->streetName), lsf, true);
495  nbe->setPermissions(permissions);
496  if (addSidewalk) {
497  nbe->addSidewalk(tc.getSidewalkWidth(type));
498  }
499  if (!ec.insert(nbe)) {
500  delete nbe;
501  throw ProcessError("Could not add edge '" + id + "'.");
502  }
503  id = "-" + id;
504  }
505  if (addBackward) {
506  assert(numLanesBackward > 0);
507  NBEdge* nbe = new NBEdge(StringUtils::escapeXML(id), to, from, type, speed, numLanesBackward, tc.getPriority(type),
509  nbe->setPermissions(permissions);
510  if (addSidewalk) {
511  nbe->addSidewalk(tc.getSidewalkWidth(type));
512  }
513  if (!ec.insert(nbe)) {
514  delete nbe;
515  throw ProcessError("Could not add edge " + id + "'.");
516  }
517  }
518  }
519  return newIndex;
520 }
521 
522 
523 // ---------------------------------------------------------------------------
524 // definitions of NIImporter_OpenStreetMap::NodesHandler-methods
525 // ---------------------------------------------------------------------------
527  std::map<SUMOLong, NIOSMNode*>& toFill,
528  std::set<NIOSMNode*, CompareNodes>& uniqueNodes,
529  bool importElevation) :
530  SUMOSAXHandler("osm - file"),
531  myToFill(toFill),
532  myLastNodeID(-1),
533  myIsInValidNodeTag(false),
534  myHierarchyLevel(0),
535  myUniqueNodes(uniqueNodes),
536  myImportElevation(importElevation)
537 { }
538 
539 
541 
542 
543 void
545  ++myHierarchyLevel;
546  if (element == SUMO_TAG_NODE) {
547  bool ok = true;
548  if (myHierarchyLevel != 2) {
549  WRITE_ERROR("Node element on wrong XML hierarchy level (id='" + toString(attrs.get<SUMOLong>(SUMO_ATTR_ID, 0, ok)) + "', level='" + toString(myHierarchyLevel) + "').");
550  return;
551  }
552  SUMOLong id = attrs.get<SUMOLong>(SUMO_ATTR_ID, 0, ok);
553  std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : "";
554  if (action == "delete") {
555  return;
556  }
557  if (!ok) {
558  return;
559  }
560  myLastNodeID = -1;
561  if (myToFill.find(id) == myToFill.end()) {
562  myLastNodeID = id;
563  // assume we are loading multiple files...
564  // ... so we won't report duplicate nodes
565  bool ok = true;
566  double tlat, tlon;
567  std::istringstream lon(attrs.get<std::string>(SUMO_ATTR_LON, toString(id).c_str(), ok));
568  if (!ok) {
569  return;
570  }
571  lon >> tlon;
572  if (lon.fail()) {
573  WRITE_ERROR("Node's '" + toString(id) + "' lon information is not numeric.");
574  return;
575  }
576  std::istringstream lat(attrs.get<std::string>(SUMO_ATTR_LAT, toString(id).c_str(), ok));
577  if (!ok) {
578  return;
579  }
580  lat >> tlat;
581  if (lat.fail()) {
582  WRITE_ERROR("Node's '" + toString(id) + "' lat information is not numeric.");
583  return;
584  }
585  NIOSMNode* toAdd = new NIOSMNode(id, tlon, tlat);
586  myIsInValidNodeTag = true;
587 
588  std::set<NIOSMNode*, CompareNodes>::iterator similarNode = myUniqueNodes.find(toAdd);
589  if (similarNode == myUniqueNodes.end()) {
590  myUniqueNodes.insert(toAdd);
591  } else {
592  delete toAdd;
593  toAdd = *similarNode;
594  WRITE_MESSAGE("Found duplicate nodes. Substituting " + toString(id) + " with " + toString(toAdd->id));
595  }
596  myToFill[id] = toAdd;
597  }
598  }
599  if (element == SUMO_TAG_TAG && myIsInValidNodeTag) {
600  if (myHierarchyLevel != 3) {
601  WRITE_ERROR("Tag element on wrong XML hierarchy level.");
602  return;
603  }
604  bool ok = true;
605  std::string key = attrs.get<std::string>(SUMO_ATTR_K, toString(myLastNodeID).c_str(), ok, false);
606  std::string value = attrs.get<std::string>(SUMO_ATTR_V, toString(myLastNodeID).c_str(), ok, false);
607  if (key == "highway" && value.find("traffic_signal") != std::string::npos) {
608  myToFill[myLastNodeID]->tlsControlled = true;
609  } else if (myImportElevation && key == "ele") {
610  try {
611  myToFill[myLastNodeID]->ele = TplConvert::_2SUMOReal(value.c_str());
612  } catch (...) {
613  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in node '" +
614  toString(myLastNodeID) + "'.");
615  }
616  }
617  }
618 }
619 
620 
621 void
623  if (element == SUMO_TAG_NODE && myHierarchyLevel == 2) {
624  myLastNodeID = -1;
625  myIsInValidNodeTag = false;
626  }
627  --myHierarchyLevel;
628 }
629 
630 
631 // ---------------------------------------------------------------------------
632 // definitions of NIImporter_OpenStreetMap::EdgesHandler-methods
633 // ---------------------------------------------------------------------------
635  const std::map<SUMOLong, NIOSMNode*>& osmNodes,
636  std::map<SUMOLong, Edge*>& toFill) :
637  SUMOSAXHandler("osm - file"),
638  myOSMNodes(osmNodes),
639  myEdgeMap(toFill) {
640  mySpeedMap["signals"] = MAXSPEED_UNGIVEN;
641  mySpeedMap["none"] = 300.;
642  mySpeedMap["no"] = 300.;
643  mySpeedMap["walk"] = 5.;
644  mySpeedMap["DE:rural"] = 100.;
645  mySpeedMap["DE:urban"] = 50.;
646  mySpeedMap["DE:living_street"] = 10.;
647 
648 }
649 
650 
652 }
653 
654 
655 void
657  const SUMOSAXAttributes& attrs) {
658  myParentElements.push_back(element);
659  // parse "way" elements
660  if (element == SUMO_TAG_WAY) {
661  bool ok = true;
662  SUMOLong id = attrs.get<SUMOLong>(SUMO_ATTR_ID, 0, ok);
663  std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : "";
664  if (action == "delete") {
665  myCurrentEdge = 0;
666  return;
667  }
668  if (!ok) {
669  myCurrentEdge = 0;
670  return;
671  }
672  myCurrentEdge = new Edge(id);
673  }
674  // parse "nd" (node) elements
675  if (element == SUMO_TAG_ND) {
676  bool ok = true;
677  SUMOLong ref = attrs.get<SUMOLong>(SUMO_ATTR_REF, 0, ok);
678  if (ok) {
679  std::map<SUMOLong, NIOSMNode*>::const_iterator node = myOSMNodes.find(ref);
680  if (node == myOSMNodes.end()) {
681  WRITE_WARNING("The referenced geometry information (ref='" + toString(ref) + "') is not known");
682  return;
683  } else {
684  ref = node->second->id; // node may have been substituted
685  if (myCurrentEdge->myCurrentNodes.size() == 0 ||
686  myCurrentEdge->myCurrentNodes.back() != ref) { // avoid consecutive duplicates
687  myCurrentEdge->myCurrentNodes.push_back(ref);
688  }
689  }
690  }
691  }
692  // parse values
693  if (element == SUMO_TAG_TAG && myParentElements.size() > 2 && myParentElements[myParentElements.size() - 2] == SUMO_TAG_WAY) {
694  if (myCurrentEdge == 0) {
695  return;
696  }
697  bool ok = true;
698  std::string key = attrs.get<std::string>(SUMO_ATTR_K, toString(myCurrentEdge->id).c_str(), ok, false);
699  std::string value = attrs.get<std::string>(SUMO_ATTR_V, toString(myCurrentEdge->id).c_str(), ok, false);
700 
701  if (key == "highway" || key == "railway") {
702  if (myCurrentEdge->myHighWayType != "") {
703  // osm-ways may be used by more than one mode (eg railway.tram + highway.residential. this is relevant for multimodal traffic)
704  // we create a new type for this kind of situation which must then be resolved in insertEdge()
705  myCurrentEdge->myHighWayType = myCurrentEdge->myHighWayType + compoundTypeSeparator + key + "." + value;
706  } else {
707  myCurrentEdge->myHighWayType = key + "." + value;
708  }
709  myCurrentEdge->myCurrentIsRoad = true;
710  } else if (key == "lanes") {
711  try {
712  myCurrentEdge->myNoLanes = TplConvert::_2int(value.c_str());
713  } catch (NumberFormatException&) {
714  // might be a list of values
715  StringTokenizer st(value, ";", true);
716  std::vector<std::string> list = st.getVector();
717  if (list.size() >= 2) {
718  int minLanes = std::numeric_limits<int>::max();
719  try {
720  for (std::vector<std::string>::iterator i = list.begin(); i != list.end(); ++i) {
721  int numLanes = TplConvert::_2int(StringUtils::prune(*i).c_str());
722  minLanes = MIN2(minLanes, numLanes);
723  }
724  myCurrentEdge->myNoLanes = minLanes;
725  WRITE_WARNING("Using minimum lane number from list (" + value + ") for edge '" + toString(myCurrentEdge->id) + "'.");
726  } catch (NumberFormatException&) {
727  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
728  toString(myCurrentEdge->id) + "'.");
729  }
730  }
731  } catch (EmptyData&) {
732  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
733  toString(myCurrentEdge->id) + "'.");
734  }
735  } else if (key == "lanes:forward") {
736  try {
737  myCurrentEdge->myNoLanesForward = TplConvert::_2int(value.c_str());
738  } catch (...) {
739  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
740  toString(myCurrentEdge->id) + "'.");
741  }
742  } else if (key == "lanes:backward") {
743  try {
744  // denote backwards count with a negative sign
745  myCurrentEdge->myNoLanesForward = -TplConvert::_2int(value.c_str());
746  } catch (...) {
747  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
748  toString(myCurrentEdge->id) + "'.");
749  }
750  } else if (key == "maxspeed") {
751  if (mySpeedMap.find(value) != mySpeedMap.end()) {
752  myCurrentEdge->myMaxSpeed = mySpeedMap[value];
753  } else {
754  SUMOReal conversion = 1; // OSM default is km/h
755  if (StringUtils::to_lower_case(value).find("km/h") != std::string::npos) {
756  value = StringUtils::prune(value.substr(0, value.find_first_not_of("0123456789")));
757  } else if (StringUtils::to_lower_case(value).find("mph") != std::string::npos) {
758  value = StringUtils::prune(value.substr(0, value.find_first_not_of("0123456789")));
759  conversion = 1.609344; // kilometers per mile
760  }
761  try {
762  myCurrentEdge->myMaxSpeed = TplConvert::_2SUMOReal(value.c_str()) * conversion;
763  } catch (...) {
764  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
765  toString(myCurrentEdge->id) + "'.");
766  }
767  }
768  } else if (key == "junction") {
769  if ((value == "roundabout") && (myCurrentEdge->myIsOneWay == "")) {
770  myCurrentEdge->myIsOneWay = "yes";
771  }
772  } else if (key == "oneway") {
773  myCurrentEdge->myIsOneWay = value;
774  } else if (key == "name") {
775  myCurrentEdge->streetName = value;
776  } else if (key == "tracks") {
777  try {
778  if (TplConvert::_2int(value.c_str()) > 1) {
779  myCurrentEdge->myIsOneWay = "false";
780  } else {
781  myCurrentEdge->myIsOneWay = "true";
782  }
783  } catch (...) {
784  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
785  toString(myCurrentEdge->id) + "'.");
786  }
787  }
788  }
789 }
790 
791 
792 void
794  myParentElements.pop_back();
795  if (element == SUMO_TAG_WAY) {
796  if (myCurrentEdge != 0 && myCurrentEdge->myCurrentIsRoad) {
797  myEdgeMap[myCurrentEdge->id] = myCurrentEdge;
798  } else {
799  delete myCurrentEdge;
800  }
801  myCurrentEdge = 0;
802  }
803 }
804 
805 
806 // ---------------------------------------------------------------------------
807 // definitions of NIImporter_OpenStreetMap::RelationHandler-methods
808 // ---------------------------------------------------------------------------
810  const std::map<SUMOLong, NIOSMNode*>& osmNodes,
811  const std::map<SUMOLong, Edge*>& osmEdges) :
812  SUMOSAXHandler("osm - file"),
813  myOSMNodes(osmNodes),
814  myOSMEdges(osmEdges) {
815  resetValues();
816 }
817 
818 
820 }
821 
822 void
824  myCurrentRelation = INVALID_ID;
825  myIsRestriction = false;
826  myFromWay = INVALID_ID;
827  myToWay = INVALID_ID;
828  myViaNode = INVALID_ID;
829  myViaWay = INVALID_ID;
830  myRestrictionType = RESTRICTION_UNKNOWN;
831 }
832 
833 void
835  const SUMOSAXAttributes& attrs) {
836  myParentElements.push_back(element);
837  // parse "way" elements
838  if (element == SUMO_TAG_RELATION) {
839  bool ok = true;
840  myCurrentRelation = attrs.get<SUMOLong>(SUMO_ATTR_ID, 0, ok);
841  std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : "";
842  if (action == "delete" || !ok) {
843  myCurrentRelation = INVALID_ID;
844  }
845  return;
846  } else if (myCurrentRelation == INVALID_ID) {
847  return;
848  }
849  // parse member elements
850  if (element == SUMO_TAG_MEMBER) {
851  bool ok = true;
852  std::string role = attrs.hasAttribute("role") ? attrs.getStringSecure("role", "") : "";
853  SUMOLong ref = attrs.get<SUMOLong>(SUMO_ATTR_REF, 0, ok);
854  if (role == "via") {
855  // u-turns for divided ways may be given with 2 via-nodes or 1 via-way
856  std::string memberType = attrs.get<std::string>(SUMO_ATTR_TYPE, 0, ok);
857  if (memberType == "way" && checkEdgeRef(ref)) {
858  myViaWay = ref;
859  } else if (memberType == "node") {
860  if (myOSMNodes.find(ref) != myOSMNodes.end()) {
861  myViaNode = ref;
862  } else {
863  WRITE_WARNING("No node found for reference '" + toString(ref) + "' in relation '" + toString(myCurrentRelation) + "'");
864  }
865  }
866  } else if (role == "from" && checkEdgeRef(ref)) {
867  myFromWay = ref;
868  } else if (role == "to" && checkEdgeRef(ref)) {
869  myToWay = ref;
870  }
871  return;
872  }
873  // parse values
874  if (element == SUMO_TAG_TAG) {
875  bool ok = true;
876  std::string key = attrs.get<std::string>(SUMO_ATTR_K, toString(myCurrentRelation).c_str(), ok, false);
877  std::string value = attrs.get<std::string>(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false);
878 
879  if (key == "type" && value == "restriction") {
880  myIsRestriction = true;
881  return;
882  }
883  if (key == "restriction") {
884  if (value.substr(0, 5) == "only_") {
885  myRestrictionType = RESTRICTION_ONLY;
886  } else if (value.substr(0, 3) == "no_") {
887  myRestrictionType = RESTRICTION_NO;
888  } else {
889  WRITE_WARNING("Found unknown restriction type '" + value + "' in relation '" + toString(myCurrentRelation) + "'");
890  }
891  return;
892  }
893  }
894 }
895 
896 
897 bool
899  if (myOSMEdges.find(ref) != myOSMEdges.end()) {
900  return true;
901  } else {
902  WRITE_WARNING("No way found for reference '" + toString(ref) + "' in relation '" + toString(myCurrentRelation) + "'");
903  return false;
904  }
905 }
906 
907 
908 void
910  myParentElements.pop_back();
911  if (element == SUMO_TAG_RELATION) {
912  if (myIsRestriction) {
913  assert(myCurrentRelation != INVALID_ID);
914  bool ok = true;
915  if (myRestrictionType == RESTRICTION_UNKNOWN) {
916  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown type.");
917  ok = false;
918  }
919  if (myFromWay == INVALID_ID) {
920  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown from-way.");
921  ok = false;
922  }
923  if (myToWay == INVALID_ID) {
924  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown to-way.");
925  ok = false;
926  }
927  if (myViaNode == INVALID_ID && myViaWay == INVALID_ID) {
928  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown via.");
929  ok = false;
930  }
931  if (ok && !applyRestriction()) {
932  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "'.");
933  }
934  }
935  // other relations might use similar subelements so reset in any case
936  resetValues();
937  }
938 }
939 
940 
941 bool
943  // since OSM ways are bidirectional we need the via to figure out which direction was meant
944  if (myViaNode != INVALID_ID) {
945  NBNode* viaNode = myOSMNodes.find(myViaNode)->second->node;
946  if (viaNode == 0) {
947  WRITE_WARNING("Via-node '" + toString(myViaNode) + "' was not instantiated");
948  return false;
949  }
950  NBEdge* from = findEdgeRef(myFromWay, viaNode->getIncomingEdges());
951  NBEdge* to = findEdgeRef(myToWay, viaNode->getOutgoingEdges());
952  if (from == 0) {
953  WRITE_WARNING("from-edge of restriction relation could not be determined");
954  return false;
955  }
956  if (to == 0) {
957  WRITE_WARNING("to-edge of restriction relation could not be determined");
958  return false;
959  }
960  if (myRestrictionType == RESTRICTION_ONLY) {
961  from->addEdge2EdgeConnection(to);
962  } else {
963  from->removeFromConnections(to, -1, -1, true);
964  }
965  } else {
966  // XXX interpreting via-ways or via-node lists not yet implemented
967  WRITE_WARNING("direction of restriction relation could not be determined");
968  return false;
969  }
970  return true;
971 }
972 
973 
974 NBEdge*
975 NIImporter_OpenStreetMap::RelationHandler::findEdgeRef(SUMOLong wayRef, const std::vector<NBEdge*>& candidates) const {
976  const std::string prefix = toString(wayRef);
977  const std::string backPrefix = "-" + prefix;
978  NBEdge* result = 0;
979  int found = 0;
980  for (EdgeVector::const_iterator it = candidates.begin(); it != candidates.end(); ++it) {
981  if (((*it)->getID().substr(0, prefix.size()) == prefix) ||
982  ((*it)->getID().substr(0, backPrefix.size()) == backPrefix)) {
983  result = *it;
984  found++;
985  }
986  }
987  if (found > 1) {
988  WRITE_WARNING("Ambigous way reference '" + prefix + "' in restriction relation");
989  result = 0;
990  }
991  return result;
992 }
993 
994 
995 /****************************************************************************/
996