21 package org.matsim.core.mobsim.qsim;
23 import com.google.inject.Injector;
24 import org.apache.logging.log4j.LogManager;
25 import org.apache.logging.log4j.Logger;
65 import jakarta.inject.Inject;
67 import java.util.Map.Entry;
68 import java.util.concurrent.atomic.AtomicLong;
100 final private static Logger
log = LogManager.getLogger(
QSim.class);
140 if (analyzeRunTimes) this.mobsimEngineRunTimes =
new HashMap<>();
141 else this.mobsimEngineRunTimes = null;
151 public synchronized void arrangeNextAgentState(
MobsimAgent agent) {
156 public QSim getMobsim() {
161 public synchronized void registerAdditionalAgentOnLink(
final MobsimAgent planAgent) {
175 @Override
public final List<DepartureHandler> getDepartureHandlers() {
188 activityHandler.rescheduleActivityEnd( agent );
208 this.listenerManager =
new MobsimListenerManager(
this );
220 boolean tryBlockWithException =
false;
223 this.departureHandlers.add(this.teleportationEngine);
226 this.activityHandlers.add(this.activityEngine);
229 this.listenerManager.fireQueueSimulationInitializedEvent();
238 for (
MobsimAgent agent :
new ArrayList<>(this.agents.values())) {
243 boolean doContinue =
true;
245 doContinue = doSimStep();
248 tryBlockWithException =
true;
249 throw tryBlockException;
257 if (tryBlockWithException) {
260 log.warn(
"exception in finally block - " 261 +
"this may be a follow-up exception of an exception thrown in the try block.",
265 throw cleanupException;
289 mobsimEngine.onPrepareSim();
294 for (
AgentSource agentSource : this.agentSources) {
295 agentSource.insertAgentsIntoMobsim();
306 if (this.netEngine != null) {
310 log.warn(
"not able to add parked vehicle since there is no netsim engine. continuing anyway, but it may " 311 +
"not be clear what this means ...") ;
319 this.vehicles.
put( veh.
getId(), veh ) ;
333 return Collections.unmodifiableMap( this.vehicles ) ;
337 this.listenerManager.fireQueueSimulationBeforeCleanupEvent();
339 boolean gotException =
false;
343 mobsimEngine.afterSim();
346 log.error(
"got exception while cleaning up", e);
351 if (gotException)
throw new RuntimeException(
"got exception while cleaning up the QSim. Please check the error messages above for details.");
353 if (analyzeRunTimes) {
354 log.info(
"qsim internal cpu time (nanos): " + qSimInternalTime);
355 for (Entry<MobsimEngine, AtomicLong> entry : this.mobsimEngineRunTimes.entrySet()) {
356 log.info(entry.getKey().getClass().toString() +
" cpu time (nanos): " + entry.getValue().get());
360 ((QNetsimEngineI)this.netEngine).printEngineRunTimes();
371 boolean doSimStep() {
372 if (analyzeRunTimes) this.startClockTime = System.nanoTime();
376 this.listenerManager.fireQueueSimulationBeforeSimStepEvent(now);
378 if (analyzeRunTimes) this.qSimInternalTime += System.nanoTime() - this.
startClockTime;
384 if (this.withindayEngine != null) {
385 if (analyzeRunTimes) startClockTime = System.nanoTime();
387 if (analyzeRunTimes) this.mobsimEngineRunTimes.get(this.withindayEngine).addAndGet(System.nanoTime() - this.
startClockTime);
392 if (analyzeRunTimes) this.startClockTime = System.nanoTime();
395 if (mobsimEngine == this.withindayEngine)
continue;
397 mobsimEngine.doSimStep(now);
400 this.mobsimEngineRunTimes.get(mobsimEngine).addAndGet(System.nanoTime() - this.
startClockTime);
403 if (analyzeRunTimes) this.startClockTime = System.nanoTime();
412 this.listenerManager.fireQueueSimulationAfterSimStepEvent(now);
416 boolean doContinue = (this.
agentCounter.isLiving() && (this.stopTime > now));
425 if (analyzeRunTimes) this.qSimInternalTime += System.nanoTime() - this.
startClockTime;
431 if (this.agents.containsKey(agent.
getId())) {
432 throw new RuntimeException(
"Agent with same Id (" + agent.
getId().toString() +
") already in mobsim; aborting ... ") ;
434 this.agents.put(agent.
getId(), agent);
438 if ( !allpersons.
getPersons().containsKey( ((HasPerson) agent).getPerson().getId() ) ){
439 allpersons.
addPerson( ((HasPerson) agent).getPerson() );
458 this.agents.remove(agent.
getId()) ;
469 if (activityHandler.handleActivity(agent)) {
486 String routingMode = null;
489 Leg currentLeg = (
Leg) ((PlanAgent) agent).getCurrentPlanElement();
496 if (departureHandler.handleDeparture(now, agent, linkId)) {
500 log.warn(
"no departure handler wanted to handle the departure of agent " + agent.
getId());
513 if (this.stopTime == 0) {
514 this.stopTime = Double.MAX_VALUE;
520 simStartTime = Math.floor(Math.max(configuredStartTime, firstAgentStartTime));
522 simStartTime = configuredStartTime;
524 throw new RuntimeException(
"unkonwn starttimeInterpretation; aborting ...");
528 this.simTimer.
setTime(simStartTime);
533 double firstAgentStartTime = Double.POSITIVE_INFINITY;
535 firstAgentStartTime = Math.min(firstAgentStartTime, agent.getActivityEndTime());
537 return firstAgentStartTime;
545 if (time >= this.infoTime) {
548 Date endtime =
new Date();
549 long diffreal = (endtime.getTime() - this.realWorldStarttime
555 +
"s realT=" + (diffreal) +
"s; (s/r): " 556 + (diffsim / (diffreal + Double.MIN_VALUE)));
605 agentTrackers.add((AgentTracker) mobsimEngine);
608 this.activityEngine = (ActivityEngine) mobsimEngine;
611 agentTrackers.add(((HasAgentTracker) mobsimEngine).getAgentTracker());
614 this.netEngine = (NetsimEngine) mobsimEngine;
617 this.teleportationEngine = (TeleportationEngine) mobsimEngine;
620 this.withindayEngine = (WithinDayEngine) mobsimEngine;
623 this.mobsimEngines.add(mobsimEngine);
625 if (analyzeRunTimes) this.mobsimEngineRunTimes.put(mobsimEngine,
new AtomicLong());
636 this.departureHandlers.add(departureHandler);
644 this.activityHandlers.add( activityHandler );
654 this.listenerManager.addQueueSimulationListener(listener);
664 this.listenerManager.addQueueSimulationListener(listener);
681 return Collections.unmodifiableMap(this.agents);
685 this.agentSources.add(agentSource);
693 public Collection<AgentSnapshotInfo> addAgentSnapshotInfo(Collection<AgentSnapshotInfo> positions) {
695 if (mobsimEngine instanceof
VisData) {
696 VisData visData = (VisData) mobsimEngine;
706 return Collections.unmodifiableCollection(agentTrackers) ;
716 boolean processed = false ;
719 ((NetworkChangeEventsEngineI) engine).addNetworkChangeEvent( event );
724 throw new RuntimeException(
"received a network change event, but did not process it. Maybe " +
725 "the network change events engine was not set up for the qsim? Aborting ...") ;
final Collection< MobsimEngine > mobsimEngines
final List< AgentSource > agentSources
double orElse(double other)
static String getRoutingMode(Leg leg)
static final String ONLYONCE
static boolean analyzeRunTimes
final double getSimStartTime()
void arrangeNextAgentAction(final MobsimAgent agent)
void addMobsimEngine(MobsimEngine mobsimEngine)
MobsimAgent unregisterAdditionalAgentOnLink(Id< Person > agentId, Id< Link > linkId)
void addAgentSource(AgentSource agentSource)
static void assertIf(boolean flag)
final List< ActivityHandler > activityHandlers
final List< DepartureHandler > departureHandlers
void addQueueSimulationListeners(MobsimListener listener)
void arrangeAgentActivity(final MobsimAgent agent)
Map< Id< Person >, MobsimAgent > getAgents()
boolean containsKey(Object key)
final MobsimTimer simTimer
Map< Id< VehicleType >, VehicleType > getVehicleTypes()
NetsimNetwork getNetsimNetwork()
QSim(final Scenario sc, EventsManager events, Injector childInjector)
void registerAdditionalAgentOnLink(MobsimAgent planAgent)
static Vehicles getOrCreateAllvehicles(Scenario scenario)
EndtimeInterpretation getSimEndtimeInterpretation()
void afterSimStep(double time)
void addVehicleType(final VehicleType type)
Map< Id< Vehicle >, MobsimVehicle > getVehicles()
OptionalTime getStartTime()
Map< Id< Person >,? extends Person > getPersons()
final Date realWorldStarttime
Id< Link > getCurrentLinkId()
void setInternalInterface(InternalInterface internalInterface)
void insertAgentIntoMobsim(final MobsimAgent agent)
MobsimTimer getSimTimer()
final Map< Id< Person >, MobsimAgent > agents
Collection< AgentTracker > getAgentTrackers()
void processEvent(final Event event)
final Injector childInjector
StarttimeInterpretation getSimStarttimeInterpretation()
void arrangeAgentDeparture(final MobsimAgent agent)
void addVehicle(final Vehicle v)
TeleportationEngine teleportationEngine
double calculateFirstAgentStartTime()
VisData getNonNetworkAgentSnapshots()
static Population getOrCreateAllpersons(Scenario scenario)
ActivityEngine activityEngine
final Map< MobsimEngine, AtomicLong > mobsimEngineRunTimes
Injector getChildInjector()
void setSimStartTime(double startTimeSec)
static final String writeTime(final double seconds, final String timeformat)
NetsimNetwork getNetsimNetwork()
static void assertNotNull(Object obj)
void addDepartureHandler(DepartureHandler departureHandler)
EventsManager getEventsManager()
void addActivityHandler(ActivityHandler activityHandler)
final Collection< AgentTracker > agentTrackers
AgentCounter getAgentCounter()
final Id< VehicleType > getId()
void printSimLog(final double time)
Map< Id< Vehicle >, Vehicle > getVehicles()
void doSimStep(double time)
final void rescheduleActivityEnd(MobsimAgent agent)
WithinDayEngine withindayEngine
final IdMap< Vehicle, MobsimVehicle > vehicles
Collection< AgentSnapshotInfo > addAgentSnapshotInfo(final Collection< AgentSnapshotInfo > positions)
V put(Id< T > key, V value)
void addPerson(final Person p)
void addParkedVehicle(MobsimVehicle veh, Id< Link > linkId)
final void addNetworkChangeEvent(NetworkChangeEvent event)
OptionalTime getEndTime()
VisNetwork getVisNetwork()
static EventsManager getParallelFeedableInstance(EventsManager events)
final MobsimListenerManager listenerManager
maxOfStarttimeAndEarliestActivityEnd
final EventsManager events
final org.matsim.core.mobsim.qsim.AgentCounter agentCounter
void addParkedVehicle(MobsimVehicle veh, Id< Link > startLinkId)
void setTime(double timeSec)
static final int INFO_PERIOD