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 /****************************************************************************/
9 // Calibrates the flow on an edge by removing an inserting vehicles
10 /****************************************************************************/
11 // SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
12 // Copyright (C) 2005-2014 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 <string>
34 #include <algorithm>
35 #include <cmath>
36 #include <microsim/MSNet.h>
37 #include <microsim/MSEdge.h>
38 #include <microsim/MSLane.h>
42 #include <utils/common/ToString.h>
45 #include <utils/xml/XMLSubSys.h>
51 #include "MSCalibrator.h"
52 
53 #ifdef CHECK_MEMORY_LEAKS
54 #include <foreign/nvwa/debug_new.h>
55 #endif // CHECK_MEMORY_LEAKS
56 
57 //#define MSCalibrator_DEBUG
58 
59 // ===========================================================================
60 // static members
61 // ===========================================================================
62 std::vector<MSMoveReminder*> MSCalibrator::LeftoverReminders;
63 std::vector<SUMOVehicleParameter*> MSCalibrator::LeftoverVehicleParameters;
64 
65 // ===========================================================================
66 // method definitions
67 // ===========================================================================
68 MSCalibrator::MSCalibrator(const std::string& id,
69  const MSEdge* const edge, const SUMOReal pos,
70  const std::string& aXMLFilename,
71  const std::string& outputFilename,
72  const SUMOTime freq, const SUMOReal length,
73  const MSRouteProbe* probe,
74  const bool addLaneMeanData) :
75  MSTrigger(id),
76  MSRouteHandler(aXMLFilename, false),
77  myEdge(edge), myPos(pos), myProbe(probe),
78  myEdgeMeanData(0, length, false),
79  myOutput(0), myFrequency(freq), myRemoved(0),
80  myInserted(0), myClearedInJam(0),
81  mySpeedIsDefault(true), myDidSpeedAdaption(false), myDidInit(false),
82  myDefaultSpeed(myEdge->getSpeedLimit()),
83  myHaveWarnedAboutClearingJam(false),
84  myAmActive(false) {
85  if (outputFilename != "") {
86  myOutput = &OutputDevice::getDevice(outputFilename);
87  myOutput->writeXMLHeader("calibratorstats");
88  }
89  if (aXMLFilename != "") {
90  XMLSubSys::runParser(*this, aXMLFilename);
91  if (!myDidInit) {
92  init();
93  }
94  }
95  if (addLaneMeanData) {
96  for (size_t i = 0; i < myEdge->getLanes().size(); ++i) {
97  MSLane* lane = myEdge->getLanes()[i];
99  laneData->setDescription("meandata_calibrator_" + lane->getID());
100  LeftoverReminders.push_back(laneData);
101  myLaneMeanData.push_back(laneData);
102  VehicleRemover* remover = new VehicleRemover(lane, (int)i, this);
103  LeftoverReminders.push_back(remover);
104  myVehicleRemovers.push_back(remover);
105  }
106  }
107 }
108 
109 
110 void
112  if (myIntervals.size() > 0) {
113  if (myIntervals.back().end == -1) {
114  myIntervals.back().end = SUMOTime_MAX;
115  }
117  // calibration should happen after regular insertions have taken place
119  MSNet::getInstance()->getCurrentTimeStep(),
121  } else {
122  WRITE_WARNING("No flow intervals in calibrator '" + myID + "'.");
123  }
124  myDidInit = true;
125 }
126 
127 
129  if (myCurrentStateInterval != myIntervals.end()) {
130  writeXMLOutput();
131  }
132  for (std::vector<VehicleRemover*>::iterator it = myVehicleRemovers.begin(); it != myVehicleRemovers.end(); ++it) {
133  (*it)->disable();
134  }
135 }
136 
137 
138 void
140  const SUMOSAXAttributes& attrs) {
141  if (element == SUMO_TAG_FLOW) {
142  AspiredState state;
143  int lastEnd = -1;
144  if (myIntervals.size() > 0) {
145  lastEnd = myIntervals.back().end;
146  if (lastEnd == -1) {
147  lastEnd = myIntervals.back().begin;
148  }
149  }
150  try {
151  bool ok = true;
152  state.q = attrs.getOpt<SUMOReal>(SUMO_ATTR_VEHSPERHOUR, 0, ok, -1.);
153  state.v = attrs.getOpt<SUMOReal>(SUMO_ATTR_SPEED, 0, ok, -1.);
154  state.begin = attrs.getSUMOTimeReporting(SUMO_ATTR_BEGIN, myID.c_str(), ok);
155  if (state.begin < lastEnd) {
156  WRITE_ERROR("Overlapping or unsorted intervals in calibrator '" + myID + "'.");
157  }
158  state.end = attrs.getOptSUMOTimeReporting(SUMO_ATTR_END, myID.c_str(), ok, -1);
161  // vehicles should be inserted with max speed unless stated otherwise
164  }
165  // vehicles should be inserted on any lane unless stated otherwise
168  }
169  if (state.vehicleParameter->vtypeid != DEFAULT_VTYPE_ID &&
171  WRITE_ERROR("Unknown vehicle type '" + state.vehicleParameter->vtypeid + "' in calibrator '" + myID + "'.");
172  }
173  } catch (EmptyData) {
174  WRITE_ERROR("Mandatory attribute missing in definition of calibrator '" + myID + "'.");
175  } catch (NumberFormatException) {
176  WRITE_ERROR("Non-numeric value for numeric attribute in definition of calibrator '" + myID + "'.");
177  }
178  if (state.q < 0 && state.v < 0) {
179  WRITE_ERROR("Either 'vehsPerHour' or 'speed' has to be given in flow definition of calibrator '" + myID + "'.");
180  }
181  if (myIntervals.size() > 0 && myIntervals.back().end == -1) {
182  myIntervals.back().end = state.begin;
183  }
184  myIntervals.push_back(state);
185  } else {
186  MSRouteHandler::myStartElement(element, attrs);
187  }
188 }
189 
190 
191 void
193  if (element == SUMO_TAG_CALIBRATOR) {
194  if (!myDidInit) {
195  init();
196  }
197  } else if (element != SUMO_TAG_FLOW) {
199  }
200 }
201 
202 
203 void
205  if (myOutput != 0) {
206  updateMeanData();
207  const int p = passed();
208  // meandata will be off if vehicles are removed on the next edge instead of this one
210  assert(discrepancy >= 0);
211  const std::string ds = (discrepancy > 0 ? "\" vaporizedOnNextEdge=\"" + toString(discrepancy) : "");
212  const SUMOReal durationSeconds = STEPS2TIME(myCurrentStateInterval->end - myCurrentStateInterval->begin);
213  (*myOutput) << " <interval begin=\"" << time2string(myCurrentStateInterval->begin) <<
214  "\" end=\"" << time2string(myCurrentStateInterval->end) <<
215  "\" id=\"" << myID <<
216  "\" nVehContrib=\"" << p <<
217  "\" removed=\"" << myRemoved <<
218  "\" inserted=\"" << myInserted <<
219  "\" cleared=\"" << myClearedInJam <<
220  "\" flow=\"" << p * 3600.0 / durationSeconds <<
221  "\" aspiredFlow=\"" << myCurrentStateInterval->q <<
223  "\" aspiredSpeed=\"" << myCurrentStateInterval->v <<
224  ds << //optional
225  "\"/>\n";
226  }
227  myDidSpeedAdaption = false;
228  myInserted = 0;
229  myRemoved = 0;
230  myClearedInJam = 0;
232  reset();
233 }
234 
235 
236 bool
238  while (myCurrentStateInterval != myIntervals.end() && myCurrentStateInterval->end <= time) {
239  // XXX what about skipped intervals?
241  }
242  return myCurrentStateInterval != myIntervals.end() &&
243  myCurrentStateInterval->begin <= time && myCurrentStateInterval->end > time;
244 }
245 
246 int
248  if (myCurrentStateInterval != myIntervals.end()) {
249  const SUMOReal totalHourFraction = STEPS2TIME(myCurrentStateInterval->end - myCurrentStateInterval->begin) / (SUMOReal) 3600.;
250  return (int)std::floor(myCurrentStateInterval->q * totalHourFraction + 0.5); // round to closest int
251  } else {
252  return -1;
253  }
254 }
255 
256 
257 bool
259  if (myToRemove.size() > 0) {
261  // it is not save to remove the vehicles inside
262  // VehicleRemover::notifyEnter so we do it here
263  for (std::set<std::string>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
264  MSVehicle* vehicle = dynamic_cast<MSVehicle*>(vc.getVehicle(*it));
265  if (vehicle != 0) {
268  vc.scheduleVehicleRemoval(vehicle);
269  } else {
270  WRITE_WARNING("Calibrator '" + getID() + "' could not remove vehicle '" + *it);
271  }
272  }
273  myToRemove.clear();
274  return true;
275  }
276  return false;
277 }
278 
279 
280 SUMOTime
282  // get current simulation values (valid for the last simulation second)
283  // XXX could we miss vehicle movements if this is called less often than every DELTA_T (default) ?
284  updateMeanData();
285  const bool hadRemovals = removePending();
286  // check whether an adaptation value exists
287  if (isCurrentStateActive(currentTime)) {
288  myAmActive = true;
289  // all happens in isCurrentStateActive()
290  } else {
291  myAmActive = false;
292  reset();
293  if (!mySpeedIsDefault) {
294  // reset speed to default
295  for (std::vector<MSLane*>::const_iterator i = myEdge->getLanes().begin(); i != myEdge->getLanes().end(); ++i) {
296  (*i)->setMaxSpeed(myDefaultSpeed);
297  }
298  mySpeedIsDefault = true;
299  }
300  if (myCurrentStateInterval == myIntervals.end()) {
301  // keep calibrator alive for gui but do not call again
302  return TIME2STEPS(86400);
303  }
304  return myFrequency;
305  }
306  // we are active
307  if (!myDidSpeedAdaption && myCurrentStateInterval->v >= 0) {
308  for (std::vector<MSLane*>::const_iterator i = myEdge->getLanes().begin(); i != myEdge->getLanes().end(); ++i) {
309  (*i)->setMaxSpeed(myCurrentStateInterval->v);
310  }
311  mySpeedIsDefault = false;
312  myDidSpeedAdaption = true;
313  }
314 
315  const bool calibrateFlow = myCurrentStateInterval->q >= 0;
316  const int totalWishedNum = totalWished();
317  int adaptedNum = passed() + myClearedInJam;
318 #ifdef MSCalibrator_DEBUG
319  std::cout << time2string(currentTime) << " " << myID
320  << " q=" << myCurrentStateInterval->q
321  << " totalWished=" << totalWishedNum
322  << " adapted=" << adaptedNum
323  << " jam=" << invalidJam(-1)
324  << " entered=" << myEdgeMeanData.nVehEntered
325  << " departed=" << myEdgeMeanData.nVehDeparted
326  << " arrived=" << myEdgeMeanData.nVehArrived
327  << " left=" << myEdgeMeanData.nVehLeft
328  << " waitSecs=" << myEdgeMeanData.waitSeconds
329  << " vaporized=" << myEdgeMeanData.nVehVaporized
330  << "\n";
331 #endif
332  if (calibrateFlow && adaptedNum < totalWishedNum && !hadRemovals) {
333  // we need to insert some vehicles
334  const SUMOReal hourFraction = STEPS2TIME(currentTime - myCurrentStateInterval->begin + DELTA_T) / (SUMOReal) 3600.;
335  const int wishedNum = (int)std::floor(myCurrentStateInterval->q * hourFraction + 0.5); // round to closest int
336  // only the difference between inflow and aspiredFlow should be added, thus
337  // we should not count vehicles vaporized from a jam here
338  // if we have enough time left we can add missing vehicles later
339  const int relaxedInsertion = (int)std::floor(STEPS2TIME(myCurrentStateInterval->end - currentTime) / 3);
340  const int insertionSlack = MAX2(0, adaptedNum + relaxedInsertion - totalWishedNum);
341  // increase number of vehicles
342 #ifdef MSCalibrator_DEBUG
343  std::cout
344  << " wished:" << wishedNum
345  << " slack:" << insertionSlack
346  << " before:" << adaptedNum
347  << "\n";
348 #endif
349  while (wishedNum > adaptedNum + insertionSlack) {
350  SUMOVehicleParameter* pars = myCurrentStateInterval->vehicleParameter;
351  const MSRoute* route = myProbe != 0 ? myProbe->getRoute() : 0;
352  if (route == 0) {
353  route = MSRoute::dictionary(pars->routeid);
354  }
355  if (route == 0) {
356  WRITE_WARNING("No valid routes in calibrator '" + myID + "'.");
357  break;
358  }
359  if (!route->contains(myEdge)) {
360  WRITE_WARNING("Route '" + route->getID() + "' in calibrator '" + myID + "' does not contain edge '" + myEdge->getID() + "'.");
361  break;
362  }
363  const unsigned int routeIndex = (unsigned int)std::distance(route->begin(),
364  std::find(route->begin(), route->end(), myEdge));
366  assert(route != 0 && vtype != 0);
367  // build the vehicle
368  SUMOVehicleParameter* newPars = new SUMOVehicleParameter(*pars);
369  newPars->id = myID + "." + toString((int)STEPS2TIME(myCurrentStateInterval->begin)) + "." + toString(myInserted);
370  newPars->depart = currentTime;
371  newPars->routeid = route->getID();
373  newPars, route, vtype));
374 #ifdef MSCalibrator_DEBUG
375  std::cout << " resetting route pos: " << routeIndex << "\n";
376 #endif
377  vehicle->resetRoutePosition(routeIndex);
378  if (myEdge->insertVehicle(*vehicle, currentTime)) {
379  vehicle->onDepart();
380  if (!MSNet::getInstance()->getVehicleControl().addVehicle(vehicle->getID(), vehicle)) {
381  throw ProcessError("Emission of vehicle '" + vehicle->getID() + "' in calibrator '" + getID() + "'failed!");
382  }
383  myInserted++;
384  adaptedNum++;
385 #ifdef MSCalibrator_DEBUG
386  std::cout << "I ";
387 #endif
388  } else {
389  // could not insert vehicle
390 #ifdef MSCalibrator_DEBUG
391  std::cout << "F ";
392 #endif
394  break;
395  }
396  }
397  }
398  if (myCurrentStateInterval->end <= currentTime + myFrequency) {
399  writeXMLOutput();
400  }
401  return myFrequency;
402 }
403 
404 void
407  for (std::vector<MSMeanData_Net::MSLaneMeanDataValues*>::iterator it = myLaneMeanData.begin(); it != myLaneMeanData.end(); ++it) {
408  (*it)->reset();
409  }
410 }
411 
412 
413 bool
414 MSCalibrator::invalidJam(int laneIndex) const {
415  if (laneIndex < 0) {
416  const int numLanes = (int)myEdge->getLanes().size();
417  for (int i = 0; i < numLanes; ++i) {
418  if (invalidJam(i)) {
419  return true;
420  }
421  }
422  return false;
423  }
424  assert(laneIndex < (int)myEdge->getLanes().size());
425  const MSLane* const lane = myEdge->getLanes()[laneIndex];
426  if (lane->getVehicleNumber() < 4) {
427  // cannot reliably detect invalid jams
428  return false;
429  }
430  // maxSpeed reflects the calibration target
431  const bool toSlow = lane->getMeanSpeed() < 0.5 * myEdge->getSpeedLimit();
432  return toSlow && remainingVehicleCapacity(laneIndex) < 1;
433 }
434 
435 
436 int
438  if (laneIndex < 0) {
439  const int numLanes = (int)myEdge->getLanes().size();
440  int result = 0;
441  for (int i = 0; i < numLanes; ++i) {
442  result = MAX2(result, remainingVehicleCapacity(i));
443  }
444  return result;
445  }
446  assert(laneIndex < (int)myEdge->getLanes().size());
447  MSLane* lane = myEdge->getLanes()[laneIndex];
448  MSVehicle* last = lane->getLastVehicle();
449  const SUMOVehicleParameter* pars = myCurrentStateInterval->vehicleParameter;
451  const SUMOReal spacePerVehicle = vtype->getLengthWithGap() + myEdge->getSpeedLimit() * vtype->getCarFollowModel().getHeadwayTime();
452  if (last == 0) {
453  // ensure vehicles can be inserted on short edges
454  return MAX2(1, (int)(myEdge->getLength() / spacePerVehicle));
455  } else {
456  return (int)(last->getPositionOnLane() / spacePerVehicle);
457  }
458 }
459 
460 
461 void
463  for (std::vector<MSMoveReminder*>::iterator it = LeftoverReminders.begin(); it != LeftoverReminders.end(); ++it) {
464  delete *it;
465  }
466  LeftoverReminders.clear();
467  for (std::vector<SUMOVehicleParameter*>::iterator it = LeftoverVehicleParameters.begin();
468  it != LeftoverVehicleParameters.end(); ++it) {
469  delete *it;
470  }
472 }
473 
474 
475 void
478  for (std::vector<MSMeanData_Net::MSLaneMeanDataValues*>::iterator it = myLaneMeanData.begin();
479  it != myLaneMeanData.end(); ++it) {
480  (*it)->addTo(myEdgeMeanData);
481  }
482 }
483 
485  if (myParent == 0) {
486  return false;
487  }
488  if (myParent->isActive()) {
490  const bool calibrateFlow = myParent->myCurrentStateInterval->q >= 0;
491  const int totalWishedNum = myParent->totalWished();
492  int adaptedNum = myParent->passed() + myParent->myClearedInJam;
493  MSVehicle* vehicle = dynamic_cast<MSVehicle*>(&veh);
494  if (calibrateFlow && adaptedNum > totalWishedNum) {
495 #ifdef MSCalibrator_DEBUG
496  std::cout << time2string(MSNet::getInstance()->getCurrentTimeStep()) << " " << myParent->getID()
497  << " vaporizing " << vehicle->getID() << " to reduce flow\n";
498 #endif
499  if (myParent->scheduleRemoval(vehicle)) {
500  myParent->myRemoved++;
501  }
502  } else if (myParent->invalidJam(myLaneIndex)) {
503 #ifdef MSCalibrator_DEBUG
504  std::cout << time2string(MSNet::getInstance()->getCurrentTimeStep()) << " " << myParent->getID()
505  << " vaporizing " << vehicle->getID() << " to clear jam\n";
506 #endif
508  WRITE_WARNING("Clearing jam at calibrator '" + myParent->myID + "' at time "
509  + time2string(MSNet::getInstance()->getCurrentTimeStep()));
511  }
512  if (myParent->scheduleRemoval(vehicle)) {
514  }
515  }
516  }
517  return true;
518 }
519 
520 
521 
522 /****************************************************************************/
523