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-2025 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
147
148// ===========================================================================
149// static member method definitions
150// ===========================================================================
151double
152MSNet::getEffort(const MSEdge* const e, const SUMOVehicle* const v, double t) {
153 double value;
154 const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
155 if (veh != nullptr && veh->getWeightsStorage().retrieveExistingEffort(e, t, value)) {
156 return value;
157 }
159 return value;
160 }
161 return 0;
162}
163
164
165double
166MSNet::getTravelTime(const MSEdge* const e, const SUMOVehicle* const v, double t) {
167 double value;
168 const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
169 if (veh != nullptr && veh->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
170 return value;
171 }
173 return value;
174 }
175 if (veh != nullptr && veh->getRoutingMode() == libsumo::ROUTING_MODE_AGGREGATED_CUSTOM) {
176 return MSRoutingEngine::getEffortExtra(e, v, t);
177 }
178 return e->getMinimumTravelTime(v);
179}
180
181
182// ---------------------------------------------------------------------------
183// MSNet - methods
184// ---------------------------------------------------------------------------
185MSNet*
187 if (myInstance != nullptr) {
188 return myInstance;
189 }
190 throw ProcessError(TL("A network was not yet constructed."));
191}
192
193void
197
198void
204
205
206MSNet::MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents,
207 MSEventControl* endOfTimestepEvents,
208 MSEventControl* insertionEvents,
209 ShapeContainer* shapeCont):
210 myAmInterrupted(false),
211 myVehiclesMoved(0),
212 myPersonsMoved(0),
213 myHavePermissions(false),
214 myHasInternalLinks(false),
215 myJunctionHigherSpeeds(false),
216 myHasElevation(false),
217 myHasPedestrianNetwork(false),
218 myHasBidiEdges(false),
219 myEdgeDataEndTime(-1),
220 myDynamicShapeUpdater(nullptr) {
221 if (myInstance != nullptr) {
222 throw ProcessError(TL("A network was already constructed."));
223 }
225 myStep = string2time(oc.getString("begin"));
226 myMaxTeleports = oc.getInt("max-num-teleports");
227 myLogExecutionTime = !oc.getBool("no-duration-log");
228 myLogStepNumber = !oc.getBool("no-step-log");
229 myLogStepPeriod = oc.getInt("step-log.period");
230 myInserter = new MSInsertionControl(*vc, string2time(oc.getString("max-depart-delay")), oc.getBool("eager-insert"), oc.getInt("max-num-vehicles"),
231 string2time(oc.getString("random-depart-offset")));
232 myVehicleControl = vc;
234 myEdges = nullptr;
235 myJunctions = nullptr;
236 myRouteLoaders = nullptr;
237 myLogics = nullptr;
238 myPersonControl = nullptr;
239 myContainerControl = nullptr;
240 myEdgeWeights = nullptr;
241 myShapeContainer = shapeCont == nullptr ? new ShapeContainer() : shapeCont;
242
243 myBeginOfTimestepEvents = beginOfTimestepEvents;
244 myEndOfTimestepEvents = endOfTimestepEvents;
245 myInsertionEvents = insertionEvents;
246 myLanesRTree.first = false;
247
249 MSGlobals::gMesoNet = new MELoop(string2time(oc.getString("meso-recheck")));
250 }
251 myInstance = this;
252 initStatic();
253}
254
255
256void
258 SUMORouteLoaderControl* routeLoaders,
259 MSTLLogicControl* tlc,
260 std::vector<SUMOTime> stateDumpTimes,
261 std::vector<std::string> stateDumpFiles,
262 bool hasInternalLinks,
263 bool junctionHigherSpeeds,
264 const MMVersion& version) {
265 myEdges = edges;
266 myJunctions = junctions;
267 myRouteLoaders = routeLoaders;
268 myLogics = tlc;
269 // save the time the network state shall be saved at
270 myStateDumpTimes = stateDumpTimes;
271 myStateDumpFiles = stateDumpFiles;
272 myStateDumpPeriod = string2time(oc.getString("save-state.period"));
273 myStateDumpPrefix = oc.getString("save-state.prefix");
274 myStateDumpSuffix = oc.getString("save-state.suffix");
275
276 // initialise performance computation
278 myTraCIMillis = 0;
280 myJunctionHigherSpeeds = junctionHigherSpeeds;
284 myVersion = version;
287 throw ProcessError(TL("Option weights.separate-turns is only supported when simulating with internal lanes"));
288 }
289}
290
291
294 // delete controls
295 delete myJunctions;
296 delete myDetectorControl;
297 // delete mean data
298 delete myEdges;
299 delete myInserter;
300 myInserter = nullptr;
301 delete myLogics;
302 delete myRouteLoaders;
303 if (myPersonControl != nullptr) {
304 delete myPersonControl;
305 myPersonControl = nullptr; // just to have that clear for later cleanups
306 }
307 if (myContainerControl != nullptr) {
308 delete myContainerControl;
309 myContainerControl = nullptr; // just to have that clear for later cleanups
310 }
311 delete myVehicleControl; // must happen after deleting transportables
312 // delete events late so that vehicles can get rid of references first
314 myBeginOfTimestepEvents = nullptr;
316 myEndOfTimestepEvents = nullptr;
317 delete myInsertionEvents;
318 myInsertionEvents = nullptr;
319 delete myShapeContainer;
320 delete myEdgeWeights;
321 for (auto& router : myRouterTT) {
322 delete router.second;
323 }
324 myRouterTT.clear();
325 for (auto& router : myRouterEffort) {
326 delete router.second;
327 }
328 myRouterEffort.clear();
329 for (auto& router : myPedestrianRouter) {
330 delete router.second;
331 }
332 myPedestrianRouter.clear();
333 for (auto& router : myIntermodalRouter) {
334 delete router.second;
335 }
336 myIntermodalRouter.clear();
337 myLanesRTree.second.RemoveAll();
338 clearAll();
340 delete MSGlobals::gMesoNet;
341 }
342 myInstance = nullptr;
343}
344
345
346void
347MSNet::addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed) {
348 myRestrictions[id][svc] = speed;
349}
350
351
352const std::map<SUMOVehicleClass, double>*
353MSNet::getRestrictions(const std::string& id) const {
354 std::map<std::string, std::map<SUMOVehicleClass, double> >::const_iterator i = myRestrictions.find(id);
355 if (i == myRestrictions.end()) {
356 return nullptr;
357 }
358 return &i->second;
359}
360
361void
362MSNet::addMesoType(const std::string& typeID, const MESegment::MesoEdgeType& edgeType) {
363 myMesoEdgeTypes[typeID] = edgeType;
364}
365
367MSNet::getMesoType(const std::string& typeID) {
368 if (myMesoEdgeTypes.count(typeID) == 0) {
369 // init defaults
372 edgeType.tauff = string2time(oc.getString("meso-tauff"));
373 edgeType.taufj = string2time(oc.getString("meso-taufj"));
374 edgeType.taujf = string2time(oc.getString("meso-taujf"));
375 edgeType.taujj = string2time(oc.getString("meso-taujj"));
376 edgeType.jamThreshold = oc.getFloat("meso-jam-threshold");
377 edgeType.junctionControl = oc.getBool("meso-junction-control");
378 edgeType.tlsPenalty = oc.getFloat("meso-tls-penalty");
379 edgeType.tlsFlowPenalty = oc.getFloat("meso-tls-flow-penalty");
380 edgeType.minorPenalty = string2time(oc.getString("meso-minor-penalty"));
381 edgeType.overtaking = oc.getBool("meso-overtaking");
382 myMesoEdgeTypes[typeID] = edgeType;
383 }
384 return myMesoEdgeTypes[typeID];
385}
386
387
388bool
389MSNet::hasFlow(const std::string& id) const {
390 // inserter is deleted at the end of the simulation
391 return myInserter != nullptr && myInserter->hasFlow(id);
392}
393
394
397 // report the begin when wished
398 WRITE_MESSAGEF(TL("Simulation version % started with time: %."), VERSION_STRING, time2string(start));
399 // the simulation loop
401 // state loading may have changed the start time so we need to reinit it
402 myStep = start;
403 int numSteps = 0;
404 bool doStepLog = false;
405 while (state == SIMSTATE_RUNNING) {
406 doStepLog = myLogStepNumber && (numSteps % myLogStepPeriod == 0);
407 if (doStepLog) {
409 }
411 if (doStepLog) {
413 }
414 state = adaptToState(simulationState(stop));
415#ifdef DEBUG_SIMSTEP
416 std::cout << SIMTIME << " MSNet::simulate(" << start << ", " << stop << ")"
417 << "\n simulation state: " << getStateMessage(state)
418 << std::endl;
419#endif
420 numSteps++;
421 }
422 if (myLogStepNumber && !doStepLog) {
423 // ensure some output on the last step
426 }
427 // exit simulation loop
428 if (myLogStepNumber) {
429 // start new line for final verbose output
430 std::cout << "\n";
431 }
432 closeSimulation(start, getStateMessage(state));
433 return state;
434}
435
436
437void
441
442
443const std::string
444MSNet::generateStatistics(const SUMOTime start, const long now) {
445 std::ostringstream msg;
446 if (myLogExecutionTime) {
447 const long duration = now - mySimBeginMillis;
448 // print performance notice
449 msg << "Performance:\n" << " Duration: " << elapsedMs2string(duration) << "\n";
450 if (duration != 0) {
451 if (TraCIServer::getInstance() != nullptr) {
452 msg << " TraCI-Duration: " << elapsedMs2string(myTraCIMillis) << "\n";
453 }
454 msg << " Real time factor: " << (STEPS2TIME(myStep - start) * 1000. / (double)duration) << "\n";
455 msg.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
456 msg.setf(std::ios::showpoint); // print decimal point
457 msg << " UPS: " << ((double)myVehiclesMoved / ((double)duration / 1000)) << "\n";
458 if (myPersonsMoved > 0) {
459 msg << " UPS-Persons: " << ((double)myPersonsMoved / ((double)duration / 1000)) << "\n";
460 }
461 }
462 // print vehicle statistics
463 const std::string vehDiscardNotice = ((myVehicleControl->getLoadedVehicleNo() != myVehicleControl->getDepartedVehicleNo()) ?
464 " (Loaded: " + toString(myVehicleControl->getLoadedVehicleNo()) + ")" : "");
465 msg << "Vehicles:\n"
466 << " Inserted: " << myVehicleControl->getDepartedVehicleNo() << vehDiscardNotice << "\n"
467 << " Running: " << myVehicleControl->getRunningVehicleNo() << "\n"
468 << " Waiting: " << myInserter->getWaitingVehicleNo() << "\n";
469
471 // print optional teleport statistics
472 std::vector<std::string> reasons;
474 reasons.push_back("Collisions: " + toString(myVehicleControl->getCollisionCount()));
475 }
477 reasons.push_back("Jam: " + toString(myVehicleControl->getTeleportsJam()));
478 }
480 reasons.push_back("Yield: " + toString(myVehicleControl->getTeleportsYield()));
481 }
483 reasons.push_back("Wrong Lane: " + toString(myVehicleControl->getTeleportsWrongLane()));
484 }
485 msg << " Teleports: " << myVehicleControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
486 }
488 msg << " Emergency Stops: " << myVehicleControl->getEmergencyStops() << "\n";
489 }
491 msg << " Emergency Braking: " << myVehicleControl->getEmergencyBrakingCount() << "\n";
492 }
493 if (myPersonControl != nullptr && myPersonControl->getLoadedNumber() > 0) {
494 const std::string discardNotice = ((myPersonControl->getLoadedNumber() != myPersonControl->getDepartedNumber()) ?
495 " (Loaded: " + toString(myPersonControl->getLoadedNumber()) + ")" : "");
496 msg << "Persons:\n"
497 << " Inserted: " << myPersonControl->getDepartedNumber() << discardNotice << "\n"
498 << " Running: " << myPersonControl->getRunningNumber() << "\n";
499 if (myPersonControl->getJammedNumber() > 0) {
500 msg << " Jammed: " << myPersonControl->getJammedNumber() << "\n";
501 }
503 std::vector<std::string> reasons;
505 reasons.push_back("Abort Wait: " + toString(myPersonControl->getTeleportsAbortWait()));
506 }
508 reasons.push_back("Wrong Dest: " + toString(myPersonControl->getTeleportsWrongDest()));
509 }
510 msg << " Teleports: " << myPersonControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
511 }
512 }
513 if (myContainerControl != nullptr && myContainerControl->getLoadedNumber() > 0) {
514 const std::string discardNotice = ((myContainerControl->getLoadedNumber() != myContainerControl->getDepartedNumber()) ?
515 " (Loaded: " + toString(myContainerControl->getLoadedNumber()) + ")" : "");
516 msg << "Containers:\n"
517 << " Inserted: " << myContainerControl->getDepartedNumber() << "\n"
518 << " Running: " << myContainerControl->getRunningNumber() << "\n";
520 msg << " Jammed: " << myContainerControl->getJammedNumber() << "\n";
521 }
523 std::vector<std::string> reasons;
525 reasons.push_back("Abort Wait: " + toString(myContainerControl->getTeleportsAbortWait()));
526 }
528 reasons.push_back("Wrong Dest: " + toString(myContainerControl->getTeleportsWrongDest()));
529 }
530 msg << " Teleports: " << myContainerControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
531 }
532 }
533 }
534 if (OptionsCont::getOptions().getBool("duration-log.statistics")) {
536 }
537 std::string result = msg.str();
538 result.erase(result.end() - 1);
539 return result;
540}
541
542
543void
545 OutputDevice& od = OutputDevice::getDeviceByOption("collision-output");
546 for (const auto& item : myCollisions) {
547 for (const auto& c : item.second) {
548 if (c.time != SIMSTEP) {
549 continue;
550 }
551 od.openTag("collision");
553 od.writeAttr("type", c.type);
554 od.writeAttr("lane", c.lane->getID());
555 od.writeAttr("pos", c.pos);
556 od.writeAttr("collider", item.first);
557 od.writeAttr("victim", c.victim);
558 od.writeAttr("colliderType", c.colliderType);
559 od.writeAttr("victimType", c.victimType);
560 od.writeAttr("colliderSpeed", c.colliderSpeed);
561 od.writeAttr("victimSpeed", c.victimSpeed);
562 od.writeAttr("colliderFront", c.colliderFront);
563 od.writeAttr("colliderBack", c.colliderBack);
564 od.writeAttr("victimFront", c.victimFront);
565 od.writeAttr("victimBack", c.victimBack);
566 od.closeTag();
567 }
568 }
569}
570
571
572void
573MSNet::writeStatistics(const SUMOTime start, const long now) const {
574 const long duration = now - mySimBeginMillis;
575 OutputDevice& od = OutputDevice::getDeviceByOption("statistic-output");
576 od.openTag("performance");
577 od.writeAttr("clockBegin", time2string(mySimBeginMillis));
578 od.writeAttr("clockEnd", time2string(now));
579 od.writeAttr("clockDuration", time2string(duration));
580 od.writeAttr("traciDuration", time2string(myTraCIMillis));
581 od.writeAttr("realTimeFactor", duration != 0 ? (double)(myStep - start) / (double)duration : -1);
582 od.writeAttr("vehicleUpdatesPerSecond", duration != 0 ? (double)myVehiclesMoved / ((double)duration / 1000) : -1);
583 od.writeAttr("personUpdatesPerSecond", duration != 0 ? (double)myPersonsMoved / ((double)duration / 1000) : -1);
584 od.writeAttr("begin", time2string(start));
585 od.writeAttr("end", time2string(myStep));
586 od.writeAttr("duration", time2string(myStep - start));
587 od.closeTag();
588 od.openTag("vehicles");
592 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
593 od.closeTag();
594 od.openTag("teleports");
599 od.closeTag();
600 od.openTag("safety");
601 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
602 od.writeAttr("emergencyStops", myVehicleControl->getEmergencyStops());
603 od.writeAttr("emergencyBraking", myVehicleControl->getEmergencyBrakingCount());
604 od.closeTag();
605 od.openTag("persons");
606 od.writeAttr("loaded", myPersonControl != nullptr ? myPersonControl->getLoadedNumber() : 0);
607 od.writeAttr("running", myPersonControl != nullptr ? myPersonControl->getRunningNumber() : 0);
608 od.writeAttr("jammed", myPersonControl != nullptr ? myPersonControl->getJammedNumber() : 0);
609 od.closeTag();
610 od.openTag("personTeleports");
611 od.writeAttr("total", myPersonControl != nullptr ? myPersonControl->getTeleportCount() : 0);
612 od.writeAttr("abortWait", myPersonControl != nullptr ? myPersonControl->getTeleportsAbortWait() : 0);
613 od.writeAttr("wrongDest", myPersonControl != nullptr ? myPersonControl->getTeleportsWrongDest() : 0);
614 od.closeTag();
615 if (OptionsCont::getOptions().isSet("tripinfo-output") || OptionsCont::getOptions().getBool("duration-log.statistics")) {
617 }
618
619}
620
621
622void
624 // summary output
626 const bool hasOutput = oc.isSet("summary-output");
627 const bool hasPersonOutput = oc.isSet("person-summary-output");
628 if (hasOutput || hasPersonOutput) {
629 const SUMOTime period = string2time(oc.getString("summary-output.period"));
630 const SUMOTime begin = string2time(oc.getString("begin"));
631 if (period > 0 && (myStep - begin) % period != 0) {
632 return;
633 }
634 }
635 if (hasOutput) {
636 OutputDevice& od = OutputDevice::getDeviceByOption("summary-output");
637 int departedVehiclesNumber = myVehicleControl->getDepartedVehicleNo();
638 const double meanWaitingTime = departedVehiclesNumber != 0 ? myVehicleControl->getTotalDepartureDelay() / (double) departedVehiclesNumber : -1.;
639 int endedVehicleNumber = myVehicleControl->getEndedVehicleNo();
640 const double meanTravelTime = endedVehicleNumber != 0 ? myVehicleControl->getTotalTravelTime() / (double) endedVehicleNumber : -1.;
641 od.openTag("step");
642 od.writeAttr("time", time2string(myStep));
646 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
649 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
650 od.writeAttr("teleports", myVehicleControl->getTeleportCount());
653 od.writeAttr("meanWaitingTime", meanWaitingTime);
654 od.writeAttr("meanTravelTime", meanTravelTime);
655 std::pair<double, double> meanSpeed = myVehicleControl->getVehicleMeanSpeeds();
656 od.writeAttr("meanSpeed", meanSpeed.first);
657 od.writeAttr("meanSpeedRelative", meanSpeed.second);
658 if (myLogExecutionTime) {
659 od.writeAttr("duration", mySimStepDuration);
660 }
661 od.closeTag();
662 }
663 if (hasPersonOutput) {
664 OutputDevice& od = OutputDevice::getDeviceByOption("person-summary-output");
666 od.openTag("step");
667 od.writeAttr("time", time2string(myStep));
668 od.writeAttr("loaded", pc.getLoadedNumber());
669 od.writeAttr("inserted", pc.getDepartedNumber());
670 od.writeAttr("walking", pc.getMovingNumber());
671 od.writeAttr("waitingForRide", pc.getWaitingForVehicleNumber());
672 od.writeAttr("riding", pc.getRidingNumber());
673 od.writeAttr("stopping", pc.getWaitingUntilNumber());
674 od.writeAttr("jammed", pc.getJammedNumber());
675 od.writeAttr("ended", pc.getEndedNumber());
676 od.writeAttr("arrived", pc.getArrivedNumber());
677 od.writeAttr("teleports", pc.getTeleportCount());
678 if (myLogExecutionTime) {
679 od.writeAttr("duration", mySimStepDuration);
680 }
681 od.closeTag();
682 }
683}
684
685
686void
687MSNet::closeSimulation(SUMOTime start, const std::string& reason) {
688 // report the end when wished
689 WRITE_MESSAGE(TLF("Simulation ended at time: %.", time2string(getCurrentTimeStep())));
690 if (reason != "") {
691 WRITE_MESSAGE(TL("Reason: ") + reason);
692 }
694 if (MSStopOut::active() && OptionsCont::getOptions().getBool("stop-output.write-unfinished")) {
696 }
697 MSDevice_Vehroutes::writePendingOutput(OptionsCont::getOptions().getBool("vehroute-output.write-unfinished"));
698 if (OptionsCont::getOptions().getBool("tripinfo-output.write-unfinished")) {
700 }
701 if (OptionsCont::getOptions().isSet("chargingstations-output")) {
702 if (!OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
704 } else if (OptionsCont::getOptions().getBool("chargingstations-output.aggregated.write-unfinished")) {
705 MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"), true);
706 }
707 }
708 if (OptionsCont::getOptions().isSet("overheadwiresegments-output")) {
710 }
711 if (OptionsCont::getOptions().isSet("substations-output")) {
713 }
715 const long now = SysUtils::getCurrentMillis();
716 if (myLogExecutionTime || OptionsCont::getOptions().getBool("duration-log.statistics")) {
718 }
719 if (OptionsCont::getOptions().isSet("statistic-output")) {
720 writeStatistics(start, now);
721 }
722}
723
724
725void
726MSNet::simulationStep(const bool onlyMove) {
728 postMoveStep();
730 return;
731 }
732#ifdef DEBUG_SIMSTEP
733 std::cout << SIMTIME << ": MSNet::simulationStep() called"
734 << ", myStep = " << myStep
735 << std::endl;
736#endif
738 int lastTraCICmd = 0;
739 if (t != nullptr) {
740 if (myLogExecutionTime) {
742 }
743 lastTraCICmd = t->processCommands(myStep);
744#ifdef DEBUG_SIMSTEP
745 bool loadRequested = !TraCI::getLoadArgs().empty();
746 assert(t->getTargetTime() >= myStep || loadRequested || TraCIServer::wasClosed());
747#endif
748 if (myLogExecutionTime) {
750 }
751 if (TraCIServer::wasClosed() || !t->getLoadArgs().empty()) {
752 return;
753 }
754 }
755#ifdef DEBUG_SIMSTEP
756 std::cout << SIMTIME << ": TraCI target time: " << t->getTargetTime() << std::endl;
757#endif
758 // execute beginOfTimestepEvents
759 if (myLogExecutionTime) {
761 }
762 // simulation state output
763 std::vector<SUMOTime>::iterator timeIt = std::find(myStateDumpTimes.begin(), myStateDumpTimes.end(), myStep);
764 if (timeIt != myStateDumpTimes.end()) {
765 const int dist = (int)distance(myStateDumpTimes.begin(), timeIt);
767 }
768 if (myStateDumpPeriod > 0 && myStep % myStateDumpPeriod == 0) {
769 std::string timeStamp = time2string(myStep);
770 std::replace(timeStamp.begin(), timeStamp.end(), ':', '-');
771 const std::string filename = myStateDumpPrefix + "_" + timeStamp + myStateDumpSuffix;
773 myPeriodicStateFiles.push_back(filename);
774 int keep = OptionsCont::getOptions().getInt("save-state.period.keep");
775 if (keep > 0 && (int)myPeriodicStateFiles.size() > keep) {
776 std::remove(myPeriodicStateFiles.front().c_str());
778 }
779 }
783 }
784#ifdef HAVE_FOX
785 MSRoutingEngine::waitForAll();
786#endif
789 }
790 // check whether the tls programs need to be switched
792
795 } else {
796 // assure all lanes with vehicles are 'active'
798
799 // compute safe velocities for all vehicles for the next few lanes
800 // also register ApproachingVehicleInformation for all links
802
803 // register junction approaches based on planned velocities as basis for right-of-way decision
805
806 // decide right-of-way and execute movements
810 }
811
812 // vehicles may change lanes
814
817 }
818 }
819 // flush arrived meso vehicles and micro vehicles that were removed due to collision
821 loadRoutes();
822
823 // persons
826 }
827 // containers
830 }
833 // preserve waitRelation from insertion for the next step
834 }
835 // insert vehicles
838#ifdef HAVE_FOX
839 MSRoutingEngine::waitForAll();
840#endif
843 //myEdges->patchActiveLanes(); // @note required to detect collisions on lanes that were empty before insertion. wasteful?
845 }
847
848 // execute endOfTimestepEvents
850
851 if (myLogExecutionTime) {
853 }
854 if (onlyMove) {
856 return;
857 }
858 if (t != nullptr && lastTraCICmd == libsumo::CMD_EXECUTEMOVE) {
859 t->processCommands(myStep, true);
860 }
861 postMoveStep();
862}
863
864
865void
867 const int numControlled = libsumo::Helper::postProcessRemoteControl();
868 if (numControlled > 0 && MSGlobals::gCheck4Accidents) {
870 }
871 if (myLogExecutionTime) {
874 }
876 // collisions from the previous step were kept to avoid duplicate
877 // warnings. we must remove them now to ensure correct output.
879 }
880 // update and write (if needed) detector values
882 writeOutput();
883
884 if (myLogExecutionTime) {
886 if (myPersonControl != nullptr) {
888 }
889 }
890 myStep += DELTA_T;
891}
892
893
898 }
899 if (TraCIServer::getInstance() != nullptr && !TraCIServer::getInstance()->getLoadArgs().empty()) {
900 return SIMSTATE_LOADING;
901 }
902 if ((stopTime < 0 || myStep > stopTime) && TraCIServer::getInstance() == nullptr && (stopTime > 0 || myStep > myEdgeDataEndTime)) {
905 && (myPersonControl == nullptr || !myPersonControl->hasNonWaiting())
909 }
910 }
911 if (stopTime >= 0 && myStep >= stopTime) {
913 }
916 }
917 if (myAmInterrupted) {
919 }
920 return SIMSTATE_RUNNING;
921}
922
923
925MSNet::adaptToState(MSNet::SimulationState state, const bool isLibsumo) const {
926 if (state == SIMSTATE_LOADING) {
929 } else if (state != SIMSTATE_RUNNING && ((TraCIServer::getInstance() != nullptr && !TraCIServer::wasClosed()) || isLibsumo)) {
930 // overrides SIMSTATE_END_STEP_REACHED, e.g. (TraCI / Libsumo ignore SUMO's --end option)
931 return SIMSTATE_RUNNING;
932 } else if (state == SIMSTATE_NO_FURTHER_VEHICLES) {
933 if (myPersonControl != nullptr) {
935 }
936 if (myContainerControl != nullptr) {
938 }
940 }
941 return state;
942}
943
944
945std::string
947 switch (state) {
949 return "";
951 return TL("The final simulation step has been reached.");
953 return TL("All vehicles have left the simulation.");
955 return TL("TraCI requested termination.");
957 return TL("An error occurred (see log).");
959 return TL("Interrupted.");
961 return TL("Too many teleports.");
963 return TL("TraCI issued load command.");
964 default:
965 return TL("Unknown reason.");
966 }
967}
968
969
970void
972 // clear container
979 while (!MSLaneSpeedTrigger::getInstances().empty()) {
980 delete MSLaneSpeedTrigger::getInstances().begin()->second;
981 }
982 while (!MSTriggeredRerouter::getInstances().empty()) {
983 delete MSTriggeredRerouter::getInstances().begin()->second;
984 }
993 if (t != nullptr) {
994 t->cleanup();
995 }
998}
999
1000
1001void
1002MSNet::clearState(const SUMOTime step, bool quickReload) {
1006 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1007 for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*edge); s != nullptr; s = s->getNextSegment()) {
1008 s->clearState();
1009 }
1010 }
1011 } else {
1012 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1013 for (MSLane* const lane : edge->getLanes()) {
1014 lane->getVehiclesSecure();
1015 lane->clearState();
1016 lane->releaseVehicles();
1017 }
1018 edge->clearState();
1019 }
1020 }
1022 // detectors may still reference persons/vehicles
1026
1027 if (myPersonControl != nullptr) {
1029 }
1030 if (myContainerControl != nullptr) {
1032 }
1033 // delete vtypes after transportables have removed their types
1037 // delete all routes after vehicles and detector output is done
1039 for (auto& item : myStoppingPlaces) {
1040 for (auto& item2 : item.second) {
1041 item2.second->clearState();
1042 }
1043 }
1050 myStep = step;
1051 MSGlobals::gClearState = false;
1052}
1053
1054
1055void
1057 // update detector values
1060
1061 // check state dumps
1062 if (oc.isSet("netstate-dump")) {
1064 oc.getInt("netstate-dump.precision"));
1065 }
1066
1067 // check fcd dumps
1068 if (OptionsCont::getOptions().isSet("fcd-output")) {
1070 }
1071
1072 // check emission dumps
1073 if (OptionsCont::getOptions().isSet("emission-output")) {
1075 }
1076
1077 // battery dumps
1078 if (OptionsCont::getOptions().isSet("battery-output")) {
1080 oc.getInt("battery-output.precision"));
1081 }
1082
1083 // charging station aggregated dumps
1084 if (OptionsCont::getOptions().isSet("chargingstations-output") && OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
1086 }
1087
1088 // elecHybrid dumps
1089 if (OptionsCont::getOptions().isSet("elechybrid-output")) {
1090 std::string output = OptionsCont::getOptions().getString("elechybrid-output");
1091
1092 if (oc.getBool("elechybrid-output.aggregated")) {
1093 // build a xml file with aggregated device.elechybrid output
1095 oc.getInt("elechybrid-output.precision"));
1096 } else {
1097 // build a separate xml file for each vehicle equipped with device.elechybrid
1098 // RICE_TODO: Does this have to be placed here in MSNet.cpp ?
1100 for (MSVehicleControl::constVehIt it = vc.loadedVehBegin(); it != vc.loadedVehEnd(); ++it) {
1101 const SUMOVehicle* veh = it->second;
1102 if (!veh->isOnRoad()) {
1103 continue;
1104 }
1105 if (static_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid))) != nullptr) {
1106 std::string vehID = veh->getID();
1107 std::string filename2 = output + "_" + vehID + ".xml";
1108 OutputDevice& dev = OutputDevice::getDevice(filename2);
1109 std::map<SumoXMLAttr, std::string> attrs;
1110 attrs[SUMO_ATTR_VEHICLE] = vehID;
1113 dev.writeXMLHeader("elecHybrid-export", "", attrs);
1114 MSElecHybridExport::write(OutputDevice::getDevice(filename2), veh, myStep, oc.getInt("elechybrid-output.precision"));
1115 }
1116 }
1117 }
1118 }
1119
1120
1121 // check full dumps
1122 if (OptionsCont::getOptions().isSet("full-output")) {
1125 }
1126
1127 // check queue dumps
1128 if (OptionsCont::getOptions().isSet("queue-output")) {
1130 }
1131
1132 // check amitran dumps
1133 if (OptionsCont::getOptions().isSet("amitran-output")) {
1135 }
1136
1137 // check vtk dumps
1138 if (OptionsCont::getOptions().isSet("vtk-output")) {
1139
1140 if (MSNet::getInstance()->getVehicleControl().getRunningVehicleNo() > 0) {
1141 std::string timestep = time2string(myStep);
1142 timestep = timestep.substr(0, timestep.length() - 3);
1143 std::string output = OptionsCont::getOptions().getString("vtk-output");
1144 std::string filename = output + "_" + timestep + ".vtp";
1145
1146 OutputDevice_File dev(filename);
1147
1148 //build a huge mass of xml files
1150
1151 }
1152
1153 }
1154
1156
1157 // write detector values
1159
1160 // write link states
1161 if (OptionsCont::getOptions().isSet("link-output")) {
1162 OutputDevice& od = OutputDevice::getDeviceByOption("link-output");
1163 od.openTag("timestep");
1165 for (const MSEdge* const edge : myEdges->getEdges()) {
1166 for (const MSLane* const lane : edge->getLanes()) {
1167 for (const MSLink* const link : lane->getLinkCont()) {
1168 link->writeApproaching(od, lane->getID());
1169 }
1170 }
1171 }
1172 od.closeTag();
1173 }
1174
1175 // write SSM output
1177 dev->updateAndWriteOutput();
1178 }
1179
1180 // write ToC output
1182 if (dev->generatesOutput()) {
1183 dev->writeOutput();
1184 }
1185 }
1186
1187 if (OptionsCont::getOptions().isSet("collision-output")) {
1189 }
1190}
1191
1192
1193bool
1197
1198
1201 if (myPersonControl == nullptr) {
1203 }
1204 return *myPersonControl;
1205}
1206
1207
1210 if (myContainerControl == nullptr) {
1212 }
1213 return *myContainerControl;
1214}
1215
1218 myDynamicShapeUpdater = std::unique_ptr<MSDynamicShapeUpdater> (new MSDynamicShapeUpdater(*myShapeContainer));
1219 return myDynamicShapeUpdater.get();
1220}
1221
1224 if (myEdgeWeights == nullptr) {
1226 }
1227 return *myEdgeWeights;
1228}
1229
1230
1231void
1233 std::cout << "Step #" << time2string(myStep);
1234}
1235
1236
1237void
1239 if (myLogExecutionTime) {
1240 std::ostringstream oss;
1241 oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
1242 oss.setf(std::ios::showpoint); // print decimal point
1243 oss << std::setprecision(gPrecision);
1244 if (mySimStepDuration != 0) {
1245 const double durationSec = (double)mySimStepDuration / 1000.;
1246 oss << " (" << mySimStepDuration << "ms ~= "
1247 << (TS / durationSec) << "*RT, ~"
1248 << ((double) myVehicleControl->getRunningVehicleNo() / durationSec);
1249 } else {
1250 oss << " (0ms ?*RT. ?";
1251 }
1252 oss << "UPS, ";
1253 if (TraCIServer::getInstance() != nullptr) {
1254 oss << "TraCI: " << myTraCIStepDuration << "ms, ";
1255 }
1256 oss << "vehicles TOT " << myVehicleControl->getDepartedVehicleNo()
1257 << " ACT " << myVehicleControl->getRunningVehicleNo()
1258 << " BUF " << myInserter->getWaitingVehicleNo()
1259 << ") ";
1260 std::string prev = "Step #" + time2string(myStep - DELTA_T);
1261 std::cout << oss.str().substr(0, 90 - prev.length());
1262 }
1263 std::cout << '\r';
1264}
1265
1266
1267void
1269 if (find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener) == myVehicleStateListeners.end()) {
1270 myVehicleStateListeners.push_back(listener);
1271 }
1272}
1273
1274
1275void
1277 std::vector<VehicleStateListener*>::iterator i = std::find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener);
1278 if (i != myVehicleStateListeners.end()) {
1279 myVehicleStateListeners.erase(i);
1280 }
1281}
1282
1283
1284void
1285MSNet::informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info) {
1286#ifdef HAVE_FOX
1287 ScopedLocker<> lock(myVehicleStateListenerMutex, MSGlobals::gNumThreads > 1);
1288#endif
1289 for (VehicleStateListener* const listener : myVehicleStateListeners) {
1290 listener->vehicleStateChanged(vehicle, to, info);
1291 }
1292}
1293
1294
1295void
1301
1302
1303void
1305 std::vector<TransportableStateListener*>::iterator i = std::find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener);
1306 if (i != myTransportableStateListeners.end()) {
1308 }
1309}
1310
1311
1312void
1313MSNet::informTransportableStateListener(const MSTransportable* const transportable, TransportableState to, const std::string& info) {
1314#ifdef HAVE_FOX
1315 ScopedLocker<> lock(myTransportableStateListenerMutex, MSGlobals::gNumThreads > 1);
1316#endif
1318 listener->transportableStateChanged(transportable, to, info);
1319 }
1320}
1321
1322
1323bool
1324MSNet::registerCollision(const SUMOTrafficObject* collider, const SUMOTrafficObject* victim, const std::string& collisionType, const MSLane* lane, double pos) {
1325 auto it = myCollisions.find(collider->getID());
1326 if (it != myCollisions.end()) {
1327 for (Collision& old : it->second) {
1328 if (old.victim == victim->getID()) {
1329 // collision from previous step continues
1330 old.continuationTime = myStep;
1331 return false;
1332 }
1333 }
1334 } else {
1335 // maybe the roles have been reversed
1336 auto it2 = myCollisions.find(victim->getID());
1337 if (it2 != myCollisions.end()) {
1338 for (Collision& old : it2->second) {
1339 if (old.victim == collider->getID()) {
1340 // collision from previous step continues (keep the old roles)
1341 old.continuationTime = myStep;
1342 return false;
1343 }
1344 }
1345 }
1346 }
1347 Collision c;
1348 c.victim = victim->getID();
1349 c.colliderType = collider->getVehicleType().getID();
1350 c.victimType = victim->getVehicleType().getID();
1351 c.colliderSpeed = collider->getSpeed();
1352 c.victimSpeed = victim->getSpeed();
1353 c.colliderFront = collider->getPosition();
1354 c.victimFront = victim->getPosition();
1355 c.colliderBack = collider->getPosition(-collider->getVehicleType().getLength());
1356 c.victimBack = victim->getPosition(-victim->getVehicleType().getLength());
1357 c.type = collisionType;
1358 c.lane = lane;
1359 c.pos = pos;
1360 c.time = myStep;
1362 myCollisions[collider->getID()].push_back(c);
1363 return true;
1364}
1365
1366
1367void
1369 for (auto it = myCollisions.begin(); it != myCollisions.end();) {
1370 for (auto it2 = it->second.begin(); it2 != it->second.end();) {
1371 if (it2->continuationTime != myStep) {
1372 it2 = it->second.erase(it2);
1373 } else {
1374 it2++;
1375 }
1376 }
1377 if (it->second.size() == 0) {
1378 it = myCollisions.erase(it);
1379 } else {
1380 it++;
1381 }
1382 }
1383}
1384
1385
1386bool
1388 return myStoppingPlaces[category == SUMO_TAG_TRAIN_STOP ? SUMO_TAG_BUS_STOP : category].add(stop->getID(), stop);
1389}
1390
1391
1392bool
1394 if (find(myTractionSubstations.begin(), myTractionSubstations.end(), substation) == myTractionSubstations.end()) {
1395 myTractionSubstations.push_back(substation);
1396 return true;
1397 }
1398 return false;
1399}
1400
1401
1403MSNet::getStoppingPlace(const std::string& id, const SumoXMLTag category) const {
1404 if (myStoppingPlaces.count(category) > 0) {
1405 return myStoppingPlaces.find(category)->second.get(id);
1406 }
1407 return nullptr;
1408}
1409
1410
1412MSNet::getStoppingPlace(const std::string& id) const {
1414 MSStoppingPlace* result = getStoppingPlace(id, category);
1415 if (result != nullptr) {
1416 return result;
1417 }
1418 }
1419 return nullptr;
1420}
1421
1422
1423std::string
1424MSNet::getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const {
1425 if (myStoppingPlaces.count(category) > 0) {
1426 for (const auto& it : myStoppingPlaces.find(category)->second) {
1427 MSStoppingPlace* stop = it.second;
1428 if (&stop->getLane() == lane && stop->getBeginLanePosition() - POSITION_EPS <= pos && stop->getEndLanePosition() + POSITION_EPS >= pos) {
1429 return stop->getID();
1430 }
1431 }
1432 }
1433 return "";
1434}
1435
1436
1439 auto it = myStoppingPlaces.find(category);
1440 if (it != myStoppingPlaces.end()) {
1441 return it->second;
1442 } else {
1444 }
1445}
1446
1447
1448void
1451 OutputDevice& output = OutputDevice::getDeviceByOption("chargingstations-output");
1452 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_CHARGING_STATION)->second) {
1453 static_cast<MSChargingStation*>(it.second)->writeChargingStationOutput(output);
1454 }
1455 }
1456}
1457
1458
1459void
1461 if (OptionsCont::getOptions().isSet("railsignal-block-output")) {
1462 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-block-output");
1463 for (auto tls : myLogics->getAllLogics()) {
1464 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1465 if (rs != nullptr) {
1466 rs->writeBlocks(output, false);
1467 }
1468 }
1469 MSDriveWay::writeDepatureBlocks(output, false);
1470 }
1471 if (OptionsCont::getOptions().isSet("railsignal-vehicle-output")) {
1472 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-vehicle-output");
1473 for (auto tls : myLogics->getAllLogics()) {
1474 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1475 if (rs != nullptr) {
1476 rs->writeBlocks(output, true);
1477 }
1478 }
1479 MSDriveWay::writeDepatureBlocks(output, true);
1480 }
1481}
1482
1483
1484void
1487 OutputDevice& output = OutputDevice::getDeviceByOption("overheadwiresegments-output");
1488 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_OVERHEAD_WIRE_SEGMENT)->second) {
1489 static_cast<MSOverheadWire*>(it.second)->writeOverheadWireSegmentOutput(output);
1490 }
1491 }
1492}
1493
1494
1495void
1497 if (myTractionSubstations.size() > 0) {
1498 OutputDevice& output = OutputDevice::getDeviceByOption("substations-output");
1499 output.setPrecision(OptionsCont::getOptions().getInt("substations-output.precision"));
1500 for (auto& it : myTractionSubstations) {
1501 it->writeTractionSubstationOutput(output);
1502 }
1503 }
1504}
1505
1506
1508MSNet::findTractionSubstation(const std::string& substationId) {
1509 for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1510 if ((*it)->getID() == substationId) {
1511 return *it;
1512 }
1513 }
1514 return nullptr;
1515}
1516
1517
1518bool
1519MSNet::existTractionSubstation(const std::string& substationId) {
1520 for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1521 if ((*it)->getID() == substationId) {
1522 return true;
1523 }
1524 }
1525 return false;
1526}
1527
1528
1530MSNet::getRouterTT(int rngIndex, const Prohibitions& prohibited) const {
1531 if (MSGlobals::gNumSimThreads == 1) {
1532 rngIndex = 0;
1533 }
1534 if (myRouterTT.count(rngIndex) == 0) {
1535 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1536 if (routingAlgorithm == "dijkstra") {
1537 myRouterTT[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, false, nullptr, true);
1538 } else {
1539 if (routingAlgorithm != "astar") {
1540 WRITE_WARNINGF(TL("TraCI and Triggers cannot use routing algorithm '%'. using 'astar' instead."), routingAlgorithm);
1541 }
1543 }
1544 }
1545 myRouterTT[rngIndex]->prohibit(prohibited);
1546 return *myRouterTT[rngIndex];
1547}
1548
1549
1551MSNet::getRouterEffort(int rngIndex, const Prohibitions& prohibited) const {
1552 if (MSGlobals::gNumSimThreads == 1) {
1553 rngIndex = 0;
1554 }
1555 if (myRouterEffort.count(rngIndex) == 0) {
1557 }
1558 myRouterEffort[rngIndex]->prohibit(prohibited);
1559 return *myRouterEffort[rngIndex];
1560}
1561
1562
1564MSNet::getPedestrianRouter(int rngIndex, const Prohibitions& prohibited) const {
1565 if (MSGlobals::gNumSimThreads == 1) {
1566 rngIndex = 0;
1567 }
1568 if (myPedestrianRouter.count(rngIndex) == 0) {
1569 myPedestrianRouter[rngIndex] = new MSPedestrianRouter();
1570 }
1571 myPedestrianRouter[rngIndex]->prohibit(prohibited);
1572 return *myPedestrianRouter[rngIndex];
1573}
1574
1575
1577MSNet::getIntermodalRouter(int rngIndex, const int routingMode, const Prohibitions& prohibited) const {
1578 if (MSGlobals::gNumSimThreads == 1) {
1579 rngIndex = 0;
1580 }
1582 const int key = rngIndex * oc.getInt("thread-rngs") + routingMode;
1583 if (myIntermodalRouter.count(key) == 0) {
1584 const int carWalk = SUMOVehicleParserHelper::parseCarWalkTransfer(oc, MSDevice_Taxi::getTaxi() != nullptr);
1585 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1586 const double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1587 if (routingMode == libsumo::ROUTING_MODE_COMBINED) {
1588 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode, new FareModul());
1589 } else {
1590 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode);
1591 }
1592 }
1593 myIntermodalRouter[key]->prohibit(prohibited);
1594 return *myIntermodalRouter[key];
1595}
1596
1597
1598void
1600 double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1601 // add access to all parking areas
1602 EffortCalculator* const external = router.getExternalEffort();
1603 for (const auto& stopType : myInstance->myStoppingPlaces) {
1604 // add access to all stopping places
1605 const SumoXMLTag element = stopType.first;
1606 for (const auto& i : stopType.second) {
1607 const MSEdge* const edge = &i.second->getLane().getEdge();
1608 router.getNetwork()->addAccess(i.first, edge, i.second->getBeginLanePosition(), i.second->getEndLanePosition(),
1609 0., element, false, taxiWait);
1610 if (element == SUMO_TAG_BUS_STOP) {
1611 // add access to all public transport stops
1612 for (const auto& a : i.second->getAllAccessPos()) {
1613 router.getNetwork()->addAccess(i.first, &a.lane->getEdge(), a.startPos, a.endPos, a.length, element, true, taxiWait);
1614 }
1615 if (external != nullptr) {
1616 external->addStop(router.getNetwork()->getStopEdge(i.first)->getNumericalID(), *i.second);
1617 }
1618 }
1619 }
1620 }
1623 // add access to transfer from walking to taxi-use
1625 for (MSEdge* edge : myInstance->getEdgeControl().getEdges()) {
1626 if ((edge->getPermissions() & SVC_PEDESTRIAN) != 0 && (edge->getPermissions() & SVC_TAXI) != 0) {
1627 router.getNetwork()->addCarAccess(edge, SVC_TAXI, taxiWait);
1628 }
1629 }
1630 }
1631}
1632
1633
1634bool
1636 const MSEdgeVector& edges = myEdges->getEdges();
1637 for (MSEdgeVector::const_iterator e = edges.begin(); e != edges.end(); ++e) {
1638 for (std::vector<MSLane*>::const_iterator i = (*e)->getLanes().begin(); i != (*e)->getLanes().end(); ++i) {
1639 if ((*i)->getShape().hasElevation()) {
1640 return true;
1641 }
1642 }
1643 }
1644 return false;
1645}
1646
1647
1648bool
1650 for (const MSEdge* e : myEdges->getEdges()) {
1651 if (e->getFunction() == SumoXMLEdgeFunc::WALKINGAREA) {
1652 return true;
1653 }
1654 }
1655 return false;
1656}
1657
1658
1659bool
1661 for (const MSEdge* e : myEdges->getEdges()) {
1662 if (e->getBidiEdge() != nullptr) {
1663 return true;
1664 }
1665 }
1666 return false;
1667}
1668
1669bool
1670MSNet::warnOnce(const std::string& typeAndID) {
1671 if (myWarnedOnce.find(typeAndID) == myWarnedOnce.end()) {
1672 myWarnedOnce[typeAndID] = true;
1673 return true;
1674 }
1675 return false;
1676}
1677
1678
1681 auto loader = myRouteLoaders->getFirstLoader();
1682 if (loader != nullptr) {
1683 return dynamic_cast<MSMapMatcher*>(loader->getRouteHandler());
1684 } else {
1685 return nullptr;
1686 }
1687}
1688
1689void
1692 clearState(string2time(oc.getString("begin")), true);
1694 // load traffic from additional files
1695 for (std::string file : oc.getStringVector("additional-files")) {
1696 // ignore failure on parsing calibrator flow
1697 MSRouteHandler rh(file, true);
1698 const long before = PROGRESS_BEGIN_TIME_MESSAGE("Loading traffic from '" + file + "'");
1699 if (!XMLSubSys::runParser(rh, file, false)) {
1700 throw ProcessError(TLF("Loading of % failed.", file));
1701 }
1702 PROGRESS_TIME_MESSAGE(before);
1703 }
1704 delete myRouteLoaders;
1706 updateGUI();
1707}
1708
1709
1711MSNet::loadState(const std::string& fileName, const bool catchExceptions) {
1712 // load time only
1713 const SUMOTime newTime = MSStateHandler::MSStateTimeHandler::getTime(fileName);
1714 // clean up state
1715 clearState(newTime);
1716 // load state
1717 MSStateHandler h(fileName, 0);
1718 XMLSubSys::runParser(h, fileName, false, false, false, catchExceptions);
1719 if (MsgHandler::getErrorInstance()->wasInformed()) {
1720 throw ProcessError(TLF("Loading state from '%' failed.", fileName));
1721 }
1722 // reset route loaders
1723 delete myRouteLoaders;
1725 // prevent loading errors on rewound route file
1727
1728 updateGUI();
1729 return newTime;
1730}
1731
1732
1733/****************************************************************************/
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:288
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:290
#define WRITE_MESSAGE(msg)
Definition MsgHandler.h:289
#define PROGRESS_BEGIN_TIME_MESSAGE(msg)
Definition MsgHandler.h:293
#define TL(string)
Definition MsgHandler.h:305
#define PROGRESS_TIME_MESSAGE(before)
Definition MsgHandler.h:294
#define TLF(string,...)
Definition MsgHandler.h:307
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:55
#define SIMSTEP
Definition SUMOTime.h:61
#define TS
Definition SUMOTime.h:42
#define SIMTIME
Definition SUMOTime.h:62
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_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_ATTR_MAXIMUMBATTERYCAPACITY
Maxium battery capacity.
@ SUMO_ATTR_VEHICLE
@ SUMO_ATTR_RECUPERATIONENABLE
@ SUMO_ATTR_ID
int gPrecision
the precision for floating point outputs
Definition StdDefs.cpp:26
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:283
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 hasServableReservations()
check whether there are still (servable) reservations in the system
static SUMOVehicle * getTaxi()
returns a taxi if any exist or nullptr
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:1092
static void clear()
Clears the dictionary.
Definition MSEdge.cpp:1098
double getMinimumTravelTime(const SUMOVehicle *const veh) const
returns the minimum travel time for the given vehicle
Definition MSEdge.h:476
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)
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:2501
static const std::map< std::string, MSLaneSpeedTrigger * > & getInstances()
return all MSLaneSpeedTrigger instances
Interface for objects listening to transportable state changes.
Definition MSNet.h:706
Interface for objects listening to vehicle state changes.
Definition MSNet.h:647
The simulated network and simulation perfomer.
Definition MSNet.h:89
std::map< SumoXMLTag, NamedObjectCont< MSStoppingPlace * > > myStoppingPlaces
Dictionary of bus / container stops.
Definition MSNet.h:996
long myTraCIMillis
The overall time spent waiting for traci operations including.
Definition MSNet.h:935
MSMapMatcher * getMapMatcher() const
Definition MSNet.cpp:1680
static double getEffort(const MSEdge *const e, const SUMOVehicle *const v, double t)
Returns the effort to pass an edge.
Definition MSNet.cpp:152
bool warnOnce(const std::string &typeAndID)
return whether a warning regarding the given object shall be issued
Definition MSNet.cpp:1670
SUMOTime loadState(const std::string &fileName, const bool catchExceptions)
load state from file and return new time
Definition MSNet.cpp:1711
bool myLogExecutionTime
Information whether the simulation duration shall be logged.
Definition MSNet.h:921
MSTransportableControl * myPersonControl
Controls person building and deletion;.
Definition MSNet.h:890
void removeVehicleStateListener(VehicleStateListener *listener)
Removes a vehicle states listener.
Definition MSNet.cpp:1276
SUMORouteLoaderControl * myRouteLoaders
Route loader for dynamic loading of routes.
Definition MSNet.h:868
bool addStoppingPlace(const SumoXMLTag category, MSStoppingPlace *stop)
Adds a stopping place.
Definition MSNet.cpp:1387
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:1313
SUMOTime myStateDumpPeriod
The period for writing state.
Definition MSNet.h:954
static const NamedObjectCont< MSStoppingPlace * > myEmptyStoppingPlaceCont
Definition MSNet.h:1017
void writeOverheadWireSegmentOutput() const
write the output generated by an overhead wire segment
Definition MSNet.cpp:1485
void writeChargingStationOutput() const
write charging station output
Definition MSNet.cpp:1449
std::pair< bool, NamedRTree > myLanesRTree
An RTree structure holding lane IDs.
Definition MSNet.h:1033
bool checkBidiEdges()
check wether bidirectional edges occur in the network
Definition MSNet.cpp:1660
VehicleState
Definition of a vehicle state.
Definition MSNet.h:614
int myLogStepPeriod
Period between successive step-log outputs.
Definition MSNet.h:926
SUMOTime myStep
Current time step.
Definition MSNet.h:871
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:186
bool myHasBidiEdges
Whether the network contains bidirectional rail edges.
Definition MSNet.h:984
MSEventControl * myBeginOfTimestepEvents
Controls events executed at the begin of a time step;.
Definition MSNet.h:904
bool addTractionSubstation(MSTractionSubstation *substation)
Adds a traction substation.
Definition MSNet.cpp:1393
std::map< std::string, bool > myWarnedOnce
container to record warnings that shall only be issued once
Definition MSNet.h:1020
static void initStatic()
Place for static initializations of simulation components (called after successful net build)
Definition MSNet.cpp:194
void removeOutdatedCollisions()
remove collisions from the previous simulation step
Definition MSNet.cpp:1368
MSJunctionControl * myJunctions
Controls junctions, realizes right-of-way rules;.
Definition MSNet.h:896
std::vector< std::string > myPeriodicStateFiles
The names of the last K periodic state files (only only K shall be kept)
Definition MSNet.h:952
ShapeContainer * myShapeContainer
A container for geometrical shapes;.
Definition MSNet.h:910
std::string myStateDumpSuffix
Definition MSNet.h:957
bool checkElevation()
check all lanes for elevation data
Definition MSNet.cpp:1635
MSTransportableRouter & getIntermodalRouter(int rngIndex, const int routingMode=0, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1577
bool existTractionSubstation(const std::string &substationId)
return whether given electrical substation exists in the network
Definition MSNet.cpp:1519
void removeTransportableStateListener(TransportableStateListener *listener)
Removes a transportable states listener.
Definition MSNet.cpp:1304
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:925
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:257
bool myLogStepNumber
Information whether the number of the simulation step shall be logged.
Definition MSNet.h:924
MMVersion myVersion
the network version
Definition MSNet.h:990
MSEventControl * myInsertionEvents
Controls insertion events;.
Definition MSNet.h:908
virtual MSTransportableControl & getContainerControl()
Returns the container control.
Definition MSNet.cpp:1209
MSVehicleRouter & getRouterTT(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1530
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:1029
static const std::string STAGE_MOVEMENTS
Definition MSNet.h:841
bool hasFlow(const std::string &id) const
return whether the given flow is known
Definition MSNet.cpp:389
int myMaxTeleports
Maximum number of teleports.
Definition MSNet.h:877
long mySimStepDuration
Definition MSNet.h:929
MSEventControl * myEndOfTimestepEvents
Controls events executed at the end of a time step;.
Definition MSNet.h:906
static std::string getStateMessage(SimulationState state)
Returns the message to show if a certain state occurs.
Definition MSNet.cpp:946
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:1424
bool myHasInternalLinks
Whether the network contains internal links/lanes/edges.
Definition MSNet.h:972
void writeSubstationOutput() const
write electrical substation output
Definition MSNet.cpp:1496
static const std::string STAGE_INSERTIONS
Definition MSNet.h:843
long long int myPersonsMoved
Definition MSNet.h:939
void quickReload()
reset state to the beginning without reloading the network
Definition MSNet.cpp:1690
MSPedestrianRouter & getPedestrianRouter(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1564
MSVehicleControl * myVehicleControl
Controls vehicle building and deletion;.
Definition MSNet.h:888
static void clearAll()
Clears all dictionaries.
Definition MSNet.cpp:971
static void cleanupStatic()
Place for static initializations of simulation components (called after successful net build)
Definition MSNet.cpp:199
void writeStatistics(const SUMOTime start, const long now) const
write statistic output to (xml) file
Definition MSNet.cpp:573
void writeSummaryOutput()
write summary-output to (xml) file
Definition MSNet.cpp:623
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:326
MSEdgeControl * myEdges
Controls edges, performs vehicle movement;.
Definition MSNet.h:894
std::unique_ptr< MSDynamicShapeUpdater > myDynamicShapeUpdater
Updater for dynamic shapes that are tracking traffic objects (ensures removal of shape dynamics when ...
Definition MSNet.h:1038
std::map< const MSEdge *, double > Prohibitions
Definition MSNet.h:132
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:353
void closeSimulation(SUMOTime start, const std::string &reason="")
Closes the simulation (all files, connections, etc.)
Definition MSNet.cpp:687
MSStoppingPlace * getStoppingPlace(const std::string &id, const SumoXMLTag category) const
Returns the named stopping place of the given category.
Definition MSNet.cpp:1403
bool myHasElevation
Whether the network contains elevation data.
Definition MSNet.h:978
static double getTravelTime(const MSEdge *const e, const SUMOVehicle *const v, double t)
Returns the travel time to pass an edge.
Definition MSNet.cpp:166
MSTransportableControl * myContainerControl
Controls container building and deletion;.
Definition MSNet.h:892
std::vector< TransportableStateListener * > myTransportableStateListeners
Container for transportable state listener.
Definition MSNet.h:1005
void writeOutput()
Write netstate, summary and detector output.
Definition MSNet.cpp:1056
virtual void updateGUI() const
update view after simulation.loadState
Definition MSNet.h:602
bool myAmInterrupted
whether an interrupt occurred
Definition MSNet.h:880
void simulationStep(const bool onlyMove=false)
Performs a single simulation step.
Definition MSNet.cpp:726
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1268
void clearState(const SUMOTime step, bool quickReload=false)
Resets events when quick-loading state.
Definition MSNet.cpp:1002
void preSimStepOutput() const
Prints the current step number.
Definition MSNet.cpp:1232
void writeCollisions() const
write collision output to (xml) file
Definition MSNet.cpp:544
std::vector< SUMOTime > myStateDumpTimes
Times at which a state shall be written.
Definition MSNet.h:948
void addTransportableStateListener(TransportableStateListener *listener)
Adds a transportable states listener.
Definition MSNet.cpp:1296
std::vector< MSTractionSubstation * > myTractionSubstations
Dictionary of traction substations.
Definition MSNet.h:999
SUMOTime myEdgeDataEndTime
end of loaded edgeData
Definition MSNet.h:993
MSEdgeWeightsStorage & getWeightsStorage()
Returns the net's internal edge travel times/efforts container.
Definition MSNet.cpp:1223
std::map< std::string, std::map< SUMOVehicleClass, double > > myRestrictions
The vehicle class specific speed restrictions.
Definition MSNet.h:966
std::vector< std::string > myStateDumpFiles
The names for the state files.
Definition MSNet.h:950
void addMesoType(const std::string &typeID, const MESegment::MesoEdgeType &edgeType)
Adds edge type specific meso parameters.
Definition MSNet.cpp:362
void writeRailSignalBlocks() const
write rail signal block output
Definition MSNet.cpp:1460
MSTLLogicControl * myLogics
Controls tls logics, realizes waiting on tls rules;.
Definition MSNet.h:898
bool logSimulationDuration() const
Returns whether duration shall be logged.
Definition MSNet.cpp:1194
long long int myVehiclesMoved
The overall number of vehicle movements.
Definition MSNet.h:938
static const std::string STAGE_REMOTECONTROL
Definition MSNet.h:844
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:1285
std::map< int, MSTransportableRouter * > myIntermodalRouter
Definition MSNet.h:1030
std::vector< VehicleStateListener * > myVehicleStateListeners
Container for vehicle state listener.
Definition MSNet.h:1002
SimulationState simulationState(SUMOTime stopTime) const
This method returns the current simulation state. It should not modify status.
Definition MSNet.cpp:895
long myTraCIStepDuration
The last simulation step duration.
Definition MSNet.h:929
TransportableState
Definition of a transportable state.
Definition MSNet.h:691
MSInsertionControl & getInsertionControl()
Returns the insertion control.
Definition MSNet.h:437
MSDetectorControl * myDetectorControl
Controls detectors;.
Definition MSNet.h:902
bool myStepCompletionMissing
whether libsumo triggered a partial step (executeMove)
Definition MSNet.h:874
static const std::string STAGE_LANECHANGE
Definition MSNet.h:842
MSNet(MSVehicleControl *vc, MSEventControl *beginOfTimestepEvents, MSEventControl *endOfTimestepEvents, MSEventControl *insertionEvents, ShapeContainer *shapeCont=0)
Constructor.
Definition MSNet.cpp:206
void addRestriction(const std::string &id, const SUMOVehicleClass svc, const double speed)
Adds a restriction for an edge type.
Definition MSNet.cpp:347
std::map< std::string, MESegment::MesoEdgeType > myMesoEdgeTypes
The edge type specific meso parameters.
Definition MSNet.h:969
MSEdgeWeightsStorage * myEdgeWeights
The net's knowledge about edge efforts/travel times;.
Definition MSNet.h:912
MSDynamicShapeUpdater * makeDynamicShapeUpdater()
Creates and returns a dynamic shapes updater.
Definition MSNet.cpp:1217
virtual ~MSNet()
Destructor.
Definition MSNet.cpp:292
std::map< int, MSVehicleRouter * > myRouterEffort
Definition MSNet.h:1028
MSTractionSubstation * findTractionSubstation(const std::string &substationId)
find electrical substation by its id
Definition MSNet.cpp:1508
static MSNet * myInstance
Unique instance of MSNet.
Definition MSNet.h:865
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition MSNet.h:384
MSInsertionControl * myInserter
Controls vehicle insertion;.
Definition MSNet.h:900
void postSimStepOutput() const
Prints the statistics of the step at its end.
Definition MSNet.cpp:1238
virtual MSTransportableControl & getPersonControl()
Returns the person control.
Definition MSNet.cpp:1200
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:1324
static const std::string STAGE_EVENTS
string constants for simstep stages
Definition MSNet.h:840
void loadRoutes()
loads routes for the next few steps
Definition MSNet.cpp:438
std::string myStateDumpPrefix
name components for periodic state
Definition MSNet.h:956
bool myJunctionHigherSpeeds
Whether the network was built with higher speed on junctions.
Definition MSNet.h:975
MSEdgeControl & getEdgeControl()
Returns the edge control.
Definition MSNet.h:427
long mySimBeginMillis
The overall simulation duration.
Definition MSNet.h:932
bool myHasPedestrianNetwork
Whether the network contains pedestrian network elements.
Definition MSNet.h:981
std::map< int, MSVehicleRouter * > myRouterTT
Definition MSNet.h:1027
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:367
void postMoveStep()
Performs the parts of the simulation step which happen after the move.
Definition MSNet.cpp:866
bool hasInternalLinks() const
return whether the network contains internal links
Definition MSNet.h:786
const std::string generateStatistics(const SUMOTime start, const long now)
Writes performance output and running vehicle stats.
Definition MSNet.cpp:444
bool checkWalkingarea()
check all lanes for type walkingArea
Definition MSNet.cpp:1649
static void adaptIntermodalRouter(MSTransportableRouter &router)
Definition MSNet.cpp:1599
CollisionMap myCollisions
collisions in the current time step
Definition MSNet.h:1008
MSVehicleRouter & getRouterEffort(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1551
const NamedObjectCont< MSStoppingPlace * > & getStoppingPlaces(SumoXMLTag category) const
Definition MSNet.cpp:1438
SimulationState simulate(SUMOTime start, SUMOTime stop)
Simulates from timestep start to stop.
Definition MSNet.cpp:396
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:301
static void clear()
Clears the dictionary (delete all known routes, too)
Definition MSRoute.cpp:174
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.
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 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.
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)
Representation of a vehicle.
Definition SUMOVehicle.h:62
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=false)
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:57
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