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-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>
32
33#define DEBUGCOND (veh.isSelected())
34
35
37MSStoppingPlaceRerouter::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
51MSStoppingPlaceRerouter::reroute(std::vector<StoppingPlaceVisible>& stoppingPlaceCandidates, const std::vector<double>& probs, SUMOVehicle& veh, bool& newDestination, ConstMSEdgeVector& newRoute, StoppingPlaceParamMap_t& scores,
52 const MSEdgeVector& closedEdges, const int insertStopIndex, const bool keepCurrentStop) {
53 // Reroute destination from initial stopping place to an alternative stopping place
54 // if the following conditions are met:
55 // - next stop target is a stopping place of the right type
56 // - target is included in the current alternative set
57 // - target is visibly full
58 // Any stopping places that are visibly full at the current location are
59 // committed to the stopping place memory corresponding to their type
60
61 MSStoppingPlace* nearStoppingPlace = nullptr;
62
63 // get vehicle params
64 MSStoppingPlace* destStoppingPlace = nullptr;
65 bool destVisible = false;
67 destStoppingPlace = veh.getNextParkingArea();
68 if (destStoppingPlace == nullptr) {
69 // not driving towards the right type of stop
70 return nullptr;
71 }
72 destVisible = (&destStoppingPlace->getLane().getEdge() == veh.getEdge());
73 // if the vehicle is on the destination stop edge it is always visible
74 for (auto stoppingPlace : stoppingPlaceCandidates) {
75 if (stoppingPlace.first == destStoppingPlace && stoppingPlace.second) {
76 destVisible = true;
77 break;
78 }
79 }
80 }
81 const MSRoute& route = veh.getRoute();
82
83 MSStoppingPlace* onTheWay = nullptr;
84 const int stopAnywhere = (int)getWeight(veh, "anywhere", -1);
85 // check whether we are ready to accept any free stopping place along the
86 // way to our destination
87 if (stopAnywhere < 0 || stopAnywhere > getNumberStoppingPlaceReroutes(veh)) {
88 if (!destVisible) {
89 // cannot determine destination occupancy, only register visibly full
90 for (const StoppingPlaceVisible& stoppingPlace : stoppingPlaceCandidates) {
91 if (stoppingPlace.second && getLastStepStoppingPlaceOccupancy(stoppingPlace.first) >= getStoppingPlaceCapacity(stoppingPlace.first)) {
92 rememberStoppingPlaceScore(veh, stoppingPlace.first, "occupied");
93 rememberBlockedStoppingPlace(veh, stoppingPlace.first, &stoppingPlace.first->getLane().getEdge() == veh.getEdge());
94 }
95 }
96#ifdef DEBUG_STOPPINGPLACE
97 if (DEBUGCOND) {
98 //std::cout << SIMTIME << " << " veh=" << veh.getID()
99 // << " dest=" << ((destStoppingPlace == nullptr)? "null" : destStoppingPlace->getID()) << " stopAnywhere=" << stopAnywhere << "reroutes=" << getNumberStoppingPlaceReroutes(veh) << " stay on original route\n";
100 }
101#endif
102 }
103 } else {
104 double bestDist = std::numeric_limits<double>::max();
105 const double brakeGap = veh.getBrakeGap(true);
106 for (StoppingPlaceVisible& item : stoppingPlaceCandidates) {
107 if (item.second) {
108 if (&item.first->getLane().getEdge() == veh.getEdge()
109 && getLastStepStoppingPlaceOccupancy(item.first) < getStoppingPlaceCapacity(item.first)) {
110 const double distToStart = item.first->getBeginLanePosition() - veh.getPositionOnLane();
111 const double distToEnd = item.first->getEndLanePosition() - veh.getPositionOnLane();
112 if (distToEnd > brakeGap) {
113 rememberStoppingPlaceScore(veh, item.first, "dist=" + toString(distToStart));
114 if (distToStart < bestDist) {
115 bestDist = distToStart;
116 onTheWay = item.first;
117 }
118 } else {
119 rememberStoppingPlaceScore(veh, item.first, "tooClose");
120 }
121 }
122 }
123 }
124#ifdef DEBUG_STOPPINGPLACE
125 if (DEBUGCOND) {
126 std::cout << SIMTIME << " veh=" << veh.getID()
127 << " dest=" << ((destStoppingPlace == nullptr) ? "null" : destStoppingPlace->getID()) << " stopAnywhere=" << stopAnywhere << " reroutes=" << getNumberStoppingPlaceReroutes(veh) << " alongTheWay=" << Named::getIDSecure(onTheWay) << "\n";
128 }
129#endif
130 }
131 if (myConsiderDestVisibility && !destVisible && onTheWay == nullptr) {
132 return nullptr;
133 }
134
135 if (!myConsiderDestVisibility || getLastStepStoppingPlaceOccupancy(destStoppingPlace) >= getStoppingPlaceCapacity(destStoppingPlace) || onTheWay != nullptr) {
136 // if the current route ends at the stopping place, the new route will
137 // also end at the new stopping place
138 newDestination = (destStoppingPlace != nullptr && &destStoppingPlace->getLane().getEdge() == route.getLastEdge()
139 && veh.getArrivalPos() >= destStoppingPlace->getBeginLanePosition()
140 && veh.getArrivalPos() <= destStoppingPlace->getEndLanePosition()
141 && veh.getStops().size() == 1);
142
143#ifdef DEBUG_STOPPINGPLACE
144 if (DEBUGCOND) {
145 std::cout << SIMTIME << " veh=" << veh.getID()
146 << " newDest=" << newDestination
147 << " onTheWay=" << Named::getIDSecure(onTheWay)
148 << "\n";
149 }
150#endif
151 std::map<MSStoppingPlace*, ConstMSEdgeVector> newRoutes;
152 std::map<MSStoppingPlace*, ConstMSEdgeVector> stopApproaches;
153 StoppingPlaceParamMap_t weights = collectWeights(veh); // add option to patch values for interdependent values
154 StoppingPlaceParamMap_t maxValues;
155 for (auto param : weights) {
156 maxValues[param.first] = 0.;
157 }
158
159 // a map stores elegible stopping places
160 StoppingPlaceMap_t stoppingPlaces;
161 SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = getRouter(veh, closedEdges);
162 const double brakeGap = veh.getBrakeGap(true);
163
164 if (onTheWay != nullptr) {
165 // compute new route
166 if (newDestination) {
167 newRoute.push_back(veh.getEdge());
168 } else {
169 bool valid = evaluateDestination(veh, brakeGap, newDestination, onTheWay, getLastStepStoppingPlaceOccupancy(onTheWay), 1, router, stoppingPlaces, newRoutes, stopApproaches, maxValues, scores, insertStopIndex, keepCurrentStop);
170 if (!valid) {
171 WRITE_WARNINGF(TL("Stopping place '%' along the way cannot be used by vehicle '%' for unknown reason"), onTheWay->getID(), veh.getID());
172 return nullptr;
173 }
174 newRoute = newRoutes[onTheWay];
175 }
176 return onTheWay;
177 }
178 int numAlternatives = 0;
179 std::vector<std::tuple<SUMOTime, MSStoppingPlace*, int>> blockedTimes;
181
182 if (destStoppingPlace != nullptr) {
183 rememberStoppingPlaceScore(veh, destStoppingPlace, "occupied");
184 rememberBlockedStoppingPlace(veh, destStoppingPlace, &destStoppingPlace->getLane().getEdge() == veh.getEdge());
185 }
186 const SUMOTime stoppingPlaceMemory = TIME2STEPS(getWeight(veh, "memory", 600));
187 const double stoppingPlaceFrustration = getWeight(veh, "frustration", 100);
188 const double stoppingPlaceKnowledge = getWeight(veh, "knowledge", 0);
189
190 for (int i = 0; i < (int)stoppingPlaceCandidates.size(); ++i) {
191 // alternative occupancy is randomized (but never full) if invisible
192 // current destination must be visible at this point
193 if (!useStoppingPlace(stoppingPlaceCandidates[i].first)) {
194 continue;
195 }
196 const bool visible = stoppingPlaceCandidates[i].second || (stoppingPlaceCandidates[i].first == destStoppingPlace && destVisible);
197 double occupancy = getStoppingPlaceOccupancy(stoppingPlaceCandidates[i].first);
198 if (!visible && (stoppingPlaceKnowledge == 0 || stoppingPlaceKnowledge < RandHelper::rand(veh.getRNG()))) {
199 double capacity = getStoppingPlaceCapacity(stoppingPlaceCandidates[i].first);
200 const double minOccupancy = MIN2(capacity - NUMERICAL_EPS, (getNumberStoppingPlaceReroutes(veh) * capacity / stoppingPlaceFrustration));
201 occupancy = RandHelper::rand(minOccupancy, capacity);
202 // previously visited?
203 SUMOTime blockedTime = sawBlockedStoppingPlace(veh, stoppingPlaceCandidates[i].first, false);
204 if (blockedTime >= 0 && SIMSTEP - blockedTime < stoppingPlaceMemory) {
205 // assume it's still occupied
206 occupancy = capacity;
207 blockedTimes.push_back(std::make_tuple(blockedTime, stoppingPlaceCandidates[i].first, i));
208#ifdef DEBUG_STOPPINGPLACE
209 if (DEBUGCOND) {
210 std::cout << " altStoppingPlace=" << stoppingPlaceCandidates[i].first->getID() << " was blocked at " << time2string(blockedTime) << "\n";
211 }
212#endif
213 }
214 }
215 if (occupancy < getStoppingPlaceCapacity(stoppingPlaceCandidates[i].first)) {
216 if (evaluateDestination(veh, brakeGap, newDestination, stoppingPlaceCandidates[i].first, occupancy, probs[i], router, stoppingPlaces, newRoutes, stopApproaches, maxValues, scores, insertStopIndex, keepCurrentStop)) {
217 numAlternatives++;
218 }
219 } else if (visible) {
220 // might only be visible now (i.e. because it's on the other
221 // side of the street), so we should remember this for later.
222 rememberStoppingPlaceScore(veh, stoppingPlaceCandidates[i].first, "occupied");
223 rememberBlockedStoppingPlace(veh, stoppingPlaceCandidates[i].first, &stoppingPlaceCandidates[i].first->getLane().getEdge() == veh.getEdge());
224 }
225 }
226
227 if (numAlternatives == 0) {
228 // use parkingArea with lowest blockedTime
229 std::sort(blockedTimes.begin(), blockedTimes.end(),
230 [](std::tuple<SUMOTime, MSStoppingPlace*, int> const & t1, std::tuple<SUMOTime, MSStoppingPlace*, int> const & t2) {
231 if (std::get<0>(t1) < std::get<0>(t2)) {
232 return true;
233 }
234 if (std::get<0>(t1) == std::get<0>(t2)) {
235 if (std::get<1>(t1)->getID() < std::get<1>(t2)->getID()) {
236 return true;
237 }
238 if (std::get<1>(t1)->getID() == std::get<1>(t2)->getID()) {
239 return std::get<2>(t1) < std::get<2>(t2);
240 }
241 }
242 return false;
243 }
244 );
245 for (auto item : blockedTimes) {
246 MSStoppingPlace* sp = std::get<1>(item);
247 double prob = probs[std::get<2>(item)];
248 // all stopping places are occupied. We have no good basis for
249 // prefering one or the other based on estimated occupancy
250 double occupancy = RandHelper::rand(getStoppingPlaceCapacity(sp));
251 if (evaluateDestination(veh, brakeGap, newDestination, sp, occupancy, prob, router, stoppingPlaces, newRoutes, stopApproaches, maxValues, scores, insertStopIndex, keepCurrentStop)) {
252#ifdef DEBUG_STOPPINGPLACE
253 if (DEBUGCOND) {
254 std::cout << " altStoppingPlace=" << sp->getID() << " targeting occupied stopping place based on blockTime " << STEPS2TIME(std::get<0>(item)) << " among " << blockedTimes.size() << " alternatives\n";
255 }
256#endif
257 numAlternatives = 1;
258 break;
259 }
260 //std::cout << " candidate=" << item.second->getID() << " observed=" << time2string(item.first) << "\n";
261 }
262 if (numAlternatives == 0) {
263 // take any random target but prefer one that hasn't been visited yet
264 std::vector<std::pair<SUMOTime, MSStoppingPlace*>> candidates;
265 for (const StoppingPlaceVisible& stoppingPlaceCandidate : stoppingPlaceCandidates) {
266 if (stoppingPlaceCandidate.first == destStoppingPlace) {
267 continue;
268 }
269 SUMOTime dummy = sawBlockedStoppingPlace(veh, stoppingPlaceCandidate.first, true);
270 if (dummy < 0) {
271 // randomize among the unvisited
272 dummy = -RandHelper::rand(1000000);
273 }
274 candidates.push_back(std::make_pair(dummy, stoppingPlaceCandidate.first));
275 }
276 std::sort(candidates.begin(), candidates.end(),
277 [](std::tuple<SUMOTime, MSStoppingPlace*> const & t1, std::tuple<SUMOTime, MSStoppingPlace*> const & t2) {
278 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());
279 }
280 );
281 for (auto item : candidates) {
282 if (evaluateDestination(veh, brakeGap, newDestination, item.second, 0, 1, router, stoppingPlaces, newRoutes, stopApproaches, maxValues, scores, insertStopIndex, keepCurrentStop)) {
283#ifdef DEBUG_STOPPINGPLACE
284 if (DEBUGCOND) {
285 std::cout << " altStoppingPlace=" << item.second->getID() << " targeting occupied stopping place (based on pure randomness) among " << candidates.size() << " alternatives\n";
286 }
287#endif
288 numAlternatives = 1;
289 break;
290 }
291 }
292 }
293 }
294 getRouter(veh); // reset closed edges
295
296#ifdef DEBUG_STOPPINGPLACE
297 if (DEBUGCOND) {
298 std::cout << " maxValues=" << joinToString(maxValues, " ", ":") << "\n";
299 }
300#endif
301
302 // minimum cost to get the parking area
303 double minStoppingPlaceCost = 0.0;
304
305 for (StoppingPlaceMap_t::iterator it = stoppingPlaces.begin(); it != stoppingPlaces.end(); ++it) {
306 // get the parking values
307 StoppingPlaceParamMap_t stoppingPlaceValues = it->second;
308
309 if (weights["probability"] > 0. && maxValues["probability"] > 0.) {
310 // random search should not drive past a usable parking area
311 bool dominated = false;
312 double endPos = it->first->getEndLanePosition();
313 const ConstMSEdgeVector& to1 = stopApproaches[it->first];
314 assert(to1.size() > 0);
315 for (auto altSp : stoppingPlaces) {
316 if (altSp.first == it->first) {
317 continue;
318 }
319 const ConstMSEdgeVector& to2 = stopApproaches[altSp.first];
320 assert(to2.size() > 0);
321 if (to1.size() > to2.size()) {
322 if (std::equal(to2.begin(), to2.end(), to1.begin())) {
323 // other target lies on the route to the current candidate
324 dominated = true;
325 //std::cout << SIMTIME << " rrP veh=" << veh.getID() << " full=" << destParkArea->getID() << " cand=" << it->first->getID() << " onTheWay=" << altPa.first->getID() << "\n";
326 break;
327 }
328 } else if (to1 == to2 && endPos > altSp.first->getEndLanePosition()) {
329 // other target is on the same edge but ahead of the current candidate
330 dominated = true;
331 //std::cout << SIMTIME << " rrP veh=" << veh.getID() << " full=" << destParkArea->getID() << " cand=" << it->first->getID() << " sameEdge=" << altPa.first->getID() << "\n";
332 break;
333 }
334 }
335 double prob = 0;
336 if (!dominated) {
337 prob = RandHelper::rand(stoppingPlaceValues["probability"], veh.getRNG());
338 stoppingPlaceValues["probability"] = 1.0 - prob / maxValues["probability"];
339 } else {
340 // worst probability score
341 stoppingPlaceValues["probability"] = 1.0;
342 }
343 } else {
344 // value takes no effect due to weight=0
345 stoppingPlaceValues["probability"] = 0;
346 }
347
348 // get the parking area cost
349 double stoppingPlaceCost = getTargetValue(stoppingPlaceValues, maxValues, weights, myNormParams, myInvertParams);
350 rememberStoppingPlaceScore(veh, it->first, toString(stoppingPlaceCost));
351
352 // get the parking area with minimum cost
353 if (nearStoppingPlace == nullptr || stoppingPlaceCost < minStoppingPlaceCost) {
354 minStoppingPlaceCost = stoppingPlaceCost;
355 nearStoppingPlace = it->first;
356 newRoute = newRoutes[nearStoppingPlace];
357 }
358#ifdef DEBUG_STOPPINGPLACE
359 if (DEBUGCOND) {
360 std::cout << " altStoppingPlace=" << it->first->getID() << " score=" << stoppingPlaceCost << " vals=" << joinToString(stoppingPlaceValues, " ", ":") << "\n";
361 }
362#endif
363 }
364 // expose the scores of the best solution
365 if (nearStoppingPlace != nullptr) {
366 for (auto component : stoppingPlaces[nearStoppingPlace]) {
367 scores[component.first] = component.second;
368 }
369 }
371 } else {
372#ifdef DEBUG_STOPPINGPLACE
373 if (DEBUGCOND) {
374 std::cout << SIMTIME << " veh=" << veh.getID() << " dest=" << destStoppingPlace->getID() << " sufficient space\n";
375 }
376#endif
377 }
378
379#ifdef DEBUG_STOPPINGPLACE
380 if (DEBUGCOND) {
381 std::cout << " stoppingPlaceResult=" << Named::getIDSecure(nearStoppingPlace) << "\n";
382 }
383#endif
384 return nearStoppingPlace;
385}
386
387
388bool
389MSStoppingPlaceRerouter::evaluateDestination(SUMOVehicle& veh, double brakeGap, bool newDestination, MSStoppingPlace* alternative,
390 double occupancy, double prob, SUMOAbstractRouter<MSEdge, SUMOVehicle>& router, StoppingPlaceMap_t& stoppingPlaces,
391 std::map<MSStoppingPlace*, ConstMSEdgeVector>& newRoutes, std::map<MSStoppingPlace*, ConstMSEdgeVector>& stoppingPlaceApproaches,
392 StoppingPlaceParamMap_t& maxValues, StoppingPlaceParamMap_t& addInput, const int insertStopIndex, const bool keepCurrentStop) {
393
394 // a map stores the stopping place values
395 StoppingPlaceParamMap_t stoppingPlaceValues;
396 const SUMOTime now = SIMSTEP;
397
398 const MSRoute& route = veh.getRoute();
399 const RGBColor& c = route.getColor();
400 const MSEdge* stoppingPlaceEdge = &(alternative->getLane().getEdge());
401
402 const bool includeInternalLengths = MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks();
403
404 // Compute the route from the current edge to the stopping place edge
405 ConstMSEdgeVector edgesToStop;
406 ConstMSEdgeVector edgesUpstream;
407 const double targetPos = alternative->getLastFreePos(veh);
408 MSRouteIterator rerouteOriginIt = determineRerouteOrigin(veh, insertStopIndex);
409 double posOnLane = veh.getPositionOnLane();
410 if (insertStopIndex > 0) {
411 posOnLane = 0.;
412 // determine preceding edges
413 for (MSRouteIterator it = veh.getCurrentRouteEdge(); it != rerouteOriginIt; ++it) {
414 if (it != rerouteOriginIt) {
415 edgesUpstream.push_back(*it);
416 }
417 }
418 }
419 const MSEdge* rerouteOrigin = *rerouteOriginIt;
420 router.compute(rerouteOrigin, posOnLane, stoppingPlaceEdge, targetPos, &veh, now, edgesToStop, true);
421 if (edgesToStop.size() > 0) {
422 // Compute the route from the stopping place edge to the end of the route
423 if (insertStopIndex == 0 && rerouteOrigin != veh.getEdge()) {
424 edgesToStop.insert(edgesToStop.begin(), veh.getEdge());
425 }
426 // prepend preceding edges
427 std::reverse(edgesUpstream.begin(), edgesUpstream.end());
428 for (auto edge : edgesUpstream) {
429 edgesToStop.insert(edgesToStop.begin(), edge);
430 }
431 ConstMSEdgeVector edgesFromStop;
432 stoppingPlaceApproaches[alternative] = edgesToStop;
433
434 const MSEdge* nextDestination = route.getLastEdge();
435 double nextPos = veh.getArrivalPos();
436 int nextDestinationIndex = route.size() - 1;
437 if (!newDestination) {
438 std::vector<std::pair<int, double> > stopIndices = veh.getStopIndices();
439 int nextDestStopIndex = 1 + insertStopIndex;
440 if (!keepCurrentStop) {
441 nextDestStopIndex++;
442 }
443 if ((int)stopIndices.size() > nextDestStopIndex) {
444 nextDestinationIndex = stopIndices[nextDestStopIndex].first;
445 nextDestination = route.getEdges()[nextDestinationIndex];
446 nextPos = stopIndices[nextDestStopIndex].second;
447 }
448 router.compute(stoppingPlaceEdge, targetPos, nextDestination, nextPos, &veh, now, edgesFromStop, true);
449 }
450 if (edgesFromStop.size() > 0 || newDestination) {
451 stoppingPlaceValues["probability"] = prob;
452 if (stoppingPlaceValues["probability"] > maxValues["probability"]) {
453 maxValues["probability"] = stoppingPlaceValues["probability"];
454 }
455 stoppingPlaceValues["capacity"] = getStoppingPlaceCapacity(alternative);
456 stoppingPlaceValues["absfreespace"] = stoppingPlaceValues["capacity"] - occupancy;
457 // if capacity = 0 then absfreespace and relfreespace are also 0
458 stoppingPlaceValues["relfreespace"] = stoppingPlaceValues["absfreespace"] / MAX2(1.0, stoppingPlaceValues["capacity"]);
459 MSRoute routeToPark(route.getID() + "!to" + myParamPrefix + "#1", edgesToStop, false,
460 &c == &RGBColor::DEFAULT_COLOR ? nullptr : new RGBColor(c), route.getStops());
461
462 // The distance from the current edge to the new parking area
463 double toPos = alternative->getBeginLanePosition();
464 if (&alternative->getLane().getEdge() == veh.getEdge()) {
465 toPos = MAX2(veh.getPositionOnLane(), toPos);
466 }
467 stoppingPlaceValues["distanceto"] = routeToPark.getDistanceBetween(veh.getPositionOnLane(), toPos,
468 routeToPark.begin(), routeToPark.end() - 1, includeInternalLengths);
469
470 if (stoppingPlaceValues["distanceto"] == std::numeric_limits<double>::max()) {
471 WRITE_WARNINGF(TL("Invalid distance computation for vehicle '%' to stopping place '%' at time=%."),
472 veh.getID(), alternative->getID(), time2string(now));
473 }
474 const double endPos = getStoppingPlaceOccupancy(alternative) == getStoppingPlaceCapacity(alternative)
475 ? alternative->getLastFreePos(veh, veh.getPositionOnLane() + brakeGap)
476 : alternative->getEndLanePosition();
477 const double distToEnd = stoppingPlaceValues["distanceto"] - toPos + endPos;
478
479 if (distToEnd < brakeGap) {
480 rememberStoppingPlaceScore(veh, alternative, "tooClose");
481 return false;
482 }
483
484 // The time to reach the new stopping place
485 stoppingPlaceValues["timeto"] = router.recomputeCosts(edgesToStop, &veh, SIMSTEP) - ((alternative->getLane().getLength() - alternative->getEndLanePosition()) / alternative->getLane().getSpeedLimit());
486 ConstMSEdgeVector newEdges = edgesToStop;
487 if (newDestination) {
488 stoppingPlaceValues["distancefrom"] = 0;
489 stoppingPlaceValues["timefrom"] = 0;
490 } else {
491 MSRoute routeFromPark(route.getID() + "!from" + myParamPrefix + "#1", edgesFromStop, false,
492 &c == &RGBColor::DEFAULT_COLOR ? nullptr : new RGBColor(c), route.getStops());
493 // The distance from the new parking area to the end of the route
494 stoppingPlaceValues["distancefrom"] = routeFromPark.getDistanceBetween(alternative->getBeginLanePosition(), routeFromPark.getLastEdge()->getLength(),
495 routeFromPark.begin(), routeFromPark.end() - 1, includeInternalLengths);
496 if (stoppingPlaceValues["distancefrom"] == std::numeric_limits<double>::max()) {
497 WRITE_WARNINGF(TL("Invalid distance computation for vehicle '%' from stopping place '%' at time=%."),
498 veh.getID(), alternative->getID(), time2string(SIMSTEP));
499 }
500 // The time to reach this area
501 stoppingPlaceValues["timefrom"] = router.recomputeCosts(edgesFromStop, &veh, SIMSTEP) - (alternative->getEndLanePosition() / alternative->getLane().getSpeedLimit());
502 newEdges.insert(newEdges.end(), edgesFromStop.begin() + 1, edgesFromStop.end());
503 newEdges.insert(newEdges.end(), route.begin() + nextDestinationIndex + 1, route.end());
504 }
505
506 // add some additional/custom target function components
507 if (!evaluateCustomComponents(veh, brakeGap, newDestination, alternative, occupancy, prob, router, stoppingPlaceValues, stoppingPlaceApproaches[alternative], newEdges, maxValues, addInput)) {
508 return false;
509 }
510 if (!myCheckValidity || validComponentValues(stoppingPlaceValues)) {
511 updateMaxValues(stoppingPlaceValues, maxValues);
512 stoppingPlaces[alternative] = stoppingPlaceValues;
513 newRoutes[alternative] = newEdges;
514 return true;
515 } else {
516 return false;
517 }
518 } else {
519 rememberStoppingPlaceScore(veh, alternative, "unreachable");
520 }
521 } else {
522 rememberStoppingPlaceScore(veh, alternative, "unreachable");
523 }
524 // unreachable
525 return false;
526}
527
528
529bool
530MSStoppingPlaceRerouter::evaluateCustomComponents(SUMOVehicle& /*veh*/, double /*brakeGap*/, bool /*newDestination*/,
531 MSStoppingPlace* /*alternative*/, double /*occupancy*/, double /*prob*/, SUMOAbstractRouter<MSEdge, SUMOVehicle>& /*router*/,
532 StoppingPlaceParamMap_t& /*stoppingPlaceValues*/, ConstMSEdgeVector& /*newRoute*/, ConstMSEdgeVector& /*stoppingPlaceApproach*/,
533 StoppingPlaceParamMap_t& /*maxValues*/, StoppingPlaceParamMap_t& /*addInput*/) {
534 return true;
535}
536
537
538bool
540 return true;
541}
542
543
544bool
546 return true;
547}
548
549
552 return MSNet::getInstance()->getRouterTT(veh.getRNGIndex(), prohibited);
553}
554
555
559 myEvalParams["distanceto"] = getWeight(veh, "distance.weight", myEvalParams["distanceto"]);
560 for (auto evalParam : myEvalParams) {
561 result[evalParam.first] = getWeight(veh, evalParam.first + ".weight", evalParam.second);
562 }
563 result["probability"] = getWeight(veh, "probability.weight", 0.);
564 return result;
565}
566
567
568double
569MSStoppingPlaceRerouter::getWeight(SUMOVehicle& veh, const std::string param, const double defaultWeight, const bool warn) {
570 // get custom vehicle parameter
571 const std::string key = myParamPrefix + "." + param;
572 if (veh.getParameter().hasParameter(key)) {
573 try {
574 return StringUtils::toDouble(veh.getParameter().getParameter(key, "-1"));
575 } catch (...) {
576 WRITE_WARNINGF(TL("Invalid value '%' for vehicle parameter '%'"), veh.getParameter().getParameter(key, "-1"), key);
577 }
578 } else {
579 // get custom vType parameter
580 if (veh.getVehicleType().getParameter().hasParameter(key)) {
581 try {
583 } catch (...) {
584 WRITE_WARNINGF(TL("Invalid value '%' for vType parameter '%'"), veh.getVehicleType().getParameter().getParameter(key, "-1"), key);
585 }
586 }
587 }
588 if (warn) {
589 WRITE_MESSAGEF("Vehicle '%' does not supply vehicle parameter '%'. Using default of %\n", veh.getID(), key, toString(defaultWeight));
590 }
591 return defaultWeight;
592}
593
594
595void
597 for (auto it = maxValues.begin(); it != maxValues.end(); ++it) {
598 if (stoppingPlaceValues[it->first] > it->second) {
599 it->second = stoppingPlaceValues[it->first];
600 }
601 }
602}
603
604
605double
607 double cost = 0.;
608 for (StoppingPlaceParamMap_t::const_iterator sc = absValues.begin(); sc != absValues.end(); ++sc) {
609 double weight = weights.at(sc->first);
610 double val = sc->second;
611 if (norm.at(sc->first) && maxValues.at(sc->first) > 0.) {
612 val /= maxValues.at(sc->first);
613 }
614 cost += (invert.at(sc->first)) ? weight * (1. - val) : weight * val;
615 }
616 return cost;
617}
618
619
620/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:74
std::vector< MSEdge * > MSEdgeVector
Definition MSEdge.h:73
#define DEBUGCOND(PED)
ConstMSEdgeVector::const_iterator MSRouteIterator
Definition MSRoute.h:57
#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
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:592
double getLength() const
Returns the lane's length.
Definition MSLane.h:606
MSEdge & getEdge() const
Returns the lane's edge.
Definition MSLane.h:764
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:186
MSVehicleRouter & getRouterTT(const int rngIndex, const MSEdgeVector &prohibited=MSEdgeVector()) const
Definition MSNet.cpp:1508
bool hasInternalLinks() const
return whether the network contains internal links
Definition MSNet.h:780
int size() const
Returns the number of edges to pass.
Definition MSRoute.cpp:85
const ConstMSEdgeVector & getEdges() const
Definition MSRoute.h:125
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
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...
MSStoppingPlace * reroute(std::vector< StoppingPlaceVisible > &stoppingPlaceCandidates, const std::vector< double > &probs, SUMOVehicle &veh, bool &newDestination, ConstMSEdgeVector &newRoute, StoppingPlaceParamMap_t &scores, const MSEdgeVector &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...
const MSRouteIterator determineRerouteOrigin(SUMOVehicle &veh, int insertStopIndex)
Determine the rerouting origin edge (not necessarily the current edge of the vehicle!...
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
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.
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.
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:199
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:62
virtual MSParkingArea * getNextParkingArea()=0
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