Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSNet.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/****************************************************************************/
25// The simulated network and simulation performer
26/****************************************************************************/
27#include <config.h>
28
29#ifdef HAVE_VERSION_H
30#include <version.h>
31#endif
32
33#include <string>
34#include <iostream>
35#include <sstream>
36#include <typeinfo>
37#include <algorithm>
38#include <cassert>
39#include <vector>
40#include <ctime>
41
42#ifdef HAVE_FOX
44#endif
64#include <utils/xml/XMLSubSys.h>
66#include <libsumo/Helper.h>
67#include <libsumo/Simulation.h>
68#include <mesosim/MELoop.h>
69#include <mesosim/MESegment.h>
106#include <netload/NLBuilder.h>
107
108#include "MSEdgeControl.h"
109#include "MSJunctionControl.h"
110#include "MSInsertionControl.h"
112#include "MSEventControl.h"
113#include "MSEdge.h"
114#include "MSJunction.h"
115#include "MSJunctionLogic.h"
116#include "MSLane.h"
117#include "MSVehicleControl.h"
118#include "MSVehicleTransfer.h"
119#include "MSRoute.h"
120#include "MSGlobals.h"
121#include "MSEdgeWeightsStorage.h"
122#include "MSStateHandler.h"
123#include "MSFrame.h"
124#include "MSParkingArea.h"
125#include "MSStoppingPlace.h"
126#include "MSNet.h"
127
128
129// ===========================================================================
130// debug constants
131// ===========================================================================
132//#define DEBUG_SIMSTEP
133
134
135// ===========================================================================
136// static member definitions
137// ===========================================================================
138MSNet* MSNet::myInstance = nullptr;
139
140const std::string MSNet::STAGE_EVENTS("events");
141const std::string MSNet::STAGE_MOVEMENTS("move");
142const std::string MSNet::STAGE_LANECHANGE("laneChange");
143const std::string MSNet::STAGE_INSERTIONS("insertion");
144const std::string MSNet::STAGE_REMOTECONTROL("remoteControl");
145
147const std::vector<MSStoppingPlace*> MSNet::myEmptyStoppingPlaceVector;
148
149// ===========================================================================
150// static member method definitions
151// ===========================================================================
152double
153MSNet::getEffort(const MSEdge* const e, const SUMOVehicle* const v, double t) {
154 double value;
155 const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
156 if (veh != nullptr && veh->getWeightsStorage().retrieveExistingEffort(e, t, value)) {
157 return value;
158 }
160 return value;
161 }
162 return 0;
163}
164
165
166double
167MSNet::getTravelTime(const MSEdge* const e, const SUMOVehicle* const v, double t) {
168 double value;
169 const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
170 if (veh != nullptr && veh->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
171 return value;
172 }
174 return value;
175 }
176 if (veh != nullptr && veh->getRoutingMode() == libsumo::ROUTING_MODE_AGGREGATED_CUSTOM) {
177 return MSRoutingEngine::getEffortExtra(e, v, t);
178 }
179 return e->getMinimumTravelTime(v);
180}
181
182
183// ---------------------------------------------------------------------------
184// MSNet - methods
185// ---------------------------------------------------------------------------
186MSNet*
188 if (myInstance != nullptr) {
189 return myInstance;
190 }
191 throw ProcessError(TL("A network was not yet constructed."));
192}
193
194void
199
200void
206
207
208MSNet::MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents,
209 MSEventControl* endOfTimestepEvents,
210 MSEventControl* insertionEvents,
211 ShapeContainer* shapeCont):
212 myAmInterrupted(false),
213 myVehiclesMoved(0),
214 myPersonsMoved(0),
215 myHavePermissions(false),
216 myHasInternalLinks(false),
217 myJunctionHigherSpeeds(false),
218 myHasElevation(false),
219 myHasPedestrianNetwork(false),
220 myHasBidiEdges(false),
221 myEdgeDataEndTime(-1),
222 myDynamicShapeUpdater(nullptr) {
223 if (myInstance != nullptr) {
224 throw ProcessError(TL("A network was already constructed."));
225 }
227 myStep = string2time(oc.getString("begin"));
228 myMaxTeleports = oc.getInt("max-num-teleports");
229 myLogExecutionTime = !oc.getBool("no-duration-log");
230 myLogStepNumber = !oc.getBool("no-step-log");
231 myLogStepPeriod = oc.getInt("step-log.period");
232 myInserter = new MSInsertionControl(*vc, string2time(oc.getString("max-depart-delay")), oc.getBool("eager-insert"), oc.getInt("max-num-vehicles"),
233 string2time(oc.getString("random-depart-offset")));
234 myVehicleControl = vc;
236 myEdges = nullptr;
237 myJunctions = nullptr;
238 myRouteLoaders = nullptr;
239 myLogics = nullptr;
240 myPersonControl = nullptr;
241 myContainerControl = nullptr;
242 myEdgeWeights = nullptr;
243 myShapeContainer = shapeCont == nullptr ? new ShapeContainer() : shapeCont;
244
245 myBeginOfTimestepEvents = beginOfTimestepEvents;
246 myEndOfTimestepEvents = endOfTimestepEvents;
247 myInsertionEvents = insertionEvents;
248 myLanesRTree.first = false;
249
251 MSGlobals::gMesoNet = new MELoop(string2time(oc.getString("meso-recheck")));
252 }
253 myInstance = this;
254 initStatic();
255}
256
257
258void
260 SUMORouteLoaderControl* routeLoaders,
261 MSTLLogicControl* tlc,
262 std::vector<SUMOTime> stateDumpTimes,
263 std::vector<std::string> stateDumpFiles,
264 bool hasInternalLinks,
265 bool junctionHigherSpeeds,
266 const MMVersion& version) {
267 myEdges = edges;
268 myJunctions = junctions;
269 myRouteLoaders = routeLoaders;
270 myLogics = tlc;
271 // save the time the network state shall be saved at
272 myStateDumpTimes = stateDumpTimes;
273 myStateDumpFiles = stateDumpFiles;
274 myStateDumpPeriod = string2time(oc.getString("save-state.period"));
275 myStateDumpPrefix = oc.getString("save-state.prefix");
276 myStateDumpSuffix = oc.getString("save-state.suffix");
277
278 // initialise performance computation
280 myTraCIMillis = 0;
282 myJunctionHigherSpeeds = junctionHigherSpeeds;
286 myVersion = version;
289 throw ProcessError(TL("Option weights.separate-turns is only supported when simulating with internal lanes"));
290 }
291}
292
293
296 // delete controls
297 delete myJunctions;
298 delete myDetectorControl;
299 // delete mean data
300 delete myEdges;
301 delete myInserter;
302 myInserter = nullptr;
303 delete myLogics;
304 delete myRouteLoaders;
305 if (myPersonControl != nullptr) {
306 delete myPersonControl;
307 myPersonControl = nullptr; // just to have that clear for later cleanups
308 }
309 if (myContainerControl != nullptr) {
310 delete myContainerControl;
311 myContainerControl = nullptr; // just to have that clear for later cleanups
312 }
313 delete myVehicleControl; // must happen after deleting transportables
314 // delete events late so that vehicles can get rid of references first
316 myBeginOfTimestepEvents = nullptr;
318 myEndOfTimestepEvents = nullptr;
319 delete myInsertionEvents;
320 myInsertionEvents = nullptr;
321 delete myShapeContainer;
322 delete myEdgeWeights;
323 for (auto& router : myRouterTT) {
324 delete router.second;
325 }
326 myRouterTT.clear();
327 for (auto& router : myRouterEffort) {
328 delete router.second;
329 }
330 myRouterEffort.clear();
331 for (auto& router : myPedestrianRouter) {
332 delete router.second;
333 }
334 myPedestrianRouter.clear();
335 for (auto& router : myIntermodalRouter) {
336 delete router.second;
337 }
338 myIntermodalRouter.clear();
339 myLanesRTree.second.RemoveAll();
340 clearAll();
342 delete MSGlobals::gMesoNet;
343 }
344 myInstance = nullptr;
345}
346
347
348void
349MSNet::addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed) {
350 myRestrictions[id][svc] = speed;
351}
352
353
354const std::map<SUMOVehicleClass, double>*
355MSNet::getRestrictions(const std::string& id) const {
356 std::map<std::string, std::map<SUMOVehicleClass, double> >::const_iterator i = myRestrictions.find(id);
357 if (i == myRestrictions.end()) {
358 return nullptr;
359 }
360 return &i->second;
361}
362
363
364double
365MSNet::getPreference(const std::string& routingType, const SUMOVTypeParameter& pars) const {
367 auto it = myVTypePreferences.find(pars.id);
368 if (it != myVTypePreferences.end()) {
369 auto it2 = it->second.find(routingType);
370 if (it2 != it->second.end()) {
371 return it2->second;
372 }
373 }
374 auto it3 = myVClassPreferences.find(pars.vehicleClass);
375 if (it3 != myVClassPreferences.end()) {
376 auto it4 = it3->second.find(routingType);
377 if (it4 != it3->second.end()) {
378 return it4->second;
379 }
380 }
381 // fallback to generel preferences
382 it = myVTypePreferences.find("");
383 if (it != myVTypePreferences.end()) {
384 auto it2 = it->second.find(routingType);
385 if (it2 != it->second.end()) {
386 return it2->second;
387 }
388 }
389 }
390 return 1;
391}
392
393
394void
395MSNet::addPreference(const std::string& routingType, SUMOVehicleClass svc, double prio) {
396 myVClassPreferences[svc][routingType] = prio;
397 gRoutingPreferences = true;
398}
399
400
401void
402MSNet::addPreference(const std::string& routingType, std::string vType, double prio) {
403 myVTypePreferences[vType][routingType] = prio;
404 gRoutingPreferences = true;
405}
406
407void
408MSNet::addMesoType(const std::string& typeID, const MESegment::MesoEdgeType& edgeType) {
409 myMesoEdgeTypes[typeID] = edgeType;
410}
411
413MSNet::getMesoType(const std::string& typeID) {
414 if (myMesoEdgeTypes.count(typeID) == 0) {
415 // init defaults
418 edgeType.tauff = string2time(oc.getString("meso-tauff"));
419 edgeType.taufj = string2time(oc.getString("meso-taufj"));
420 edgeType.taujf = string2time(oc.getString("meso-taujf"));
421 edgeType.taujj = string2time(oc.getString("meso-taujj"));
422 edgeType.jamThreshold = oc.getFloat("meso-jam-threshold");
423 edgeType.junctionControl = oc.getBool("meso-junction-control");
424 edgeType.tlsPenalty = oc.getFloat("meso-tls-penalty");
425 edgeType.tlsFlowPenalty = oc.getFloat("meso-tls-flow-penalty");
426 edgeType.minorPenalty = string2time(oc.getString("meso-minor-penalty"));
427 edgeType.overtaking = oc.getBool("meso-overtaking");
428 edgeType.edgeLength = oc.getFloat("meso-edgelength");
429 myMesoEdgeTypes[typeID] = edgeType;
430 }
431 return myMesoEdgeTypes[typeID];
432}
433
434
435bool
436MSNet::hasFlow(const std::string& id) const {
437 // inserter is deleted at the end of the simulation
438 return myInserter != nullptr && myInserter->hasFlow(id);
439}
440
441
444 // report the begin when wished
445 WRITE_MESSAGEF(TL("Simulation version % started with time: %."), VERSION_STRING, time2string(start));
446 // the simulation loop
448 // state loading may have changed the start time so we need to reinit it
449 myStep = start;
450 int numSteps = 0;
451 bool doStepLog = false;
452 while (state == SIMSTATE_RUNNING) {
453 doStepLog = myLogStepNumber && (numSteps % myLogStepPeriod == 0);
454 if (doStepLog) {
456 }
458 if (doStepLog) {
460 }
461 state = adaptToState(simulationState(stop));
462#ifdef DEBUG_SIMSTEP
463 std::cout << SIMTIME << " MSNet::simulate(" << start << ", " << stop << ")"
464 << "\n simulation state: " << getStateMessage(state)
465 << std::endl;
466#endif
467 numSteps++;
468 }
469 if (myLogStepNumber && !doStepLog) {
470 // ensure some output on the last step
473 }
474 // exit simulation loop
475 if (myLogStepNumber) {
476 // start new line for final verbose output
477 std::cout << "\n";
478 }
479 closeSimulation(start, getStateMessage(state));
480 return state;
481}
482
483
484void
488
489
490const std::string
491MSNet::generateStatistics(const SUMOTime start, const long now) {
492 std::ostringstream msg;
493 if (myLogExecutionTime) {
494 const long duration = now - mySimBeginMillis;
495 // print performance notice
496 msg << "Performance:\n" << " Duration: " << elapsedMs2string(duration) << "\n";
497 if (duration != 0) {
498 if (TraCIServer::getInstance() != nullptr) {
499 msg << " TraCI-Duration: " << elapsedMs2string(myTraCIMillis) << "\n";
500 }
501 msg << " Real time factor: " << (STEPS2TIME(myStep - start) * 1000. / (double)duration) << "\n";
502 msg.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
503 msg.setf(std::ios::showpoint); // print decimal point
504 msg << " UPS: " << ((double)myVehiclesMoved / ((double)duration / 1000)) << "\n";
505 if (myPersonsMoved > 0) {
506 msg << " UPS-Persons: " << ((double)myPersonsMoved / ((double)duration / 1000)) << "\n";
507 }
508 }
509 // print vehicle statistics
510 const std::string vehDiscardNotice = ((myVehicleControl->getLoadedVehicleNo() != myVehicleControl->getDepartedVehicleNo()) ?
511 " (Loaded: " + toString(myVehicleControl->getLoadedVehicleNo()) + ")" : "");
512 msg << "Vehicles:\n"
513 << " Inserted: " << myVehicleControl->getDepartedVehicleNo() << vehDiscardNotice << "\n"
514 << " Running: " << myVehicleControl->getRunningVehicleNo() << "\n"
515 << " Waiting: " << myInserter->getWaitingVehicleNo() << "\n";
516
518 // print optional teleport statistics
519 std::vector<std::string> reasons;
521 reasons.push_back("Collisions: " + toString(myVehicleControl->getCollisionCount()));
522 }
524 reasons.push_back("Jam: " + toString(myVehicleControl->getTeleportsJam()));
525 }
527 reasons.push_back("Yield: " + toString(myVehicleControl->getTeleportsYield()));
528 }
530 reasons.push_back("Wrong Lane: " + toString(myVehicleControl->getTeleportsWrongLane()));
531 }
532 msg << " Teleports: " << myVehicleControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
533 }
535 msg << " Emergency Stops: " << myVehicleControl->getEmergencyStops() << "\n";
536 }
538 msg << " Emergency Braking: " << myVehicleControl->getEmergencyBrakingCount() << "\n";
539 }
540 if (myPersonControl != nullptr && myPersonControl->getLoadedNumber() > 0) {
541 const std::string discardNotice = ((myPersonControl->getLoadedNumber() != myPersonControl->getDepartedNumber()) ?
542 " (Loaded: " + toString(myPersonControl->getLoadedNumber()) + ")" : "");
543 msg << "Persons:\n"
544 << " Inserted: " << myPersonControl->getDepartedNumber() << discardNotice << "\n"
545 << " Running: " << myPersonControl->getRunningNumber() << "\n";
546 if (myPersonControl->getJammedNumber() > 0) {
547 msg << " Jammed: " << myPersonControl->getJammedNumber() << "\n";
548 }
550 std::vector<std::string> reasons;
552 reasons.push_back("Abort Wait: " + toString(myPersonControl->getTeleportsAbortWait()));
553 }
555 reasons.push_back("Wrong Dest: " + toString(myPersonControl->getTeleportsWrongDest()));
556 }
557 msg << " Teleports: " << myPersonControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
558 }
559 }
560 if (myContainerControl != nullptr && myContainerControl->getLoadedNumber() > 0) {
561 const std::string discardNotice = ((myContainerControl->getLoadedNumber() != myContainerControl->getDepartedNumber()) ?
562 " (Loaded: " + toString(myContainerControl->getLoadedNumber()) + ")" : "");
563 msg << "Containers:\n"
564 << " Inserted: " << myContainerControl->getDepartedNumber() << "\n"
565 << " Running: " << myContainerControl->getRunningNumber() << "\n";
567 msg << " Jammed: " << myContainerControl->getJammedNumber() << "\n";
568 }
570 std::vector<std::string> reasons;
572 reasons.push_back("Abort Wait: " + toString(myContainerControl->getTeleportsAbortWait()));
573 }
575 reasons.push_back("Wrong Dest: " + toString(myContainerControl->getTeleportsWrongDest()));
576 }
577 msg << " Teleports: " << myContainerControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
578 }
579 }
580 }
581 if (OptionsCont::getOptions().getBool("duration-log.statistics")) {
583 }
584 std::string result = msg.str();
585 result.erase(result.end() - 1);
586 return result;
587}
588
589
590void
592 OutputDevice& od = OutputDevice::getDeviceByOption("collision-output");
593 for (const auto& item : myCollisions) {
594 for (const auto& c : item.second) {
595 if (c.time != SIMSTEP) {
596 continue;
597 }
598 od.openTag("collision");
600 od.writeAttr("type", c.type);
601 od.writeAttr("lane", c.lane->getID());
602 od.writeAttr("pos", c.pos);
603 od.writeAttr("collider", item.first);
604 od.writeAttr("victim", c.victim);
605 od.writeAttr("colliderType", c.colliderType);
606 od.writeAttr("victimType", c.victimType);
607 od.writeAttr("colliderSpeed", c.colliderSpeed);
608 od.writeAttr("victimSpeed", c.victimSpeed);
609 od.writeAttr("colliderFront", c.colliderFront);
610 od.writeAttr("colliderBack", c.colliderBack);
611 od.writeAttr("victimFront", c.victimFront);
612 od.writeAttr("victimBack", c.victimBack);
613 od.closeTag();
614 }
615 }
616}
617
618
619void
620MSNet::writeStatistics(const SUMOTime start, const long now) const {
621 const long duration = now - mySimBeginMillis;
622 OutputDevice& od = OutputDevice::getDeviceByOption("statistic-output");
623 od.openTag("performance");
624 od.writeAttr("clockBegin", time2string(mySimBeginMillis));
625 od.writeAttr("clockEnd", time2string(now));
626 od.writeAttr("clockDuration", time2string(duration));
627 od.writeAttr("traciDuration", time2string(myTraCIMillis));
628 od.writeAttr("realTimeFactor", duration != 0 ? (double)(myStep - start) / (double)duration : -1);
629 od.writeAttr("vehicleUpdatesPerSecond", duration != 0 ? (double)myVehiclesMoved / ((double)duration / 1000) : -1);
630 od.writeAttr("personUpdatesPerSecond", duration != 0 ? (double)myPersonsMoved / ((double)duration / 1000) : -1);
631 od.writeAttr("begin", time2string(start));
632 od.writeAttr("end", time2string(myStep));
633 od.writeAttr("duration", time2string(myStep - start));
634 od.closeTag();
635 od.openTag("vehicles");
639 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
640 od.closeTag();
641 od.openTag("teleports");
646 od.closeTag();
647 od.openTag("safety");
648 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
649 od.writeAttr("emergencyStops", myVehicleControl->getEmergencyStops());
650 od.writeAttr("emergencyBraking", myVehicleControl->getEmergencyBrakingCount());
651 od.closeTag();
652 od.openTag("persons");
653 od.writeAttr("loaded", myPersonControl != nullptr ? myPersonControl->getLoadedNumber() : 0);
654 od.writeAttr("running", myPersonControl != nullptr ? myPersonControl->getRunningNumber() : 0);
655 od.writeAttr("jammed", myPersonControl != nullptr ? myPersonControl->getJammedNumber() : 0);
656 od.closeTag();
657 od.openTag("personTeleports");
658 od.writeAttr("total", myPersonControl != nullptr ? myPersonControl->getTeleportCount() : 0);
659 od.writeAttr("abortWait", myPersonControl != nullptr ? myPersonControl->getTeleportsAbortWait() : 0);
660 od.writeAttr("wrongDest", myPersonControl != nullptr ? myPersonControl->getTeleportsWrongDest() : 0);
661 od.closeTag();
662 if (OptionsCont::getOptions().isSet("tripinfo-output") || OptionsCont::getOptions().getBool("duration-log.statistics")) {
664 }
665
666}
667
668
669void
671 // summary output
673 const bool hasOutput = oc.isSet("summary-output");
674 const bool hasPersonOutput = oc.isSet("person-summary-output");
675 if (hasOutput || hasPersonOutput) {
676 const SUMOTime period = string2time(oc.getString("summary-output.period"));
677 const SUMOTime begin = string2time(oc.getString("begin"));
678 if ((period > 0 && (myStep - begin) % period != 0 && !finalStep)
679 // it's the final step but we already wrote output
680 || (finalStep && (period <= 0 || (myStep - begin) % period == 0))) {
681 return;
682 }
683 }
684 if (hasOutput) {
685 OutputDevice& od = OutputDevice::getDeviceByOption("summary-output");
686 int departedVehiclesNumber = myVehicleControl->getDepartedVehicleNo();
687 const double meanWaitingTime = departedVehiclesNumber != 0 ? myVehicleControl->getTotalDepartureDelay() / (double) departedVehiclesNumber : -1.;
688 int endedVehicleNumber = myVehicleControl->getEndedVehicleNo();
689 const double meanTravelTime = endedVehicleNumber != 0 ? myVehicleControl->getTotalTravelTime() / (double) endedVehicleNumber : -1.;
690 od.openTag("step");
691 od.writeAttr("time", time2string(myStep));
695 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
698 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
699 od.writeAttr("teleports", myVehicleControl->getTeleportCount());
702 od.writeAttr("meanWaitingTime", meanWaitingTime);
703 od.writeAttr("meanTravelTime", meanTravelTime);
704 std::pair<double, double> meanSpeed = myVehicleControl->getVehicleMeanSpeeds();
705 od.writeAttr("meanSpeed", meanSpeed.first);
706 od.writeAttr("meanSpeedRelative", meanSpeed.second);
708 if (myLogExecutionTime) {
709 od.writeAttr("duration", mySimStepDuration);
710 }
711 od.closeTag();
712 }
713 if (hasPersonOutput) {
714 OutputDevice& od = OutputDevice::getDeviceByOption("person-summary-output");
716 od.openTag("step");
717 od.writeAttr("time", time2string(myStep));
718 od.writeAttr("loaded", pc.getLoadedNumber());
719 od.writeAttr("inserted", pc.getDepartedNumber());
720 od.writeAttr("walking", pc.getMovingNumber());
721 od.writeAttr("waitingForRide", pc.getWaitingForVehicleNumber());
722 od.writeAttr("riding", pc.getRidingNumber());
723 od.writeAttr("stopping", pc.getWaitingUntilNumber());
724 od.writeAttr("jammed", pc.getJammedNumber());
725 od.writeAttr("ended", pc.getEndedNumber());
726 od.writeAttr("arrived", pc.getArrivedNumber());
727 od.writeAttr("teleports", pc.getTeleportCount());
728 od.writeAttr("discarded", pc.getDiscardedNumber());
729 if (myLogExecutionTime) {
730 od.writeAttr("duration", mySimStepDuration);
731 }
732 od.closeTag();
733 }
734}
735
736
737void
738MSNet::closeSimulation(SUMOTime start, const std::string& reason) {
739 // report the end when wished
740 WRITE_MESSAGE(TLF("Simulation ended at time: %.", time2string(getCurrentTimeStep())));
741 if (reason != "") {
742 WRITE_MESSAGE(TL("Reason: ") + reason);
743 }
745 if (MSStopOut::active() && OptionsCont::getOptions().getBool("stop-output.write-unfinished")) {
747 }
748 MSDevice_Vehroutes::writePendingOutput(OptionsCont::getOptions().getBool("vehroute-output.write-unfinished"));
749 if (OptionsCont::getOptions().getBool("tripinfo-output.write-unfinished")) {
751 }
752 if (OptionsCont::getOptions().isSet("chargingstations-output")) {
753 if (!OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
755 } else if (OptionsCont::getOptions().getBool("chargingstations-output.aggregated.write-unfinished")) {
756 MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"), true);
757 }
758 }
759 if (OptionsCont::getOptions().isSet("overheadwiresegments-output")) {
761 }
762 if (OptionsCont::getOptions().isSet("substations-output")) {
764 }
766 const long now = SysUtils::getCurrentMillis();
767 if (myLogExecutionTime || OptionsCont::getOptions().getBool("duration-log.statistics")) {
769 }
770 if (OptionsCont::getOptions().isSet("statistic-output")) {
771 writeStatistics(start, now);
772 }
773 // maybe write a final line of output if reporting is periodic
774 writeSummaryOutput(true);
775}
776
777
778void
779MSNet::simulationStep(const bool onlyMove) {
781 postMoveStep();
783 return;
784 }
785#ifdef DEBUG_SIMSTEP
786 std::cout << SIMTIME << ": MSNet::simulationStep() called"
787 << ", myStep = " << myStep
788 << std::endl;
789#endif
791 int lastTraCICmd = 0;
792 if (t != nullptr) {
793 if (myLogExecutionTime) {
795 }
796 lastTraCICmd = t->processCommands(myStep);
797#ifdef DEBUG_SIMSTEP
798 bool loadRequested = !TraCI::getLoadArgs().empty();
799 assert(t->getTargetTime() >= myStep || loadRequested || TraCIServer::wasClosed());
800#endif
801 if (myLogExecutionTime) {
803 }
804 if (TraCIServer::wasClosed() || !t->getLoadArgs().empty()) {
805 return;
806 }
807 }
808#ifdef DEBUG_SIMSTEP
809 std::cout << SIMTIME << ": TraCI target time: " << t->getTargetTime() << std::endl;
810#endif
811 // execute beginOfTimestepEvents
812 if (myLogExecutionTime) {
814 }
815 // simulation state output
816 std::vector<SUMOTime>::iterator timeIt = std::find(myStateDumpTimes.begin(), myStateDumpTimes.end(), myStep);
817 if (timeIt != myStateDumpTimes.end()) {
818 const int dist = (int)distance(myStateDumpTimes.begin(), timeIt);
820 }
821 if (myStateDumpPeriod > 0 && myStep % myStateDumpPeriod == 0) {
822 std::string timeStamp = time2string(myStep);
823 std::replace(timeStamp.begin(), timeStamp.end(), ':', '-');
824 const std::string filename = myStateDumpPrefix + "_" + timeStamp + myStateDumpSuffix;
826 myPeriodicStateFiles.push_back(filename);
827 int keep = OptionsCont::getOptions().getInt("save-state.period.keep");
828 if (keep > 0 && (int)myPeriodicStateFiles.size() > keep) {
829 std::remove(myPeriodicStateFiles.front().c_str());
831 }
832 }
836 }
837#ifdef HAVE_FOX
838 MSRoutingEngine::waitForAll();
839#endif
842 }
843 // check whether the tls programs need to be switched
845
848 } else {
849 // assure all lanes with vehicles are 'active'
851
852 // compute safe velocities for all vehicles for the next few lanes
853 // also register ApproachingVehicleInformation for all links
855
856 // register junction approaches based on planned velocities as basis for right-of-way decision
858
859 // decide right-of-way and execute movements
863 }
864
865 // vehicles may change lanes
867
870 }
871 }
872 // flush arrived meso vehicles and micro vehicles that were removed due to collision
874 loadRoutes();
875
876 // persons
879 }
880 // containers
883 }
886 // preserve waitRelation from insertion for the next step
887 }
888 // insert vehicles
891#ifdef HAVE_FOX
892 MSRoutingEngine::waitForAll();
893#endif
896 //myEdges->patchActiveLanes(); // @note required to detect collisions on lanes that were empty before insertion. wasteful?
898 }
900
901 // execute endOfTimestepEvents
903
904 if (myLogExecutionTime) {
906 }
907 if (onlyMove) {
909 return;
910 }
911 if (t != nullptr && lastTraCICmd == libsumo::CMD_EXECUTEMOVE) {
912 t->processCommands(myStep, true);
913 }
914 postMoveStep();
915}
916
917
918void
920 const int numControlled = libsumo::Helper::postProcessRemoteControl();
921 if (numControlled > 0 && MSGlobals::gCheck4Accidents) {
923 }
924 if (myLogExecutionTime) {
927 }
929 // collisions from the previous step were kept to avoid duplicate
930 // warnings. we must remove them now to ensure correct output.
932 }
933 // update and write (if needed) detector values
935 writeOutput();
936
937 if (myLogExecutionTime) {
939 if (myPersonControl != nullptr) {
941 }
942 }
943 myStep += DELTA_T;
944}
945
946
951 }
952 if (TraCIServer::getInstance() != nullptr && !TraCIServer::getInstance()->getLoadArgs().empty()) {
953 return SIMSTATE_LOADING;
954 }
955 if ((stopTime < 0 || myStep > stopTime) && TraCIServer::getInstance() == nullptr && (stopTime > 0 || myStep > myEdgeDataEndTime)) {
958 && (myPersonControl == nullptr || !myPersonControl->hasNonWaiting())
962 }
963 }
964 if (stopTime >= 0 && myStep >= stopTime) {
966 }
969 }
970 if (myAmInterrupted) {
972 }
973 return SIMSTATE_RUNNING;
974}
975
976
978MSNet::adaptToState(MSNet::SimulationState state, const bool isLibsumo) const {
979 if (state == SIMSTATE_LOADING) {
982 } else if (state != SIMSTATE_RUNNING && ((TraCIServer::getInstance() != nullptr && !TraCIServer::wasClosed()) || isLibsumo)) {
983 // overrides SIMSTATE_END_STEP_REACHED, e.g. (TraCI / Libsumo ignore SUMO's --end option)
984 return SIMSTATE_RUNNING;
985 } else if (state == SIMSTATE_NO_FURTHER_VEHICLES) {
986 if (myPersonControl != nullptr) {
988 }
989 if (myContainerControl != nullptr) {
991 }
993 }
994 return state;
995}
996
997
998std::string
1000 switch (state) {
1002 return "";
1004 return TL("The final simulation step has been reached.");
1006 return TL("All vehicles have left the simulation.");
1008 return TL("TraCI requested termination.");
1010 return TL("An error occurred (see log).");
1012 return TL("Interrupted.");
1014 return TL("Too many teleports.");
1016 return TL("TraCI issued load command.");
1017 default:
1018 return TL("Unknown reason.");
1019 }
1020}
1021
1022
1023void
1025 // clear container
1026 MSEdge::clear();
1027 MSLane::clear();
1032 while (!MSLaneSpeedTrigger::getInstances().empty()) {
1033 delete MSLaneSpeedTrigger::getInstances().begin()->second;
1034 }
1035 while (!MSTriggeredRerouter::getInstances().empty()) {
1036 delete MSTriggeredRerouter::getInstances().begin()->second;
1037 }
1046 if (t != nullptr) {
1047 t->cleanup();
1048 }
1051}
1052
1053
1054void
1055MSNet::clearState(const SUMOTime step, bool quickReload) {
1059 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1060 for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*edge); s != nullptr; s = s->getNextSegment()) {
1061 s->clearState();
1062 }
1063 }
1064 } else {
1065 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1066 for (MSLane* const lane : edge->getLanes()) {
1067 lane->getVehiclesSecure();
1068 lane->clearState();
1069 lane->releaseVehicles();
1070 }
1071 edge->clearState();
1072 }
1073 }
1075 // detectors may still reference persons/vehicles
1079
1080 if (myPersonControl != nullptr) {
1082 }
1083 if (myContainerControl != nullptr) {
1085 }
1086 // delete vtypes after transportables have removed their types
1090 // delete all routes after vehicles and detector output is done
1092 for (auto& item : myStoppingPlaces) {
1093 for (auto& item2 : item.second) {
1094 item2.second->clearState();
1095 }
1096 }
1103 myStep = step;
1104 MSGlobals::gClearState = false;
1105}
1106
1107
1108void
1110 // update detector values
1113
1114 // check state dumps
1115 if (oc.isSet("netstate-dump")) {
1117 oc.getInt("netstate-dump.precision"));
1118 }
1119
1120 // check fcd dumps
1121 if (OptionsCont::getOptions().isSet("fcd-output")) {
1122 if (OptionsCont::getOptions().isSet("person-fcd-output")) {
1125 } else {
1127 }
1128 }
1129
1130 // check emission dumps
1131 if (OptionsCont::getOptions().isSet("emission-output")) {
1133 }
1134
1135 // battery dumps
1136 if (OptionsCont::getOptions().isSet("battery-output")) {
1138 oc.getInt("battery-output.precision"));
1139 }
1140
1141 // charging station aggregated dumps
1142 if (OptionsCont::getOptions().isSet("chargingstations-output") && OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
1144 }
1145
1146 // elecHybrid dumps
1147 if (OptionsCont::getOptions().isSet("elechybrid-output")) {
1148 std::string output = OptionsCont::getOptions().getString("elechybrid-output");
1149
1150 if (oc.getBool("elechybrid-output.aggregated")) {
1151 // build a xml file with aggregated device.elechybrid output
1153 oc.getInt("elechybrid-output.precision"));
1154 } else {
1155 // build a separate xml file for each vehicle equipped with device.elechybrid
1156 // RICE_TODO: Does this have to be placed here in MSNet.cpp ?
1158 for (MSVehicleControl::constVehIt it = vc.loadedVehBegin(); it != vc.loadedVehEnd(); ++it) {
1159 const SUMOVehicle* veh = it->second;
1160 if (!veh->isOnRoad()) {
1161 continue;
1162 }
1163 if (static_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid))) != nullptr) {
1164 std::string vehID = veh->getID();
1165 std::string filename2 = output + "_" + vehID + ".xml";
1166 OutputDevice& dev = OutputDevice::getDevice(filename2);
1167 std::map<SumoXMLAttr, std::string> attrs;
1168 attrs[SUMO_ATTR_VEHICLE] = vehID;
1171 dev.writeXMLHeader("elecHybrid-export", "", attrs);
1172 MSElecHybridExport::write(OutputDevice::getDevice(filename2), veh, myStep, oc.getInt("elechybrid-output.precision"));
1173 }
1174 }
1175 }
1176 }
1177
1178
1179 // check full dumps
1180 if (OptionsCont::getOptions().isSet("full-output")) {
1183 }
1184
1185 // check queue dumps
1186 if (OptionsCont::getOptions().isSet("queue-output")) {
1188 }
1189
1190 // check amitran dumps
1191 if (OptionsCont::getOptions().isSet("amitran-output")) {
1193 }
1194
1195 // check vtk dumps
1196 if (OptionsCont::getOptions().isSet("vtk-output")) {
1197
1198 if (MSNet::getInstance()->getVehicleControl().getRunningVehicleNo() > 0) {
1199 std::string timestep = time2string(myStep);
1200 timestep = timestep.substr(0, timestep.length() - 3);
1201 std::string output = OptionsCont::getOptions().getString("vtk-output");
1202 std::string filename = output + "_" + timestep + ".vtp";
1203
1204 OutputDevice_File dev(filename);
1205
1206 //build a huge mass of xml files
1208
1209 }
1210
1211 }
1212
1214
1215 // write detector values
1217
1218 // write link states
1219 if (OptionsCont::getOptions().isSet("link-output")) {
1220 OutputDevice& od = OutputDevice::getDeviceByOption("link-output");
1221 od.openTag("timestep");
1223 for (const MSEdge* const edge : myEdges->getEdges()) {
1224 for (const MSLane* const lane : edge->getLanes()) {
1225 for (const MSLink* const link : lane->getLinkCont()) {
1226 link->writeApproaching(od, lane->getID());
1227 }
1228 }
1229 }
1230 od.closeTag();
1231 }
1232
1233 // write SSM output
1235 dev->updateAndWriteOutput();
1236 }
1237
1238 // write ToC output
1240 if (dev->generatesOutput()) {
1241 dev->writeOutput();
1242 }
1243 }
1244
1245 if (OptionsCont::getOptions().isSet("collision-output")) {
1247 }
1248}
1249
1250
1251bool
1255
1256
1259 if (myPersonControl == nullptr) {
1261 }
1262 return *myPersonControl;
1263}
1264
1265
1268 if (myContainerControl == nullptr) {
1270 }
1271 return *myContainerControl;
1272}
1273
1276 myDynamicShapeUpdater = std::unique_ptr<MSDynamicShapeUpdater> (new MSDynamicShapeUpdater(*myShapeContainer));
1277 return myDynamicShapeUpdater.get();
1278}
1279
1282 if (myEdgeWeights == nullptr) {
1284 }
1285 return *myEdgeWeights;
1286}
1287
1288
1289void
1291 std::cout << "Step #" << time2string(myStep);
1292}
1293
1294
1295void
1297 if (myLogExecutionTime) {
1298 std::ostringstream oss;
1299 oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
1300 oss.setf(std::ios::showpoint); // print decimal point
1301 oss << std::setprecision(gPrecision);
1302 if (mySimStepDuration != 0) {
1303 const double durationSec = (double)mySimStepDuration / 1000.;
1304 oss << " (" << mySimStepDuration << "ms ~= "
1305 << (TS / durationSec) << "*RT, ~"
1306 << ((double) myVehicleControl->getRunningVehicleNo() / durationSec);
1307 } else {
1308 oss << " (0ms ?*RT. ?";
1309 }
1310 oss << "UPS, ";
1311 if (TraCIServer::getInstance() != nullptr) {
1312 oss << "TraCI: " << myTraCIStepDuration << "ms, ";
1313 }
1314 oss << "vehicles TOT " << myVehicleControl->getDepartedVehicleNo()
1315 << " ACT " << myVehicleControl->getRunningVehicleNo()
1316 << " BUF " << myInserter->getWaitingVehicleNo()
1317 << ") ";
1318 std::string prev = "Step #" + time2string(myStep - DELTA_T);
1319 std::cout << oss.str().substr(0, 90 - prev.length());
1320 }
1321 std::cout << '\r';
1322}
1323
1324
1325void
1327 if (find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener) == myVehicleStateListeners.end()) {
1328 myVehicleStateListeners.push_back(listener);
1329 }
1330}
1331
1332
1333void
1335 std::vector<VehicleStateListener*>::iterator i = std::find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener);
1336 if (i != myVehicleStateListeners.end()) {
1337 myVehicleStateListeners.erase(i);
1338 }
1339}
1340
1341
1342void
1343MSNet::informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info) {
1344#ifdef HAVE_FOX
1345 ScopedLocker<> lock(myVehicleStateListenerMutex, MSGlobals::gNumThreads > 1);
1346#endif
1347 for (VehicleStateListener* const listener : myVehicleStateListeners) {
1348 listener->vehicleStateChanged(vehicle, to, info);
1349 }
1350}
1351
1352
1353void
1359
1360
1361void
1363 std::vector<TransportableStateListener*>::iterator i = std::find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener);
1364 if (i != myTransportableStateListeners.end()) {
1366 }
1367}
1368
1369
1370void
1371MSNet::informTransportableStateListener(const MSTransportable* const transportable, TransportableState to, const std::string& info) {
1372#ifdef HAVE_FOX
1373 ScopedLocker<> lock(myTransportableStateListenerMutex, MSGlobals::gNumThreads > 1);
1374#endif
1376 listener->transportableStateChanged(transportable, to, info);
1377 }
1378}
1379
1380
1381bool
1382MSNet::registerCollision(const SUMOTrafficObject* collider, const SUMOTrafficObject* victim, const std::string& collisionType, const MSLane* lane, double pos) {
1383 auto it = myCollisions.find(collider->getID());
1384 if (it != myCollisions.end()) {
1385 for (Collision& old : it->second) {
1386 if (old.victim == victim->getID()) {
1387 // collision from previous step continues
1388 old.continuationTime = myStep;
1389 return false;
1390 }
1391 }
1392 } else {
1393 // maybe the roles have been reversed
1394 auto it2 = myCollisions.find(victim->getID());
1395 if (it2 != myCollisions.end()) {
1396 for (Collision& old : it2->second) {
1397 if (old.victim == collider->getID()) {
1398 // collision from previous step continues (keep the old roles)
1399 old.continuationTime = myStep;
1400 return false;
1401 }
1402 }
1403 }
1404 }
1405 Collision c;
1406 c.victim = victim->getID();
1407 c.colliderType = collider->getVehicleType().getID();
1408 c.victimType = victim->getVehicleType().getID();
1409 c.colliderSpeed = collider->getSpeed();
1410 c.victimSpeed = victim->getSpeed();
1411 c.colliderFront = collider->getPosition();
1412 c.victimFront = victim->getPosition();
1413 c.colliderBack = collider->getPosition(-collider->getVehicleType().getLength());
1414 c.victimBack = victim->getPosition(-victim->getVehicleType().getLength());
1415 c.type = collisionType;
1416 c.lane = lane;
1417 c.pos = pos;
1418 c.time = myStep;
1420 myCollisions[collider->getID()].push_back(c);
1421 return true;
1422}
1423
1424
1425void
1427 for (auto it = myCollisions.begin(); it != myCollisions.end();) {
1428 for (auto it2 = it->second.begin(); it2 != it->second.end();) {
1429 if (it2->continuationTime != myStep) {
1430 it2 = it->second.erase(it2);
1431 } else {
1432 it2++;
1433 }
1434 }
1435 if (it->second.size() == 0) {
1436 it = myCollisions.erase(it);
1437 } else {
1438 it++;
1439 }
1440 }
1441}
1442
1443
1444bool
1446 if (category == SUMO_TAG_TRAIN_STOP) {
1447 category = SUMO_TAG_BUS_STOP;
1448 }
1449 const bool isNew = myStoppingPlaces[category].add(stop->getID(), stop);
1450 if (isNew && stop->getMyName() != "") {
1451 myNamedStoppingPlaces[category][stop->getMyName()].push_back(stop);
1452 }
1453 return isNew;
1454}
1455
1456
1457bool
1459 if (find(myTractionSubstations.begin(), myTractionSubstations.end(), substation) == myTractionSubstations.end()) {
1460 myTractionSubstations.push_back(substation);
1461 return true;
1462 }
1463 return false;
1464}
1465
1466
1468MSNet::getStoppingPlace(const std::string& id, const SumoXMLTag category) const {
1469 if (myStoppingPlaces.count(category) > 0) {
1470 return myStoppingPlaces.find(category)->second.get(id);
1471 }
1472 return nullptr;
1473}
1474
1475
1477MSNet::getStoppingPlace(const std::string& id) const {
1479 MSStoppingPlace* result = getStoppingPlace(id, category);
1480 if (result != nullptr) {
1481 return result;
1482 }
1483 }
1484 return nullptr;
1485}
1486
1487
1488std::string
1489MSNet::getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const {
1490 if (myStoppingPlaces.count(category) > 0) {
1491 for (const auto& it : myStoppingPlaces.find(category)->second) {
1492 MSStoppingPlace* stop = it.second;
1493 if (&stop->getLane() == lane && stop->getBeginLanePosition() - POSITION_EPS <= pos && stop->getEndLanePosition() + POSITION_EPS >= pos) {
1494 return stop->getID();
1495 }
1496 }
1497 }
1498 return "";
1499}
1500
1501
1502const std::vector<MSStoppingPlace*>&
1503MSNet::getStoppingPlaceAlternatives(const std::string& name, SumoXMLTag category) const {
1504 if (category == SUMO_TAG_TRAIN_STOP) {
1505 category = SUMO_TAG_BUS_STOP;
1506 }
1507 auto it = myNamedStoppingPlaces.find(category);
1508 if (it != myNamedStoppingPlaces.end()) {
1509 auto it2 = it->second.find(name);
1510 if (it2 != it->second.end()) {
1511 return it2->second;
1512 }
1513 }
1515}
1516
1517
1520 auto it = myStoppingPlaces.find(category);
1521 if (it != myStoppingPlaces.end()) {
1522 return it->second;
1523 } else {
1525 }
1526}
1527
1528
1529void
1532 OutputDevice& output = OutputDevice::getDeviceByOption("chargingstations-output");
1533 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_CHARGING_STATION)->second) {
1534 static_cast<MSChargingStation*>(it.second)->writeChargingStationOutput(output);
1535 }
1536 }
1537}
1538
1539
1540void
1542 if (OptionsCont::getOptions().isSet("railsignal-block-output")) {
1543 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-block-output");
1544 for (auto tls : myLogics->getAllLogics()) {
1545 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1546 if (rs != nullptr) {
1547 rs->writeBlocks(output, false);
1548 }
1549 }
1550 MSDriveWay::writeDepatureBlocks(output, false);
1551 }
1552 if (OptionsCont::getOptions().isSet("railsignal-vehicle-output")) {
1553 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-vehicle-output");
1554 for (auto tls : myLogics->getAllLogics()) {
1555 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1556 if (rs != nullptr) {
1557 rs->writeBlocks(output, true);
1558 }
1559 }
1560 MSDriveWay::writeDepatureBlocks(output, true);
1561 }
1562}
1563
1564
1565void
1568 OutputDevice& output = OutputDevice::getDeviceByOption("overheadwiresegments-output");
1569 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_OVERHEAD_WIRE_SEGMENT)->second) {
1570 static_cast<MSOverheadWire*>(it.second)->writeOverheadWireSegmentOutput(output);
1571 }
1572 }
1573}
1574
1575
1576void
1578 if (myTractionSubstations.size() > 0) {
1579 OutputDevice& output = OutputDevice::getDeviceByOption("substations-output");
1580 output.setPrecision(OptionsCont::getOptions().getInt("substations-output.precision"));
1581 for (auto& it : myTractionSubstations) {
1582 it->writeTractionSubstationOutput(output);
1583 }
1584 }
1585}
1586
1587
1589MSNet::findTractionSubstation(const std::string& substationId) {
1590 for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1591 if ((*it)->getID() == substationId) {
1592 return *it;
1593 }
1594 }
1595 return nullptr;
1596}
1597
1598
1599bool
1600MSNet::existTractionSubstation(const std::string& substationId) {
1601 for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1602 if ((*it)->getID() == substationId) {
1603 return true;
1604 }
1605 }
1606 return false;
1607}
1608
1609
1611MSNet::getRouterTT(int rngIndex, const Prohibitions& prohibited) const {
1612 if (MSGlobals::gNumSimThreads == 1) {
1613 rngIndex = 0;
1614 }
1615 if (myRouterTT.count(rngIndex) == 0) {
1616 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1617 if (routingAlgorithm == "dijkstra") {
1618 myRouterTT[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, false, nullptr, true);
1619 } else {
1620 if (routingAlgorithm != "astar") {
1621 WRITE_WARNINGF(TL("TraCI and Triggers cannot use routing algorithm '%'. using 'astar' instead."), routingAlgorithm);
1622 }
1624 }
1625 }
1626 myRouterTT[rngIndex]->prohibit(prohibited);
1627 return *myRouterTT[rngIndex];
1628}
1629
1630
1632MSNet::getRouterEffort(int rngIndex, const Prohibitions& prohibited) const {
1633 if (MSGlobals::gNumSimThreads == 1) {
1634 rngIndex = 0;
1635 }
1636 if (myRouterEffort.count(rngIndex) == 0) {
1638 }
1639 myRouterEffort[rngIndex]->prohibit(prohibited);
1640 return *myRouterEffort[rngIndex];
1641}
1642
1643
1645MSNet::getPedestrianRouter(int rngIndex, const Prohibitions& prohibited) const {
1646 if (MSGlobals::gNumSimThreads == 1) {
1647 rngIndex = 0;
1648 }
1649 if (myPedestrianRouter.count(rngIndex) == 0) {
1650 myPedestrianRouter[rngIndex] = new MSPedestrianRouter();
1651 }
1652 myPedestrianRouter[rngIndex]->prohibit(prohibited);
1653 return *myPedestrianRouter[rngIndex];
1654}
1655
1656
1658MSNet::getIntermodalRouter(int rngIndex, const int routingMode, const Prohibitions& prohibited) const {
1659 if (MSGlobals::gNumSimThreads == 1) {
1660 rngIndex = 0;
1661 }
1663 const int key = rngIndex * oc.getInt("thread-rngs") + routingMode;
1664 if (myIntermodalRouter.count(key) == 0) {
1666 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1667 const double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1668 if (routingMode == libsumo::ROUTING_MODE_COMBINED) {
1669 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode, new FareModul());
1670 } else {
1671 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode);
1672 }
1673 }
1674 myIntermodalRouter[key]->prohibit(prohibited);
1675 return *myIntermodalRouter[key];
1676}
1677
1678
1679void
1681 double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1682 // add access to all parking areas
1683 EffortCalculator* const external = router.getExternalEffort();
1684 for (const auto& stopType : myInstance->myStoppingPlaces) {
1685 // add access to all stopping places
1686 const SumoXMLTag element = stopType.first;
1687 for (const auto& i : stopType.second) {
1688 const MSEdge* const edge = &i.second->getLane().getEdge();
1689 router.getNetwork()->addAccess(i.first, edge, i.second->getBeginLanePosition(), i.second->getEndLanePosition(),
1690 0., element, false, taxiWait);
1691 if (element == SUMO_TAG_BUS_STOP) {
1692 // add access to all public transport stops
1693 for (const auto& a : i.second->getAllAccessPos()) {
1694 router.getNetwork()->addAccess(i.first, &a.lane->getEdge(), a.startPos, a.endPos, a.length, element, true, taxiWait);
1695 }
1696 if (external != nullptr) {
1697 external->addStop(router.getNetwork()->getStopEdge(i.first)->getNumericalID(), *i.second);
1698 }
1699 }
1700 }
1701 }
1704 // add access to transfer from walking to taxi-use
1706 for (MSEdge* edge : myInstance->getEdgeControl().getEdges()) {
1707 if ((edge->getPermissions() & SVC_PEDESTRIAN) != 0 && (edge->getPermissions() & SVC_TAXI) != 0) {
1708 router.getNetwork()->addCarAccess(edge, SVC_TAXI, taxiWait);
1709 }
1710 }
1711 }
1712}
1713
1714
1715bool
1717 const MSEdgeVector& edges = myEdges->getEdges();
1718 for (MSEdgeVector::const_iterator e = edges.begin(); e != edges.end(); ++e) {
1719 for (std::vector<MSLane*>::const_iterator i = (*e)->getLanes().begin(); i != (*e)->getLanes().end(); ++i) {
1720 if ((*i)->getShape().hasElevation()) {
1721 return true;
1722 }
1723 }
1724 }
1725 return false;
1726}
1727
1728
1729bool
1731 for (const MSEdge* e : myEdges->getEdges()) {
1732 if (e->getFunction() == SumoXMLEdgeFunc::WALKINGAREA) {
1733 return true;
1734 }
1735 }
1736 return false;
1737}
1738
1739
1740bool
1742 for (const MSEdge* e : myEdges->getEdges()) {
1743 if (e->getBidiEdge() != nullptr) {
1744 return true;
1745 }
1746 }
1747 return false;
1748}
1749
1750bool
1751MSNet::warnOnce(const std::string& typeAndID) {
1752 if (myWarnedOnce.find(typeAndID) == myWarnedOnce.end()) {
1753 myWarnedOnce[typeAndID] = true;
1754 return true;
1755 }
1756 return false;
1757}
1758
1759
1762 auto loader = myRouteLoaders->getFirstLoader();
1763 if (loader != nullptr) {
1764 return dynamic_cast<MSMapMatcher*>(loader->getRouteHandler());
1765 } else {
1766 return nullptr;
1767 }
1768}
1769
1770void
1773 clearState(string2time(oc.getString("begin")), true);
1775 // load traffic from additional files
1776 for (std::string file : oc.getStringVector("additional-files")) {
1777 // ignore failure on parsing calibrator flow
1778 MSRouteHandler rh(file, true);
1779 const long before = PROGRESS_BEGIN_TIME_MESSAGE("Loading traffic from '" + file + "'");
1780 if (!XMLSubSys::runParser(rh, file, false)) {
1781 throw ProcessError(TLF("Loading of % failed.", file));
1782 }
1783 PROGRESS_TIME_MESSAGE(before);
1784 }
1785 delete myRouteLoaders;
1787 updateGUI();
1788}
1789
1790
1792MSNet::loadState(const std::string& fileName, const bool catchExceptions) {
1793 // load time only
1794 const SUMOTime newTime = MSStateHandler::MSStateTimeHandler::getTime(fileName);
1795 // clean up state
1796 clearState(newTime);
1797 // load state
1798 MSStateHandler h(fileName, 0);
1799 XMLSubSys::runParser(h, fileName, false, false, false, catchExceptions);
1800 if (MsgHandler::getErrorInstance()->wasInformed()) {
1801 throw ProcessError(TLF("Loading state from '%' failed.", fileName));
1802 }
1803 // reset route loaders
1804 delete myRouteLoaders;
1806 // prevent loading errors on rewound route file
1808
1809 updateGUI();
1810 return newTime;
1811}
1812
1813
1814/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
@ TAXI_PICKUP_ANYWHERE
taxi customer may be picked up anywhere
std::vector< MSEdge * > MSEdgeVector
Definition MSEdge.h:73
IntermodalRouter< MSEdge, MSLane, MSJunction, SUMOVehicle > MSTransportableRouter
PedestrianRouter< MSEdge, MSLane, MSJunction, SUMOVehicle > MSPedestrianRouter
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:287
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:289
#define WRITE_MESSAGE(msg)
Definition MsgHandler.h:288
#define PROGRESS_BEGIN_TIME_MESSAGE(msg)
Definition MsgHandler.h:292
#define TL(string)
Definition MsgHandler.h:304
#define PROGRESS_TIME_MESSAGE(before)
Definition MsgHandler.h:293
#define TLF(string,...)
Definition MsgHandler.h:306
std::string elapsedMs2string(long long int t)
convert ms to string for log output
Definition SUMOTime.cpp:145
SUMOTime DELTA_T
Definition SUMOTime.cpp:38
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 SIMSTEP
Definition SUMOTime.h:64
#define TS
Definition SUMOTime.h:45
#define SIMTIME
Definition SUMOTime.h:65
SUMOVehicleClass
Definition of vehicle classes to differ between different lane usage and authority types.
@ SVC_TAXI
vehicle is a taxi
@ SVC_PEDESTRIAN
pedestrian
SumoXMLTag
Numbers representing SUMO-XML - element names.
@ SUMO_TAG_CHARGING_STATION
A Charging Station.
@ SUMO_TAG_CONTAINER_STOP
A container stop.
@ SUMO_TAG_BUS_STOP
A bus stop.
@ SUMO_TAG_VEHICLE
description of a vehicle
@ SUMO_TAG_PARKING_AREA
A parking area.
@ SUMO_TAG_TRAIN_STOP
A train stop (alias for bus stop)
@ SUMO_TAG_OVERHEAD_WIRE_SEGMENT
An overhead wire segment.
@ SUMO_TAG_PERSON
@ SUMO_ATTR_MAXIMUMBATTERYCAPACITY
Maxium battery capacity.
@ SUMO_ATTR_VEHICLE
@ SUMO_ATTR_RECUPERATIONENABLE
@ SUMO_ATTR_ID
bool gRoutingPreferences
Definition StdDefs.cpp:37
int gPrecision
the precision for floating point outputs
Definition StdDefs.cpp:27
std::pair< int, double > MMVersion
(M)ajor/(M)inor version for written networks and default version for loading
Definition StdDefs.h:71
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
Computes the shortest path through a network using the A* algorithm.
Definition AStarRouter.h:76
Computes the shortest path through a network using the Dijkstra algorithm.
the effort calculator interface
virtual void addStop(const int stopEdge, const Parameterised &params)=0
int getNumericalID() const
void addCarAccess(const E *edge, SUMOVehicleClass svc, double traveltime)
Adds access edges for transfering from walking to vehicle use.
void addAccess(const std::string &stopId, const E *stopEdge, const double startPos, const double endPos, const double length, const SumoXMLTag category, bool isAccess, double taxiWait)
Adds access edges for stopping places to the intermodal network.
_IntermodalEdge * getStopEdge(const std::string &stopId) const
Returns the associated stop edge.
EffortCalculator * getExternalEffort() const
Network * getNetwork() const
int getCarWalkTransfer() const
The main mesocopic simulation loop.
Definition MELoop.h:47
void simulate(SUMOTime tMax)
Perform simulation up to the given time.
Definition MELoop.cpp:61
void clearState()
Remove all vehicles before quick-loading state.
Definition MELoop.cpp:245
A single mesoscopic segment (cell)
Definition MESegment.h:50
static void write(OutputDevice &of, const SUMOTime timestep)
Writes the complete network state into the given device.
const MSEdgeWeightsStorage & getWeightsStorage() const
Returns the vehicle's internal edge travel times/efforts container.
int getRoutingMode() const
return routing mode (configures router choice but also handling of transient permission changes)
static void write(OutputDevice &of, SUMOTime timestep, int precision)
Writes the complete network state of the given edges into the given device.
static void cleanup()
cleanup remaining data structures
static void write(OutputDevice &of, bool end=false)
Writes the recently completed charging events.
Detectors container; responsible for string and output generation.
void writeOutput(SUMOTime step, bool closing)
Writes the output to be generated within the given time step.
void clearState(SUMOTime step)
Remove all vehicles before quick-loading state.
void updateDetectors(const SUMOTime step)
Computes detector values.
void close(SUMOTime step)
Closes the detector outputs.
static void cleanup()
removes remaining vehicleInformation in sVehicles
A device which collects info on the vehicle trip (mainly on departure and arrival)
double getMaximumBatteryCapacity() const
Get the total vehicle's Battery Capacity in kWh.
A device which collects info on the vehicle trip (mainly on departure and arrival)
static const std::set< MSDevice_SSM *, ComparatorNumericalIdLess > & getInstances()
returns all currently existing SSM devices
static void cleanup()
Clean up remaining devices instances.
static bool hasFleet()
returns whether taxis have been loaded
static bool hasServableReservations()
check whether there are still (servable) reservations in the system
The ToC Device controls transition of control between automated and manual driving.
static void cleanup()
Closes root tags of output files.
static const std::set< MSDevice_ToC *, ComparatorNumericalIdLess > & getInstances()
returns all currently existing ToC devices
static void writeStatistics(OutputDevice &od)
write statistic output to (xml) file
static std::string printStatistics()
get statistics for printing to stdout
static void generateOutputForUnfinished()
generate output for vehicles which are still in the network
static void writePendingOutput(const bool includeUnfinished)
generate vehroute output for pending vehicles at sim end, either due to sorting or because they are s...
static void cleanupAll()
perform cleanup for all devices
Definition MSDevice.cpp:149
static void clearState()
static void writeDepatureBlocks(OutputDevice &od, bool writeVehicles)
static void init()
static void cleanup()
Stores edges and lanes, performs moving of vehicle.
void setJunctionApproaches()
Register junction approaches for all vehicles after velocities have been planned. This is a prerequis...
void patchActiveLanes()
Resets information whether a lane is active for all lanes.
void detectCollisions(SUMOTime timestep, const std::string &stage)
Detect collisions.
void executeMovements(SUMOTime t)
Executes planned vehicle movements with regards to right-of-way.
const MSEdgeVector & getEdges() const
Returns loaded edges.
void planMovements(SUMOTime t)
Compute safe velocities for all vehicles based on positions and speeds from the last time step....
void changeLanes(const SUMOTime t)
Moves (precomputes) critical vehicles.
A road/street connecting two junctions.
Definition MSEdge.h:77
static const MSEdgeVector & getAllEdges()
Returns all edges with a numerical id.
Definition MSEdge.cpp:1114
static void clear()
Clears the dictionary.
Definition MSEdge.cpp:1120
double getMinimumTravelTime(const SUMOVehicle *const veh) const
returns the minimum travel time for the given vehicle
Definition MSEdge.h:485
A storage for edge travel times and efforts.
bool retrieveExistingTravelTime(const MSEdge *const e, const double t, double &value) const
Returns a travel time for an edge and time if stored.
bool retrieveExistingEffort(const MSEdge *const e, const double t, double &value) const
Returns an effort for an edge and time if stored.
static void writeAggregated(OutputDevice &of, SUMOTime timestep, int precision)
static void write(OutputDevice &of, const SUMOVehicle *veh, SUMOTime timestep, int precision)
Writes the complete network state of the given edges into the given device.
static void write(OutputDevice &of, SUMOTime timestep)
Writes emission values into the given device.
Stores time-dependant events and executes them at the proper time.
virtual void execute(SUMOTime time)
Executes time-dependant commands.
void clearState(SUMOTime currentTime, SUMOTime newTime)
Remove all events before quick-loading state.
static void write(OutputDevice &of, const SUMOTime timestep, const SumoXMLTag tag=SUMO_TAG_NOTHING)
Writes the position and the angle of each vehicle into the given device.
static void write(OutputDevice &of, SUMOTime timestep)
Dumping a hugh List of Parameters available in the Simulation.
static bool gUseMesoSim
Definition MSGlobals.h:106
static double gWeightsSeparateTurns
Whether turning specific weights are estimated (and how much)
Definition MSGlobals.h:177
static bool gOverheadWireRecuperation
Definition MSGlobals.h:124
static MELoop * gMesoNet
mesoscopic simulation infrastructure
Definition MSGlobals.h:112
static bool gStateLoaded
Information whether a state has been loaded.
Definition MSGlobals.h:103
static bool gCheck4Accidents
Definition MSGlobals.h:88
static bool gClearState
whether the simulation is in the process of clearing state (MSNet::clearState)
Definition MSGlobals.h:143
static bool gHaveEmissions
Whether emission output of some type is needed (files or GUI)
Definition MSGlobals.h:183
static int gNumSimThreads
how many threads to use for simulation
Definition MSGlobals.h:146
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition MSGlobals.h:81
static int gNumThreads
how many threads to use
Definition MSGlobals.h:149
Inserts vehicles into the network when their departure time is reached.
void adaptIntermodalRouter(MSTransportableRouter &router) const
int getWaitingVehicleNo() const
Returns the number of waiting vehicles.
int emitVehicles(SUMOTime time)
Emits vehicles that want to depart at the given time.
bool hasFlow(const std::string &id) const
checks whether the given flow still exists
void determineCandidates(SUMOTime time)
Checks for all vehicles whether they can be emitted.
int getPendingFlowCount() const
Returns the number of flows that are still active.
void clearState()
Remove all vehicles before quick-loading state.
Container for junctions; performs operations on all stored junctions.
Representation of a lane in the micro simulation.
Definition MSLane.h:84
static void clear()
Clears the dictionary.
Definition MSLane.cpp:2519
static const std::map< std::string, MSLaneSpeedTrigger * > & getInstances()
return all MSLaneSpeedTrigger instances
Interface for objects listening to transportable state changes.
Definition MSNet.h:718
Interface for objects listening to vehicle state changes.
Definition MSNet.h:659
The simulated network and simulation perfomer.
Definition MSNet.h:89
std::map< SumoXMLTag, NamedObjectCont< MSStoppingPlace * > > myStoppingPlaces
Dictionary of bus / container stops.
Definition MSNet.h:1009
long myTraCIMillis
The overall time spent waiting for traci operations including.
Definition MSNet.h:947
MSMapMatcher * getMapMatcher() const
Definition MSNet.cpp:1761
static double getEffort(const MSEdge *const e, const SUMOVehicle *const v, double t)
Returns the effort to pass an edge.
Definition MSNet.cpp:153
bool warnOnce(const std::string &typeAndID)
return whether a warning regarding the given object shall be issued
Definition MSNet.cpp:1751
SUMOTime loadState(const std::string &fileName, const bool catchExceptions)
load state from file and return new time
Definition MSNet.cpp:1792
bool myLogExecutionTime
Information whether the simulation duration shall be logged.
Definition MSNet.h:933
MSTransportableControl * myPersonControl
Controls person building and deletion;.
Definition MSNet.h:902
void removeVehicleStateListener(VehicleStateListener *listener)
Removes a vehicle states listener.
Definition MSNet.cpp:1334
SUMORouteLoaderControl * myRouteLoaders
Route loader for dynamic loading of routes.
Definition MSNet.h:880
std::map< std::string, std::map< std::string, double > > myVTypePreferences
Definition MSNet.h:982
void informTransportableStateListener(const MSTransportable *const transportable, TransportableState to, const std::string &info="")
Informs all added listeners about a transportable's state change.
Definition MSNet.cpp:1371
SUMOTime myStateDumpPeriod
The period for writing state.
Definition MSNet.h:966
static const NamedObjectCont< MSStoppingPlace * > myEmptyStoppingPlaceCont
Definition MSNet.h:1033
void writeOverheadWireSegmentOutput() const
write the output generated by an overhead wire segment
Definition MSNet.cpp:1566
void writeChargingStationOutput() const
write charging station output
Definition MSNet.cpp:1530
std::pair< bool, NamedRTree > myLanesRTree
An RTree structure holding lane IDs.
Definition MSNet.h:1050
bool checkBidiEdges()
check wether bidirectional edges occur in the network
Definition MSNet.cpp:1741
VehicleState
Definition of a vehicle state.
Definition MSNet.h:626
int myLogStepPeriod
Period between successive step-log outputs.
Definition MSNet.h:938
SUMOTime myStep
Current time step.
Definition MSNet.h:883
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:187
bool myHasBidiEdges
Whether the network contains bidirectional rail edges.
Definition MSNet.h:1000
bool addStoppingPlace(SumoXMLTag category, MSStoppingPlace *stop)
Adds a stopping place.
Definition MSNet.cpp:1445
void addPreference(const std::string &routingType, SUMOVehicleClass svc, double prio)
add edge type specific routing preference
Definition MSNet.cpp:395
MSEventControl * myBeginOfTimestepEvents
Controls events executed at the begin of a time step;.
Definition MSNet.h:916
bool addTractionSubstation(MSTractionSubstation *substation)
Adds a traction substation.
Definition MSNet.cpp:1458
std::map< std::string, bool > myWarnedOnce
container to record warnings that shall only be issued once
Definition MSNet.h:1037
static void initStatic()
Place for static initializations of simulation components (called after successful net build)
Definition MSNet.cpp:195
void removeOutdatedCollisions()
remove collisions from the previous simulation step
Definition MSNet.cpp:1426
MSJunctionControl * myJunctions
Controls junctions, realizes right-of-way rules;.
Definition MSNet.h:908
std::map< const MSEdge *, RouterProhibition > Prohibitions
Definition MSNet.h:132
std::vector< std::string > myPeriodicStateFiles
The names of the last K periodic state files (only only K shall be kept)
Definition MSNet.h:964
ShapeContainer * myShapeContainer
A container for geometrical shapes;.
Definition MSNet.h:922
std::string myStateDumpSuffix
Definition MSNet.h:969
const std::vector< MSStoppingPlace * > & getStoppingPlaceAlternatives(const std::string &name, SumoXMLTag category) const
Definition MSNet.cpp:1503
bool checkElevation()
check all lanes for elevation data
Definition MSNet.cpp:1716
MSTransportableRouter & getIntermodalRouter(int rngIndex, const int routingMode=0, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1658
bool existTractionSubstation(const std::string &substationId)
return whether given electrical substation exists in the network
Definition MSNet.cpp:1600
std::map< SumoXMLTag, std::map< std::string, std::vector< MSStoppingPlace * > > > myNamedStoppingPlaces
dictionary of named stopping places
Definition MSNet.h:1012
static const std::vector< MSStoppingPlace * > myEmptyStoppingPlaceVector
Definition MSNet.h:1034
void removeTransportableStateListener(TransportableStateListener *listener)
Removes a transportable states listener.
Definition MSNet.cpp:1362
SimulationState adaptToState(const SimulationState state, const bool isLibsumo=false) const
Called after a simulation step, this method adapts the current simulation state if necessary.
Definition MSNet.cpp:978
void closeBuilding(const OptionsCont &oc, MSEdgeControl *edges, MSJunctionControl *junctions, SUMORouteLoaderControl *routeLoaders, MSTLLogicControl *tlc, std::vector< SUMOTime > stateDumpTimes, std::vector< std::string > stateDumpFiles, bool hasInternalLinks, bool junctionHigherSpeeds, const MMVersion &version)
Closes the network's building process.
Definition MSNet.cpp:259
bool myLogStepNumber
Information whether the number of the simulation step shall be logged.
Definition MSNet.h:936
MMVersion myVersion
the network version
Definition MSNet.h:1003
MSEventControl * myInsertionEvents
Controls insertion events;.
Definition MSNet.h:920
virtual MSTransportableControl & getContainerControl()
Returns the container control.
Definition MSNet.cpp:1267
MSVehicleRouter & getRouterTT(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1611
SimulationState
Possible states of a simulation - running or stopped with different reasons.
Definition MSNet.h:94
@ SIMSTATE_TOO_MANY_TELEPORTS
The simulation had too many teleports.
Definition MSNet.h:110
@ SIMSTATE_NO_FURTHER_VEHICLES
The simulation does not contain further vehicles.
Definition MSNet.h:102
@ SIMSTATE_LOADING
The simulation is loading.
Definition MSNet.h:96
@ SIMSTATE_ERROR_IN_SIM
An error occurred during the simulation step.
Definition MSNet.h:106
@ SIMSTATE_CONNECTION_CLOSED
The connection to a client was closed by the client.
Definition MSNet.h:104
@ SIMSTATE_INTERRUPTED
An external interrupt occurred.
Definition MSNet.h:108
@ SIMSTATE_RUNNING
The simulation is running.
Definition MSNet.h:98
@ SIMSTATE_END_STEP_REACHED
The final simulation step has been performed.
Definition MSNet.h:100
std::map< int, MSPedestrianRouter * > myPedestrianRouter
Definition MSNet.h:1046
static const std::string STAGE_MOVEMENTS
Definition MSNet.h:853
bool hasFlow(const std::string &id) const
return whether the given flow is known
Definition MSNet.cpp:436
int myMaxTeleports
Maximum number of teleports.
Definition MSNet.h:889
long mySimStepDuration
Definition MSNet.h:941
double getPreference(const std::string &routingType, const SUMOVTypeParameter &pars) const
retriefe edge type specific routing preference
Definition MSNet.cpp:365
MSEventControl * myEndOfTimestepEvents
Controls events executed at the end of a time step;.
Definition MSNet.h:918
static std::string getStateMessage(SimulationState state)
Returns the message to show if a certain state occurs.
Definition MSNet.cpp:999
std::string getStoppingPlaceID(const MSLane *lane, const double pos, const SumoXMLTag category) const
Returns the stop of the given category close to the given position.
Definition MSNet.cpp:1489
bool myHasInternalLinks
Whether the network contains internal links/lanes/edges.
Definition MSNet.h:988
void writeSubstationOutput() const
write electrical substation output
Definition MSNet.cpp:1577
static const std::string STAGE_INSERTIONS
Definition MSNet.h:855
std::map< SUMOVehicleClass, std::map< std::string, double > > myVClassPreferences
Preferences for routing.
Definition MSNet.h:981
long long int myPersonsMoved
Definition MSNet.h:951
void quickReload()
reset state to the beginning without reloading the network
Definition MSNet.cpp:1771
MSPedestrianRouter & getPedestrianRouter(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1645
MSVehicleControl * myVehicleControl
Controls vehicle building and deletion;.
Definition MSNet.h:900
static void clearAll()
Clears all dictionaries.
Definition MSNet.cpp:1024
static void cleanupStatic()
Place for static initializations of simulation components (called after successful net build)
Definition MSNet.cpp:201
void writeStatistics(const SUMOTime start, const long now) const
write statistic output to (xml) file
Definition MSNet.cpp:620
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:334
MSEdgeControl * myEdges
Controls edges, performs vehicle movement;.
Definition MSNet.h:906
std::unique_ptr< MSDynamicShapeUpdater > myDynamicShapeUpdater
Updater for dynamic shapes that are tracking traffic objects (ensures removal of shape dynamics when ...
Definition MSNet.h:1055
const std::map< SUMOVehicleClass, double > * getRestrictions(const std::string &id) const
Returns the restrictions for an edge type If no restrictions are present, 0 is returned.
Definition MSNet.cpp:355
void closeSimulation(SUMOTime start, const std::string &reason="")
Closes the simulation (all files, connections, etc.)
Definition MSNet.cpp:738
MSStoppingPlace * getStoppingPlace(const std::string &id, const SumoXMLTag category) const
Returns the named stopping place of the given category.
Definition MSNet.cpp:1468
bool myHasElevation
Whether the network contains elevation data.
Definition MSNet.h:994
static double getTravelTime(const MSEdge *const e, const SUMOVehicle *const v, double t)
Returns the travel time to pass an edge.
Definition MSNet.cpp:167
MSTransportableControl * myContainerControl
Controls container building and deletion;.
Definition MSNet.h:904
std::vector< TransportableStateListener * > myTransportableStateListeners
Container for transportable state listener.
Definition MSNet.h:1021
void writeOutput()
Write netstate, summary and detector output.
Definition MSNet.cpp:1109
virtual void updateGUI() const
update view after simulation.loadState
Definition MSNet.h:614
bool myAmInterrupted
whether an interrupt occurred
Definition MSNet.h:892
void simulationStep(const bool onlyMove=false)
Performs a single simulation step.
Definition MSNet.cpp:779
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1326
void clearState(const SUMOTime step, bool quickReload=false)
Resets events when quick-loading state.
Definition MSNet.cpp:1055
void preSimStepOutput() const
Prints the current step number.
Definition MSNet.cpp:1290
void writeCollisions() const
write collision output to (xml) file
Definition MSNet.cpp:591
std::vector< SUMOTime > myStateDumpTimes
Times at which a state shall be written.
Definition MSNet.h:960
void writeSummaryOutput(bool finalStep=false)
write summary-output to (xml) file
Definition MSNet.cpp:670
void addTransportableStateListener(TransportableStateListener *listener)
Adds a transportable states listener.
Definition MSNet.cpp:1354
std::vector< MSTractionSubstation * > myTractionSubstations
Dictionary of traction substations.
Definition MSNet.h:1015
SUMOTime myEdgeDataEndTime
end of loaded edgeData
Definition MSNet.h:1006
MSEdgeWeightsStorage & getWeightsStorage()
Returns the net's internal edge travel times/efforts container.
Definition MSNet.cpp:1281
std::map< std::string, std::map< SUMOVehicleClass, double > > myRestrictions
The vehicle class specific speed restrictions.
Definition MSNet.h:978
std::vector< std::string > myStateDumpFiles
The names for the state files.
Definition MSNet.h:962
void addMesoType(const std::string &typeID, const MESegment::MesoEdgeType &edgeType)
Adds edge type specific meso parameters.
Definition MSNet.cpp:408
void writeRailSignalBlocks() const
write rail signal block output
Definition MSNet.cpp:1541
MSTLLogicControl * myLogics
Controls tls logics, realizes waiting on tls rules;.
Definition MSNet.h:910
bool logSimulationDuration() const
Returns whether duration shall be logged.
Definition MSNet.cpp:1252
long long int myVehiclesMoved
The overall number of vehicle movements.
Definition MSNet.h:950
static const std::string STAGE_REMOTECONTROL
Definition MSNet.h:856
void informVehicleStateListener(const SUMOVehicle *const vehicle, VehicleState to, const std::string &info="")
Informs all added listeners about a vehicle's state change.
Definition MSNet.cpp:1343
std::map< int, MSTransportableRouter * > myIntermodalRouter
Definition MSNet.h:1047
std::vector< VehicleStateListener * > myVehicleStateListeners
Container for vehicle state listener.
Definition MSNet.h:1018
SimulationState simulationState(SUMOTime stopTime) const
This method returns the current simulation state. It should not modify status.
Definition MSNet.cpp:948
long myTraCIStepDuration
The last simulation step duration.
Definition MSNet.h:941
TransportableState
Definition of a transportable state.
Definition MSNet.h:703
MSInsertionControl & getInsertionControl()
Returns the insertion control.
Definition MSNet.h:445
MSDetectorControl * myDetectorControl
Controls detectors;.
Definition MSNet.h:914
bool myStepCompletionMissing
whether libsumo triggered a partial step (executeMove)
Definition MSNet.h:886
static const std::string STAGE_LANECHANGE
Definition MSNet.h:854
MSNet(MSVehicleControl *vc, MSEventControl *beginOfTimestepEvents, MSEventControl *endOfTimestepEvents, MSEventControl *insertionEvents, ShapeContainer *shapeCont=0)
Constructor.
Definition MSNet.cpp:208
void addRestriction(const std::string &id, const SUMOVehicleClass svc, const double speed)
Adds a restriction for an edge type.
Definition MSNet.cpp:349
std::map< std::string, MESegment::MesoEdgeType > myMesoEdgeTypes
The edge type specific meso parameters.
Definition MSNet.h:985
MSEdgeWeightsStorage * myEdgeWeights
The net's knowledge about edge efforts/travel times;.
Definition MSNet.h:924
MSDynamicShapeUpdater * makeDynamicShapeUpdater()
Creates and returns a dynamic shapes updater.
Definition MSNet.cpp:1275
virtual ~MSNet()
Destructor.
Definition MSNet.cpp:294
std::map< int, MSVehicleRouter * > myRouterEffort
Definition MSNet.h:1045
MSTractionSubstation * findTractionSubstation(const std::string &substationId)
find electrical substation by its id
Definition MSNet.cpp:1589
static MSNet * myInstance
Unique instance of MSNet.
Definition MSNet.h:877
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition MSNet.h:392
MSInsertionControl * myInserter
Controls vehicle insertion;.
Definition MSNet.h:912
void postSimStepOutput() const
Prints the statistics of the step at its end.
Definition MSNet.cpp:1296
virtual MSTransportableControl & getPersonControl()
Returns the person control.
Definition MSNet.cpp:1258
bool registerCollision(const SUMOTrafficObject *collider, const SUMOTrafficObject *victim, const std::string &collisionType, const MSLane *lane, double pos)
register collision and return whether it was the first one involving these vehicles
Definition MSNet.cpp:1382
static const std::string STAGE_EVENTS
string constants for simstep stages
Definition MSNet.h:852
void loadRoutes()
loads routes for the next few steps
Definition MSNet.cpp:485
std::string myStateDumpPrefix
name components for periodic state
Definition MSNet.h:968
bool myJunctionHigherSpeeds
Whether the network was built with higher speed on junctions.
Definition MSNet.h:991
MSEdgeControl & getEdgeControl()
Returns the edge control.
Definition MSNet.h:435
long mySimBeginMillis
The overall simulation duration.
Definition MSNet.h:944
bool myHasPedestrianNetwork
Whether the network contains pedestrian network elements.
Definition MSNet.h:997
std::map< int, MSVehicleRouter * > myRouterTT
Definition MSNet.h:1044
const MESegment::MesoEdgeType & getMesoType(const std::string &typeID)
Returns edge type specific meso parameters if no type specific parameters have been loaded,...
Definition MSNet.cpp:413
void postMoveStep()
Performs the parts of the simulation step which happen after the move.
Definition MSNet.cpp:919
bool hasInternalLinks() const
return whether the network contains internal links
Definition MSNet.h:798
const std::string generateStatistics(const SUMOTime start, const long now)
Writes performance output and running vehicle stats.
Definition MSNet.cpp:491
bool checkWalkingarea()
check all lanes for type walkingArea
Definition MSNet.cpp:1730
static void adaptIntermodalRouter(MSTransportableRouter &router)
Definition MSNet.cpp:1680
CollisionMap myCollisions
collisions in the current time step
Definition MSNet.h:1024
MSVehicleRouter & getRouterEffort(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1632
const NamedObjectCont< MSStoppingPlace * > & getStoppingPlaces(SumoXMLTag category) const
Definition MSNet.cpp:1519
SimulationState simulate(SUMOTime start, SUMOTime stop)
Simulates from timestep start to stop.
Definition MSNet.cpp:443
Definition of overhead wire segment.
static void write(OutputDevice &of, SUMOTime timestep)
Export the queueing length in front of a junction (very experimental!)
static void cleanup()
clean up state
static MSRailSignalControl & getInstance()
void updateSignals(SUMOTime t)
update active rail signals
static void clearState()
Perform resets events when quick-loading state.
void resetWaitRelations()
reset all waiting-for relationships at the start of the simulation step
A signal for rails.
void writeBlocks(OutputDevice &od, bool writeVehicles) const
write rail signal block output for all links and driveways
Parser and container for routes during their loading.
static void dict_clearState()
Decrement all route references before quick-loading state.
Definition MSRoute.cpp:308
static void clear()
Clears the dictionary (delete all known routes, too)
Definition MSRoute.cpp:181
static double getEffortExtra(const MSEdge *const e, const SUMOVehicle *const v, double t)
static SUMOTime getTime(const std::string &fileName)
parse time from state file
Parser and output filter for routes and vehicles state saving and loading.
static void saveState(const std::string &file, SUMOTime step, bool usePrefix=true)
Saves the current state.
static bool active()
Definition MSStopOut.h:54
static void cleanup()
Definition MSStopOut.cpp:50
void generateOutputForUnfinished()
generate output for vehicles which are still stopped at simulation end
static MSStopOut * getInstance()
Definition MSStopOut.h:60
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.
const std::string & getMyName() const
A class that stores and controls tls and switching of their programs.
void clearState(SUMOTime time, bool quickReload=false)
Clear all tls states before quick-loading state.
std::vector< MSTrafficLightLogic * > getAllLogics() const
Returns a vector which contains all logics.
void check2Switch(SUMOTime step)
Checks whether any WAUT is trying to switch a tls into another program.
Traction substation powering one or more overhead wire sections.
int getRunningNumber() const
Returns the number of build and inserted, but not yet deleted transportables.
bool hasTransportables() const
checks whether any transportable waits to finish her plan
int getWaitingForVehicleNumber() const
Returns the number of transportables waiting for a ride.
int getEndedNumber() const
Returns the number of transportables that exited the simulation.
void checkWaiting(MSNet *net, const SUMOTime time)
checks whether any transportables waiting time is over
int getArrivedNumber() const
Returns the number of transportables that arrived at their destination.
int getTeleportCount() const
Returns the number of teleports transportables did.
int getLoadedNumber() const
Returns the number of build transportables.
int getWaitingUntilNumber() const
Returns the number of transportables waiting for a specified amount of time.
int getTeleportsWrongDest() const
return the number of teleports of transportables riding to the wrong destination
void abortAnyWaitingForVehicle()
aborts the plan for any transportable that is still waiting for a ride
bool hasNonWaiting() const
checks whether any transportable is still engaged in walking / stopping
int getMovingNumber() const
Returns the number of transportables moving by themselvs (i.e. walking)
int getJammedNumber() const
Returns the number of times a transportables was jammed.
void clearState()
Resets transportables when quick-loading state.
int getTeleportsAbortWait() const
return the number of teleports due to excessive waiting for a ride
int getDiscardedNumber() const
Returns the number of discarded transportables.
int getRidingNumber() const
Returns the number of transportables riding a vehicle.
static const std::map< std::string, MSTriggeredRerouter * > & getInstances()
return all rerouter instances
static void write(OutputDevice &of, SUMOTime timestep)
Produce a VTK output to use with Tools like ParaView.
static void cleanup()
Static cleanup.
The class responsible for building and deletion of vehicles.
void adaptIntermodalRouter(MSTransportableRouter &router) const
int getRunningVehicleNo() const
Returns the number of build and inserted, but not yet deleted vehicles.
void removePending()
Removes a vehicle after it has ended.
double getTotalTravelTime() const
Returns the total travel time.
int getLoadedVehicleNo() const
Returns the number of build vehicles.
int getCollisionCount() const
return the number of collisions
int getTeleportsWrongLane() const
return the number of teleports due to vehicles stuck on the wrong lane
int getStoppedVehiclesCount() const
return the number of vehicles that are currently stopped
int getTeleportsYield() const
return the number of teleports due to vehicles stuck on a minor road
void clearState(const bool reinit)
Remove all vehicles before quick-loading state.
int getEmergencyBrakingCount() const
return the number of emergency stops
int getEmergencyStops() const
return the number of emergency stops
double getTotalDepartureDelay() const
Returns the total departure delay.
virtual std::pair< double, double > getVehicleMeanSpeeds() const
get current absolute and relative mean vehicle speed in the network
int getDepartedVehicleNo() const
Returns the number of inserted vehicles.
int getArrivedVehicleNo() const
Returns the number of arrived vehicles.
int getActiveVehicleCount() const
Returns the number of build vehicles that have not been removed or need to wait for a passenger or a ...
std::map< std::string, SUMOVehicle * >::const_iterator constVehIt
Definition of the internal vehicles map iterator.
int getTeleportsJam() const
return the number of teleports due to jamming
int getEndedVehicleNo() const
Returns the number of removed vehicles.
virtual int getHaltingVehicleNo() const
Returns the number of halting vehicles.
constVehIt loadedVehBegin() const
Returns the begin of the internal vehicle map.
int getTeleportCount() const
return the number of teleports (including collisions)
void abortWaiting()
informes about all waiting vehicles (deletion in destructor)
constVehIt loadedVehEnd() const
Returns the end of the internal vehicle map.
int getDiscardedVehicleNo() const
Returns the number of discarded vehicles.
Representation of a vehicle in the micro simulation.
Definition MSVehicle.h:77
static MSVehicleTransfer * getInstance()
Returns the instance of this object.
void checkInsertions(SUMOTime time)
Checks "movement" of stored vehicles.
void clearState()
Remove all vehicles before quick-loading state.
const std::string & getID() const
Returns the name of the vehicle type.
double getLength() const
Get vehicle's length [m].
static void write(OutputDevice &of, const MSEdgeControl &ec, SUMOTime timestep, int precision)
Writes the complete network state of the given edges into the given device.
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
static SUMORouteLoaderControl * buildRouteLoaderControl(const OptionsCont &oc)
Builds the route loader control.
static void initRandomness()
initializes all RNGs
const std::string & getID() const
Returns the id.
Definition Named.h:74
A map of named object pointers.
A storage for options typed value containers)
Definition OptionsCont.h:89
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
int getInt(const std::string &name) const
Returns the int-value of the named option (only for Option_Integer)
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
const StringVector & getStringVector(const std::string &name) const
Returns the list of string-value of the named option (only for Option_StringVector)
static OptionsCont & getOptions()
Retrieves the options.
static void setArgs(int argc, char **argv)
Stores the command line arguments for later parsing.
Definition OptionsIO.cpp:58
An output device that encapsulates an ofstream.
Static storage of an output device and its base (abstract) implementation.
OutputDevice & writeAttr(const SumoXMLAttr attr, const T &val)
writes a named attribute
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
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.
void setPrecision(int precision=gPrecision)
Sets the precision or resets it to default.
static void closeAll(bool keepErrorRetrievers=false)
static OutputDevice & getDevice(const std::string &name, bool usePrefix=true)
Returns the described OutputDevice.
bool writeXMLHeader(const std::string &rootElement, const std::string &schemaFile, std::map< SumoXMLAttr, std::string > attrs=std::map< SumoXMLAttr, std::string >(), bool includeConfig=true)
Writes an XML header with optional configuration.
SUMORouteLoader * getFirstLoader() const
return a route loader
void loadNext(SUMOTime step)
loads the next routes up to and including the given time step
Representation of a vehicle, person, or container.
virtual const MSVehicleType & getVehicleType() const =0
Returns the object's "vehicle" type.
virtual MSDevice * getDevice(const std::type_info &type) const =0
Returns a device of the given type if it exists or nullptr if not.
virtual double getSpeed() const =0
Returns the object's current speed.
virtual Position getPosition(const double offset=0) const =0
Return current position (x/y, cartesian)
Structure representing possible vehicle parameter.
SUMOVehicleClass vehicleClass
The vehicle's class.
std::string id
The vehicle type's id.
Representation of a vehicle.
Definition SUMOVehicle.h:63
virtual bool isOnRoad() const =0
Returns the information whether the vehicle is on a road (is simulated)
static int parseCarWalkTransfer(const OptionsCont &oc, const bool hasTaxi)
A scoped lock which only triggers on condition.
Storage for geometrical objects.
void clearState()
Remove all dynamics before quick-loading state.
static long getCurrentMillis()
Returns the current time in milliseconds.
Definition SysUtils.cpp:44
TraCI server used to control sumo by a remote TraCI client.
Definition TraCIServer.h:59
static bool wasClosed()
check whether close was requested
SUMOTime getTargetTime() const
Definition TraCIServer.h:64
static TraCIServer * getInstance()
Definition TraCIServer.h:68
std::vector< std::string > & getLoadArgs()
void cleanup()
clean up subscriptions
int processCommands(const SUMOTime step, const bool afterMove=false)
process all commands until the next SUMO simulation step. It is guaranteed that t->getTargetTime() >=...
static bool runParser(GenericSAXHandler &handler, const std::string &file, const bool isNet=false, const bool isRoute=false, const bool isExternal=false, const bool catchExceptions=true)
Runs the given handler on the given file; returns if everything's ok.
static void cleanup()
Definition Helper.cpp:700
static int postProcessRemoteControl()
return number of remote-controlled entities
Definition Helper.cpp:1415
TRACI_CONST int CMD_EXECUTEMOVE
TRACI_CONST int ROUTING_MODE_AGGREGATED_CUSTOM
TRACI_CONST int ROUTING_MODE_COMBINED
edge type specific meso parameters
Definition MESegment.h:58
collision tracking
Definition MSNet.h:114
double victimSpeed
Definition MSNet.h:119
Position colliderFront
Definition MSNet.h:120
const MSLane * lane
Definition MSNet.h:125
Position victimBack
Definition MSNet.h:123
std::string victimType
Definition MSNet.h:117
SUMOTime continuationTime
Definition MSNet.h:128
Position victimFront
Definition MSNet.h:121
std::string type
Definition MSNet.h:124
std::string colliderType
Definition MSNet.h:116
std::string victim
Definition MSNet.h:115
double colliderSpeed
Definition MSNet.h:118
Position colliderBack
Definition MSNet.h:122
SUMOTime time
Definition MSNet.h:127