Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
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-2026 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>
32
33//#define DEBUG_STOPPINGPLACE
34#define DEBUGCOND (veh.isSelected())
35//#define DEBUGCOND (true)
36
37
39MSStoppingPlaceRerouter::MSStoppingPlaceRerouter(std::string paramPrefix, bool checkValidity, StoppingPlaceParamMap_t addEvalParams, StoppingPlaceParamSwitchMap_t addInvertParams) :
40 myParamPrefix(paramPrefix), myCheckValidity(checkValidity) {
41 myEvalParams = { {"probability", 0.}, {"capacity", 0.}, {"timefrom", 0.}, {"timeto", 0.}, {"distancefrom", 0.}, {"distanceto", 1.}, {"absfreespace", 0.}, {"relfreespace", 0.}, };
42 myInvertParams = { {"probability", false}, { "capacity", true }, { "timefrom", false }, { "timeto", false }, { "distancefrom", false }, { "distanceto", false }, { "absfreespace", true }, { "relfreespace", true } };
43 for (auto param : addEvalParams) {
44 myEvalParams[param.first] = param.second;
45 myInvertParams[param.first] = (addInvertParams.count(param.first) > 0) ? addInvertParams[param.first] : false;
46 }
47 for (auto param : myEvalParams) {
48 myNormParams.insert({param.first, param.first != "probability"});
49 }
50}
51
53MSStoppingPlaceRerouter::rerouteStoppingPlace(MSStoppingPlace* destStoppingPlace, const std::vector<StoppingPlaceVisible>& stoppingPlaceCandidates, const std::vector<double>& probs, SUMOVehicle& veh, bool& newDestination, ConstMSEdgeVector& newRoute, StoppingPlaceParamMap_t& scores,
54 const Prohibitions& closedEdges, const int insertStopIndex, const bool keepCurrentStop) {
55 // Reroute destination from initial stopping place to an alternative stopping place
56 // if the following conditions are met:
57 // - next stop target is a stopping place of the right type
58 // - target is included in the current alternative set
59 // - target is visibly full
60 // Any stopping places that are visibly full at the current location are
61 // committed to the stopping place memory corresponding to their type
62
63 MSStoppingPlace* nearStoppingPlace = nullptr;
64
65 // get vehicle params
66 bool destVisible = false;
67 if (destStoppingPlace != nullptr) {
68 destVisible = (&destStoppingPlace->getLane().getEdge() == veh.getEdge());
69 // if the vehicle is on the destination stop edge it is always visible
70 for (auto stoppingPlace : stoppingPlaceCandidates) {
71 if (stoppingPlace.first == destStoppingPlace && stoppingPlace.second) {
72 destVisible = true;
73 break;
74 }
75 }
76 }
77 const MSRoute& route = veh.getRoute();
78
79 MSStoppingPlace* onTheWay = nullptr;
80 const int stopAnywhere = (int)getWeight(veh, "anywhere", -1);
81 const bool ignoreDest = getWeight(veh, "ignoreDest", destStoppingPlace != nullptr ? 0 : 1) != 0;
82 // check whether we are ready to accept any free stopping place along the
83 // way to our destination
84 if (stopAnywhere < 0 || stopAnywhere > getNumberStoppingPlaceReroutes(veh)) {
85 if (!destVisible) {
86 // cannot determine destination occupancy, only register visibly full
87 for (const StoppingPlaceVisible& stoppingPlace : stoppingPlaceCandidates) {
88 if (stoppingPlace.second && getLastStepStoppingPlaceOccupancy(stoppingPlace.first, &veh) >= getStoppingPlaceCapacity(stoppingPlace.first)) {
89 rememberStoppingPlaceScore(veh, stoppingPlace.first, "occupied");
90 rememberBlockedStoppingPlace(veh, stoppingPlace.first, &stoppingPlace.first->getLane().getEdge() == veh.getEdge());
91 }
92 }
93#ifdef DEBUG_STOPPINGPLACE
94 if (DEBUGCOND) {
95 //std::cout << SIMTIME << " veh=" << veh.getID() << " dest=" << ((destStoppingPlace == nullptr)? "null" : destStoppingPlace->getID()) << " stopAnywhere=" << stopAnywhere << " reroutes=" << getNumberStoppingPlaceReroutes(veh) << " stay on original route\n";
96 }
97#endif
98 }
99 } else {
100 double bestDist = std::numeric_limits<double>::max();
101 const double brakeGap = veh.getBrakeGap(true);
102 for (const StoppingPlaceVisible& item : stoppingPlaceCandidates) {
103 if (item.second) {
104 if (&item.first->getLane().getEdge() == veh.getEdge()
105 && getLastStepStoppingPlaceOccupancy(item.first, &veh) < getStoppingPlaceCapacity(item.first)) {
106 const double distToStart = item.first->getBeginLanePosition() - veh.getPositionOnLane();
107 const double distToEnd = item.first->getEndLanePosition() - veh.getPositionOnLane();
108 if (distToEnd > brakeGap) {
109 rememberStoppingPlaceScore(veh, item.first, "dist=" + toString(distToStart));
110 if (distToStart < bestDist) {
111 bestDist = distToStart;
112 onTheWay = item.first;
113 }
114 } else {
115 rememberStoppingPlaceScore(veh, item.first, "tooClose");
116 }
117 }
118 }
119 }
120#ifdef DEBUG_STOPPINGPLACE
121 if (DEBUGCOND) {
122 std::cout << SIMTIME << " veh=" << veh.getID()
123 << " dest=" << ((destStoppingPlace == nullptr) ? "null" : destStoppingPlace->getID()) << " stopAnywhere=" << stopAnywhere << " reroutes=" << getNumberStoppingPlaceReroutes(veh) << " alongTheWay=" << Named::getIDSecure(onTheWay) << "\n";
124 }
125#endif
126 }
127 if (!ignoreDest && !destVisible && onTheWay == nullptr) {
128 return nullptr;
129 }
130
131 const bool destIsFull = destStoppingPlace != nullptr && getLastStepStoppingPlaceOccupancy(destStoppingPlace, &veh) >= getStoppingPlaceCapacity(destStoppingPlace);
132 if (ignoreDest || destIsFull || onTheWay != nullptr) {
133 // if the current route ends at the stopping place, the new route will
134 // also end at the new stopping place
135 newDestination = (destStoppingPlace != nullptr && &destStoppingPlace->getLane().getEdge() == route.getLastEdge()
136 && veh.getArrivalPos() >= destStoppingPlace->getBeginLanePosition()
137 && veh.getArrivalPos() <= destStoppingPlace->getEndLanePosition()
138 && veh.getStops().size() == 1);
139
140#ifdef DEBUG_STOPPINGPLACE
141 if (DEBUGCOND) {
142 std::cout << SIMTIME << " veh=" << veh.getID()
143 << " newDest=" << newDestination
144 << " destIsFull=" << destIsFull
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();
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, &veh), 1, router, stoppingPlaces, newRoutes, stopApproaches, maxValues, scores, insertStopIndex, keepCurrentStop);
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 && destIsFull) {
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, &veh);
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, scores, insertStopIndex, keepCurrentStop)) {
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, scores, insertStopIndex, keepCurrentStop)) {
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, scores, insertStopIndex, keepCurrentStop)) {
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 }
362 // expose the scores of the best solution
363 if (nearStoppingPlace != nullptr) {
364 for (auto component : stoppingPlaces[nearStoppingPlace]) {
365 scores[component.first] = component.second;
366 }
367 }
369 } else {
370#ifdef DEBUG_STOPPINGPLACE
371 if (DEBUGCOND) {
372 std::cout << SIMTIME << " veh=" << veh.getID() << " dest=" << destStoppingPlace->getID() << " sufficient space\n";
373 }
374#endif
375 }
376
377#ifdef DEBUG_STOPPINGPLACE
378 if (DEBUGCOND) {
379 std::cout << " stoppingPlaceResult=" << Named::getIDSecure(nearStoppingPlace) << "\n";
380 }
381#endif
382 return nearStoppingPlace;
383}
384
385
386bool
387MSStoppingPlaceRerouter::evaluateDestination(SUMOVehicle& veh, double brakeGap, bool newDestination, MSStoppingPlace* alternative,
388 double occupancy, double prob, SUMOAbstractRouter<MSEdge, SUMOVehicle>& router, StoppingPlaceMap_t& stoppingPlaces,
389 std::map<MSStoppingPlace*, ConstMSEdgeVector>& newRoutes, std::map<MSStoppingPlace*, ConstMSEdgeVector>& stoppingPlaceApproaches,
390 StoppingPlaceParamMap_t& maxValues, StoppingPlaceParamMap_t& addInput, const int insertStopIndex, const bool keepCurrentStop) {
391
392 // a map stores the stopping place values
393 StoppingPlaceParamMap_t stoppingPlaceValues;
394 const SUMOTime now = SIMSTEP;
395
396 const MSRoute& route = veh.getRoute();
397 const RGBColor& c = route.getColor();
398 const MSEdge* stoppingPlaceEdge = &(alternative->getLane().getEdge());
399
400 const bool includeInternalLengths = MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks();
401
402 // Compute the route from the current edge to the stopping place edge
403 ConstMSEdgeVector edgesToStop;
404 ConstMSEdgeVector edgesUpstream;
405 const double targetPos = alternative->getLastFreePos(veh);
406 MSRouteIterator rerouteOriginIt = determineRerouteOrigin(veh, insertStopIndex);
407 double posOnLane = veh.getPositionOnLane();
408 if (insertStopIndex > 0) {
409 posOnLane = 0.;
410 // determine preceding edges
411 for (MSRouteIterator it = veh.getCurrentRouteEdge(); it != rerouteOriginIt; ++it) {
412 if (it != rerouteOriginIt) {
413 edgesUpstream.push_back(*it);
414 }
415 }
416 }
417 const MSEdge* rerouteOrigin = *rerouteOriginIt;
418 router.compute(rerouteOrigin, posOnLane, stoppingPlaceEdge, targetPos, &veh, now, edgesToStop, true);
419 if (edgesToStop.size() > 0) {
420 // Compute the route from the stopping place edge to the end of the route
421 if (insertStopIndex == 0 && rerouteOrigin != veh.getEdge()) {
422 edgesToStop.insert(edgesToStop.begin(), veh.getEdge());
423 }
424 // prepend preceding edges
425 std::reverse(edgesUpstream.begin(), edgesUpstream.end());
426 for (auto edge : edgesUpstream) {
427 edgesToStop.insert(edgesToStop.begin(), edge);
428 }
429 ConstMSEdgeVector edgesFromStop;
430 stoppingPlaceApproaches[alternative] = edgesToStop;
431
432 const MSEdge* nextDestination = route.getLastEdge();
433 double nextPos = veh.getArrivalPos();
434 int nextDestinationIndex = route.size() - 1;
435 if (!newDestination) {
436 std::vector<std::pair<int, double> > stopIndices = veh.getStopIndices();
437 int nextDestStopIndex = 1 + insertStopIndex;
438 if (!keepCurrentStop) {
439 nextDestStopIndex++;
440 }
441 if ((int)stopIndices.size() > nextDestStopIndex) {
442 nextDestinationIndex = stopIndices[nextDestStopIndex].first;
443 nextDestination = route.getEdges()[nextDestinationIndex];
444 nextPos = stopIndices[nextDestStopIndex].second;
445 }
446 router.compute(stoppingPlaceEdge, targetPos, nextDestination, nextPos, &veh, now, edgesFromStop, true);
447 }
448 if (edgesFromStop.size() > 0 || newDestination) {
449 stoppingPlaceValues["probability"] = prob;
450 if (stoppingPlaceValues["probability"] > maxValues["probability"]) {
451 maxValues["probability"] = stoppingPlaceValues["probability"];
452 }
453 stoppingPlaceValues["capacity"] = getStoppingPlaceCapacity(alternative);
454 stoppingPlaceValues["absfreespace"] = stoppingPlaceValues["capacity"] - occupancy;
455 // if capacity = 0 then absfreespace and relfreespace are also 0
456 stoppingPlaceValues["relfreespace"] = stoppingPlaceValues["absfreespace"] / MAX2(1.0, stoppingPlaceValues["capacity"]);
457 MSRoute routeToPark(route.getID() + "!to" + myParamPrefix + "#1", edgesToStop, false,
458 &c == &RGBColor::DEFAULT_COLOR ? nullptr : new RGBColor(c), route.getStops());
459
460 // The distance from the current edge to the new parking area
461 double toPos = alternative->getBeginLanePosition();
462 if (&alternative->getLane().getEdge() == veh.getEdge()) {
463 toPos = MAX2(veh.getPositionOnLane(), toPos);
464 }
465 stoppingPlaceValues["distanceto"] = routeToPark.getDistanceBetween(veh.getPositionOnLane(), toPos,
466 routeToPark.begin(), routeToPark.end() - 1, includeInternalLengths);
467
468 if (stoppingPlaceValues["distanceto"] == std::numeric_limits<double>::max()) {
469 WRITE_WARNINGF(TL("Invalid distance computation for vehicle '%' to stopping place '%' at time=%."),
470 veh.getID(), alternative->getID(), time2string(now));
471 }
472 const double endPos = alternative->getLastFreePos(veh, veh.getPositionOnLane() + brakeGap);
473 const double distToEnd = stoppingPlaceValues["distanceto"] - toPos + endPos;
474
475 if (distToEnd < brakeGap) {
476 rememberStoppingPlaceScore(veh, alternative, "tooClose");
477 return false;
478 }
479
480 // The time to reach the new stopping place
481 const double correctionLastEdge = ((alternative->getLane().getLength() - alternative->getEndLanePosition()) / alternative->getLane().getVehicleMaxSpeed(&veh));
482 const double correctionFirstEdge = veh.getPositionOnLane() / edgesToStop.front()->getVehicleMaxSpeed(&veh);
483
484 stoppingPlaceValues["timeto"] = router.recomputeCosts(edgesToStop, &veh, SIMSTEP) - correctionLastEdge - correctionFirstEdge;
485 ConstMSEdgeVector newEdges = edgesToStop;
486 if (newDestination) {
487 stoppingPlaceValues["distancefrom"] = 0;
488 stoppingPlaceValues["timefrom"] = 0;
489 } else {
490 MSRoute routeFromPark(route.getID() + "!from" + myParamPrefix + "#1", edgesFromStop, false,
491 &c == &RGBColor::DEFAULT_COLOR ? nullptr : new RGBColor(c), route.getStops());
492 // The distance from the new parking area to the end of the route
493 stoppingPlaceValues["distancefrom"] = routeFromPark.getDistanceBetween(alternative->getBeginLanePosition(), routeFromPark.getLastEdge()->getLength(),
494 routeFromPark.begin(), routeFromPark.end() - 1, includeInternalLengths);
495 if (stoppingPlaceValues["distancefrom"] == std::numeric_limits<double>::max()) {
496 WRITE_WARNINGF(TL("Invalid distance computation for vehicle '%' from stopping place '%' at time=%."),
497 veh.getID(), alternative->getID(), time2string(SIMSTEP));
498 }
499 // The time to reach this area
500 stoppingPlaceValues["timefrom"] = router.recomputeCosts(edgesFromStop, &veh, SIMSTEP) - (alternative->getEndLanePosition() / alternative->getLane().getSpeedLimit());
501 newEdges.insert(newEdges.end(), edgesFromStop.begin() + 1, edgesFromStop.end());
502 newEdges.insert(newEdges.end(), route.begin() + nextDestinationIndex + 1, route.end());
503 }
504
505 // add some additional/custom target function components
506 if (!evaluateCustomComponents(veh, brakeGap, newDestination, alternative, occupancy, prob, router, stoppingPlaceValues, stoppingPlaceApproaches[alternative], newEdges, maxValues, addInput)) {
507 return false;
508 }
509 if (!myCheckValidity || validComponentValues(stoppingPlaceValues)) {
510 updateMaxValues(stoppingPlaceValues, maxValues);
511 stoppingPlaces[alternative] = stoppingPlaceValues;
512 newRoutes[alternative] = newEdges;
513 return true;
514 } else {
515 return false;
516 }
517 } else {
518 rememberStoppingPlaceScore(veh, alternative, "unreachable");
519 }
520 } else {
521 rememberStoppingPlaceScore(veh, alternative, "unreachable");
522 }
523 // unreachable
524 return false;
525}
526
527
528bool
529MSStoppingPlaceRerouter::evaluateCustomComponents(SUMOVehicle& /*veh*/, double /*brakeGap*/, bool /*newDestination*/,
530 MSStoppingPlace* /*alternative*/, double /*occupancy*/, double /*prob*/, SUMOAbstractRouter<MSEdge, SUMOVehicle>& /*router*/,
531 StoppingPlaceParamMap_t& /*stoppingPlaceValues*/, ConstMSEdgeVector& /*newRoute*/, ConstMSEdgeVector& /*stoppingPlaceApproach*/,
532 StoppingPlaceParamMap_t& /*maxValues*/, StoppingPlaceParamMap_t& /*addInput*/) {
533 return true;
534}
535
536
537bool
539 return true;
540}
541
542
543bool
545 return true;
546}
547
548
551 return MSNet::getInstance()->getRouterTT(veh.getRNGIndex(), prohibited);
552}
553
554
558 myEvalParams["distanceto"] = getWeight(veh, "distance.weight", myEvalParams["distanceto"]);
559 for (auto evalParam : myEvalParams) {
560 result[evalParam.first] = getWeight(veh, evalParam.first + ".weight", evalParam.second);
561 }
562 result["probability"] = getWeight(veh, "probability.weight", 0.);
563 return result;
564}
565
566
567double
568MSStoppingPlaceRerouter::getWeight(SUMOVehicle& veh, const std::string param, const double defaultWeight, const bool warn) {
569 // get custom vehicle parameter
570 const std::string key = myParamPrefix + "." + param;
571 if (veh.getParameter().hasParameter(key)) {
572 try {
573 return StringUtils::toDouble(veh.getParameter().getParameter(key, "-1"));
574 } catch (...) {
575 WRITE_WARNINGF(TL("Invalid value '%' for vehicle parameter '%'"), veh.getParameter().getParameter(key, "-1"), key);
576 }
577 } else {
578 // get custom vType parameter
579 if (veh.getVehicleType().getParameter().hasParameter(key)) {
580 try {
582 } catch (...) {
583 WRITE_WARNINGF(TL("Invalid value '%' for vType parameter '%'"), veh.getVehicleType().getParameter().getParameter(key, "-1"), key);
584 }
585 }
586 }
587 if (warn) {
588 WRITE_MESSAGEF("Vehicle '%' does not supply vehicle parameter '%'. Using default of %\n", veh.getID(), key, toString(defaultWeight));
589 }
590 return defaultWeight;
591}
592
593
594void
596 for (auto it = maxValues.begin(); it != maxValues.end(); ++it) {
597 if (stoppingPlaceValues[it->first] > it->second) {
598 it->second = stoppingPlaceValues[it->first];
599 }
600 }
601}
602
603
604double
606 double cost = 0.;
607 for (StoppingPlaceParamMap_t::const_iterator sc = absValues.begin(); sc != absValues.end(); ++sc) {
608 double weight = weights.at(sc->first);
609 double val = sc->second;
610 if (norm.at(sc->first) && maxValues.at(sc->first) > 0.) {
611 val /= maxValues.at(sc->first);
612 }
613 cost += (invert.at(sc->first)) ? weight * (1. - val) : weight * val;
614 }
615 return cost;
616}
617
618
619/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:74
#define DEBUGCOND(PED)
ConstMSEdgeVector::const_iterator MSRouteIterator
Definition MSRoute.h:57
#define DEBUGCOND
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:287
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:289
#define TL(string)
Definition MsgHandler.h:304
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition SUMOTime.cpp:91
#define STEPS2TIME(x)
Definition SUMOTime.h:58
#define SIMSTEP
Definition SUMOTime.h:64
#define SIMTIME
Definition SUMOTime.h:65
#define TIME2STEPS(x)
Definition SUMOTime.h:60
T MIN2(T a, T b)
Definition StdDefs.h:80
T MAX2(T a, T b)
Definition StdDefs.h:86
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=gPrecision)
Definition ToString.h:289
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:46
A road/street connecting two junctions.
Definition MSEdge.h:77
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition MSGlobals.h:81
double getSpeedLimit() const
Returns the lane's maximum allowed speed.
Definition MSLane.h:603
double getLength() const
Returns the lane's length.
Definition MSLane.h:617
double getVehicleMaxSpeed(const SUMOTrafficObject *const veh) const
Returns the lane's maximum speed, given a vehicle's speed limit adaptation.
Definition MSLane.h:575
MSEdge & getEdge() const
Returns the lane's edge.
Definition MSLane.h:775
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:187
MSVehicleRouter & getRouterTT(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1615
bool hasInternalLinks() const
return whether the network contains internal links
Definition MSNet.h:798
int size() const
Returns the number of edges to pass.
Definition MSRoute.cpp:85
const ConstMSEdgeVector & getEdges() const
Definition MSRoute.h:128
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:402
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:318
const StopParVector & getStops() const
Returns the stops.
Definition MSRoute.cpp:411
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.
virtual 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 Prohibitions &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.
MSStoppingPlace * rerouteStoppingPlace(MSStoppingPlace *destStoppingPlace, const std::vector< StoppingPlaceVisible > &stoppingPlaceCandidates, const std::vector< double > &probs, SUMOVehicle &veh, bool &newDestination, ConstMSEdgeVector &newRoute, StoppingPlaceParamMap_t &scores, const Prohibitions &closedEdges={}, const int insertStopIndex=0, const bool keepCurrentStop=true)
main method to trigger the rerouting to the "best" StoppingPlace according to the custom evaluation f...
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...
const MSRouteIterator determineRerouteOrigin(SUMOVehicle &veh, int insertStopIndex)
Determine the rerouting origin edge (not necessarily the current edge of the vehicle!...
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
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
std::map< const MSEdge *, RouterProhibition > Prohibitions
virtual bool validComponentValues(StoppingPlaceParamMap_t &stoppingPlaceValues)
Whether the stopping place should be discarded due to its results from the component evaluation (allo...
virtual double getLastStepStoppingPlaceOccupancy(MSStoppingPlace *stoppingPlace, const SUMOVehicle *veh)=0
Return the number of occupied places of the StoppingPlace from the previous time step.
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.
virtual double getStoppingPlaceOccupancy(MSStoppingPlace *stoppingPlace, const SUMOVehicle *veh)=0
Return the number of occupied places of the StoppingPlace.
std::pair< MSStoppingPlace *, bool > StoppingPlaceVisible
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, const int insertStopIndex=0, const bool keepCurrentStop=true)
compute the target function for a single alternative
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:202
static double rand(SumoRNG *rng=nullptr)
Returns a random real number in [0, 1)
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 const MSVehicleType & getVehicleType() const =0
Returns the object's "vehicle" type.
virtual const MSLane * getLane() const =0
Returns the lane the object is currently at.
virtual int getRNGIndex() const =0
virtual const SUMOVehicleParameter & getParameter() const =0
Returns the vehicle's parameter (including departure definition)
virtual SumoRNG * getRNG() const =0
Returns the associated RNG for this object.
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:63
virtual const std::list< MSStop > & getStops() const =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)
virtual std::vector< std::pair< int, double > > getStopIndices() const =0
return list of route indices and stop positions for the remaining stops
virtual const ConstMSEdgeVector::const_iterator & getCurrentRouteEdge() const =0
Returns an iterator pointing to the current edge in this vehicles route.
virtual const MSRoute & getRoute() const =0
Returns the current route.
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter