Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto refresh config when values change #2085

Merged
merged 3 commits into from
Aug 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ private void setupActorsAndRunPhysSim(int iterationNumber) {
this.beamConfigChangesObservable
);
}
org.matsim.core.mobsim.jdeqsim.JDEQSimulation jdeqSimulation = getJDEQSimulation(jdeqSimScenario, beamConfig,
org.matsim.core.mobsim.jdeqsim.JDEQSimulation jdeqSimulation = getJDEQSimulation(jdeqSimScenario,
jdeqsimEvents, iterationNumber, beamServices.matsimServices().getControlerIO(),
roadCapacityAdjustmentFunction);
linkStatsGraph.notifyIterationStarts(jdeqsimEvents, agentSimScenario.getConfig().travelTimeCalculator());
Expand Down Expand Up @@ -279,12 +279,12 @@ private void setupActorsAndRunPhysSim(int iterationNumber) {

}

public org.matsim.core.mobsim.jdeqsim.JDEQSimulation getJDEQSimulation(MutableScenario jdeqSimScenario, BeamConfig beamConfig,
EventsManager jdeqsimEvents, int iterationNumber,
OutputDirectoryHierarchy controlerIO,
RoadCapacityAdjustmentFunction roadCapacityAdjustmentFunction) {
public org.matsim.core.mobsim.jdeqsim.JDEQSimulation getJDEQSimulation(MutableScenario jdeqSimScenario, EventsManager jdeqsimEvents,
int iterationNumber, OutputDirectoryHierarchy controlerIO, RoadCapacityAdjustmentFunction roadCapacityAdjustmentFunction) {
JDEQSimConfigGroup config = new JDEQSimConfigGroup();
config.setFlowCapacityFactor(beamConfig.beam().physsim().flowCapacityFactor());
double flowCapacityFactor = beamConfig.beam().physsim().flowCapacityFactor();

config.setFlowCapacityFactor(flowCapacityFactor);
config.setStorageCapacityFactor(beamConfig.beam().physsim().storageCapacityFactor());
config.setSimulationEndTime(beamConfig.matsim().modules().qsim().endTime());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ public class Hao2018CaccRoadCapacityAdjustmentFunction implements RoadCapacityAd

private int nonCACCCategoryRoadsTravelled = 0;
private int caccCategoryRoadsTravelled = 0;
private double flowCapacityFactor;
private final MultiValuedMap<Double, Double> caccCapacityIncrease = new ArrayListValuedHashMap<>();
private final Map<String, Double> caccLinkCapacityIncrease = new HashMap<>();
private final Map<String, Double> allLinksCapacityIncrease = new HashMap<>();
Expand All @@ -66,7 +65,6 @@ public Hao2018CaccRoadCapacityAdjustmentFunction(BeamConfig beamConfig, int iter
double caccMinRoadCapacity = beamConfig.beam().physsim().jdeqsim().cacc().minRoadCapacity();
double caccMinSpeedMetersPerSec = beamConfig.beam().physsim().jdeqsim().cacc().minSpeedMetersPerSec();
log.info("caccMinRoadCapacity: " + caccMinRoadCapacity + ", caccMinSpeedMetersPerSec: " + caccMinSpeedMetersPerSec);
this.flowCapacityFactor = beamConfig.beam().physsim().flowCapacityFactor();
this.caccMinRoadCapacity = caccMinRoadCapacity;
this.caccMinSpeedMetersPerSec = caccMinSpeedMetersPerSec;
this.currentIterationNumber = iterationNumber;
Expand Down
20 changes: 5 additions & 15 deletions src/main/java/beam/physsim/jdeqsim/cacc/sim/Road.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ public double getInitialCACCShare(Vehicle vehicle){

@Override
public void enterRoad(org.matsim.core.mobsim.jdeqsim.Vehicle vehicle, double simTime) {

double nextAvailableTimeForLeavingStreet = getNextAvailableTimeForLeavingStreet(simTime);

markCarAsProcessed((Vehicle) vehicle);
Expand All @@ -97,33 +96,24 @@ public void enterRoad(org.matsim.core.mobsim.jdeqsim.Vehicle vehicle, double sim
updateEarliestDepartureTimeOfCar(nextAvailableTimeForLeavingStreet);

if (onlyOneCarRoad()) {



nextAvailableTimeForLeavingStreet=Math.max(nextAvailableTimeForLeavingStreet,
this.timeOfLastLeavingVehicle + getInverseCapacity(vehicle,simTime));
double lastTimeLEavingPlusInverseCapacity = timeOfLastLeavingVehicle + getInverseCapacity(vehicle, simTime);
nextAvailableTimeForLeavingStreet = Math.max(nextAvailableTimeForLeavingStreet, lastTimeLEavingPlusInverseCapacity);
vehicle.scheduleEndRoadMessage(nextAvailableTimeForLeavingStreet, this);
}

}




private double getInverseCapacity(org.matsim.core.mobsim.jdeqsim.Vehicle vehicle, double simTime){
double caccShare=getInitialCACCShare((Vehicle) vehicle);

if (caccShareEncounteredByVehicle.containsKey(vehicle)){
caccShare=caccShareEncounteredByVehicle.remove(vehicle);
}

return (1/roadCapacityAdjustmentFunction.getCapacityWithCACCPerSecond(link,caccShare,simTime)*config.getFlowCapacityFactor());
double capacityWithCACCPerSecond = roadCapacityAdjustmentFunction.getCapacityWithCACCPerSecond(link, caccShare, simTime);
double flowCapacityFactor = config.getFlowCapacityFactor();
return (1 / capacityWithCACCPerSecond * flowCapacityFactor);
}





private LinkedList<Double> gap_;
private LinkedList<org.matsim.core.mobsim.jdeqsim.Vehicle> interestedInEnteringRoad_;
LinkedList<DeadlockPreventionMessage> deadlockPreventionMessages_;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,30 @@
package beam.agentsim.agents.modalbehaviors

import akka.actor.FSM.Failure
import scala.collection.mutable

import akka.actor.{ActorRef, Stash}
import akka.actor.FSM.Failure
import beam.agentsim.Resource.{NotifyVehicleIdle, ReleaseParkingStall}
import beam.agentsim.agents.BeamAgent
import beam.agentsim.agents.PersonAgent._
import beam.agentsim.agents.modalbehaviors.DrivesVehicle._
import beam.agentsim.agents.ridehail.RideHailAgent._
import beam.agentsim.agents.vehicles._
import beam.agentsim.agents.vehicles.AccessErrorCodes.VehicleFullError
import beam.agentsim.agents.vehicles.BeamVehicle.{BeamVehicleState, FuelConsumed}
import beam.agentsim.agents.vehicles.FuelType.{Electricity, Gasoline}
import beam.agentsim.agents.vehicles.VehicleProtocol._
import beam.agentsim.agents.vehicles._
import beam.agentsim.events.{
ChargingPlugInEvent,
ChargingPlugOutEvent,
ParkEvent,
PathTraversalEvent,
RefuelSessionEvent,
SpaceTime
}
import beam.agentsim.events.{ChargingPlugInEvent, ParkEvent, PathTraversalEvent, SpaceTime}
import beam.agentsim.infrastructure.ParkingStall
import beam.agentsim.scheduler.BeamAgentScheduler.{CompletionNotice, ScheduleTrigger, SchedulerMessage}
import beam.agentsim.scheduler.Trigger
import beam.agentsim.scheduler.Trigger.TriggerWithId
import beam.router.Modes.BeamMode
import beam.router.Modes.BeamMode.{TRANSIT, WALK}
import beam.router.Modes.BeamMode.WALK
import beam.router.model.{BeamLeg, BeamPath}
import beam.router.osm.TollCalculator
import beam.sim.BeamScenario
import beam.sim.{BeamConfigChangesObservable, BeamScenario}
import beam.sim.common.GeoUtils
import beam.sim.config.BeamConfig
import beam.utils.NetworkHelper
import com.conveyal.r5.transit.TransportNetwork
import org.matsim.api.core.v01.Id
Expand All @@ -43,8 +38,6 @@ import org.matsim.api.core.v01.population.Person
import org.matsim.core.api.experimental.events.EventsManager
import org.matsim.vehicles.Vehicle

import scala.collection.mutable

/**
* DrivesVehicle
*/
Expand Down Expand Up @@ -204,6 +197,8 @@ trait DrivesVehicle[T <: DrivingData] extends BeamAgent[T] with Stash {
protected val fuelConsumedByTrip: mutable.Map[Id[Person], FuelConsumed] = mutable.Map()
var latestObservedTick: Int = 0

private def beamConfig: BeamConfig = BeamConfigChangesObservable.lastBeamConfig

case class PassengerScheduleEmptyMessage(
lastVisited: SpaceTime,
toll: Double,
Expand Down Expand Up @@ -242,8 +237,8 @@ trait DrivesVehicle[T <: DrivingData] extends BeamAgent[T] with Stash {
var nbPassengers = data.passengerSchedule.schedule(currentLeg).riders.size
if (nbPassengers > 0) {
if (currentLeg.mode.isTransit) {
nbPassengers =
(nbPassengers / beamScenario.beamConfig.beam.agentsim.tuning.transitCapacity.getOrElse(1.0)).toInt
val transitCapacity = beamConfig.beam.agentsim.tuning.transitCapacity
nbPassengers = (nbPassengers / transitCapacity.getOrElse(1.0)).toInt
}
data.passengerSchedule.schedule(currentLeg).riders foreach { rider =>
updateFuelConsumedByTrip(rider.personId, fuelConsumed, nbPassengers)
Expand All @@ -264,12 +259,6 @@ trait DrivesVehicle[T <: DrivingData] extends BeamAgent[T] with Stash {
)
)
}
// log.debug(
// "DrivesVehicle.Driving.nextNotifyVehicleResourceIdle:{}, vehicleId({}) - tick({})",
// nextNotifyVehicleResourceIdle,
// currentVehicleUnderControl,
// tick
// )

data.passengerSchedule.schedule(currentLeg).alighters.foreach { pv =>
logDebug(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,25 @@ import org.matsim.api.core.v01.Id
import org.matsim.api.core.v01.population.Activity
import org.matsim.core.population.PopulationUtils
import org.matsim.core.utils.collections.QuadTree

import scala.collection.JavaConverters._
import scala.collection.immutable.List
import scala.collection.mutable.ListBuffer

import beam.sim.config.BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager

class AlonsoMoraPoolingAlgForRideHail(
spatialDemand: QuadTree[CustomerRequest],
supply: List[VehicleAndSchedule],
beamServices: BeamServices,
skimmer: BeamSkimmer
) {

var solutionSpaceSizePerVehicle =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.solutionSpaceSizePerVehicle

var waitingTimeInSec =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.waitingTimeInSec
// Methods below should be kept as def (instead of val) to allow automatic value updating
private def alonsoMora: AllocationManager.AlonsoMora =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora
private def solutionSpaceSizePerVehicle: Int = alonsoMora.solutionSpaceSizePerVehicle
private def waitingTimeInSec: Int = alonsoMora.waitingTimeInSec

var travelTimeDelayAsFraction =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.travelTimeDelayAsFraction
val rvG = RVGraph(classOf[RideHailTrip])
val rTvG = RTVGraph(classOf[DefaultEdge])
// Request Vehicle Graph
Expand Down Expand Up @@ -273,10 +272,11 @@ object AlonsoMoraPoolingAlgForRideHail {
)(
implicit skimmer: BeamSkimmer
): CustomerRequest = {
val waitingTimeInSec =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.waitingTimeInSec
val travelTimeDelayAsFraction =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.travelTimeDelayAsFraction
val alonsoMora: AllocationManager.AlonsoMora =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora
val waitingTimeInSec = alonsoMora.waitingTimeInSec
val travelTimeDelayAsFraction = alonsoMora.travelTimeDelayAsFraction

val p1Act1: Activity = PopulationUtils.createActivityFromCoord(s"${vehiclePersonId.personId}Act1", src)
p1Act1.setEndTime(departureTime)
val p1Act2: Activity = PopulationUtils.createActivityFromCoord(s"${vehiclePersonId.personId}Act2", dst)
Expand Down Expand Up @@ -324,10 +324,6 @@ object AlonsoMoraPoolingAlgForRideHail {
beamServices: BeamServices,
remainingRangeInMeters: Double
): VehicleAndSchedule = {
val waitingTimeInSec =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.waitingTimeInSec
val travelTimeDelayAsFraction =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.travelTimeDelayAsFraction
val v1 = new BeamVehicle(
Id.create(veh.vehicleId, classOf[BeamVehicle]),
new Powertrain(0.0),
Expand All @@ -338,6 +334,12 @@ object AlonsoMoraPoolingAlgForRideHail {
val v1Act0: Activity = PopulationUtils.createActivityFromCoord(s"${veh.vehicleId}Act0", vehCurrentLocation)
v1Act0.setEndTime(tick)
var alonsoSchedule: ListBuffer[MobilityRequest] = ListBuffer()

val alonsoMora: AllocationManager.AlonsoMora =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora
val waitingTimeInSec = alonsoMora.waitingTimeInSec
val travelTimeDelayAsFraction = alonsoMora.travelTimeDelayAsFraction

veh.currentPassengerSchedule.foreach {
_.schedule.foreach {
case (leg, manifest) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,19 @@ class AsyncAlonsoMoraAlgForRideHail(
skimmer: BeamSkimmer
) {

var solutionSpaceSizePerVehicle =
private val solutionSpaceSizePerVehicle =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.solutionSpaceSizePerVehicle

var waitingTimeInSec =
private val waitingTimeInSec =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.waitingTimeInSec

var travelTimeDelayAsFraction =
beamServices.beamConfig.beam.agentsim.agents.rideHail.allocationManager.alonsoMora.travelTimeDelayAsFraction

private def matchVehicleRequests(v: VehicleAndSchedule): (List[RTVGraphNode], List[(RTVGraphNode, RTVGraphNode)]) = {
import scala.collection.mutable.{ListBuffer => MListBuffer}
val vertices = MListBuffer.empty[RTVGraphNode]
val edges = MListBuffer.empty[(RTVGraphNode, RTVGraphNode)]
val finalRequestsList = MListBuffer.empty[RideHailTrip]
val center = v.getRequestWithCurrentVehiclePosition.activity.getCoord

val searchRadius = waitingTimeInSec * BeamSkimmer.speedMeterPerSec(BeamMode.CAV)
val requests = v.geofence match {
case Some(gf) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,8 @@ class RideHailManager(
.build()
}

private val fleet: Double = beamServices.beamConfig.beam.agentsim.agents.vehicles.fractionOfInitialVehicleFleet

private val initialNumHouseholdVehicles = scenario.getHouseholds.getHouseholds
.values()
.asScala
Expand All @@ -262,7 +264,7 @@ class RideHailManager(
}
}
.filter(beamVehicleType => beamVehicleType.vehicleCategory == VehicleCategory.Car)
.size / beamServices.beamConfig.beam.agentsim.agents.vehicles.fractionOfInitialVehicleFleet
.size / fleet
// Undo sampling to estimate initial number

val numRideHailAgents: Long = math.round(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,23 @@ class DemandFollowingRepositioningManager(val beamServices: BeamServices, val ri
extends RepositioningManager(beamServices, rideHailManager)
with LazyLogging {

val cfg =
beamServices.beamConfig.beam.agentsim.agents.rideHail.repositioningManager.demandFollowingRepositioningManager

val intervalSize: Int =
rideHailManager.beamServices.beamConfig.beam.agentsim.agents.rideHail.repositioningManager.timeout
private val activitySegment: ActivitySegment = {
val intervalSize: Int =
rideHailManager.beamServices.beamConfig.beam.agentsim.agents.rideHail.repositioningManager.timeout

val activitySegment: ActivitySegment =
ProfilingUtils.timed(s"Build ActivitySegment with intervalSize $intervalSize", x => logger.info(x)) {
ActivitySegment(rideHailManager.beamServices.matsimServices.getScenario, intervalSize)
}
}

// When we have all activities, we can make `sensitivityOfRepositioningToDemand` in the range from [0, 1] to make it easer to calibrate
// If sensitivityOfRepositioningToDemand = 1, it means all vehicles reposition all the time
// sensitivityOfRepositioningToDemand = 0, means no one reposition
private val cfg =
beamServices.beamConfig.beam.agentsim.agents.rideHail.repositioningManager.demandFollowingRepositioningManager

val sensitivityOfRepositioningToDemand: Double = cfg.sensitivityOfRepositioningToDemand
val numberOfClustersForDemand = cfg.numberOfClustersForDemand
val numberOfClustersForDemand: Int = cfg.numberOfClustersForDemand
val rndGen: Random = new Random(beamServices.beamConfig.matsim.modules.global.randomSeed)
val rng = new MersenneTwister(beamServices.beamConfig.matsim.modules.global.randomSeed) // Random.org

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,8 @@ class BeamScoringFunctionFactory @Inject()(
val t = o.asInstanceOf[(_, _)]
val beamConfig = t._2.asInstanceOf[BeamConfig]
this.beamConfig = beamConfig

}

}

/**
Expand Down
15 changes: 13 additions & 2 deletions src/main/scala/beam/sim/BeamConfigChangesObservable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import javax.inject.{Inject, Singleton}
@Singleton
class BeamConfigChangesObservable @Inject()(beamConfig: BeamConfig) extends java.util.Observable {

var lastBeamConfig: BeamConfig = beamConfig
BeamConfigChangesObservable.lastBeamConfigValue = beamConfig

def getUpdatedBeamConfig: BeamConfig = {
val configFileLocation = System.getProperty(BeamConfigChangesObservable.configFileLocationString)
Option(configFileLocation) match {
Expand All @@ -20,16 +23,24 @@ class BeamConfigChangesObservable @Inject()(beamConfig: BeamConfig) extends java

def notifyChangeToSubscribers() {
setChanged()
val beamConfig = getUpdatedBeamConfig
notifyObservers(this, beamConfig)
val updatedBeamConfig = getUpdatedBeamConfig
lastBeamConfig = updatedBeamConfig
BeamConfigChangesObservable.lastBeamConfigValue = updatedBeamConfig
notifyObservers(this, updatedBeamConfig)
}

}

object BeamConfigChangesObservable {

private var lastBeamConfigValue: BeamConfig = _

def lastBeamConfig: BeamConfig = lastBeamConfigValue

val configFileLocationString = "configFileLocation"

def clear(): Unit = {
System.clearProperty(configFileLocationString)
}

}
4 changes: 3 additions & 1 deletion src/main/scala/beam/sim/BeamHelper.scala
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ trait BeamHelper extends LazyLogging {
// This code will be executed 3 times due to this https://github.com/LBNL-UCB-STI/matsim/blob/master/matsim/src/main/java/org/matsim/core/controler/Injector.java#L99:L101
// createMapBindingsForType is called 3 times. Be careful not to do expensive operations here
bind(classOf[BeamConfigHolder])
bind(classOf[BeamConfigChangesObservable]).toInstance(new BeamConfigChangesObservable(beamConfig))
val beamConfigChangesObservable = new BeamConfigChangesObservable(beamConfig)

bind(classOf[BeamConfigChangesObservable]).toInstance(beamConfigChangesObservable)
bind(classOf[PrepareForSim]).to(classOf[BeamPrepareForSim])
bind(classOf[RideHailSurgePricingManager]).asEagerSingleton()

Expand Down
Loading