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 6743125 : MSNet::getTravelTime(const MSEdge* const e, const SUMOVehicle* const v, double t) {
168 : double value;
169 6743125 : const MSVehicle* const veh = dynamic_cast<const MSVehicle* const>(v);
170 6742293 : if (veh != nullptr && veh->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
171 522 : return value;
172 : }
173 6742603 : if (getInstance()->getWeightsStorage().retrieveExistingTravelTime(e, t, value)) {
174 177 : return value;
175 : }
176 6742426 : if (veh != nullptr) {
177 6566008 : if ((veh->getRoutingMode() & libsumo::ROUTING_MODE_AGGREGATED_CUSTOM) != 0) {
178 3508 : return MSRoutingEngine::getEffortExtra(e, v, t);
179 6562500 : } 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 6561933 : } else if (MSRoutingEngine::haveExtras()) {
186 6561933 : double tt = e->getMinimumTravelTime(v);
187 6561933 : MSRoutingEngine::applyExtras(e, v, SIMSTEP, tt);
188 6561933 : return tt;
189 : }
190 : }
191 176418 : return e->getMinimumTravelTime(v);
192 : }
193 :
194 :
195 : // ---------------------------------------------------------------------------
196 : // MSNet - methods
197 : // ---------------------------------------------------------------------------
198 : MSNet*
199 5369329907 : MSNet::getInstance(void) {
200 5369329907 : if (myInstance != nullptr) {
201 5369329862 : return myInstance;
202 : }
203 90 : throw ProcessError(TL("A network was not yet constructed."));
204 : }
205 :
206 : void
207 42726 : MSNet::initStatic() {
208 42726 : gRoutingPreferences = false;
209 42726 : MSDriveWay::init();
210 42726 : }
211 :
212 : void
213 42104 : MSNet::cleanupStatic() {
214 42104 : if (!MSGlobals::gUseMesoSim) {
215 35227 : MSVehicle::Influencer::cleanup();
216 : }
217 42104 : }
218 :
219 :
220 42726 : MSNet::MSNet(MSVehicleControl* vc, MSEventControl* beginOfTimestepEvents,
221 : MSEventControl* endOfTimestepEvents,
222 : MSEventControl* insertionEvents,
223 42726 : ShapeContainer* shapeCont):
224 42726 : myAmInterrupted(false),
225 42726 : myVehiclesMoved(0),
226 42726 : myPersonsMoved(0),
227 42726 : myHavePermissions(false),
228 42726 : myHasInternalLinks(false),
229 42726 : myJunctionHigherSpeeds(false),
230 42726 : myHasElevation(false),
231 42726 : myHasPedestrianNetwork(false),
232 42726 : myHasBidiEdges(false),
233 42726 : myEdgeDataEndTime(-1),
234 42726 : myDynamicShapeUpdater(nullptr) {
235 42726 : if (myInstance != nullptr) {
236 0 : throw ProcessError(TL("A network was already constructed."));
237 : }
238 42726 : OptionsCont& oc = OptionsCont::getOptions();
239 42726 : myStep = string2time(oc.getString("begin"));
240 42726 : myStateLoaderTime = myStep - 1,
241 42726 : myMaxTeleports = oc.getInt("max-num-teleports");
242 42726 : myLogExecutionTime = !oc.getBool("no-duration-log");
243 42726 : myLogStepNumber = !oc.getBool("no-step-log");
244 42726 : myLogStepPeriod = oc.getInt("step-log.period");
245 170904 : myInserter = new MSInsertionControl(*vc, string2time(oc.getString("max-depart-delay")), oc.getBool("eager-insert"), oc.getInt("max-num-vehicles"),
246 170904 : string2time(oc.getString("random-depart-offset")));
247 42726 : myVehicleControl = vc;
248 42726 : myDetectorControl = new MSDetectorControl();
249 42726 : myEdges = nullptr;
250 42726 : myJunctions = nullptr;
251 42726 : myRouteLoaders = nullptr;
252 42726 : myLogics = nullptr;
253 42726 : myPersonControl = nullptr;
254 42726 : myContainerControl = nullptr;
255 42726 : myEdgeWeights = nullptr;
256 42726 : myShapeContainer = shapeCont == nullptr ? new ShapeContainer() : shapeCont;
257 :
258 42726 : myBeginOfTimestepEvents = beginOfTimestepEvents;
259 42726 : myEndOfTimestepEvents = endOfTimestepEvents;
260 42726 : myInsertionEvents = insertionEvents;
261 42726 : myLanesRTree.first = false;
262 :
263 42726 : if (MSGlobals::gUseMesoSim) {
264 13954 : MSGlobals::gMesoNet = new MELoop(string2time(oc.getString("meso-recheck")));
265 : }
266 42726 : myInstance = this;
267 42726 : initStatic();
268 42726 : }
269 :
270 :
271 : void
272 42244 : 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 42244 : myEdges = edges;
281 42244 : myJunctions = junctions;
282 42244 : myRouteLoaders = routeLoaders;
283 42244 : myLogics = tlc;
284 : // save the time the network state shall be saved at
285 42244 : myStateDumpTimes = stateDumpTimes;
286 42244 : myStateDumpFiles = stateDumpFiles;
287 42244 : myStateDumpPeriod = string2time(oc.getString("save-state.period"));
288 42244 : myStateDumpPrefix = oc.getString("save-state.prefix");
289 42244 : myStateDumpSuffix = oc.getString("save-state.suffix");
290 :
291 : // initialise performance computation
292 42244 : mySimBeginMillis = SysUtils::getCurrentMillis();
293 42244 : myTraCIMillis = 0;
294 42244 : myHasInternalLinks = hasInternalLinks;
295 42244 : myJunctionHigherSpeeds = junctionHigherSpeeds;
296 42244 : myHasElevation = checkElevation();
297 42244 : myHasPedestrianNetwork = checkWalkingarea();
298 42244 : myHasBidiEdges = checkBidiEdges();
299 : myVersion = version;
300 42244 : if ((!MSGlobals::gUsingInternalLanes || !myHasInternalLinks)
301 15322 : && MSGlobals::gWeightsSeparateTurns > 0) {
302 0 : throw ProcessError(TL("Option weights.separate-turns is only supported when simulating with internal lanes"));
303 : }
304 42244 : }
305 :
306 :
307 75338 : MSNet::~MSNet() {
308 42104 : cleanupStatic();
309 : // delete controls
310 42104 : delete myJunctions;
311 42104 : delete myDetectorControl;
312 : // delete mean data
313 42104 : delete myEdges;
314 42104 : delete myInserter;
315 42104 : myInserter = nullptr;
316 42104 : delete myLogics;
317 42104 : delete myRouteLoaders;
318 42104 : if (myPersonControl != nullptr) {
319 8212 : delete myPersonControl;
320 8212 : myPersonControl = nullptr; // just to have that clear for later cleanups
321 : }
322 42104 : if (myContainerControl != nullptr) {
323 1949 : delete myContainerControl;
324 1949 : myContainerControl = nullptr; // just to have that clear for later cleanups
325 : }
326 42104 : 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 42104 : delete myShapeContainer;
332 42104 : myShapeContainer = nullptr;
333 : // delete events late so that vehicles can get rid of references first
334 42104 : delete myBeginOfTimestepEvents;
335 42104 : myBeginOfTimestepEvents = nullptr;
336 42104 : delete myEndOfTimestepEvents;
337 42104 : myEndOfTimestepEvents = nullptr;
338 42104 : delete myInsertionEvents;
339 42104 : myInsertionEvents = nullptr;
340 42104 : delete myEdgeWeights;
341 43568 : for (auto& router : myRouterTT) {
342 1464 : delete router.second;
343 : }
344 : myRouterTT.clear();
345 42115 : for (auto& router : myRouterEffort) {
346 11 : delete router.second;
347 : }
348 : myRouterEffort.clear();
349 44916 : for (auto& router : myPedestrianRouter) {
350 2812 : delete router.second;
351 : }
352 : myPedestrianRouter.clear();
353 42104 : resetIntermodalRouter();
354 : myLanesRTree.second.RemoveAll();
355 42121 : for (MSTractionSubstation* sub : myTractionSubstations) {
356 17 : delete sub;
357 : }
358 : myTractionSubstations.clear();
359 42104 : clearAll();
360 42104 : if (MSGlobals::gUseMesoSim) {
361 6877 : delete MSGlobals::gMesoNet;
362 : }
363 42104 : myInstance = nullptr;
364 159546 : }
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 2154227 : MSNet::getRestrictions(const std::string& id) const {
375 : std::map<std::string, std::map<SUMOVehicleClass, double> >::const_iterator i = myRestrictions.find(id);
376 2154227 : 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 919292 : MSNet::getMesoType(const std::string& typeID) {
433 : if (myMesoEdgeTypes.count(typeID) == 0) {
434 : // init defaults
435 7489 : const OptionsCont& oc = OptionsCont::getOptions();
436 : MESegment::MesoEdgeType edgeType;
437 7489 : edgeType.tauff = string2time(oc.getString("meso-tauff"));
438 7489 : edgeType.taufj = string2time(oc.getString("meso-taufj"));
439 7489 : edgeType.taujf = string2time(oc.getString("meso-taujf"));
440 7489 : edgeType.taujj = string2time(oc.getString("meso-taujj"));
441 7489 : edgeType.jamThreshold = oc.getFloat("meso-jam-threshold");
442 7489 : edgeType.junctionControl = oc.getBool("meso-junction-control");
443 7489 : edgeType.tlsPenalty = oc.getFloat("meso-tls-penalty");
444 7489 : edgeType.tlsFlowPenalty = oc.getFloat("meso-tls-flow-penalty");
445 7489 : edgeType.minorPenalty = string2time(oc.getString("meso-minor-penalty"));
446 7489 : edgeType.overtaking = oc.getBool("meso-overtaking");
447 7489 : edgeType.edgeLength = oc.getFloat("meso-edgelength");
448 7489 : myMesoEdgeTypes[typeID] = edgeType;
449 : }
450 919292 : return myMesoEdgeTypes[typeID];
451 : }
452 :
453 :
454 : bool
455 7317819 : MSNet::hasFlow(const std::string& id) const {
456 : // inserter is deleted at the end of the simulation
457 7317819 : return myInserter != nullptr && myInserter->hasFlow(id);
458 : }
459 :
460 :
461 : MSNet::SimulationState
462 31807 : MSNet::simulate(SUMOTime start, SUMOTime stop) {
463 : // report the begin when wished
464 63614 : 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 31807 : myStep = start;
469 : int numSteps = 0;
470 : bool doStepLog = false;
471 50004497 : while (state == SIMSTATE_RUNNING) {
472 49973089 : doStepLog = myLogStepNumber && (numSteps % myLogStepPeriod == 0);
473 : if (doStepLog) {
474 110 : preSimStepOutput();
475 : }
476 49973089 : simulationStep();
477 49972690 : if (doStepLog) {
478 110 : postSimStepOutput();
479 : }
480 49972690 : 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 49972690 : numSteps++;
487 : }
488 31408 : if (myLogStepNumber && !doStepLog) {
489 : // ensure some output on the last step
490 17 : preSimStepOutput();
491 17 : postSimStepOutput();
492 : }
493 : // exit simulation loop
494 31408 : if (myLogStepNumber) {
495 : // start new line for final verbose output
496 20 : std::cout << "\n";
497 : }
498 31408 : closeSimulation(start, getStateMessage(state));
499 31408 : return state;
500 : }
501 :
502 :
503 : void
504 63227647 : MSNet::loadRoutes() {
505 63227647 : myRouteLoaders->loadNext(myStep);
506 63227058 : }
507 :
508 :
509 : const std::string
510 13225 : MSNet::generateStatistics(const SUMOTime start, const long now) {
511 13225 : std::ostringstream msg;
512 13225 : if (myLogExecutionTime) {
513 12873 : const long duration = now - mySimBeginMillis;
514 : // print performance notice
515 25746 : msg << "Performance:\n" << " Duration: " << elapsedMs2string(duration) << "\n";
516 12873 : if (duration != 0) {
517 12710 : if (TraCIServer::getInstance() != nullptr) {
518 4272 : msg << " TraCI-Duration: " << elapsedMs2string(myTraCIMillis) << "\n";
519 : }
520 12710 : 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 12710 : msg << " UPS: " << ((double)myVehiclesMoved / ((double)duration / 1000)) << "\n";
524 12710 : if (myPersonsMoved > 0) {
525 2361 : msg << " UPS-Persons: " << ((double)myPersonsMoved / ((double)duration / 1000)) << "\n";
526 : }
527 : }
528 : // print vehicle statistics
529 12873 : const std::string vehDiscardNotice = ((myVehicleControl->getLoadedVehicleNo() != myVehicleControl->getDepartedVehicleNo()) ?
530 16995 : " (Loaded: " + toString(myVehicleControl->getLoadedVehicleNo()) + ")" : "");
531 : msg << "Vehicles:\n"
532 12873 : << " Inserted: " << myVehicleControl->getDepartedVehicleNo() << vehDiscardNotice << "\n"
533 25746 : << " Running: " << myVehicleControl->getRunningVehicleNo() << "\n"
534 25746 : << " Waiting: " << myInserter->getWaitingVehicleNo() << "\n";
535 :
536 12873 : if (myVehicleControl->getTeleportCount() > 0 || myVehicleControl->getCollisionCount() > 0) {
537 : // print optional teleport statistics
538 : std::vector<std::string> reasons;
539 708 : if (myVehicleControl->getCollisionCount() > 0) {
540 650 : reasons.push_back("Collisions: " + toString(myVehicleControl->getCollisionCount()));
541 : }
542 708 : if (myVehicleControl->getTeleportsJam() > 0) {
543 506 : reasons.push_back("Jam: " + toString(myVehicleControl->getTeleportsJam()));
544 : }
545 708 : if (myVehicleControl->getTeleportsYield() > 0) {
546 282 : reasons.push_back("Yield: " + toString(myVehicleControl->getTeleportsYield()));
547 : }
548 708 : if (myVehicleControl->getTeleportsWrongLane() > 0) {
549 280 : reasons.push_back("Wrong Lane: " + toString(myVehicleControl->getTeleportsWrongLane()));
550 : }
551 2124 : msg << " Teleports: " << myVehicleControl->getTeleportCount() << " (" << joinToString(reasons, ", ") << ")\n";
552 708 : }
553 12873 : if (myVehicleControl->getEmergencyStops() > 0) {
554 70 : msg << " Emergency Stops: " << myVehicleControl->getEmergencyStops() << "\n";
555 : }
556 12873 : if (myVehicleControl->getEmergencyBrakingCount() > 0) {
557 297 : msg << " Emergency Braking: " << myVehicleControl->getEmergencyBrakingCount() << "\n";
558 : }
559 12873 : if (myPersonControl != nullptr && myPersonControl->getLoadedNumber() > 0) {
560 2417 : const std::string discardNotice = ((myPersonControl->getLoadedNumber() != myPersonControl->getDepartedNumber()) ?
561 2786 : " (Loaded: " + toString(myPersonControl->getLoadedNumber()) + ")" : "");
562 : msg << "Persons:\n"
563 2417 : << " Inserted: " << myPersonControl->getDepartedNumber() << discardNotice << "\n"
564 4834 : << " Running: " << myPersonControl->getRunningNumber() << "\n";
565 2417 : if (myPersonControl->getJammedNumber() > 0) {
566 54 : msg << " Jammed: " << myPersonControl->getJammedNumber() << "\n";
567 : }
568 2417 : 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 12873 : if (myContainerControl != nullptr && myContainerControl->getLoadedNumber() > 0) {
580 75 : const std::string discardNotice = ((myContainerControl->getLoadedNumber() != myContainerControl->getDepartedNumber()) ?
581 75 : " (Loaded: " + toString(myContainerControl->getLoadedNumber()) + ")" : "");
582 : msg << "Containers:\n"
583 75 : << " Inserted: " << myContainerControl->getDepartedNumber() << "\n"
584 150 : << " Running: " << myContainerControl->getRunningNumber() << "\n";
585 75 : if (myContainerControl->getJammedNumber() > 0) {
586 0 : msg << " Jammed: " << myContainerControl->getJammedNumber() << "\n";
587 : }
588 75 : 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 26450 : if (OptionsCont::getOptions().getBool("duration-log.statistics")) {
601 6802 : msg << MSDevice_Tripinfo::printStatistics();
602 : }
603 : std::string result = msg.str();
604 : result.erase(result.end() - 1);
605 13225 : return result;
606 13225 : }
607 :
608 :
609 : void
610 10353 : MSNet::writeCollisions() const {
611 20706 : OutputDevice& od = OutputDevice::getDeviceByOption("collision-output");
612 10512 : 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 10353 : }
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 63226409 : MSNet::writeSummaryOutput(bool finalStep) {
689 : // summary output
690 63226409 : const OptionsCont& oc = OptionsCont::getOptions();
691 63226409 : const bool hasOutput = oc.isSet("summary-output");
692 63226409 : const bool hasPersonOutput = oc.isSet("person-summary-output");
693 63226409 : 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 63224966 : 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 40593 : MSNet::closeSimulation(SUMOTime start, const std::string& reason) {
757 : // report the end when wished
758 81186 : WRITE_MESSAGE(TLF("Simulation ended at time: %.", time2string(getCurrentTimeStep())));
759 40593 : if (reason != "") {
760 80322 : WRITE_MESSAGE(TL("Reason: ") + reason);
761 : }
762 40593 : myDetectorControl->close(myStep);
763 42046 : if (MSStopOut::active() && OptionsCont::getOptions().getBool("stop-output.write-unfinished")) {
764 122 : MSStopOut::getInstance()->generateOutputForUnfinished();
765 : }
766 40593 : MSDevice_Vehroutes::writePendingOutput(OptionsCont::getOptions().getBool("vehroute-output.write-unfinished"));
767 81186 : if (OptionsCont::getOptions().getBool("tripinfo-output.write-unfinished")) {
768 1099 : MSDevice_Tripinfo::generateOutputForUnfinished();
769 : }
770 81186 : if (OptionsCont::getOptions().isSet("chargingstations-output")) {
771 240 : if (!OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
772 100 : writeChargingStationOutput();
773 40 : } else if (OptionsCont::getOptions().getBool("chargingstations-output.aggregated.write-unfinished")) {
774 12 : MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"), true);
775 : }
776 : }
777 81186 : if (OptionsCont::getOptions().isSet("overheadwiresegments-output")) {
778 5 : writeOverheadWireSegmentOutput();
779 : }
780 81186 : if (OptionsCont::getOptions().isSet("substations-output")) {
781 5 : writeSubstationOutput();
782 : }
783 40593 : writeRailSignalBlocks();
784 40593 : const long now = SysUtils::getCurrentMillis();
785 68313 : if (myLogExecutionTime || OptionsCont::getOptions().getBool("duration-log.statistics")) {
786 26450 : WRITE_MESSAGE(generateStatistics(start, now));
787 : }
788 81186 : if (OptionsCont::getOptions().isSet("statistic-output")) {
789 379 : writeStatistics(start, now);
790 : }
791 : // maybe write a final line of output if reporting is periodic
792 40593 : writeSummaryOutput(true);
793 40593 : }
794 :
795 :
796 : void
797 63188985 : MSNet::simulationStep(const bool onlyMove) {
798 63188985 : if (myStepCompletionMissing) {
799 4 : postMoveStep();
800 4 : myStepCompletionMissing = false;
801 2651 : return;
802 : }
803 : #ifdef DEBUG_SIMSTEP
804 : std::cout << SIMTIME << ": MSNet::simulationStep() called"
805 : << ", myStep = " << myStep
806 : << std::endl;
807 : #endif
808 : TraCIServer* t = TraCIServer::getInstance();
809 : int lastTraCICmd = 0;
810 63188981 : if (t != nullptr) {
811 8423445 : if (myLogExecutionTime) {
812 8226510 : myTraCIStepDuration = SysUtils::getCurrentMillis();
813 : }
814 8423445 : lastTraCICmd = t->processCommands(myStep);
815 : #ifdef DEBUG_SIMSTEP
816 : bool loadRequested = !TraCI::getLoadArgs().empty();
817 : assert(t->getTargetTime() >= myStep || loadRequested || TraCIServer::wasClosed());
818 : #endif
819 8423343 : if (myLogExecutionTime) {
820 8226434 : myTraCIStepDuration = SysUtils::getCurrentMillis() - myTraCIStepDuration;
821 : }
822 8423343 : if (TraCIServer::wasClosed() || !t->getLoadArgs().empty()) {
823 : return;
824 : }
825 : }
826 : #ifdef DEBUG_SIMSTEP
827 : std::cout << SIMTIME << ": TraCI target time: " << t->getTargetTime() << std::endl;
828 : #endif
829 : // execute beginOfTimestepEvents
830 63186236 : if (myLogExecutionTime) {
831 25418504 : mySimStepDuration = SysUtils::getCurrentMillis();
832 : }
833 : // simulation state output
834 63186236 : std::vector<SUMOTime>::iterator timeIt = std::find(myStateDumpTimes.begin(), myStateDumpTimes.end(), myStep);
835 63186236 : if (timeIt != myStateDumpTimes.end()) {
836 375 : const int dist = (int)distance(myStateDumpTimes.begin(), timeIt);
837 375 : MSStateHandler::saveState(myStateDumpFiles[dist], myStep);
838 : }
839 63186236 : if (myStateDumpPeriod > 0 && myStep % myStateDumpPeriod == 0) {
840 84 : std::string timeStamp = time2string(myStep);
841 : std::replace(timeStamp.begin(), timeStamp.end(), ':', '-');
842 84 : const std::string filename = myStateDumpPrefix + "_" + timeStamp + myStateDumpSuffix;
843 84 : MSStateHandler::saveState(filename, myStep);
844 84 : myPeriodicStateFiles.push_back(filename);
845 84 : int keep = OptionsCont::getOptions().getInt("save-state.period.keep");
846 84 : if (keep > 0 && (int)myPeriodicStateFiles.size() > keep) {
847 0 : std::remove(myPeriodicStateFiles.front().c_str());
848 : myPeriodicStateFiles.erase(myPeriodicStateFiles.begin());
849 : }
850 : }
851 63186236 : myBeginOfTimestepEvents->execute(myStep);
852 63186228 : if (MSRailSignalControl::hasInstance()) {
853 8458732 : MSRailSignalControl::getInstance().updateSignals(myStep);
854 : }
855 : #ifdef HAVE_FOX
856 63186228 : MSRoutingEngine::waitForAll();
857 : #endif
858 63186228 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
859 43936696 : myEdges->detectCollisions(myStep, STAGE_EVENTS);
860 : }
861 : // check whether the tls programs need to be switched
862 63186228 : myLogics->check2Switch(myStep);
863 :
864 63186228 : if (MSGlobals::gUseMesoSim) {
865 19249532 : MSGlobals::gMesoNet->simulate(myStep);
866 : } else {
867 : // assure all lanes with vehicles are 'active'
868 43936696 : myEdges->patchActiveLanes();
869 :
870 : // compute safe velocities for all vehicles for the next few lanes
871 : // also register ApproachingVehicleInformation for all links
872 43936696 : myEdges->planMovements(myStep);
873 :
874 : // register junction approaches based on planned velocities as basis for right-of-way decision
875 43936696 : myEdges->setJunctionApproaches();
876 :
877 : // decide right-of-way and execute movements
878 43936696 : myEdges->executeMovements(myStep);
879 43936693 : if (MSGlobals::gCheck4Accidents) {
880 43936693 : myEdges->detectCollisions(myStep, STAGE_MOVEMENTS);
881 : }
882 :
883 : // vehicles may change lanes
884 43936693 : myEdges->changeLanes(myStep);
885 :
886 43936693 : if (MSGlobals::gCheck4Accidents) {
887 43936693 : myEdges->detectCollisions(myStep, STAGE_LANECHANGE);
888 : }
889 : }
890 : // flush arrived meso vehicles and micro vehicles that were removed due to collision
891 63186225 : myVehicleControl->removePending();
892 63186225 : loadRoutes();
893 :
894 : // persons
895 63186209 : if (myPersonControl != nullptr && myPersonControl->hasTransportables()) {
896 3533317 : myPersonControl->checkWaiting(this, myStep);
897 : }
898 : // containers
899 63186154 : if (myContainerControl != nullptr && myContainerControl->hasTransportables()) {
900 4493398 : myContainerControl->checkWaiting(this, myStep);
901 : }
902 63186154 : if (MSRailSignalControl::hasInstance()) {
903 8458732 : MSRailSignalControl::getInstance().resetWaitRelations();
904 : // preserve waitRelation from insertion for the next step
905 : }
906 : // insert vehicles
907 63186154 : myInserter->determineCandidates(myStep);
908 63186107 : myInsertionEvents->execute(myStep);
909 : #ifdef HAVE_FOX
910 63186011 : MSRoutingEngine::waitForAll();
911 : #endif
912 63185987 : myInserter->emitVehicles(myStep);
913 63185841 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
914 : //myEdges->patchActiveLanes(); // @note required to detect collisions on lanes that were empty before insertion. wasteful?
915 43936418 : myEdges->detectCollisions(myStep, STAGE_INSERTIONS);
916 : }
917 63185841 : MSVehicleTransfer::getInstance()->checkInsertions(myStep);
918 :
919 : // execute endOfTimestepEvents
920 63185841 : myEndOfTimestepEvents->execute(myStep);
921 :
922 63185831 : if (myLogExecutionTime) {
923 25418330 : myTraCIStepDuration -= SysUtils::getCurrentMillis();
924 : }
925 63185831 : if (onlyMove) {
926 4 : myStepCompletionMissing = true;
927 4 : return;
928 : }
929 63185827 : if (t != nullptr && lastTraCICmd == libsumo::CMD_EXECUTEMOVE) {
930 6 : t->processCommands(myStep, true);
931 : }
932 63185827 : postMoveStep();
933 : }
934 :
935 :
936 : void
937 63185831 : MSNet::postMoveStep() {
938 63185831 : const int numControlled = libsumo::Helper::postProcessRemoteControl();
939 63185831 : if (numControlled > 0 && MSGlobals::gCheck4Accidents) {
940 9460 : myEdges->detectCollisions(myStep, STAGE_REMOTECONTROL);
941 : }
942 63185831 : if (myLogExecutionTime) {
943 25418330 : myTraCIStepDuration += SysUtils::getCurrentMillis();
944 25418330 : myTraCIMillis += myTraCIStepDuration;
945 : }
946 63185831 : if (MSGlobals::gCheck4Accidents && !MSGlobals::gUseMesoSim) {
947 : // collisions from the previous step were kept to avoid duplicate
948 : // warnings. we must remove them now to ensure correct output.
949 43936413 : removeOutdatedCollisions();
950 : }
951 : // update and write (if needed) detector values
952 63185831 : mySimStepDuration = SysUtils::getCurrentMillis() - mySimStepDuration;
953 63185831 : writeOutput();
954 :
955 63185815 : if (myLogExecutionTime) {
956 25418330 : myVehiclesMoved += myVehicleControl->getRunningVehicleNo();
957 25418330 : if (myPersonControl != nullptr) {
958 2741943 : myPersonsMoved += myPersonControl->getRunningNumber();
959 : }
960 : }
961 63185815 : myStep += DELTA_T;
962 63185815 : }
963 :
964 :
965 : MSNet::SimulationState
966 63089981 : MSNet::simulationState(SUMOTime stopTime) const {
967 63089981 : if (TraCIServer::wasClosed()) {
968 : return SIMSTATE_CONNECTION_CLOSED;
969 : }
970 63087215 : if (TraCIServer::getInstance() != nullptr && !TraCIServer::getInstance()->getLoadArgs().empty()) {
971 : return SIMSTATE_LOADING;
972 : }
973 63087202 : if ((stopTime < 0 || myStep > stopTime) && TraCIServer::getInstance() == nullptr && (stopTime > 0 || myStep > myEdgeDataEndTime)) {
974 33259228 : if ((myVehicleControl->getActiveVehicleCount() == 0)
975 6143069 : && (myInserter->getPendingFlowCount() == 0)
976 1949639 : && (myPersonControl == nullptr || !myPersonControl->hasNonWaiting())
977 412601 : && (myContainerControl == nullptr || !myContainerControl->hasNonWaiting())
978 33322615 : && !MSDevice_Taxi::hasServableReservations()) {
979 : return SIMSTATE_NO_FURTHER_VEHICLES;
980 : }
981 : }
982 63040663 : if (stopTime >= 0 && myStep >= stopTime) {
983 : return SIMSTATE_END_STEP_REACHED;
984 : }
985 63019608 : if (myMaxTeleports >= 0 && myVehicleControl->getTeleportCount() > myMaxTeleports) {
986 : return SIMSTATE_TOO_MANY_TELEPORTS;
987 : }
988 63019600 : if (myAmInterrupted) {
989 6 : return SIMSTATE_INTERRUPTED;
990 : }
991 : return SIMSTATE_RUNNING;
992 : }
993 :
994 :
995 : MSNet::SimulationState
996 63081402 : MSNet::adaptToState(MSNet::SimulationState state, const bool isLibsumo) const {
997 63081402 : if (state == SIMSTATE_LOADING) {
998 13 : OptionsIO::setArgs(TraCIServer::getInstance()->getLoadArgs());
999 : TraCIServer::getInstance()->getLoadArgs().clear();
1000 63081389 : } else if (state != SIMSTATE_RUNNING && ((TraCIServer::getInstance() != nullptr && !TraCIServer::wasClosed()) || isLibsumo)) {
1001 : // overrides SIMSTATE_END_STEP_REACHED, e.g. (TraCI / Libsumo ignore SUMO's --end option)
1002 23056 : return SIMSTATE_RUNNING;
1003 63058333 : } else if (state == SIMSTATE_NO_FURTHER_VEHICLES) {
1004 28313 : if (myPersonControl != nullptr) {
1005 6859 : myPersonControl->abortAnyWaitingForVehicle();
1006 : }
1007 28313 : if (myContainerControl != nullptr) {
1008 1862 : myContainerControl->abortAnyWaitingForVehicle();
1009 : }
1010 28313 : myVehicleControl->abortWaiting();
1011 : }
1012 : return state;
1013 : }
1014 :
1015 :
1016 : std::string
1017 39987 : MSNet::getStateMessage(MSNet::SimulationState state) {
1018 39987 : switch (state) {
1019 : case MSNet::SIMSTATE_RUNNING:
1020 432 : return "";
1021 : case MSNet::SIMSTATE_END_STEP_REACHED:
1022 8220 : return TL("The final simulation step has been reached.");
1023 : case MSNet::SIMSTATE_NO_FURTHER_VEHICLES:
1024 28680 : return TL("All vehicles have left the simulation.");
1025 : case MSNet::SIMSTATE_CONNECTION_CLOSED:
1026 2630 : return TL("TraCI requested termination.");
1027 : case MSNet::SIMSTATE_ERROR_IN_SIM:
1028 0 : return TL("An error occurred (see log).");
1029 : case MSNet::SIMSTATE_INTERRUPTED:
1030 6 : return TL("Interrupted.");
1031 : case MSNet::SIMSTATE_TOO_MANY_TELEPORTS:
1032 6 : return TL("Too many teleports.");
1033 : case MSNet::SIMSTATE_LOADING:
1034 13 : return TL("TraCI issued load command.");
1035 : default:
1036 0 : return TL("Unknown reason.");
1037 : }
1038 : }
1039 :
1040 :
1041 : void
1042 42395 : MSNet::clearAll() {
1043 : // clear container
1044 42395 : MSEdge::clear();
1045 42395 : MSLane::clear();
1046 42395 : MSRoute::clear();
1047 42395 : delete MSVehicleTransfer::getInstance();
1048 42395 : MSDevice::cleanupAll();
1049 42395 : MSCalibrator::cleanup();
1050 85290 : while (!MSLaneSpeedTrigger::getInstances().empty()) {
1051 500 : delete MSLaneSpeedTrigger::getInstances().begin()->second;
1052 : }
1053 46569 : while (!MSTriggeredRerouter::getInstances().empty()) {
1054 4174 : delete MSTriggeredRerouter::getInstances().begin()->second;
1055 : }
1056 42395 : MSDevice_BTsender::cleanup();
1057 42395 : MSDevice_SSM::cleanup();
1058 42395 : MSDevice_ToC::cleanup();
1059 42395 : MSStopOut::cleanup();
1060 42395 : MSRailSignalConstraint::cleanup();
1061 42395 : MSRailSignalControl::cleanup();
1062 42395 : MSDriveWay::cleanup();
1063 : TraCIServer* t = TraCIServer::getInstance();
1064 42395 : if (t != nullptr) {
1065 2748 : t->cleanup();
1066 : }
1067 42395 : libsumo::Helper::cleanup();
1068 42395 : OutputDevice::closeAll(true);
1069 42395 : }
1070 :
1071 :
1072 : void
1073 167 : MSNet::clearState(const SUMOTime step, bool quickReload) {
1074 167 : MSGlobals::gClearState = true;
1075 167 : if (MSGlobals::gUseMesoSim) {
1076 16 : MSGlobals::gMesoNet->clearState();
1077 766 : for (MSEdge* const edge : MSEdge::getAllEdges()) {
1078 1488 : for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*edge); s != nullptr; s = s->getNextSegment()) {
1079 754 : s->clearState();
1080 : }
1081 : }
1082 : } else {
1083 7174 : for (MSEdge* const edge : MSEdge::getAllEdges()) {
1084 15558 : for (MSLane* const lane : edge->getLanes()) {
1085 8535 : lane->getVehiclesSecure();
1086 8535 : lane->clearState();
1087 8535 : lane->releaseVehicles();
1088 : }
1089 7023 : edge->clearState();
1090 : }
1091 : }
1092 167 : myInserter->clearState();
1093 : // detectors may still reference persons/vehicles
1094 167 : myDetectorControl->updateDetectors(myStep);
1095 167 : myDetectorControl->writeOutput(myStep, true);
1096 167 : myDetectorControl->clearState(step);
1097 :
1098 167 : if (myPersonControl != nullptr) {
1099 23 : myPersonControl->clearState();
1100 : }
1101 167 : if (myContainerControl != nullptr) {
1102 0 : myContainerControl->clearState();
1103 : }
1104 : // delete vtypes after transportables have removed their types
1105 167 : myVehicleControl->clearState(true);
1106 167 : MSVehicleTransfer::getInstance()->clearState();
1107 167 : myLogics->clearState(step, quickReload);
1108 : // delete all routes after vehicles and detector output is done
1109 167 : MSRoute::dict_clearState();
1110 208 : for (auto& item : myStoppingPlaces) {
1111 82 : for (auto& item2 : item.second) {
1112 41 : item2.second->clearState();
1113 : }
1114 : }
1115 167 : myShapeContainer->clearState();
1116 167 : myBeginOfTimestepEvents->clearState(myStep, step);
1117 167 : myEndOfTimestepEvents->clearState(myStep, step);
1118 167 : myInsertionEvents->clearState(myStep, step);
1119 167 : MSRailSignalControl::clearState();
1120 167 : MSDriveWay::clearState();
1121 167 : myStep = step;
1122 167 : MSGlobals::gClearState = false;
1123 167 : }
1124 :
1125 :
1126 : SUMOTime
1127 573 : MSNet::getLoaderTime() const {
1128 573 : return myRouteLoaders->getCurrentLoadTime();
1129 : }
1130 :
1131 : void
1132 713 : MSNet::setLoaderTime(SUMOTime time) {
1133 713 : myRouteLoaders->setCurrentLoadTime(time);
1134 713 : myStateLoaderTime = MAX2(myStateLoaderTime, time);
1135 713 : }
1136 :
1137 : void
1138 63185831 : MSNet::writeOutput() {
1139 : // update detector values
1140 63185831 : myDetectorControl->updateDetectors(myStep);
1141 63185822 : const OptionsCont& oc = OptionsCont::getOptions();
1142 :
1143 : // check state dumps
1144 126371644 : if (oc.isSet("netstate-dump")) {
1145 12936 : MSXMLRawOut::write(OutputDevice::getDeviceByOption("netstate-dump"), *myEdges, myStep,
1146 : oc.getInt("netstate-dump.precision"));
1147 : }
1148 :
1149 : // check fcd dumps
1150 126371644 : if (OptionsCont::getOptions().isSet("fcd-output")) {
1151 9507274 : if (OptionsCont::getOptions().isSet("person-fcd-output")) {
1152 24 : MSFCDExport::write(OutputDevice::getDeviceByOption("fcd-output"), myStep, SUMO_TAG_VEHICLE);
1153 48 : MSFCDExport::write(OutputDevice::getDeviceByOption("person-fcd-output"), myStep, SUMO_TAG_PERSON);
1154 : } else {
1155 9507226 : MSFCDExport::write(OutputDevice::getDeviceByOption("fcd-output"), myStep);
1156 : }
1157 : }
1158 :
1159 : // check emission dumps
1160 126371644 : if (OptionsCont::getOptions().isSet("emission-output")) {
1161 215992 : MSEmissionExport::write(OutputDevice::getDeviceByOption("emission-output"), myStep);
1162 : }
1163 :
1164 : // battery dumps
1165 126371644 : if (OptionsCont::getOptions().isSet("battery-output")) {
1166 145458 : MSBatteryExport::write(OutputDevice::getDeviceByOption("battery-output"), myStep,
1167 : oc.getInt("battery-output.precision"));
1168 : }
1169 :
1170 : // charging station aggregated dumps
1171 63275538 : if (OptionsCont::getOptions().isSet("chargingstations-output") && OptionsCont::getOptions().getBool("chargingstations-output.aggregated")) {
1172 22248 : MSChargingStationExport::write(OutputDevice::getDeviceByOption("chargingstations-output"));
1173 : }
1174 :
1175 : // elecHybrid dumps
1176 126371644 : if (OptionsCont::getOptions().isSet("elechybrid-output")) {
1177 450 : std::string output = OptionsCont::getOptions().getString("elechybrid-output");
1178 :
1179 900 : if (oc.getBool("elechybrid-output.aggregated")) {
1180 : // build a xml file with aggregated device.elechybrid output
1181 600 : MSElecHybridExport::writeAggregated(OutputDevice::getDeviceByOption("elechybrid-output"), myStep,
1182 : oc.getInt("elechybrid-output.precision"));
1183 : } else {
1184 : // build a separate xml file for each vehicle equipped with device.elechybrid
1185 : // RICE_TODO: Does this have to be placed here in MSNet.cpp ?
1186 150 : MSVehicleControl& vc = MSNet::getInstance()->getVehicleControl();
1187 210 : for (MSVehicleControl::constVehIt it = vc.loadedVehBegin(); it != vc.loadedVehEnd(); ++it) {
1188 60 : const SUMOVehicle* veh = it->second;
1189 60 : if (!veh->isOnRoad()) {
1190 0 : continue;
1191 : }
1192 60 : if (static_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid))) != nullptr) {
1193 : std::string vehID = veh->getID();
1194 60 : std::string filename2 = output + "_" + vehID + ".xml";
1195 60 : OutputDevice& dev = OutputDevice::getDevice(filename2);
1196 : std::map<SumoXMLAttr, std::string> attrs;
1197 60 : attrs[SUMO_ATTR_VEHICLE] = vehID;
1198 60 : attrs[SUMO_ATTR_MAXIMUMBATTERYCAPACITY] = toString(dynamic_cast<MSDevice_ElecHybrid*>(veh->getDevice(typeid(MSDevice_ElecHybrid)))->getMaximumBatteryCapacity());
1199 60 : attrs[SUMO_ATTR_RECUPERATIONENABLE] = toString(MSGlobals::gOverheadWireRecuperation);
1200 120 : dev.writeXMLHeader("elecHybrid-export", "", attrs);
1201 120 : MSElecHybridExport::write(OutputDevice::getDevice(filename2), veh, myStep, oc.getInt("elechybrid-output.precision"));
1202 : }
1203 : }
1204 : }
1205 : }
1206 :
1207 :
1208 : // check full dumps
1209 126371644 : if (OptionsCont::getOptions().isSet("full-output")) {
1210 1138 : MSGlobals::gHaveEmissions = true;
1211 2276 : MSFullExport::write(OutputDevice::getDeviceByOption("full-output"), myStep);
1212 : }
1213 :
1214 : // check queue dumps
1215 126371644 : if (OptionsCont::getOptions().isSet("queue-output")) {
1216 325614 : MSQueueExport::write(OutputDevice::getDeviceByOption("queue-output"), myStep);
1217 : }
1218 :
1219 : // check amitran dumps
1220 126371644 : if (OptionsCont::getOptions().isSet("amitran-output")) {
1221 2340 : MSAmitranTrajectories::write(OutputDevice::getDeviceByOption("amitran-output"), myStep);
1222 : }
1223 :
1224 : // check vtk dumps
1225 126371644 : if (OptionsCont::getOptions().isSet("vtk-output")) {
1226 :
1227 60 : if (MSNet::getInstance()->getVehicleControl().getRunningVehicleNo() > 0) {
1228 60 : std::string timestep = time2string(myStep);
1229 60 : if (TS >= 1.0) {
1230 48 : timestep = timestep.substr(0, timestep.length() - 3);
1231 36 : } else if (DELTA_T % 100 == 0) {
1232 72 : timestep = timestep.substr(0, timestep.length() - 1);
1233 : }
1234 66 : std::string output = OptionsCont::getOptions().getString("vtk-output");
1235 66 : std::string filename = output + "_" + timestep + ".vtp";
1236 :
1237 60 : OutputDevice_File dev(filename);
1238 :
1239 : //build a huge mass of xml files
1240 54 : MSVTKExport::write(dev, myStep);
1241 :
1242 54 : }
1243 :
1244 : }
1245 :
1246 63185816 : writeSummaryOutput();
1247 :
1248 : // write detector values
1249 63185816 : myDetectorControl->writeOutput(myStep + DELTA_T, false);
1250 :
1251 : // write link states
1252 126371630 : if (OptionsCont::getOptions().isSet("link-output")) {
1253 4048 : OutputDevice& od = OutputDevice::getDeviceByOption("link-output");
1254 4048 : od.openTag("timestep");
1255 4048 : od.writeAttr(SUMO_ATTR_ID, STEPS2TIME(myStep));
1256 85848 : for (const MSEdge* const edge : myEdges->getEdges()) {
1257 180200 : for (const MSLane* const lane : edge->getLanes()) {
1258 212304 : for (const MSLink* const link : lane->getLinkCont()) {
1259 227808 : link->writeApproaching(od, lane->getID());
1260 : }
1261 : }
1262 : }
1263 8096 : od.closeTag();
1264 : }
1265 :
1266 : // write SSM output
1267 65719012 : for (MSDevice_SSM* dev : MSDevice_SSM::getInstances()) {
1268 2533197 : dev->updateAndWriteOutput();
1269 : }
1270 :
1271 : // write ToC output
1272 63201534 : for (MSDevice_ToC* dev : MSDevice_ToC::getInstances()) {
1273 15719 : if (dev->generatesOutput()) {
1274 15513 : dev->writeOutput();
1275 : }
1276 : }
1277 :
1278 126371630 : if (OptionsCont::getOptions().isSet("collision-output")) {
1279 10353 : writeCollisions();
1280 : }
1281 63185815 : }
1282 :
1283 :
1284 : bool
1285 0 : MSNet::logSimulationDuration() const {
1286 0 : return myLogExecutionTime;
1287 : }
1288 :
1289 :
1290 : MSTransportableControl&
1291 15012119 : MSNet::getPersonControl() {
1292 15012119 : if (myPersonControl == nullptr) {
1293 6668 : myPersonControl = new MSTransportableControl(true);
1294 : }
1295 15012095 : return *myPersonControl;
1296 : }
1297 :
1298 :
1299 : MSTransportableControl&
1300 8164872 : MSNet::getContainerControl() {
1301 8164872 : if (myContainerControl == nullptr) {
1302 1782 : myContainerControl = new MSTransportableControl(false);
1303 : }
1304 8164872 : return *myContainerControl;
1305 : }
1306 :
1307 : MSDynamicShapeUpdater*
1308 23 : MSNet::makeDynamicShapeUpdater() {
1309 23 : myDynamicShapeUpdater = std::unique_ptr<MSDynamicShapeUpdater> (new MSDynamicShapeUpdater(*myShapeContainer));
1310 23 : return myDynamicShapeUpdater.get();
1311 : }
1312 :
1313 : MSEdgeWeightsStorage&
1314 6743226 : MSNet::getWeightsStorage() {
1315 6743226 : if (myEdgeWeights == nullptr) {
1316 1932 : myEdgeWeights = new MSEdgeWeightsStorage();
1317 : }
1318 6743226 : return *myEdgeWeights;
1319 : }
1320 :
1321 :
1322 : void
1323 127 : MSNet::preSimStepOutput() const {
1324 127 : std::cout << "Step #" << time2string(myStep);
1325 127 : }
1326 :
1327 :
1328 : void
1329 127 : MSNet::postSimStepOutput() const {
1330 127 : if (myLogExecutionTime) {
1331 125 : std::ostringstream oss;
1332 : oss.setf(std::ios::fixed, std::ios::floatfield); // use decimal format
1333 : oss.setf(std::ios::showpoint); // print decimal point
1334 125 : oss << std::setprecision(gPrecision);
1335 125 : if (mySimStepDuration != 0) {
1336 73 : const double durationSec = (double)mySimStepDuration / 1000.;
1337 73 : oss << " (" << mySimStepDuration << "ms ~= "
1338 73 : << (TS / durationSec) << "*RT, ~"
1339 73 : << ((double) myVehicleControl->getRunningVehicleNo() / durationSec);
1340 : } else {
1341 52 : oss << " (0ms ?*RT. ?";
1342 : }
1343 125 : oss << "UPS, ";
1344 125 : if (TraCIServer::getInstance() != nullptr) {
1345 79 : oss << "TraCI: " << myTraCIStepDuration << "ms, ";
1346 : }
1347 125 : oss << "vehicles TOT " << myVehicleControl->getDepartedVehicleNo()
1348 250 : << " ACT " << myVehicleControl->getRunningVehicleNo()
1349 125 : << " BUF " << myInserter->getWaitingVehicleNo()
1350 125 : << ") ";
1351 250 : std::string prev = "Step #" + time2string(myStep - DELTA_T);
1352 250 : std::cout << oss.str().substr(0, 90 - prev.length());
1353 125 : }
1354 127 : std::cout << '\r';
1355 127 : }
1356 :
1357 :
1358 : void
1359 11578 : MSNet::addVehicleStateListener(VehicleStateListener* listener) {
1360 11578 : if (find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener) == myVehicleStateListeners.end()) {
1361 11578 : myVehicleStateListeners.push_back(listener);
1362 : }
1363 11578 : }
1364 :
1365 :
1366 : void
1367 57 : MSNet::removeVehicleStateListener(VehicleStateListener* listener) {
1368 57 : std::vector<VehicleStateListener*>::iterator i = std::find(myVehicleStateListeners.begin(), myVehicleStateListeners.end(), listener);
1369 57 : if (i != myVehicleStateListeners.end()) {
1370 57 : myVehicleStateListeners.erase(i);
1371 : }
1372 57 : }
1373 :
1374 :
1375 : void
1376 15959115 : MSNet::informVehicleStateListener(const SUMOVehicle* const vehicle, VehicleState to, const std::string& info) {
1377 : #ifdef HAVE_FOX
1378 15959115 : ScopedLocker<> lock(myVehicleStateListenerMutex, MSGlobals::gNumThreads > 1);
1379 : #endif
1380 16652178 : for (VehicleStateListener* const listener : myVehicleStateListeners) {
1381 693063 : listener->vehicleStateChanged(vehicle, to, info);
1382 : }
1383 15959115 : }
1384 :
1385 :
1386 : void
1387 3895 : MSNet::addTransportableStateListener(TransportableStateListener* listener) {
1388 3895 : if (find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener) == myTransportableStateListeners.end()) {
1389 3895 : myTransportableStateListeners.push_back(listener);
1390 : }
1391 3895 : }
1392 :
1393 :
1394 : void
1395 0 : MSNet::removeTransportableStateListener(TransportableStateListener* listener) {
1396 0 : std::vector<TransportableStateListener*>::iterator i = std::find(myTransportableStateListeners.begin(), myTransportableStateListeners.end(), listener);
1397 0 : if (i != myTransportableStateListeners.end()) {
1398 0 : myTransportableStateListeners.erase(i);
1399 : }
1400 0 : }
1401 :
1402 :
1403 : void
1404 1006810 : MSNet::informTransportableStateListener(const MSTransportable* const transportable, TransportableState to, const std::string& info) {
1405 : #ifdef HAVE_FOX
1406 1006810 : ScopedLocker<> lock(myTransportableStateListenerMutex, MSGlobals::gNumThreads > 1);
1407 : #endif
1408 1009559 : for (TransportableStateListener* const listener : myTransportableStateListeners) {
1409 2749 : listener->transportableStateChanged(transportable, to, info);
1410 : }
1411 1006810 : }
1412 :
1413 :
1414 : bool
1415 17680 : MSNet::registerCollision(const SUMOTrafficObject* collider, const SUMOTrafficObject* victim, const std::string& collisionType, const MSLane* lane, double pos) {
1416 : auto it = myCollisions.find(collider->getID());
1417 17680 : if (it != myCollisions.end()) {
1418 8497 : for (Collision& old : it->second) {
1419 8392 : if (old.victim == victim->getID()) {
1420 : // collision from previous step continues
1421 7614 : old.continuationTime = myStep;
1422 : return false;
1423 : }
1424 : }
1425 : } else {
1426 : // maybe the roles have been reversed
1427 : auto it2 = myCollisions.find(victim->getID());
1428 9961 : if (it2 != myCollisions.end()) {
1429 3951 : for (Collision& old : it2->second) {
1430 3775 : if (old.victim == collider->getID()) {
1431 : // collision from previous step continues (keep the old roles)
1432 3596 : old.continuationTime = myStep;
1433 : return false;
1434 : }
1435 : }
1436 : }
1437 : }
1438 : Collision c;
1439 : c.victim = victim->getID();
1440 6470 : c.colliderType = collider->getVehicleType().getID();
1441 6470 : c.victimType = victim->getVehicleType().getID();
1442 6470 : c.colliderSpeed = collider->getSpeed();
1443 6470 : c.victimSpeed = victim->getSpeed();
1444 6470 : c.colliderFront = collider->getPosition();
1445 6470 : c.victimFront = victim->getPosition();
1446 6470 : c.colliderBack = collider->getPosition(-collider->getVehicleType().getLength());
1447 6470 : c.victimBack = victim->getPosition(-victim->getVehicleType().getLength());
1448 : c.type = collisionType;
1449 6470 : c.lane = lane;
1450 6470 : c.pos = pos;
1451 6470 : c.time = myStep;
1452 6470 : c.continuationTime = myStep;
1453 6470 : myCollisions[collider->getID()].push_back(c);
1454 : return true;
1455 6470 : }
1456 :
1457 :
1458 : void
1459 43936413 : MSNet::removeOutdatedCollisions() {
1460 43954750 : for (auto it = myCollisions.begin(); it != myCollisions.end();) {
1461 36900 : for (auto it2 = it->second.begin(); it2 != it->second.end();) {
1462 18563 : if (it2->continuationTime != myStep) {
1463 6459 : it2 = it->second.erase(it2);
1464 : } else {
1465 : it2++;
1466 : }
1467 : }
1468 18337 : if (it->second.size() == 0) {
1469 : it = myCollisions.erase(it);
1470 : } else {
1471 : it++;
1472 : }
1473 : }
1474 43936413 : }
1475 :
1476 :
1477 : bool
1478 83943 : MSNet::addStoppingPlace(SumoXMLTag category, MSStoppingPlace* stop) {
1479 83943 : if (category == SUMO_TAG_TRAIN_STOP) {
1480 14048 : category = SUMO_TAG_BUS_STOP;
1481 : }
1482 83943 : const bool isNew = myStoppingPlaces[category].add(stop->getID(), stop);
1483 83943 : if (isNew && stop->getMyName() != "") {
1484 15969 : myNamedStoppingPlaces[category][stop->getMyName()].push_back(stop);
1485 : }
1486 83943 : return isNew;
1487 : }
1488 :
1489 :
1490 : bool
1491 17 : MSNet::addTractionSubstation(MSTractionSubstation* substation) {
1492 17 : if (find(myTractionSubstations.begin(), myTractionSubstations.end(), substation) == myTractionSubstations.end()) {
1493 17 : myTractionSubstations.push_back(substation);
1494 17 : return true;
1495 : }
1496 : return false;
1497 : }
1498 :
1499 :
1500 : MSStoppingPlace*
1501 1596715 : MSNet::getStoppingPlace(const std::string& id, const SumoXMLTag category) const {
1502 : if (myStoppingPlaces.count(category) > 0) {
1503 : return myStoppingPlaces.find(category)->second.get(id);
1504 : }
1505 : return nullptr;
1506 : }
1507 :
1508 :
1509 : MSStoppingPlace*
1510 172506 : MSNet::getStoppingPlace(const std::string& id) const {
1511 855134 : 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})) {
1512 719119 : MSStoppingPlace* result = getStoppingPlace(id, category);
1513 719119 : if (result != nullptr) {
1514 : return result;
1515 : }
1516 172506 : }
1517 136015 : return nullptr;
1518 : }
1519 :
1520 :
1521 : std::string
1522 464598 : MSNet::getStoppingPlaceID(const MSLane* lane, const double pos, const SumoXMLTag category) const {
1523 : if (myStoppingPlaces.count(category) > 0) {
1524 954022 : for (const auto& it : myStoppingPlaces.find(category)->second) {
1525 874279 : MSStoppingPlace* stop = it.second;
1526 874279 : if (&stop->getLane() == lane && stop->getBeginLanePosition() - POSITION_EPS <= pos && stop->getEndLanePosition() + POSITION_EPS >= pos) {
1527 : return stop->getID();
1528 : }
1529 : }
1530 : }
1531 359441 : return "";
1532 : }
1533 :
1534 :
1535 : const std::vector<MSStoppingPlace*>&
1536 1590 : MSNet::getStoppingPlaceAlternatives(const std::string& name, SumoXMLTag category) const {
1537 1590 : if (category == SUMO_TAG_TRAIN_STOP) {
1538 : category = SUMO_TAG_BUS_STOP;
1539 : }
1540 : auto it = myNamedStoppingPlaces.find(category);
1541 1590 : if (it != myNamedStoppingPlaces.end()) {
1542 : auto it2 = it->second.find(name);
1543 1515 : if (it2 != it->second.end()) {
1544 1515 : return it2->second;
1545 : }
1546 : }
1547 : return myEmptyStoppingPlaceVector;
1548 : }
1549 :
1550 :
1551 : const NamedObjectCont<MSStoppingPlace*>&
1552 14009 : MSNet::getStoppingPlaces(SumoXMLTag category) const {
1553 : auto it = myStoppingPlaces.find(category);
1554 14009 : if (it != myStoppingPlaces.end()) {
1555 13724 : return it->second;
1556 : } else {
1557 : return myEmptyStoppingPlaceCont;
1558 : }
1559 : }
1560 :
1561 :
1562 : void
1563 100 : MSNet::writeChargingStationOutput() const {
1564 : if (myStoppingPlaces.count(SUMO_TAG_CHARGING_STATION) > 0) {
1565 192 : OutputDevice& output = OutputDevice::getDeviceByOption("chargingstations-output");
1566 574 : for (const auto& it : myStoppingPlaces.find(SUMO_TAG_CHARGING_STATION)->second) {
1567 478 : static_cast<MSChargingStation*>(it.second)->writeChargingStationOutput(output);
1568 : }
1569 : }
1570 100 : }
1571 :
1572 :
1573 : void
1574 40593 : MSNet::writeRailSignalBlocks() const {
1575 81186 : if (OptionsCont::getOptions().isSet("railsignal-block-output")) {
1576 1362 : OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-block-output");
1577 5415 : for (auto tls : myLogics->getAllLogics()) {
1578 4053 : MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1579 4053 : if (rs != nullptr) {
1580 4009 : rs->writeBlocks(output, false);
1581 : }
1582 1362 : }
1583 1362 : MSDriveWay::writeDepatureBlocks(output, false);
1584 : }
1585 81186 : if (OptionsCont::getOptions().isSet("railsignal-vehicle-output")) {
1586 185 : OutputDevice& output = OutputDevice::getDeviceByOption("railsignal-vehicle-output");
1587 599 : for (auto tls : myLogics->getAllLogics()) {
1588 414 : MSRailSignal* rs = dynamic_cast<MSRailSignal*>(tls);
1589 414 : if (rs != nullptr) {
1590 414 : rs->writeBlocks(output, true);
1591 : }
1592 185 : }
1593 185 : MSDriveWay::writeDepatureBlocks(output, true);
1594 : }
1595 40593 : }
1596 :
1597 :
1598 : void
1599 5 : MSNet::writeOverheadWireSegmentOutput() const {
1600 : if (myStoppingPlaces.count(SUMO_TAG_OVERHEAD_WIRE_SEGMENT) > 0) {
1601 10 : OutputDevice& output = OutputDevice::getDeviceByOption("overheadwiresegments-output");
1602 63 : for (const auto& it : myStoppingPlaces.find(SUMO_TAG_OVERHEAD_WIRE_SEGMENT)->second) {
1603 58 : static_cast<MSOverheadWire*>(it.second)->writeOverheadWireSegmentOutput(output);
1604 : }
1605 : }
1606 5 : }
1607 :
1608 :
1609 : void
1610 5 : MSNet::writeSubstationOutput() const {
1611 5 : if (myTractionSubstations.size() > 0) {
1612 5 : OutputDevice& output = OutputDevice::getDeviceByOption("substations-output");
1613 10 : output.setPrecision(OptionsCont::getOptions().getInt("substations-output.precision"));
1614 13 : for (auto& it : myTractionSubstations) {
1615 8 : it->writeTractionSubstationOutput(output);
1616 : }
1617 : }
1618 5 : }
1619 :
1620 :
1621 : MSTractionSubstation*
1622 19 : MSNet::findTractionSubstation(const std::string& substationId) {
1623 22 : for (std::vector<MSTractionSubstation*>::iterator it = myTractionSubstations.begin(); it != myTractionSubstations.end(); ++it) {
1624 22 : if ((*it)->getID() == substationId) {
1625 : return *it;
1626 : }
1627 : }
1628 : return nullptr;
1629 : }
1630 :
1631 :
1632 : MSVehicleRouter&
1633 125540 : MSNet::getRouterTT(int rngIndex, const Prohibitions& prohibited) const {
1634 125540 : if (MSGlobals::gNumSimThreads == 1) {
1635 107420 : rngIndex = 0;
1636 : }
1637 : if (myRouterTT.count(rngIndex) == 0) {
1638 1465 : const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1639 1465 : if (routingAlgorithm == "dijkstra") {
1640 1367 : myRouterTT[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, false, nullptr, true);
1641 : } else {
1642 98 : if (routingAlgorithm != "astar") {
1643 0 : WRITE_WARNINGF(TL("TraCI and Triggers cannot use routing algorithm '%'. using 'astar' instead."), routingAlgorithm);
1644 : }
1645 98 : myRouterTT[rngIndex] = new AStarRouter<MSEdge, SUMOVehicle, MSMapMatcher>(MSEdge::getAllEdges(), true, &MSNet::getTravelTime, nullptr, true);
1646 : }
1647 : }
1648 125540 : myRouterTT[rngIndex]->prohibit(prohibited);
1649 125540 : return *myRouterTT[rngIndex];
1650 : }
1651 :
1652 :
1653 : MSVehicleRouter&
1654 11 : MSNet::getRouterEffort(int rngIndex, const Prohibitions& prohibited) const {
1655 11 : if (MSGlobals::gNumSimThreads == 1) {
1656 11 : rngIndex = 0;
1657 : }
1658 : if (myRouterEffort.count(rngIndex) == 0) {
1659 11 : myRouterEffort[rngIndex] = new DijkstraRouter<MSEdge, SUMOVehicle>(MSEdge::getAllEdges(), true, &MSNet::getEffort, &MSNet::getTravelTime, false, nullptr, true);
1660 : }
1661 11 : myRouterEffort[rngIndex]->prohibit(prohibited);
1662 11 : return *myRouterEffort[rngIndex];
1663 : }
1664 :
1665 :
1666 : MSPedestrianRouter&
1667 815917 : MSNet::getPedestrianRouter(int rngIndex, const Prohibitions& prohibited) const {
1668 815917 : if (MSGlobals::gNumSimThreads == 1) {
1669 727142 : rngIndex = 0;
1670 : }
1671 : if (myPedestrianRouter.count(rngIndex) == 0) {
1672 2812 : myPedestrianRouter[rngIndex] = new MSPedestrianRouter();
1673 : }
1674 815917 : myPedestrianRouter[rngIndex]->prohibit(prohibited);
1675 815917 : return *myPedestrianRouter[rngIndex];
1676 : }
1677 :
1678 :
1679 : MSTransportableRouter&
1680 168979 : MSNet::getIntermodalRouter(int rngIndex, const int routingMode, const Prohibitions& prohibited) const {
1681 168979 : if (MSGlobals::gNumSimThreads == 1) {
1682 : rngIndex = 0;
1683 : }
1684 168979 : const OptionsCont& oc = OptionsCont::getOptions();
1685 168979 : const int key = rngIndex * oc.getInt("thread-rngs") + routingMode;
1686 : if (myIntermodalRouter.count(key) == 0) {
1687 4186 : const int carWalk = SUMOVehicleParserHelper::parseCarWalkTransfer(oc, MSDevice_Taxi::hasFleet() || myInserter->hasTaxiFlow());
1688 3972 : const std::string routingAlgorithm = OptionsCont::getOptions().getString("routing-algorithm");
1689 3972 : const double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1690 3972 : if (routingMode == libsumo::ROUTING_MODE_COMBINED) {
1691 0 : myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode, new FareModul());
1692 : } else {
1693 3972 : myIntermodalRouter[key] = new MSTransportableRouter(MSNet::adaptIntermodalRouter, carWalk, taxiWait, routingAlgorithm, routingMode);
1694 : }
1695 : }
1696 168979 : myIntermodalRouter[key]->prohibit(prohibited);
1697 168979 : return *myIntermodalRouter[key];
1698 : }
1699 :
1700 :
1701 : void
1702 42201 : MSNet::resetIntermodalRouter() const {
1703 46172 : for (auto& router : myIntermodalRouter) {
1704 3971 : delete router.second;
1705 : }
1706 : myIntermodalRouter.clear();
1707 42201 : }
1708 :
1709 :
1710 : void
1711 4939 : MSNet::adaptIntermodalRouter(MSTransportableRouter& router) {
1712 9878 : double taxiWait = STEPS2TIME(string2time(OptionsCont::getOptions().getString("persontrip.taxi.waiting-time")));
1713 : // add access to all parking areas
1714 : EffortCalculator* const external = router.getExternalEffort();
1715 14707 : for (const auto& stopType : myInstance->myStoppingPlaces) {
1716 : // add access to all stopping places
1717 9768 : const SumoXMLTag element = stopType.first;
1718 36037 : for (const auto& i : stopType.second) {
1719 26269 : const MSEdge* const edge = &i.second->getLane().getEdge();
1720 26269 : router.getNetwork()->addAccess(i.first, edge, i.second->getBeginLanePosition(), i.second->getEndLanePosition(),
1721 : 0., element, false, taxiWait);
1722 26269 : if (element == SUMO_TAG_BUS_STOP) {
1723 : // add access to all public transport stops
1724 12767 : for (const auto& a : i.second->getAllAccessPos()) {
1725 1166 : router.getNetwork()->addAccess(i.first, &a.lane->getEdge(), a.startPos, a.endPos, a.length, element, true, taxiWait);
1726 : }
1727 11601 : if (external != nullptr) {
1728 0 : external->addStop(router.getNetwork()->getStopEdge(i.first)->getNumericalID(), *i.second);
1729 : }
1730 : }
1731 : }
1732 : }
1733 4939 : myInstance->getInsertionControl().adaptIntermodalRouter(router);
1734 4939 : myInstance->getVehicleControl().adaptIntermodalRouter(router);
1735 : // add access to transfer from walking to taxi-use
1736 4939 : if ((router.getCarWalkTransfer() & ModeChangeOptions::TAXI_PICKUP_ANYWHERE) != 0) {
1737 66047 : for (MSEdge* edge : myInstance->getEdgeControl().getEdges()) {
1738 65798 : if ((edge->getPermissions() & SVC_PEDESTRIAN) != 0 && (edge->getPermissions() & SVC_TAXI) != 0) {
1739 22575 : router.getNetwork()->addCarAccess(edge, SVC_TAXI, taxiWait);
1740 : }
1741 : }
1742 : }
1743 4939 : }
1744 :
1745 :
1746 : bool
1747 42244 : MSNet::checkElevation() {
1748 42244 : const MSEdgeVector& edges = myEdges->getEdges();
1749 1822278 : for (MSEdgeVector::const_iterator e = edges.begin(); e != edges.end(); ++e) {
1750 3920112 : for (std::vector<MSLane*>::const_iterator i = (*e)->getLanes().begin(); i != (*e)->getLanes().end(); ++i) {
1751 2140078 : if ((*i)->getShape().hasElevation()) {
1752 : return true;
1753 : }
1754 : }
1755 : }
1756 : return false;
1757 : }
1758 :
1759 :
1760 : bool
1761 42244 : MSNet::checkWalkingarea() {
1762 1254360 : for (const MSEdge* e : myEdges->getEdges()) {
1763 1222644 : if (e->getFunction() == SumoXMLEdgeFunc::WALKINGAREA) {
1764 : return true;
1765 : }
1766 : }
1767 : return false;
1768 : }
1769 :
1770 :
1771 : bool
1772 42244 : MSNet::checkBidiEdges() {
1773 1759197 : for (const MSEdge* e : myEdges->getEdges()) {
1774 1718209 : if (e->getBidiEdge() != nullptr) {
1775 : return true;
1776 : }
1777 : }
1778 : return false;
1779 : }
1780 :
1781 : bool
1782 303 : MSNet::warnOnce(const std::string& typeAndID) {
1783 303 : if (myWarnedOnce.find(typeAndID) == myWarnedOnce.end()) {
1784 303 : myWarnedOnce[typeAndID] = true;
1785 303 : return true;
1786 : }
1787 : return false;
1788 : }
1789 :
1790 :
1791 : MSMapMatcher*
1792 35 : MSNet::getMapMatcher() const {
1793 35 : auto loader = myRouteLoaders->getFirstLoader();
1794 35 : if (loader != nullptr) {
1795 35 : return dynamic_cast<MSMapMatcher*>(loader->getRouteHandler());
1796 : } else {
1797 : return nullptr;
1798 : }
1799 : }
1800 :
1801 : void
1802 0 : MSNet::quickReload() {
1803 0 : const OptionsCont& oc = OptionsCont::getOptions();
1804 0 : clearState(string2time(oc.getString("begin")), true);
1805 0 : NLBuilder::initRandomness();
1806 : // load traffic from additional files
1807 0 : for (std::string file : oc.getStringVector("additional-files")) {
1808 : // ignore failure on parsing calibrator flow
1809 0 : MSRouteHandler rh(file, true);
1810 0 : const long before = PROGRESS_BEGIN_TIME_MESSAGE("Loading traffic from '" + file + "'");
1811 0 : if (!XMLSubSys::runParser(rh, file, false)) {
1812 0 : throw ProcessError(TLF("Loading of % failed.", file));
1813 : }
1814 0 : PROGRESS_TIME_MESSAGE(before);
1815 0 : }
1816 0 : delete myRouteLoaders;
1817 0 : myRouteLoaders = NLBuilder::buildRouteLoaderControl(OptionsCont::getOptions());
1818 0 : updateGUI();
1819 0 : }
1820 :
1821 :
1822 : SUMOTime
1823 177 : MSNet::loadState(const std::string& fileName, const bool catchExceptions) {
1824 : // load time only
1825 177 : const SUMOTime newTime = MSStateHandler::MSStateTimeHandler::getTime(fileName);
1826 : // clean up state
1827 167 : clearState(newTime);
1828 : // load state
1829 167 : MSStateHandler h(fileName, 0);
1830 167 : XMLSubSys::runParser(h, fileName, false, false, false, catchExceptions);
1831 163 : if (MsgHandler::getErrorInstance()->wasInformed()) {
1832 0 : throw ProcessError(TLF("Loading state from '%' failed.", fileName));
1833 : }
1834 : // reset route loaders
1835 163 : delete myRouteLoaders;
1836 163 : myRouteLoaders = NLBuilder::buildRouteLoaderControl(OptionsCont::getOptions());
1837 : // prevent loading errors on rewound route file
1838 163 : MSGlobals::gStateLoaded = true;
1839 :
1840 163 : updateGUI();
1841 163 : return newTime;
1842 167 : }
1843 :
1844 :
1845 : /****************************************************************************/
|