Eclipse SUMO - Simulation of Urban MObility
MSStoppingPlaceRerouter.cpp
Go to the documentation of this file.
1 /****************************************************************************/
2 // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3 // Copyright (C) 2001-2024 German Aerospace Center (DLR) and others.
4 // This program and the accompanying materials are made available under the
5 // terms of the Eclipse Public License 2.0 which is available at
6 // https://www.eclipse.org/legal/epl-2.0/
7 // This Source Code may also be made available under the following Secondary
8 // Licenses when the conditions for such availability set forth in the Eclipse
9 // Public License 2.0 are satisfied: GNU General Public License, version 2
10 // or later which is available at
11 // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12 // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13 /****************************************************************************/
18 // The StoppingPlaceRerouter provides an interface to structure the rerouting
19 // to the best StoppingPlace according to the evaluation components and
20 // associated weights.
21 /****************************************************************************/
23 #include <microsim/MSEdge.h>
24 #include <microsim/MSGlobals.h>
25 #include <microsim/MSLane.h>
26 #include <microsim/MSRoute.h>
27 #include <microsim/MSParkingArea.h>
29 #include <microsim/MSVehicleType.h>
32 
33 #define DEBUGCOND (veh.isSelected())
34 
35 
37 MSStoppingPlaceRerouter::MSStoppingPlaceRerouter(SumoXMLTag stoppingType, std::string paramPrefix, bool checkValidity, bool checkVisibility, StoppingPlaceParamMap_t addEvalParams, StoppingPlaceParamSwitchMap_t addInvertParams) :
38  myStoppingType(stoppingType), myParamPrefix(paramPrefix), myCheckValidity(checkValidity), myConsiderDestVisibility(checkVisibility) {
39  myEvalParams = { {"probability", 0.}, {"capacity", 0.}, {"timefrom", 0.}, {"timeto", 0.}, {"distancefrom", 0.}, {"distanceto", 1.}, {"absfreespace", 0.}, {"relfreespace", 0.}, };
40  myInvertParams = { {"probability", false}, { "capacity", true }, { "timefrom", false }, { "timeto", false }, { "distancefrom", false }, { "distanceto", false }, { "absfreespace", true }, { "relfreespace", true } };
41  for (auto param : addEvalParams) {
42  myEvalParams[param.first] = param.second;
43  myInvertParams[param.first] = (addInvertParams.count(param.first) > 0) ? addInvertParams[param.first] : false;
44  }
45  for (auto param : myEvalParams) {
46  myNormParams.insert({param.first, param.first != "probability"});
47  }
48 }
49 
51 MSStoppingPlaceRerouter::reroute(std::vector<StoppingPlaceVisible>& stoppingPlaceCandidates, const std::vector<double>& probs, SUMOVehicle& veh, bool& newDestination, ConstMSEdgeVector& newRoute, StoppingPlaceParamMap_t& addInput, const MSEdgeVector& closedEdges) {
52  // Reroute destination from initial stopping place to an alternative stopping place
53  // if the following conditions are met:
54  // - next stop target is a stopping place of the right type
55  // - target is included in the current alternative set
56  // - target is visibly full
57  // Any stopping places that are visibly full at the current location are
58  // committed to the stopping place memory corresponding to their type
59 
60  MSStoppingPlace* nearStoppingPlace = nullptr;
61 
62  // get vehicle params
63  MSStoppingPlace* destStoppingPlace = nullptr;
64  bool destVisible = false;
66  destStoppingPlace = veh.getNextParkingArea();
67  if (destStoppingPlace == nullptr) {
68  // not driving towards the right type of stop
69  return nullptr;
70  }
71  destVisible = (&destStoppingPlace->getLane().getEdge() == veh.getEdge());
72  // if the vehicle is on the destination stop edge it is always visible
73  for (auto stoppingPlace : stoppingPlaceCandidates) {
74  if (stoppingPlace.first == destStoppingPlace && stoppingPlace.second) {
75  destVisible = true;
76  break;
77  }
78  }
79  }
80  const MSRoute& route = veh.getRoute();
81 
82  MSStoppingPlace* onTheWay = nullptr;
83  const int stopAnywhere = (int)getWeight(veh, "anywhere", -1);
84  // check whether we are ready to accept any free stopping place along the
85  // way to our destination
86  if (stopAnywhere < 0 || stopAnywhere > getNumberStoppingPlaceReroutes(veh)) {
87  if (!destVisible) {
88  // cannot determine destination occupancy, only register visibly full
89  for (const StoppingPlaceVisible& stoppingPlace : stoppingPlaceCandidates) {
90  if (stoppingPlace.second && getLastStepStoppingPlaceOccupancy(stoppingPlace.first) >= getStoppingPlaceCapacity(stoppingPlace.first)) {
91  rememberStoppingPlaceScore(veh, stoppingPlace.first, "occupied");
92  rememberBlockedStoppingPlace(veh, stoppingPlace.first, &stoppingPlace.first->getLane().getEdge() == veh.getEdge());
93  }
94  }
95 #ifdef DEBUG_STOPPINGPLACE
96  if (DEBUGCOND) {
97  //std::cout << SIMTIME << " << " veh=" << veh.getID()
98  // << " dest=" << ((destStoppingPlace == nullptr)? "null" : destStoppingPlace->getID()) << " stopAnywhere=" << stopAnywhere << "reroutes=" << getNumberStoppingPlaceReroutes(veh) << " stay on original route\n";
99  }
100 #endif
101  }
102  } else {
103  double bestDist = std::numeric_limits<double>::max();
104  const double brakeGap = veh.getBrakeGap(true);
105  for (StoppingPlaceVisible& item : stoppingPlaceCandidates) {
106  if (item.second) {
107  if (&item.first->getLane().getEdge() == veh.getEdge()
108  && getLastStepStoppingPlaceOccupancy(item.first) < getStoppingPlaceCapacity(item.first)) {
109  const double distToStart = item.first->getBeginLanePosition() - veh.getPositionOnLane();
110  const double distToEnd = item.first->getEndLanePosition() - veh.getPositionOnLane();
111  if (distToEnd > brakeGap) {
112  rememberStoppingPlaceScore(veh, item.first, "dist=" + toString(distToStart));
113  if (distToStart < bestDist) {
114  bestDist = distToStart;
115  onTheWay = item.first;
116  }
117  } else {
118  rememberStoppingPlaceScore(veh, item.first, "tooClose");
119  }
120  }
121  }
122  }
123 #ifdef DEBUG_STOPPINGPLACE
124  if (DEBUGCOND) {
125  std::cout << SIMTIME << " veh=" << veh.getID()
126  << " dest=" << ((destStoppingPlace == nullptr) ? "null" : destStoppingPlace->getID()) << " stopAnywhere=" << stopAnywhere << " reroutes=" << getNumberStoppingPlaceReroutes(veh) << " alongTheWay=" << Named::getIDSecure(onTheWay) << "\n";
127  }
128 #endif
129  }
130  if (myConsiderDestVisibility && !destVisible && onTheWay == nullptr) {
131  return nullptr;
132  }
133 
134  if (!myConsiderDestVisibility || getLastStepStoppingPlaceOccupancy(destStoppingPlace) >= getStoppingPlaceCapacity(destStoppingPlace) || onTheWay != nullptr) {
135  // if the current route ends at the stopping place, the new route will
136  // also end at the new stopping place
137  newDestination = (destStoppingPlace != nullptr && &destStoppingPlace->getLane().getEdge() == route.getLastEdge()
138  && veh.getArrivalPos() >= destStoppingPlace->getBeginLanePosition()
139  && veh.getArrivalPos() <= destStoppingPlace->getEndLanePosition());
140 
141 #ifdef DEBUG_STOPPINGPLACE
142  if (DEBUGCOND) {
143  std::cout << SIMTIME << " veh=" << veh.getID()
144  << " newDest=" << newDestination
145  << " onTheWay=" << Named::getIDSecure(onTheWay)
146  << "\n";
147  }
148 #endif
149  std::map<MSStoppingPlace*, ConstMSEdgeVector> newRoutes;
150  std::map<MSStoppingPlace*, ConstMSEdgeVector> stopApproaches;
151  StoppingPlaceParamMap_t weights = collectWeights(veh); // add option to patch values for interdependent values
152  StoppingPlaceParamMap_t maxValues;
153  for (auto param : weights) {
154  maxValues[param.first] = 0.;
155  }
156 
157  // a map stores elegible stopping places
158  StoppingPlaceMap_t stoppingPlaces;
159  SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = getRouter(veh, closedEdges);
160  const double brakeGap = veh.getBrakeGap(true);
161 
162  if (onTheWay != nullptr) {
163  // compute new route
164  if (newDestination) {
165  newRoute.push_back(veh.getEdge());
166  } else {
167  bool valid = evaluateDestination(veh, brakeGap, newDestination, onTheWay, getLastStepStoppingPlaceOccupancy(onTheWay), 1, router, stoppingPlaces, newRoutes, stopApproaches, maxValues, addInput);
168  if (!valid) {
169  WRITE_WARNINGF(TL("Stopping place '%' along the way cannot be used by vehicle '%' for unknown reason"), onTheWay->getID(), veh.getID());
170  return nullptr;
171  }
172  newRoute = newRoutes[onTheWay];
173  }
174  return onTheWay;
175  }
176  int numAlternatives = 0;
177  std::vector<std::tuple<SUMOTime, MSStoppingPlace*, int>> blockedTimes;
179 
180  if (destStoppingPlace != nullptr) {
181  rememberStoppingPlaceScore(veh, destStoppingPlace, "occupied");
182  rememberBlockedStoppingPlace(veh, destStoppingPlace, &destStoppingPlace->getLane().getEdge() == veh.getEdge());
183  }
184  const SUMOTime stoppingPlaceMemory = TIME2STEPS(getWeight(veh, "memory", 600));
185  const double stoppingPlaceFrustration = getWeight(veh, "frustration", 100);
186  const double stoppingPlaceKnowledge = getWeight(veh, "knowledge", 0);
187 
188  for (int i = 0; i < (int)stoppingPlaceCandidates.size(); ++i) {
189  // alternative occupancy is randomized (but never full) if invisible
190  // current destination must be visible at this point
191  if (!useStoppingPlace(stoppingPlaceCandidates[i].first)) {
192  continue;
193  }
194  const bool visible = stoppingPlaceCandidates[i].second || (stoppingPlaceCandidates[i].first == destStoppingPlace && destVisible);
195  double occupancy = getStoppingPlaceOccupancy(stoppingPlaceCandidates[i].first);
196  if (!visible && (stoppingPlaceKnowledge == 0 || stoppingPlaceKnowledge < RandHelper::rand(veh.getRNG()))) {
197  double capacity = getStoppingPlaceCapacity(stoppingPlaceCandidates[i].first);
198  const double minOccupancy = MIN2(capacity - NUMERICAL_EPS, (getNumberStoppingPlaceReroutes(veh) * capacity / stoppingPlaceFrustration));
199  occupancy = RandHelper::rand(minOccupancy, capacity);
200  // previously visited?
201  SUMOTime blockedTime = sawBlockedStoppingPlace(veh, stoppingPlaceCandidates[i].first, false);
202  if (blockedTime >= 0 && SIMSTEP - blockedTime < stoppingPlaceMemory) {
203  // assume it's still occupied
204  occupancy = capacity;
205  blockedTimes.push_back(std::make_tuple(blockedTime, stoppingPlaceCandidates[i].first, i));
206 #ifdef DEBUG_STOPPINGPLACE
207  if (DEBUGCOND) {
208  std::cout << " altStoppingPlace=" << stoppingPlaceCandidates[i].first->getID() << " was blocked at " << time2string(blockedTime) << "\n";
209  }
210 #endif
211  }
212  }
213  if (occupancy < getStoppingPlaceCapacity(stoppingPlaceCandidates[i].first)) {
214  if (evaluateDestination(veh, brakeGap, newDestination, stoppingPlaceCandidates[i].first, occupancy, probs[i], router, stoppingPlaces, newRoutes, stopApproaches, maxValues, addInput)) {
215  numAlternatives++;
216  }
217  } else if (visible) {
218  // might only be visible now (i.e. because it's on the other
219  // side of the street), so we should remember this for later.
220  rememberStoppingPlaceScore(veh, stoppingPlaceCandidates[i].first, "occupied");
221  rememberBlockedStoppingPlace(veh, stoppingPlaceCandidates[i].first, &stoppingPlaceCandidates[i].first->getLane().getEdge() == veh.getEdge());
222  }
223  }
224 
225  if (numAlternatives == 0) {
226  // use parkingArea with lowest blockedTime
227  std::sort(blockedTimes.begin(), blockedTimes.end(),
228  [](std::tuple<SUMOTime, MSStoppingPlace*, int> const & t1, std::tuple<SUMOTime, MSStoppingPlace*, int> const & t2) {
229  if (std::get<0>(t1) < std::get<0>(t2)) {
230  return true;
231  }
232  if (std::get<0>(t1) == std::get<0>(t2)) {
233  if (std::get<1>(t1)->getID() < std::get<1>(t2)->getID()) {
234  return true;
235  }
236  if (std::get<1>(t1)->getID() == std::get<1>(t2)->getID()) {
237  return std::get<2>(t1) < std::get<2>(t2);
238  }
239  }
240  return false;
241  }
242  );
243  for (auto item : blockedTimes) {
244  MSStoppingPlace* sp = std::get<1>(item);
245  double prob = probs[std::get<2>(item)];
246  // all stopping places are occupied. We have no good basis for
247  // prefering one or the other based on estimated occupancy
248  double occupancy = RandHelper::rand(getStoppingPlaceCapacity(sp));
249  if (evaluateDestination(veh, brakeGap, newDestination, sp, occupancy, prob, router, stoppingPlaces, newRoutes, stopApproaches, maxValues, addInput)) {
250 #ifdef DEBUG_STOPPINGPLACE
251  if (DEBUGCOND) {
252  std::cout << " altStoppingPlace=" << sp->getID() << " targeting occupied stopping place based on blockTime " << STEPS2TIME(std::get<0>(item)) << " among " << blockedTimes.size() << " alternatives\n";
253  }
254 #endif
255  numAlternatives = 1;
256  break;
257  }
258  //std::cout << " candidate=" << item.second->getID() << " observed=" << time2string(item.first) << "\n";
259  }
260  if (numAlternatives == 0) {
261  // take any random target but prefer one that hasn't been visited yet
262  std::vector<std::pair<SUMOTime, MSStoppingPlace*>> candidates;
263  for (const StoppingPlaceVisible& stoppingPlaceCandidate : stoppingPlaceCandidates) {
264  if (stoppingPlaceCandidate.first == destStoppingPlace) {
265  continue;
266  }
267  SUMOTime dummy = sawBlockedStoppingPlace(veh, stoppingPlaceCandidate.first, true);
268  if (dummy < 0) {
269  // randomize among the unvisited
270  dummy = -RandHelper::rand(1000000);
271  }
272  candidates.push_back(std::make_pair(dummy, stoppingPlaceCandidate.first));
273  }
274  std::sort(candidates.begin(), candidates.end(),
275  [](std::tuple<SUMOTime, MSStoppingPlace*> const & t1, std::tuple<SUMOTime, MSStoppingPlace*> const & t2) {
276  return std::get<0>(t1) < std::get<0>(t2) || (std::get<0>(t1) == std::get<0>(t2) && std::get<1>(t1)->getID() < std::get<1>(t2)->getID());
277  }
278  );
279  for (auto item : candidates) {
280  if (evaluateDestination(veh, brakeGap, newDestination, item.second, 0, 1, router, stoppingPlaces, newRoutes, stopApproaches, maxValues, addInput)) {
281 #ifdef DEBUG_STOPPINGPLACE
282  if (DEBUGCOND) {
283  std::cout << " altStoppingPlace=" << item.second->getID() << " targeting occupied stopping place (based on pure randomness) among " << candidates.size() << " alternatives\n";
284  }
285 #endif
286  numAlternatives = 1;
287  break;
288  }
289  }
290  }
291  }
292  getRouter(veh); // reset closed edges
293 
294 #ifdef DEBUG_STOPPINGPLACE
295  if (DEBUGCOND) {
296  std::cout << " maxValues=" << joinToString(maxValues, " ", ":") << "\n";
297  }
298 #endif
299 
300  // minimum cost to get the parking area
301  double minStoppingPlaceCost = 0.0;
302 
303  for (StoppingPlaceMap_t::iterator it = stoppingPlaces.begin(); it != stoppingPlaces.end(); ++it) {
304  // get the parking values
305  StoppingPlaceParamMap_t stoppingPlaceValues = it->second;
306 
307  if (weights["probability"] > 0. && maxValues["probability"] > 0.) {
308  // random search should not drive past a usable parking area
309  bool dominated = false;
310  double endPos = it->first->getEndLanePosition();
311  const ConstMSEdgeVector& to1 = stopApproaches[it->first];
312  assert(to1.size() > 0);
313  for (auto altSp : stoppingPlaces) {
314  if (altSp.first == it->first) {
315  continue;
316  }
317  const ConstMSEdgeVector& to2 = stopApproaches[altSp.first];
318  assert(to2.size() > 0);
319  if (to1.size() > to2.size()) {
320  if (std::equal(to2.begin(), to2.end(), to1.begin())) {
321  // other target lies on the route to the current candidate
322  dominated = true;
323  //std::cout << SIMTIME << " rrP veh=" << veh.getID() << " full=" << destParkArea->getID() << " cand=" << it->first->getID() << " onTheWay=" << altPa.first->getID() << "\n";
324  break;
325  }
326  } else if (to1 == to2 && endPos > altSp.first->getEndLanePosition()) {
327  // other target is on the same edge but ahead of the current candidate
328  dominated = true;
329  //std::cout << SIMTIME << " rrP veh=" << veh.getID() << " full=" << destParkArea->getID() << " cand=" << it->first->getID() << " sameEdge=" << altPa.first->getID() << "\n";
330  break;
331  }
332  }
333  double prob = 0;
334  if (!dominated) {
335  prob = RandHelper::rand(stoppingPlaceValues["probability"], veh.getRNG());
336  stoppingPlaceValues["probability"] = 1.0 - prob / maxValues["probability"];
337  } else {
338  // worst probability score
339  stoppingPlaceValues["probability"] = 1.0;
340  }
341  } else {
342  // value takes no effect due to weight=0
343  stoppingPlaceValues["probability"] = 0;
344  }
345 
346  // get the parking area cost
347  double stoppingPlaceCost = getTargetValue(stoppingPlaceValues, maxValues, weights, myNormParams, myInvertParams);
348  rememberStoppingPlaceScore(veh, it->first, toString(stoppingPlaceCost));
349 
350  // get the parking area with minimum cost
351  if (nearStoppingPlace == nullptr || stoppingPlaceCost < minStoppingPlaceCost) {
352  minStoppingPlaceCost = stoppingPlaceCost;
353  nearStoppingPlace = it->first;
354  newRoute = newRoutes[nearStoppingPlace];
355  }
356 #ifdef DEBUG_STOPPINGPLACE
357  if (DEBUGCOND) {
358  std::cout << " altStoppingPlace=" << it->first->getID() << " score=" << stoppingPlaceCost << " vals=" << joinToString(stoppingPlaceValues, " ", ":") << "\n";
359  }
360 #endif
361  }
363  } else {
364 #ifdef DEBUG_STOPPINGPLACE
365  if (DEBUGCOND) {
366  std::cout << SIMTIME << " veh=" << veh.getID() << " dest=" << destStoppingPlace->getID() << " sufficient space\n";
367  }
368 #endif
369  }
370 
371 #ifdef DEBUG_STOPPINGPLACE
372  if (DEBUGCOND) {
373  std::cout << " stoppingPlaceResult=" << Named::getIDSecure(nearStoppingPlace) << "\n";
374  }
375 #endif
376 
377  return nearStoppingPlace;
378 }
379 
380 
381 bool
382 MSStoppingPlaceRerouter::evaluateDestination(SUMOVehicle& veh, double brakeGap, bool newDestination, MSStoppingPlace* alternative,
383  double occupancy, double prob, SUMOAbstractRouter<MSEdge, SUMOVehicle>& router, StoppingPlaceMap_t& stoppingPlaces,
384  std::map<MSStoppingPlace*, ConstMSEdgeVector>& newRoutes, std::map<MSStoppingPlace*, ConstMSEdgeVector>& stoppingPlaceApproaches,
385  StoppingPlaceParamMap_t& maxValues, StoppingPlaceParamMap_t& addInput) {
386 
387  // a map stores the stopping place values
388  StoppingPlaceParamMap_t stoppingPlaceValues;
389  const SUMOTime now = SIMSTEP;
390 
391  const MSRoute& route = veh.getRoute();
392  const RGBColor& c = route.getColor();
393  const MSEdge* stoppingPlaceEdge = &(alternative->getLane().getEdge());
394 
395  const bool includeInternalLengths = MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks();
396 
397  // Compute the route from the current edge to the stopping place edge
398  ConstMSEdgeVector edgesToStop;
399  const double targetPos = alternative->getLastFreePos(veh);
400  const MSEdge* rerouteOrigin = *veh.getRerouteOrigin();
401  router.compute(rerouteOrigin, veh.getPositionOnLane(), stoppingPlaceEdge, targetPos, &veh, now, edgesToStop, true);
402 
403  if (edgesToStop.size() > 0) {
404  // Compute the route from the stopping place edge to the end of the route
405  if (rerouteOrigin != veh.getEdge()) {
406  edgesToStop.insert(edgesToStop.begin(), veh.getEdge());
407  }
408  ConstMSEdgeVector edgesFromStop;
409  stoppingPlaceApproaches[alternative] = edgesToStop;
410 
411  const MSEdge* nextDestination = route.getLastEdge();
412  double nextPos = veh.getArrivalPos();
413  int nextDestinationIndex = route.size() - 1;
414  if (!newDestination) {
415  std::vector<std::pair<int, double> > stopIndices = veh.getStopIndices();
416  if (stopIndices.size() > 1) {
417  nextDestinationIndex = stopIndices[1].first;
418  nextDestination = route.getEdges()[nextDestinationIndex];
419  nextPos = stopIndices[1].second;
420 
421  }
422  router.compute(stoppingPlaceEdge, targetPos, nextDestination, nextPos, &veh, now, edgesFromStop, true);
423  }
424  if (edgesFromStop.size() > 0 || newDestination) {
425  stoppingPlaceValues["probability"] = prob;
426  if (stoppingPlaceValues["probability"] > maxValues["probability"]) {
427  maxValues["probability"] = stoppingPlaceValues["probability"];
428  }
429  stoppingPlaceValues["capacity"] = getStoppingPlaceCapacity(alternative);
430  stoppingPlaceValues["absfreespace"] = stoppingPlaceValues["capacity"] - occupancy;
431  // if capacity = 0 then absfreespace and relfreespace are also 0
432  stoppingPlaceValues["relfreespace"] = stoppingPlaceValues["absfreespace"] / MAX2(1.0, stoppingPlaceValues["capacity"]);
433  MSRoute routeToPark(route.getID() + "!to" + myParamPrefix + "#1", edgesToStop, false,
434  &c == &RGBColor::DEFAULT_COLOR ? nullptr : new RGBColor(c), route.getStops());
435 
436  // The distance from the current edge to the new parking area
437  double toPos = alternative->getBeginLanePosition();
438  if (&alternative->getLane().getEdge() == veh.getEdge()) {
439  toPos = MAX2(veh.getPositionOnLane(), toPos);
440  }
441  stoppingPlaceValues["distanceto"] = routeToPark.getDistanceBetween(veh.getPositionOnLane(), toPos,
442  routeToPark.begin(), routeToPark.end() - 1, includeInternalLengths);
443 
444  if (stoppingPlaceValues["distanceto"] == std::numeric_limits<double>::max()) {
445  WRITE_WARNINGF(TL("Invalid distance computation for vehicle '%' to stopping place '%' at time=%."),
446  veh.getID(), alternative->getID(), time2string(now));
447  }
448  const double endPos = getStoppingPlaceOccupancy(alternative) == getStoppingPlaceCapacity(alternative)
449  ? alternative->getLastFreePos(veh, veh.getPositionOnLane() + brakeGap)
450  : alternative->getEndLanePosition();
451  const double distToEnd = stoppingPlaceValues["distanceto"] - toPos + endPos;
452 
453  if (distToEnd < brakeGap) {
454  rememberStoppingPlaceScore(veh, alternative, "tooClose");
455  return false;
456  }
457 
458  // The time to reach the new parking area
459  stoppingPlaceValues["timeto"] = router.recomputeCosts(edgesToStop, &veh, SIMSTEP);
460  ConstMSEdgeVector newEdges = edgesToStop;
461  if (newDestination) {
462  stoppingPlaceValues["distancefrom"] = 0;
463  stoppingPlaceValues["timefrom"] = 0;
464  } else {
465  MSRoute routeFromPark(route.getID() + "!from" + myParamPrefix + "#1", edgesFromStop, false,
466  &c == &RGBColor::DEFAULT_COLOR ? nullptr : new RGBColor(c), route.getStops());
467  // The distance from the new parking area to the end of the route
468  stoppingPlaceValues["distancefrom"] = routeFromPark.getDistanceBetween(alternative->getBeginLanePosition(), routeFromPark.getLastEdge()->getLength(),
469  routeFromPark.begin(), routeFromPark.end() - 1, includeInternalLengths);
470  if (stoppingPlaceValues["distancefrom"] == std::numeric_limits<double>::max()) {
471  WRITE_WARNINGF(TL("Invalid distance computation for vehicle '%' from stopping place '%' at time=%."),
472  veh.getID(), alternative->getID(), time2string(SIMSTEP));
473  }
474  // The time to reach this area
475  stoppingPlaceValues["timefrom"] = router.recomputeCosts(edgesFromStop, &veh, SIMSTEP);
476  newEdges.insert(newEdges.end(), edgesFromStop.begin() + 1, edgesFromStop.end());
477  newEdges.insert(newEdges.end(), route.begin() + nextDestinationIndex + 1, route.end());
478  }
479 
480  // add some additional/custom target function components
481  if (!evaluateCustomComponents(veh, brakeGap, newDestination, alternative, occupancy, prob, router, stoppingPlaceValues, stoppingPlaceApproaches[alternative], newEdges, maxValues, addInput)) {
482  return false;
483  }
484  if (!myCheckValidity || validComponentValues(stoppingPlaceValues)) {
485  updateMaxValues(stoppingPlaceValues, maxValues);
486  stoppingPlaces[alternative] = stoppingPlaceValues;
487  newRoutes[alternative] = newEdges;
488  return true;
489  } else {
490  return false;
491  }
492  } else {
493  rememberStoppingPlaceScore(veh, alternative, "unreachable");
494  }
495  } else {
496  rememberStoppingPlaceScore(veh, alternative, "unreachable");
497  }
498  // unreachable
499  return false;
500 }
501 
502 
503 bool
504 MSStoppingPlaceRerouter::evaluateCustomComponents(SUMOVehicle& /*veh*/, double /*brakeGap*/, bool /*newDestination*/,
505  MSStoppingPlace* /*alternative*/, double /*occupancy*/, double /*prob*/, SUMOAbstractRouter<MSEdge, SUMOVehicle>& /*router*/,
506  StoppingPlaceParamMap_t& /*stoppingPlaceValues*/, ConstMSEdgeVector& /*newRoute*/, ConstMSEdgeVector& /*stoppingPlaceApproach*/,
507  StoppingPlaceParamMap_t& /*maxValues*/, StoppingPlaceParamMap_t& /*addInput*/) {
508  return true;
509 }
510 
511 
512 bool
514  return true;
515 }
516 
517 
518 bool
520  return true;
521 }
522 
523 
526  return MSNet::getInstance()->getRouterTT(veh.getRNGIndex(), prohibited);
527 }
528 
529 
533  myEvalParams["distanceto"] = getWeight(veh, "distance.weight", myEvalParams["distanceto"]);
534  for (auto evalParam : myEvalParams) {
535  result[evalParam.first] = getWeight(veh, evalParam.first + ".weight", evalParam.second);
536  }
537  result["probability"] = getWeight(veh, "probability.weight", 0.);
538  return result;
539 }
540 
541 
542 double
543 MSStoppingPlaceRerouter::getWeight(SUMOVehicle& veh, const std::string param, const double defaultWeight, const bool warn) {
544  // get custom vehicle parameter
545  const std::string key = myParamPrefix + "." + param;
546  if (veh.getParameter().hasParameter(key)) {
547  try {
548  return StringUtils::toDouble(veh.getParameter().getParameter(key, "-1"));
549  } catch (...) {
550  WRITE_WARNINGF(TL("Invalid value '%' for vehicle parameter '%'"), veh.getParameter().getParameter(key, "-1"), key);
551  }
552  } else {
553  // get custom vType parameter
554  if (veh.getVehicleType().getParameter().hasParameter(key)) {
555  try {
557  } catch (...) {
558  WRITE_WARNINGF(TL("Invalid value '%' for vType parameter '%'"), veh.getVehicleType().getParameter().getParameter(key, "-1"), key);
559  }
560  }
561  }
562  if (warn) {
563  WRITE_MESSAGEF("Vehicle '%' does not supply vehicle parameter '%'. Using default of %\n", veh.getID(), key, toString(defaultWeight));
564  }
565  return defaultWeight;
566 }
567 
568 
569 void
571  for (auto it = maxValues.begin(); it != maxValues.end(); ++it) {
572  if (stoppingPlaceValues[it->first] > it->second) {
573  it->second = stoppingPlaceValues[it->first];
574  }
575  }
576 }
577 
578 
579 double
581  double cost = 0.;
582  for (StoppingPlaceParamMap_t::const_iterator sc = absValues.begin(); sc != absValues.end(); ++sc) {
583  double weight = weights.at(sc->first);
584  double val = sc->second;
585  if (norm.at(sc->first) && maxValues.at(sc->first) > 0.) {
586  val /= maxValues.at(sc->first);
587  }
588  cost += (invert.at(sc->first)) ? weight * (1. - val) : weight * val;
589  }
590  return cost;
591 }
long long int SUMOTime
Definition: GUI.h:35
std::vector< const MSEdge * > ConstMSEdgeVector
Definition: MSEdge.h:74
std::vector< MSEdge * > MSEdgeVector
Definition: MSEdge.h:73
#define DEBUGCOND
#define WRITE_WARNINGF(...)
Definition: MsgHandler.h:296
#define WRITE_MESSAGEF(...)
Definition: MsgHandler.h:298
#define TL(string)
Definition: MsgHandler.h:315
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition: SUMOTime.cpp:69
#define STEPS2TIME(x)
Definition: SUMOTime.h:55
#define SIMSTEP
Definition: SUMOTime.h:61
#define SIMTIME
Definition: SUMOTime.h:62
#define TIME2STEPS(x)
Definition: SUMOTime.h:57
SumoXMLTag
Numbers representing SUMO-XML - element names.
@ SUMO_TAG_PARKING_AREA
A parking area.
T MIN2(T a, T b)
Definition: StdDefs.h:76
T MAX2(T a, T b)
Definition: StdDefs.h:82
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=gPrecision)
Definition: ToString.h:283
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition: ToString.h:46
A road/street connecting two junctions.
Definition: MSEdge.h:77
double getLength() const
return the length of the edge
Definition: MSEdge.h:662
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition: MSGlobals.h:78
MSEdge & getEdge() const
Returns the lane's edge.
Definition: MSLane.h:756
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition: MSNet.cpp:183
MSVehicleRouter & getRouterTT(const int rngIndex, const MSEdgeVector &prohibited=MSEdgeVector()) const
Definition: MSNet.cpp:1469
bool hasInternalLinks() const
return whether the network contains internal links
Definition: MSNet.h:774
int size() const
Returns the number of edges to pass.
Definition: MSRoute.cpp:85
const std::vector< SUMOVehicleParameter::Stop > & getStops() const
Returns the stops.
Definition: MSRoute.cpp:404
MSRouteIterator end() const
Returns the end of the list of edges to pass.
Definition: MSRoute.cpp:79
const MSEdge * getLastEdge() const
returns the destination edge
Definition: MSRoute.cpp:91
const RGBColor & getColor() const
Returns the color.
Definition: MSRoute.cpp:395
MSRouteIterator begin() const
Returns the begin of the list of edges to pass.
Definition: MSRoute.cpp:73
double getDistanceBetween(double fromPos, double toPos, const MSLane *fromLane, const MSLane *toLane, int routePosition=0) const
Compute the distance between 2 given edges on this route, optionally including the length of internal...
Definition: MSRoute.cpp:311
const ConstMSEdgeVector & getEdges() const
Definition: MSRoute.h:124
A lane area vehicles can halt at.
double getBeginLanePosition() const
Returns the begin position of this stop.
double getEndLanePosition() const
Returns the end position of this stop.
const MSLane & getLane() const
Returns the lane this stop is located at.
double getLastFreePos(const SUMOVehicle &forVehicle, double brakePos=0) const
Returns the last free position on this stop.
virtual bool useStoppingPlace(MSStoppingPlace *stoppingPlace)
Whether the stopping place should be included in the search (can be used to add an additional filter)
virtual void rememberBlockedStoppingPlace(SUMOVehicle &veh, const MSStoppingPlace *stoppingPlace, bool blocked)=0
store the blocked stopping place in the vehicle
virtual SUMOTime sawBlockedStoppingPlace(SUMOVehicle &veh, MSStoppingPlace *place, bool local)=0
ask the vehicle when it has seen the stopping place
StoppingPlaceParamSwitchMap_t myNormParams
std::map< std::string, bool > StoppingPlaceParamSwitchMap_t
std::map< std::string, double > StoppingPlaceParamMap_t
static void updateMaxValues(StoppingPlaceParamMap_t &stoppingPlaceValues, StoppingPlaceParamMap_t &maxValues)
keep track of the maximum values of each component
virtual SUMOAbstractRouter< MSEdge, SUMOVehicle > & getRouter(SUMOVehicle &veh, const MSEdgeVector &prohibited={})
Provide the router to use (MSNet::getRouterTT or MSRoutingEngine)
std::map< MSStoppingPlace *, StoppingPlaceParamMap_t, ComparatorIdLess > StoppingPlaceMap_t
virtual int getNumberStoppingPlaceReroutes(SUMOVehicle &veh)=0
ask how many times already the vehicle has been rerouted to another stopping place
virtual double getStoppingPlaceCapacity(MSStoppingPlace *stoppingPlace)=0
Return the number of places the StoppingPlace provides.
static double getTargetValue(const StoppingPlaceParamMap_t &absValues, const StoppingPlaceParamMap_t &maxValues, const StoppingPlaceParamMap_t &weights, const StoppingPlaceParamSwitchMap_t &norm, const StoppingPlaceParamSwitchMap_t &invert)
compute the scalar target function value by means of a linear combination of all components/weights a...
virtual double getStoppingPlaceOccupancy(MSStoppingPlace *stoppingPlace)=0
Return the number of occupied places of the StoppingPlace.
double getWeight(SUMOVehicle &veh, const std::string param, const double defaultWeight, const bool warn=false)
read the value of a stopping place search param, e.g. a component weight factor
virtual StoppingPlaceParamMap_t collectWeights(SUMOVehicle &veh)
read target function weights for this vehicle
virtual bool evaluateDestination(SUMOVehicle &veh, double brakeGap, bool newDestination, MSStoppingPlace *alternative, double occupancy, double prob, SUMOAbstractRouter< MSEdge, SUMOVehicle > &router, StoppingPlaceMap_t &stoppingPlaces, std::map< MSStoppingPlace *, ConstMSEdgeVector > &newRoutes, std::map< MSStoppingPlace *, ConstMSEdgeVector > &stoppingPlaceApproaches, StoppingPlaceParamMap_t &maxValues, StoppingPlaceParamMap_t &addInput)
compute the target function for a single alternative
StoppingPlaceParamMap_t myEvalParams
StoppingPlaceParamSwitchMap_t myInvertParams
virtual void rememberStoppingPlaceScore(SUMOVehicle &veh, MSStoppingPlace *place, const std::string &score)=0
store the stopping place score in the vehicle
virtual void resetStoppingPlaceScores(SUMOVehicle &veh)=0
forget all stopping place score for this vehicle
virtual void setNumberStoppingPlaceReroutes(SUMOVehicle &veh, int value)=0
update the number of reroutes for the vehicle
virtual bool validComponentValues(StoppingPlaceParamMap_t &stoppingPlaceValues)
Whether the stopping place should be discarded due to its results from the component evaluation (allo...
virtual bool evaluateCustomComponents(SUMOVehicle &veh, double brakeGap, bool newDestination, MSStoppingPlace *alternative, double occupancy, double prob, SUMOAbstractRouter< MSEdge, SUMOVehicle > &router, StoppingPlaceParamMap_t &stoppingPlaceValues, ConstMSEdgeVector &newRoute, ConstMSEdgeVector &stoppingPlaceApproach, StoppingPlaceParamMap_t &maxValues, StoppingPlaceParamMap_t &addInput)
Compute some custom target function components.
MSStoppingPlace * reroute(std::vector< StoppingPlaceVisible > &stoppingPlaceCandidates, const std::vector< double > &probs, SUMOVehicle &veh, bool &newDestination, ConstMSEdgeVector &newRoute, StoppingPlaceParamMap_t &addInput, const MSEdgeVector &closedEdges={})
main method to trigger the rerouting to the "best" StoppingPlace according to the custom evaluation f...
std::pair< MSStoppingPlace *, bool > StoppingPlaceVisible
virtual double getLastStepStoppingPlaceOccupancy(MSStoppingPlace *stoppingPlace)=0
Return the number of occupied places of the StoppingPlace from the previous time step.
MSStoppingPlaceRerouter()=delete
Constructor.
const SUMOVTypeParameter & getParameter() const
static std::string getIDSecure(const T *obj, const std::string &fallBack="NULL")
get an identifier for Named-like object which may be Null
Definition: Named.h:67
const std::string & getID() const
Returns the id.
Definition: Named.h:74
bool hasParameter(const std::string &key) const
Returns whether the parameter is set.
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
static const RGBColor DEFAULT_COLOR
The default color (for vehicle types and vehicles)
Definition: RGBColor.h:199
static double rand(SumoRNG *rng=nullptr)
Returns a random real number in [0, 1)
Definition: RandHelper.cpp:94
virtual bool compute(const E *from, const E *to, const V *const vehicle, SUMOTime msTime, std::vector< const E * > &into, bool silent=false)=0
Builds the route between the given edges using the minimum effort at the given time The definition of...
virtual double recomputeCosts(const std::vector< const E * > &edges, const V *const v, SUMOTime msTime, double *lengthp=nullptr) const
virtual int getRNGIndex() const =0
virtual SumoRNG * getRNG() const =0
Returns the associated RNG for this object.
virtual const MSVehicleType & getVehicleType() const =0
Returns the object's "vehicle" type.
virtual const SUMOVehicleParameter & getParameter() const =0
Returns the vehicle's parameter (including departure definition)
virtual const MSLane * getLane() const =0
Returns the lane the object is currently at.
virtual const MSEdge * getEdge() const =0
Returns the edge the object is currently at.
virtual double getPositionOnLane() const =0
Get the object's position along the lane.
Representation of a vehicle.
Definition: SUMOVehicle.h:61
virtual ConstMSEdgeVector::const_iterator getRerouteOrigin() const =0
Returns the starting point for reroutes (usually the current edge)
virtual std::vector< std::pair< int, double > > getStopIndices() const =0
return list of route indices and stop positions for the remaining stops
virtual const MSRoute & getRoute() const =0
Returns the current route.
virtual MSParkingArea * getNextParkingArea()=0
virtual double getArrivalPos() const =0
Returns this vehicle's desired arrivalPos for its current route (may change on reroute)
virtual double getBrakeGap(bool delayed=false) const =0
get distance for coming to a stop (used for rerouting checks)
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter