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 }
158 if (getInstance()->getWeightsStorage().retrieveExistingEffort(e, t, value)) {
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 }
172 if (getInstance()->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
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
198
199void
205
206
207MSNet::MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents,
208 MSEventControl* endOfTimestepEvents,
209 MSEventControl* insertionEvents,
210 ShapeContainer* shapeCont):
211 myAmInterrupted(false),
214 myHavePermissions(false),
215 myHasInternalLinks(false),
217 myHasElevation(false),
219 myHasBidiEdges(false),
221 myDynamicShapeUpdater(nullptr) {
222 if (myInstance != nullptr) {
223 throw ProcessError(TL("A network was already constructed."));
224 }
226 myStep = string2time(oc.getString("begin"));
227 myMaxTeleports = oc.getInt("max-num-teleports");
228 myLogExecutionTime = !oc.getBool("no-duration-log");
229 myLogStepNumber = !oc.getBool("no-step-log");
230 myLogStepPeriod = oc.getInt("step-log.period");
231 myInserter = new MSInsertionControl(*vc, string2time(oc.getString("max-depart-delay")), oc.getBool("eager-insert"), oc.getInt("max-num-vehicles"),
232 string2time(oc.getString("random-depart-offset")));
233 myVehicleControl = vc;
235 myEdges = nullptr;
236 myJunctions = nullptr;
237 myRouteLoaders = nullptr;
238 myLogics = nullptr;
239 myPersonControl = nullptr;
240 myContainerControl = nullptr;
241 myEdgeWeights = nullptr;
242 myShapeContainer = shapeCont == nullptr ? new ShapeContainer() : shapeCont;
243
244 myBeginOfTimestepEvents = beginOfTimestepEvents;
245 myEndOfTimestepEvents = endOfTimestepEvents;
246 myInsertionEvents = insertionEvents;
247 myLanesRTree.first = false;
248
250 MSGlobals::gMesoNet = new MELoop(string2time(oc.getString("meso-recheck")));
251 }
252 myInstance = this;
253 initStatic();
254}
255
256
257void
259 SUMORouteLoaderControl* routeLoaders,
260 MSTLLogicControl* tlc,
261 std::vector<SUMOTime> stateDumpTimes,
262 std::vector<std::string> stateDumpFiles,
263 bool hasInternalLinks,
264 bool junctionHigherSpeeds,
265 const MMVersion& version) {
266 myEdges = edges;
267 myJunctions = junctions;
268 myRouteLoaders = routeLoaders;
269 myLogics = tlc;
270 // save the time the network state shall be saved at
271 myStateDumpTimes = stateDumpTimes;
272 myStateDumpFiles = stateDumpFiles;
273 myStateDumpPeriod = string2time(oc.getString("save-state.period"));
274 myStateDumpPrefix = oc.getString("save-state.prefix");
275 myStateDumpSuffix = oc.getString("save-state.suffix");
276
277 // initialise performance computation
279 myTraCIMillis = 0;
281 myJunctionHigherSpeeds = junctionHigherSpeeds;
285 myVersion = version;
288 throw ProcessError(TL("Option weights.separate-turns is only supported when simulating with internal lanes"));
289 }
290}
291
292
295 // delete controls
296 delete myJunctions;
297 delete myDetectorControl;
298 // delete mean data
299 delete myEdges;
300 delete myInserter;
301 myInserter = nullptr;
302 delete myLogics;
303 delete myRouteLoaders;
304 if (myPersonControl != nullptr) {
305 delete myPersonControl;
306 myPersonControl = nullptr; // just to have that clear for later cleanups
307 }
308 if (myContainerControl != nullptr) {
309 delete myContainerControl;
310 myContainerControl = nullptr; // just to have that clear for later cleanups
311 }
312 delete myVehicleControl; // must happen after deleting transportables
313 // delete events late so that vehicles can get rid of references first
315 myBeginOfTimestepEvents = nullptr;
317 myEndOfTimestepEvents = nullptr;
318 delete myInsertionEvents;
319 myInsertionEvents = nullptr;
320 delete myShapeContainer;
321 delete myEdgeWeights;
322 for (auto& router : myRouterTT) {
323 delete router.second;
324 }
325 myRouterTT.clear();
326 for (auto& router : myRouterEffort) {
327 delete router.second;
328 }
329 myRouterEffort.clear();
330 for (auto& router : myPedestrianRouter) {
331 delete router.second;
332 }
333 myPedestrianRouter.clear();
334 for (auto& router : myIntermodalRouter) {
335 delete router.second;
336 }
337 myIntermodalRouter.clear();
338 myLanesRTree.second.RemoveAll();
339 clearAll();
341 delete MSGlobals::gMesoNet;
342 }
343 myInstance = nullptr;
344}
345
346
347void
348MSNet::addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed) {
349 myRestrictions[id][svc] = speed;
350}
351
352
353const std::map<SUMOVehicleClass, double>*
354MSNet::getRestrictions(const std::string& id) const {
355 std::map<std::string, std::map<SUMOVehicleClass, double> >::const_iterator i = myRestrictions.find(id);
356 if (i == myRestrictions.end()) {
357 return nullptr;
358 }
359 return &i->second;
360}
361
362
363double
364MSNet::getPreference(const std::string& routingType, const SUMOVTypeParameter& pars) const {
366 auto it = myVTypePreferences.find(pars.id);
367 if (it != myVTypePreferences.end()) {
368 auto it2 = it->second.find(routingType);
369 if (it2 != it->second.end()) {
370 return it2->second;
371 }
372 }
373 auto it3 = myVClassPreferences.find(pars.vehicleClass);
374 if (it3 != myVClassPreferences.end()) {
375 auto it4 = it3->second.find(routingType);
376 if (it4 != it3->second.end()) {
377 return it4->second;
378 }
379 }
380 // fallback to generel preferences
381 it = myVTypePreferences.find("");
382 if (it != myVTypePreferences.end()) {
383 auto it2 = it->second.find(routingType);
384 if (it2 != it->second.end()) {
385 return it2->second;
386 }
387 }
388 }
389 return 1;
390}
391
392
393void
394MSNet::addPreference(const std::string& routingType, SUMOVehicleClass svc, double prio) {
395 myVClassPreferences[svc][routingType] = prio;
396 gRoutingPreferences = true;
397}
398
399
400void
401MSNet::addPreference(const std::string& routingType, std::string vType, double prio) {
402 myVTypePreferences[vType][routingType] = prio;
403 gRoutingPreferences = true;
404}
405
406void
407MSNet::addMesoType(const std::string& typeID, const MESegment::MesoEdgeType& edgeType) {
408 myMesoEdgeTypes[typeID] = edgeType;
409}
410
412MSNet::getMesoType(const std::string& typeID) {
413 if (myMesoEdgeTypes.count(typeID) == 0) {
414 // init defaults
417 edgeType.tauff = string2time(oc.getString("meso-tauff"));
418 edgeType.taufj = string2time(oc.getString("meso-taufj"));
419 edgeType.taujf = string2time(oc.getString("meso-taujf"));
420 edgeType.taujj = string2time(oc.getString("meso-taujj"));
421 edgeType.jamThreshold = oc.getFloat("meso-jam-threshold");
422 edgeType.junctionControl = oc.getBool("meso-junction-control");
423 edgeType.tlsPenalty = oc.getFloat("meso-tls-penalty");
424 edgeType.tlsFlowPenalty = oc.getFloat("meso-tls-flow-penalty");
425 edgeType.minorPenalty = string2time(oc.getString("meso-minor-penalty"));
426 edgeType.overtaking = oc.getBool("meso-overtaking");
427 myMesoEdgeTypes[typeID] = edgeType;
428 }
429 return myMesoEdgeTypes[typeID];
430}
431
432
433bool
434MSNet::hasFlow(const std::string& id) const {
435 // inserter is deleted at the end of the simulation
436 return myInserter != nullptr && myInserter->hasFlow(id);
437}
438
439
442 // report the begin when wished
443 WRITE_MESSAGEF(TL("Simulation version % started with time: %."), VERSION_STRING, time2string(start));
444 // the simulation loop
446 // state loading may have changed the start time so we need to reinit it
447 myStep = start;
448 int numSteps = 0;
449 bool doStepLog = false;
450 while (state == SIMSTATE_RUNNING) {
451 doStepLog = myLogStepNumber && (numSteps % myLogStepPeriod == 0);
452 if (doStepLog) {
454 }
456 if (doStepLog) {
458 }
459 state = adaptToState(simulationState(stop));
460#ifdef DEBUG_SIMSTEP
461 std::cout << SIMTIME << " MSNet::simulate(" << start << ", " << stop << ")"
462 << "\n simulation state: " << getStateMessage(state)
463 << std::endl;
464#endif
465 numSteps++;
466 }
467 if (myLogStepNumber && !doStepLog) {
468 // ensure some output on the last step
471 }
472 // exit simulation loop
473 if (myLogStepNumber) {
474 // start new line for final verbose output
475 std::cout << "\n";
476 }
477 closeSimulation(start, getStateMessage(state));
478 return state;
479}
480
481
482void
484 myRouteLoaders->loadNext(myStep);
485}
486
487
488const std::string
489MSNet::generateStatistics(const SUMOTime start, const long now) {
490 std::ostringstream msg;
491 if (myLogExecutionTime) {
492 const long duration = now - mySimBeginMillis;
493 // print performance notice
494 msg << "Performance:\n" << " Duration: " << elapsedMs2string(duration) << "\n";
495 if (duration != 0) {
496 if (TraCIServer::getInstance() != nullptr) {
497 msg << " TraCI-Duration: " << elapsedMs2string(myTraCIMillis) << "\n";
498 }
499 msg << " Real time factor: " << (STEPS2TIME(myStep - start) * 1000. / (double)duration) << "\n";
500 msg.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
501 msg.setf(std::ios::showpoint); // print decimal point
502 msg << " UPS: " << ((double)myVehiclesMoved / ((double)duration / 1000)) << "\n";
503 if (myPersonsMoved > 0) {
504 msg << " UPS-Persons: " << ((double)myPersonsMoved / ((double)duration / 1000)) << "\n";
505 }
506 }
507 // print vehicle statistics
508 const std::string vehDiscardNotice = ((myVehicleControl->getLoadedVehicleNo() != myVehicleControl->getDepartedVehicleNo()) ?
509 " (Loaded: " + toString(myVehicleControl->getLoadedVehicleNo()) + ")" : "");
510 msg << "Vehicles:\n"
511 << " Inserted: " << myVehicleControl->getDepartedVehicleNo() << vehDiscardNotice << "\n"
512 << " Running: " << myVehicleControl->getRunningVehicleNo() << "\n"
513 << " Waiting: " << myInserter->getWaitingVehicleNo() << "\n";
514
515 if (myVehicleControl->getTeleportCount() > 0 || myVehicleControl->getCollisionCount() > 0) {
516 // print optional teleport statistics
517 std::vector<std::string> reasons;
518 if (myVehicleControl->getCollisionCount() > 0) {
519 reasons.push_back("Collisions: " + toString(myVehicleControl->getCollisionCount()));
520 }
521 if (myVehicleControl->getTeleportsJam() > 0) {
522 reasons.push_back("Jam: " + toString(myVehicleControl->getTeleportsJam()));
523 }
524 if (myVehicleControl->getTeleportsYield() > 0) {
525 reasons.push_back("Yield: " + toString(myVehicleControl->getTeleportsYield()));
526 }
527 if (myVehicleControl->getTeleportsWrongLane() > 0) {
528 reasons.push_back("Wrong Lane: " + toString(myVehicleControl->getTeleportsWrongLane()));
529 }
530 msg << " Teleports: " << myVehicleControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
531 }
532 if (myVehicleControl->getEmergencyStops() > 0) {
533 msg << " Emergency Stops: " << myVehicleControl->getEmergencyStops() << "\n";
534 }
535 if (myVehicleControl->getEmergencyBrakingCount() > 0) {
536 msg << " Emergency Braking: " << myVehicleControl->getEmergencyBrakingCount() << "\n";
537 }
538 if (myPersonControl != nullptr && myPersonControl->getLoadedNumber() > 0) {
539 const std::string discardNotice = ((myPersonControl->getLoadedNumber() != myPersonControl->getDepartedNumber()) ?
540 " (Loaded: " + toString(myPersonControl->getLoadedNumber()) + ")" : "");
541 msg << "Persons:\n"
542 << " Inserted: " << myPersonControl->getDepartedNumber() << discardNotice << "\n"
543 << " Running: " << myPersonControl->getRunningNumber() << "\n";
544 if (myPersonControl->getJammedNumber() > 0) {
545 msg << " Jammed: " << myPersonControl->getJammedNumber() << "\n";
546 }
547 if (myPersonControl->getTeleportCount() > 0) {
548 std::vector<std::string> reasons;
549 if (myPersonControl->getTeleportsAbortWait() > 0) {
550 reasons.push_back("Abort Wait: " + toString(myPersonControl->getTeleportsAbortWait()));
551 }
552 if (myPersonControl->getTeleportsWrongDest() > 0) {
553 reasons.push_back("Wrong Dest: " + toString(myPersonControl->getTeleportsWrongDest()));
554 }
555 msg << " Teleports: " << myPersonControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
556 }
557 }
558 if (myContainerControl != nullptr && myContainerControl->getLoadedNumber() > 0) {
559 const std::string discardNotice = ((myContainerControl->getLoadedNumber() != myContainerControl->getDepartedNumber()) ?
560 " (Loaded: " + toString(myContainerControl->getLoadedNumber()) + ")" : "");
561 msg << "Containers:\n"
562 << " Inserted: " << myContainerControl->getDepartedNumber() << "\n"
563 << " Running: " << myContainerControl->getRunningNumber() << "\n";
564 if (myContainerControl->getJammedNumber() > 0) {
565 msg << " Jammed: " << myContainerControl->getJammedNumber() << "\n";
566 }
567 if (myContainerControl->getTeleportCount() > 0) {
568 std::vector<std::string> reasons;
569 if (myContainerControl->getTeleportsAbortWait() > 0) {
570 reasons.push_back("Abort Wait: " + toString(myContainerControl->getTeleportsAbortWait()));
571 }
572 if (myContainerControl->getTeleportsWrongDest() > 0) {
573 reasons.push_back("Wrong Dest: " + toString(myContainerControl->getTeleportsWrongDest()));
574 }
575 msg << " Teleports: " << myContainerControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
576 }
577 }
578 }
579 if (OptionsCont::getOptions().getBool("duration-log.statistics")) {
581 }
582 std::string result = msg.str();
583 result.erase(result.end() - 1);
584 return result;
585}
586
587
588void
590 OutputDevice& od = OutputDevice::getDeviceByOption("collision-output");
591 for (const auto& item : myCollisions) {
592 for (const auto& c : item.second) {
593 if (c.time != SIMSTEP) {
594 continue;
595 }
596 od.openTag("collision");
598 od.writeAttr("type", c.type);
599 od.writeAttr("lane", c.lane->getID());
600 od.writeAttr("pos", c.pos);
601 od.writeAttr("collider", item.first);
602 od.writeAttr("victim", c.victim);
603 od.writeAttr("colliderType", c.colliderType);
604 od.writeAttr("victimType", c.victimType);
605 od.writeAttr("colliderSpeed", c.colliderSpeed);
606 od.writeAttr("victimSpeed", c.victimSpeed);
607 od.writeAttr("colliderFront", c.colliderFront);
608 od.writeAttr("colliderBack", c.colliderBack);
609 od.writeAttr("victimFront", c.victimFront);
610 od.writeAttr("victimBack", c.victimBack);
611 od.closeTag();
612 }
613 }
614}
615
616
617void
618MSNet::writeStatistics(const SUMOTime start, const long now) const {
619 const long duration = now - mySimBeginMillis;
620 OutputDevice& od = OutputDevice::getDeviceByOption("statistic-output");
621 od.openTag("performance");
622 od.writeAttr("clockBegin", time2string(mySimBeginMillis));
623 od.writeAttr("clockEnd", time2string(now));
624 od.writeAttr("clockDuration", time2string(duration));
625 od.writeAttr("traciDuration", time2string(myTraCIMillis));
626 od.writeAttr("realTimeFactor", duration != 0 ? (double)(myStep - start) / (double)duration : -1);
627 od.writeAttr("vehicleUpdatesPerSecond", duration != 0 ? (double)myVehiclesMoved / ((double)duration / 1000) : -1);
628 od.writeAttr("personUpdatesPerSecond", duration != 0 ? (double)myPersonsMoved / ((double)duration / 1000) : -1);
629 od.writeAttr("begin", time2string(start));
630 od.writeAttr("end", time2string(myStep));
631 od.writeAttr("duration", time2string(myStep - start));
632 od.closeTag();
633 od.openTag("vehicles");
634 od.writeAttr("loaded", myVehicleControl->getLoadedVehicleNo());
635 od.writeAttr("inserted", myVehicleControl->getDepartedVehicleNo());
636 od.writeAttr("running", myVehicleControl->getRunningVehicleNo());
637 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
638 od.closeTag();
639 od.openTag("teleports");
640 od.writeAttr("total", myVehicleControl->getTeleportCount());
641 od.writeAttr("jam", myVehicleControl->getTeleportsJam());
642 od.writeAttr("yield", myVehicleControl->getTeleportsYield());
643 od.writeAttr("wrongLane", myVehicleControl->getTeleportsWrongLane());
644 od.closeTag();
645 od.openTag("safety");
646 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
647 od.writeAttr("emergencyStops", myVehicleControl->getEmergencyStops());
648 od.writeAttr("emergencyBraking", myVehicleControl->getEmergencyBrakingCount());
649 od.closeTag();
650 od.openTag("persons");
651 od.writeAttr("loaded", myPersonControl != nullptr ? myPersonControl->getLoadedNumber() : 0);
652 od.writeAttr("running", myPersonControl != nullptr ? myPersonControl->getRunningNumber() : 0);
653 od.writeAttr("jammed", myPersonControl != nullptr ? myPersonControl->getJammedNumber() : 0);
654 od.closeTag();
655 od.openTag("personTeleports");
656 od.writeAttr("total", myPersonControl != nullptr ? myPersonControl->getTeleportCount() : 0);
657 od.writeAttr("abortWait", myPersonControl != nullptr ? myPersonControl->getTeleportsAbortWait() : 0);
658 od.writeAttr("wrongDest", myPersonControl != nullptr ? myPersonControl->getTeleportsWrongDest() : 0);
659 od.closeTag();
660 if (OptionsCont::getOptions().isSet("tripinfo-output") || OptionsCont::getOptions().getBool("duration-log.statistics")) {
662 }
663
664}
665
666
667void
669 // summary output
671 const bool hasOutput = oc.isSet("summary-output");
672 const bool hasPersonOutput = oc.isSet("person-summary-output");
673 if (hasOutput || hasPersonOutput) {
674 const SUMOTime period = string2time(oc.getString("summary-output.period"));
675 const SUMOTime begin = string2time(oc.getString("begin"));
676 if ((period > 0 && (myStep - begin) % period != 0 && !finalStep)
677 // it's the final step but we already wrote output
678 || (finalStep && (period <= 0 || (myStep - begin) % period == 0))) {
679 return;
680 }
681 }
682 if (hasOutput) {
683 OutputDevice& od = OutputDevice::getDeviceByOption("summary-output");
684 int departedVehiclesNumber = myVehicleControl->getDepartedVehicleNo();
685 const double meanWaitingTime = departedVehiclesNumber != 0 ? myVehicleControl->getTotalDepartureDelay() / (double) departedVehiclesNumber : -1.;
686 int endedVehicleNumber = myVehicleControl->getEndedVehicleNo();
687 const double meanTravelTime = endedVehicleNumber != 0 ? myVehicleControl->getTotalTravelTime() / (double) endedVehicleNumber : -1.;
688 od.openTag("step");
689 od.writeAttr("time", time2string(myStep));
690 od.writeAttr("loaded", myVehicleControl->getLoadedVehicleNo());
691 od.writeAttr("inserted", myVehicleControl->getDepartedVehicleNo());
692 od.writeAttr("running", myVehicleControl->getRunningVehicleNo());
693 od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
694 od.writeAttr("ended", myVehicleControl->getEndedVehicleNo());
695 od.writeAttr("arrived", myVehicleControl->getArrivedVehicleNo());
696 od.writeAttr("collisions", myVehicleControl->getCollisionCount());
697 od.writeAttr("teleports", myVehicleControl->getTeleportCount());
698 od.writeAttr("halting", myVehicleControl->getHaltingVehicleNo());
699 od.writeAttr("stopped", myVehicleControl->getStoppedVehiclesCount());
700 od.writeAttr("meanWaitingTime", meanWaitingTime);
701 od.writeAttr("meanTravelTime", meanTravelTime);
702 std::pair<double, double> meanSpeed = myVehicleControl->getVehicleMeanSpeeds();
703 od.writeAttr("meanSpeed", meanSpeed.first);
704 od.writeAttr("meanSpeedRelative", meanSpeed.second);
705 od.writeAttr("discarded", myVehicleControl->getDiscardedVehicleNo());
706 if (myLogExecutionTime) {
707 od.writeAttr("duration", mySimStepDuration);
708 }
709 od.closeTag();
710 }
711 if (hasPersonOutput) {
712 OutputDevice& od = OutputDevice::getDeviceByOption("person-summary-output");
714 od.openTag("step");
715 od.writeAttr("time", time2string(myStep));
716 od.writeAttr("loaded", pc.getLoadedNumber());
717 od.writeAttr("inserted", pc.getDepartedNumber());
718 od.writeAttr("walking", pc.getMovingNumber());
719 od.writeAttr("waitingForRide", pc.getWaitingForVehicleNumber());
720 od.writeAttr("riding", pc.getRidingNumber());
721 od.writeAttr("stopping", pc.getWaitingUntilNumber());
722 od.writeAttr("jammed", pc.getJammedNumber());
723 od.writeAttr("ended", pc.getEndedNumber());
724 od.writeAttr("arrived", pc.getArrivedNumber());
725 od.writeAttr("teleports", pc.getTeleportCount());
726 od.writeAttr("discarded", pc.getDiscardedNumber());
727 if (myLogExecutionTime) {
728 od.writeAttr("duration", mySimStepDuration);
729 }
730 od.closeTag();
731 }
732}
733
734
735void
736MSNet::closeSimulation(SUMOTime start, const std::string& reason) {
737 // report the end when wished
738 WRITE_MESSAGE(TLF("Simulation ended at time: %.", time2string(getCurrentTimeStep())));
739 if (reason != "") {
740 WRITE_MESSAGE(TL("Reason: ") + reason);
741 }
743 if (MSStopOut::active() && OptionsCont::getOptions().getBool("stop-output.write-unfinished")) {
745 }
746 MSDevice_Vehroutes::writePendingOutput(OptionsCont::getOptions().getBool("vehroute-output.write-unfinished"));
747 if (OptionsCont::getOptions().getBool("tripinfo-output.write-unfinished")) {
749 }
750 if (OptionsCont::getOptions().isSet("chargingstations-output")) {
751 if (!OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
753 } else if (OptionsCont::getOptions().getBool("chargingstations-output.aggregated.write-unfinished")) {
754 MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"), true);
755 }
756 }
757 if (OptionsCont::getOptions().isSet("overheadwiresegments-output")) {
759 }
760 if (OptionsCont::getOptions().isSet("substations-output")) {
762 }
764 const long now = SysUtils::getCurrentMillis();
765 if (myLogExecutionTime || OptionsCont::getOptions().getBool("duration-log.statistics")) {
767 }
768 if (OptionsCont::getOptions().isSet("statistic-output")) {
769 writeStatistics(start, now);
770 }
771 // maybe write a final line of output if reporting is periodic
772 writeSummaryOutput(true);
773}
774
775
776void
777MSNet::simulationStep(const bool onlyMove) {
779 postMoveStep();
781 return;
782 }
783#ifdef DEBUG_SIMSTEP
784 std::cout << SIMTIME << ": MSNet::simulationStep() called"
785 << ", myStep = " << myStep
786 << std::endl;
787#endif
789 int lastTraCICmd = 0;
790 if (t != nullptr) {
791 if (myLogExecutionTime) {
793 }
794 lastTraCICmd = t->processCommands(myStep);
795#ifdef DEBUG_SIMSTEP
796 bool loadRequested = !TraCI::getLoadArgs().empty();
797 assert(t->getTargetTime() >= myStep || loadRequested || TraCIServer::wasClosed());
798#endif
799 if (myLogExecutionTime) {
801 }
802 if (TraCIServer::wasClosed() || !t->getLoadArgs().empty()) {
803 return;
804 }
805 }
806#ifdef DEBUG_SIMSTEP
807 std::cout << SIMTIME << ": TraCI target time: " << t->getTargetTime() << std::endl;
808#endif
809 // execute beginOfTimestepEvents
810 if (myLogExecutionTime) {
812 }
813 // simulation state output
814 std::vector<SUMOTime>::iterator timeIt = std::find(myStateDumpTimes.begin(), myStateDumpTimes.end(), myStep);
815 if (timeIt != myStateDumpTimes.end()) {
816 const int dist = (int)distance(myStateDumpTimes.begin(), timeIt);
818 }
819 if (myStateDumpPeriod > 0 && myStep % myStateDumpPeriod == 0) {
820 std::string timeStamp = time2string(myStep);
821 std::replace(timeStamp.begin(), timeStamp.end(), ':', '-');
822 const std::string filename = myStateDumpPrefix + "_" + timeStamp + myStateDumpSuffix;
824 myPeriodicStateFiles.push_back(filename);
825 int keep = OptionsCont::getOptions().getInt("save-state.period.keep");
826 if (keep > 0 && (int)myPeriodicStateFiles.size() > keep) {
827 std::remove(myPeriodicStateFiles.front().c_str());
829 }
830 }
834 }
835#ifdef HAVE_FOX
836 MSRoutingEngine::waitForAll();
837#endif
839 myEdges->detectCollisions(myStep, STAGE_EVENTS);
840 }
841 // check whether the tls programs need to be switched
842 myLogics->check2Switch(myStep);
843
845 MSGlobals::gMesoNet->simulate(myStep);
846 } else {
847 // assure all lanes with vehicles are 'active'
848 myEdges->patchActiveLanes();
849
850 // compute safe velocities for all vehicles for the next few lanes
851 // also register ApproachingVehicleInformation for all links
852 myEdges->planMovements(myStep);
853
854 // register junction approaches based on planned velocities as basis for right-of-way decision
855 myEdges->setJunctionApproaches();
856
857 // decide right-of-way and execute movements
858 myEdges->executeMovements(myStep);
860 myEdges->detectCollisions(myStep, STAGE_MOVEMENTS);
861 }
862
863 // vehicles may change lanes
864 myEdges->changeLanes(myStep);
865
867 myEdges->detectCollisions(myStep, STAGE_LANECHANGE);
868 }
869 }
870 // flush arrived meso vehicles and micro vehicles that were removed due to collision
871 myVehicleControl->removePending();
872 loadRoutes();
873
874 // persons
875 if (myPersonControl != nullptr && myPersonControl->hasTransportables()) {
876 myPersonControl->checkWaiting(this, myStep);
877 }
878 // containers
879 if (myContainerControl != nullptr && myContainerControl->hasTransportables()) {
880 myContainerControl->checkWaiting(this, myStep);
881 }
884 // preserve waitRelation from insertion for the next step
885 }
886 // insert vehicles
887 myInserter->determineCandidates(myStep);
888 myInsertionEvents->execute(myStep);
889#ifdef HAVE_FOX
890 MSRoutingEngine::waitForAll();
891#endif
892 myInserter->emitVehicles(myStep);
894 //myEdges->patchActiveLanes(); // @note required to detect collisions on lanes that were empty before insertion. wasteful?
895 myEdges->detectCollisions(myStep, STAGE_INSERTIONS);
896 }
898
899 // execute endOfTimestepEvents
901
902 if (myLogExecutionTime) {
904 }
905 if (onlyMove) {
907 return;
908 }
909 if (t != nullptr && lastTraCICmd == libsumo::CMD_EXECUTEMOVE) {
910 t->processCommands(myStep, true);
911 }
912 postMoveStep();
913}
914
915
916void
918 const int numControlled = libsumo::Helper::postProcessRemoteControl();
919 if (numControlled > 0 && MSGlobals::gCheck4Accidents) {
920 myEdges->detectCollisions(myStep, STAGE_REMOTECONTROL);
921 }
922 if (myLogExecutionTime) {
925 }
927 // collisions from the previous step were kept to avoid duplicate
928 // warnings. we must remove them now to ensure correct output.
930 }
931 // update and write (if needed) detector values
933 writeOutput();
934
935 if (myLogExecutionTime) {
936 myVehiclesMoved += myVehicleControl->getRunningVehicleNo();
937 if (myPersonControl != nullptr) {
938 myPersonsMoved += myPersonControl->getRunningNumber();
939 }
940 }
941 myStep += DELTA_T;
942}
943
944
949 }
950 if (TraCIServer::getInstance() != nullptr && !TraCIServer::getInstance()->getLoadArgs().empty()) {
951 return SIMSTATE_LOADING;
952 }
953 if ((stopTime < 0 || myStep > stopTime) && TraCIServer::getInstance() == nullptr && (stopTime > 0 || myStep > myEdgeDataEndTime)) {
954 if ((myVehicleControl->getActiveVehicleCount() == 0)
955 && (myInserter->getPendingFlowCount() == 0)
956 && (myPersonControl == nullptr || !myPersonControl->hasNonWaiting())
957 && (myContainerControl == nullptr || !myContainerControl->hasNonWaiting())
960 }
961 }
962 if (stopTime >= 0 && myStep >= stopTime) {
964 }
965 if (myMaxTeleports >= 0 && myVehicleControl->getTeleportCount() > myMaxTeleports) {
967 }
968 if (myAmInterrupted) {
970 }
971 return SIMSTATE_RUNNING;
972}
973
974
976MSNet::adaptToState(MSNet::SimulationState state, const bool isLibsumo) const {
977 if (state == SIMSTATE_LOADING) {
980 } else if (state != SIMSTATE_RUNNING && ((TraCIServer::getInstance() != nullptr && !TraCIServer::wasClosed()) || isLibsumo)) {
981 // overrides SIMSTATE_END_STEP_REACHED, e.g. (TraCI / Libsumo ignore SUMO's --end option)
982 return SIMSTATE_RUNNING;
983 } else if (state == SIMSTATE_NO_FURTHER_VEHICLES) {
984 if (myPersonControl != nullptr) {
985 myPersonControl->abortAnyWaitingForVehicle();
986 }
987 if (myContainerControl != nullptr) {
988 myContainerControl->abortAnyWaitingForVehicle();
989 }
990 myVehicleControl->abortWaiting();
991 }
992 return state;
993}
994
995
996std::string
998 switch (state) {
1000 return "";
1002 return TL("The final simulation step has been reached.");
1004 return TL("All vehicles have left the simulation.");
1006 return TL("TraCI requested termination.");
1008 return TL("An error occurred (see log).");
1010 return TL("Interrupted.");
1012 return TL("Too many teleports.");
1014 return TL("TraCI issued load command.");
1015 default:
1016 return TL("Unknown reason.");
1017 }
1018}
1019
1020
1021void
1023 // clear container
1024 MSEdge::clear();
1025 MSLane::clear();
1030 while (!MSLaneSpeedTrigger::getInstances().empty()) {
1031 delete MSLaneSpeedTrigger::getInstances().begin()->second;
1032 }
1033 while (!MSTriggeredRerouter::getInstances().empty()) {
1034 delete MSTriggeredRerouter::getInstances().begin()->second;
1035 }
1044 if (t != nullptr) {
1045 t->cleanup();
1046 }
1049}
1050
1051
1052void
1056 MSGlobals::gMesoNet->clearState();
1057 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1058 for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*edge); s != nullptr; s = s->getNextSegment()) {
1059 s->clearState();
1060 }
1061 }
1062 } else {
1063 for (MSEdge* const edge : MSEdge::getAllEdges()) {
1064 for (MSLane* const lane : edge->getLanes()) {
1065 lane->getVehiclesSecure();
1066 lane->clearState();
1067 lane->releaseVehicles();
1068 }
1069 edge->clearState();
1070 }
1071 }
1072 myInserter->clearState();
1073 // detectors may still reference persons/vehicles
1074 myDetectorControl->updateDetectors(myStep);
1075 myDetectorControl->writeOutput(myStep, true);
1076 myDetectorControl->clearState(step);
1077
1078 if (myPersonControl != nullptr) {
1079 myPersonControl->clearState();
1080 }
1081 if (myContainerControl != nullptr) {
1082 myContainerControl->clearState();
1083 }
1084 // delete vtypes after transportables have removed their types
1085 myVehicleControl->clearState(true);
1087 myLogics->clearState(step, quickReload);
1088 // delete all routes after vehicles and detector output is done
1090 for (auto& item : myStoppingPlaces) {
1091 for (auto& item2 : item.second) {
1092 item2.second->clearState();
1093 }
1094 }
1095 myShapeContainer->clearState();
1096 myBeginOfTimestepEvents->clearState(myStep, step);
1097 myEndOfTimestepEvents->clearState(myStep, step);
1098 myInsertionEvents->clearState(myStep, step);
1101 myStep = step;
1102 MSGlobals::gClearState = false;
1103}
1104
1105
1106void
1108 // update detector values
1109 myDetectorControl->updateDetectors(myStep);
1111
1112 // check state dumps
1113 if (oc.isSet("netstate-dump")) {
1115 oc.getInt("netstate-dump.precision"));
1116 }
1117
1118 // check fcd dumps
1119 if (OptionsCont::getOptions().isSet("fcd-output")) {
1120 if (OptionsCont::getOptions().isSet("person-fcd-output")) {
1123 } else {
1125 }
1126 }
1127
1128 // check emission dumps
1129 if (OptionsCont::getOptions().isSet("emission-output")) {
1131 }
1132
1133 // battery dumps
1134 if (OptionsCont::getOptions().isSet("battery-output")) {
1136 oc.getInt("battery-output.precision"));
1137 }
1138
1139 // charging station aggregated dumps
1140 if (OptionsCont::getOptions().isSet("chargingstations-output") && OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
1142 }
1143
1144 // elecHybrid dumps
1145 if (OptionsCont::getOptions().isSet("elechybrid-output")) {
1146 std::string output = OptionsCont::getOptions().getString("elechybrid-output");
1147
1148 if (oc.getBool("elechybrid-output.aggregated")) {
1149 // build a xml file with aggregated device.elechybrid output
1151 oc.getInt("elechybrid-output.precision"));
1152 } else {
1153 // build a separate xml file for each vehicle equipped with device.elechybrid
1154 // RICE_TODO: Does this have to be placed here in MSNet.cpp ?
1156 for (MSVehicleControl::constVehIt it = vc.loadedVehBegin(); it != vc.loadedVehEnd(); ++it) {
1157 const SUMOVehicle* veh = it->second;
1158 if (!veh->isOnRoad()) {
1159 continue;
1160 }
1161 if (static_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid))) != nullptr) {
1162 std::string vehID = veh->getID();
1163 std::string filename2 = output + "_" + vehID + ".xml";
1164 OutputDevice& dev = OutputDevice::getDevice(filename2);
1165 std::map<SumoXMLAttr, std::string> attrs;
1166 attrs[SUMO_ATTR_VEHICLE] = vehID;
1169 dev.writeXMLHeader("elecHybrid-export", "", attrs);
1170 MSElecHybridExport::write(OutputDevice::getDevice(filename2), veh, myStep, oc.getInt("elechybrid-output.precision"));
1171 }
1172 }
1173 }
1174 }
1175
1176
1177 // check full dumps
1178 if (OptionsCont::getOptions().isSet("full-output")) {
1181 }
1182
1183 // check queue dumps
1184 if (OptionsCont::getOptions().isSet("queue-output")) {
1186 }
1187
1188 // check amitran dumps
1189 if (OptionsCont::getOptions().isSet("amitran-output")) {
1191 }
1192
1193 // check vtk dumps
1194 if (OptionsCont::getOptions().isSet("vtk-output")) {
1195
1196 if (MSNet::getInstance()->getVehicleControl().getRunningVehicleNo() > 0) {
1197 std::string timestep = time2string(myStep);
1198 timestep = timestep.substr(0, timestep.length() - 3);
1199 std::string output = OptionsCont::getOptions().getString("vtk-output");
1200 std::string filename = output + "_" + timestep + ".vtp";
1201
1202 OutputDevice_File dev(filename);
1203
1204 //build a huge mass of xml files
1206
1207 }
1208
1209 }
1210
1212
1213 // write detector values
1214 myDetectorControl->writeOutput(myStep + DELTA_T, false);
1215
1216 // write link states
1217 if (OptionsCont::getOptions().isSet("link-output")) {
1218 OutputDevice& od = OutputDevice::getDeviceByOption("link-output");
1219 od.openTag("timestep");
1221 for (const MSEdge* const edge : myEdges->getEdges()) {
1222 for (const MSLane* const lane : edge->getLanes()) {
1223 for (const MSLink* const link : lane->getLinkCont()) {
1224 link->writeApproaching(od, lane->getID());
1225 }
1226 }
1227 }
1228 od.closeTag();
1229 }
1230
1231 // write SSM output
1233 dev->updateAndWriteOutput();
1234 }
1235
1236 // write ToC output
1238 if (dev->generatesOutput()) {
1239 dev->writeOutput();
1240 }
1241 }
1242
1243 if (OptionsCont::getOptions().isSet("collision-output")) {
1245 }
1246}
1247
1248
1249bool
1253
1254
1257 if (myPersonControl == nullptr) {
1259 }
1260 return *myPersonControl;
1261}
1262
1263
1266 if (myContainerControl == nullptr) {
1268 }
1269 return *myContainerControl;
1270}
1271
1274 myDynamicShapeUpdater = std::unique_ptr<MSDynamicShapeUpdater> (new MSDynamicShapeUpdater(*myShapeContainer));
1275 return myDynamicShapeUpdater.get();
1276}
1277
1280 if (myEdgeWeights == nullptr) {
1282 }
1283 return *myEdgeWeights;
1284}
1285
1286
1287void
1289 std::cout << "Step #" << time2string(myStep);
1290}
1291
1292
1293void
1295 if (myLogExecutionTime) {
1296 std::ostringstream oss;
1297 oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
1298 oss.setf(std::ios::showpoint); // print decimal point
1299 oss << std::setprecision(gPrecision);
1300 if (mySimStepDuration != 0) {
1301 const double durationSec = (double)mySimStepDuration / 1000.;
1302 oss << " (" << mySimStepDuration << "ms ~= "
1303 << (TS / durationSec) << "*RT, ~"
1304 << ((double) myVehicleControl->getRunningVehicleNo() / durationSec);
1305 } else {
1306 oss << " (0ms ?*RT. ?";
1307 }
1308 oss << "UPS, ";
1309 if (TraCIServer::getInstance() != nullptr) {
1310 oss << "TraCI: " << myTraCIStepDuration << "ms, ";
1311 }
1312 oss << "vehicles TOT " << myVehicleControl->getDepartedVehicleNo()
1313 << " ACT " << myVehicleControl->getRunningVehicleNo()
1314 << " BUF " << myInserter->getWaitingVehicleNo()
1315 << ") ";
1316 std::string prev = "Step #" + time2string(myStep - DELTA_T);
1317 std::cout << oss.str().substr(0, 90 - prev.length());
1318 }
1319 std::cout << '\r';
1320}
1321
1322
1323void
1325 if (find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener) == myVehicleStateListeners.end()) {
1326 myVehicleStateListeners.push_back(listener);
1327 }
1328}
1329
1330
1331void
1333 std::vector<VehicleStateListener*>::iterator i = std::find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener);
1334 if (i != myVehicleStateListeners.end()) {
1335 myVehicleStateListeners.erase(i);
1336 }
1337}
1338
1339
1340void
1341MSNet::informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info) {
1342#ifdef HAVE_FOX
1343 ScopedLocker<> lock(myVehicleStateListenerMutex, MSGlobals::gNumThreads > 1);
1344#endif
1345 for (VehicleStateListener* const listener : myVehicleStateListeners) {
1346 listener->vehicleStateChanged(vehicle, to, info);
1347 }
1348}
1349
1350
1351void
1357
1358
1359void
1361 std::vector<TransportableStateListener*>::iterator i = std::find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener);
1362 if (i != myTransportableStateListeners.end()) {
1364 }
1365}
1366
1367
1368void
1369MSNet::informTransportableStateListener(const MSTransportable* const transportable, TransportableState to, const std::string& info) {
1370#ifdef HAVE_FOX
1371 ScopedLocker<> lock(myTransportableStateListenerMutex, MSGlobals::gNumThreads > 1);
1372#endif
1374 listener->transportableStateChanged(transportable, to, info);
1375 }
1376}
1377
1378
1379bool
1380MSNet::registerCollision(const SUMOTrafficObject* collider, const SUMOTrafficObject* victim, const std::string& collisionType, const MSLane* lane, double pos) {
1381 auto it = myCollisions.find(collider->getID());
1382 if (it != myCollisions.end()) {
1383 for (Collision& old : it->second) {
1384 if (old.victim == victim->getID()) {
1385 // collision from previous step continues
1387 return false;
1388 }
1389 }
1390 } else {
1391 // maybe the roles have been reversed
1392 auto it2 = myCollisions.find(victim->getID());
1393 if (it2 != myCollisions.end()) {
1394 for (Collision& old : it2->second) {
1395 if (old.victim == collider->getID()) {
1396 // collision from previous step continues (keep the old roles)
1398 return false;
1399 }
1400 }
1401 }
1402 }
1403 Collision c;
1404 c.victim = victim->getID();
1405 c.colliderType = collider->getVehicleType().getID();
1406 c.victimType = victim->getVehicleType().getID();
1407 c.colliderSpeed = collider->getSpeed();
1408 c.victimSpeed = victim->getSpeed();
1409 c.colliderFront = collider->getPosition();
1410 c.victimFront = victim->getPosition();
1411 c.colliderBack = collider->getPosition(-collider->getVehicleType().getLength());
1412 c.victimBack = victim->getPosition(-victim->getVehicleType().getLength());
1413 c.type = collisionType;
1414 c.lane = lane;
1415 c.pos = pos;
1416 c.time = myStep;
1418 myCollisions[collider->getID()].push_back(c);
1419 return true;
1420}
1421
1422
1423void
1425 for (auto it = myCollisions.begin(); it != myCollisions.end();) {
1426 for (auto it2 = it->second.begin(); it2 != it->second.end();) {
1427 if (it2->continuationTime != myStep) {
1428 it2 = it->second.erase(it2);
1429 } else {
1430 it2++;
1431 }
1432 }
1433 if (it->second.size() == 0) {
1434 it = myCollisions.erase(it);
1435 } else {
1436 it++;
1437 }
1438 }
1439}
1440
1441
1442bool
1444 return myStoppingPlaces[category == SUMO_TAG_TRAIN_STOP ? SUMO_TAG_BUS_STOP : category].add(stop->getID(), stop);
1445}
1446
1447
1448bool
1450 if (find(myTractionSubstations.begin(), myTractionSubstations.end(), substation) == myTractionSubstations.end()) {
1451 myTractionSubstations.push_back(substation);
1452 return true;
1453 }
1454 return false;
1455}
1456
1457
1459MSNet::getStoppingPlace(const std::string& id, const SumoXMLTag category) const {
1460 if (myStoppingPlaces.count(category) > 0) {
1461 return myStoppingPlaces.find(category)->second.get(id);
1462 }
1463 return nullptr;
1464}
1465
1466
1468MSNet::getStoppingPlace(const std::string& id) const {
1470 MSStoppingPlace* result = getStoppingPlace(id, category);
1471 if (result != nullptr) {
1472 return result;
1473 }
1474 }
1475 return nullptr;
1476}
1477
1478
1479std::string
1480MSNet::getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const {
1481 if (myStoppingPlaces.count(category) > 0) {
1482 for (const auto& it : myStoppingPlaces.find(category)->second) {
1483 MSStoppingPlace* stop = it.second;
1484 if (&stop->getLane() == lane && stop->getBeginLanePosition() - POSITION_EPS <= pos && stop->getEndLanePosition() + POSITION_EPS >= pos) {
1485 return stop->getID();
1486 }
1487 }
1488 }
1489 return "";
1490}
1491
1492
1495 auto it = myStoppingPlaces.find(category);
1496 if (it != myStoppingPlaces.end()) {
1497 return it->second;
1498 } else {
1500 }
1501}
1502
1503
1504void
1507 OutputDevice& output = OutputDevice::getDeviceByOption("chargingstations-output");
1508 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_CHARGING_STATION)->second) {
1509 static_cast<MSChargingStation*>(it.second)->writeChargingStationOutput(output);
1510 }
1511 }
1512}
1513
1514
1515void
1517 if (OptionsCont::getOptions().isSet("railsignal-block-output")) {
1518 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-block-output");
1519 for (auto tls : myLogics->getAllLogics()) {
1520 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1521 if (rs != nullptr) {
1522 rs->writeBlocks(output, false);
1523 }
1524 }
1525 MSDriveWay::writeDepatureBlocks(output, false);
1526 }
1527 if (OptionsCont::getOptions().isSet("railsignal-vehicle-output")) {
1528 OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-vehicle-output");
1529 for (auto tls : myLogics->getAllLogics()) {
1530 MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1531 if (rs != nullptr) {
1532 rs->writeBlocks(output, true);
1533 }
1534 }
1535 MSDriveWay::writeDepatureBlocks(output, true);
1536 }
1537}
1538
1539
1540void
1543 OutputDevice& output = OutputDevice::getDeviceByOption("overheadwiresegments-output");
1544 for (const auto& it : myStoppingPlaces.find(SUMO_TAG_OVERHEAD_WIRE_SEGMENT)->second) {
1545 static_cast<MSOverheadWire*>(it.second)->writeOverheadWireSegmentOutput(output);
1546 }
1547 }
1548}
1549
1550
1551void
1553 if (myTractionSubstations.size() > 0) {
1554 OutputDevice& output = OutputDevice::getDeviceByOption("substations-output");
1555 output.setPrecision(OptionsCont::getOptions().getInt("substations-output.precision"));
1556 for (auto& it : myTractionSubstations) {
1557 it->writeTractionSubstationOutput(output);
1558 }
1559 }
1560}
1561
1562
1564MSNet::findTractionSubstation(const std::string& substationId) {
1565 for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1566 if ((*it)->getID() == substationId) {
1567 return *it;
1568 }
1569 }
1570 return nullptr;
1571}
1572
1573
1574bool
1575MSNet::existTractionSubstation(const std::string& substationId) {
1576 for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1577 if ((*it)->getID() == substationId) {
1578 return true;
1579 }
1580 }
1581 return false;
1582}
1583
1584
1586MSNet::getRouterTT(int rngIndex, const Prohibitions& prohibited) const {
1587 if (MSGlobals::gNumSimThreads == 1) {
1588 rngIndex = 0;
1589 }
1590 if (myRouterTT.count(rngIndex) == 0) {
1591 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1592 if (routingAlgorithm == "dijkstra") {
1593 myRouterTT[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, false, nullptr, true);
1594 } else {
1595 if (routingAlgorithm != "astar") {
1596 WRITE_WARNINGF(TL("TraCI and Triggers cannot use routing algorithm '%'. using 'astar' instead."), routingAlgorithm);
1597 }
1599 }
1600 }
1601 myRouterTT[rngIndex]->prohibit(prohibited);
1602 return *myRouterTT[rngIndex];
1603}
1604
1605
1607MSNet::getRouterEffort(int rngIndex, const Prohibitions& prohibited) const {
1608 if (MSGlobals::gNumSimThreads == 1) {
1609 rngIndex = 0;
1610 }
1611 if (myRouterEffort.count(rngIndex) == 0) {
1613 }
1614 myRouterEffort[rngIndex]->prohibit(prohibited);
1615 return *myRouterEffort[rngIndex];
1616}
1617
1618
1620MSNet::getPedestrianRouter(int rngIndex, const Prohibitions& prohibited) const {
1621 if (MSGlobals::gNumSimThreads == 1) {
1622 rngIndex = 0;
1623 }
1624 if (myPedestrianRouter.count(rngIndex) == 0) {
1625 myPedestrianRouter[rngIndex] = new MSPedestrianRouter();
1626 }
1627 myPedestrianRouter[rngIndex]->prohibit(prohibited);
1628 return *myPedestrianRouter[rngIndex];
1629}
1630
1631
1633MSNet::getIntermodalRouter(int rngIndex, const int routingMode, const Prohibitions& prohibited) const {
1634 if (MSGlobals::gNumSimThreads == 1) {
1635 rngIndex = 0;
1636 }
1638 const int key = rngIndex * oc.getInt("thread-rngs") + routingMode;
1639 if (myIntermodalRouter.count(key) == 0) {
1640 const int carWalk = SUMOVehicleParserHelper::parseCarWalkTransfer(oc, MSDevice_Taxi::hasFleet() || myInserter->hasTaxiFlow());
1641 const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1642 const double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1643 if (routingMode == libsumo::ROUTING_MODE_COMBINED) {
1644 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode, new FareModul());
1645 } else {
1646 myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode);
1647 }
1648 }
1649 myIntermodalRouter[key]->prohibit(prohibited);
1650 return *myIntermodalRouter[key];
1651}
1652
1653
1654void
1656 double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1657 // add access to all parking areas
1658 EffortCalculator* const external = router.getExternalEffort();
1659 for (const auto& stopType : myInstance->myStoppingPlaces) {
1660 // add access to all stopping places
1661 const SumoXMLTag element = stopType.first;
1662 for (const auto& i : stopType.second) {
1663 const MSEdge* const edge = &i.second->getLane().getEdge();
1664 router.getNetwork()->addAccess(i.first, edge, i.second->getBeginLanePosition(), i.second->getEndLanePosition(),
1665 0., element, false, taxiWait);
1666 if (element == SUMO_TAG_BUS_STOP) {
1667 // add access to all public transport stops
1668 for (const auto& a : i.second->getAllAccessPos()) {
1669 router.getNetwork()->addAccess(i.first, &a.lane->getEdge(), a.startPos, a.endPos, a.length, element, true, taxiWait);
1670 }
1671 if (external != nullptr) {
1672 external->addStop(router.getNetwork()->getStopEdge(i.first)->getNumericalID(), *i.second);
1673 }
1674 }
1675 }
1676 }
1677 myInstance->getInsertionControl().adaptIntermodalRouter(router);
1678 myInstance->getVehicleControl().adaptIntermodalRouter(router);
1679 // add access to transfer from walking to taxi-use
1681 for (MSEdge* edge : myInstance->getEdgeControl().getEdges()) {
1682 if ((edge->getPermissions() & SVC_PEDESTRIAN) != 0 && (edge->getPermissions() & SVC_TAXI) != 0) {
1683 router.getNetwork()->addCarAccess(edge, SVC_TAXI, taxiWait);
1684 }
1685 }
1686 }
1687}
1688
1689
1690bool
1692 const MSEdgeVector& edges = myEdges->getEdges();
1693 for (MSEdgeVector::const_iterator e = edges.begin(); e != edges.end(); ++e) {
1694 for (std::vector<MSLane*>::const_iterator i = (*e)->getLanes().begin(); i != (*e)->getLanes().end(); ++i) {
1695 if ((*i)->getShape().hasElevation()) {
1696 return true;
1697 }
1698 }
1699 }
1700 return false;
1701}
1702
1703
1704bool
1706 for (const MSEdge* e : myEdges->getEdges()) {
1707 if (e->getFunction() == SumoXMLEdgeFunc::WALKINGAREA) {
1708 return true;
1709 }
1710 }
1711 return false;
1712}
1713
1714
1715bool
1717 for (const MSEdge* e : myEdges->getEdges()) {
1718 if (e->getBidiEdge() != nullptr) {
1719 return true;
1720 }
1721 }
1722 return false;
1723}
1724
1725bool
1726MSNet::warnOnce(const std::string& typeAndID) {
1727 if (myWarnedOnce.find(typeAndID) == myWarnedOnce.end()) {
1728 myWarnedOnce[typeAndID] = true;
1729 return true;
1730 }
1731 return false;
1732}
1733
1734
1737 auto loader = myRouteLoaders->getFirstLoader();
1738 if (loader != nullptr) {
1739 return dynamic_cast<MSMapMatcher*>(loader->getRouteHandler());
1740 } else {
1741 return nullptr;
1742 }
1743}
1744
1745void
1748 clearState(string2time(oc.getString("begin")), true);
1750 // load traffic from additional files
1751 for (std::string file : oc.getStringVector("additional-files")) {
1752 // ignore failure on parsing calibrator flow
1753 MSRouteHandler rh(file, true);
1754 const long before = PROGRESS_BEGIN_TIME_MESSAGE("Loading traffic from '" + file + "'");
1755 if (!XMLSubSys::runParser(rh, file, false)) {
1756 throw ProcessError(TLF("Loading of % failed.", file));
1757 }
1758 PROGRESS_TIME_MESSAGE(before);
1759 }
1760 delete myRouteLoaders;
1762 updateGUI();
1763}
1764
1765
1767MSNet::loadState(const std::string& fileName, const bool catchExceptions) {
1768 // load time only
1769 const SUMOTime newTime = MSStateHandler::MSStateTimeHandler::getTime(fileName);
1770 // clean up state
1771 clearState(newTime);
1772 // load state
1773 MSStateHandler h(fileName, 0);
1774 XMLSubSys::runParser(h, fileName, false, false, false, catchExceptions);
1775 if (MsgHandler::getErrorInstance()->wasInformed()) {
1776 throw ProcessError(TLF("Loading state from '%' failed.", fileName));
1777 }
1778 // reset route loaders
1779 delete myRouteLoaders;
1781 // prevent loading errors on rewound route file
1783
1784 updateGUI();
1785 return newTime;
1786}
1787
1788
1789/****************************************************************************/
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
SUMOAbstractRouter< MSEdge, SUMOVehicle > MSVehicleRouter
MapMatcher< MSEdge, MSLane, MSJunction > MSMapMatcher
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
const std::string invalid_return< std::string >::value
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_VEHICLE
description of a vehicle
@ SUMO_TAG_PARKING_AREA
A parking area.
@ SUMO_TAG_TRAIN_STOP
A train stop (alias for bus stop).
@ SUMO_TAG_OVERHEAD_WIRE_SEGMENT
An overhead wire segment.
@ SUMO_TAG_PERSON
@ SUMO_ATTR_MAXIMUMBATTERYCAPACITY
Maxium battery capacity.
@ SUMO_ATTR_VEHICLE
@ SUMO_ATTR_RECUPERATIONENABLE
@ SUMO_ATTR_ID
bool gRoutingPreferences
Definition StdDefs.cpp:37
int gPrecision
the precision for floating point outputs
Definition StdDefs.cpp:27
std::pair< int, double > MMVersion
(M)ajor/(M)inor version for written networks and default version for loading
Definition StdDefs.h:71
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=gPrecision)
Definition ToString.h:289
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:46
Computes the shortest path through a network using the A* algorithm.
Definition AStarRouter.h:76
Computes the shortest path through a network using the Dijkstra algorithm.
the effort calculator interface
virtual void addStop(const int stopEdge, const Parameterised &params)=0
int getNumericalID() const
void addCarAccess(const E *edge, SUMOVehicleClass svc, double traveltime)
Adds access edges for transfering from walking to vehicle use.
void addAccess(const std::string &stopId, const E *stopEdge, const double startPos, const double endPos, const double length, const SumoXMLTag category, bool isAccess, double taxiWait)
Adds access edges for stopping places to the intermodal network.
_IntermodalEdge * getStopEdge(const std::string &stopId) const
Returns the associated stop edge.
EffortCalculator * getExternalEffort() const
Network * getNetwork() const
int getCarWalkTransfer() const
The main mesocopic simulation loop.
Definition MELoop.h:47
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.
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.
A road/street connecting two junctions.
Definition MSEdge.h:77
static const MSEdgeVector & getAllEdges()
Returns all edges with a numerical id.
Definition MSEdge.cpp:1096
static void clear()
Clears the dictionary.
Definition MSEdge.cpp:1102
double getMinimumTravelTime(const SUMOVehicle *const veh) const
returns the minimum travel time for the given vehicle
Definition MSEdge.h:484
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.
static void write(OutputDevice &of, const SUMOTime timestep, const SumoXMLTag tag=SUMO_TAG_NOTHING)
Writes the position and the angle of each vehicle into the given device.
static void write(OutputDevice &of, SUMOTime timestep)
Dumping a hugh List of Parameters available in the Simulation.
static bool gUseMesoSim
Definition MSGlobals.h:106
static double gWeightsSeparateTurns
Whether turning specific weights are estimated (and how much).
Definition MSGlobals.h:177
static bool gOverheadWireRecuperation
Definition MSGlobals.h:124
static MELoop * gMesoNet
mesoscopic simulation infrastructure
Definition MSGlobals.h:112
static bool gStateLoaded
Information whether a state has been loaded.
Definition MSGlobals.h:103
static bool gCheck4Accidents
Definition MSGlobals.h:88
static bool gClearState
whether the simulation is in the process of clearing state (MSNet::clearState)
Definition MSGlobals.h:143
static bool gHaveEmissions
Whether emission output of some type is needed (files or GUI).
Definition MSGlobals.h:183
static int gNumSimThreads
how many threads to use for simulation
Definition MSGlobals.h:146
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition MSGlobals.h:81
static int gNumThreads
how many threads to use
Definition MSGlobals.h:149
Inserts vehicles into the network when their departure time is reached.
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:2512
static const std::map< std::string, MSLaneSpeedTrigger * > & getInstances()
return all MSLaneSpeedTrigger instances
Interface for objects listening to transportable state changes.
Definition MSNet.h:714
Interface for objects listening to vehicle state changes.
Definition MSNet.h:655
The simulated network and simulation perfomer.
Definition MSNet.h:89
std::map< SumoXMLTag, NamedObjectCont< MSStoppingPlace * > > myStoppingPlaces
Dictionary of bus / container stops.
Definition MSNet.h:1008
long myTraCIMillis
The overall time spent waiting for traci operations including.
Definition MSNet.h:943
MSMapMatcher * getMapMatcher() const
Definition MSNet.cpp:1736
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:1726
SUMOTime loadState(const std::string &fileName, const bool catchExceptions)
load state from file and return new time
Definition MSNet.cpp:1767
bool myLogExecutionTime
Information whether the simulation duration shall be logged.
Definition MSNet.h:929
MSTransportableControl * myPersonControl
Controls person building and deletion;.
Definition MSNet.h:898
void removeVehicleStateListener(VehicleStateListener *listener)
Removes a vehicle states listener.
Definition MSNet.cpp:1332
SUMORouteLoaderControl * myRouteLoaders
Route loader for dynamic loading of routes.
Definition MSNet.h:876
std::map< std::string, std::map< std::string, double > > myVTypePreferences
Definition MSNet.h:978
bool addStoppingPlace(const SumoXMLTag category, MSStoppingPlace *stop)
Adds a stopping place.
Definition MSNet.cpp:1443
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:1369
SUMOTime myStateDumpPeriod
The period for writing state.
Definition MSNet.h:962
static const NamedObjectCont< MSStoppingPlace * > myEmptyStoppingPlaceCont
Definition MSNet.h:1029
void writeOverheadWireSegmentOutput() const
write the output generated by an overhead wire segment
Definition MSNet.cpp:1541
void writeChargingStationOutput() const
write charging station output
Definition MSNet.cpp:1505
std::pair< bool, NamedRTree > myLanesRTree
An RTree structure holding lane IDs.
Definition MSNet.h:1045
bool checkBidiEdges()
check wether bidirectional edges occur in the network
Definition MSNet.cpp:1716
VehicleState
Definition of a vehicle state.
Definition MSNet.h:622
int myLogStepPeriod
Period between successive step-log outputs.
Definition MSNet.h:934
SUMOTime myStep
Current time step.
Definition MSNet.h:879
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:996
void addPreference(const std::string &routingType, SUMOVehicleClass svc, double prio)
add edge type specific routing preference
Definition MSNet.cpp:394
MSEventControl * myBeginOfTimestepEvents
Controls events executed at the begin of a time step;.
Definition MSNet.h:912
bool addTractionSubstation(MSTractionSubstation *substation)
Adds a traction substation.
Definition MSNet.cpp:1449
std::map< std::string, bool > myWarnedOnce
container to record warnings that shall only be issued once
Definition MSNet.h:1032
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:1424
MSJunctionControl * myJunctions
Controls junctions, realizes right-of-way rules;.
Definition MSNet.h:904
std::vector< std::string > myPeriodicStateFiles
The names of the last K periodic state files (only only K shall be kept).
Definition MSNet.h:960
ShapeContainer * myShapeContainer
A container for geometrical shapes;.
Definition MSNet.h:918
std::string myStateDumpSuffix
Definition MSNet.h:965
bool checkElevation()
check all lanes for elevation data
Definition MSNet.cpp:1691
bool myHavePermissions
Whether the network contains edges which not all vehicles may pass.
Definition MSNet.h:971
MSTransportableRouter & getIntermodalRouter(int rngIndex, const int routingMode=0, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1633
bool existTractionSubstation(const std::string &substationId)
return whether given electrical substation exists in the network
Definition MSNet.cpp:1575
void removeTransportableStateListener(TransportableStateListener *listener)
Removes a transportable states listener.
Definition MSNet.cpp:1360
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:976
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:258
bool myLogStepNumber
Information whether the number of the simulation step shall be logged.
Definition MSNet.h:932
MMVersion myVersion
the network version
Definition MSNet.h:1002
MSEventControl * myInsertionEvents
Controls insertion events;.
Definition MSNet.h:916
virtual MSTransportableControl & getContainerControl()
Returns the container control.
Definition MSNet.cpp:1265
MSVehicleRouter & getRouterTT(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1586
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:1041
static const std::string STAGE_MOVEMENTS
Definition MSNet.h:849
bool hasFlow(const std::string &id) const
return whether the given flow is known
Definition MSNet.cpp:434
int myMaxTeleports
Maximum number of teleports.
Definition MSNet.h:885
long mySimStepDuration
Definition MSNet.h:937
double getPreference(const std::string &routingType, const SUMOVTypeParameter &pars) const
retriefe edge type specific routing preference
Definition MSNet.cpp:364
MSEventControl * myEndOfTimestepEvents
Controls events executed at the end of a time step;.
Definition MSNet.h:914
static std::string getStateMessage(SimulationState state)
Returns the message to show if a certain state occurs.
Definition MSNet.cpp:997
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:1480
bool myHasInternalLinks
Whether the network contains internal links/lanes/edges.
Definition MSNet.h:984
void writeSubstationOutput() const
write electrical substation output
Definition MSNet.cpp:1552
static const std::string STAGE_INSERTIONS
Definition MSNet.h:851
std::map< SUMOVehicleClass, std::map< std::string, double > > myVClassPreferences
Preferences for routing.
Definition MSNet.h:977
long long int myPersonsMoved
Definition MSNet.h:947
void quickReload()
reset state to the beginning without reloading the network
Definition MSNet.cpp:1746
MSPedestrianRouter & getPedestrianRouter(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1620
MSVehicleControl * myVehicleControl
Controls vehicle building and deletion;.
Definition MSNet.h:896
static void clearAll()
Clears all dictionaries.
Definition MSNet.cpp:1022
static void cleanupStatic()
Place for static initializations of simulation components (called after successful net build).
Definition MSNet.cpp:200
void writeStatistics(const SUMOTime start, const long now) const
write statistic output to (xml) file
Definition MSNet.cpp:618
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:334
MSEdgeControl * myEdges
Controls edges, performs vehicle movement;.
Definition MSNet.h:902
std::unique_ptr< MSDynamicShapeUpdater > myDynamicShapeUpdater
Updater for dynamic shapes that are tracking traffic objects (ensures removal of shape dynamics when ...
Definition MSNet.h:1050
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:354
void closeSimulation(SUMOTime start, const std::string &reason="")
Closes the simulation (all files, connections, etc.).
Definition MSNet.cpp:736
MSStoppingPlace * getStoppingPlace(const std::string &id, const SumoXMLTag category) const
Returns the named stopping place of the given category.
Definition MSNet.cpp:1459
bool myHasElevation
Whether the network contains elevation data.
Definition MSNet.h:990
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:900
std::vector< TransportableStateListener * > myTransportableStateListeners
Container for transportable state listener.
Definition MSNet.h:1017
void writeOutput()
Write netstate, summary and detector output.
Definition MSNet.cpp:1107
virtual void updateGUI() const
update view after simulation.loadState
Definition MSNet.h:610
bool myAmInterrupted
whether an interrupt occurred
Definition MSNet.h:888
void simulationStep(const bool onlyMove=false)
Performs a single simulation step.
Definition MSNet.cpp:777
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1324
void clearState(const SUMOTime step, bool quickReload=false)
Resets events when quick-loading state.
Definition MSNet.cpp:1053
void preSimStepOutput() const
Prints the current step number.
Definition MSNet.cpp:1288
void writeCollisions() const
write collision output to (xml) file
Definition MSNet.cpp:589
std::vector< SUMOTime > myStateDumpTimes
Times at which a state shall be written.
Definition MSNet.h:956
void writeSummaryOutput(bool finalStep=false)
write summary-output to (xml) file
Definition MSNet.cpp:668
void addTransportableStateListener(TransportableStateListener *listener)
Adds a transportable states listener.
Definition MSNet.cpp:1352
std::vector< MSTractionSubstation * > myTractionSubstations
Dictionary of traction substations.
Definition MSNet.h:1011
SUMOTime myEdgeDataEndTime
end of loaded edgeData
Definition MSNet.h:1005
MSEdgeWeightsStorage & getWeightsStorage()
Returns the net's internal edge travel times/efforts container.
Definition MSNet.cpp:1279
std::map< std::string, std::map< SUMOVehicleClass, double > > myRestrictions
The vehicle class specific speed restrictions.
Definition MSNet.h:974
std::vector< std::string > myStateDumpFiles
The names for the state files.
Definition MSNet.h:958
void addMesoType(const std::string &typeID, const MESegment::MesoEdgeType &edgeType)
Adds edge type specific meso parameters.
Definition MSNet.cpp:407
void writeRailSignalBlocks() const
write rail signal block output
Definition MSNet.cpp:1516
MSTLLogicControl * myLogics
Controls tls logics, realizes waiting on tls rules;.
Definition MSNet.h:906
bool logSimulationDuration() const
Returns whether duration shall be logged.
Definition MSNet.cpp:1250
long long int myVehiclesMoved
The overall number of vehicle movements.
Definition MSNet.h:946
static const std::string STAGE_REMOTECONTROL
Definition MSNet.h:852
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:1341
std::map< int, MSTransportableRouter * > myIntermodalRouter
Definition MSNet.h:1042
std::vector< VehicleStateListener * > myVehicleStateListeners
Container for vehicle state listener.
Definition MSNet.h:1014
SimulationState simulationState(SUMOTime stopTime) const
This method returns the current simulation state. It should not modify status.
Definition MSNet.cpp:946
long myTraCIStepDuration
The last simulation step duration.
Definition MSNet.h:937
TransportableState
Definition of a transportable state.
Definition MSNet.h:699
MSDetectorControl * myDetectorControl
Controls detectors;.
Definition MSNet.h:910
bool myStepCompletionMissing
whether libsumo triggered a partial step (executeMove)
Definition MSNet.h:882
static const std::string STAGE_LANECHANGE
Definition MSNet.h:850
MSNet(MSVehicleControl *vc, MSEventControl *beginOfTimestepEvents, MSEventControl *endOfTimestepEvents, MSEventControl *insertionEvents, ShapeContainer *shapeCont=0)
Constructor.
Definition MSNet.cpp:207
void addRestriction(const std::string &id, const SUMOVehicleClass svc, const double speed)
Adds a restriction for an edge type.
Definition MSNet.cpp:348
std::map< std::string, MESegment::MesoEdgeType > myMesoEdgeTypes
The edge type specific meso parameters.
Definition MSNet.h:981
MSEdgeWeightsStorage * myEdgeWeights
The net's knowledge about edge efforts/travel times;.
Definition MSNet.h:920
MSDynamicShapeUpdater * makeDynamicShapeUpdater()
Creates and returns a dynamic shapes updater.
Definition MSNet.cpp:1273
virtual ~MSNet()
Destructor.
Definition MSNet.cpp:293
std::map< int, MSVehicleRouter * > myRouterEffort
Definition MSNet.h:1040
MSTractionSubstation * findTractionSubstation(const std::string &substationId)
find electrical substation by its id
Definition MSNet.cpp:1564
static MSNet * myInstance
Unique instance of MSNet.
Definition MSNet.h:873
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition MSNet.h:392
MSInsertionControl * myInserter
Controls vehicle insertion;.
Definition MSNet.h:908
void postSimStepOutput() const
Prints the statistics of the step at its end.
Definition MSNet.cpp:1294
virtual MSTransportableControl & getPersonControl()
Returns the person control.
Definition MSNet.cpp:1256
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:1380
static const std::string STAGE_EVENTS
string constants for simstep stages
Definition MSNet.h:848
void loadRoutes()
loads routes for the next few steps
Definition MSNet.cpp:483
std::string myStateDumpPrefix
name components for periodic state
Definition MSNet.h:964
bool myJunctionHigherSpeeds
Whether the network was built with higher speed on junctions.
Definition MSNet.h:987
long mySimBeginMillis
The overall simulation duration.
Definition MSNet.h:940
bool myHasPedestrianNetwork
Whether the network contains pedestrian network elements.
Definition MSNet.h:993
std::map< int, MSVehicleRouter * > myRouterTT
Definition MSNet.h:1039
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:412
void postMoveStep()
Performs the parts of the simulation step which happen after the move.
Definition MSNet.cpp:917
bool hasInternalLinks() const
return whether the network contains internal links
Definition MSNet.h:794
const std::string generateStatistics(const SUMOTime start, const long now)
Writes performance output and running vehicle stats.
Definition MSNet.cpp:489
bool checkWalkingarea()
check all lanes for type walkingArea
Definition MSNet.cpp:1705
static void adaptIntermodalRouter(MSTransportableRouter &router)
Definition MSNet.cpp:1655
CollisionMap myCollisions
collisions in the current time step
Definition MSNet.h:1020
MSVehicleRouter & getRouterEffort(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1607
const NamedObjectCont< MSStoppingPlace * > & getStoppingPlaces(SumoXMLTag category) const
Definition MSNet.cpp:1494
SimulationState simulate(SUMOTime start, SUMOTime stop)
Simulates from timestep start to stop.
Definition MSNet.cpp:441
Definition of overhead wire segment.
static void write(OutputDevice &of, SUMOTime timestep)
Export the queueing length in front of a junction (very experimental!).
static void cleanup()
clean up state
static MSRailSignalControl & getInstance()
void updateSignals(SUMOTime t)
update active rail signals
static void clearState()
Perform resets events when quick-loading state.
void resetWaitRelations()
reset all waiting-for relationships at the start of the simulation step
A signal for rails.
void writeBlocks(OutputDevice &od, bool writeVehicles) const
write rail signal block output for all links and driveways
Parser and container for routes during their loading.
static void dict_clearState()
Decrement all route references before quick-loading state.
Definition MSRoute.cpp:308
static void clear()
Clears the dictionary (delete all known routes, too).
Definition MSRoute.cpp:181
static double getEffortExtra(const MSEdge *const e, const SUMOVehicle *const v, double t)
static SUMOTime getTime(const std::string &fileName)
parse time from state file
Parser and output filter for routes and vehicles state saving and loading.
static void saveState(const std::string &file, SUMOTime step, bool usePrefix=true)
Saves the current state.
static bool active()
Definition MSStopOut.h:54
static void cleanup()
Definition MSStopOut.cpp:50
void generateOutputForUnfinished()
generate output for vehicles which are still stopped at simulation end
static MSStopOut * getInstance()
Definition MSStopOut.h:60
A lane area vehicles can halt at.
double getBeginLanePosition() const
Returns the begin position of this stop.
const MSLane & getLane() const
Returns the lane this stop is located at.
A class that stores and controls tls and switching of their programs.
Traction substation powering one or more overhead wire sections.
int getWaitingForVehicleNumber() const
Returns the number of transportables waiting for a ride.
int getEndedNumber() const
Returns the number of transportables that exited the simulation.
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 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.
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.
std::map< std::string, SUMOVehicle * >::const_iterator constVehIt
Definition of the internal vehicles map iterator.
constVehIt loadedVehBegin() const
Returns the begin of the internal vehicle map.
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.
Representation of a vehicle, person, or container.
virtual const MSVehicleType & getVehicleType() const =0
Returns the object's "vehicle" type.
virtual MSDevice * getDevice(const std::type_info &type) const =0
Returns a device of the given type if it exists or nullptr if not.
virtual double getSpeed() const =0
Returns the object's current speed.
virtual Position getPosition(const double offset=0) const =0
Return current position (x/y, cartesian).
Structure representing possible vehicle parameter.
SUMOVehicleClass vehicleClass
The vehicle's class.
std::string id
The vehicle type's id.
Representation of a vehicle.
Definition SUMOVehicle.h: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)
A scoped lock which only triggers on condition.
Storage for geometrical objects.
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