Eclipse SUMO - Simulation of Urban MObility
MSStateHandler.cpp
Go to the documentation of this file.
1 /****************************************************************************/
2 // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
3 // Copyright (C) 2012-2019 German Aerospace Center (DLR) and others.
4 // This program and the accompanying materials
5 // are made available under the terms of the Eclipse Public License v2.0
6 // which accompanies this distribution, and is available at
7 // http://www.eclipse.org/legal/epl-v20.html
8 // SPDX-License-Identifier: EPL-2.0
9 /****************************************************************************/
17 // Parser and output filter for routes and vehicles state saving and loading
18 /****************************************************************************/
19 
20 
21 // ===========================================================================
22 // included modules
23 // ===========================================================================
24 #include <config.h>
25 
26 #ifdef HAVE_VERSION_H
27 #include <version.h>
28 #endif
29 
30 #include <sstream>
39 #include <microsim/MSEdge.h>
40 #include <microsim/MSLane.h>
41 #include <microsim/MSGlobals.h>
42 #include <microsim/MSNet.h>
45 #include <microsim/MSRoute.h>
47 #include <microsim/MSDriverState.h>
48 #include "MSStateHandler.h"
49 
50 #include <mesosim/MESegment.h>
51 #include <mesosim/MELoop.h>
52 
53 
54 // ===========================================================================
55 // method definitions
56 // ===========================================================================
57 MSStateHandler::MSStateHandler(const std::string& file, const SUMOTime offset) :
58  MSRouteHandler(file, true),
59  myOffset(offset),
60  mySegment(nullptr),
61  myCurrentLane(nullptr),
62  myAttrs(nullptr),
63  myLastParameterised(nullptr) {
64  myAmLoadingState = true;
65  const std::vector<std::string> vehIDs = OptionsCont::getOptions().getStringVector("load-state.remove-vehicles");
66  myVehiclesToRemove.insert(vehIDs.begin(), vehIDs.end());
67 }
68 
69 
71 }
72 
73 
74 void
75 MSStateHandler::saveState(const std::string& file, SUMOTime step) {
78  out.writeAttr("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance").writeAttr("xsi:noNamespaceSchemaLocation", "http://sumo.dlr.de/xsd/state_file.xsd");
80  //saveRNGs(out);
86  for (int i = 0; i < MSEdge::dictSize(); i++) {
87  for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*MSEdge::getAllEdges()[i]); s != nullptr; s = s->getNextSegment()) {
88  s->saveState(out);
89  }
90  }
91  } else {
92  for (int i = 0; i < MSEdge::dictSize(); i++) {
93  const std::vector<MSLane*>& lanes = MSEdge::getAllEdges()[i]->getLanes();
94  for (std::vector<MSLane*>::const_iterator it = lanes.begin(); it != lanes.end(); ++it) {
95  (*it)->saveState(out);
96  }
97  }
98  }
99  out.close();
100 }
101 
102 
103 void
105  MSRouteHandler::myStartElement(element, attrs);
107  switch (element) {
108  case SUMO_TAG_SNAPSHOT: {
110  const std::string& version = attrs.getString(SUMO_ATTR_VERSION);
111  if (version != VERSION_STRING) {
112  WRITE_WARNING("State was written with sumo version " + version + " (present: " + VERSION_STRING + ")!");
113  }
114  break;
115  }
116  case SUMO_TAG_RNGSTATE: {
117  if (attrs.hasAttribute(SUMO_ATTR_RNG_DEFAULT)) {
119  }
122  }
125  }
126  if (attrs.hasAttribute(SUMO_ATTR_RNG_DEVICE)) {
128  }
131  }
134  }
137  }
138  break;
139  }
140  case SUMO_TAG_DELAY: {
141  vc.setState(attrs.getInt(SUMO_ATTR_NUMBER),
142  attrs.getInt(SUMO_ATTR_BEGIN),
143  attrs.getInt(SUMO_ATTR_END),
144  attrs.getFloat(SUMO_ATTR_DEPART),
145  attrs.getFloat(SUMO_ATTR_TIME));
146  break;
147  }
148  case SUMO_TAG_FLOWSTATE: {
150  pars->id = attrs.getString(SUMO_ATTR_ID);
151  bool ok;
152  if (attrs.getOpt<bool>(SUMO_ATTR_REROUTE, nullptr, ok, false)) {
154  }
156  attrs.getInt(SUMO_ATTR_INDEX));
157  break;
158  }
159  case SUMO_TAG_VTYPE: {
161  break;
162  }
163  case SUMO_TAG_VEHICLE: {
165  myAttrs = attrs.clone();
166  break;
167  }
168  case SUMO_TAG_DEVICE: {
169  myDeviceAttrs.push_back(attrs.clone());
170  break;
171  }
174  break;
175  }
176  case SUMO_TAG_SEGMENT: {
177  if (mySegment == nullptr) {
179  } else if (mySegment->getNextSegment() == nullptr) {
181  } else {
183  }
184  myQueIndex = 0;
185  break;
186  }
187  case SUMO_TAG_LANE: {
188  bool ok;
189  const std::string laneID = attrs.get<std::string>(SUMO_ATTR_ID, nullptr, ok);
191  if (myCurrentLane == nullptr) {
192  throw ProcessError("Unknown lane '" + laneID + "' in loaded state");
193  }
194  break;
195  }
197  try {
198  const std::vector<std::string>& vehIDs = attrs.getStringVector(SUMO_ATTR_VALUE);
201  } else {
202  myCurrentLane->loadState(vehIDs, MSNet::getInstance()->getVehicleControl());
203  }
204  } catch (EmptyData&) {} // attr may be empty
205  myQueIndex++;
206  break;
207  }
208  case SUMO_TAG_PARAM: {
209  bool ok;
210  const std::string key = attrs.get<std::string>(SUMO_ATTR_KEY, nullptr, ok);
211  // circumventing empty string test
212  const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : "";
213  assert(myLastParameterised != 0);
214  if (myLastParameterised != nullptr) {
216  }
217  break;
218  }
219  default:
220  break;
221  }
222 }
223 
224 
225 void
228  if (element != SUMO_TAG_PARAM && myVehicleParameter == nullptr && myCurrentVType == nullptr) {
229  myLastParameterised = nullptr;
230  }
231 }
232 
233 
234 void
236  assert(myVehicleParameter != 0);
238  // the vehicle was already counted in MSVehicleControl::setState
240  // make a copy because myVehicleParameter is reset in closeVehicle()
241  const std::string vehID = myVehicleParameter->id;
242  if (myVehiclesToRemove.count(vehID) == 0) {
244  // reset depart
245  vc.discountStateLoaded();
246  SUMOVehicle* v = vc.getVehicle(vehID);
248  v->loadState(*myAttrs, myOffset);
249  if (v->hasDeparted()) {
250  // vehicle already departed: disable pre-insertion rerouting and enable regular routing behavior
251  MSDevice_Routing* routingDevice = static_cast<MSDevice_Routing*>(v->getDevice(typeid(MSDevice_Routing)));
252  if (routingDevice != nullptr) {
254  }
256  }
257  while (!myDeviceAttrs.empty()) {
258  const std::string attrID = myDeviceAttrs.back()->getString(SUMO_ATTR_ID);
259  for (MSVehicleDevice* const dev : v->getDevices()) {
260  if (dev->getID() == attrID) {
261  dev->loadState(*myDeviceAttrs.back());
262  }
263  }
264  delete myDeviceAttrs.back();
265  myDeviceAttrs.pop_back();
266  }
267  } else {
268  vc.discountStateLoaded(true);
269  delete myVehicleParameter;
270  myVehicleParameter = nullptr;
271  }
272  delete myAttrs;
273 }
274 
275 
276 void
281  out.writeAttr(SUMO_ATTR_RNG_INSERTIONCONTROL, RandHelper::saveState(MSNet::getInstance()->getInsertionControl().getFlowRNG()));
286  out.closeTag();
287 
288 }
289 
290 
291 /****************************************************************************/
static std::string saveState(std::mt19937 *rng=0)
save rng state to string
Definition: RandHelper.h:160
MESegment * getNextSegment() const
Returns the following segment on the same edge (0 if it is the last).
Definition: MESegment.h:152
void myStartElement(int element, const SUMOSAXAttributes &attrs)
Called on the opening of a tag;.
OutputDevice & writeAttr(const SumoXMLAttr attr, const T &val)
writes a named attribute
Definition: OutputDevice.h:256
void discountStateLoaded(bool removed=false)
avoid counting a vehicle twice if it was loaded from state and route input
void close()
Closes the device and removes it from the dictionary.
segment of a lane
virtual void myEndElement(int element)
Called when a closing tag occurs.
long long int SUMOTime
Definition: SUMOTime.h:35
virtual bool hasDeparted() const =0
Returns whether this vehicle has departed.
const int VEHPARS_FORCE_REROUTE
description of a vehicle type
Parameterised * myLastParameterised
the last object that potentially carries parameters
MSLane * myCurrentLane
current lane being loaded
virtual SUMOSAXAttributes * clone() const =0
return a new deep-copy attributes object
MESegment * getSegmentForEdge(const MSEdge &e, double pos=0)
Get the segment for a given edge at a given position.
Definition: MELoop.cpp:293
virtual void closeVehicle()
Ends the processing of a vehicle (note: is virtual because is reimplemented in MSStateHandler) ...
begin/end of the description of a single lane
static int dictSize()
Returns the number of edges.
Definition: MSEdge.cpp:831
virtual MSVehicleDevice * getDevice(const std::type_info &type) const =0
Returns a device of the given type if it exists or 0.
SUMOVehicleParameter * myVehicleParameter
Parameter of the current vehicle, trip, person, container or flow.
void closeVehicle()
Ends the processing of a vehicle.
SUMOVehicle * getVehicle(const std::string &id) const
Returns the vehicle with the given id.
int parametersSet
Information for the router which parameter were set, TraCI may modify this (whe changing color) ...
SUMOVTypeParameter * myCurrentVType
The currently parsed vehicle type.
std::string time2string(SUMOTime t)
Definition: SUMOTime.cpp:65
A device that performs vehicle rerouting based on current edge speeds.
a flow state definition (used when saving and loading simulatino state)
weights: time range begin
MESegment * mySegment
segment
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition: MSNet.cpp:168
static std::mt19937 * getRNG()
Definition: MSDriverState.h:78
int getNumericalID() const
Returns the numerical id of the edge.
Definition: MSEdge.h:263
static std::mt19937 * getEquipmentRNG()
Definition: MSDevice.h:91
virtual bool hasAttribute(int id) const =0
Returns the information whether the named (by its enum-value) attribute is within the current list...
void setState(int runningVehNo, int loadedVehNo, int endedVehNo, double totalDepartureDelay, double totalTravelTime)
Sets the current state variables as loaded from the stream.
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:239
static void dict_saveState(OutputDevice &out)
Saves all known routes into the given stream.
Definition: MSRoute.cpp:257
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:58
virtual std::string getString(int id) const =0
Returns the string-value of the named (by its enum-value) attribute.
static std::mt19937 * getParsingRNG()
get parsing RNG
bool writeHeader(const SumoXMLTag &rootElement)
Definition: OutputDevice.h:188
A road/street connecting two junctions.
Definition: MSEdge.h:76
static std::mt19937 * getResponseTimeRNG()
Definition: MSDevice_ToC.h:190
bool addFlow(SUMOVehicleParameter *const pars, int index=-1)
Adds parameter for a vehicle flow for departure.
bool notifyEnter(SUMOTrafficObject &veh, MSMoveReminder::Notification reason, const MSLane *enteredLane=0)
Computes a new route on vehicle insertion.
virtual void setChosenSpeedFactor(const double factor)=0
MSStateHandler(const std::string &file, const SUMOTime offset)
standard constructor
void saveState(OutputDevice &out)
Saves the current state into the given stream.
Representation of a vehicle.
Definition: SUMOVehicle.h:61
Encapsulated SAX-Attributes.
T get(int attr, const char *objectid, bool &ok, bool report=true) const
Tries to read given attribute assuming it is an int.
parameter associated to a certain key
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition: MSNet.h:337
virtual const std::vector< MSVehicleDevice * > & getDevices() const =0
Returns this vehicle&#39;s devices.
SUMOTime myTime
time
SUMOTime string2time(const std::string &r)
Definition: SUMOTime.cpp:42
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) ...
void saveState(OutputDevice &out)
Saves the current state into the given stream.
const SUMOTime myOffset
offset
SUMOSAXAttributes * myAttrs
cached attrs (used when loading vehicles)
void setParameter(const std::string &key, const std::string &value)
Sets a parameter.
void loadState(const SUMOSAXAttributes &attrs, const SUMOTime offset, MSVehicleControl &vc)
Loads one transfer vehicle state from the given descriptionn.
virtual void myStartElement(int element, const SUMOSAXAttributes &attrs)
Called on the opening of a tag;.
void alreadyDeparted(SUMOVehicle *veh)
stops trying to emit the given vehicle (because it already departed)
#define VERSION_STRING
Definition: config.h:207
static MSVehicleTransfer * getInstance()
Returns the instance of this object.
static bool dictionary(const std::string &id, MSLane *lane)
Static (sic!) container methods {.
Definition: MSLane.cpp:1855
virtual double getFloat(int id) const =0
Returns the double-value of the named (by its enum-value) attribute.
trigger: the time of the step
T getOpt(int attr, const char *objectid, bool &ok, T defaultValue, bool report=true) const
Tries to read given attribute assuming it is an int.
static std::mt19937 * getRNG()
The vehicle has departed (was inserted into the network)
Structure representing possible vehicle parameter.
void loadState(const std::vector< std::string > &vehIDs, MSVehicleControl &vc, const SUMOTime blockTime, const int queIdx)
Loads the state of this segment with the given parameters.
Definition: MESegment.cpp:663
bool myAmLoadingState
whether a state file is being loaded
MSInsertionControl & getInsertionControl()
Returns the insertion control.
Definition: MSNet.h:390
static OutputDevice & getDevice(const std::string &name)
Returns the described OutputDevice.
static const MSEdgeVector & getAllEdges()
Returns all edges with a numerical id.
Definition: MSEdge.cpp:837
virtual ~MSStateHandler()
standard destructor
static long long int toLong(const std::string &sData)
converts a string into the long value described by it by calling the char-type converter, which
weights: time range end
A single mesoscopic segment (cell)
Definition: MESegment.h:50
void myEndElement(int element)
Called when a closing tag occurs.
std::vector< SUMOSAXAttributes * > myDeviceAttrs
cached device attrs (used when loading vehicles)
const std::vector< std::string > getStringVector(int attr) const
Tries to read given attribute assuming it is a string vector.
Abstract in-vehicle device.
static MELoop * gMesoNet
mesoscopic simulation infrastructure
Definition: MSGlobals.h:106
virtual int getInt(int id) const =0
Returns the int-value of the named (by its enum-value) attribute.
std::set< std::string > myVehiclesToRemove
vehicles that shall be removed when loading state
description of a vehicle
void loadState(const std::vector< std::string > &vehIDs, MSVehicleControl &vc)
Loads the state of this segment with the given parameters.
Definition: MSLane.cpp:3030
Static storage of an output device and its base (abstract) implementation.
Definition: OutputDevice.h:64
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
int myQueIndex
que index
The class responsible for building and deletion of vehicles.
static void loadState(const std::string &state, std::mt19937 *rng=0)
load rng state from string
Definition: RandHelper.h:170
void saveState(OutputDevice &out)
Saves the current state into the given stream.
static void saveRNGs(OutputDevice &out)
save the state of random number generators
std::mt19937 * getFlowRNG()
retrieve internal RNG
static bool gUseMesoSim
Definition: MSGlobals.h:91
const MSEdge & getEdge() const
Returns the edge this segment belongs to.
Definition: MESegment.h:266
virtual void loadState(const SUMOSAXAttributes &attrs, const SUMOTime offset)=0
Loads the state of this vehicle from the given description.
Parser and container for routes during their loading.
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
static void saveState(const std::string &file, SUMOTime step)
Saves the current state.
std::string id
The vehicle&#39;s id.