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) {
178 return MSRoutingEngine::getEffortExtra(e, v, t);
179 } else if ((veh->getRoutingMode() & libsumo::ROUTING_MODE_AGGREGATED) != 0) {
181 return MSRoutingEngine::getEffortBike(e, v, t);
182 } else {
183 return MSRoutingEngine::getEffort(e, v, t);
184 }
185 } else if (MSRoutingEngine::haveExtras()) {
186 double tt = e->getMinimumTravelTime(v);
188 return tt;
189 }
190 }
191 return e->getMinimumTravelTime(v);
192}
193
194
195// ---------------------------------------------------------------------------
196// MSNet - methods
197// ---------------------------------------------------------------------------
198MSNet*
200 if (myInstance != nullptr) {
201 return myInstance;
202 }
203 throw ProcessError(TL("A network was not yet constructed."));
204}
205
206void
211
212void
218
219
220MSNet::MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents,
221 MSEventControl* endOfTimestepEvents,
222 MSEventControl* insertionEvents,
223 ShapeContainer* shapeCont):
224 myAmInterrupted(false),
225 myVehiclesMoved(0),
226 myPersonsMoved(0),
227 myHavePermissions(false),
228 myHasInternalLinks(false),
229 myJunctionHigherSpeeds(false),
230 myHasElevation(false),
231 myHasPedestrianNetwork(false),
232 myHasBidiEdges(false),
233 myEdgeDataEndTime(-1),
234 myDynamicShapeUpdater(nullptr) {
235 if (myInstance != nullptr) {
236 throw ProcessError(TL("A network was already constructed."));
237 }
239 myStep = string2time(oc.getString("begin"));
241 myMaxTeleports = oc.getInt("max-num-teleports");
242 myLogExecutionTime = !oc.getBool("no-duration-log");
243 myLogStepNumber = !oc.getBool("no-step-log");
244 myLogStepPeriod = oc.getInt("step-log.period");
245 myInserter = new MSInsertionControl(*vc, string2time(oc.getString("max-depart-delay")), oc.getBool("eager-insert"), oc.getInt("max-num-vehicles"),
246 string2time(oc.getString("random-depart-offset")));
247 myVehicleControl = vc;
249 myEdges = nullptr;
250 myJunctions = nullptr;
251 myRouteLoaders = nullptr;
252 myLogics = nullptr;
253 myPersonControl = nullptr;
254 myContainerControl = nullptr;
255 myEdgeWeights = nullptr;
256 myShapeContainer = shapeCont == nullptr ? new ShapeContainer() : shapeCont;
257
258 myBeginOfTimestepEvents = beginOfTimestepEvents;
259 myEndOfTimestepEvents = endOfTimestepEvents;
260 myInsertionEvents = insertionEvents;
261 myLanesRTree.first = false;
262
264 MSGlobals::gMesoNet = new MELoop(string2time(oc.getString("meso-recheck")));
265 }
266 myInstance = this;
267 initStatic();
268}
269
270
271void
273 SUMORouteLoaderControl* routeLoaders,
274 MSTLLogicControl* tlc,
275 std::vector<SUMOTime> stateDumpTimes,
276 std::vector<std::string> stateDumpFiles,
277 bool hasInternalLinks,
278 bool junctionHigherSpeeds,
279 const MMVersion& version) {
280 myEdges = edges;
281 myJunctions = junctions;
282 myRouteLoaders = routeLoaders;
283 myLogics = tlc;
284 // save the time the network state shall be saved at
285 myStateDumpTimes = stateDumpTimes;
286 myStateDumpFiles = stateDumpFiles;
287 myStateDumpPeriod = string2time(oc.getString("save-state.period"));
288 myStateDumpPrefix = oc.getString("save-state.prefix");
289 myStateDumpSuffix = oc.getString("save-state.suffix");
290
291 // initialise performance computation
293 myTraCIMillis = 0;
295 myJunctionHigherSpeeds = junctionHigherSpeeds;
299 myVersion = version;
302 throw ProcessError(TL("Option weights.separate-turns is only supported when simulating with internal lanes"));
303 }
304}
305
306
309 // delete controls
310 delete myJunctions;
311 delete myDetectorControl;
312 // delete mean data
313 delete myEdges;
314 delete myInserter;
315 myInserter = nullptr;
316 delete myLogics;
317 delete myRouteLoaders;
318 if (myPersonControl != nullptr) {
319 delete myPersonControl;
320 myPersonControl = nullptr; // just to have that clear for later cleanups
321 }
322 if (myContainerControl != nullptr) {
323 delete myContainerControl;
324 myContainerControl = nullptr; // just to have that clear for later cleanups
325 }
326 delete myVehicleControl; // must happen after deleting transportables
327 // ShapeContainer registers polygon-update commands with the event controls.
328 // It must be torn down before the event controls so that ~ShapeContainer
329 // can still deschedule() its (live) commands; the event controls then
330 // delete the commands themselves.
331 delete myShapeContainer;
332 myShapeContainer = nullptr;
333 // delete events late so that vehicles can get rid of references first
335 myBeginOfTimestepEvents = nullptr;
337 myEndOfTimestepEvents = nullptr;
338 delete myInsertionEvents;
339 myInsertionEvents = nullptr;
340 delete myEdgeWeights;
341 for (auto& router : myRouterTT) {
342 delete router.second;
343 }
344 myRouterTT.clear();
345 for (auto& router : myRouterEffort) {
346 delete router.second;
347 }
348 myRouterEffort.clear();
349 for (auto& router : myPedestrianRouter) {
350 delete router.second;
351 }
352 myPedestrianRouter.clear();
354 myLanesRTree.second.RemoveAll();
356 delete sub;
357 }
358 myTractionSubstations.clear();
359 clearAll();
361 delete MSGlobals::gMesoNet;
362 }
363 myInstance = nullptr;
364}
365
366
367void
368MSNet::addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed) {
369 myRestrictions[id][svc] = speed;
370}
371
372
373const std::map<SUMOVehicleClass, double>*
374MSNet::getRestrictions(const std::string& id) const {
375 std::map<std::string, std::map<SUMOVehicleClass, double> >::const_iterator i = myRestrictions.find(id);
376 if (i == myRestrictions.end()) {
377 return nullptr;
378 }
379 return &i->second;
380}
381
382
383double
384MSNet::getPreference(const std::string& routingType, const SUMOVTypeParameter& pars) const {
386 auto it = myVTypePreferences.find(pars.id);
387 if (it != myVTypePreferences.end()) {
388 auto it2 = it->second.find(routingType);
389 if (it2 != it->second.end()) {
390 return it2->second;
391 }
392 }
393 auto it3 = myVClassPreferences.find(pars.vehicleClass);
394 if (it3 != myVClassPreferences.end()) {
395 auto it4 = it3->second.find(routingType);
396 if (it4 != it3->second.end()) {
397 return it4->second;
398 }
399 }
400 // fallback to generel preferences
401 it = myVTypePreferences.find("");
402 if (it != myVTypePreferences.end()) {
403 auto it2 = it->second.find(routingType);
404 if (it2 != it->second.end()) {
405 return it2->second;
406 }
407 }
408 }
409 return 1;
410}
411
412
413void
414MSNet::addPreference(const std::string& routingType, SUMOVehicleClass svc, double prio) {
415 myVClassPreferences[svc][routingType] = prio;
416 gRoutingPreferences = true;
417}
418
419
420void
421MSNet::addPreference(const std::string& routingType, std::string vType, double prio) {
422 myVTypePreferences[vType][routingType] = prio;
423 gRoutingPreferences = true;
424}
425
426void
427MSNet::addMesoType(const std::string& typeID, const MESegment::MesoEdgeType& edgeType) {
428 myMesoEdgeTypes[typeID] = edgeType;
429}
430
432MSNet::getMesoType(const std::string& typeID) {
433 if (myMesoEdgeTypes.count(typeID) == 0) {
434 // init defaults
437 edgeType.tauff = string2time(oc.getString("meso-tauff"));
438 edgeType.taufj = string2time(oc.getString("meso-taufj"));
439 edgeType.taujf = string2time(oc.getString("meso-taujf"));
440 edgeType.taujj = string2time(oc.getString("meso-taujj"));
441 edgeType.jamThreshold = oc.getFloat("meso-jam-threshold");
442 edgeType.junctionControl = oc.getBool("meso-junction-control");
443 edgeType.tlsPenalty = oc.getFloat("meso-tls-penalty");
444 edgeType.tlsFlowPenalty = oc.getFloat("meso-tls-flow-penalty");
445 edgeType.minorPenalty = string2time(oc.getString("meso-minor-penalty"));
446 edgeType.overtaking = oc.getBool("meso-overtaking");
447 edgeType.edgeLength = oc.getFloat("meso-edgelength");
448 myMesoEdgeTypes[typeID] = edgeType;
449 }
450 return myMesoEdgeTypes[typeID];
451}
452
453
454bool
455MSNet::hasFlow(const std::string& id) const {
456 // inserter is deleted at the end of the simulation
457 return myInserter != nullptr && myInserter->hasFlow(id);
458}
459
460
463 // report the begin when wished
464 WRITE_MESSAGEF(TL("Simulation version % started with time: %."), VERSION_STRING, time2string(start));
465 // the simulation loop
467 // state loading may have changed the start time so we need to reinit it
468 myStep = start;
469 int numSteps = 0;
470 bool doStepLog = false;
471 while (state == SIMSTATE_RUNNING) {
472 doStepLog = myLogStepNumber && (numSteps % myLogStepPeriod == 0);
473 if (doStepLog) {
475 }
477 if (doStepLog) {
479 }
480 state = adaptToState(simulationState(stop));
481#ifdef DEBUG_SIMSTEP
482 std::cout << SIMTIME << " MSNet::simulate(" << start << ", " << stop << ")"
483 << "\n simulation state: " << getStateMessage(state)
484 << std::endl;
485#endif
486 numSteps++;
487 }
488 if (myLogStepNumber && !doStepLog) {
489 // ensure some output on the last step
492 }
493 // exit simulation loop
494 if (myLogStepNumber) {
495 // start new line for final verbose output
496 std::cout << "\n";
497 }
498 closeSimulation(start, getStateMessage(state));
499 return state;
500}
501
502
503void
507
508
509const std::string
510MSNet::generateStatistics(const SUMOTime start, const long now) {
511 std::ostringstream msg;
512 if (myLogExecutionTime) {
513 const long duration = now - mySimBeginMillis;
514 // print performance notice
515 msg << "Performance:\n" << " Duration: " << elapsedMs2string(duration) << "\n";
516 if (duration != 0) {
517 if (TraCIServer::getInstance() != nullptr) {
518 msg << " TraCI-Duration: " << elapsedMs2string(myTraCIMillis) << "\n";
519 }
520 msg << " Real time factor: " << (STEPS2TIME(myStep - start) * 1000. / (double)duration) << "\n";
521 msg.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
522 msg.setf(std::ios::showpoint); // print decimal point
523 msg << " UPS: " << ((double)myVehiclesMoved / ((double)duration / 1000)) << "\n";
524 if (myPersonsMoved > 0) {
525 msg << " UPS-Persons: " << ((double)myPersonsMoved / ((double)duration / 1000)) << "\n";
526 }
527 }
528 // print vehicle statistics
529 const std::string vehDiscardNotice = ((myVehicleControl->getLoadedVehicleNo() != myVehicleControl->getDepartedVehicleNo()) ?
530 " (Loaded: " + toString(myVehicleControl->getLoadedVehicleNo()) + ")" : "");
531 msg << "Vehicles:\n"
532 << " Inserted: " << myVehicleControl->getDepartedVehicleNo() << vehDiscardNotice << "\n"
533 << " Running: " << myVehicleControl->getRunningVehicleNo() << "\n"
534 << " Waiting: " << myInserter->getWaitingVehicleNo() << "\n";
535
537 // print optional teleport statistics
538 std::vector<std::string> reasons;
540 reasons.push_back("Collisions: " + toString(myVehicleControl->getCollisionCount()));
541 }
543 reasons.push_back("Jam: " + toString(myVehicleControl->getTeleportsJam()));
544 }
546 reasons.push_back("Yield: " + toString(myVehicleControl->getTeleportsYield()));
547 }
549 reasons.push_back("Wrong Lane: " + toString(myVehicleControl->getTeleportsWrongLane()));
550 }
551 msg << " Teleports: " << myVehicleControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
552 }
554 msg << " Emergency Stops: " << myVehicleControl->getEmergencyStops() << "\n";
555 }
557 msg << " Emergency Braking: " << myVehicleControl->getEmergencyBrakingCount() << "\n";
558 }
559 if (myPersonControl != nullptr && myPersonControl->getLoadedNumber() > 0) {
560 const std::string discardNotice = ((myPersonControl->getLoadedNumber() != myPersonControl->getDepartedNumber()) ?
561 " (Loaded: " + toString(myPersonControl->getLoadedNumber()) + ")" : "");
562 msg << "Persons:\n"
563 << " Inserted: " << myPersonControl->getDepartedNumber() << discardNotice << "\n"
564 << " Running: " << myPersonControl->getRunningNumber() << "\n";
565 if (myPersonControl->getJammedNumber() > 0) {
566 msg << " Jammed: " << myPersonControl->getJammedNumber() << "\n";
567 }
569 std::vector<std::string> reasons;
571 reasons.push_back("Abort Wait: " + toString(myPersonControl->getTeleportsAbortWait()));
572 }
574 reasons.push_back("Wrong Dest: " + toString(myPersonControl->getTeleportsWrongDest()));
575 }
576 msg << " Teleports: " << myPersonControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
577 }
578 }
579 if (myContainerControl != nullptr && myContainerControl->getLoadedNumber() > 0) {
580 const std::string discardNotice = ((myContainerControl->getLoadedNumber() != myContainerControl->getDepartedNumber()) ?
581 " (Loaded: " + toString(myContainerControl->getLoadedNumber()) + ")" : "");
582 msg << "Containers:\n"
583 << " Inserted: " << myContainerControl->getDepartedNumber() << "\n"
584 << " Running: " << myContainerControl->getRunningNumber() << "\n";
586 msg << " Jammed: " << myContainerControl->getJammedNumber() << "\n";
587 }
589 std::vector<std::string> reasons;
591 reasons.push_back("Abort Wait: " + toString(myContainerControl->getTeleportsAbortWait()));
592 }
594 reasons.push_back("Wrong Dest: " + toString(myContainerControl->getTeleportsWrongDest()));
595 }
596 msg << " Teleports: " << myContainerControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
597 }
598 }
599 }
600 if (OptionsCont::getOptions().getBool("duration-log.statistics")) {
602 }
603 std::string result = msg.str();
604 result.erase(result.end() - 1);
605 return result;
606}
607
608
609void
611 OutputDevice& od = OutputDevice::getDeviceByOption("collision-output");
612 for (const auto& item : myCollisions) {
613 for (const auto& c : item.second) {
614 if (c.time != SIMSTEP) {
615 continue;
616 }
617 od.openTag("collision");
619 od.writeAttr("type", c.type);
620 od.writeAttr("lane", c.lane->getID());
621 od.writeAttr("pos", c.pos);
622 od.writeAttr("collider", item.first);
623 od.writeAttr("victim", c.victim);
624 od.writeAttr("colliderType", c.colliderType);
625 od.writeAttr("victimType", c.victimType);
626 od.writeAttr("colliderSpeed", c.colliderSpeed);
627 od.writeAttr("victimSpeed", c.victimSpeed);
628 od.writeAttr("colliderFront", c.colliderFront);
629 od.writeAttr("colliderBack", c.colliderBack);
630 od.writeAttr("victimFront", c.victimFront);
631 od.writeAttr("victimBack", c.victimBack);
632 od.closeTag();
633 }
634 }
635}
636
637
638void
639MSNet::writeStatistics(const SUMOTime start, const long now) const {
640 const long duration = now - mySimBeginMillis;
641 OutputDevice& od = OutputDevice::getDeviceByOption("statistic-output");
642 od.openTag("performance");
643 od.writeAttr("clockBegin", time2string(mySimBeginMillis));
644 od.writeAttr("clockEnd", time2string(now));
645 od.writeAttr("clockDuration", time2string(duration));
646 od.writeAttr("traciDuration", time2string(myTraCIMillis));
647 od.writeAttr("realTimeFactor", duration != 0 ? (double)(myStep - start) / (double)duration : -1);
648 od.writeAttr("vehicleUpdatesPerSecond", duration != 0 ? (double)myVehiclesMoved / ((double)duration / 1000) : -1);
649 od.writeAttr("personUpdatesPerSecond", duration != 0 ? (double)myPersonsMoved / ((double)duration / 1000) : -1);
650 od.writeAttr("begin", time2string(start));
651 od.writeAttr("end", time2string(myStep));
652 od.writeAttr("duration", time2string(myStep - start));
653 od.closeTag();
654 od.openTag("vehicles");
658 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
659 od.closeTag();
660 od.openTag("teleports");
665 od.closeTag();
666 od.openTag("safety");
667 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
668 od.writeAttr("emergencyStops", myVehicleControl->getEmergencyStops());
669 od.writeAttr("emergencyBraking", myVehicleControl->getEmergencyBrakingCount());
670 od.closeTag();
671 od.openTag("persons");
672 od.writeAttr("loaded", myPersonControl != nullptr ? myPersonControl->getLoadedNumber() : 0);
673 od.writeAttr("running", myPersonControl != nullptr ? myPersonControl->getRunningNumber() : 0);
674 od.writeAttr("jammed", myPersonControl != nullptr ? myPersonControl->getJammedNumber() : 0);
675 od.closeTag();
676 od.openTag("personTeleports");
677 od.writeAttr("total", myPersonControl != nullptr ? myPersonControl->getTeleportCount() : 0);
678 od.writeAttr("abortWait", myPersonControl != nullptr ? myPersonControl->getTeleportsAbortWait() : 0);
679 od.writeAttr("wrongDest", myPersonControl != nullptr ? myPersonControl->getTeleportsWrongDest() : 0);
680 od.closeTag();
681 if (OptionsCont::getOptions().isSet("tripinfo-output") || OptionsCont::getOptions().getBool("duration-log.statistics")) {
683 }
684}
685
686
687void
689 // summary output
691 const bool hasOutput = oc.isSet("summary-output");
692 const bool hasPersonOutput = oc.isSet("person-summary-output");
693 if (hasOutput || hasPersonOutput) {
694 const SUMOTime period = string2time(oc.getString("summary-output.period"));
695 const SUMOTime begin = string2time(oc.getString("begin"));
696 if ((period > 0 && (myStep - begin) % period != 0 && !finalStep)
697 // it's the final step but we already wrote output
698 || (finalStep && (period <= 0 || (myStep - begin) % period == 0))) {
699 return;
700 }
701 }
702 if (hasOutput) {
703 OutputDevice& od = OutputDevice::getDeviceByOption("summary-output");
704 int departedVehiclesNumber = myVehicleControl->getDepartedVehicleNo();
705 const double meanWaitingTime = departedVehiclesNumber != 0 ? myVehicleControl->getTotalDepartureDelay() / (double) departedVehiclesNumber : -1.;
706 int endedVehicleNumber = myVehicleControl->getEndedVehicleNo();
707 const double meanTravelTime = endedVehicleNumber != 0 ? myVehicleControl->getTotalTravelTime() / (double) endedVehicleNumber : -1.;
708 od.openTag("step");
709 od.writeAttr("time", time2string(myStep));
713 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
716 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
717 od.writeAttr("teleports", myVehicleControl->getTeleportCount());
720 od.writeAttr("meanWaitingTime", meanWaitingTime);
721 od.writeAttr("meanTravelTime", meanTravelTime);
722 std::pair<double, double> meanSpeed = myVehicleControl->getVehicleMeanSpeeds();
723 od.writeAttr("meanSpeed", meanSpeed.first);
724 od.writeAttr("meanSpeedRelative", meanSpeed.second);
726 if (myLogExecutionTime) {
727 od.writeAttr("duration", mySimStepDuration);
728 }
729 od.closeTag();
730 }
731 if (hasPersonOutput) {
732 OutputDevice& od = OutputDevice::getDeviceByOption("person-summary-output");
734 od.openTag("step");
735 od.writeAttr("time", time2string(myStep));
736 od.writeAttr("loaded", pc.getLoadedNumber());
737 od.writeAttr("inserted", pc.getDepartedNumber());
738 od.writeAttr("walking", pc.getMovingNumber());
739 od.writeAttr("waitingForRide", pc.getWaitingForVehicleNumber());
740 od.writeAttr("riding", pc.getRidingNumber());
741 od.writeAttr("stopping", pc.getWaitingUntilNumber());
742 od.writeAttr("jammed", pc.getJammedNumber());
743 od.writeAttr("ended", pc.getEndedNumber());
744 od.writeAttr("arrived", pc.getArrivedNumber());
745 od.writeAttr("teleports", pc.getTeleportCount());
746 od.writeAttr("discarded", pc.getDiscardedNumber());
747 if (myLogExecutionTime) {
748 od.writeAttr("duration", mySimStepDuration);
749 }
750 od.closeTag();
751 }
752}
753
754
755void
756MSNet::closeSimulation(SUMOTime start, const std::string& reason) {
757 // report the end when wished
758 WRITE_MESSAGE(TLF("Simulation ended at time: %.", time2string(getCurrentTimeStep())));
759 if (reason != "") {
760 WRITE_MESSAGE(TL("Reason: ") + reason);
761 }
763 if (MSStopOut::active() && OptionsCont::getOptions().getBool("stop-output.write-unfinished")) {
765 }
766 MSDevice_Vehroutes::writePendingOutput(OptionsCont::getOptions().getBool("vehroute-output.write-unfinished"));
767 if (OptionsCont::getOptions().getBool("tripinfo-output.write-unfinished")) {
769 }
770 if (OptionsCont::getOptions().isSet("chargingstations-output")) {
771 if (!OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
773 } else if (OptionsCont::getOptions().getBool("chargingstations-output.aggregated.write-unfinished")) {
774 MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"), true);
775 }
776 }
777 if (OptionsCont::getOptions().isSet("overheadwiresegments-output")) {
779 }
780 if (OptionsCont::getOptions().isSet("substations-output")) {
782 }
784 const long now = SysUtils::getCurrentMillis();
785 if (myLogExecutionTime || OptionsCont::getOptions().getBool("duration-log.statistics")) {
787 }
788 if (OptionsCont::getOptions().isSet("statistic-output")) {
789 writeStatistics(start, now);
790 }
791 // maybe write a final line of output if reporting is periodic
792 writeSummaryOutput(true);
793}
794
795
796void
797MSNet::simulationStep(const bool onlyMove) {
799 postMoveStep();
801 return;
802 }
803#ifdef DEBUG_SIMSTEP
804 std::cout << SIMTIME << ": MSNet::simulationStep() called"
805 << ", myStep = " << myStep
806 << std::endl;
807#endif
809 int lastTraCICmd = 0;
810 if (t != nullptr) {
811 if (myLogExecutionTime) {
813 }
814 lastTraCICmd = t->processCommands(myStep);
815#ifdef DEBUG_SIMSTEP
816 bool loadRequested = !TraCI::getLoadArgs().empty();
817 assert(t->getTargetTime() >= myStep || loadRequested || TraCIServer::wasClosed());
818#endif
819 if (myLogExecutionTime) {
821 }
822 if (TraCIServer::wasClosed() || !t->getLoadArgs().empty()) {
823 return;
824 }
825 }
826#ifdef DEBUG_SIMSTEP
827 std::cout << SIMTIME << ": TraCI target time: " << t->getTargetTime() << std::endl;
828#endif
829 // execute beginOfTimestepEvents
830 if (myLogExecutionTime) {
832 }
833 // simulation state output
834 std::vector<SUMOTime>::iterator timeIt = std::find(myStateDumpTimes.begin(), myStateDumpTimes.end(), myStep);
835 if (timeIt != myStateDumpTimes.end()) {
836 const int dist = (int)distance(myStateDumpTimes.begin(), timeIt);
838 }
839 if (myStateDumpPeriod > 0 && myStep % myStateDumpPeriod == 0) {
840 std::string timeStamp = time2string(myStep);
841 std::replace(timeStamp.begin(), timeStamp.end(), ':', '-');
842 const std::string filename = myStateDumpPrefix + "_" + timeStamp + myStateDumpSuffix;
844 myPeriodicStateFiles.push_back(filename);
845 int keep = OptionsCont::getOptions().getInt("save-state.period.keep");
846 if (keep > 0 && (int)myPeriodicStateFiles.size() > keep) {
847 std::remove(myPeriodicStateFiles.front().c_str());
849 }
850 }
854 }
855#ifdef HAVE_FOX
856 MSRoutingEngine::waitForAll();
857#endif
860 }
861 // check whether the tls programs need to be switched
863
866 } else {
867 // assure all lanes with vehicles are 'active'
869
870 // compute safe velocities for all vehicles for the next few lanes
871 // also register ApproachingVehicleInformation for all links
873
874 // register junction approaches based on planned velocities as basis for right-of-way decision
876
877 // decide right-of-way and execute movements
881 }
882
883 // vehicles may change lanes
885
888 }
889 }
890 // flush arrived meso vehicles and micro vehicles that were removed due to collision
892 loadRoutes();
893
894 // persons
897 }
898 // containers
901 }
904 // preserve waitRelation from insertion for the next step
905 }
906 // insert vehicles
909#ifdef HAVE_FOX
910 MSRoutingEngine::waitForAll();
911#endif
914 //myEdges->patchActiveLanes(); // @note required to detect collisions on lanes that were empty before insertion. wasteful?
916 }
918
919 // execute endOfTimestepEvents
921
922 if (myLogExecutionTime) {
924 }
925 if (onlyMove) {
927 return;
928 }
929 if (t != nullptr && lastTraCICmd == libsumo::CMD_EXECUTEMOVE) {
930 t->processCommands(myStep, true);
931 }
932 postMoveStep();
933}
934
935
936void
938 const int numControlled = libsumo::Helper::postProcessRemoteControl();
939 if (numControlled > 0 && MSGlobals::gCheck4Accidents) {
941 }
942 if (myLogExecutionTime) {
945 }
947 // collisions from the previous step were kept to avoid duplicate
948 // warnings. we must remove them now to ensure correct output.
950 }
951 // update and write (if needed) detector values
953 writeOutput();
954
955 if (myLogExecutionTime) {
957 if (myPersonControl != nullptr) {
959 }
960 }
961 myStep += DELTA_T;
962}
963
964
969 }
970 if (TraCIServer::getInstance() != nullptr && !TraCIServer::getInstance()->getLoadArgs().empty()) {
971 return SIMSTATE_LOADING;
972 }
973 if ((stopTime < 0 || myStep > stopTime) && TraCIServer::getInstance() == nullptr && (stopTime > 0 || myStep > myEdgeDataEndTime)) {
976 && (myPersonControl == nullptr || !myPersonControl->hasNonWaiting())
980 }
981 }
982 if (stopTime >= 0 && myStep >= stopTime) {
984 }
987 }
988 if (myAmInterrupted) {
990 }
991 return SIMSTATE_RUNNING;
992}
993
994
996MSNet::adaptToState(MSNet::SimulationState state, const bool isLibsumo) const {
997 if (state == SIMSTATE_LOADING) {
1000 } else if (state != SIMSTATE_RUNNING && ((TraCIServer::getInstance() != nullptr && !TraCIServer::wasClosed()) || isLibsumo)) {
1001 // overrides SIMSTATE_END_STEP_REACHED, e.g. (TraCI / Libsumo ignore SUMO's --end option)
1002 return SIMSTATE_RUNNING;
1003 } else if (state == SIMSTATE_NO_FURTHER_VEHICLES) {
1004 if (myPersonControl != nullptr) {
1006 }
1007 if (myContainerControl != nullptr) {
1009 }
1011 }
1012 return state;
1013}
1014
1015
1016std::string
1018 switch (state) {
1020 return "";
1022 return TL("The final simulation step has been reached.");
1024 return TL("All vehicles have left the simulation.");
1026 return TL("TraCI requested termination.");
1028 return TL("An error occurred (see log).");
1030 return TL("Interrupted.");
1032 return TL("Too many teleports.");
1034 return TL("TraCI issued load command.");
1035 default:
1036 return TL("Unknown reason.");
1037 }
1038}
1039
1040
1041void
1043 // clear container
1044 MSEdge::clear();
1045 MSLane::clear();
1050 while (!MSLaneSpeedTrigger::getInstances().empty()) {
1051 delete MSLaneSpeedTrigger::getInstances().begin()->second;
1052 }
1053 while (!MSTriggeredRerouter::getInstances().empty()) {
1054 delete MSTriggeredRerouter::getInstances().begin()->second;
1055 }
1064 if (t != nullptr) {
1065 t->cleanup();
1066 }
1069}
1070
1071
1072void
1073MSNet::clearState(const SUMOTime step, bool quickReload) {
1077 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1078 for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*edge); s != nullptr; s = s->getNextSegment()) {
1079 s->clearState();
1080 }
1081 }
1082 } else {
1083 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1084 for (MSLane* const lane : edge->getLanes()) {
1085 lane->getVehiclesSecure();
1086 lane->clearState();
1087 lane->releaseVehicles();
1088 }
1089 edge->clearState();
1090 }
1091 }
1093 // detectors may still reference persons/vehicles
1097
1098 if (myPersonControl != nullptr) {
1100 }
1101 if (myContainerControl != nullptr) {
1103 }
1104 // delete vtypes after transportables have removed their types
1108 // delete all routes after vehicles and detector output is done
1110 for (auto& item : myStoppingPlaces) {
1111 for (auto& item2 : item.second) {
1112 item2.second->clearState();
1113 }
1114 }
1121 myStep = step;
1122 MSGlobals::gClearState = false;
1123}
1124
1125
1130
1131void
1136
1137void
1139 // update detector values
1142
1143 // check state dumps
1144 if (oc.isSet("netstate-dump")) {
1146 oc.getInt("netstate-dump.precision"));
1147 }
1148
1149 // check fcd dumps
1150 if (OptionsCont::getOptions().isSet("fcd-output")) {
1151 if (OptionsCont::getOptions().isSet("person-fcd-output")) {
1154 } else {
1156 }
1157 }
1158
1159 // check emission dumps
1160 if (OptionsCont::getOptions().isSet("emission-output")) {
1162 }
1163
1164 // battery dumps
1165 if (OptionsCont::getOptions().isSet("battery-output")) {
1167 oc.getInt("battery-output.precision"));
1168 }
1169
1170 // charging station aggregated dumps
1171 if (OptionsCont::getOptions().isSet("chargingstations-output") && OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
1173 }
1174
1175 // elecHybrid dumps
1176 if (OptionsCont::getOptions().isSet("elechybrid-output")) {
1177 std::string output = OptionsCont::getOptions().getString("elechybrid-output");
1178
1179 if (oc.getBool("elechybrid-output.aggregated")) {
1180 // build a xml file with aggregated device.elechybrid output
1182 oc.getInt("elechybrid-output.precision"));
1183 } else {
1184 // build a separate xml file for each vehicle equipped with device.elechybrid
1185 // RICE_TODO: Does this have to be placed here in MSNet.cpp ?
1187 for (MSVehicleControl::constVehIt it = vc.loadedVehBegin(); it != vc.loadedVehEnd(); ++it) {
1188 const SUMOVehicle* veh = it->second;
1189 if (!veh->isOnRoad()) {
1190 continue;
1191 }
1192 if (static_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid))) != nullptr) {
1193 std::string vehID = veh->getID();
1194 std::string filename2 = output + "_" + vehID + ".xml";
1195 OutputDevice& dev = OutputDevice::getDevice(filename2);
1196 std::map<SumoXMLAttr, std::string> attrs;
1197 attrs[SUMO_ATTR_VEHICLE] = vehID;
1200 dev.writeXMLHeader("elecHybrid-export", "", attrs);
1201 MSElecHybridExport::write(OutputDevice::getDevice(filename2), veh, myStep, oc.getInt("elechybrid-output.precision"));
1202 }
1203 }
1204 }
1205 }
1206
1207
1208 // check full dumps
1209 if (OptionsCont::getOptions().isSet("full-output")) {
1212 }
1213
1214 // check queue dumps
1215 if (OptionsCont::getOptions().isSet("queue-output")) {
1217 }
1218
1219 // check amitran dumps
1220 if (OptionsCont::getOptions().isSet("amitran-output")) {
1222 }
1223
1224 // check vtk dumps
1225 if (OptionsCont::getOptions().isSet("vtk-output")) {
1226
1227 if (MSNet::getInstance()->getVehicleControl().getRunningVehicleNo() > 0) {
1228 std::string timestep = time2string(myStep);
1229 if (TS >= 1.0) {
1230 timestep = timestep.substr(0, timestep.length() - 3);
1231 } else if (DELTA_T % 100 == 0) {
1232 timestep = timestep.substr(0, timestep.length() - 1);
1233 }
1234 std::string output = OptionsCont::getOptions().getString("vtk-output");
1235 std::string filename = output + "_" + timestep + ".vtp";
1236
1237 OutputDevice_File dev(filename);
1238
1239 //build a huge mass of xml files
1241
1242 }
1243
1244 }
1245
1247
1248 // write detector values
1250
1251 // write link states
1252 if (OptionsCont::getOptions().isSet("link-output")) {
1253 OutputDevice& od = OutputDevice::getDeviceByOption("link-output");
1254 od.openTag("timestep");
1256 for (const MSEdge* const edge : myEdges->getEdges()) {
1257 for (const MSLane* const lane : edge->getLanes()) {
1258 for (const MSLink* const link : lane->getLinkCont()) {
1259 link->writeApproaching(od, lane->getID());
1260 }
1261 }
1262 }
1263 od.closeTag();
1264 }
1265
1266 // write SSM output
1268 dev->updateAndWriteOutput();
1269 }
1270
1271 // write ToC output
1273 if (dev->generatesOutput()) {
1274 dev->writeOutput();
1275 }
1276 }
1277
1278 if (OptionsCont::getOptions().isSet("collision-output")) {
1280 }
1281}
1282
1283
1284bool
1288
1289
1292 if (myPersonControl == nullptr) {
1294 }
1295 return *myPersonControl;
1296}
1297
1298
1301 if (myContainerControl == nullptr) {
1303 }
1304 return *myContainerControl;
1305}
1306
1309 myDynamicShapeUpdater = std::unique_ptr<MSDynamicShapeUpdater> (new MSDynamicShapeUpdater(*myShapeContainer));
1310 return myDynamicShapeUpdater.get();
1311}
1312
1315 if (myEdgeWeights == nullptr) {
1317 }
1318 return *myEdgeWeights;
1319}
1320
1321
1322void
1324 std::cout << "Step #" << time2string(myStep);
1325}
1326
1327
1328void
1330 if (myLogExecutionTime) {
1331 std::ostringstream oss;
1332 oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
1333 oss.setf(std::ios::showpoint); // print decimal point
1334 oss << std::setprecision(gPrecision);
1335 if (mySimStepDuration != 0) {
1336 const double durationSec = (double)mySimStepDuration / 1000.;
1337 oss << " (" << mySimStepDuration << "ms ~= "
1338 << (TS / durationSec) << "*RT, ~"
1339 << ((double) myVehicleControl->getRunningVehicleNo() / durationSec);
1340 } else {
1341 oss << " (0ms ?*RT. ?";
1342 }
1343 oss << "UPS, ";
1344 if (TraCIServer::getInstance() != nullptr) {
1345 oss << "TraCI: " << myTraCIStepDuration << "ms, ";
1346 }
1347 oss << "vehicles TOT " << myVehicleControl->getDepartedVehicleNo()
1348 << " ACT " << myVehicleControl->getRunningVehicleNo()
1349 << " BUF " << myInserter->getWaitingVehicleNo()
1350 << ") ";
1351 std::string prev = "Step #" + time2string(myStep - DELTA_T);
1352 std::cout << oss.str().substr(0, 90 - prev.length());
1353 }
1354 std::cout << '\r';
1355}
1356
1357
1358void
1360 if (find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener) == myVehicleStateListeners.end()) {
1361 myVehicleStateListeners.push_back(listener);
1362 }
1363}
1364
1365
1366void
1368 std::vector<VehicleStateListener*>::iterator i = std::find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener);
1369 if (i != myVehicleStateListeners.end()) {
1370 myVehicleStateListeners.erase(i);
1371 }
1372}
1373
1374
1375void
1376MSNet::informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info) {
1377#ifdef HAVE_FOX
1378 ScopedLocker<> lock(myVehicleStateListenerMutex, MSGlobals::gNumThreads > 1);
1379#endif
1380 for (VehicleStateListener* const listener : myVehicleStateListeners) {
1381 listener->vehicleStateChanged(vehicle, to, info);
1382 }
1383}
1384
1385
1386void
1392
1393
1394void
1396 std::vector<TransportableStateListener*>::iterator i = std::find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener);
1397 if (i != myTransportableStateListeners.end()) {
1399 }
1400}
1401
1402
1403void
1404MSNet::informTransportableStateListener(const MSTransportable* const transportable, TransportableState to, const std::string& info) {
1405#ifdef HAVE_FOX
1406 ScopedLocker<> lock(myTransportableStateListenerMutex, MSGlobals::gNumThreads > 1);
1407#endif
1409 listener->transportableStateChanged(transportable, to, info);
1410 }
1411}
1412
1413
1414bool
1415MSNet::registerCollision(const SUMOTrafficObject* collider, const SUMOTrafficObject* victim, const std::string& collisionType, const MSLane* lane, double pos) {
1416 auto it = myCollisions.find(collider->getID());
1417 if (it != myCollisions.end()) {
1418 for (Collision& old : it->second) {
1419 if (old.victim == victim->getID()) {
1420 // collision from previous step continues
1421 old.continuationTime = myStep;
1422 return false;
1423 }
1424 }
1425 } else {
1426 // maybe the roles have been reversed
1427 auto it2 = myCollisions.find(victim->getID());
1428 if (it2 != myCollisions.end()) {
1429 for (Collision& old : it2->second) {
1430 if (old.victim == collider->getID()) {
1431 // collision from previous step continues (keep the old roles)
1432 old.continuationTime = myStep;
1433 return false;
1434 }
1435 }
1436 }
1437 }
1438 Collision c;
1439 c.victim = victim->getID();
1440 c.colliderType = collider->getVehicleType().getID();
1441 c.victimType = victim->getVehicleType().getID();
1442 c.colliderSpeed = collider->getSpeed();
1443 c.victimSpeed = victim->getSpeed();
1444 c.colliderFront = collider->getPosition();
1445 c.victimFront = victim->getPosition();
1446 c.colliderBack = collider->getPosition(-collider->getVehicleType().getLength());
1447 c.victimBack = victim->getPosition(-victim->getVehicleType().getLength());
1448 c.type = collisionType;
1449 c.lane = lane;
1450 c.pos = pos;
1451 c.time = myStep;
1453 myCollisions[collider->getID()].push_back(c);
1454 return true;
1455}
1456
1457
1458void
1460 for (auto it = myCollisions.begin(); it != myCollisions.end();) {
1461 for (auto it2 = it->second.begin(); it2 != it->second.end();) {
1462 if (it2->continuationTime != myStep) {
1463 it2 = it->second.erase(it2);
1464 } else {
1465 it2++;
1466 }
1467 }
1468 if (it->second.size() == 0) {
1469 it = myCollisions.erase(it);
1470 } else {
1471 it++;
1472 }
1473 }
1474}
1475
1476
1477bool
1479 if (category == SUMO_TAG_TRAIN_STOP) {
1480 category = SUMO_TAG_BUS_STOP;
1481 }
1482 const bool isNew = myStoppingPlaces[category].add(stop->getID(), stop);
1483 if (isNew && stop->getMyName() != "") {
1484 myNamedStoppingPlaces[category][stop->getMyName()].push_back(stop);
1485 }
1486 return isNew;
1487}
1488
1489
1490bool
1492 if (find(myTractionSubstations.begin(), myTractionSubstations.end(), substation) == myTractionSubstations.end()) {
1493 myTractionSubstations.push_back(substation);
1494 return true;
1495 }
1496 return false;
1497}
1498
1499
1501MSNet::getStoppingPlace(const std::string& id, const SumoXMLTag category) const {
1502 if (myStoppingPlaces.count(category) > 0) {
1503 return myStoppingPlaces.find(category)->second.get(id);
1504 }
1505 return nullptr;
1506}
1507
1508
1510MSNet::getStoppingPlace(const std::string& id) const {
1512 MSStoppingPlace* result = getStoppingPlace(id, category);
1513 if (result != nullptr) {
1514 return result;
1515 }
1516 }
1517 return nullptr;
1518}
1519
1520
1521std::string
1522MSNet::getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const {
1523 if (myStoppingPlaces.count(category) > 0) {
1524 for (const auto& it : myStoppingPlaces.find(category)->second) {
1525 MSStoppingPlace* stop = it.second;
1526 if (&stop->getLane() == lane && stop->getBeginLanePosition() - POSITION_EPS <= pos && stop->getEndLanePosition() + POSITION_EPS >= pos) {
1527 return stop->getID();
1528 }
1529 }
1530 }
1531 return "";
1532}
1533
1534
1535const std::vector<MSStoppingPlace*>&
1536MSNet::getStoppingPlaceAlternatives(const std::string& name, SumoXMLTag category) const {
1537 if (category == SUMO_TAG_TRAIN_STOP) {
1538 category = SUMO_TAG_BUS_STOP;
1539 }
1540 auto it = myNamedStoppingPlaces.find(category);
1541 if (it != myNamedStoppingPlaces.end()) {
1542 auto it2 = it->second.find(name);
1543 if (it2 != it->second.end()) {
1544 return it2->second;
1545 }
1546 }
1548}
1549
1550
1553 auto it = myStoppingPlaces.find(category);
1554 if (it != myStoppingPlaces.end()) {
1555 return it->second;
1556 } else {
1558 }
1559}
1560
1561
1562void
1565 OutputDevice& output = OutputDevice::getDeviceByOption("chargingstations-output");
1566 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_CHARGING_STATION)->second) {
1567 static_cast<MSChargingStation*>(it.second)->writeChargingStationOutput(output);
1568 }
1569 }
1570}
1571
1572
1573void
1575 if (OptionsCont::getOptions().isSet("railsignal-block-output")) {
1576 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-block-output");
1577 for (auto tls : myLogics->getAllLogics()) {
1578 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1579 if (rs != nullptr) {
1580 rs->writeBlocks(output, false);
1581 }
1582 }
1583 MSDriveWay::writeDepatureBlocks(output, false);
1584 }
1585 if (OptionsCont::getOptions().isSet("railsignal-vehicle-output")) {
1586 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-vehicle-output");
1587 for (auto tls : myLogics->getAllLogics()) {
1588 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1589 if (rs != nullptr) {
1590 rs->writeBlocks(output, true);
1591 }
1592 }
1593 MSDriveWay::writeDepatureBlocks(output, true);
1594 }
1595}
1596
1597
1598void
1601 OutputDevice& output = OutputDevice::getDeviceByOption("overheadwiresegments-output");
1602 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_OVERHEAD_WIRE_SEGMENT)->second) {
1603 static_cast<MSOverheadWire*>(it.second)->writeOverheadWireSegmentOutput(output);
1604 }
1605 }
1606}
1607
1608
1609void
1611 if (myTractionSubstations.size() > 0) {
1612 OutputDevice& output = OutputDevice::getDeviceByOption("substations-output");
1613 output.setPrecision(OptionsCont::getOptions().getInt("substations-output.precision"));
1614 for (auto& it : myTractionSubstations) {
1615 it->writeTractionSubstationOutput(output);
1616 }
1617 }
1618}
1619
1620
1622MSNet::findTractionSubstation(const std::string& substationId) {
1623 for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1624 if ((*it)->getID() == substationId) {
1625 return *it;
1626 }
1627 }
1628 return nullptr;
1629}
1630
1631
1633MSNet::getRouterTT(int rngIndex, const Prohibitions& prohibited) const {
1634 if (MSGlobals::gNumSimThreads == 1) {
1635 rngIndex = 0;
1636 }
1637 if (myRouterTT.count(rngIndex) == 0) {
1638 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1639 if (routingAlgorithm == "dijkstra") {
1640 myRouterTT[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, false, nullptr, true);
1641 } else {
1642 if (routingAlgorithm != "astar") {
1643 WRITE_WARNINGF(TL("TraCI and Triggers cannot use routing algorithm '%'. using 'astar' instead."), routingAlgorithm);
1644 }
1646 }
1647 }
1648 myRouterTT[rngIndex]->prohibit(prohibited);
1649 return *myRouterTT[rngIndex];
1650}
1651
1652
1654MSNet::getRouterEffort(int rngIndex, const Prohibitions& prohibited) const {
1655 if (MSGlobals::gNumSimThreads == 1) {
1656 rngIndex = 0;
1657 }
1658 if (myRouterEffort.count(rngIndex) == 0) {
1660 }
1661 myRouterEffort[rngIndex]->prohibit(prohibited);
1662 return *myRouterEffort[rngIndex];
1663}
1664
1665
1667MSNet::getPedestrianRouter(int rngIndex, const Prohibitions& prohibited) const {
1668 if (MSGlobals::gNumSimThreads == 1) {
1669 rngIndex = 0;
1670 }
1671 if (myPedestrianRouter.count(rngIndex) == 0) {
1672 myPedestrianRouter[rngIndex] = new MSPedestrianRouter();
1673 }
1674 myPedestrianRouter[rngIndex]->prohibit(prohibited);
1675 return *myPedestrianRouter[rngIndex];
1676}
1677
1678
1680MSNet::getIntermodalRouter(int rngIndex, const int routingMode, const Prohibitions& prohibited) const {
1681 if (MSGlobals::gNumSimThreads == 1) {
1682 rngIndex = 0;
1683 }
1685 const int key = rngIndex * oc.getInt("thread-rngs") + routingMode;
1686 if (myIntermodalRouter.count(key) == 0) {
1688 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1689 const double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1690 if (routingMode == libsumo::ROUTING_MODE_COMBINED) {
1691 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode, new FareModul());
1692 } else {
1693 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode);
1694 }
1695 }
1696 myIntermodalRouter[key]->prohibit(prohibited);
1697 return *myIntermodalRouter[key];
1698}
1699
1700
1701void
1703 for (auto& router : myIntermodalRouter) {
1704 delete router.second;
1705 }
1706 myIntermodalRouter.clear();
1707}
1708
1709
1710void
1712 double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1713 // add access to all parking areas
1714 EffortCalculator* const external = router.getExternalEffort();
1715 for (const auto& stopType : myInstance->myStoppingPlaces) {
1716 // add access to all stopping places
1717 const SumoXMLTag element = stopType.first;
1718 for (const auto& i : stopType.second) {
1719 const MSEdge* const edge = &i.second->getLane().getEdge();
1720 router.getNetwork()->addAccess(i.first, edge, i.second->getBeginLanePosition(), i.second->getEndLanePosition(),
1721 0., element, false, taxiWait);
1722 if (element == SUMO_TAG_BUS_STOP) {
1723 // add access to all public transport stops
1724 for (const auto& a : i.second->getAllAccessPos()) {
1725 router.getNetwork()->addAccess(i.first, &a.lane->getEdge(), a.startPos, a.endPos, a.length, element, true, taxiWait);
1726 }
1727 if (external != nullptr) {
1728 external->addStop(router.getNetwork()->getStopEdge(i.first)->getNumericalID(), *i.second);
1729 }
1730 }
1731 }
1732 }
1735 // add access to transfer from walking to taxi-use
1737 for (MSEdge* edge : myInstance->getEdgeControl().getEdges()) {
1738 if ((edge->getPermissions() & SVC_PEDESTRIAN) != 0 && (edge->getPermissions() & SVC_TAXI) != 0) {
1739 router.getNetwork()->addCarAccess(edge, SVC_TAXI, taxiWait);
1740 }
1741 }
1742 }
1743}
1744
1745
1746bool
1748 const MSEdgeVector& edges = myEdges->getEdges();
1749 for (MSEdgeVector::const_iterator e = edges.begin(); e != edges.end(); ++e) {
1750 for (std::vector<MSLane*>::const_iterator i = (*e)->getLanes().begin(); i != (*e)->getLanes().end(); ++i) {
1751 if ((*i)->getShape().hasElevation()) {
1752 return true;
1753 }
1754 }
1755 }
1756 return false;
1757}
1758
1759
1760bool
1762 for (const MSEdge* e : myEdges->getEdges()) {
1763 if (e->getFunction() == SumoXMLEdgeFunc::WALKINGAREA) {
1764 return true;
1765 }
1766 }
1767 return false;
1768}
1769
1770
1771bool
1773 for (const MSEdge* e : myEdges->getEdges()) {
1774 if (e->getBidiEdge() != nullptr) {
1775 return true;
1776 }
1777 }
1778 return false;
1779}
1780
1781bool
1782MSNet::warnOnce(const std::string& typeAndID) {
1783 if (myWarnedOnce.find(typeAndID) == myWarnedOnce.end()) {
1784 myWarnedOnce[typeAndID] = true;
1785 return true;
1786 }
1787 return false;
1788}
1789
1790
1793 auto loader = myRouteLoaders->getFirstLoader();
1794 if (loader != nullptr) {
1795 return dynamic_cast<MSMapMatcher*>(loader->getRouteHandler());
1796 } else {
1797 return nullptr;
1798 }
1799}
1800
1801void
1804 clearState(string2time(oc.getString("begin")), true);
1806 // load traffic from additional files
1807 for (std::string file : oc.getStringVector("additional-files")) {
1808 // ignore failure on parsing calibrator flow
1809 MSRouteHandler rh(file, true);
1810 const long before = PROGRESS_BEGIN_TIME_MESSAGE("Loading traffic from '" + file + "'");
1811 if (!XMLSubSys::runParser(rh, file, false)) {
1812 throw ProcessError(TLF("Loading of % failed.", file));
1813 }
1814 PROGRESS_TIME_MESSAGE(before);
1815 }
1816 delete myRouteLoaders;
1818 updateGUI();
1819}
1820
1821
1823MSNet::loadState(const std::string& fileName, const bool catchExceptions) {
1824 // load time only
1825 const SUMOTime newTime = MSStateHandler::MSStateTimeHandler::getTime(fileName);
1826 // clean up state
1827 clearState(newTime);
1828 // load state
1829 MSStateHandler h(fileName, 0);
1830 XMLSubSys::runParser(h, fileName, false, false, false, catchExceptions);
1831 if (MsgHandler::getErrorInstance()->wasInformed()) {
1832 throw ProcessError(TLF("Loading state from '%' failed.", fileName));
1833 }
1834 // reset route loaders
1835 delete myRouteLoaders;
1837 // prevent loading errors on rewound route file
1839
1840 updateGUI();
1841 return newTime;
1842}
1843
1844
1845/****************************************************************************/
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_BICYCLE
vehicle is a bicycle
@ 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
T MAX2(T a, T b)
Definition StdDefs.h:86
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=gPrecision)
Definition ToString.h:314
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:49
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:248
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:1120
static void clear()
Clears the dictionary.
Definition MSEdge.cpp:1126
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:127
static MELoop * gMesoNet
mesoscopic simulation infrastructure
Definition MSGlobals.h:115
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:2544
static const std::map< std::string, MSLaneSpeedTrigger * > & getInstances()
return all MSLaneSpeedTrigger instances
Interface for objects listening to transportable state changes.
Definition MSNet.h:728
Interface for objects listening to vehicle state changes.
Definition MSNet.h:669
The simulated network and simulation perfomer.
Definition MSNet.h:89
std::map< SumoXMLTag, NamedObjectCont< MSStoppingPlace * > > myStoppingPlaces
Dictionary of bus / container stops.
Definition MSNet.h:1028
long myTraCIMillis
The overall time spent waiting for traci operations including.
Definition MSNet.h:966
MSMapMatcher * getMapMatcher() const
Definition MSNet.cpp:1792
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:1782
MSNet(MSVehicleControl *vc, MSEventControl *beginOfTimestepEvents, MSEventControl *endOfTimestepEvents, MSEventControl *insertionEvents, ShapeContainer *shapeCont=nullptr)
Constructor.
Definition MSNet.cpp:220
SUMOTime loadState(const std::string &fileName, const bool catchExceptions)
load state from file and return new time
Definition MSNet.cpp:1823
bool myLogExecutionTime
Information whether the simulation duration shall be logged.
Definition MSNet.h:952
MSTransportableControl * myPersonControl
Controls person building and deletion;.
Definition MSNet.h:921
void removeVehicleStateListener(VehicleStateListener *listener)
Removes a vehicle states listener.
Definition MSNet.cpp:1367
SUMORouteLoaderControl * myRouteLoaders
Route loader for dynamic loading of routes.
Definition MSNet.h:890
std::map< std::string, std::map< std::string, double > > myVTypePreferences
Definition MSNet.h:1001
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:1404
SUMOTime myStateDumpPeriod
The period for writing state.
Definition MSNet.h:985
static const NamedObjectCont< MSStoppingPlace * > myEmptyStoppingPlaceCont
Definition MSNet.h:1052
void writeOverheadWireSegmentOutput() const
write the output generated by an overhead wire segment
Definition MSNet.cpp:1599
void writeChargingStationOutput() const
write charging station output
Definition MSNet.cpp:1563
SUMOTime myStateLoaderTime
Definition MSNet.h:902
std::pair< bool, NamedRTree > myLanesRTree
An RTree structure holding lane IDs.
Definition MSNet.h:1069
bool checkBidiEdges()
check wether bidirectional edges occur in the network
Definition MSNet.cpp:1772
VehicleState
Definition of a vehicle state.
Definition MSNet.h:636
int myLogStepPeriod
Period between successive step-log outputs.
Definition MSNet.h:957
SUMOTime myStep
Current time step.
Definition MSNet.h:893
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:199
bool myHasBidiEdges
Whether the network contains bidirectional rail edges.
Definition MSNet.h:1019
bool addStoppingPlace(SumoXMLTag category, MSStoppingPlace *stop)
Adds a stopping place.
Definition MSNet.cpp:1478
void addPreference(const std::string &routingType, SUMOVehicleClass svc, double prio)
add edge type specific routing preference
Definition MSNet.cpp:414
MSEventControl * myBeginOfTimestepEvents
Controls events executed at the begin of a time step;.
Definition MSNet.h:935
SUMOTime getLoaderTime() const
Definition MSNet.cpp:1127
bool addTractionSubstation(MSTractionSubstation *substation)
Adds a traction substation.
Definition MSNet.cpp:1491
std::map< std::string, bool > myWarnedOnce
container to record warnings that shall only be issued once
Definition MSNet.h:1056
static void initStatic()
Place for static initializations of simulation components (called after successful net build)
Definition MSNet.cpp:207
void removeOutdatedCollisions()
remove collisions from the previous simulation step
Definition MSNet.cpp:1459
MSJunctionControl * myJunctions
Controls junctions, realizes right-of-way rules;.
Definition MSNet.h:927
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:983
ShapeContainer * myShapeContainer
A container for geometrical shapes;.
Definition MSNet.h:941
std::string myStateDumpSuffix
Definition MSNet.h:988
const std::vector< MSStoppingPlace * > & getStoppingPlaceAlternatives(const std::string &name, SumoXMLTag category) const
Definition MSNet.cpp:1536
bool checkElevation()
check all lanes for elevation data
Definition MSNet.cpp:1747
MSTransportableRouter & getIntermodalRouter(int rngIndex, const int routingMode=0, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1680
std::map< SumoXMLTag, std::map< std::string, std::vector< MSStoppingPlace * > > > myNamedStoppingPlaces
dictionary of named stopping places
Definition MSNet.h:1031
static const std::vector< MSStoppingPlace * > myEmptyStoppingPlaceVector
Definition MSNet.h:1053
void removeTransportableStateListener(TransportableStateListener *listener)
Removes a transportable states listener.
Definition MSNet.cpp:1395
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:996
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:272
bool myLogStepNumber
Information whether the number of the simulation step shall be logged.
Definition MSNet.h:955
MMVersion myVersion
the network version
Definition MSNet.h:1022
MSEventControl * myInsertionEvents
Controls insertion events;.
Definition MSNet.h:939
virtual MSTransportableControl & getContainerControl()
Returns the container control.
Definition MSNet.cpp:1300
MSVehicleRouter & getRouterTT(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1633
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:1065
static const std::string STAGE_MOVEMENTS
Definition MSNet.h:863
bool hasFlow(const std::string &id) const
return whether the given flow is known
Definition MSNet.cpp:455
int myMaxTeleports
Maximum number of teleports.
Definition MSNet.h:908
long mySimStepDuration
Definition MSNet.h:960
double getPreference(const std::string &routingType, const SUMOVTypeParameter &pars) const
retriefe edge type specific routing preference
Definition MSNet.cpp:384
MSEventControl * myEndOfTimestepEvents
Controls events executed at the end of a time step;.
Definition MSNet.h:937
static std::string getStateMessage(SimulationState state)
Returns the message to show if a certain state occurs.
Definition MSNet.cpp:1017
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:1522
bool myHasInternalLinks
Whether the network contains internal links/lanes/edges.
Definition MSNet.h:1007
void writeSubstationOutput() const
write electrical substation output
Definition MSNet.cpp:1610
static const std::string STAGE_INSERTIONS
Definition MSNet.h:865
std::map< SUMOVehicleClass, std::map< std::string, double > > myVClassPreferences
Preferences for routing.
Definition MSNet.h:1000
long long int myPersonsMoved
Definition MSNet.h:970
void quickReload()
reset state to the beginning without reloading the network
Definition MSNet.cpp:1802
MSPedestrianRouter & getPedestrianRouter(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1667
MSVehicleControl * myVehicleControl
Controls vehicle building and deletion;.
Definition MSNet.h:919
static void clearAll()
Clears all dictionaries.
Definition MSNet.cpp:1042
static void cleanupStatic()
Place for static initializations of simulation components (called after successful net build)
Definition MSNet.cpp:213
void writeStatistics(const SUMOTime start, const long now) const
write statistic output to (xml) file
Definition MSNet.cpp:639
void resetIntermodalRouter() const
force reconstruction of intermodal network
Definition MSNet.cpp:1702
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:334
MSEdgeControl * myEdges
Controls edges, performs vehicle movement;.
Definition MSNet.h:925
std::unique_ptr< MSDynamicShapeUpdater > myDynamicShapeUpdater
Updater for dynamic shapes that are tracking traffic objects (ensures removal of shape dynamics when ...
Definition MSNet.h:1074
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:374
void closeSimulation(SUMOTime start, const std::string &reason="")
Closes the simulation (all files, connections, etc.)
Definition MSNet.cpp:756
MSStoppingPlace * getStoppingPlace(const std::string &id, const SumoXMLTag category) const
Returns the named stopping place of the given category.
Definition MSNet.cpp:1501
bool myHasElevation
Whether the network contains elevation data.
Definition MSNet.h:1013
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:923
std::vector< TransportableStateListener * > myTransportableStateListeners
Container for transportable state listener.
Definition MSNet.h:1040
void writeOutput()
Write netstate, summary and detector output.
Definition MSNet.cpp:1138
virtual void updateGUI() const
update view after simulation.loadState
Definition MSNet.h:624
void setLoaderTime(SUMOTime time)
Definition MSNet.cpp:1132
bool myAmInterrupted
whether an interrupt occurred
Definition MSNet.h:911
void simulationStep(const bool onlyMove=false)
Performs a single simulation step.
Definition MSNet.cpp:797
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1359
void clearState(const SUMOTime step, bool quickReload=false)
Resets events when quick-loading state.
Definition MSNet.cpp:1073
void preSimStepOutput() const
Prints the current step number.
Definition MSNet.cpp:1323
void writeCollisions() const
write collision output to (xml) file
Definition MSNet.cpp:610
std::vector< SUMOTime > myStateDumpTimes
Times at which a state shall be written.
Definition MSNet.h:979
void writeSummaryOutput(bool finalStep=false)
write summary-output to (xml) file
Definition MSNet.cpp:688
void addTransportableStateListener(TransportableStateListener *listener)
Adds a transportable states listener.
Definition MSNet.cpp:1387
std::vector< MSTractionSubstation * > myTractionSubstations
Dictionary of traction substations.
Definition MSNet.h:1034
SUMOTime myEdgeDataEndTime
end of loaded edgeData
Definition MSNet.h:1025
MSEdgeWeightsStorage & getWeightsStorage()
Returns the net's internal edge travel times/efforts container.
Definition MSNet.cpp:1314
std::map< std::string, std::map< SUMOVehicleClass, double > > myRestrictions
The vehicle class specific speed restrictions.
Definition MSNet.h:997
std::vector< std::string > myStateDumpFiles
The names for the state files.
Definition MSNet.h:981
void addMesoType(const std::string &typeID, const MESegment::MesoEdgeType &edgeType)
Adds edge type specific meso parameters.
Definition MSNet.cpp:427
void writeRailSignalBlocks() const
write rail signal block output
Definition MSNet.cpp:1574
MSTLLogicControl * myLogics
Controls tls logics, realizes waiting on tls rules;.
Definition MSNet.h:929
bool logSimulationDuration() const
Returns whether duration shall be logged.
Definition MSNet.cpp:1285
long long int myVehiclesMoved
The overall number of vehicle movements.
Definition MSNet.h:969
static const std::string STAGE_REMOTECONTROL
Definition MSNet.h:866
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:1376
std::map< int, MSTransportableRouter * > myIntermodalRouter
Definition MSNet.h:1066
std::vector< VehicleStateListener * > myVehicleStateListeners
Container for vehicle state listener.
Definition MSNet.h:1037
SimulationState simulationState(SUMOTime stopTime) const
This method returns the current simulation state. It should not modify status.
Definition MSNet.cpp:966
long myTraCIStepDuration
The last simulation step duration.
Definition MSNet.h:960
TransportableState
Definition of a transportable state.
Definition MSNet.h:713
MSInsertionControl & getInsertionControl()
Returns the insertion control.
Definition MSNet.h:455
MSDetectorControl * myDetectorControl
Controls detectors;.
Definition MSNet.h:933
bool myStepCompletionMissing
whether libsumo triggered a partial step (executeMove)
Definition MSNet.h:905
static const std::string STAGE_LANECHANGE
Definition MSNet.h:864
void addRestriction(const std::string &id, const SUMOVehicleClass svc, const double speed)
Adds a restriction for an edge type.
Definition MSNet.cpp:368
std::map< std::string, MESegment::MesoEdgeType > myMesoEdgeTypes
The edge type specific meso parameters.
Definition MSNet.h:1004
MSEdgeWeightsStorage * myEdgeWeights
The net's knowledge about edge efforts/travel times;.
Definition MSNet.h:943
MSDynamicShapeUpdater * makeDynamicShapeUpdater()
Creates and returns a dynamic shapes updater.
Definition MSNet.cpp:1308
virtual ~MSNet()
Destructor.
Definition MSNet.cpp:307
std::map< int, MSVehicleRouter * > myRouterEffort
Definition MSNet.h:1064
MSTractionSubstation * findTractionSubstation(const std::string &substationId)
find electrical substation by its id
Definition MSNet.cpp:1622
static MSNet * myInstance
Unique instance of MSNet.
Definition MSNet.h:887
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition MSNet.h:402
MSInsertionControl * myInserter
Controls vehicle insertion;.
Definition MSNet.h:931
void postSimStepOutput() const
Prints the statistics of the step at its end.
Definition MSNet.cpp:1329
virtual MSTransportableControl & getPersonControl()
Returns the person control.
Definition MSNet.cpp:1291
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:1415
static const std::string STAGE_EVENTS
string constants for simstep stages
Definition MSNet.h:862
void loadRoutes()
loads routes for the next few steps
Definition MSNet.cpp:504
std::string myStateDumpPrefix
name components for periodic state
Definition MSNet.h:987
bool myJunctionHigherSpeeds
Whether the network was built with higher speed on junctions.
Definition MSNet.h:1010
MSEdgeControl & getEdgeControl()
Returns the edge control.
Definition MSNet.h:445
long mySimBeginMillis
The overall simulation duration.
Definition MSNet.h:963
bool myHasPedestrianNetwork
Whether the network contains pedestrian network elements.
Definition MSNet.h:1016
std::map< int, MSVehicleRouter * > myRouterTT
Definition MSNet.h:1063
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:432
void postMoveStep()
Performs the parts of the simulation step which happen after the move.
Definition MSNet.cpp:937
bool hasInternalLinks() const
return whether the network contains internal links
Definition MSNet.h:811
const std::string generateStatistics(const SUMOTime start, const long now)
Writes performance output and running vehicle stats.
Definition MSNet.cpp:510
bool checkWalkingarea()
check all lanes for type walkingArea
Definition MSNet.cpp:1761
static void adaptIntermodalRouter(MSTransportableRouter &router)
Definition MSNet.cpp:1711
CollisionMap myCollisions
collisions in the current time step
Definition MSNet.h:1043
MSVehicleRouter & getRouterEffort(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1654
const NamedObjectCont< MSStoppingPlace * > & getStoppingPlaces(SumoXMLTag category) const
Definition MSNet.cpp:1552
SimulationState simulate(SUMOTime start, SUMOTime stop)
Simulates from timestep start to stop.
Definition MSNet.cpp:462
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 bool haveExtras()
static double getEffortBike(const MSEdge *const e, const SUMOVehicle *const v, double t)
static void applyExtras(const MSEdge *const e, const SUMOVehicle *const v, SUMOTime step, double &effort)
apply cost modifications from randomness, priorityFactor and preferences
static bool hasBikeSpeeds()
whether the router collects bicycle speeds
static double getEffort(const MSEdge *const e, const SUMOVehicle *const v, double t)
Returns the effort to pass an edge.
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:55
static void cleanup()
Definition MSStopOut.cpp:51
void generateOutputForUnfinished()
generate output for vehicles which are still stopped at simulation end
static MSStopOut * getInstance()
Definition MSStopOut.h:61
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:73
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:59
An output device that encapsulates an ofstream.
Static storage of an output device and its base (abstract) implementation.
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
OutputDevice & writeAttr(const ATTR_TYPE &attr, const T &val, const bool isNull=false)
writes a named attribute
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
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
SUMOTime getCurrentLoadTime() const
void setCurrentLoadTime(SUMOTime time)
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 SUMOVehicleClass getVClass() const =0
Returns the object's access class.
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:45
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
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