Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSDispatch.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2007-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// An algorithm that performs dispatch for the taxi device
19/****************************************************************************/
20#include <config.h>
21
22#include <limits>
24#include <microsim/MSNet.h>
25#include <microsim/MSEdge.h>
26#include <microsim/MSGlobals.h>
28#include "MSRoutingEngine.h"
29#include "MSDispatch.h"
30
31//#define DEBUG_RESERVATION
32//#define DEBUG_DETOUR
33//#define DEBUG_COND2(obj) (obj->getID() == "p0")
34#define DEBUG_COND2(obj) (true)
35
36
37// ===========================================================================
38// Reservation methods
39// ===========================================================================
40
41// ===========================================================================
42// MSDispatch methods
43// ===========================================================================
44
46 Parameterised(params),
47 myOutput(nullptr),
48 myReservationCount(0),
49 myRoutingMode(StringUtils::toInt(getParameter("routingMode", "1"))) {
50 const std::string opt = "device.taxi.dispatch-algorithm.output";
51 if (OptionsCont::getOptions().isSet(opt)) {
52 OutputDevice::createDeviceByOption(opt, "DispatchInfo");
54 }
55 myKeepUnreachableResTime = string2time(OptionsCont::getOptions().getString("device.taxi.dispatch-keep-unreachable"));
56}
57
59 for (auto item : myGroupReservations) {
60 for (Reservation* res : item.second) {
61 delete res;
62 }
63 }
64 myGroupReservations.clear();
65}
66
67
70 SUMOTime reservationTime,
71 SUMOTime pickupTime,
72 SUMOTime earliestPickupTime,
73 const MSEdge* from, double fromPos,
74 const MSStoppingPlace* fromStop,
75 const MSEdge* to, double toPos,
76 const MSStoppingPlace* toStop,
77 std::string group,
78 const std::string& line,
79 int maxCapacity,
80 int maxContainerCapacity) {
81 std::string resID;
82 if (myLoadedReservations.size() > 0) {
83 auto itL = myLoadedReservations.find(person->getID());
84 if (itL != myLoadedReservations.end()) {
85 resID = itL->second;
86 myLoadedReservations.erase(itL);
87 }
88 }
89 // no new reservation nedded if the person can be added to an existing group
90 if (group == "") {
91 // the default empty group implies, no grouping is wanted (and
92 // transportable ids are unique)
93 group = person->getID();
94 } else {
95 auto it2 = myRunningReservations.find(group);
96 if (it2 != myRunningReservations.end()) {
97 for (auto item : it2->second) {
98 Reservation* res = const_cast<Reservation*>(item.first);
99 if (res->persons.count(person) == 0
100 && res->from == from
101 && res->to == to
102 && res->fromPos == fromPos
103 && res->toPos == toPos) {
104 MSDevice_Taxi* taxi = item.second;
105 if ((taxi->getState() == taxi->PICKUP
106 && remainingCapacity(taxi, res) > 0
107 && taxi->compatibleLine(taxi->getHolder().getParameter().line, line))
108 || resID == res->id) {
109 //std::cout << SIMTIME << " addPerson=" << person->getID() << " extendRes=" << toString(res->persons) << " taxi=" << taxi->getHolder().getID() << " state=" << taxi->getState() << "\n";
110 res->persons.insert(person);
111 taxi->addCustomer(person, res);
112#ifdef DEBUG_RESERVATION
113 if (DEBUG_COND2(person)) std::cout << SIMTIME << " extendedReservation p=" << person->getID() << " resID=" << res->getID() << " taxi=" << taxi->getID() << "\n";
114#endif
115 return res;
116 }
117 }
118 }
119 }
120 }
121 Reservation* result = nullptr;
122 bool added = false;
123 auto it = myGroupReservations.find(group);
124 if (it != myGroupReservations.end()) {
125 // try to add to existing reservation
126 for (Reservation* res : it->second) {
127 if (res->persons.count(person) == 0
128 && res->from == from
129 && res->to == to
130 && res->fromPos == fromPos
131 && res->toPos == toPos
132 && (resID.empty() || res->id == resID)) {
133 if (res->persons.size() > 0 && (*res->persons.begin())->isPerson() != person->isPerson()) {
134 WRITE_WARNINGF(TL("Mixing reservations of persons and containers with the same group is not supported for % and %"),
135 (*res->persons.begin())->getID(), person->getID());
136 }
137 if ((person->isPerson() && (int)res->persons.size() >= maxCapacity) ||
138 (!person->isPerson() && (int)res->persons.size() >= maxContainerCapacity)) {
139 // split group to ensure that at least one taxi is capable of delivering group size.
140 continue;
141 }
142 res->persons.insert(person);
143 result = res;
144 added = true;
145 break;
146 }
147 }
148 }
149 if (!added) {
150 if (resID.empty()) {
151 resID = toString(myReservationCount++);
152 }
153 Reservation* newRes = new Reservation(resID, {person}, reservationTime, pickupTime, earliestPickupTime, from, fromPos, fromStop, to, toPos, toStop, group, line);
154 myGroupReservations[group].push_back(newRes);
155 result = newRes;
156 }
158#ifdef DEBUG_RESERVATION
159 if (DEBUG_COND2(person)) std::cout << SIMTIME
160 << " addReservation p=" << person->getID()
161 << " addID=" << result->getID()
162 << " rT=" << time2string(reservationTime)
163 << " pT=" << time2string(pickupTime)
164 << " from=" << from->getID() << " fromPos=" << fromPos
165 << " to=" << to->getID() << " toPos=" << toPos
166 << " group=" << group
167 << " added=" << added
168 << "\n";
169#endif
170 return result;
171}
172
173
174std::string
176 const MSEdge* from, double fromPos,
177 const MSEdge* to, double toPos,
178 std::string group) {
179 if (group == "") {
180 // the default empty group implies, no grouping is wanted (and
181 // transportable ids are unique)
182 group = person->getID();
183 }
184 std::string removedID = "";
185 auto it = myGroupReservations.find(group);
186 if (it != myGroupReservations.end()) {
187 for (auto itRes = it->second.begin(); itRes != it->second.end(); itRes++) {
188 Reservation* res = *itRes;
189 if (res->persons.count(person) != 0
190 && res->from == from
191 && res->to == to
192 && res->fromPos == fromPos
193 && res->toPos == toPos) {
194 res->persons.erase(person);
195 if (res->persons.empty()) {
196 removedID = res->id;
197 it->second.erase(itRes);
198 // cleans up MSDispatch_Greedy
200 if (it->second.empty()) {
201 myGroupReservations.erase(it);
202 }
203 }
204 break;
205 }
206 }
207 } else {
208 auto it2 = myRunningReservations.find(group);
209 if (it2 != myRunningReservations.end()) {
210 for (auto item : it2->second) {
211 const Reservation* const res = item.first;
212 if (res->persons.count(person) != 0
213 && res->from == from
214 && res->to == to
215 && res->fromPos == fromPos
216 && res->toPos == toPos) {
217 if (res->persons.size() == 1) {
218 removedID = res->id;
219 }
220 item.second->cancelCustomer(person); // will delete res via fulfilledReservation if necessary
221 break;
222 }
223 }
224 }
225 }
227#ifdef DEBUG_RESERVATION
228 if (DEBUG_COND2(person)) std::cout << SIMTIME
229 << " removeReservation p=" << person->getID()
230 << " from=" << from->getID() << " fromPos=" << fromPos
231 << " to=" << to->getID() << " toPos=" << toPos
232 << " group=" << group
233 << " removedID=" << removedID
234 << " hasServable=" << myHasServableReservations
235 << "\n";
236#endif
237 return removedID;
238}
239
240
243 const MSEdge* from, double fromPos,
244 const MSEdge* to, double toPos,
245 std::string group, double newFromPos) {
246 if (group == "") {
247 // the default empty group implies, no grouping is wanted (and
248 // transportable ids are unique)
249 group = person->getID();
250 }
251 Reservation* result = nullptr;
252 std::string updatedID = "";
253 auto it = myGroupReservations.find(group);
254 if (it != myGroupReservations.end()) {
255 for (auto itRes = it->second.begin(); itRes != it->second.end(); itRes++) {
256 Reservation* res = *itRes;
257 // TODO: if there is already a reservation with the newFromPos, add to this reservation
258 // TODO: if there are other persons in this reservation, create a new reservation for the updated one
259 if (res->persons.count(person) != 0
260 && res->from == from
261 && res->to == to
262 && res->fromPos == fromPos
263 && res->toPos == toPos) {
264 // update fromPos
265 res->fromPos = newFromPos;
266 result = res;
267 updatedID = res->id;
268 break;
269 }
270 }
271 }
272#ifdef DEBUG_RESERVATION
273 if (DEBUG_COND2(person)) std::cout << SIMTIME
274 << " updateReservationFromPos p=" << person->getID()
275 << " from=" << from->getID() << " fromPos=" << fromPos
276 << " to=" << to->getID() << " toPos=" << toPos
277 << " group=" << group
278 << " newFromPos=" << newFromPos
279 << " updatedID=" << updatedID
280 << "\n";
281#endif
282 return result;
283}
284
285
286std::vector<Reservation*>
288 std::vector<Reservation*> reservations;
289 for (const auto& it : myGroupReservations) {
290 reservations.insert(reservations.end(), it.second.begin(), it.second.end());
291 }
292 return reservations;
293}
294
295
296std::vector<const Reservation*>
298 std::vector<const Reservation*> result;
299 for (auto item : myRunningReservations) {
300 for (auto item2 : item.second) {
301 result.push_back(item2.first);
302 }
303 }
304 return result;
305}
306
307
308void
310 auto itR = myRunningReservations.find(res->group);
311 if (itR != myRunningReservations.end() && itR->second.count(res) != 0) {
312#ifdef DEBUG_RESERVATION
313 std::cout << SIMTIME << " servedReservation res=" << res->id << " taxi=" << taxi->getID() << " (running)\n";
314#endif
315 return; // was redispatch
316 }
317#ifdef DEBUG_RESERVATION
318 std::cout << SIMTIME << " servedReservation res=" << res->id << " taxi=" << taxi->getID() << "\n";
319#endif
320 auto it = myGroupReservations.find(res->group);
321 if (it == myGroupReservations.end()) {
322 throw ProcessError(TL("Inconsistent group reservations."));
323 }
324 auto it2 = std::find(it->second.begin(), it->second.end(), res);
325 if (it2 == it->second.end()) {
326 throw ProcessError(TL("Inconsistent group reservations (2)."));
327 }
328 myRunningReservations[res->group][res] = taxi;
329 const_cast<Reservation*>(*it2)->state = Reservation::ASSIGNED;
330 it->second.erase(it2);
331 if (it->second.empty()) {
332 myGroupReservations.erase(it);
333 }
334}
335
336
337void
339#ifdef DEBUG_RESERVATION
340 std::cout << SIMTIME << " swapped res=" << res->id << " old=" << myRunningReservations[res->group][res]->getID() << " new=" << taxi->getID() << "\n";
341#endif
342 myRunningReservations[res->group][res] = taxi;
343}
344
345
346void
348 myRunningReservations[res->group].erase(res);
349 if (myRunningReservations[res->group].empty()) {
350 myRunningReservations.erase(res->group);
351 }
352 delete res;
353}
354
355
360
361
364 ConstMSEdgeVector edges;
365 double fromPos = taxi->getHolder().getPositionOnLane() - NUMERICAL_EPS;
366 const MSEdge* from = *taxi->getHolder().getRerouteOrigin();
367 const bool originDiffers = from != taxi->getHolder().getEdge();
368 router.compute(from, originDiffers ? 0 : fromPos, res.from, res.fromPos, &taxi->getHolder(), t, edges, true);
369 if (edges.empty()) {
370 return SUMOTime_MAX;
371 } else {
372 if (originDiffers) {
373 assert(from == *(taxi->getHolder().getCurrentRouteEdge() + 1));
374 edges.insert(edges.begin(), taxi->getHolder().getEdge());
375 }
376 return TIME2STEPS(router.recomputeCostsPos(edges, &taxi->getHolder(), fromPos, res.fromPos, t));
377 }
378}
379
380
381bool
383 ConstMSEdgeVector edges;
384 router.compute(res.from, res.fromPos, res.to, res.toPos, &taxi->getHolder(), t, edges, true);
385 return !edges.empty();
386}
387
388
389double
391 const MSEdge* from, double fromPos,
392 const MSEdge* via, double viaPos,
393 const MSEdge* to, double toPos,
395 double& timeDirect) {
396 ConstMSEdgeVector edges;
397 if (timeDirect < 0) {
398 router.compute(from, fromPos, to, toPos, &taxi->getHolder(), t, edges, true);
399 timeDirect = router.recomputeCostsPos(edges, &taxi->getHolder(), fromPos, toPos, t);
400 edges.clear();
401 }
402
403 router.compute(from, fromPos, via, viaPos, &taxi->getHolder(), t, edges, true);
404 const double start = STEPS2TIME(t);
405 const double leg1 = router.recomputeCostsPos(edges, &taxi->getHolder(), fromPos, viaPos, t);
406#ifdef DEBUG_DETOUR
407 std::cout << " leg1=" << toString(edges) << " startPos=" << fromPos << " toPos=" << viaPos << " time=" << leg1 << "\n";
408#endif
409 const double wait = MAX2(0.0, STEPS2TIME(viaTime) - (start + leg1));
410 edges.clear();
411 const SUMOTime timeContinue = TIME2STEPS(start + leg1 + wait);
412 router.compute(via, viaPos, to, toPos, &taxi->getHolder(), timeContinue, edges, true);
413 const double leg2 = router.recomputeCostsPos(edges, &taxi->getHolder(), viaPos, toPos, timeContinue);
414 const double timeDetour = leg1 + wait + leg2;
415#ifdef DEBUG_DETOUR
416 std::cout << " leg2=" << toString(edges) << " startPos=" << viaPos << " toPos=" << toPos << " time=" << leg2 << "\n";
417 std::cout << " t=" << STEPS2TIME(t) << " vt=" << STEPS2TIME(viaTime)
418 << " from=" << from->getID() << " to=" << to->getID() << " via=" << via->getID()
419 << " direct=" << timeDirect << " detour=" << timeDetour << " wait=" << wait << "\n";
420#endif
421 return timeDetour;
422}
423
424
425int
427 assert(res->persons.size() > 0);
428 return ((*res->persons.begin())->isPerson()
430 : taxi->getHolder().getVehicleType().getContainerCapacity()) - (int)res->persons.size();
431}
432
433
434void
435MSDispatch::saveState(OutputDevice& out, SUMOTime nextDispatch) const {
437 out.writeAttr(SUMO_ATTR_NEXT, nextDispatch);
439
440 std::ostringstream internals;
441 for (const auto& it : myRunningReservations) {
442 for (const auto& item : it.second) {
443 for (const MSTransportable* t : item.first->persons) {
444 internals << t->getID() << " " << item.first->id << " ";
445 }
446 }
447 }
448 for (const auto& it : myGroupReservations) {
449 for (const Reservation* res : it.second) {
450 for (const MSTransportable* t : res->persons) {
451 internals << t->getID() << " " << res->id << " ";
452 }
453 }
454 }
455 out.writeAttr(SUMO_ATTR_CUSTOMERS, internals.str());
456 out.closeTag();
457}
458
459
460void
462 bool ok = true;
463 myReservationCount = attrs.get<int>(SUMO_ATTR_COUNT, "dispatcher", ok);
464 std::istringstream bis(attrs.getString(SUMO_ATTR_CUSTOMERS));
465 std::string tID, rID;
466 while (bis >> tID && bis >> rID) {
467 myLoadedReservations[tID] = rID;
468 }
469}
470
471
472
473/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
#define DEBUG_COND2(obj)
Definition MESegment.cpp:54
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:74
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:287
#define TL(string)
Definition MsgHandler.h:304
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:46
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 SUMOTime_MAX
Definition SUMOTime.h:34
#define SIMTIME
Definition SUMOTime.h:65
#define TIME2STEPS(x)
Definition SUMOTime.h:60
@ SVC_TAXI
vehicle is a taxi
@ SUMO_TAG_DISPATCHER
Dispatcher state for saving.
@ SUMO_ATTR_CUSTOMERS
@ SUMO_ATTR_NEXT
succesor phase index
@ SUMO_ATTR_COUNT
T MAX2(T a, T b)
Definition StdDefs.h:86
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:49
A device which collects info on the vehicle trip (mainly on departure and arrival)
void addCustomer(const MSTransportable *t, const Reservation *res)
add person after extending reservation
int getState() const
bool compatibleLine(const Reservation *res)
whether the given reservation is compatible with the taxi line
OutputDevice * myOutput
optional file output for dispatch information
Definition MSDispatch.h:226
const int myRoutingMode
which router/edge weights to use
Definition MSDispatch.h:236
bool isReachable(SUMOTime t, const MSDevice_Taxi *taxi, const Reservation &res, SUMOAbstractRouter< MSEdge, SUMOVehicle > &router)
compute whether the reservation is servable
void swappedRunning(const Reservation *res, MSDevice_Taxi *taxi)
int remainingCapacity(const MSDevice_Taxi *taxi, const Reservation *res)
whether the given taxi has sufficient capacity to serve the reservation
static SUMOTime computePickupTime(SUMOTime t, const MSDevice_Taxi *taxi, const Reservation &res, SUMOAbstractRouter< MSEdge, SUMOVehicle > &router)
compute time to pick up the given reservation
virtual std::string removeReservation(MSTransportable *person, const MSEdge *from, double fromPos, const MSEdge *to, double toPos, std::string group)
remove person from reservation. If the whole reservation is removed, return its id
bool myHasServableReservations
whether the last call to computeDispatch has left servable reservations
Definition MSDispatch.h:198
virtual Reservation * updateReservationFromPos(MSTransportable *person, const MSEdge *from, double fromPos, const MSEdge *to, double toPos, std::string group, double newFromPos)
update fromPos of the person's reservation. TODO: if there is already a reservation with the newFromP...
std::map< std::string, std::vector< Reservation * > > myGroupReservations
Definition MSDispatch.h:233
std::vector< Reservation * > getReservations()
retrieve all reservations
virtual std::vector< const Reservation * > getRunningReservations()
retrieve all reservations that were already dispatched and are still active
SUMOTime myKeepUnreachableResTime
the duration before canceling unreachable reservations
Definition MSDispatch.h:231
std::map< std::string, std::string > myLoadedReservations
reservations loaded from state
Definition MSDispatch.h:239
static double computeDetourTime(SUMOTime t, SUMOTime viaTime, const MSDevice_Taxi *taxi, const MSEdge *from, double fromPos, const MSEdge *via, double viaPos, const MSEdge *to, double toPos, SUMOAbstractRouter< MSEdge, SUMOVehicle > &router, double &timeDirect)
compute directTime and detourTime
virtual SUMOAbstractRouter< MSEdge, SUMOVehicle > & getRouter() const
virtual Reservation * addReservation(MSTransportable *person, SUMOTime reservationTime, SUMOTime pickupTime, SUMOTime earliestPickupTime, const MSEdge *from, double fromPos, const MSStoppingPlace *fromStop, const MSEdge *to, double toPos, const MSStoppingPlace *tostop, std::string group, const std::string &line, int maxCapacity, int maxContainerCapacity)
add a new reservation
virtual void loadState(const SUMOSAXAttributes &attrs)
Loads the state of the device from the given description.
int myReservationCount
Definition MSDispatch.h:228
virtual void fulfilledReservation(const Reservation *res)
erase reservation from storage
virtual void saveState(OutputDevice &out, SUMOTime nextDispatch) const
Saves the state of the device.
MSDispatch(const Parameterised::Map &params)
Constructor;.
std::map< std::string, std::map< const Reservation *, MSDevice_Taxi *, ComparatorIdLess > > myRunningReservations
Definition MSDispatch.h:223
virtual ~MSDispatch()
Destructor.
void servedReservation(const Reservation *res, MSDevice_Taxi *taxi)
A road/street connecting two junctions.
Definition MSEdge.h:77
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:199
MSVehicleRouter & getRouterTT(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1616
static MSVehicleRouter & getRouterTT(const int rngIndex, SUMOVehicleClass svc, const Prohibitions &prohibited={})
return the vehicle router instance
A lane area vehicles can halt at.
bool isPerson() const override
Whether it is a person.
SUMOVehicle & getHolder() const
Returns the vehicle that holds this device.
int getPersonCapacity() const
Get this vehicle type's person capacity.
int getContainerCapacity() const
Get this vehicle type's container capacity.
const std::string & getID() const
Returns the id.
Definition Named.h:74
static OptionsCont & getOptions()
Retrieves the options.
Static storage of an output device and its base (abstract) implementation.
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
OutputDevice & writeAttr(const ATTR_TYPE &attr, const T &val, const bool isNull=false)
writes a named attribute
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
static bool createDeviceByOption(const std::string &optionName, const std::string &rootElement="", const std::string &schemaFile="", const int maximumDepth=2)
Creates the device using the output definition stored in the named option.
An upper class for objects with additional parameters.
std::map< std::string, std::string > Map
parameters map
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...
double recomputeCostsPos(const std::vector< const E * > &edges, const V *const v, double fromPos, double toPos, SUMOTime msTime, double *lengthp=nullptr) const
Encapsulated SAX-Attributes.
virtual std::string getString(int id, bool *isPresent=nullptr) const =0
Returns the string-value of the named (by its enum-value) attribute.
T get(int attr, const char *objectid, bool &ok, bool report=true) const
Tries to read given attribute assuming it is an int.
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 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.
virtual ConstMSEdgeVector::const_iterator getRerouteOrigin() const =0
Returns the starting point for reroutes (usually the current edge)
virtual const ConstMSEdgeVector::const_iterator & getCurrentRouteEdge() const =0
Returns an iterator pointing to the current edge in this vehicles route.
std::string line
The vehicle's line (mainly for public transport)
Some static methods for string processing.
Definition StringUtils.h:40
std::string id
Definition MSDispatch.h:76
const MSEdge * to
Definition MSDispatch.h:84
std::string getID() const
for sorting by id
Definition MSDispatch.h:105
double fromPos
Definition MSDispatch.h:82
const MSEdge * from
Definition MSDispatch.h:81
std::string group
Definition MSDispatch.h:87
ReservationState state
Definition MSDispatch.h:90
std::set< const MSTransportable * > persons
Definition MSDispatch.h:77
double toPos
Definition MSDispatch.h:85