SUMO - Simulation of Urban MObility
NLBuilder.cpp
Go to the documentation of this file.
1 /****************************************************************************/
9 // The main interface for loading a microsim
10 /****************************************************************************/
11 // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
12 // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors
13 /****************************************************************************/
14 //
15 // This file is part of SUMO.
16 // SUMO is free software: you can redistribute it and/or modify
17 // it under the terms of the GNU General Public License as published by
18 // the Free Software Foundation, either version 3 of the License, or
19 // (at your option) any later version.
20 //
21 /****************************************************************************/
22 
23 
24 // ===========================================================================
25 // included modules
26 // ===========================================================================
27 #ifdef _MSC_VER
28 #include <windows_config.h>
29 #else
30 #include <config.h>
31 #endif
32 
33 #include <iostream>
34 #include <vector>
35 #include <string>
36 #include <map>
37 
42 #include <utils/options/Option.h>
47 #include <utils/common/SysUtils.h>
48 #include <utils/common/ToString.h>
51 #include <utils/xml/XMLSubSys.h>
55 #include <microsim/MSNet.h>
57 #include <microsim/MSEdgeControl.h>
58 #include <microsim/MSGlobals.h>
60 #include <microsim/MSFrame.h>
63 
64 #include "NLHandler.h"
65 #include "NLEdgeControlBuilder.h"
67 #include "NLDetectorBuilder.h"
68 #include "NLTriggerBuilder.h"
69 #include "NLBuilder.h"
70 
71 #ifndef NO_TRACI
73 #endif
74 
75 // ===========================================================================
76 // method definitions
77 // ===========================================================================
78 // ---------------------------------------------------------------------------
79 // NLBuilder::EdgeFloatTimeLineRetriever_EdgeWeight - methods
80 // ---------------------------------------------------------------------------
81 void
83  double value, double begTime, double endTime) const {
84  MSEdge* edge = MSEdge::dictionary(id);
85  if (edge != 0) {
86  myNet.getWeightsStorage().addEffort(edge, begTime, endTime, value);
87  } else {
88  WRITE_ERROR("Trying to set the effort for the unknown edge '" + id + "'.");
89  }
90 }
91 
92 
93 // ---------------------------------------------------------------------------
94 // NLBuilder::EdgeFloatTimeLineRetriever_EdgeTravelTime - methods
95 // ---------------------------------------------------------------------------
96 void
98  double value, double begTime, double endTime) const {
99  MSEdge* edge = MSEdge::dictionary(id);
100  if (edge != 0) {
101  myNet.getWeightsStorage().addTravelTime(edge, begTime, endTime, value);
102  } else {
103  WRITE_ERROR("Trying to set the travel time for the unknown edge '" + id + "'.");
104  }
105 }
106 
107 
108 // ---------------------------------------------------------------------------
109 // NLBuilder - methods
110 // ---------------------------------------------------------------------------
112  MSNet& net,
115  NLDetectorBuilder& db,
116  NLHandler& xmlHandler)
117  : myOptions(oc), myEdgeBuilder(eb), myJunctionBuilder(jb),
118  myDetectorBuilder(db),
119  myNet(net), myXMLHandler(xmlHandler) {}
120 
121 
123 
124 
125 bool
127  // try to build the net
128  if (!load("net-file", true)) {
129  return false;
130  }
131  // check whether the loaded net agrees with the simulation options
132  if (myOptions.getBool("no-internal-links") && myXMLHandler.haveSeenInternalEdge()) {
133  WRITE_WARNING("Network contains internal links but option --no-internal-links is set. Vehicles will 'jump' across junctions and thus underestimate route lengths and travel times.");
134  }
135  if (myOptions.getString("lanechange.duration") != "0" && myXMLHandler.haveSeenNeighs()) {
136  throw ProcessError("Network contains explicit neigh lanes which do not work together with option --lanechange.duration.");
137  }
138  buildNet();
139  // @note on loading order constraints:
140  // - additional-files before route-files and state-files due to referencing
141  // - weight-files before additional-files since the latter might contain trips which depend on the weights
142 
143  // load weights if wished
144  if (myOptions.isSet("weight-files")) {
145  if (!myOptions.isUsableFileList("weight-files")) {
146  return false;
147  }
148  // build and prepare the weights handler
149  std::vector<SAXWeightsHandler::ToRetrieveDefinition*> retrieverDefs;
150  // travel time, first (always used)
152  retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition("traveltime", true, ttRetriever));
153  // the measure to use, then
155  std::string measure = myOptions.getString("weight-attribute");
156  if (!myOptions.isDefault("weight-attribute")) {
157  if (measure == "CO" || measure == "CO2" || measure == "HC" || measure == "PMx" || measure == "NOx" || measure == "fuel" || measure == "electricity") {
158  measure += "_perVeh";
159  }
160  retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition(measure, true, eRetriever));
161  }
162  // set up handler
163  SAXWeightsHandler handler(retrieverDefs, "");
164  // start parsing; for each file in the list
165  std::vector<std::string> files = myOptions.getStringVector("weight-files");
166  for (std::vector<std::string>::iterator i = files.begin(); i != files.end(); ++i) {
167  // report about loading when wished
168  WRITE_MESSAGE("Loading weights from '" + *i + "'...");
169  // parse the file
170  if (!XMLSubSys::runParser(handler, *i)) {
171  return false;
172  }
173  }
174  }
175  // load additional net elements (sources, detectors, ...)
176  if (myOptions.isSet("additional-files")) {
177  if (!load("additional-files")) {
178  return false;
179  }
180  // load shapes with separate handler
182  if (!ShapeHandler::loadFiles(myOptions.getStringVector("additional-files"), sh)) {
183  return false;
184  }
187  }
188  }
189  // load the previous state if wished
190  if (myOptions.isSet("load-state")) {
191  long before = SysUtils::getCurrentMillis();
192  const std::string& f = myOptions.getString("load-state");
193  PROGRESS_BEGIN_MESSAGE("Loading state from '" + f + "'");
194  MSStateHandler h(f, string2time(myOptions.getString("load-state.offset")));
195  XMLSubSys::runParser(h, f);
196  if (myOptions.isDefault("begin")) {
197  myOptions.set("begin", time2string(h.getTime()));
198  }
200  return false;
201  }
202  if (h.getTime() != string2time(myOptions.getString("begin"))) {
203  WRITE_WARNING("State was written at a different time " + time2string(h.getTime()) + " than the begin time " + myOptions.getString("begin") + "!");
204  }
205  PROGRESS_TIME_MESSAGE(before);
206  }
207  // load routes
208  if (myOptions.isSet("route-files") && string2time(myOptions.getString("route-steps")) <= 0) {
209  if (!load("route-files")) {
210  return false;
211  }
212  }
213  // optionally switch off traffic lights
214  if (myOptions.getBool("tls.all-off")) {
216  }
217  WRITE_MESSAGE("Loading done.");
218  return true;
219 }
220 
221 
222 int
225  while (state == MSNet::SIMSTATE_LOADING) {
227  oc.clear();
230  if (oc.processMetaOptions(OptionsIO::getArgC() < 2)) {
232  return 0;
233  }
234  XMLSubSys::setValidation(oc.getString("xml-validation"), oc.getString("xml-validation.net"));
235  if (!MSFrame::checkOptions()) {
236  throw ProcessError();
237  }
243  MSVehicleControl* vc = 0;
245  vc = new MEVehicleControl();
246  } else {
247  vc = new MSVehicleControl();
248  }
249  MSNet* net = new MSNet(vc, new MSEventControl(), new MSEventControl(), new MSEventControl());
250 #ifndef NO_TRACI
251  // need to init TraCI-Server before loading routes to catch VEHICLE_STATE_BUILT
252  TraCIServer::openSocket(std::map<int, TraCIServer::CmdExecutor>());
253 #endif
254 
256  NLDetectorBuilder db(*net);
257  NLJunctionControlBuilder jb(*net, db);
258  NLTriggerBuilder tb;
259  NLHandler handler("", *net, db, tb, eb, jb);
260  tb.setHandler(&handler);
261  NLBuilder builder(oc, *net, eb, jb, db, handler);
262  if (builder.build()) {
263  state = net->simulate(string2time(oc.getString("begin")), string2time(oc.getString("end")));
264  delete net;
265  } else {
266  MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
267  delete net;
268  return 1;
269  }
270  }
271  return 0;
272 }
273 
274 
275 void
277  MSEdgeControl* edges = 0;
278  MSJunctionControl* junctions = 0;
279  SUMORouteLoaderControl* routeLoaders = 0;
280  MSTLLogicControl* tlc = 0;
281  try {
282  edges = myEdgeBuilder.build();
283  junctions = myJunctionBuilder.build();
284  routeLoaders = buildRouteLoaderControl(myOptions);
287  std::vector<SUMOTime> stateDumpTimes;
288  std::vector<std::string> stateDumpFiles;
289  const std::vector<int> times = myOptions.getIntVector("save-state.times");
290  for (std::vector<int>::const_iterator i = times.begin(); i != times.end(); ++i) {
291  stateDumpTimes.push_back(TIME2STEPS(*i));
292  }
293  if (myOptions.isSet("save-state.files")) {
294  stateDumpFiles = myOptions.getStringVector("save-state.files");
295  if (stateDumpFiles.size() != stateDumpTimes.size()) {
296  WRITE_ERROR("Wrong number of state file names!");
297  }
298  } else {
299  const std::string prefix = myOptions.getString("save-state.prefix");
300  const std::string suffix = myOptions.getString("save-state.suffix");
301  for (std::vector<SUMOTime>::iterator i = stateDumpTimes.begin(); i != stateDumpTimes.end(); ++i) {
302  stateDumpFiles.push_back(prefix + "_" + time2string(*i) + suffix);
303  }
304  }
305  myNet.closeBuilding(myOptions, edges, junctions, routeLoaders, tlc, stateDumpTimes, stateDumpFiles,
310  } catch (IOError& e) {
311  delete edges;
312  delete junctions;
313  delete routeLoaders;
314  delete tlc;
315  throw ProcessError(e.what());
316  } catch (ProcessError&) {
317  delete edges;
318  delete junctions;
319  delete routeLoaders;
320  delete tlc;
321  throw;
322  }
323 }
324 
325 
326 bool
327 NLBuilder::load(const std::string& mmlWhat, const bool isNet) {
328  if (!myOptions.isUsableFileList(mmlWhat)) {
329  return false;
330  }
331  std::vector<std::string> files = myOptions.getStringVector(mmlWhat);
332  for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
333  PROGRESS_BEGIN_MESSAGE("Loading " + mmlWhat + " from '" + *fileIt + "'");
334  long before = SysUtils::getCurrentMillis();
335  if (!XMLSubSys::runParser(myXMLHandler, *fileIt, isNet)) {
336  WRITE_MESSAGE("Loading of " + mmlWhat + " failed.");
337  return false;
338  }
339  PROGRESS_TIME_MESSAGE(before);
340  }
341  return true;
342 }
343 
344 
347  // build the loaders
348  SUMORouteLoaderControl* loaders = new SUMORouteLoaderControl(string2time(oc.getString("route-steps")));
349  // check whether a list is existing
350  if (oc.isSet("route-files") && string2time(oc.getString("route-steps")) > 0) {
351  std::vector<std::string> files = oc.getStringVector("route-files");
352  for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
353  if (!FileHelpers::isReadable(*fileIt)) {
354  throw ProcessError("The route file '" + *fileIt + "' is not accessible.");
355  }
356  }
357  // open files for reading
358  for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
359  loaders->add(new SUMORouteLoader(new MSRouteHandler(*fileIt, false)));
360  }
361  }
362  return loaders;
363 }
364 
365 
366 /****************************************************************************/
void setHandler(NLHandler *handler)
Sets the parent handler to use for nested parsing.
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
Definition: MsgHandler.cpp:76
Builds detectors for microsim.
SUMOTime getTime() const
void switchOffAll()
switch all logic variants to &#39;off&#39;
static void getOptions(const bool commandLineOnly=false)
Parses the command line arguments and loads the configuration.
Definition: OptionsIO.cpp:82
Obtains edge efforts from a weights handler and stores them within the edges.
Definition: NLBuilder.h:181
void buildNet()
Closes the net building process.
Definition: NLBuilder.cpp:276
static bool isReadable(std::string path)
Checks whether the given file is readable.
Definition: FileHelpers.cpp:54
void addEdgeWeight(const std::string &id, double val, double beg, double end) const
Adds an effort for a given edge and time period.
Definition: NLBuilder.cpp:82
The main interface for loading a microsim.
Definition: NLBuilder.h:68
static void buildStreams()
Builds the streams used possibly by the simulation.
Definition: MSFrame.cpp:439
Parser and output filter for routes and vehicles state saving and loading.
static void setValidation(const std::string &validationScheme, const std::string &netValidationScheme)
Enables or disables validation.
Definition: XMLSubSys.cpp:65
static bool loadFiles(const std::vector< std::string > &files, ShapeHandler &sh)
loads all of the given files
An XML-handler for network weights.
SimulationState simulate(SUMOTime start, SUMOTime stop)
Simulates from timestep start to stop.
Definition: MSNet.cpp:304
static MTRand * getParsingRNG()
std::string time2string(SUMOTime t)
Definition: SUMOTime.cpp:60
MSNet & myNet
The network edges shall be obtained from.
Definition: NLBuilder.h:171
void add(SUMORouteLoader *loader)
add another loader
OptionsCont & myOptions
The options to get the names of the files to load and further information from.
Definition: NLBuilder.h:209
static bool dictionary(const std::string &id, MSEdge *edge)
Inserts edge into the static dictionary Returns true if the key id isn&#39;t already in the dictionary...
Definition: MSEdge.cpp:728
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
#define TIME2STEPS(x)
Definition: SUMOTime.h:66
bool isDefault(const std::string &name) const
Returns the information whether the named option has still the default value.
bool wasInformed() const
Returns the information whether any messages were added.
Definition: MsgHandler.cpp:269
static bool runParser(GenericSAXHandler &handler, const std::string &file, const bool isNet=false)
Runs the given handler on the given file; returns if everything&#39;s ok.
Definition: XMLSubSys.cpp:110
static void close()
Closes all of an applications subsystems.
void setAdditionalRestrictions()
apply additional restrictions
SimulationState
Possible states of a simulation - running or stopped with different reasons.
Definition: MSNet.h:99
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:200
The simulated network and simulation perfomer.
Definition: MSNet.h:94
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:65
Container for junctions; performs operations on all stored junctions.
static void initRandGlobal(MTRand *which=0)
Reads the given random number options and initialises the random number generator in accordance...
Definition: RandHelper.cpp:64
static void fillOptions()
Inserts options used by the simulation into the OptionsCont-singleton.
Definition: MSFrame.cpp:66
A class that stores and controls tls and switching of their programs.
NLJunctionControlBuilder & myJunctionBuilder
The junction control builder to use.
Definition: NLBuilder.h:215
A road/street connecting two junctions.
Definition: MSEdge.h:80
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
#define PROGRESS_TIME_MESSAGE(before)
Definition: MsgHandler.h:204
static int loadAndRun()
Definition: NLBuilder.cpp:223
MSEdgeControl * build()
builds the MSEdgeControl-class which holds all edges
bool lefthand() const
Definition: NLHandler.h:120
void clear()
Removes all information from the container.
bool isUsableFileList(const std::string &name) const
Checks whether the named option is usable as a file list (with at least a single file) ...
Builder of microsim-junctions and tls.
ShapeContainer & getShapeContainer()
Returns the shapes container.
Definition: MSNet.h:433
MSTLLogicControl & getTLSControl()
Returns the tls logics control.
Definition: MSNet.h:383
void addTravelTime(const MSEdge *const e, double begin, double end, double value)
Adds a travel time information for an edge and a time span.
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
bool processMetaOptions(bool missingOptions)
Checks for help and configuration output, returns whether we should exit.
Stores edges and lanes, performs moving of vehicle.
Definition: MSEdgeControl.h:74
SUMOTime string2time(const std::string &r)
Definition: SUMOTime.cpp:47
std::vector< std::string > getStringVector(const std::string &name) const
Returns the list of string-vector-value of the named option (only for Option_String) ...
#define PROGRESS_BEGIN_MESSAGE(msg)
Definition: MsgHandler.h:202
static int getArgC()
Return the number of command line arguments.
Definition: OptionsIO.h:73
MSNet & myNet
The net to fill.
Definition: NLBuilder.h:221
The class responsible for building and deletion of vehicles (gui-version)
NLBuilder(OptionsCont &oc, MSNet &net, NLEdgeControlBuilder &eb, NLJunctionControlBuilder &jb, NLDetectorBuilder &db, NLHandler &xmlHandler)
Constructor.
Definition: NLBuilder.cpp:111
double networkVersion() const
Definition: NLHandler.h:124
void closeBuilding(const OptionsCont &oc, MSEdgeControl *edges, MSJunctionControl *junctions, SUMORouteLoaderControl *routeLoaders, MSTLLogicControl *tlc, std::vector< SUMOTime > stateDumpTimes, std::vector< std::string > stateDumpFiles, bool hasInternalLinks, bool hasNeighs, bool lefthand, double version)
Closes the network&#39;s building process.
Definition: MSNet.cpp:211
The XML-Handler for network loading.
Definition: NLHandler.h:84
static bool checkOptions()
Checks the set options.
Definition: MSFrame.cpp:470
virtual bool build()
Builds and initialises the simulation.
Definition: NLBuilder.cpp:126
Complete definition about what shall be retrieved and where to store it.
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:206
bool haveSeenAdditionalSpeedRestrictions() const
Definition: NLHandler.h:116
static void openSocket(const std::map< int, CmdExecutor > &execs)
Initialises the server.
The simulation is loading.
Definition: MSNet.h:101
bool set(const std::string &name, const std::string &value)
Sets the given value for the named option.
The XML-Handler for shapes loading network loading.
Definition: NLHandler.h:64
const IntVector & getIntVector(const std::string &name) const
Returns the list of integer-value of the named option (only for Option_IntVector) ...
void inform(std::string msg, bool addType=true)
adds a new error to the list
Definition: MsgHandler.cpp:85
A storage for options typed value containers)
Definition: OptionsCont.h:99
SUMORouteLoaderControl * buildRouteLoaderControl(const OptionsCont &oc)
Builds the route loader control.
Definition: NLBuilder.cpp:346
bool haveSeenInternalEdge() const
Definition: NLHandler.h:108
bool load(const std::string &mmlWhat, const bool isNet=false)
Loads a described subpart form the given list of files.
Definition: NLBuilder.cpp:327
static MTRand * getEquipmentRNG()
Definition: MSDevice.h:91
static void setMSGlobals(OptionsCont &oc)
Sets the global microsim-options.
Definition: MSFrame.cpp:555
void addEdgeWeight(const std::string &id, double val, double beg, double end) const
Adds a travel time for a given edge and time period.
Definition: NLBuilder.cpp:97
MSEdgeControl & getEdgeControl()
Returns the edge control.
Definition: MSNet.h:353
MSJunctionControl * build() const
Builds the MSJunctionControl which holds all of the simulations junctions.
The class responsible for building and deletion of vehicles.
static long getCurrentMillis()
Returns the current time in milliseconds.
Definition: SysUtils.cpp:46
Builds trigger objects for microsim.
virtual ~NLBuilder()
Destructor.
Definition: NLBuilder.cpp:122
bool haveSeenNeighs() const
Definition: NLHandler.h:112
#define WRITE_MESSAGE(msg)
Definition: MsgHandler.h:201
static void initOutputOptions()
Definition: MsgHandler.cpp:193
MSTLLogicControl * buildTLLogics()
Returns the built tls-logic control.
static bool gUseMesoSim
Definition: MSGlobals.h:98
NLDetectorBuilder & myDetectorBuilder
The detector control builder to use.
Definition: NLBuilder.h:218
Stores time-dependant events and executes them at the proper time.
NLHandler & myXMLHandler
The handler used to parse the net.
Definition: NLBuilder.h:224
Parser and container for routes during their loading.
Interface for building edges.
MSEdgeWeightsStorage & getWeightsStorage()
Returns the net&#39;s internal edge travel times/efforts container.
Definition: MSNet.cpp:747
void addEffort(const MSEdge *const e, double begin, double end, double value)
Adds an effort information for an edge and a time span.
NLEdgeControlBuilder & myEdgeBuilder
The edge control builder to use.
Definition: NLBuilder.h:212