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 7094482 : MSNet::getTravelTime(const MSEdge* const e, const SUMOVehicle* const v, double t) {
168 : double value;
169 7094482 : const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
170 7093559 : if (veh != nullptr && veh->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
171 522 : return value;
172 : }
173 7093960 : if (getInstance()->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
174 177 : return value;
175 : }
176 7093783 : if (veh != nullptr) {
177 6906245 : if ((veh->getRoutingMode() & libsumo::ROUTING_MODE_AGGREGATED_CUSTOM) != 0) {
178 3508 : return MSRoutingEngine::getEffortExtra(e, v, t);
179 6902737 : } 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 6902170 : } else if (MSRoutingEngine::haveExtras()) {
186 6902170 : double tt = e->getMinimumTravelTime(v);
187 6902170 : MSRoutingEngine::applyExtras(e, v, SIMSTEP, tt);
188 6902170 : return tt;
189 : }
190 : }
191 187538 : return e->getMinimumTravelTime(v);
192 : }
193 :
194 :
195 : // ---------------------------------------------------------------------------
196 : // MSNet - methods
197 : // ---------------------------------------------------------------------------
198 : MSNet*
199 5488830777 : MSNet::getInstance(void) {
200 5488830777 : if (myInstance != nullptr) {
201 5488830732 : return myInstance;
202 : }
203 90 : throw ProcessError(TL("A network was not yet constructed."));
204 : }
205 :
206 : void
207 42871 : MSNet::initStatic() {
208 42871 : gRoutingPreferences = false;
209 42871 : MSDriveWay::init();
210 42871 : }
211 :
212 : void
213 42251 : MSNet::cleanupStatic() {
214 42251 : if (!MSGlobals::gUseMesoSim) {
215 35339 : MSVehicle::Influencer::cleanup();
216 : }
217 42251 : }
218 :
219 :
220 42871 : MSNet::MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents,
221 : MSEventControl* endOfTimestepEvents,
222 : MSEventControl* insertionEvents,
223 42871 : ShapeContainer* shapeCont):
224 42871 : myAmInterrupted(false),
225 42871 : myVehiclesMoved(0),
226 42871 : myPersonsMoved(0),
227 42871 : myHavePermissions(false),
228 42871 : myHasInternalLinks(false),
229 42871 : myJunctionHigherSpeeds(false),
230 42871 : myHasElevation(false),
231 42871 : myHasPedestrianNetwork(false),
232 42871 : myHasBidiEdges(false),
233 42871 : myEdgeDataEndTime(-1),
234 42871 : myDynamicShapeUpdater(nullptr) {
235 42871 : if (myInstance != nullptr) {
236 0 : throw ProcessError(TL("A network was already constructed."));
237 : }
238 42871 : OptionsCont& oc = OptionsCont::getOptions();
239 42871 : myStep = string2time(oc.getString("begin"));
240 42871 : myStateLoaderTime = myStep - 1,
241 42871 : myMaxTeleports = oc.getInt("max-num-teleports");
242 42871 : myLogExecutionTime = !oc.getBool("no-duration-log");
243 42871 : myLogStepNumber = !oc.getBool("no-step-log");
244 42871 : myLogStepPeriod = oc.getInt("step-log.period");
245 171484 : myInserter = new MSInsertionControl(*vc, string2time(oc.getString("max-depart-delay")), oc.getBool("eager-insert"), oc.getInt("max-num-vehicles"),
246 171484 : string2time(oc.getString("random-depart-offset")));
247 42871 : myVehicleControl = vc;
248 42871 : myDetectorControl = new MSDetectorControl();
249 42871 : myEdges = nullptr;
250 42871 : myJunctions = nullptr;
251 42871 : myRouteLoaders = nullptr;
252 42871 : myLogics = nullptr;
253 42871 : myPersonControl = nullptr;
254 42871 : myContainerControl = nullptr;
255 42871 : myEdgeWeights = nullptr;
256 42871 : myShapeContainer = shapeCont == nullptr ? new ShapeContainer() : shapeCont;
257 :
258 42871 : myBeginOfTimestepEvents = beginOfTimestepEvents;
259 42871 : myEndOfTimestepEvents = endOfTimestepEvents;
260 42871 : myInsertionEvents = insertionEvents;
261 42871 : myLanesRTree.first = false;
262 :
263 42871 : if (MSGlobals::gUseMesoSim) {
264 14024 : MSGlobals::gMesoNet = new MELoop(string2time(oc.getString("meso-recheck")));
265 : }
266 42871 : myInstance = this;
267 42871 : initStatic();
268 42871 : }
269 :
270 :
271 : void
272 42388 : 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 42388 : myEdges = edges;
281 42388 : myJunctions = junctions;
282 42388 : myRouteLoaders = routeLoaders;
283 42388 : myLogics = tlc;
284 : // save the time the network state shall be saved at
285 42388 : myStateDumpTimes = stateDumpTimes;
286 42388 : myStateDumpFiles = stateDumpFiles;
287 42388 : myStateDumpPeriod = string2time(oc.getString("save-state.period"));
288 42388 : myStateDumpPrefix = oc.getString("save-state.prefix");
289 42388 : myStateDumpSuffix = oc.getString("save-state.suffix");
290 :
291 : // initialise performance computation
292 42388 : mySimBeginMillis = SysUtils::getCurrentMillis();
293 42388 : myTraCIMillis = 0;
294 42388 : myHasInternalLinks = hasInternalLinks;
295 42388 : myJunctionHigherSpeeds = junctionHigherSpeeds;
296 42388 : myHasElevation = checkElevation();
297 42388 : myHasPedestrianNetwork = checkWalkingarea();
298 42388 : myHasBidiEdges = checkBidiEdges();
299 : myVersion = version;
300 42388 : if ((!MSGlobals::gUsingInternalLanes || !myHasInternalLinks)
301 15049 : && MSGlobals::gWeightsSeparateTurns > 0) {
302 0 : throw ProcessError(TL("Option weights.separate-turns is only supported when simulating with internal lanes"));
303 : }
304 42388 : }
305 :
306 :
307 75590 : MSNet::~MSNet() {
308 42251 : cleanupStatic();
309 : // delete controls
310 42251 : delete myJunctions;
311 42251 : delete myDetectorControl;
312 : // delete mean data
313 42251 : delete myEdges;
314 42251 : delete myInserter;
315 42251 : myInserter = nullptr;
316 42251 : delete myLogics;
317 42251 : delete myRouteLoaders;
318 42251 : if (myPersonControl != nullptr) {
319 8249 : delete myPersonControl;
320 8249 : myPersonControl = nullptr; // just to have that clear for later cleanups
321 : }
322 42251 : if (myContainerControl != nullptr) {
323 1949 : delete myContainerControl;
324 1949 : myContainerControl = nullptr; // just to have that clear for later cleanups
325 : }
326 42251 : 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 42251 : delete myShapeContainer;
332 42251 : myShapeContainer = nullptr;
333 : // delete events late so that vehicles can get rid of references first
334 42251 : delete myBeginOfTimestepEvents;
335 42251 : myBeginOfTimestepEvents = nullptr;
336 42251 : delete myEndOfTimestepEvents;
337 42251 : myEndOfTimestepEvents = nullptr;
338 42251 : delete myInsertionEvents;
339 42251 : myInsertionEvents = nullptr;
340 42251 : delete myEdgeWeights;
341 43708 : for (auto& router : myRouterTT) {
342 1457 : delete router.second;
343 : }
344 : myRouterTT.clear();
345 42262 : for (auto& router : myRouterEffort) {
346 11 : delete router.second;
347 : }
348 : myRouterEffort.clear();
349 45079 : for (auto& router : myPedestrianRouter) {
350 2828 : delete router.second;
351 : }
352 : myPedestrianRouter.clear();
353 42251 : resetIntermodalRouter();
354 : myLanesRTree.second.RemoveAll();
355 42268 : for (MSTractionSubstation* sub : myTractionSubstations) {
356 17 : delete sub;
357 : }
358 : myTractionSubstations.clear();
359 42251 : clearAll();
360 42251 : if (MSGlobals::gUseMesoSim) {
361 6912 : delete MSGlobals::gMesoNet;
362 : }
363 42251 : myInstance = nullptr;
364 160092 : }
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 2161274 : MSNet::getRestrictions(const std::string& id) const {
375 : std::map<std::string, std::map<SUMOVehicleClass, double> >::const_iterator i = myRestrictions.find(id);
376 2161274 : 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 927140 : MSNet::getMesoType(const std::string& typeID) {
433 : if (myMesoEdgeTypes.count(typeID) == 0) {
434 : // init defaults
435 7524 : const OptionsCont& oc = OptionsCont::getOptions();
436 : MESegment::MesoEdgeType edgeType;
437 7524 : edgeType.tauff = string2time(oc.getString("meso-tauff"));
438 7524 : edgeType.taufj = string2time(oc.getString("meso-taufj"));
439 7524 : edgeType.taujf = string2time(oc.getString("meso-taujf"));
440 7524 : edgeType.taujj = string2time(oc.getString("meso-taujj"));
441 7524 : edgeType.jamThreshold = oc.getFloat("meso-jam-threshold");
442 7524 : edgeType.junctionControl = oc.getBool("meso-junction-control");
443 7524 : edgeType.tlsPenalty = oc.getFloat("meso-tls-penalty");
444 7524 : edgeType.tlsFlowPenalty = oc.getFloat("meso-tls-flow-penalty");
445 7524 : edgeType.minorPenalty = string2time(oc.getString("meso-minor-penalty"));
446 7524 : edgeType.overtaking = oc.getBool("meso-overtaking");
447 7524 : edgeType.edgeLength = oc.getFloat("meso-edgelength");
448 7524 : myMesoEdgeTypes[typeID] = edgeType;
449 : }
450 927140 : return myMesoEdgeTypes[typeID];
451 : }
452 :
453 :
454 : bool
455 7336689 : MSNet::hasFlow(const std::string& id) const {
456 : // inserter is deleted at the end of the simulation
457 7336689 : return myInserter != nullptr && myInserter->hasFlow(id);
458 : }
459 :
460 :
461 : MSNet::SimulationState
462 31913 : MSNet::simulate(SUMOTime start, SUMOTime stop) {
463 : // report the begin when wished
464 63826 : 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 31913 : myStep = start;
469 : int numSteps = 0;
470 : bool doStepLog = false;
471 51952941 : while (state == SIMSTATE_RUNNING) {
472 51921429 : doStepLog = myLogStepNumber && (numSteps % myLogStepPeriod == 0);
473 : if (doStepLog) {
474 110 : preSimStepOutput();
475 : }
476 51921429 : simulationStep();
477 51921028 : if (doStepLog) {
478 110 : postSimStepOutput();
479 : }
480 51921028 : 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 51921028 : numSteps++;
487 : }
488 31512 : if (myLogStepNumber && !doStepLog) {
489 : // ensure some output on the last step
490 17 : preSimStepOutput();
491 17 : postSimStepOutput();
492 : }
493 : // exit simulation loop
494 31512 : if (myLogStepNumber) {
495 : // start new line for final verbose output
496 20 : std::cout << "\n";
497 : }
498 31512 : closeSimulation(start, getStateMessage(state));
499 31512 : return state;
500 : }
501 :
502 :
503 : void
504 65205444 : MSNet::loadRoutes() {
505 65205444 : myRouteLoaders->loadNext(myStep);
506 65204858 : }
507 :
508 :
509 : const std::string
510 13300 : MSNet::generateStatistics(const SUMOTime start, const long now) {
511 13300 : std::ostringstream msg;
512 13300 : if (myLogExecutionTime) {
513 12922 : const long duration = now - mySimBeginMillis;
514 : // print performance notice
515 25844 : msg << "Performance:\n" << " Duration: " << elapsedMs2string(duration) << "\n";
516 12922 : if (duration != 0) {
517 12763 : if (TraCIServer::getInstance() != nullptr) {
518 4311 : msg << " TraCI-Duration: " << elapsedMs2string(myTraCIMillis) << "\n";
519 : }
520 12763 : 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 12763 : msg << " UPS: " << ((double)myVehiclesMoved / ((double)duration / 1000)) << "\n";
524 12763 : if (myPersonsMoved > 0) {
525 2373 : msg << " UPS-Persons: " << ((double)myPersonsMoved / ((double)duration / 1000)) << "\n";
526 : }
527 : }
528 : // print vehicle statistics
529 12922 : const std::string vehDiscardNotice = ((myVehicleControl->getLoadedVehicleNo() != myVehicleControl->getDepartedVehicleNo()) ?
530 17083 : " (Loaded: " + toString(myVehicleControl->getLoadedVehicleNo()) + ")" : "");
531 : msg << "Vehicles:\n"
532 12922 : << " Inserted: " << myVehicleControl->getDepartedVehicleNo() << vehDiscardNotice << "\n"
533 25844 : << " Running: " << myVehicleControl->getRunningVehicleNo() << "\n"
534 25844 : << " Waiting: " << myInserter->getWaitingVehicleNo() << "\n";
535 :
536 12922 : if (myVehicleControl->getTeleportCount() > 0 || myVehicleControl->getCollisionCount() > 0) {
537 : // print optional teleport statistics
538 : std::vector<std::string> reasons;
539 714 : if (myVehicleControl->getCollisionCount() > 0) {
540 652 : reasons.push_back("Collisions: " + toString(myVehicleControl->getCollisionCount()));
541 : }
542 714 : if (myVehicleControl->getTeleportsJam() > 0) {
543 518 : reasons.push_back("Jam: " + toString(myVehicleControl->getTeleportsJam()));
544 : }
545 714 : if (myVehicleControl->getTeleportsYield() > 0) {
546 282 : reasons.push_back("Yield: " + toString(myVehicleControl->getTeleportsYield()));
547 : }
548 714 : if (myVehicleControl->getTeleportsWrongLane() > 0) {
549 278 : reasons.push_back("Wrong Lane: " + toString(myVehicleControl->getTeleportsWrongLane()));
550 : }
551 2142 : msg << " Teleports: " << myVehicleControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
552 714 : }
553 12922 : if (myVehicleControl->getEmergencyStops() > 0) {
554 70 : msg << " Emergency Stops: " << myVehicleControl->getEmergencyStops() << "\n";
555 : }
556 12922 : if (myVehicleControl->getEmergencyBrakingCount() > 0) {
557 298 : msg << " Emergency Braking: " << myVehicleControl->getEmergencyBrakingCount() << "\n";
558 : }
559 12922 : 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 12922 : 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 26600 : if (OptionsCont::getOptions().getBool("duration-log.statistics")) {
601 6892 : msg << MSDevice_Tripinfo::printStatistics();
602 : }
603 : std::string result = msg.str();
604 : result.erase(result.end() - 1);
605 13300 : return result;
606 13300 : }
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 378 : MSNet::writeStatistics(const SUMOTime start, const long now) const {
640 378 : const long duration = now - mySimBeginMillis;
641 378 : OutputDevice& od = OutputDevice::getDeviceByOption("statistic-output");
642 378 : od.openTag("performance");
643 378 : od.writeAttr("clockBegin", time2string(mySimBeginMillis));
644 378 : od.writeAttr("clockEnd", time2string(now));
645 378 : od.writeAttr("clockDuration", time2string(duration));
646 378 : od.writeAttr("traciDuration", time2string(myTraCIMillis));
647 378 : od.writeAttr("realTimeFactor", duration != 0 ? (double)(myStep - start) / (double)duration : -1);
648 378 : od.writeAttr("vehicleUpdatesPerSecond", duration != 0 ? (double)myVehiclesMoved / ((double)duration / 1000) : -1);
649 378 : od.writeAttr("personUpdatesPerSecond", duration != 0 ? (double)myPersonsMoved / ((double)duration / 1000) : -1);
650 378 : od.writeAttr("begin", time2string(start));
651 378 : od.writeAttr("end", time2string(myStep));
652 378 : od.writeAttr("duration", time2string(myStep - start));
653 378 : od.closeTag();
654 378 : od.openTag("vehicles");
655 378 : od.writeAttr("loaded", myVehicleControl->getLoadedVehicleNo());
656 378 : od.writeAttr("inserted", myVehicleControl->getDepartedVehicleNo());
657 378 : od.writeAttr("running", myVehicleControl->getRunningVehicleNo());
658 378 : od.writeAttr("waiting", myInserter->getWaitingVehicleNo());
659 378 : od.closeTag();
660 378 : od.openTag("teleports");
661 378 : od.writeAttr("total", myVehicleControl->getTeleportCount());
662 378 : od.writeAttr("jam", myVehicleControl->getTeleportsJam());
663 378 : od.writeAttr("yield", myVehicleControl->getTeleportsYield());
664 378 : od.writeAttr("wrongLane", myVehicleControl->getTeleportsWrongLane());
665 378 : od.closeTag();
666 378 : od.openTag("safety");
667 378 : od.writeAttr("collisions", myVehicleControl->getCollisionCount());
668 378 : od.writeAttr("emergencyStops", myVehicleControl->getEmergencyStops());
669 378 : od.writeAttr("emergencyBraking", myVehicleControl->getEmergencyBrakingCount());
670 378 : od.closeTag();
671 378 : od.openTag("persons");
672 384 : od.writeAttr("loaded", myPersonControl != nullptr ? myPersonControl->getLoadedNumber() : 0);
673 384 : od.writeAttr("running", myPersonControl != nullptr ? myPersonControl->getRunningNumber() : 0);
674 384 : od.writeAttr("jammed", myPersonControl != nullptr ? myPersonControl->getJammedNumber() : 0);
675 378 : od.closeTag();
676 378 : od.openTag("personTeleports");
677 384 : od.writeAttr("total", myPersonControl != nullptr ? myPersonControl->getTeleportCount() : 0);
678 384 : od.writeAttr("abortWait", myPersonControl != nullptr ? myPersonControl->getTeleportsAbortWait() : 0);
679 384 : od.writeAttr("wrongDest", myPersonControl != nullptr ? myPersonControl->getTeleportsWrongDest() : 0);
680 378 : od.closeTag();
681 601 : if (OptionsCont::getOptions().isSet("tripinfo-output") || OptionsCont::getOptions().getBool("duration-log.statistics")) {
682 264 : MSDevice_Tripinfo::writeStatistics(od);
683 : }
684 378 : }
685 :
686 :
687 : void
688 65204209 : MSNet::writeSummaryOutput(bool finalStep) {
689 : // summary output
690 65204209 : const OptionsCont& oc = OptionsCont::getOptions();
691 65204209 : const bool hasOutput = oc.isSet("summary-output");
692 65204209 : const bool hasPersonOutput = oc.isSet("person-summary-output");
693 65204209 : 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 65202766 : 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 40739 : MSNet::closeSimulation(SUMOTime start, const std::string& reason) {
757 : // report the end when wished
758 81478 : WRITE_MESSAGE(TLF("Simulation ended at time: %.", time2string(getCurrentTimeStep())));
759 40739 : if (reason != "") {
760 80606 : WRITE_MESSAGE(TL("Reason: ") + reason);
761 : }
762 40739 : myDetectorControl->close(myStep);
763 81478 : if (OptionsCont::getOptions().isSet("queue-output")) {
764 358 : MSQueueExport::finish(OutputDevice::getDeviceByOption("queue-output"), myStep);
765 : }
766 42201 : if (MSStopOut::active() && OptionsCont::getOptions().getBool("stop-output.write-unfinished")) {
767 121 : MSStopOut::getInstance()->generateOutputForUnfinished();
768 : }
769 40739 : MSDevice_Vehroutes::writePendingOutput(OptionsCont::getOptions().getBool("vehroute-output.write-unfinished"));
770 81478 : if (OptionsCont::getOptions().getBool("tripinfo-output.write-unfinished")) {
771 1110 : MSDevice_Tripinfo::generateOutputForUnfinished();
772 : }
773 81478 : if (OptionsCont::getOptions().isSet("chargingstations-output")) {
774 252 : if (!OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
775 106 : 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 81478 : if (OptionsCont::getOptions().isSet("overheadwiresegments-output")) {
781 5 : writeOverheadWireSegmentOutput();
782 : }
783 81478 : if (OptionsCont::getOptions().isSet("substations-output")) {
784 5 : writeSubstationOutput();
785 : }
786 40739 : writeRailSignalBlocks();
787 40739 : const long now = SysUtils::getCurrentMillis();
788 68556 : if (myLogExecutionTime || OptionsCont::getOptions().getBool("duration-log.statistics")) {
789 26600 : WRITE_MESSAGE(generateStatistics(start, now));
790 : }
791 81478 : if (OptionsCont::getOptions().isSet("statistic-output")) {
792 378 : writeStatistics(start, now);
793 : }
794 : // maybe write a final line of output if reporting is periodic
795 40739 : writeSummaryOutput(true);
796 40739 : }
797 :
798 :
799 : void
800 65166652 : MSNet::simulationStep(const bool onlyMove) {
801 65166652 : 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 65166648 : if (t != nullptr) {
814 10409005 : if (myLogExecutionTime) {
815 10212036 : myTraCIStepDuration = SysUtils::getCurrentMillis();
816 : }
817 10409005 : 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 10408900 : if (myLogExecutionTime) {
823 10211958 : myTraCIStepDuration = SysUtils::getCurrentMillis() - myTraCIStepDuration;
824 : }
825 10408900 : 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 65163888 : if (myLogExecutionTime) {
834 27418996 : mySimStepDuration = SysUtils::getCurrentMillis();
835 : }
836 : // simulation state output
837 65163888 : std::vector<SUMOTime>::iterator timeIt = std::find(myStateDumpTimes.begin(), myStateDumpTimes.end(), myStep);
838 65163888 : if (timeIt != myStateDumpTimes.end()) {
839 375 : const int dist = (int)distance(myStateDumpTimes.begin(), timeIt);
840 375 : MSStateHandler::saveState(myStateDumpFiles[dist], myStep);
841 : }
842 65163888 : 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 65163888 : myBeginOfTimestepEvents->execute(myStep);
855 65163880 : if (MSRailSignalControl::hasInstance()) {
856 8555288 : MSRailSignalControl::getInstance().updateSignals(myStep);
857 : }
858 : #ifdef HAVE_FOX
859 65163880 : MSRoutingEngine::waitForAll();
860 : #endif
861 65163880 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
862 43890637 : myEdges->detectCollisions(myStep, STAGE_EVENTS);
863 : }
864 : // check whether the tls programs need to be switched
865 65163880 : myLogics->check2Switch(myStep);
866 :
867 65163880 : if (MSGlobals::gUseMesoSim) {
868 21273243 : MSGlobals::gMesoNet->simulate(myStep);
869 : } else {
870 : // assure all lanes with vehicles are 'active'
871 43890637 : myEdges->patchActiveLanes();
872 :
873 : // compute safe velocities for all vehicles for the next few lanes
874 : // also register ApproachingVehicleInformation for all links
875 43890637 : myEdges->planMovements(myStep);
876 :
877 : // register junction approaches based on planned velocities as basis for right-of-way decision
878 43890637 : myEdges->setJunctionApproaches();
879 :
880 : // decide right-of-way and execute movements
881 43890637 : myEdges->executeMovements(myStep);
882 43890634 : if (MSGlobals::gCheck4Accidents) {
883 43890634 : myEdges->detectCollisions(myStep, STAGE_MOVEMENTS);
884 : }
885 :
886 : // vehicles may change lanes
887 43890634 : myEdges->changeLanes(myStep);
888 :
889 43890634 : if (MSGlobals::gCheck4Accidents) {
890 43890634 : myEdges->detectCollisions(myStep, STAGE_LANECHANGE);
891 : }
892 : }
893 : // flush arrived meso vehicles and micro vehicles that were removed due to collision
894 65163877 : myVehicleControl->removePending();
895 65163877 : loadRoutes();
896 :
897 : // persons
898 65163861 : if (myPersonControl != nullptr && myPersonControl->hasTransportables()) {
899 5437223 : myPersonControl->checkWaiting(this, myStep);
900 : }
901 : // containers
902 65163805 : if (myContainerControl != nullptr && myContainerControl->hasTransportables()) {
903 4415365 : myContainerControl->checkWaiting(this, myStep);
904 : }
905 65163805 : if (MSRailSignalControl::hasInstance()) {
906 8555288 : MSRailSignalControl::getInstance().resetWaitRelations();
907 : // preserve waitRelation from insertion for the next step
908 : }
909 : // insert vehicles
910 65163805 : myInserter->determineCandidates(myStep);
911 65163758 : myInsertionEvents->execute(myStep);
912 : #ifdef HAVE_FOX
913 65163664 : MSRoutingEngine::waitForAll();
914 : #endif
915 65163640 : myInserter->emitVehicles(myStep);
916 65163495 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
917 : //myEdges->patchActiveLanes(); // @note required to detect collisions on lanes that were empty before insertion. wasteful?
918 43890358 : myEdges->detectCollisions(myStep, STAGE_INSERTIONS);
919 : }
920 65163495 : MSVehicleTransfer::getInstance()->checkInsertions(myStep);
921 :
922 : // execute endOfTimestepEvents
923 65163495 : myEndOfTimestepEvents->execute(myStep);
924 :
925 65163485 : if (myLogExecutionTime) {
926 27418823 : myTraCIStepDuration -= SysUtils::getCurrentMillis();
927 : }
928 65163485 : if (onlyMove) {
929 4 : myStepCompletionMissing = true;
930 4 : return;
931 : }
932 65163481 : if (t != nullptr && lastTraCICmd == libsumo::CMD_EXECUTEMOVE) {
933 6 : t->processCommands(myStep, true);
934 : }
935 65163481 : postMoveStep();
936 : }
937 :
938 :
939 : void
940 65163485 : MSNet::postMoveStep() {
941 65163485 : const int numControlled = libsumo::Helper::postProcessRemoteControl();
942 65163485 : if (numControlled > 0 && MSGlobals::gCheck4Accidents) {
943 1897037 : myEdges->detectCollisions(myStep, STAGE_REMOTECONTROL);
944 : }
945 65163485 : if (myLogExecutionTime) {
946 27418823 : myTraCIStepDuration += SysUtils::getCurrentMillis();
947 27418823 : myTraCIMillis += myTraCIStepDuration;
948 : }
949 65163485 : 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 43890353 : removeOutdatedCollisions();
953 : }
954 : // update and write (if needed) detector values
955 65163485 : mySimStepDuration = SysUtils::getCurrentMillis() - mySimStepDuration;
956 65163485 : writeOutput();
957 :
958 65163469 : if (myLogExecutionTime) {
959 27418823 : myVehiclesMoved += myVehicleControl->getRunningVehicleNo();
960 27418823 : if (myPersonControl != nullptr) {
961 4631844 : myPersonsMoved += myPersonControl->getRunningNumber();
962 : }
963 : }
964 65163469 : myStep += DELTA_T;
965 65163469 : }
966 :
967 :
968 : MSNet::SimulationState
969 65067689 : MSNet::simulationState(SUMOTime stopTime) const {
970 65067689 : if (TraCIServer::wasClosed()) {
971 : return SIMSTATE_CONNECTION_CLOSED;
972 : }
973 65064911 : if (TraCIServer::getInstance() != nullptr && !TraCIServer::getInstance()->getLoadArgs().empty()) {
974 : return SIMSTATE_LOADING;
975 : }
976 65064898 : if ((stopTime < 0 || myStep > stopTime) && TraCIServer::getInstance() == nullptr && (stopTime > 0 || myStep > myEdgeDataEndTime)) {
977 33229748 : if ((myVehicleControl->getActiveVehicleCount() == 0)
978 6145371 : && (myInserter->getPendingFlowCount() == 0)
979 1951969 : && (myPersonControl == nullptr || !myPersonControl->hasNonWaiting())
980 412754 : && (myContainerControl == nullptr || !myContainerControl->hasNonWaiting())
981 33293288 : && !MSDevice_Taxi::hasServableReservations()) {
982 : return SIMSTATE_NO_FURTHER_VEHICLES;
983 : }
984 : }
985 65018224 : if (stopTime >= 0 && myStep >= stopTime) {
986 : return SIMSTATE_END_STEP_REACHED;
987 : }
988 64997127 : if (myMaxTeleports >= 0 && myVehicleControl->getTeleportCount() > myMaxTeleports) {
989 : return SIMSTATE_TOO_MANY_TELEPORTS;
990 : }
991 64997119 : if (myAmInterrupted) {
992 5 : return SIMSTATE_INTERRUPTED;
993 : }
994 : return SIMSTATE_RUNNING;
995 : }
996 :
997 :
998 : MSNet::SimulationState
999 65059068 : MSNet::adaptToState(MSNet::SimulationState state, const bool isLibsumo) const {
1000 65059068 : if (state == SIMSTATE_LOADING) {
1001 13 : OptionsIO::setArgs(TraCIServer::getInstance()->getLoadArgs());
1002 : TraCIServer::getInstance()->getLoadArgs().clear();
1003 65059055 : } 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 23062 : return SIMSTATE_RUNNING;
1006 65035993 : } else if (state == SIMSTATE_NO_FURTHER_VEHICLES) {
1007 28415 : if (myPersonControl != nullptr) {
1008 6888 : myPersonControl->abortAnyWaitingForVehicle();
1009 : }
1010 28415 : if (myContainerControl != nullptr) {
1011 1862 : myContainerControl->abortAnyWaitingForVehicle();
1012 : }
1013 28415 : myVehicleControl->abortWaiting();
1014 : }
1015 : return state;
1016 : }
1017 :
1018 :
1019 : std::string
1020 40133 : MSNet::getStateMessage(MSNet::SimulationState state) {
1021 40133 : switch (state) {
1022 : case MSNet::SIMSTATE_RUNNING:
1023 436 : return "";
1024 : case MSNet::SIMSTATE_END_STEP_REACHED:
1025 8251 : return TL("The final simulation step has been reached.");
1026 : case MSNet::SIMSTATE_NO_FURTHER_VEHICLES:
1027 28780 : 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 42542 : MSNet::clearAll() {
1046 : // clear container
1047 42542 : MSEdge::clear();
1048 42542 : MSLane::clear();
1049 42542 : MSRoute::clear();
1050 42542 : delete MSVehicleTransfer::getInstance();
1051 42542 : MSDevice::cleanupAll();
1052 42542 : MSCalibrator::cleanup();
1053 85584 : while (!MSLaneSpeedTrigger::getInstances().empty()) {
1054 500 : delete MSLaneSpeedTrigger::getInstances().begin()->second;
1055 : }
1056 46678 : while (!MSTriggeredRerouter::getInstances().empty()) {
1057 4136 : delete MSTriggeredRerouter::getInstances().begin()->second;
1058 : }
1059 42542 : MSDevice_BTsender::cleanup();
1060 42542 : MSDevice_SSM::cleanup();
1061 42542 : MSDevice_ToC::cleanup();
1062 42542 : MSStopOut::cleanup();
1063 42542 : MSRailSignalConstraint::cleanup();
1064 42542 : MSRailSignalControl::cleanup();
1065 42542 : MSDriveWay::cleanup();
1066 : TraCIServer* t = TraCIServer::getInstance();
1067 42542 : if (t != nullptr) {
1068 2761 : t->cleanup();
1069 : }
1070 42542 : libsumo::Helper::cleanup();
1071 42542 : OutputDevice::closeAll(true);
1072 42542 : }
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 711 : MSNet::setLoaderTime(SUMOTime time) {
1136 711 : myRouteLoaders->setCurrentLoadTime(time);
1137 711 : myStateLoaderTime = MAX2(myStateLoaderTime, time);
1138 711 : }
1139 :
1140 : void
1141 65163485 : MSNet::writeOutput() {
1142 : // update detector values
1143 65163485 : myDetectorControl->updateDetectors(myStep);
1144 65163476 : const OptionsCont& oc = OptionsCont::getOptions();
1145 :
1146 : // check state dumps
1147 130326952 : 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 130326952 : if (OptionsCont::getOptions().isSet("fcd-output")) {
1154 13127698 : 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 13127650 : MSFCDExport::write(OutputDevice::getDeviceByOption("fcd-output"), myStep);
1159 : }
1160 : }
1161 :
1162 : // check emission dumps
1163 130326952 : if (OptionsCont::getOptions().isSet("emission-output")) {
1164 215992 : MSEmissionExport::write(OutputDevice::getDeviceByOption("emission-output"), myStep);
1165 : }
1166 :
1167 : // battery dumps
1168 130326952 : if (OptionsCont::getOptions().isSet("battery-output")) {
1169 148254 : MSBatteryExport::write(OutputDevice::getDeviceByOption("battery-output"), myStep,
1170 : oc.getInt("battery-output.precision"));
1171 : }
1172 :
1173 : // charging station aggregated dumps
1174 65254590 : 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 130326952 : 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 130326952 : 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 130326952 : if (OptionsCont::getOptions().isSet("queue-output")) {
1219 330534 : MSQueueExport::write(OutputDevice::getDeviceByOption("queue-output"), myStep);
1220 : }
1221 :
1222 : // check amitran dumps
1223 130326952 : if (OptionsCont::getOptions().isSet("amitran-output")) {
1224 2040 : MSAmitranTrajectories::write(OutputDevice::getDeviceByOption("amitran-output"), myStep);
1225 : }
1226 :
1227 : // check vtk dumps
1228 130326952 : 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 65163470 : writeSummaryOutput();
1250 :
1251 : // write detector values
1252 65163470 : myDetectorControl->writeOutput(myStep + DELTA_T, false);
1253 :
1254 : // write link states
1255 130326938 : 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 67696476 : for (MSDevice_SSM* dev : MSDevice_SSM::getInstances()) {
1271 2533007 : dev->updateAndWriteOutput();
1272 : }
1273 :
1274 : // write ToC output
1275 65179188 : for (MSDevice_ToC* dev : MSDevice_ToC::getInstances()) {
1276 15719 : if (dev->generatesOutput()) {
1277 15513 : dev->writeOutput();
1278 : }
1279 : }
1280 :
1281 130326938 : if (OptionsCont::getOptions().isSet("collision-output")) {
1282 10356 : writeCollisions();
1283 : }
1284 65163469 : }
1285 :
1286 :
1287 : bool
1288 0 : MSNet::logSimulationDuration() const {
1289 0 : return myLogExecutionTime;
1290 : }
1291 :
1292 :
1293 : MSTransportableControl&
1294 28305036 : MSNet::getPersonControl() {
1295 28305036 : if (myPersonControl == nullptr) {
1296 6694 : myPersonControl = new MSTransportableControl(true);
1297 : }
1298 28305012 : return *myPersonControl;
1299 : }
1300 :
1301 :
1302 : MSTransportableControl&
1303 8008922 : MSNet::getContainerControl() {
1304 8008922 : if (myContainerControl == nullptr) {
1305 1782 : myContainerControl = new MSTransportableControl(false);
1306 : }
1307 8008922 : return *myContainerControl;
1308 : }
1309 :
1310 : MSDynamicShapeUpdater*
1311 23 : MSNet::makeDynamicShapeUpdater() {
1312 23 : myDynamicShapeUpdater = std::unique_ptr<MSDynamicShapeUpdater> (new MSDynamicShapeUpdater(*myShapeContainer));
1313 23 : return myDynamicShapeUpdater.get();
1314 : }
1315 :
1316 : MSEdgeWeightsStorage&
1317 7094583 : MSNet::getWeightsStorage() {
1318 7094583 : if (myEdgeWeights == nullptr) {
1319 1968 : myEdgeWeights = new MSEdgeWeightsStorage();
1320 : }
1321 7094583 : 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 77 : const double durationSec = (double)mySimStepDuration / 1000.;
1340 77 : oss << " (" << mySimStepDuration << "ms ~= "
1341 77 : << (TS / durationSec) << "*RT, ~"
1342 77 : << ((double) myVehicleControl->getRunningVehicleNo() / durationSec);
1343 : } else {
1344 48 : 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 11600 : MSNet::addVehicleStateListener(VehicleStateListener* listener) {
1363 11600 : if (find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener) == myVehicleStateListeners.end()) {
1364 11600 : myVehicleStateListeners.push_back(listener);
1365 : }
1366 11600 : }
1367 :
1368 :
1369 : void
1370 58 : MSNet::removeVehicleStateListener(VehicleStateListener* listener) {
1371 58 : std::vector<VehicleStateListener*>::iterator i = std::find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener);
1372 58 : if (i != myVehicleStateListeners.end()) {
1373 58 : myVehicleStateListeners.erase(i);
1374 : }
1375 58 : }
1376 :
1377 :
1378 : void
1379 15981746 : MSNet::informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info) {
1380 : #ifdef HAVE_FOX
1381 15981746 : ScopedLocker<> lock(myVehicleStateListenerMutex, MSGlobals::gNumThreads > 1);
1382 : #endif
1383 16673541 : for (VehicleStateListener* const listener : myVehicleStateListeners) {
1384 691795 : listener->vehicleStateChanged(vehicle, to, info);
1385 : }
1386 15981746 : }
1387 :
1388 :
1389 : void
1390 3911 : MSNet::addTransportableStateListener(TransportableStateListener* listener) {
1391 3911 : if (find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener) == myTransportableStateListeners.end()) {
1392 3911 : myTransportableStateListeners.push_back(listener);
1393 : }
1394 3911 : }
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 1009207 : MSNet::informTransportableStateListener(const MSTransportable* const transportable, TransportableState to, const std::string& info) {
1408 : #ifdef HAVE_FOX
1409 1009207 : ScopedLocker<> lock(myTransportableStateListenerMutex, MSGlobals::gNumThreads > 1);
1410 : #endif
1411 1012010 : for (TransportableStateListener* const listener : myTransportableStateListeners) {
1412 2803 : listener->transportableStateChanged(transportable, to, info);
1413 : }
1414 1009207 : }
1415 :
1416 :
1417 : bool
1418 17694 : 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 17694 : if (it != myCollisions.end()) {
1421 8510 : for (Collision& old : it->second) {
1422 8405 : if (old.victim == victim->getID()) {
1423 : // collision from previous step continues
1424 7627 : 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 9962 : if (it2 != myCollisions.end()) {
1432 3951 : for (Collision& old : it2->second) {
1433 3775 : if (old.victim == collider->getID()) {
1434 : // collision from previous step continues (keep the old roles)
1435 3596 : old.continuationTime = myStep;
1436 : return false;
1437 : }
1438 : }
1439 : }
1440 : }
1441 : Collision c;
1442 : c.victim = victim->getID();
1443 6471 : c.colliderType = collider->getVehicleType().getID();
1444 6471 : c.victimType = victim->getVehicleType().getID();
1445 6471 : c.colliderSpeed = collider->getSpeed();
1446 6471 : c.victimSpeed = victim->getSpeed();
1447 6471 : c.colliderFront = collider->getPosition();
1448 6471 : c.victimFront = victim->getPosition();
1449 6471 : c.colliderBack = collider->getPosition(-collider->getVehicleType().getLength());
1450 6471 : c.victimBack = victim->getPosition(-victim->getVehicleType().getLength());
1451 : c.type = collisionType;
1452 6471 : c.lane = lane;
1453 6471 : c.pos = pos;
1454 6471 : c.time = myStep;
1455 6471 : c.continuationTime = myStep;
1456 6471 : myCollisions[collider->getID()].push_back(c);
1457 : return true;
1458 6471 : }
1459 :
1460 :
1461 : void
1462 43890353 : MSNet::removeOutdatedCollisions() {
1463 43908697 : for (auto it = myCollisions.begin(); it != myCollisions.end();) {
1464 36914 : for (auto it2 = it->second.begin(); it2 != it->second.end();) {
1465 18570 : if (it2->continuationTime != myStep) {
1466 6460 : it2 = it->second.erase(it2);
1467 : } else {
1468 : it2++;
1469 : }
1470 : }
1471 18344 : if (it->second.size() == 0) {
1472 : it = myCollisions.erase(it);
1473 : } else {
1474 : it++;
1475 : }
1476 : }
1477 43890353 : }
1478 :
1479 :
1480 : bool
1481 83897 : MSNet::addStoppingPlace(SumoXMLTag category, MSStoppingPlace* stop) {
1482 83897 : if (category == SUMO_TAG_TRAIN_STOP) {
1483 14049 : category = SUMO_TAG_BUS_STOP;
1484 : }
1485 83897 : const bool isNew = myStoppingPlaces[category].add(stop->getID(), stop);
1486 83897 : if (isNew && stop->getMyName() != "") {
1487 15969 : myNamedStoppingPlaces[category][stop->getMyName()].push_back(stop);
1488 : }
1489 83897 : 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 1596794 : 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 172446 : MSNet::getStoppingPlace(const std::string& id) const {
1514 854759 : 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 718807 : MSStoppingPlace* result = getStoppingPlace(id, category);
1516 718807 : if (result != nullptr) {
1517 : return result;
1518 : }
1519 172446 : }
1520 135952 : return nullptr;
1521 : }
1522 :
1523 :
1524 : std::string
1525 465942 : MSNet::getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const {
1526 : if (myStoppingPlaces.count(category) > 0) {
1527 955672 : for (const auto& it : myStoppingPlaces.find(category)->second) {
1528 875373 : MSStoppingPlace* stop = it.second;
1529 875373 : if (&stop->getLane() == lane && stop->getBeginLanePosition() - POSITION_EPS <= pos && stop->getEndLanePosition() + POSITION_EPS >= pos) {
1530 : return stop->getID();
1531 : }
1532 : }
1533 : }
1534 359997 : 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 106 : MSNet::writeChargingStationOutput() const {
1567 : if (myStoppingPlaces.count(SUMO_TAG_CHARGING_STATION) > 0) {
1568 204 : OutputDevice& output = OutputDevice::getDeviceByOption("chargingstations-output");
1569 586 : for (const auto& it : myStoppingPlaces.find(SUMO_TAG_CHARGING_STATION)->second) {
1570 484 : static_cast<MSChargingStation*>(it.second)->writeChargingStationOutput(output);
1571 : }
1572 : }
1573 106 : }
1574 :
1575 :
1576 : void
1577 40739 : MSNet::writeRailSignalBlocks() const {
1578 81478 : if (OptionsCont::getOptions().isSet("railsignal-block-output")) {
1579 1366 : OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-block-output");
1580 5419 : 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 1366 : }
1586 1366 : MSDriveWay::writeDepatureBlocks(output, false);
1587 : }
1588 81478 : 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 40739 : }
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 126838 : MSNet::getRouterTT(int rngIndex, const Prohibitions& prohibited) const {
1637 126838 : if (MSGlobals::gNumSimThreads == 1) {
1638 107992 : rngIndex = 0;
1639 : }
1640 : if (myRouterTT.count(rngIndex) == 0) {
1641 1458 : const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1642 1458 : if (routingAlgorithm == "dijkstra") {
1643 1360 : 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 126838 : myRouterTT[rngIndex]->prohibit(prohibited);
1652 126838 : 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 815853 : MSNet::getPedestrianRouter(int rngIndex, const Prohibitions& prohibited) const {
1671 815853 : if (MSGlobals::gNumSimThreads == 1) {
1672 726838 : rngIndex = 0;
1673 : }
1674 : if (myPedestrianRouter.count(rngIndex) == 0) {
1675 2828 : myPedestrianRouter[rngIndex] = new MSPedestrianRouter();
1676 : }
1677 815853 : myPedestrianRouter[rngIndex]->prohibit(prohibited);
1678 815853 : return *myPedestrianRouter[rngIndex];
1679 : }
1680 :
1681 :
1682 : MSTransportableRouter&
1683 168917 : MSNet::getIntermodalRouter(int rngIndex, const int routingMode, const Prohibitions& prohibited) const {
1684 168917 : if (MSGlobals::gNumSimThreads == 1) {
1685 : rngIndex = 0;
1686 : }
1687 168917 : const OptionsCont& oc = OptionsCont::getOptions();
1688 168917 : const int key = rngIndex * oc.getInt("thread-rngs") + routingMode;
1689 : if (myIntermodalRouter.count(key) == 0) {
1690 4217 : const int carWalk = SUMOVehicleParserHelper::parseCarWalkTransfer(oc, MSDevice_Taxi::hasFleet() || myInserter->hasTaxiFlow());
1691 4000 : const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1692 4000 : const double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1693 4000 : if (routingMode == libsumo::ROUTING_MODE_COMBINED) {
1694 0 : myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode, new FareModul());
1695 : } else {
1696 4000 : myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode);
1697 : }
1698 : }
1699 168917 : myIntermodalRouter[key]->prohibit(prohibited);
1700 168917 : return *myIntermodalRouter[key];
1701 : }
1702 :
1703 :
1704 : void
1705 42349 : MSNet::resetIntermodalRouter() const {
1706 46348 : for (auto& router : myIntermodalRouter) {
1707 3999 : delete router.second;
1708 : }
1709 : myIntermodalRouter.clear();
1710 42349 : }
1711 :
1712 :
1713 : void
1714 4967 : MSNet::adaptIntermodalRouter(MSTransportableRouter& router) {
1715 9934 : 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 14737 : for (const auto& stopType : myInstance->myStoppingPlaces) {
1719 : // add access to all stopping places
1720 9770 : const SumoXMLTag element = stopType.first;
1721 35996 : for (const auto& i : stopType.second) {
1722 26226 : const MSEdge* const edge = &i.second->getLane().getEdge();
1723 26226 : router.getNetwork()->addAccess(i.first, edge, i.second->getBeginLanePosition(), i.second->getEndLanePosition(),
1724 : 0., element, false, taxiWait);
1725 26226 : if (element == SUMO_TAG_BUS_STOP) {
1726 : // add access to all public transport stops
1727 12771 : 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 11605 : if (external != nullptr) {
1731 0 : external->addStop(router.getNetwork()->getStopEdge(i.first)->getNumericalID(), *i.second);
1732 : }
1733 : }
1734 : }
1735 : }
1736 4967 : myInstance->getInsertionControl().adaptIntermodalRouter(router);
1737 4967 : myInstance->getVehicleControl().adaptIntermodalRouter(router);
1738 : // add access to transfer from walking to taxi-use
1739 4967 : if ((router.getCarWalkTransfer() & ModeChangeOptions::TAXI_PICKUP_ANYWHERE) != 0) {
1740 66364 : for (MSEdge* edge : myInstance->getEdgeControl().getEdges()) {
1741 66114 : if ((edge->getPermissions() & SVC_PEDESTRIAN) != 0 && (edge->getPermissions() & SVC_TAXI) != 0) {
1742 22629 : router.getNetwork()->addCarAccess(edge, SVC_TAXI, taxiWait);
1743 : }
1744 : }
1745 : }
1746 4967 : }
1747 :
1748 :
1749 : bool
1750 42388 : MSNet::checkElevation() {
1751 42388 : const MSEdgeVector& edges = myEdges->getEdges();
1752 1827892 : for (MSEdgeVector::const_iterator e = edges.begin(); e != edges.end(); ++e) {
1753 3932629 : for (std::vector<MSLane*>::const_iterator i = (*e)->getLanes().begin(); i != (*e)->getLanes().end(); ++i) {
1754 2147125 : if ((*i)->getShape().hasElevation()) {
1755 : return true;
1756 : }
1757 : }
1758 : }
1759 : return false;
1760 : }
1761 :
1762 :
1763 : bool
1764 42388 : MSNet::checkWalkingarea() {
1765 1256830 : for (const MSEdge* e : myEdges->getEdges()) {
1766 1225034 : if (e->getFunction() == SumoXMLEdgeFunc::WALKINGAREA) {
1767 : return true;
1768 : }
1769 : }
1770 : return false;
1771 : }
1772 :
1773 :
1774 : bool
1775 42388 : MSNet::checkBidiEdges() {
1776 1764811 : for (const MSEdge* e : myEdges->getEdges()) {
1777 1723679 : 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 172 : MSNet::loadState(const std::string& fileName, const bool catchExceptions) {
1827 : // load time only
1828 172 : 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 : /****************************************************************************/
|