Line data Source code
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 : /****************************************************************************/
14 : /// @file MSNet.cpp
15 : /// @author Christian Roessel
16 : /// @author Daniel Krajzewicz
17 : /// @author Jakob Erdmann
18 : /// @author Clemens Honomichl
19 : /// @author Eric Nicolay
20 : /// @author Mario Krumnow
21 : /// @author Michael Behrisch
22 : /// @author Christoph Sommer
23 : /// @date Tue, 06 Mar 2001
24 : ///
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
43 : #include <utils/common/ScopedLocker.h>
44 : #endif
45 : #include <utils/common/MsgHandler.h>
46 : #include <utils/common/ToString.h>
47 : #include <utils/common/SysUtils.h>
48 : #include <utils/common/UtilExceptions.h>
49 : #include <utils/common/WrappingCommand.h>
50 : #include <utils/common/SystemFrame.h>
51 : #include <utils/geom/GeoConvHelper.h>
52 : #include <utils/iodevices/OutputDevice_File.h>
53 : #include <utils/iodevices/OutputDevice.h>
54 : #include <utils/options/OptionsCont.h>
55 : #include <utils/options/OptionsIO.h>
56 : #include <utils/shapes/ShapeContainer.h>
57 : #include <utils/router/DijkstraRouter.h>
58 : #include <utils/router/AStarRouter.h>
59 : #include <utils/router/IntermodalRouter.h>
60 : #include <utils/router/PedestrianRouter.h>
61 : #include <utils/vehicle/SUMORouteLoaderControl.h>
62 : #include <utils/vehicle/SUMORouteLoader.h>
63 : #include <utils/vehicle/SUMOVehicleParserHelper.h>
64 : #include <utils/xml/XMLSubSys.h>
65 : #include <traci-server/TraCIServer.h>
66 : #include <libsumo/Helper.h>
67 : #include <libsumo/Simulation.h>
68 : #include <mesosim/MELoop.h>
69 : #include <mesosim/MESegment.h>
70 : #include <microsim/output/MSDetectorControl.h>
71 : #include <microsim/MSVehicleTransfer.h>
72 : #include <microsim/devices/MSRoutingEngine.h>
73 : #include <microsim/devices/MSDevice_Vehroutes.h>
74 : #include <microsim/devices/MSDevice_Tripinfo.h>
75 : #include <microsim/devices/MSDevice_BTsender.h>
76 : #include <microsim/devices/MSDevice_SSM.h>
77 : #include <microsim/devices/MSDevice_ElecHybrid.h>
78 : #include <microsim/devices/MSDevice_ToC.h>
79 : #include <microsim/devices/MSDevice_Taxi.h>
80 : #include <microsim/output/MSBatteryExport.h>
81 : #include <microsim/output/MSChargingStationExport.h>
82 : #include <microsim/output/MSElecHybridExport.h>
83 : #include <microsim/output/MSEmissionExport.h>
84 : #include <microsim/output/MSFCDExport.h>
85 : #include <microsim/output/MSFullExport.h>
86 : #include <microsim/output/MSQueueExport.h>
87 : #include <microsim/output/MSVTKExport.h>
88 : #include <microsim/output/MSXMLRawOut.h>
89 : #include <microsim/output/MSAmitranTrajectories.h>
90 : #include <microsim/output/MSStopOut.h>
91 : #include <microsim/transportables/MSPModel.h>
92 : #include <microsim/transportables/MSPerson.h>
93 : #include <microsim/traffic_lights/MSTrafficLightLogic.h>
94 : #include <microsim/transportables/MSTransportableControl.h>
95 : #include <microsim/traffic_lights/MSRailSignal.h>
96 : #include <microsim/traffic_lights/MSRailSignalConstraint.h>
97 : #include <microsim/traffic_lights/MSRailSignalControl.h>
98 : #include <microsim/traffic_lights/MSTLLogicControl.h>
99 : #include <microsim/traffic_lights/MSDriveWay.h>
100 : #include <microsim/trigger/MSCalibrator.h>
101 : #include <microsim/trigger/MSChargingStation.h>
102 : #include <microsim/trigger/MSLaneSpeedTrigger.h>
103 : #include <microsim/trigger/MSOverheadWire.h>
104 : #include <microsim/trigger/MSTriggeredRerouter.h>
105 : #include <utils/router/FareModul.h>
106 : #include <netload/NLBuilder.h>
107 :
108 : #include "MSEdgeControl.h"
109 : #include "MSJunctionControl.h"
110 : #include "MSInsertionControl.h"
111 : #include "MSDynamicShapeUpdater.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 : // ===========================================================================
138 : MSNet* MSNet::myInstance = nullptr;
139 :
140 : const std::string MSNet::STAGE_EVENTS("events");
141 : const std::string MSNet::STAGE_MOVEMENTS("move");
142 : const std::string MSNet::STAGE_LANECHANGE("laneChange");
143 : const std::string MSNet::STAGE_INSERTIONS("insertion");
144 : const std::string MSNet::STAGE_REMOTECONTROL("remoteControl");
145 :
146 : const NamedObjectCont<MSStoppingPlace*> MSNet::myEmptyStoppingPlaceCont;
147 : const std::vector<MSStoppingPlace*> MSNet::myEmptyStoppingPlaceVector;
148 :
149 : // ===========================================================================
150 : // static member method definitions
151 : // ===========================================================================
152 : double
153 336 : MSNet::getEffort(const MSEdge* const e, const SUMOVehicle* const v, double t) {
154 : double value;
155 336 : const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
156 336 : if (veh != nullptr && veh->getWeightsStorage().retrieveExistingEffort(e, t, value)) {
157 2 : return value;
158 : }
159 334 : if (getInstance()->getWeightsStorage().retrieveExistingEffort(e, t, value)) {
160 2 : return value;
161 : }
162 : return 0;
163 : }
164 :
165 :
166 : double
167 7023315 : MSNet::getTravelTime(const MSEdge* const e, const SUMOVehicle* const v, double t) {
168 : double value;
169 7023315 : const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
170 7022392 : if (veh != nullptr && veh->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
171 522 : return value;
172 : }
173 7022793 : if (getInstance()->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
174 177 : return value;
175 : }
176 7022616 : if (veh != nullptr) {
177 6836364 : if ((veh->getRoutingMode() & libsumo::ROUTING_MODE_AGGREGATED_CUSTOM) != 0) {
178 3508 : return MSRoutingEngine::getEffortExtra(e, v, t);
179 6832856 : } else if ((veh->getRoutingMode() & libsumo::ROUTING_MODE_AGGREGATED) != 0) {
180 567 : if (MSRoutingEngine::hasBikeSpeeds() && v->getVClass() == SVC_BICYCLE) {
181 0 : return MSRoutingEngine::getEffortBike(e, v, t);
182 : } else {
183 567 : return MSRoutingEngine::getEffort(e, v, t);
184 : }
185 6832289 : } else if (MSRoutingEngine::haveExtras()) {
186 6832289 : double tt = e->getMinimumTravelTime(v);
187 6832289 : MSRoutingEngine::applyExtras(e, v, SIMSTEP, tt);
188 6832289 : return tt;
189 : }
190 : }
191 186252 : return e->getMinimumTravelTime(v);
192 : }
193 :
194 :
195 : // ---------------------------------------------------------------------------
196 : // MSNet - methods
197 : // ---------------------------------------------------------------------------
198 : MSNet*
199 5445613401 : MSNet::getInstance(void) {
200 5445613401 : if (myInstance != nullptr) {
201 5445613356 : return myInstance;
202 : }
203 90 : throw ProcessError(TL("A network was not yet constructed."));
204 : }
205 :
206 : void
207 42780 : MSNet::initStatic() {
208 42780 : gRoutingPreferences = false;
209 42780 : MSDriveWay::init();
210 42780 : }
211 :
212 : void
213 42167 : MSNet::cleanupStatic() {
214 42167 : if (!MSGlobals::gUseMesoSim) {
215 35265 : MSVehicle::Influencer::cleanup();
216 : }
217 42167 : }
218 :
219 :
220 42780 : MSNet::MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents,
221 : MSEventControl* endOfTimestepEvents,
222 : MSEventControl* insertionEvents,
223 42780 : ShapeContainer* shapeCont):
224 42780 : myAmInterrupted(false),
225 42780 : myVehiclesMoved(0),
226 42780 : myPersonsMoved(0),
227 42780 : myHavePermissions(false),
228 42780 : myHasInternalLinks(false),
229 42780 : myJunctionHigherSpeeds(false),
230 42780 : myHasElevation(false),
231 42780 : myHasPedestrianNetwork(false),
232 42780 : myHasBidiEdges(false),
233 42780 : myEdgeDataEndTime(-1),
234 42780 : myDynamicShapeUpdater(nullptr) {
235 42780 : if (myInstance != nullptr) {
236 0 : throw ProcessError(TL("A network was already constructed."));
237 : }
238 42780 : OptionsCont& oc = OptionsCont::getOptions();
239 42780 : myStep = string2time(oc.getString("begin"));
240 42780 : myStateLoaderTime = myStep - 1,
241 42780 : myMaxTeleports = oc.getInt("max-num-teleports");
242 42780 : myLogExecutionTime = !oc.getBool("no-duration-log");
243 42780 : myLogStepNumber = !oc.getBool("no-step-log");
244 42780 : myLogStepPeriod = oc.getInt("step-log.period");
245 171120 : myInserter = new MSInsertionControl(*vc, string2time(oc.getString("max-depart-delay")), oc.getBool("eager-insert"), oc.getInt("max-num-vehicles"),
246 171120 : string2time(oc.getString("random-depart-offset")));
247 42780 : myVehicleControl = vc;
248 42780 : myDetectorControl = new MSDetectorControl();
249 42780 : myEdges = nullptr;
250 42780 : myJunctions = nullptr;
251 42780 : myRouteLoaders = nullptr;
252 42780 : myLogics = nullptr;
253 42780 : myPersonControl = nullptr;
254 42780 : myContainerControl = nullptr;
255 42780 : myEdgeWeights = nullptr;
256 42780 : myShapeContainer = shapeCont == nullptr ? new ShapeContainer() : shapeCont;
257 :
258 42780 : myBeginOfTimestepEvents = beginOfTimestepEvents;
259 42780 : myEndOfTimestepEvents = endOfTimestepEvents;
260 42780 : myInsertionEvents = insertionEvents;
261 42780 : myLanesRTree.first = false;
262 :
263 42780 : if (MSGlobals::gUseMesoSim) {
264 14004 : MSGlobals::gMesoNet = new MELoop(string2time(oc.getString("meso-recheck")));
265 : }
266 42780 : myInstance = this;
267 42780 : initStatic();
268 42780 : }
269 :
270 :
271 : void
272 42298 : MSNet::closeBuilding(const OptionsCont& oc, MSEdgeControl* edges, MSJunctionControl* junctions,
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 42298 : myEdges = edges;
281 42298 : myJunctions = junctions;
282 42298 : myRouteLoaders = routeLoaders;
283 42298 : myLogics = tlc;
284 : // save the time the network state shall be saved at
285 42298 : myStateDumpTimes = stateDumpTimes;
286 42298 : myStateDumpFiles = stateDumpFiles;
287 42298 : myStateDumpPeriod = string2time(oc.getString("save-state.period"));
288 42298 : myStateDumpPrefix = oc.getString("save-state.prefix");
289 42298 : myStateDumpSuffix = oc.getString("save-state.suffix");
290 :
291 : // initialise performance computation
292 42298 : mySimBeginMillis = SysUtils::getCurrentMillis();
293 42298 : myTraCIMillis = 0;
294 42298 : myHasInternalLinks = hasInternalLinks;
295 42298 : myJunctionHigherSpeeds = junctionHigherSpeeds;
296 42298 : myHasElevation = checkElevation();
297 42298 : myHasPedestrianNetwork = checkWalkingarea();
298 42298 : myHasBidiEdges = checkBidiEdges();
299 : myVersion = version;
300 42298 : if ((!MSGlobals::gUsingInternalLanes || !myHasInternalLinks)
301 15025 : && MSGlobals::gWeightsSeparateTurns > 0) {
302 0 : throw ProcessError(TL("Option weights.separate-turns is only supported when simulating with internal lanes"));
303 : }
304 42298 : }
305 :
306 :
307 75440 : MSNet::~MSNet() {
308 42167 : cleanupStatic();
309 : // delete controls
310 42167 : delete myJunctions;
311 42167 : delete myDetectorControl;
312 : // delete mean data
313 42167 : delete myEdges;
314 42167 : delete myInserter;
315 42167 : myInserter = nullptr;
316 42167 : delete myLogics;
317 42167 : delete myRouteLoaders;
318 42167 : if (myPersonControl != nullptr) {
319 8222 : delete myPersonControl;
320 8222 : myPersonControl = nullptr; // just to have that clear for later cleanups
321 : }
322 42167 : if (myContainerControl != nullptr) {
323 1950 : delete myContainerControl;
324 1950 : myContainerControl = nullptr; // just to have that clear for later cleanups
325 : }
326 42167 : 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 42167 : delete myShapeContainer;
332 42167 : myShapeContainer = nullptr;
333 : // delete events late so that vehicles can get rid of references first
334 42167 : delete myBeginOfTimestepEvents;
335 42167 : myBeginOfTimestepEvents = nullptr;
336 42167 : delete myEndOfTimestepEvents;
337 42167 : myEndOfTimestepEvents = nullptr;
338 42167 : delete myInsertionEvents;
339 42167 : myInsertionEvents = nullptr;
340 42167 : delete myEdgeWeights;
341 43623 : for (auto& router : myRouterTT) {
342 1456 : delete router.second;
343 : }
344 : myRouterTT.clear();
345 42178 : for (auto& router : myRouterEffort) {
346 11 : delete router.second;
347 : }
348 : myRouterEffort.clear();
349 44979 : for (auto& router : myPedestrianRouter) {
350 2812 : delete router.second;
351 : }
352 : myPedestrianRouter.clear();
353 42167 : resetIntermodalRouter();
354 : myLanesRTree.second.RemoveAll();
355 42184 : for (MSTractionSubstation* sub : myTractionSubstations) {
356 17 : delete sub;
357 : }
358 : myTractionSubstations.clear();
359 42167 : clearAll();
360 42167 : if (MSGlobals::gUseMesoSim) {
361 6902 : delete MSGlobals::gMesoNet;
362 : }
363 42167 : myInstance = nullptr;
364 159774 : }
365 :
366 :
367 : void
368 221 : MSNet::addRestriction(const std::string& id, const SUMOVehicleClass svc, const double speed) {
369 221 : myRestrictions[id][svc] = speed;
370 221 : }
371 :
372 :
373 : const std::map<SUMOVehicleClass, double>*
374 2156841 : MSNet::getRestrictions(const std::string& id) const {
375 : std::map<std::string, std::map<SUMOVehicleClass, double> >::const_iterator i = myRestrictions.find(id);
376 2156841 : if (i == myRestrictions.end()) {
377 : return nullptr;
378 : }
379 1130 : return &i->second;
380 : }
381 :
382 :
383 : double
384 5337 : MSNet::getPreference(const std::string& routingType, const SUMOVTypeParameter& pars) const {
385 5337 : if (gRoutingPreferences) {
386 5337 : auto it = myVTypePreferences.find(pars.id);
387 5337 : if (it != myVTypePreferences.end()) {
388 : auto it2 = it->second.find(routingType);
389 224 : if (it2 != it->second.end()) {
390 56 : return it2->second;
391 : }
392 : }
393 : auto it3 = myVClassPreferences.find(pars.vehicleClass);
394 5281 : if (it3 != myVClassPreferences.end()) {
395 : auto it4 = it3->second.find(routingType);
396 336 : if (it4 != it3->second.end()) {
397 84 : return it4->second;
398 : }
399 : }
400 : // fallback to generel preferences
401 5197 : it = myVTypePreferences.find("");
402 5197 : if (it != myVTypePreferences.end()) {
403 : auto it2 = it->second.find(routingType);
404 4021 : if (it2 != it->second.end()) {
405 1165 : return it2->second;
406 : }
407 : }
408 : }
409 : return 1;
410 : }
411 :
412 :
413 : void
414 28 : MSNet::addPreference(const std::string& routingType, SUMOVehicleClass svc, double prio) {
415 28 : myVClassPreferences[svc][routingType] = prio;
416 28 : gRoutingPreferences = true;
417 28 : }
418 :
419 :
420 : void
421 90 : MSNet::addPreference(const std::string& routingType, std::string vType, double prio) {
422 90 : myVTypePreferences[vType][routingType] = prio;
423 90 : gRoutingPreferences = true;
424 90 : }
425 :
426 : void
427 24 : MSNet::addMesoType(const std::string& typeID, const MESegment::MesoEdgeType& edgeType) {
428 24 : myMesoEdgeTypes[typeID] = edgeType;
429 24 : }
430 :
431 : const MESegment::MesoEdgeType&
432 924302 : MSNet::getMesoType(const std::string& typeID) {
433 : if (myMesoEdgeTypes.count(typeID) == 0) {
434 : // init defaults
435 7514 : const OptionsCont& oc = OptionsCont::getOptions();
436 : MESegment::MesoEdgeType edgeType;
437 7514 : edgeType.tauff = string2time(oc.getString("meso-tauff"));
438 7514 : edgeType.taufj = string2time(oc.getString("meso-taufj"));
439 7514 : edgeType.taujf = string2time(oc.getString("meso-taujf"));
440 7514 : edgeType.taujj = string2time(oc.getString("meso-taujj"));
441 7514 : edgeType.jamThreshold = oc.getFloat("meso-jam-threshold");
442 7514 : edgeType.junctionControl = oc.getBool("meso-junction-control");
443 7514 : edgeType.tlsPenalty = oc.getFloat("meso-tls-penalty");
444 7514 : edgeType.tlsFlowPenalty = oc.getFloat("meso-tls-flow-penalty");
445 7514 : edgeType.minorPenalty = string2time(oc.getString("meso-minor-penalty"));
446 7514 : edgeType.overtaking = oc.getBool("meso-overtaking");
447 7514 : edgeType.edgeLength = oc.getFloat("meso-edgelength");
448 7514 : myMesoEdgeTypes[typeID] = edgeType;
449 : }
450 924302 : return myMesoEdgeTypes[typeID];
451 : }
452 :
453 :
454 : bool
455 7318067 : MSNet::hasFlow(const std::string& id) const {
456 : // inserter is deleted at the end of the simulation
457 7318067 : return myInserter != nullptr && myInserter->hasFlow(id);
458 : }
459 :
460 :
461 : MSNet::SimulationState
462 31847 : MSNet::simulate(SUMOTime start, SUMOTime stop) {
463 : // report the begin when wished
464 63694 : WRITE_MESSAGEF(TL("Simulation version % started with time: %."), VERSION_STRING, time2string(start));
465 : // the simulation loop
466 : SimulationState state = SIMSTATE_RUNNING;
467 : // state loading may have changed the start time so we need to reinit it
468 31847 : myStep = start;
469 : int numSteps = 0;
470 : bool doStepLog = false;
471 50997773 : while (state == SIMSTATE_RUNNING) {
472 50966325 : doStepLog = myLogStepNumber && (numSteps % myLogStepPeriod == 0);
473 : if (doStepLog) {
474 110 : preSimStepOutput();
475 : }
476 50966325 : simulationStep();
477 50965926 : if (doStepLog) {
478 110 : postSimStepOutput();
479 : }
480 50965926 : 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 50965926 : numSteps++;
487 : }
488 31448 : if (myLogStepNumber && !doStepLog) {
489 : // ensure some output on the last step
490 17 : preSimStepOutput();
491 17 : postSimStepOutput();
492 : }
493 : // exit simulation loop
494 31448 : if (myLogStepNumber) {
495 : // start new line for final verbose output
496 20 : std::cout << "\n";
497 : }
498 31448 : closeSimulation(start, getStateMessage(state));
499 31448 : return state;
500 : }
501 :
502 :
503 : void
504 64242305 : MSNet::loadRoutes() {
505 64242305 : myRouteLoaders->loadNext(myStep);
506 64241720 : }
507 :
508 :
509 : const std::string
510 13248 : MSNet::generateStatistics(const SUMOTime start, const long now) {
511 13248 : std::ostringstream msg;
512 13248 : if (myLogExecutionTime) {
513 12895 : const long duration = now - mySimBeginMillis;
514 : // print performance notice
515 25790 : msg << "Performance:\n" << " Duration: " << elapsedMs2string(duration) << "\n";
516 12895 : if (duration != 0) {
517 12726 : if (TraCIServer::getInstance() != nullptr) {
518 4308 : msg << " TraCI-Duration: " << elapsedMs2string(myTraCIMillis) << "\n";
519 : }
520 12726 : 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 12726 : msg << " UPS: " << ((double)myVehiclesMoved / ((double)duration / 1000)) << "\n";
524 12726 : if (myPersonsMoved > 0) {
525 2380 : msg << " UPS-Persons: " << ((double)myPersonsMoved / ((double)duration / 1000)) << "\n";
526 : }
527 : }
528 : // print vehicle statistics
529 12895 : const std::string vehDiscardNotice = ((myVehicleControl->getLoadedVehicleNo() != myVehicleControl->getDepartedVehicleNo()) ?
530 17044 : " (Loaded: " + toString(myVehicleControl->getLoadedVehicleNo()) + ")" : "");
531 : msg << "Vehicles:\n"
532 12895 : << " Inserted: " << myVehicleControl->getDepartedVehicleNo() << vehDiscardNotice << "\n"
533 25790 : << " Running: " << myVehicleControl->getRunningVehicleNo() << "\n"
534 25790 : << " Waiting: " << myInserter->getWaitingVehicleNo() << "\n";
535 :
536 12895 : if (myVehicleControl->getTeleportCount() > 0 || myVehicleControl->getCollisionCount() > 0) {
537 : // print optional teleport statistics
538 : std::vector<std::string> reasons;
539 710 : if (myVehicleControl->getCollisionCount() > 0) {
540 652 : reasons.push_back("Collisions: " + toString(myVehicleControl->getCollisionCount()));
541 : }
542 710 : if (myVehicleControl->getTeleportsJam() > 0) {
543 510 : reasons.push_back("Jam: " + toString(myVehicleControl->getTeleportsJam()));
544 : }
545 710 : if (myVehicleControl->getTeleportsYield() > 0) {
546 280 : reasons.push_back("Yield: " + toString(myVehicleControl->getTeleportsYield()));
547 : }
548 710 : if (myVehicleControl->getTeleportsWrongLane() > 0) {
549 280 : reasons.push_back("Wrong Lane: " + toString(myVehicleControl->getTeleportsWrongLane()));
550 : }
551 2130 : msg << " Teleports: " << myVehicleControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
552 710 : }
553 12895 : if (myVehicleControl->getEmergencyStops() > 0) {
554 70 : msg << " Emergency Stops: " << myVehicleControl->getEmergencyStops() << "\n";
555 : }
556 12895 : if (myVehicleControl->getEmergencyBrakingCount() > 0) {
557 298 : msg << " Emergency Braking: " << myVehicleControl->getEmergencyBrakingCount() << "\n";
558 : }
559 12895 : if (myPersonControl != nullptr && myPersonControl->getLoadedNumber() > 0) {
560 2427 : const std::string discardNotice = ((myPersonControl->getLoadedNumber() != myPersonControl->getDepartedNumber()) ?
561 2802 : " (Loaded: " + toString(myPersonControl->getLoadedNumber()) + ")" : "");
562 : msg << "Persons:\n"
563 2427 : << " Inserted: " << myPersonControl->getDepartedNumber() << discardNotice << "\n"
564 4854 : << " Running: " << myPersonControl->getRunningNumber() << "\n";
565 2427 : if (myPersonControl->getJammedNumber() > 0) {
566 54 : msg << " Jammed: " << myPersonControl->getJammedNumber() << "\n";
567 : }
568 2427 : if (myPersonControl->getTeleportCount() > 0) {
569 : std::vector<std::string> reasons;
570 7 : if (myPersonControl->getTeleportsAbortWait() > 0) {
571 0 : reasons.push_back("Abort Wait: " + toString(myPersonControl->getTeleportsAbortWait()));
572 : }
573 7 : if (myPersonControl->getTeleportsWrongDest() > 0) {
574 14 : reasons.push_back("Wrong Dest: " + toString(myPersonControl->getTeleportsWrongDest()));
575 : }
576 21 : msg << " Teleports: " << myPersonControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
577 7 : }
578 : }
579 12895 : if (myContainerControl != nullptr && myContainerControl->getLoadedNumber() > 0) {
580 76 : const std::string discardNotice = ((myContainerControl->getLoadedNumber() != myContainerControl->getDepartedNumber()) ?
581 76 : " (Loaded: " + toString(myContainerControl->getLoadedNumber()) + ")" : "");
582 : msg << "Containers:\n"
583 76 : << " Inserted: " << myContainerControl->getDepartedNumber() << "\n"
584 152 : << " Running: " << myContainerControl->getRunningNumber() << "\n";
585 76 : if (myContainerControl->getJammedNumber() > 0) {
586 0 : msg << " Jammed: " << myContainerControl->getJammedNumber() << "\n";
587 : }
588 76 : if (myContainerControl->getTeleportCount() > 0) {
589 : std::vector<std::string> reasons;
590 0 : if (myContainerControl->getTeleportsAbortWait() > 0) {
591 0 : reasons.push_back("Abort Wait: " + toString(myContainerControl->getTeleportsAbortWait()));
592 : }
593 0 : if (myContainerControl->getTeleportsWrongDest() > 0) {
594 0 : reasons.push_back("Wrong Dest: " + toString(myContainerControl->getTeleportsWrongDest()));
595 : }
596 0 : msg << " Teleports: " << myContainerControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
597 0 : }
598 : }
599 : }
600 26496 : if (OptionsCont::getOptions().getBool("duration-log.statistics")) {
601 6806 : msg << MSDevice_Tripinfo::printStatistics();
602 : }
603 : std::string result = msg.str();
604 : result.erase(result.end() - 1);
605 13248 : return result;
606 13248 : }
607 :
608 :
609 : void
610 10356 : MSNet::writeCollisions() const {
611 20712 : OutputDevice& od = OutputDevice::getDeviceByOption("collision-output");
612 10515 : for (const auto& item : myCollisions) {
613 318 : for (const auto& c : item.second) {
614 159 : if (c.time != SIMSTEP) {
615 18 : continue;
616 : }
617 282 : od.openTag("collision");
618 141 : od.writeAttr("time", time2string(getCurrentTimeStep()));
619 141 : od.writeAttr("type", c.type);
620 141 : od.writeAttr("lane", c.lane->getID());
621 141 : od.writeAttr("pos", c.pos);
622 141 : od.writeAttr("collider", item.first);
623 141 : od.writeAttr("victim", c.victim);
624 141 : od.writeAttr("colliderType", c.colliderType);
625 141 : od.writeAttr("victimType", c.victimType);
626 141 : od.writeAttr("colliderSpeed", c.colliderSpeed);
627 141 : od.writeAttr("victimSpeed", c.victimSpeed);
628 141 : od.writeAttr("colliderFront", c.colliderFront);
629 141 : od.writeAttr("colliderBack", c.colliderBack);
630 141 : od.writeAttr("victimFront", c.victimFront);
631 141 : od.writeAttr("victimBack", c.victimBack);
632 282 : od.closeTag();
633 : }
634 : }
635 10356 : }
636 :
637 :
638 : void
639 379 : MSNet::writeStatistics(const SUMOTime start, const long now) const {
640 379 : const long duration = now - mySimBeginMillis;
641 379 : OutputDevice& od = OutputDevice::getDeviceByOption("statistic-output");
642 379 : od.openTag("performance");
643 379 : od.writeAttr("clockBegin", time2string(mySimBeginMillis));
644 379 : od.writeAttr("clockEnd", time2string(now));
645 379 : od.writeAttr("clockDuration", time2string(duration));
646 379 : od.writeAttr("traciDuration", time2string(myTraCIMillis));
647 379 : od.writeAttr("realTimeFactor", duration != 0 ? (double)(myStep - start) / (double)duration : -1);
648 379 : od.writeAttr("vehicleUpdatesPerSecond", duration != 0 ? (double)myVehiclesMoved / ((double)duration / 1000) : -1);
649 379 : od.writeAttr("personUpdatesPerSecond", duration != 0 ? (double)myPersonsMoved / ((double)duration / 1000) : -1);
650 379 : od.writeAttr("begin", time2string(start));
651 379 : od.writeAttr("end", time2string(myStep));
652 379 : od.writeAttr("duration", time2string(myStep - start));
653 379 : od.closeTag();
654 379 : od.openTag("vehicles");
655 379 : od.writeAttr("loaded", myVehicleControl->getLoadedVehicleNo());
656 379 : od.writeAttr("inserted", myVehicleControl->getDepartedVehicleNo());
657 379 : od.writeAttr("running", myVehicleControl->getRunningVehicleNo());
658 379 : od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
659 379 : od.closeTag();
660 379 : od.openTag("teleports");
661 379 : od.writeAttr("total", myVehicleControl->getTeleportCount());
662 379 : od.writeAttr("jam", myVehicleControl->getTeleportsJam());
663 379 : od.writeAttr("yield", myVehicleControl->getTeleportsYield());
664 379 : od.writeAttr("wrongLane", myVehicleControl->getTeleportsWrongLane());
665 379 : od.closeTag();
666 379 : od.openTag("safety");
667 379 : od.writeAttr("collisions", myVehicleControl->getCollisionCount());
668 379 : od.writeAttr("emergencyStops", myVehicleControl->getEmergencyStops());
669 379 : od.writeAttr("emergencyBraking", myVehicleControl->getEmergencyBrakingCount());
670 379 : od.closeTag();
671 379 : od.openTag("persons");
672 385 : od.writeAttr("loaded", myPersonControl != nullptr ? myPersonControl->getLoadedNumber() : 0);
673 385 : od.writeAttr("running", myPersonControl != nullptr ? myPersonControl->getRunningNumber() : 0);
674 385 : od.writeAttr("jammed", myPersonControl != nullptr ? myPersonControl->getJammedNumber() : 0);
675 379 : od.closeTag();
676 379 : od.openTag("personTeleports");
677 385 : od.writeAttr("total", myPersonControl != nullptr ? myPersonControl->getTeleportCount() : 0);
678 385 : od.writeAttr("abortWait", myPersonControl != nullptr ? myPersonControl->getTeleportsAbortWait() : 0);
679 385 : od.writeAttr("wrongDest", myPersonControl != nullptr ? myPersonControl->getTeleportsWrongDest() : 0);
680 379 : od.closeTag();
681 603 : if (OptionsCont::getOptions().isSet("tripinfo-output") || OptionsCont::getOptions().getBool("duration-log.statistics")) {
682 264 : MSDevice_Tripinfo::writeStatistics(od);
683 : }
684 379 : }
685 :
686 :
687 : void
688 64241076 : MSNet::writeSummaryOutput(bool finalStep) {
689 : // summary output
690 64241076 : const OptionsCont& oc = OptionsCont::getOptions();
691 64241076 : const bool hasOutput = oc.isSet("summary-output");
692 64241076 : const bool hasPersonOutput = oc.isSet("person-summary-output");
693 64241076 : if (hasOutput || hasPersonOutput) {
694 531916 : const SUMOTime period = string2time(oc.getString("summary-output.period"));
695 531916 : const SUMOTime begin = string2time(oc.getString("begin"));
696 531916 : if ((period > 0 && (myStep - begin) % period != 0 && !finalStep)
697 : // it's the final step but we already wrote output
698 530996 : || (finalStep && (period <= 0 || (myStep - begin) % period == 0))) {
699 : return;
700 : }
701 : }
702 530473 : if (hasOutput) {
703 522721 : OutputDevice& od = OutputDevice::getDeviceByOption("summary-output");
704 522721 : int departedVehiclesNumber = myVehicleControl->getDepartedVehicleNo();
705 522721 : const double meanWaitingTime = departedVehiclesNumber != 0 ? myVehicleControl->getTotalDepartureDelay() / (double) departedVehiclesNumber : -1.;
706 : int endedVehicleNumber = myVehicleControl->getEndedVehicleNo();
707 522721 : const double meanTravelTime = endedVehicleNumber != 0 ? myVehicleControl->getTotalTravelTime() / (double) endedVehicleNumber : -1.;
708 522721 : od.openTag("step");
709 522721 : od.writeAttr("time", time2string(myStep));
710 522721 : od.writeAttr("loaded", myVehicleControl->getLoadedVehicleNo());
711 522721 : od.writeAttr("inserted", myVehicleControl->getDepartedVehicleNo());
712 522721 : od.writeAttr("running", myVehicleControl->getRunningVehicleNo());
713 522721 : od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
714 522721 : od.writeAttr("ended", myVehicleControl->getEndedVehicleNo());
715 522721 : od.writeAttr("arrived", myVehicleControl->getArrivedVehicleNo());
716 522721 : od.writeAttr("collisions", myVehicleControl->getCollisionCount());
717 522721 : od.writeAttr("teleports", myVehicleControl->getTeleportCount());
718 522721 : od.writeAttr("halting", myVehicleControl->getHaltingVehicleNo());
719 522721 : od.writeAttr("stopped", myVehicleControl->getStoppedVehiclesCount());
720 522721 : od.writeAttr("meanWaitingTime", meanWaitingTime);
721 522721 : od.writeAttr("meanTravelTime", meanTravelTime);
722 522721 : std::pair<double, double> meanSpeed = myVehicleControl->getVehicleMeanSpeeds();
723 522721 : od.writeAttr("meanSpeed", meanSpeed.first);
724 522721 : od.writeAttr("meanSpeedRelative", meanSpeed.second);
725 522721 : od.writeAttr("discarded", myVehicleControl->getDiscardedVehicleNo());
726 522721 : if (myLogExecutionTime) {
727 235433 : od.writeAttr("duration", mySimStepDuration);
728 : }
729 1045442 : od.closeTag();
730 : }
731 64239633 : if (hasPersonOutput) {
732 7752 : OutputDevice& od = OutputDevice::getDeviceByOption("person-summary-output");
733 7752 : MSTransportableControl& pc = getPersonControl();
734 7752 : od.openTag("step");
735 15504 : od.writeAttr("time", time2string(myStep));
736 7752 : od.writeAttr("loaded", pc.getLoadedNumber());
737 7752 : od.writeAttr("inserted", pc.getDepartedNumber());
738 7752 : od.writeAttr("walking", pc.getMovingNumber());
739 7752 : od.writeAttr("waitingForRide", pc.getWaitingForVehicleNumber());
740 7752 : od.writeAttr("riding", pc.getRidingNumber());
741 7752 : od.writeAttr("stopping", pc.getWaitingUntilNumber());
742 7752 : od.writeAttr("jammed", pc.getJammedNumber());
743 7752 : od.writeAttr("ended", pc.getEndedNumber());
744 7752 : od.writeAttr("arrived", pc.getArrivedNumber());
745 7752 : od.writeAttr("teleports", pc.getTeleportCount());
746 7752 : od.writeAttr("discarded", pc.getDiscardedNumber());
747 7752 : if (myLogExecutionTime) {
748 0 : od.writeAttr("duration", mySimStepDuration);
749 : }
750 15504 : od.closeTag();
751 : }
752 : }
753 :
754 :
755 : void
756 40657 : MSNet::closeSimulation(SUMOTime start, const std::string& reason) {
757 : // report the end when wished
758 81314 : WRITE_MESSAGE(TLF("Simulation ended at time: %.", time2string(getCurrentTimeStep())));
759 40657 : if (reason != "") {
760 80432 : WRITE_MESSAGE(TL("Reason: ") + reason);
761 : }
762 40657 : myDetectorControl->close(myStep);
763 81314 : if (OptionsCont::getOptions().isSet("queue-output")) {
764 358 : MSQueueExport::finish(OutputDevice::getDeviceByOption("queue-output"), myStep);
765 : }
766 42111 : if (MSStopOut::active() && OptionsCont::getOptions().getBool("stop-output.write-unfinished")) {
767 121 : MSStopOut::getInstance()->generateOutputForUnfinished();
768 : }
769 40657 : MSDevice_Vehroutes::writePendingOutput(OptionsCont::getOptions().getBool("vehroute-output.write-unfinished"));
770 81314 : if (OptionsCont::getOptions().getBool("tripinfo-output.write-unfinished")) {
771 1100 : MSDevice_Tripinfo::generateOutputForUnfinished();
772 : }
773 81314 : if (OptionsCont::getOptions().isSet("chargingstations-output")) {
774 240 : if (!OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
775 100 : writeChargingStationOutput();
776 40 : } else if (OptionsCont::getOptions().getBool("chargingstations-output.aggregated.write-unfinished")) {
777 12 : MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"), true);
778 : }
779 : }
780 81314 : if (OptionsCont::getOptions().isSet("overheadwiresegments-output")) {
781 5 : writeOverheadWireSegmentOutput();
782 : }
783 81314 : if (OptionsCont::getOptions().isSet("substations-output")) {
784 5 : writeSubstationOutput();
785 : }
786 40657 : writeRailSignalBlocks();
787 40657 : const long now = SysUtils::getCurrentMillis();
788 68419 : if (myLogExecutionTime || OptionsCont::getOptions().getBool("duration-log.statistics")) {
789 26496 : WRITE_MESSAGE(generateStatistics(start, now));
790 : }
791 81314 : if (OptionsCont::getOptions().isSet("statistic-output")) {
792 379 : writeStatistics(start, now);
793 : }
794 : // maybe write a final line of output if reporting is periodic
795 40657 : writeSummaryOutput(true);
796 40657 : }
797 :
798 :
799 : void
800 64203601 : MSNet::simulationStep(const bool onlyMove) {
801 64203601 : if (myStepCompletionMissing) {
802 4 : postMoveStep();
803 4 : myStepCompletionMissing = false;
804 2663 : return;
805 : }
806 : #ifdef DEBUG_SIMSTEP
807 : std::cout << SIMTIME << ": MSNet::simulationStep() called"
808 : << ", myStep = " << myStep
809 : << std::endl;
810 : #endif
811 : TraCIServer* t = TraCIServer::getInstance();
812 : int lastTraCICmd = 0;
813 64203597 : if (t != nullptr) {
814 10741280 : if (myLogExecutionTime) {
815 10544311 : myTraCIStepDuration = SysUtils::getCurrentMillis();
816 : }
817 10741280 : lastTraCICmd = t->processCommands(myStep);
818 : #ifdef DEBUG_SIMSTEP
819 : bool loadRequested = !TraCI::getLoadArgs().empty();
820 : assert(t->getTargetTime() >= myStep || loadRequested || TraCIServer::wasClosed());
821 : #endif
822 10741177 : if (myLogExecutionTime) {
823 10544235 : myTraCIStepDuration = SysUtils::getCurrentMillis() - myTraCIStepDuration;
824 : }
825 10741177 : if (TraCIServer::wasClosed() || !t->getLoadArgs().empty()) {
826 : return;
827 : }
828 : }
829 : #ifdef DEBUG_SIMSTEP
830 : std::cout << SIMTIME << ": TraCI target time: " << t->getTargetTime() << std::endl;
831 : #endif
832 : // execute beginOfTimestepEvents
833 64200839 : if (myLogExecutionTime) {
834 27738566 : mySimStepDuration = SysUtils::getCurrentMillis();
835 : }
836 : // simulation state output
837 64200839 : std::vector<SUMOTime>::iterator timeIt = std::find(myStateDumpTimes.begin(), myStateDumpTimes.end(), myStep);
838 64200839 : if (timeIt != myStateDumpTimes.end()) {
839 375 : const int dist = (int)distance(myStateDumpTimes.begin(), timeIt);
840 375 : MSStateHandler::saveState(myStateDumpFiles[dist], myStep);
841 : }
842 64200839 : if (myStateDumpPeriod > 0 && myStep % myStateDumpPeriod == 0) {
843 84 : std::string timeStamp = time2string(myStep);
844 : std::replace(timeStamp.begin(), timeStamp.end(), ':', '-');
845 84 : const std::string filename = myStateDumpPrefix + "_" + timeStamp + myStateDumpSuffix;
846 84 : MSStateHandler::saveState(filename, myStep);
847 84 : myPeriodicStateFiles.push_back(filename);
848 84 : int keep = OptionsCont::getOptions().getInt("save-state.period.keep");
849 84 : if (keep > 0 && (int)myPeriodicStateFiles.size() > keep) {
850 0 : std::remove(myPeriodicStateFiles.front().c_str());
851 : myPeriodicStateFiles.erase(myPeriodicStateFiles.begin());
852 : }
853 : }
854 64200839 : myBeginOfTimestepEvents->execute(myStep);
855 64200831 : if (MSRailSignalControl::hasInstance()) {
856 8828263 : MSRailSignalControl::getInstance().updateSignals(myStep);
857 : }
858 : #ifdef HAVE_FOX
859 64200831 : MSRoutingEngine::waitForAll();
860 : #endif
861 64200831 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
862 42596434 : myEdges->detectCollisions(myStep, STAGE_EVENTS);
863 : }
864 : // check whether the tls programs need to be switched
865 64200831 : myLogics->check2Switch(myStep);
866 :
867 64200831 : if (MSGlobals::gUseMesoSim) {
868 21604397 : MSGlobals::gMesoNet->simulate(myStep);
869 : } else {
870 : // assure all lanes with vehicles are 'active'
871 42596434 : myEdges->patchActiveLanes();
872 :
873 : // compute safe velocities for all vehicles for the next few lanes
874 : // also register ApproachingVehicleInformation for all links
875 42596434 : myEdges->planMovements(myStep);
876 :
877 : // register junction approaches based on planned velocities as basis for right-of-way decision
878 42596434 : myEdges->setJunctionApproaches();
879 :
880 : // decide right-of-way and execute movements
881 42596434 : myEdges->executeMovements(myStep);
882 42596431 : if (MSGlobals::gCheck4Accidents) {
883 42596431 : myEdges->detectCollisions(myStep, STAGE_MOVEMENTS);
884 : }
885 :
886 : // vehicles may change lanes
887 42596431 : myEdges->changeLanes(myStep);
888 :
889 42596431 : if (MSGlobals::gCheck4Accidents) {
890 42596431 : myEdges->detectCollisions(myStep, STAGE_LANECHANGE);
891 : }
892 : }
893 : // flush arrived meso vehicles and micro vehicles that were removed due to collision
894 64200828 : myVehicleControl->removePending();
895 64200828 : loadRoutes();
896 :
897 : // persons
898 64200812 : if (myPersonControl != nullptr && myPersonControl->hasTransportables()) {
899 5486511 : myPersonControl->checkWaiting(this, myStep);
900 : }
901 : // containers
902 64200756 : if (myContainerControl != nullptr && myContainerControl->hasTransportables()) {
903 3150929 : myContainerControl->checkWaiting(this, myStep);
904 : }
905 64200756 : if (MSRailSignalControl::hasInstance()) {
906 8828263 : MSRailSignalControl::getInstance().resetWaitRelations();
907 : // preserve waitRelation from insertion for the next step
908 : }
909 : // insert vehicles
910 64200756 : myInserter->determineCandidates(myStep);
911 64200709 : myInsertionEvents->execute(myStep);
912 : #ifdef HAVE_FOX
913 64200614 : MSRoutingEngine::waitForAll();
914 : #endif
915 64200590 : myInserter->emitVehicles(myStep);
916 64200444 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
917 : //myEdges->patchActiveLanes(); // @note required to detect collisions on lanes that were empty before insertion. wasteful?
918 42596155 : myEdges->detectCollisions(myStep, STAGE_INSERTIONS);
919 : }
920 64200444 : MSVehicleTransfer::getInstance()->checkInsertions(myStep);
921 :
922 : // execute endOfTimestepEvents
923 64200444 : myEndOfTimestepEvents->execute(myStep);
924 :
925 64200434 : if (myLogExecutionTime) {
926 27738392 : myTraCIStepDuration -= SysUtils::getCurrentMillis();
927 : }
928 64200434 : if (onlyMove) {
929 4 : myStepCompletionMissing = true;
930 4 : return;
931 : }
932 64200430 : if (t != nullptr && lastTraCICmd == libsumo::CMD_EXECUTEMOVE) {
933 6 : t->processCommands(myStep, true);
934 : }
935 64200430 : postMoveStep();
936 : }
937 :
938 :
939 : void
940 64200434 : MSNet::postMoveStep() {
941 64200434 : const int numControlled = libsumo::Helper::postProcessRemoteControl();
942 64200434 : if (numControlled > 0 && MSGlobals::gCheck4Accidents) {
943 1953558 : myEdges->detectCollisions(myStep, STAGE_REMOTECONTROL);
944 : }
945 64200434 : if (myLogExecutionTime) {
946 27738392 : myTraCIStepDuration += SysUtils::getCurrentMillis();
947 27738392 : myTraCIMillis += myTraCIStepDuration;
948 : }
949 64200434 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
950 : // collisions from the previous step were kept to avoid duplicate
951 : // warnings. we must remove them now to ensure correct output.
952 42596150 : removeOutdatedCollisions();
953 : }
954 : // update and write (if needed) detector values
955 64200434 : mySimStepDuration = SysUtils::getCurrentMillis() - mySimStepDuration;
956 64200434 : writeOutput();
957 :
958 64200418 : if (myLogExecutionTime) {
959 27738392 : myVehiclesMoved += myVehicleControl->getRunningVehicleNo();
960 27738392 : if (myPersonControl != nullptr) {
961 4688363 : myPersonsMoved += myPersonControl->getRunningNumber();
962 : }
963 : }
964 64200418 : myStep += DELTA_T;
965 64200418 : }
966 :
967 :
968 : MSNet::SimulationState
969 64104620 : MSNet::simulationState(SUMOTime stopTime) const {
970 64104620 : if (TraCIServer::wasClosed()) {
971 : return SIMSTATE_CONNECTION_CLOSED;
972 : }
973 64101842 : if (TraCIServer::getInstance() != nullptr && !TraCIServer::getInstance()->getLoadArgs().empty()) {
974 : return SIMSTATE_LOADING;
975 : }
976 64101829 : if ((stopTime < 0 || myStep > stopTime) && TraCIServer::getInstance() == nullptr && (stopTime > 0 || myStep > myEdgeDataEndTime)) {
977 31948367 : if ((myVehicleControl->getActiveVehicleCount() == 0)
978 6143748 : && (myInserter->getPendingFlowCount() == 0)
979 1950315 : && (myPersonControl == nullptr || !myPersonControl->hasNonWaiting())
980 412633 : && (myContainerControl == nullptr || !myContainerControl->hasNonWaiting())
981 32011786 : && !MSDevice_Taxi::hasServableReservations()) {
982 : return SIMSTATE_NO_FURTHER_VEHICLES;
983 : }
984 : }
985 64055276 : if (stopTime >= 0 && myStep >= stopTime) {
986 : return SIMSTATE_END_STEP_REACHED;
987 : }
988 64034187 : if (myMaxTeleports >= 0 && myVehicleControl->getTeleportCount() > myMaxTeleports) {
989 : return SIMSTATE_TOO_MANY_TELEPORTS;
990 : }
991 64034179 : if (myAmInterrupted) {
992 5 : return SIMSTATE_INTERRUPTED;
993 : }
994 : return SIMSTATE_RUNNING;
995 : }
996 :
997 :
998 : MSNet::SimulationState
999 64096017 : MSNet::adaptToState(MSNet::SimulationState state, const bool isLibsumo) const {
1000 64096017 : if (state == SIMSTATE_LOADING) {
1001 13 : OptionsIO::setArgs(TraCIServer::getInstance()->getLoadArgs());
1002 : TraCIServer::getInstance()->getLoadArgs().clear();
1003 64096004 : } else if (state != SIMSTATE_RUNNING && ((TraCIServer::getInstance() != nullptr && !TraCIServer::wasClosed()) || isLibsumo)) {
1004 : // overrides SIMSTATE_END_STEP_REACHED, e.g. (TraCI / Libsumo ignore SUMO's --end option)
1005 23045 : return SIMSTATE_RUNNING;
1006 64072959 : } else if (state == SIMSTATE_NO_FURTHER_VEHICLES) {
1007 28332 : if (myPersonControl != nullptr) {
1008 6860 : myPersonControl->abortAnyWaitingForVehicle();
1009 : }
1010 28332 : if (myContainerControl != nullptr) {
1011 1863 : myContainerControl->abortAnyWaitingForVehicle();
1012 : }
1013 28332 : myVehicleControl->abortWaiting();
1014 : }
1015 : return state;
1016 : }
1017 :
1018 :
1019 : std::string
1020 40051 : MSNet::getStateMessage(MSNet::SimulationState state) {
1021 40051 : switch (state) {
1022 : case MSNet::SIMSTATE_RUNNING:
1023 441 : return "";
1024 : case MSNet::SIMSTATE_END_STEP_REACHED:
1025 8245 : return TL("The final simulation step has been reached.");
1026 : case MSNet::SIMSTATE_NO_FURTHER_VEHICLES:
1027 28699 : return TL("All vehicles have left the simulation.");
1028 : case MSNet::SIMSTATE_CONNECTION_CLOSED:
1029 2642 : return TL("TraCI requested termination.");
1030 : case MSNet::SIMSTATE_ERROR_IN_SIM:
1031 0 : return TL("An error occurred (see log).");
1032 : case MSNet::SIMSTATE_INTERRUPTED:
1033 5 : return TL("Interrupted.");
1034 : case MSNet::SIMSTATE_TOO_MANY_TELEPORTS:
1035 6 : return TL("Too many teleports.");
1036 : case MSNet::SIMSTATE_LOADING:
1037 13 : return TL("TraCI issued load command.");
1038 : default:
1039 0 : return TL("Unknown reason.");
1040 : }
1041 : }
1042 :
1043 :
1044 : void
1045 42458 : MSNet::clearAll() {
1046 : // clear container
1047 42458 : MSEdge::clear();
1048 42458 : MSLane::clear();
1049 42458 : MSRoute::clear();
1050 42458 : delete MSVehicleTransfer::getInstance();
1051 42458 : MSDevice::cleanupAll();
1052 42458 : MSCalibrator::cleanup();
1053 85416 : while (!MSLaneSpeedTrigger::getInstances().empty()) {
1054 500 : delete MSLaneSpeedTrigger::getInstances().begin()->second;
1055 : }
1056 46585 : while (!MSTriggeredRerouter::getInstances().empty()) {
1057 4127 : delete MSTriggeredRerouter::getInstances().begin()->second;
1058 : }
1059 42458 : MSDevice_BTsender::cleanup();
1060 42458 : MSDevice_SSM::cleanup();
1061 42458 : MSDevice_ToC::cleanup();
1062 42458 : MSStopOut::cleanup();
1063 42458 : MSRailSignalConstraint::cleanup();
1064 42458 : MSRailSignalControl::cleanup();
1065 42458 : MSDriveWay::cleanup();
1066 : TraCIServer* t = TraCIServer::getInstance();
1067 42458 : if (t != nullptr) {
1068 2759 : t->cleanup();
1069 : }
1070 42458 : libsumo::Helper::cleanup();
1071 42458 : OutputDevice::closeAll(true);
1072 42458 : }
1073 :
1074 :
1075 : void
1076 164 : MSNet::clearState(const SUMOTime step, bool quickReload) {
1077 164 : MSGlobals::gClearState = true;
1078 164 : if (MSGlobals::gUseMesoSim) {
1079 12 : MSGlobals::gMesoNet->clearState();
1080 390 : for (MSEdge* const edge : MSEdge::getAllEdges()) {
1081 776 : for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*edge); s != nullptr; s = s->getNextSegment()) {
1082 398 : s->clearState();
1083 : }
1084 : }
1085 : } else {
1086 7184 : for (MSEdge* const edge : MSEdge::getAllEdges()) {
1087 15576 : for (MSLane* const lane : edge->getLanes()) {
1088 8544 : lane->getVehiclesSecure();
1089 8544 : lane->clearState();
1090 8544 : lane->releaseVehicles();
1091 : }
1092 7032 : edge->clearState();
1093 : }
1094 : }
1095 164 : myInserter->clearState();
1096 : // detectors may still reference persons/vehicles
1097 164 : myDetectorControl->updateDetectors(myStep);
1098 164 : myDetectorControl->writeOutput(myStep, true);
1099 164 : myDetectorControl->clearState(step);
1100 :
1101 164 : if (myPersonControl != nullptr) {
1102 20 : myPersonControl->clearState();
1103 : }
1104 164 : if (myContainerControl != nullptr) {
1105 0 : myContainerControl->clearState();
1106 : }
1107 : // delete vtypes after transportables have removed their types
1108 164 : myVehicleControl->clearState(true);
1109 164 : MSVehicleTransfer::getInstance()->clearState();
1110 164 : myLogics->clearState(step, quickReload);
1111 : // delete all routes after vehicles and detector output is done
1112 164 : MSRoute::dict_clearState();
1113 205 : for (auto& item : myStoppingPlaces) {
1114 82 : for (auto& item2 : item.second) {
1115 41 : item2.second->clearState();
1116 : }
1117 : }
1118 164 : myShapeContainer->clearState();
1119 164 : myBeginOfTimestepEvents->clearState(myStep, step);
1120 164 : myEndOfTimestepEvents->clearState(myStep, step);
1121 164 : myInsertionEvents->clearState(myStep, step);
1122 164 : MSRailSignalControl::clearState();
1123 164 : MSDriveWay::clearState();
1124 164 : myStep = step;
1125 164 : MSGlobals::gClearState = false;
1126 164 : }
1127 :
1128 :
1129 : SUMOTime
1130 571 : MSNet::getLoaderTime() const {
1131 571 : return myRouteLoaders->getCurrentLoadTime();
1132 : }
1133 :
1134 : void
1135 712 : MSNet::setLoaderTime(SUMOTime time) {
1136 712 : myRouteLoaders->setCurrentLoadTime(time);
1137 712 : myStateLoaderTime = MAX2(myStateLoaderTime, time);
1138 712 : }
1139 :
1140 : void
1141 64200434 : MSNet::writeOutput() {
1142 : // update detector values
1143 64200434 : myDetectorControl->updateDetectors(myStep);
1144 64200425 : const OptionsCont& oc = OptionsCont::getOptions();
1145 :
1146 : // check state dumps
1147 128400850 : if (oc.isSet("netstate-dump")) {
1148 12936 : MSXMLRawOut::write(OutputDevice::getDeviceByOption("netstate-dump"), *myEdges, myStep,
1149 : oc.getInt("netstate-dump.precision"));
1150 : }
1151 :
1152 : // check fcd dumps
1153 128400850 : if (OptionsCont::getOptions().isSet("fcd-output")) {
1154 10710454 : if (OptionsCont::getOptions().isSet("person-fcd-output")) {
1155 24 : MSFCDExport::write(OutputDevice::getDeviceByOption("fcd-output"), myStep, SUMO_TAG_VEHICLE);
1156 48 : MSFCDExport::write(OutputDevice::getDeviceByOption("person-fcd-output"), myStep, SUMO_TAG_PERSON);
1157 : } else {
1158 10710406 : MSFCDExport::write(OutputDevice::getDeviceByOption("fcd-output"), myStep);
1159 : }
1160 : }
1161 :
1162 : // check emission dumps
1163 128400850 : if (OptionsCont::getOptions().isSet("emission-output")) {
1164 215992 : MSEmissionExport::write(OutputDevice::getDeviceByOption("emission-output"), myStep);
1165 : }
1166 :
1167 : // battery dumps
1168 128400850 : if (OptionsCont::getOptions().isSet("battery-output")) {
1169 145458 : MSBatteryExport::write(OutputDevice::getDeviceByOption("battery-output"), myStep,
1170 : oc.getInt("battery-output.precision"));
1171 : }
1172 :
1173 : // charging station aggregated dumps
1174 64290141 : if (OptionsCont::getOptions().isSet("chargingstations-output") && OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
1175 22248 : MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"));
1176 : }
1177 :
1178 : // elecHybrid dumps
1179 128400850 : if (OptionsCont::getOptions().isSet("elechybrid-output")) {
1180 450 : std::string output = OptionsCont::getOptions().getString("elechybrid-output");
1181 :
1182 900 : if (oc.getBool("elechybrid-output.aggregated")) {
1183 : // build a xml file with aggregated device.elechybrid output
1184 600 : MSElecHybridExport::writeAggregated(OutputDevice::getDeviceByOption("elechybrid-output"), myStep,
1185 : oc.getInt("elechybrid-output.precision"));
1186 : } else {
1187 : // build a separate xml file for each vehicle equipped with device.elechybrid
1188 : // RICE_TODO: Does this have to be placed here in MSNet.cpp ?
1189 150 : MSVehicleControl& vc = MSNet::getInstance()->getVehicleControl();
1190 204 : for (MSVehicleControl::constVehIt it = vc.loadedVehBegin(); it != vc.loadedVehEnd(); ++it) {
1191 54 : const SUMOVehicle* veh = it->second;
1192 54 : if (!veh->isOnRoad()) {
1193 0 : continue;
1194 : }
1195 54 : if (static_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid))) != nullptr) {
1196 : std::string vehID = veh->getID();
1197 54 : std::string filename2 = output + "_" + vehID + ".xml";
1198 54 : OutputDevice& dev = OutputDevice::getDevice(filename2);
1199 : std::map<SumoXMLAttr, std::string> attrs;
1200 54 : attrs[SUMO_ATTR_VEHICLE] = vehID;
1201 54 : attrs[SUMO_ATTR_MAXIMUMBATTERYCAPACITY] = toString(dynamic_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid)))->getMaximumBatteryCapacity());
1202 54 : attrs[SUMO_ATTR_RECUPERATIONENABLE] = toString(MSGlobals::gOverheadWireRecuperation);
1203 108 : dev.writeXMLHeader("elecHybrid-export", "", attrs);
1204 108 : MSElecHybridExport::write(OutputDevice::getDevice(filename2), veh, myStep, oc.getInt("elechybrid-output.precision"));
1205 : }
1206 : }
1207 : }
1208 : }
1209 :
1210 :
1211 : // check full dumps
1212 128400850 : if (OptionsCont::getOptions().isSet("full-output")) {
1213 1138 : MSGlobals::gHaveEmissions = true;
1214 2276 : MSFullExport::write(OutputDevice::getDeviceByOption("full-output"), myStep);
1215 : }
1216 :
1217 : // check queue dumps
1218 128400850 : if (OptionsCont::getOptions().isSet("queue-output")) {
1219 330534 : MSQueueExport::write(OutputDevice::getDeviceByOption("queue-output"), myStep);
1220 : }
1221 :
1222 : // check amitran dumps
1223 128400850 : if (OptionsCont::getOptions().isSet("amitran-output")) {
1224 2340 : MSAmitranTrajectories::write(OutputDevice::getDeviceByOption("amitran-output"), myStep);
1225 : }
1226 :
1227 : // check vtk dumps
1228 128400850 : if (OptionsCont::getOptions().isSet("vtk-output")) {
1229 :
1230 60 : if (MSNet::getInstance()->getVehicleControl().getRunningVehicleNo() > 0) {
1231 60 : std::string timestep = time2string(myStep);
1232 60 : if (TS >= 1.0) {
1233 48 : timestep = timestep.substr(0, timestep.length() - 3);
1234 36 : } else if (DELTA_T % 100 == 0) {
1235 72 : timestep = timestep.substr(0, timestep.length() - 1);
1236 : }
1237 66 : std::string output = OptionsCont::getOptions().getString("vtk-output");
1238 66 : std::string filename = output + "_" + timestep + ".vtp";
1239 :
1240 60 : OutputDevice_File dev(filename);
1241 :
1242 : //build a huge mass of xml files
1243 54 : MSVTKExport::write(dev, myStep);
1244 :
1245 54 : }
1246 :
1247 : }
1248 :
1249 64200419 : writeSummaryOutput();
1250 :
1251 : // write detector values
1252 64200419 : myDetectorControl->writeOutput(myStep + DELTA_T, false);
1253 :
1254 : // write link states
1255 128400836 : if (OptionsCont::getOptions().isSet("link-output")) {
1256 4048 : OutputDevice& od = OutputDevice::getDeviceByOption("link-output");
1257 4048 : od.openTag("timestep");
1258 4048 : od.writeAttr(SUMO_ATTR_ID, STEPS2TIME(myStep));
1259 85848 : for (const MSEdge* const edge : myEdges->getEdges()) {
1260 180200 : for (const MSLane* const lane : edge->getLanes()) {
1261 212304 : for (const MSLink* const link : lane->getLinkCont()) {
1262 227808 : link->writeApproaching(od, lane->getID());
1263 : }
1264 : }
1265 : }
1266 8096 : od.closeTag();
1267 : }
1268 :
1269 : // write SSM output
1270 66733527 : for (MSDevice_SSM* dev : MSDevice_SSM::getInstances()) {
1271 2533109 : dev->updateAndWriteOutput();
1272 : }
1273 :
1274 : // write ToC output
1275 64216137 : for (MSDevice_ToC* dev : MSDevice_ToC::getInstances()) {
1276 15719 : if (dev->generatesOutput()) {
1277 15513 : dev->writeOutput();
1278 : }
1279 : }
1280 :
1281 128400836 : if (OptionsCont::getOptions().isSet("collision-output")) {
1282 10356 : writeCollisions();
1283 : }
1284 64200418 : }
1285 :
1286 :
1287 : bool
1288 0 : MSNet::logSimulationDuration() const {
1289 0 : return myLogExecutionTime;
1290 : }
1291 :
1292 :
1293 : MSTransportableControl&
1294 28629975 : MSNet::getPersonControl() {
1295 28629975 : if (myPersonControl == nullptr) {
1296 6676 : myPersonControl = new MSTransportableControl(true);
1297 : }
1298 28629951 : return *myPersonControl;
1299 : }
1300 :
1301 :
1302 : MSTransportableControl&
1303 5479788 : MSNet::getContainerControl() {
1304 5479788 : if (myContainerControl == nullptr) {
1305 1782 : myContainerControl = new MSTransportableControl(false);
1306 : }
1307 5479788 : return *myContainerControl;
1308 : }
1309 :
1310 : MSDynamicShapeUpdater*
1311 22 : MSNet::makeDynamicShapeUpdater() {
1312 22 : myDynamicShapeUpdater = std::unique_ptr<MSDynamicShapeUpdater> (new MSDynamicShapeUpdater(*myShapeContainer));
1313 22 : return myDynamicShapeUpdater.get();
1314 : }
1315 :
1316 : MSEdgeWeightsStorage&
1317 7023416 : MSNet::getWeightsStorage() {
1318 7023416 : if (myEdgeWeights == nullptr) {
1319 1941 : myEdgeWeights = new MSEdgeWeightsStorage();
1320 : }
1321 7023416 : return *myEdgeWeights;
1322 : }
1323 :
1324 :
1325 : void
1326 127 : MSNet::preSimStepOutput() const {
1327 127 : std::cout << "Step #" << time2string(myStep);
1328 127 : }
1329 :
1330 :
1331 : void
1332 127 : MSNet::postSimStepOutput() const {
1333 127 : if (myLogExecutionTime) {
1334 125 : std::ostringstream oss;
1335 : oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
1336 : oss.setf(std::ios::showpoint); // print decimal point
1337 125 : oss << std::setprecision(gPrecision);
1338 125 : if (mySimStepDuration != 0) {
1339 73 : const double durationSec = (double)mySimStepDuration / 1000.;
1340 73 : oss << " (" << mySimStepDuration << "ms ~= "
1341 73 : << (TS / durationSec) << "*RT, ~"
1342 73 : << ((double) myVehicleControl->getRunningVehicleNo() / durationSec);
1343 : } else {
1344 52 : oss << " (0ms ?*RT. ?";
1345 : }
1346 125 : oss << "UPS, ";
1347 125 : if (TraCIServer::getInstance() != nullptr) {
1348 79 : oss << "TraCI: " << myTraCIStepDuration << "ms, ";
1349 : }
1350 125 : oss << "vehicles TOT " << myVehicleControl->getDepartedVehicleNo()
1351 250 : << " ACT " << myVehicleControl->getRunningVehicleNo()
1352 125 : << " BUF " << myInserter->getWaitingVehicleNo()
1353 125 : << ") ";
1354 250 : std::string prev = "Step #" + time2string(myStep - DELTA_T);
1355 250 : std::cout << oss.str().substr(0, 90 - prev.length());
1356 125 : }
1357 127 : std::cout << '\r';
1358 127 : }
1359 :
1360 :
1361 : void
1362 11596 : MSNet::addVehicleStateListener(VehicleStateListener* listener) {
1363 11596 : if (find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener) == myVehicleStateListeners.end()) {
1364 11596 : myVehicleStateListeners.push_back(listener);
1365 : }
1366 11596 : }
1367 :
1368 :
1369 : void
1370 57 : MSNet::removeVehicleStateListener(VehicleStateListener* listener) {
1371 57 : std::vector<VehicleStateListener*>::iterator i = std::find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener);
1372 57 : if (i != myVehicleStateListeners.end()) {
1373 57 : myVehicleStateListeners.erase(i);
1374 : }
1375 57 : }
1376 :
1377 :
1378 : void
1379 15950654 : MSNet::informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info) {
1380 : #ifdef HAVE_FOX
1381 15950654 : ScopedLocker<> lock(myVehicleStateListenerMutex, MSGlobals::gNumThreads > 1);
1382 : #endif
1383 16642678 : for (VehicleStateListener* const listener : myVehicleStateListeners) {
1384 692024 : listener->vehicleStateChanged(vehicle, to, info);
1385 : }
1386 15950654 : }
1387 :
1388 :
1389 : void
1390 3909 : MSNet::addTransportableStateListener(TransportableStateListener* listener) {
1391 3909 : if (find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener) == myTransportableStateListeners.end()) {
1392 3909 : myTransportableStateListeners.push_back(listener);
1393 : }
1394 3909 : }
1395 :
1396 :
1397 : void
1398 0 : MSNet::removeTransportableStateListener(TransportableStateListener* listener) {
1399 0 : std::vector<TransportableStateListener*>::iterator i = std::find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener);
1400 0 : if (i != myTransportableStateListeners.end()) {
1401 0 : myTransportableStateListeners.erase(i);
1402 : }
1403 0 : }
1404 :
1405 :
1406 : void
1407 1007118 : MSNet::informTransportableStateListener(const MSTransportable* const transportable, TransportableState to, const std::string& info) {
1408 : #ifdef HAVE_FOX
1409 1007118 : ScopedLocker<> lock(myTransportableStateListenerMutex, MSGlobals::gNumThreads > 1);
1410 : #endif
1411 1009927 : for (TransportableStateListener* const listener : myTransportableStateListeners) {
1412 2809 : listener->transportableStateChanged(transportable, to, info);
1413 : }
1414 1007118 : }
1415 :
1416 :
1417 : bool
1418 17659 : MSNet::registerCollision(const SUMOTrafficObject* collider, const SUMOTrafficObject* victim, const std::string& collisionType, const MSLane* lane, double pos) {
1419 : auto it = myCollisions.find(collider->getID());
1420 17659 : if (it != myCollisions.end()) {
1421 8469 : for (Collision& old : it->second) {
1422 8364 : if (old.victim == victim->getID()) {
1423 : // collision from previous step continues
1424 7586 : old.continuationTime = myStep;
1425 : return false;
1426 : }
1427 : }
1428 : } else {
1429 : // maybe the roles have been reversed
1430 : auto it2 = myCollisions.find(victim->getID());
1431 9968 : if (it2 != myCollisions.end()) {
1432 3959 : for (Collision& old : it2->second) {
1433 3783 : if (old.victim == collider->getID()) {
1434 : // collision from previous step continues (keep the old roles)
1435 3604 : old.continuationTime = myStep;
1436 : return false;
1437 : }
1438 : }
1439 : }
1440 : }
1441 : Collision c;
1442 : c.victim = victim->getID();
1443 6469 : c.colliderType = collider->getVehicleType().getID();
1444 6469 : c.victimType = victim->getVehicleType().getID();
1445 6469 : c.colliderSpeed = collider->getSpeed();
1446 6469 : c.victimSpeed = victim->getSpeed();
1447 6469 : c.colliderFront = collider->getPosition();
1448 6469 : c.victimFront = victim->getPosition();
1449 6469 : c.colliderBack = collider->getPosition(-collider->getVehicleType().getLength());
1450 6469 : c.victimBack = victim->getPosition(-victim->getVehicleType().getLength());
1451 : c.type = collisionType;
1452 6469 : c.lane = lane;
1453 6469 : c.pos = pos;
1454 6469 : c.time = myStep;
1455 6469 : c.continuationTime = myStep;
1456 6469 : myCollisions[collider->getID()].push_back(c);
1457 : return true;
1458 6469 : }
1459 :
1460 :
1461 : void
1462 42596150 : MSNet::removeOutdatedCollisions() {
1463 42614452 : for (auto it = myCollisions.begin(); it != myCollisions.end();) {
1464 36830 : for (auto it2 = it->second.begin(); it2 != it->second.end();) {
1465 18528 : if (it2->continuationTime != myStep) {
1466 6457 : it2 = it->second.erase(it2);
1467 : } else {
1468 : it2++;
1469 : }
1470 : }
1471 18302 : if (it->second.size() == 0) {
1472 : it = myCollisions.erase(it);
1473 : } else {
1474 : it++;
1475 : }
1476 : }
1477 42596150 : }
1478 :
1479 :
1480 : bool
1481 83887 : MSNet::addStoppingPlace(SumoXMLTag category, MSStoppingPlace* stop) {
1482 83887 : if (category == SUMO_TAG_TRAIN_STOP) {
1483 14049 : category = SUMO_TAG_BUS_STOP;
1484 : }
1485 83887 : const bool isNew = myStoppingPlaces[category].add(stop->getID(), stop);
1486 83887 : if (isNew && stop->getMyName() != "") {
1487 15969 : myNamedStoppingPlaces[category][stop->getMyName()].push_back(stop);
1488 : }
1489 83887 : return isNew;
1490 : }
1491 :
1492 :
1493 : bool
1494 17 : MSNet::addTractionSubstation(MSTractionSubstation* substation) {
1495 17 : if (find(myTractionSubstations.begin(), myTractionSubstations.end(), substation) == myTractionSubstations.end()) {
1496 17 : myTractionSubstations.push_back(substation);
1497 17 : return true;
1498 : }
1499 : return false;
1500 : }
1501 :
1502 :
1503 : MSStoppingPlace*
1504 1597154 : MSNet::getStoppingPlace(const std::string& id, const SumoXMLTag category) const {
1505 : if (myStoppingPlaces.count(category) > 0) {
1506 : return myStoppingPlaces.find(category)->second.get(id);
1507 : }
1508 : return nullptr;
1509 : }
1510 :
1511 :
1512 : MSStoppingPlace*
1513 172531 : MSNet::getStoppingPlace(const std::string& id) const {
1514 855274 : for (SumoXMLTag category : std::vector<SumoXMLTag>({SUMO_TAG_BUS_STOP, SUMO_TAG_PARKING_AREA, SUMO_TAG_CONTAINER_STOP, SUMO_TAG_CHARGING_STATION, SUMO_TAG_OVERHEAD_WIRE_SEGMENT})) {
1515 719236 : MSStoppingPlace* result = getStoppingPlace(id, category);
1516 719236 : if (result != nullptr) {
1517 : return result;
1518 : }
1519 172531 : }
1520 136038 : return nullptr;
1521 : }
1522 :
1523 :
1524 : std::string
1525 464598 : MSNet::getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const {
1526 : if (myStoppingPlaces.count(category) > 0) {
1527 953772 : for (const auto& it : myStoppingPlaces.find(category)->second) {
1528 874029 : MSStoppingPlace* stop = it.second;
1529 874029 : if (&stop->getLane() == lane && stop->getBeginLanePosition() - POSITION_EPS <= pos && stop->getEndLanePosition() + POSITION_EPS >= pos) {
1530 : return stop->getID();
1531 : }
1532 : }
1533 : }
1534 359441 : return "";
1535 : }
1536 :
1537 :
1538 : const std::vector<MSStoppingPlace*>&
1539 1590 : MSNet::getStoppingPlaceAlternatives(const std::string& name, SumoXMLTag category) const {
1540 1590 : if (category == SUMO_TAG_TRAIN_STOP) {
1541 : category = SUMO_TAG_BUS_STOP;
1542 : }
1543 : auto it = myNamedStoppingPlaces.find(category);
1544 1590 : if (it != myNamedStoppingPlaces.end()) {
1545 : auto it2 = it->second.find(name);
1546 1515 : if (it2 != it->second.end()) {
1547 1515 : return it2->second;
1548 : }
1549 : }
1550 : return myEmptyStoppingPlaceVector;
1551 : }
1552 :
1553 :
1554 : const NamedObjectCont<MSStoppingPlace*>&
1555 14009 : MSNet::getStoppingPlaces(SumoXMLTag category) const {
1556 : auto it = myStoppingPlaces.find(category);
1557 14009 : if (it != myStoppingPlaces.end()) {
1558 13724 : return it->second;
1559 : } else {
1560 : return myEmptyStoppingPlaceCont;
1561 : }
1562 : }
1563 :
1564 :
1565 : void
1566 100 : MSNet::writeChargingStationOutput() const {
1567 : if (myStoppingPlaces.count(SUMO_TAG_CHARGING_STATION) > 0) {
1568 192 : OutputDevice& output = OutputDevice::getDeviceByOption("chargingstations-output");
1569 574 : for (const auto& it : myStoppingPlaces.find(SUMO_TAG_CHARGING_STATION)->second) {
1570 478 : static_cast<MSChargingStation*>(it.second)->writeChargingStationOutput(output);
1571 : }
1572 : }
1573 100 : }
1574 :
1575 :
1576 : void
1577 40657 : MSNet::writeRailSignalBlocks() const {
1578 81314 : if (OptionsCont::getOptions().isSet("railsignal-block-output")) {
1579 1367 : OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-block-output");
1580 5420 : for (auto tls : myLogics->getAllLogics()) {
1581 4053 : MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1582 4053 : if (rs != nullptr) {
1583 4009 : rs->writeBlocks(output, false);
1584 : }
1585 1367 : }
1586 1367 : MSDriveWay::writeDepatureBlocks(output, false);
1587 : }
1588 81314 : if (OptionsCont::getOptions().isSet("railsignal-vehicle-output")) {
1589 185 : OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-vehicle-output");
1590 599 : for (auto tls : myLogics->getAllLogics()) {
1591 414 : MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1592 414 : if (rs != nullptr) {
1593 414 : rs->writeBlocks(output, true);
1594 : }
1595 185 : }
1596 185 : MSDriveWay::writeDepatureBlocks(output, true);
1597 : }
1598 40657 : }
1599 :
1600 :
1601 : void
1602 5 : MSNet::writeOverheadWireSegmentOutput() const {
1603 : if (myStoppingPlaces.count(SUMO_TAG_OVERHEAD_WIRE_SEGMENT) > 0) {
1604 10 : OutputDevice& output = OutputDevice::getDeviceByOption("overheadwiresegments-output");
1605 53 : for (const auto& it : myStoppingPlaces.find(SUMO_TAG_OVERHEAD_WIRE_SEGMENT)->second) {
1606 48 : static_cast<MSOverheadWire*>(it.second)->writeOverheadWireSegmentOutput(output);
1607 : }
1608 : }
1609 5 : }
1610 :
1611 :
1612 : void
1613 5 : MSNet::writeSubstationOutput() const {
1614 5 : if (myTractionSubstations.size() > 0) {
1615 5 : OutputDevice& output = OutputDevice::getDeviceByOption("substations-output");
1616 10 : output.setPrecision(OptionsCont::getOptions().getInt("substations-output.precision"));
1617 13 : for (auto& it : myTractionSubstations) {
1618 8 : it->writeTractionSubstationOutput(output);
1619 : }
1620 : }
1621 5 : }
1622 :
1623 :
1624 : MSTractionSubstation*
1625 19 : MSNet::findTractionSubstation(const std::string& substationId) {
1626 22 : for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1627 22 : if ((*it)->getID() == substationId) {
1628 : return *it;
1629 : }
1630 : }
1631 : return nullptr;
1632 : }
1633 :
1634 :
1635 : MSVehicleRouter&
1636 127017 : MSNet::getRouterTT(int rngIndex, const Prohibitions& prohibited) const {
1637 127017 : if (MSGlobals::gNumSimThreads == 1) {
1638 108209 : rngIndex = 0;
1639 : }
1640 : if (myRouterTT.count(rngIndex) == 0) {
1641 1457 : const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1642 1457 : if (routingAlgorithm == "dijkstra") {
1643 1359 : myRouterTT[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, false, nullptr, true);
1644 : } else {
1645 98 : if (routingAlgorithm != "astar") {
1646 0 : WRITE_WARNINGF(TL("TraCI and Triggers cannot use routing algorithm '%'. using 'astar' instead."), routingAlgorithm);
1647 : }
1648 98 : myRouterTT[rngIndex] = new AStarRouter<MSEdge, SUMOVehicle, MSMapMatcher>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, true);
1649 : }
1650 : }
1651 127017 : myRouterTT[rngIndex]->prohibit(prohibited);
1652 127017 : return *myRouterTT[rngIndex];
1653 : }
1654 :
1655 :
1656 : MSVehicleRouter&
1657 11 : MSNet::getRouterEffort(int rngIndex, const Prohibitions& prohibited) const {
1658 11 : if (MSGlobals::gNumSimThreads == 1) {
1659 11 : rngIndex = 0;
1660 : }
1661 : if (myRouterEffort.count(rngIndex) == 0) {
1662 11 : myRouterEffort[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getEffort, &MSNet::getTravelTime, false, nullptr, true);
1663 : }
1664 11 : myRouterEffort[rngIndex]->prohibit(prohibited);
1665 11 : return *myRouterEffort[rngIndex];
1666 : }
1667 :
1668 :
1669 : MSPedestrianRouter&
1670 816010 : MSNet::getPedestrianRouter(int rngIndex, const Prohibitions& prohibited) const {
1671 816010 : if (MSGlobals::gNumSimThreads == 1) {
1672 727235 : rngIndex = 0;
1673 : }
1674 : if (myPedestrianRouter.count(rngIndex) == 0) {
1675 2812 : myPedestrianRouter[rngIndex] = new MSPedestrianRouter();
1676 : }
1677 816010 : myPedestrianRouter[rngIndex]->prohibit(prohibited);
1678 816010 : return *myPedestrianRouter[rngIndex];
1679 : }
1680 :
1681 :
1682 : MSTransportableRouter&
1683 169003 : MSNet::getIntermodalRouter(int rngIndex, const int routingMode, const Prohibitions& prohibited) const {
1684 169003 : if (MSGlobals::gNumSimThreads == 1) {
1685 : rngIndex = 0;
1686 : }
1687 169003 : const OptionsCont& oc = OptionsCont::getOptions();
1688 169003 : const int key = rngIndex * oc.getInt("thread-rngs") + routingMode;
1689 : if (myIntermodalRouter.count(key) == 0) {
1690 4188 : const int carWalk = SUMOVehicleParserHelper::parseCarWalkTransfer(oc, MSDevice_Taxi::hasFleet() || myInserter->hasTaxiFlow());
1691 3974 : const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1692 3974 : const double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1693 3974 : if (routingMode == libsumo::ROUTING_MODE_COMBINED) {
1694 0 : myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode, new FareModul());
1695 : } else {
1696 3974 : myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode);
1697 : }
1698 : }
1699 169003 : myIntermodalRouter[key]->prohibit(prohibited);
1700 169003 : return *myIntermodalRouter[key];
1701 : }
1702 :
1703 :
1704 : void
1705 42265 : MSNet::resetIntermodalRouter() const {
1706 46238 : for (auto& router : myIntermodalRouter) {
1707 3973 : delete router.second;
1708 : }
1709 : myIntermodalRouter.clear();
1710 42265 : }
1711 :
1712 :
1713 : void
1714 4940 : MSNet::adaptIntermodalRouter(MSTransportableRouter& router) {
1715 9880 : double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1716 : // add access to all parking areas
1717 : EffortCalculator* const external = router.getExternalEffort();
1718 14708 : for (const auto& stopType : myInstance->myStoppingPlaces) {
1719 : // add access to all stopping places
1720 9768 : const SumoXMLTag element = stopType.first;
1721 35991 : for (const auto& i : stopType.second) {
1722 26223 : const MSEdge* const edge = &i.second->getLane().getEdge();
1723 26223 : router.getNetwork()->addAccess(i.first, edge, i.second->getBeginLanePosition(), i.second->getEndLanePosition(),
1724 : 0., element, false, taxiWait);
1725 26223 : if (element == SUMO_TAG_BUS_STOP) {
1726 : // add access to all public transport stops
1727 12769 : for (const auto& a : i.second->getAllAccessPos()) {
1728 1166 : router.getNetwork()->addAccess(i.first, &a.lane->getEdge(), a.startPos, a.endPos, a.length, element, true, taxiWait);
1729 : }
1730 11603 : if (external != nullptr) {
1731 0 : external->addStop(router.getNetwork()->getStopEdge(i.first)->getNumericalID(), *i.second);
1732 : }
1733 : }
1734 : }
1735 : }
1736 4940 : myInstance->getInsertionControl().adaptIntermodalRouter(router);
1737 4940 : myInstance->getVehicleControl().adaptIntermodalRouter(router);
1738 : // add access to transfer from walking to taxi-use
1739 4940 : if ((router.getCarWalkTransfer() & ModeChangeOptions::TAXI_PICKUP_ANYWHERE) != 0) {
1740 65730 : for (MSEdge* edge : myInstance->getEdgeControl().getEdges()) {
1741 65482 : if ((edge->getPermissions() & SVC_PEDESTRIAN) != 0 && (edge->getPermissions() & SVC_TAXI) != 0) {
1742 22521 : router.getNetwork()->addCarAccess(edge, SVC_TAXI, taxiWait);
1743 : }
1744 : }
1745 : }
1746 4940 : }
1747 :
1748 :
1749 : bool
1750 42298 : MSNet::checkElevation() {
1751 42298 : const MSEdgeVector& edges = myEdges->getEdges();
1752 1824553 : for (MSEdgeVector::const_iterator e = edges.begin(); e != edges.end(); ++e) {
1753 3924947 : for (std::vector<MSLane*>::const_iterator i = (*e)->getLanes().begin(); i != (*e)->getLanes().end(); ++i) {
1754 2142692 : if ((*i)->getShape().hasElevation()) {
1755 : return true;
1756 : }
1757 : }
1758 : }
1759 : return false;
1760 : }
1761 :
1762 :
1763 : bool
1764 42298 : MSNet::checkWalkingarea() {
1765 1254926 : for (const MSEdge* e : myEdges->getEdges()) {
1766 1223192 : if (e->getFunction() == SumoXMLEdgeFunc::WALKINGAREA) {
1767 : return true;
1768 : }
1769 : }
1770 : return false;
1771 : }
1772 :
1773 :
1774 : bool
1775 42298 : MSNet::checkBidiEdges() {
1776 1761472 : for (const MSEdge* e : myEdges->getEdges()) {
1777 1720430 : if (e->getBidiEdge() != nullptr) {
1778 : return true;
1779 : }
1780 : }
1781 : return false;
1782 : }
1783 :
1784 : bool
1785 303 : MSNet::warnOnce(const std::string& typeAndID) {
1786 303 : if (myWarnedOnce.find(typeAndID) == myWarnedOnce.end()) {
1787 303 : myWarnedOnce[typeAndID] = true;
1788 303 : return true;
1789 : }
1790 : return false;
1791 : }
1792 :
1793 :
1794 : MSMapMatcher*
1795 35 : MSNet::getMapMatcher() const {
1796 35 : auto loader = myRouteLoaders->getFirstLoader();
1797 35 : if (loader != nullptr) {
1798 35 : return dynamic_cast<MSMapMatcher*>(loader->getRouteHandler());
1799 : } else {
1800 : return nullptr;
1801 : }
1802 : }
1803 :
1804 : void
1805 0 : MSNet::quickReload() {
1806 0 : const OptionsCont& oc = OptionsCont::getOptions();
1807 0 : clearState(string2time(oc.getString("begin")), true);
1808 0 : NLBuilder::initRandomness();
1809 : // load traffic from additional files
1810 0 : for (std::string file : oc.getStringVector("additional-files")) {
1811 : // ignore failure on parsing calibrator flow
1812 0 : MSRouteHandler rh(file, true);
1813 0 : const long before = PROGRESS_BEGIN_TIME_MESSAGE("Loading traffic from '" + file + "'");
1814 0 : if (!XMLSubSys::runParser(rh, file, false)) {
1815 0 : throw ProcessError(TLF("Loading of % failed.", file));
1816 : }
1817 0 : PROGRESS_TIME_MESSAGE(before);
1818 0 : }
1819 0 : delete myRouteLoaders;
1820 0 : myRouteLoaders = NLBuilder::buildRouteLoaderControl(OptionsCont::getOptions());
1821 0 : updateGUI();
1822 0 : }
1823 :
1824 :
1825 : SUMOTime
1826 174 : MSNet::loadState(const std::string& fileName, const bool catchExceptions) {
1827 : // load time only
1828 174 : const SUMOTime newTime = MSStateHandler::MSStateTimeHandler::getTime(fileName);
1829 : // clean up state
1830 164 : clearState(newTime);
1831 : // load state
1832 164 : MSStateHandler h(fileName, 0);
1833 164 : XMLSubSys::runParser(h, fileName, false, false, false, catchExceptions);
1834 160 : if (MsgHandler::getErrorInstance()->wasInformed()) {
1835 0 : throw ProcessError(TLF("Loading state from '%' failed.", fileName));
1836 : }
1837 : // reset route loaders
1838 160 : delete myRouteLoaders;
1839 160 : myRouteLoaders = NLBuilder::buildRouteLoaderControl(OptionsCont::getOptions());
1840 : // prevent loading errors on rewound route file
1841 160 : MSGlobals::gStateLoaded = true;
1842 :
1843 160 : updateGUI();
1844 160 : return newTime;
1845 164 : }
1846 :
1847 :
1848 : /****************************************************************************/
|