SUMO - Simulation of Urban MObility
NLBuilder.cpp
Go to the documentation of this file.
1 /****************************************************************************/
2 // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
3 // Copyright (C) 2001-2017 German Aerospace Center (DLR) and others.
4 /****************************************************************************/
5 //
6 // This program and the accompanying materials
7 // are made available under the terms of the Eclipse Public License v2.0
8 // which accompanies this distribution, and is available at
9 // http://www.eclipse.org/legal/epl-v20.html
10 //
11 /****************************************************************************/
19 // The main interface for loading a microsim
20 /****************************************************************************/
21 
22 
23 // ===========================================================================
24 // included modules
25 // ===========================================================================
26 #ifdef _MSC_VER
27 #include <windows_config.h>
28 #else
29 #include <config.h>
30 #endif
31 
32 #include <iostream>
33 #include <vector>
34 #include <string>
35 #include <map>
36 
41 #include <utils/options/Option.h>
46 #include <utils/common/SysUtils.h>
47 #include <utils/common/ToString.h>
50 #include <utils/xml/XMLSubSys.h>
54 #include <microsim/MSNet.h>
56 #include <microsim/MSEdgeControl.h>
57 #include <microsim/MSGlobals.h>
59 #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  // - additional-files before weight-files since the latter might contain intermodal edge data and the intermodal net depends on the stops and public transport from the additionals
142 
143  // load additional net elements (sources, detectors, ...)
144  if (myOptions.isSet("additional-files")) {
145  if (!load("additional-files")) {
146  return false;
147  }
148  // load shapes with separate handler
150  if (!ShapeHandler::loadFiles(myOptions.getStringVector("additional-files"), sh)) {
151  return false;
152  }
155  }
156  }
157  // load weights if wished
158  if (myOptions.isSet("weight-files")) {
159  if (!myOptions.isUsableFileList("weight-files")) {
160  return false;
161  }
162  // build and prepare the weights handler
163  std::vector<SAXWeightsHandler::ToRetrieveDefinition*> retrieverDefs;
164  // travel time, first (always used)
166  retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition("traveltime", true, ttRetriever));
167  // the measure to use, then
169  std::string measure = myOptions.getString("weight-attribute");
170  if (!myOptions.isDefault("weight-attribute")) {
171  if (measure == "CO" || measure == "CO2" || measure == "HC" || measure == "PMx" || measure == "NOx" || measure == "fuel" || measure == "electricity") {
172  measure += "_perVeh";
173  }
174  retrieverDefs.push_back(new SAXWeightsHandler::ToRetrieveDefinition(measure, true, eRetriever));
175  }
176  // set up handler
177  SAXWeightsHandler handler(retrieverDefs, "");
178  // start parsing; for each file in the list
179  std::vector<std::string> files = myOptions.getStringVector("weight-files");
180  for (std::vector<std::string>::iterator i = files.begin(); i != files.end(); ++i) {
181  // report about loading when wished
182  WRITE_MESSAGE("Loading weights from '" + *i + "'...");
183  // parse the file
184  if (!XMLSubSys::runParser(handler, *i)) {
185  return false;
186  }
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  if (TraCIServer::getInstance() != 0) {
200  }
201  }
203  return false;
204  }
205  if (h.getTime() != string2time(myOptions.getString("begin"))) {
206  WRITE_WARNING("State was written at a different time " + time2string(h.getTime()) + " than the begin time " + myOptions.getString("begin") + "!");
207  }
208  PROGRESS_TIME_MESSAGE(before);
209  }
210  // load routes
211  if (myOptions.isSet("route-files") && string2time(myOptions.getString("route-steps")) <= 0) {
212  if (!load("route-files")) {
213  return false;
214  }
215  }
216  // optionally switch off traffic lights
217  if (myOptions.getBool("tls.all-off")) {
219  }
220  WRITE_MESSAGE("Loading done.");
221  return true;
222 }
223 
224 
225 MSNet*
228  oc.clear();
231  if (oc.processMetaOptions(OptionsIO::getArgC() < 2)) {
233  return nullptr;
234  }
235  XMLSubSys::setValidation(oc.getString("xml-validation"), oc.getString("xml-validation.net"));
236  if (!MSFrame::checkOptions()) {
237  throw ProcessError();
238  }
244  MSVehicleControl* vc = 0;
246  vc = new MEVehicleControl();
247  } else {
248  vc = new MSVehicleControl();
249  }
250  MSNet* net = new MSNet(vc, new MSEventControl(), new MSEventControl(), new MSEventControl());
251 #ifndef NO_TRACI
252  // need to init TraCI-Server before loading routes to catch VEHICLE_STATE_BUILT
253  TraCIServer::openSocket(std::map<int, TraCIServer::CmdExecutor>());
254 #endif
255 
257  NLDetectorBuilder db(*net);
258  NLJunctionControlBuilder jb(*net, db);
259  NLTriggerBuilder tb;
260  NLHandler handler("", *net, db, tb, eb, jb);
261  tb.setHandler(&handler);
262  NLBuilder builder(oc, *net, eb, jb, db, handler);
266  if (builder.build()) {
267  // preload the routes especially for TraCI
268  net->loadRoutes();
269  return net;
270  }
271  delete net;
272  throw ProcessError();
273 }
274 
275 
276 void
278  MSEdgeControl* edges = 0;
279  MSJunctionControl* junctions = 0;
280  SUMORouteLoaderControl* routeLoaders = 0;
281  MSTLLogicControl* tlc = 0;
282  std::vector<SUMOTime> stateDumpTimes;
283  std::vector<std::string> stateDumpFiles;
284  try {
285  edges = myEdgeBuilder.build();
286  junctions = myJunctionBuilder.build();
287  routeLoaders = buildRouteLoaderControl(myOptions);
290  const std::vector<int> times = myOptions.getIntVector("save-state.times");
291  for (std::vector<int>::const_iterator i = times.begin(); i != times.end(); ++i) {
292  stateDumpTimes.push_back(TIME2STEPS(*i));
293  }
294  if (myOptions.isSet("save-state.files")) {
295  stateDumpFiles = myOptions.getStringVector("save-state.files");
296  if (stateDumpFiles.size() != stateDumpTimes.size()) {
297  WRITE_ERROR("Wrong number of state file names!");
298  }
299  } else {
300  const std::string prefix = myOptions.getString("save-state.prefix");
301  const std::string suffix = myOptions.getString("save-state.suffix");
302  for (std::vector<SUMOTime>::iterator i = stateDumpTimes.begin(); i != stateDumpTimes.end(); ++i) {
303  stateDumpFiles.push_back(prefix + "_" + time2string(*i) + suffix);
304  }
305  }
306  } catch (IOError& e) {
307  delete edges;
308  delete junctions;
309  delete routeLoaders;
310  delete tlc;
311  throw ProcessError(e.what());
312  } catch (ProcessError&) {
313  delete edges;
314  delete junctions;
315  delete routeLoaders;
316  delete tlc;
317  throw;
318  }
319  // if anthing goes wrong after this point, the net is responsible for cleaning up
320  myNet.closeBuilding(myOptions, edges, junctions, routeLoaders, tlc, stateDumpTimes, stateDumpFiles,
325 }
326 
327 
328 bool
329 NLBuilder::load(const std::string& mmlWhat, const bool isNet) {
330  if (!myOptions.isUsableFileList(mmlWhat)) {
331  return false;
332  }
333  std::vector<std::string> files = myOptions.getStringVector(mmlWhat);
334  for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
335  PROGRESS_BEGIN_MESSAGE("Loading " + mmlWhat + " from '" + *fileIt + "'");
336  long before = SysUtils::getCurrentMillis();
337  if (!XMLSubSys::runParser(myXMLHandler, *fileIt, isNet)) {
338  WRITE_MESSAGE("Loading of " + mmlWhat + " failed.");
339  return false;
340  }
341  PROGRESS_TIME_MESSAGE(before);
342  }
343  return true;
344 }
345 
346 
349  // build the loaders
350  SUMORouteLoaderControl* loaders = new SUMORouteLoaderControl(string2time(oc.getString("route-steps")));
351  // check whether a list is existing
352  if (oc.isSet("route-files") && string2time(oc.getString("route-steps")) > 0) {
353  std::vector<std::string> files = oc.getStringVector("route-files");
354  for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
355  if (!FileHelpers::isReadable(*fileIt)) {
356  throw ProcessError("The route file '" + *fileIt + "' is not accessible.");
357  }
358  }
359  // open files for reading
360  for (std::vector<std::string>::const_iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
361  loaders->add(new SUMORouteLoader(new MSRouteHandler(*fileIt, false)));
362  }
363  }
364  return loaders;
365 }
366 
367 
368 /****************************************************************************/
void setHandler(NLHandler *handler)
Sets the parent handler to use for nested parsing.
static MsgHandler * getWarningInstance()
Returns the instance to add warnings to.
Definition: MsgHandler.cpp:66
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
Definition: MsgHandler.cpp:75
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:180
void buildNet()
Closes the net building process.
Definition: NLBuilder.cpp:277
static bool isReadable(std::string path)
Checks whether the given file is readable.
Definition: FileHelpers.cpp:53
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:67
static void buildStreams()
Builds the streams used possibly by the simulation.
Definition: MSFrame.cpp:484
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:64
static bool loadFiles(const std::vector< std::string > &files, ShapeHandler &sh)
loads all of the given files
An XML-handler for network weights.
std::string time2string(SUMOTime t)
Definition: SUMOTime.cpp:59
MSNet & myNet
The network edges shall be obtained from.
Definition: NLBuilder.h:170
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:208
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:744
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:268
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:109
static void close()
Closes all of an applications subsystems.
void setAdditionalRestrictions()
apply additional restrictions
static std::mt19937 * getEquipmentRNG()
Definition: MSDevice.h:90
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:199
The simulated network and simulation perfomer.
Definition: MSNet.h:90
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:64
Container for junctions; performs operations on all stored junctions.
static std::mt19937 * getParsingRNG()
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:214
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:203
MSEdgeControl * build()
builds the MSEdgeControl-class which holds all edges
bool lefthand() const
Definition: NLHandler.h:123
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:429
MSTLLogicControl & getTLSControl()
Returns the tls logics control.
Definition: MSNet.h:379
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:73
SUMOTime string2time(const std::string &r)
Definition: SUMOTime.cpp:46
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:201
static MsgHandler * getMessageInstance()
Returns the instance to add normal messages to.
Definition: MsgHandler.cpp:57
static int getArgC()
Return the number of command line arguments.
Definition: OptionsIO.h:72
MSNet & myNet
The net to fill.
Definition: NLBuilder.h:220
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:127
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:219
The XML-Handler for network loading.
Definition: NLHandler.h:87
static bool checkOptions()
Checks the set options.
Definition: MSFrame.cpp:515
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:205
bool haveSeenAdditionalSpeedRestrictions() const
Definition: NLHandler.h:119
static void openSocket(const std::map< int, CmdExecutor > &execs)
Initialises the server.
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:63
const IntVector & getIntVector(const std::string &name) const
Returns the list of integer-value of the named option (only for Option_IntVector) ...
void setTargetTime(SUMOTime targetTime)
Sets myTargetTime on server and sockets to the given value.
static TraCIServer * getInstance()
Definition: TraCIServer.h:81
A storage for options typed value containers)
Definition: OptionsCont.h:98
SUMORouteLoaderControl * buildRouteLoaderControl(const OptionsCont &oc)
Builds the route loader control.
Definition: NLBuilder.cpp:348
static void initRandGlobal(std::mt19937 *which=0)
Reads the given random number options and initialises the random number generator in accordance...
Definition: RandHelper.cpp:76
bool haveSeenInternalEdge() const
Definition: NLHandler.h:111
bool load(const std::string &mmlWhat, const bool isNet=false)
Loads a described subpart form the given list of files.
Definition: NLBuilder.cpp:329
static void setMSGlobals(OptionsCont &oc)
Sets the global microsim-options.
Definition: MSFrame.cpp:615
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:349
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:45
Builds trigger objects for microsim.
virtual ~NLBuilder()
Destructor.
Definition: NLBuilder.cpp:122
void loadRoutes()
loads routes for the next few steps
Definition: MSNet.cpp:366
static MSNet * init()
Definition: NLBuilder.cpp:226
void clear()
Clears information whether an error occured previously.
Definition: MsgHandler.cpp:144
bool haveSeenNeighs() const
Definition: NLHandler.h:115
#define WRITE_MESSAGE(msg)
Definition: MsgHandler.h:200
static void initOutputOptions()
Definition: MsgHandler.cpp:192
MSTLLogicControl * buildTLLogics()
Returns the built tls-logic control.
static bool gUseMesoSim
Definition: MSGlobals.h:97
NLDetectorBuilder & myDetectorBuilder
The detector control builder to use.
Definition: NLBuilder.h:217
Stores time-dependant events and executes them at the proper time.
NLHandler & myXMLHandler
The handler used to parse the net.
Definition: NLBuilder.h:223
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:785
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:211