SUMO - Simulation of Urban MObility
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MSCalibrator.cpp
Go to the documentation of this file.
1 /****************************************************************************/
8 // Calibrates the flow on an edge by removing an inserting vehicles
9 /****************************************************************************/
10 // SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
11 // Copyright (C) 2001-2011 DLR (http://www.dlr.de/) and contributors
12 /****************************************************************************/
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; either version 2 of the License, or
17 // (at your option) any later version.
18 //
19 /****************************************************************************/
20 
21 
22 // ===========================================================================
23 // included modules
24 // ===========================================================================
25 #ifdef _MSC_VER
26 #include <windows_config.h>
27 #else
28 #include <config.h>
29 #endif
30 
31 #include <string>
32 #include <algorithm>
33 #include <cmath>
34 #include <microsim/MSNet.h>
35 #include <microsim/MSEdge.h>
36 #include <microsim/MSLane.h>
39 #include <utils/common/ToString.h>
42 #include <utils/xml/XMLSubSys.h>
48 #include "MSCalibrator.h"
49 
50 #ifdef CHECK_MEMORY_LEAKS
51 #include <foreign/nvwa/debug_new.h>
52 #endif // CHECK_MEMORY_LEAKS
53 
54 //#define MSCalibrator_DEBUG
55 
56 // ===========================================================================
57 // static members
58 // ===========================================================================
59 std::vector<MSMoveReminder*> MSCalibrator::LeftoverReminders;
60 std::vector<SUMOVehicleParameter*> MSCalibrator::LeftoverVehicleParameters;
61 
62 // ===========================================================================
63 // method definitions
64 // ===========================================================================
65 MSCalibrator::MSCalibrator(const std::string& id,
66  MSEdge* edge, SUMOReal pos,
67  const std::string& aXMLFilename,
68  const std::string& outputFilename,
69  const SUMOTime freq) :
70  MSTrigger(id),
71  MSRouteHandler(aXMLFilename, false),
72  myEdge(edge), myPos(pos),
73  myEdgeMeanData(0, myEdge->getLength(), false),
74  myOutput(0), myFrequency(freq), myRemoved(0),
75  myInserted(0), myClearedInJam(0),
76  mySpeedIsDefault(true), myDidSpeedAdaption(false), myDidInit(false),
77  myDefaultSpeed(myEdge->getSpeedLimit()),
78  myHaveWarnedAboutClearingJam(false),
79  myAmActive(false) {
80  if (outputFilename != "") {
81  myOutput = &OutputDevice::getDevice(outputFilename);
82  myOutput->writeXMLHeader("calibratorstats");
83  }
84  if (aXMLFilename != "") {
85  XMLSubSys::runParser(*this, aXMLFilename);
86  if (!myDidInit) {
87  init();
88  }
89  }
90 }
91 
92 
93 void
95  if (myIntervals.size() > 0) {
96  if (myIntervals.back().end == -1) {
97  myIntervals.back().end = SUMOTime_MAX;
98  }
100  // calibration should happen after regular insertions have taken place
102  MSNet::getInstance()->getCurrentTimeStep(),
104  for (size_t i = 0; i < myEdge->getLanes().size(); ++i) {
105  MSLane* lane = myEdge->getLanes()[i];
107  LeftoverReminders.push_back(laneData);
108  myLaneMeanData.push_back(laneData);
109  VehicleRemover* remover = new VehicleRemover(lane, (int)i, this);
110  LeftoverReminders.push_back(remover);
111  myVehicleRemovers.push_back(remover);
112  }
113  } else {
114  WRITE_WARNING("No flow intervals in calibrator '" + myID + "'.");
115  }
116  myDidInit = true;
117 }
118 
119 
121  if (myCurrentStateInterval != myIntervals.end()) {
122  writeXMLOutput();
123  }
124  //mySegment->removeDetector(&myMeanData);
125  for (std::vector<VehicleRemover*>::iterator it = myVehicleRemovers.begin(); it != myVehicleRemovers.end(); ++it) {
126  (*it)->disable();
127  }
128 }
129 
130 
131 void
133  const SUMOSAXAttributes& attrs) {
134  if (element == SUMO_TAG_FLOW) {
135  AspiredState state;
136  int lastEnd = -1;
137  if (myIntervals.size() > 0) {
138  lastEnd = myIntervals.back().end;
139  if (lastEnd == -1) {
140  lastEnd = myIntervals.back().begin;
141  }
142  }
143  try {
144  bool ok = true;
145  state.q = attrs.getOpt<SUMOReal>(SUMO_ATTR_VEHSPERHOUR, 0, ok, -1.);
146  state.v = attrs.getOpt<SUMOReal>(SUMO_ATTR_SPEED, 0, ok, -1.);
147  state.begin = attrs.getSUMOTimeReporting(SUMO_ATTR_BEGIN, myID.c_str(), ok);
148  if (state.begin < lastEnd) {
149  WRITE_ERROR("Overlapping or unsorted intervals in calibrator '" + myID + "'.");
150  }
151  state.end = attrs.getOptSUMOTimeReporting(SUMO_ATTR_END, myID.c_str(), ok, -1);
154  // vehicles should be inserted with max speed unless stated otherwise
157  }
158  // vehicles should be inserted on any lane unless stated otherwise
161  }
162  if (MSNet::getInstance()->getVehicleControl().getVType(state.vehicleParameter->vtypeid) == 0) {
163  WRITE_ERROR("Unknown vehicle type '" + state.vehicleParameter->vtypeid + "' in calibrator '" + myID + "'.");
164  }
165  } catch (EmptyData) {
166  WRITE_ERROR("Mandatory attribute missing in definition of calibrator '" + myID + "'.");
167  } catch (NumberFormatException) {
168  WRITE_ERROR("Non-numeric value for numeric attribute in definition of calibrator '" + myID + "'.");
169  }
170  if (state.q < 0 && state.v < 0) {
171  WRITE_ERROR("Either 'vehsPerHour' or 'speed' has to be given in flow definition of calibrator '" + myID + "'.");
172  }
173  if (myIntervals.size() > 0 && myIntervals.back().end == -1) {
174  myIntervals.back().end = state.begin;
175  }
176  myIntervals.push_back(state);
177  } else {
178  MSRouteHandler::myStartElement(element, attrs);
179  }
180 }
181 
182 
183 void
185  if (element == SUMO_TAG_CALIBRATOR) {
186  if (!myDidInit) {
187  init();
188  }
189  } else if (element != SUMO_TAG_FLOW) {
191  }
192 }
193 
194 
195 void
197  if (myOutput != 0) {
198  updateMeanData();
199  const int p = passed();
200  // meandata will be off if vehicles are removed on the next edge instead of this one
202  assert(discrepancy >= 0);
203  const std::string ds = (discrepancy > 0 ? "\" vaporizedOnNextEdge=\"" + toString(discrepancy) : "");
204  const SUMOReal durationSeconds = STEPS2TIME(myCurrentStateInterval->end - myCurrentStateInterval->begin);
205  (*myOutput) << " <interval begin=\"" << time2string(myCurrentStateInterval->begin) <<
206  "\" end=\"" << time2string(myCurrentStateInterval->end) <<
207  "\" id=\"" << myID <<
208  "\" nVehContrib=\"" << p <<
209  "\" removed=\"" << myRemoved <<
210  "\" inserted=\"" << myInserted <<
211  "\" cleared=\"" << myClearedInJam <<
212  "\" flow=\"" << p * 3600.0 / durationSeconds <<
213  "\" aspiredFlow=\"" << myCurrentStateInterval->q <<
215  "\" aspiredSpeed=\"" << myCurrentStateInterval->v <<
216  ds << //optional
217  "\"/>\n";
218  }
219  myDidSpeedAdaption = false;
220  myInserted = 0;
221  myRemoved = 0;
222  myClearedInJam = 0;
224  reset();
225 }
226 
227 
228 bool
230  while (myCurrentStateInterval != myIntervals.end() && myCurrentStateInterval->end <= time) {
231  // XXX what about skipped intervals?
233  }
234  return myCurrentStateInterval != myIntervals.end() &&
235  myCurrentStateInterval->begin <= time && myCurrentStateInterval->end > time;
236 }
237 
238 int
240  if (myCurrentStateInterval != myIntervals.end()) {
241  const SUMOReal totalHourFraction = STEPS2TIME(myCurrentStateInterval->end - myCurrentStateInterval->begin) / (SUMOReal) 3600.;
242  return (int)std::floor(myCurrentStateInterval->q * totalHourFraction + 0.5); // round to closest int
243  } else {
244  return -1;
245  }
246 }
247 
248 
249 SUMOTime
251  // get current simulation values (valid for the last simulation second)
252  // XXX could we miss vehicle movements if this is called less often than every DELTA_T (default) ?
253  updateMeanData();
254  // check whether an adaptation value exists
255  if (isCurrentStateActive(currentTime)) {
256  myAmActive = true;
257  // all happens in isCurrentStateActive()
258  } else {
259  myAmActive = false;
260  reset();
261  if (!mySpeedIsDefault) {
262  // reset speed to default
263  for (std::vector<MSLane*>::const_iterator i = myEdge->getLanes().begin(); i != myEdge->getLanes().end(); ++i) {
264  (*i)->setMaxSpeed(myDefaultSpeed);
265  }
266  mySpeedIsDefault = true;
267  }
268  if (myCurrentStateInterval == myIntervals.end()) {
269  // keep calibrator alive for gui but do not call again
270  return TIME2STEPS(86400);
271  }
272  return myFrequency;
273  }
274  // we are active
275  if (!myDidSpeedAdaption && myCurrentStateInterval->v >= 0) {
276  for (std::vector<MSLane*>::const_iterator i = myEdge->getLanes().begin(); i != myEdge->getLanes().end(); ++i) {
277  (*i)->setMaxSpeed(myCurrentStateInterval->v);
278  }
279  mySpeedIsDefault = false;
280  myDidSpeedAdaption = true;
281  }
282 
283  const bool calibrateFlow = myCurrentStateInterval->q >= 0;
284  const int totalWishedNum = totalWished();
285  int adaptedNum = passed() + myClearedInJam;
286 #ifdef MSCalibrator_DEBUG
287  std::cout << time2string(currentTime) << " " << myID
288  << " q=" << myCurrentStateInterval->q
289  << " totalWished=" << totalWishedNum
290  << " adapted=" << adaptedNum
291  << " jam=" << invalidJam()
292  << " entered=" << myEdgeMeanData.nVehEntered
293  << " departed=" << myEdgeMeanData.nVehDeparted
294  << " arrived=" << myEdgeMeanData.nVehArrived
295  << " left=" << myEdgeMeanData.nVehLeft
296  << " waitSecs=" << myEdgeMeanData.waitSeconds
297  << " vaporized=" << myEdgeMeanData.nVehVaporized
298  << "\n";
299 #endif
300  if (myToRemove.size() > 0) {
301  // it is not save to remove the vehicles inside
302  // VehicleRemover::notifyEnter so we do it here
303  for (std::set<MSVehicle*>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
304  MSVehicle* vehicle = *it;
308  }
309  myToRemove.clear();
310  } else if (calibrateFlow && adaptedNum < totalWishedNum) {
311  // we need to insert some vehicles
312  const SUMOReal hourFraction = STEPS2TIME(currentTime - myCurrentStateInterval->begin + DELTA_T) / (SUMOReal) 3600.;
313  const int wishedNum = (int)std::floor(myCurrentStateInterval->q * hourFraction + 0.5); // round to closest int
314  // only the difference between inflow and aspiredFlow should be added, thus
315  // we should not count vehicles vaporized from a jam here
316  // if we have enough time left we can add missing vehicles later
317  const int relaxedInsertion = (int)std::floor(STEPS2TIME(myCurrentStateInterval->end - currentTime) / 3);
318  const int insertionSlack = MAX2(0, adaptedNum + relaxedInsertion - totalWishedNum);
319  // increase number of vehicles
320 #ifdef MSCalibrator_DEBUG
321  std::cout
322  << " wished:" << wishedNum
323  << " slack:" << insertionSlack
324  << " before:" << adaptedNum
325  << "\n";
326 #endif
327  while (wishedNum > adaptedNum + insertionSlack) {
328  SUMOVehicleParameter* pars = myCurrentStateInterval->vehicleParameter;
329  const MSRoute* route = 0;
330  StringTokenizer st(pars->routeid);
331  while (route == 0 && st.hasNext()) {
332  route = MSRoute::dictionary(st.next());
333  }
334  if (route == 0) {
335  WRITE_WARNING("No valid routes in calibrator '" + myID + "'.");
336  break;
337  }
338  if (!route->contains(myEdge)) {
339  WRITE_WARNING("Route '" + route->getID() + "' in calibrator '" + myID + "' does not contain edge '" + myEdge->getID() + "'.");
340  break;
341  }
342  const unsigned int routeIndex = (unsigned int)std::distance(route->begin(),
343  std::find(route->begin(), route->end(), myEdge));
345  assert(route != 0 && vtype != 0);
346  // build the vehicle
347  SUMOVehicleParameter* newPars = new SUMOVehicleParameter(*pars);
348  newPars->id = myID + "." + toString((int)STEPS2TIME(myCurrentStateInterval->begin)) + "." + toString(myInserted);
349  newPars->depart = currentTime;
350  newPars->routeid = route->getID();
352  newPars, route, vtype));
353 #ifdef MSCalibrator_DEBUG
354  std::cout << " resetting route pos: " << routeIndex << "\n";
355 #endif
356  vehicle->resetRoutePosition(routeIndex);
357  if (myEdge->insertVehicle(*vehicle, currentTime)) {
358  vehicle->onDepart();
359  if (!MSNet::getInstance()->getVehicleControl().addVehicle(vehicle->getID(), vehicle)) {
360  throw ProcessError("Emission of vehicle '" + vehicle->getID() + "' in calibrator '" + getID() + "'failed!");
361  }
362  myInserted++;
363  adaptedNum++;
364 #ifdef MSCalibrator_DEBUG
365  std::cout << "I ";
366 #endif
367  } else {
368  // could not insert vehicle
369 #ifdef MSCalibrator_DEBUG
370  std::cout << "F ";
371 #endif
373  break;
374  }
375  }
376  }
377  if (myCurrentStateInterval->end <= currentTime + myFrequency) {
378  writeXMLOutput();
379  }
380  return myFrequency;
381 }
382 
383 void
386  for (std::vector<MSMeanData_Net::MSLaneMeanDataValues*>::iterator it = myLaneMeanData.begin(); it != myLaneMeanData.end(); ++it) {
387  (*it)->reset();
388  }
389 }
390 
391 
392 bool
393 MSCalibrator::invalidJam(int laneIndex) const {
394  if (laneIndex < 0) {
395  const int numLanes = (int)myEdge->getLanes().size();
396  for (int i = 0; i < numLanes; ++i) {
397  if (invalidJam(i)) {
398  return true;
399  }
400  }
401  return false;
402  }
403  assert(laneIndex < (int)myEdge->getLanes().size());
404  const MSLane* const lane = myEdge->getLanes()[laneIndex];
405  if (lane->getVehicleNumber() < 4) {
406  // cannot reliably detect invalid jams
407  return false;
408  }
409  // maxSpeed reflects the calibration target
410  const bool toSlow = lane->getMeanSpeed() < 0.5 * myEdge->getSpeedLimit();
411  return toSlow && remainingVehicleCapacity(laneIndex) < 1;
412 }
413 
414 
415 int
417  if (laneIndex < 0) {
418  const int numLanes = (int)myEdge->getLanes().size();
419  int result = 0;
420  for (int i = 0; i < numLanes; ++i) {
421  result = MAX2(result, remainingVehicleCapacity(i));
422  }
423  return result;
424  }
425  assert(laneIndex < (int)myEdge->getLanes().size());
426  MSLane* lane = myEdge->getLanes()[laneIndex];
427  MSVehicle* last = lane->getLastVehicle();
428  const SUMOVehicleParameter* pars = myCurrentStateInterval->vehicleParameter;
430  const SUMOReal spacePerVehicle = vtype->getLengthWithGap() + myEdge->getSpeedLimit() * vtype->getCarFollowModel().getHeadwayTime();
431  if (last == 0) {
432  // ensure vehicles can be inserted on short edges
433  return MAX2(1, (int)(myEdge->getLength() / spacePerVehicle));
434  } else {
435  return (int)(last->getPositionOnLane() / spacePerVehicle);
436  }
437 }
438 
439 
440 void
442  for (std::vector<MSMoveReminder*>::iterator it = LeftoverReminders.begin(); it != LeftoverReminders.end(); ++it) {
443  delete *it;
444  }
445  LeftoverReminders.clear();
446  for (std::vector<SUMOVehicleParameter*>::iterator it = LeftoverVehicleParameters.begin();
447  it != LeftoverVehicleParameters.end(); ++it) {
448  delete *it;
449  }
451 }
452 
453 
454 void
457  for (std::vector<MSMeanData_Net::MSLaneMeanDataValues*>::iterator it = myLaneMeanData.begin();
458  it != myLaneMeanData.end(); ++it) {
459  (*it)->addTo(myEdgeMeanData);
460  }
461 }
462 
464  if (myParent == 0) {
465  return false;
466  }
468  const bool calibrateFlow = myParent->myCurrentStateInterval->q >= 0;
469  const int totalWishedNum = myParent->totalWished();
470  int adaptedNum = myParent->passed() + myParent->myClearedInJam;
471  MSVehicle* vehicle = dynamic_cast<MSVehicle*>(&veh);
472  if (calibrateFlow && adaptedNum > totalWishedNum) {
473 #ifdef MSCalibrator_DEBUG
474  std::cout << time2string(MSNet::getInstance()->getCurrentTimeStep()) << " " << myParent->getID()
475  << " vaporizing " << vehicle->getID() << " to reduce flow\n";
476 #endif
477  if (myParent->scheduleRemoval(vehicle)) {
478  myParent->myRemoved++;
479  }
480  } else if (myParent->invalidJam(myLaneIndex)) {
481 #ifdef MSCalibrator_DEBUG
482  std::cout << time2string(MSNet::getInstance()->getCurrentTimeStep()) << " " << myParent->getID()
483  << " vaporizing " << vehicle->getID() << " to clear jam\n";
484 #endif
486  WRITE_WARNING("Clearing jam at calibrator '" + myParent->myID + "' at time "
487  + time2string(MSNet::getInstance()->getCurrentTimeStep()));
489  }
490  if (myParent->scheduleRemoval(vehicle)) {
492  }
493  }
494  return true;
495 }
496 
497 
498 
499 /****************************************************************************/
500