From 459c09cb0175f58869a88d157c7bd5bc359155a2 Mon Sep 17 00:00:00 2001 From: Colin Sheppard Date: Mon, 12 Nov 2018 17:20:46 -0800 Subject: [PATCH 1/2] been a while since we did a fmt --- .../beam/agentsim/agents/Population.scala | 11 +- .../mode/ModeChoiceDriveIfAvailable.scala | 5 +- .../agents/choice/mode/ModeChoiceLCCM.scala | 31 +- .../mode/ModeChoiceMultinomialLogit.scala | 49 +- .../mode/ModeChoiceRideHailIfAvailable.scala | 5 +- .../mode/ModeChoiceTransitIfAvailable.scala | 5 +- .../choice/mode/ModeChoiceUniformRandom.scala | 5 +- .../agents/choice/mode/ModeSubsidy.scala | 3 +- .../agentsim/agents/choice/mode/Range.scala | 4 +- .../agents/household/HouseholdActor.scala | 77 +- .../agents/modalbehaviors/ChoosesMode.scala | 176 +- .../modalbehaviors/ModeChoiceCalculator.scala | 35 +- .../agents/ridehail/RideHailManager.scala | 51 +- .../allocation/EVFleetAllocationManager.scala | 2 +- .../agents/vehicles/BeamVehicleType.scala | 41 +- .../vehicles/EnergyEconomyAttributes.scala | 3 +- .../events/handling/BeamEventsWriterXML.scala | 18 +- .../IndexerForZonalParkingManager.scala | 56 +- .../infrastructure/ZonalParkingManager.scala | 6 +- .../agentsim/scheduler/TriggerMeasurer.scala | 19 +- .../beam/calibration/BeamSigoptTuner.scala | 7 +- .../calibration/CalibrationArguments.scala | 16 +- .../beam/calibration/ExperimentRunner.scala | 48 +- .../beam/calibration/RunCalibration.scala | 3 - .../calibration/SigoptExperimentData.scala | 11 +- .../calibration/utils/CreateExperiment.scala | 1 - .../calibration/utils/DeleteSuggestion.scala | 4 +- .../scala/beam/experiment/ExperimentApp.scala | 7 +- .../scala/beam/experiment/ExperimentDef.scala | 10 +- .../beam/experiment/ExperimentGenerator.scala | 3 - .../utilitybased/ChangeModeForTour.scala | 90 +- src/main/scala/beam/router/BeamRouter.scala | 15 +- .../beam/router/LinkTravelTimeContainer.scala | 7 +- .../beam/router/TransitInitializer.scala | 3 +- .../beam/router/osm/TollCalculator.scala | 22 +- .../router/r5/DefaultNetworkCoordinator.scala | 1 - ...FrequencyAdjustingNetworkCoordinator.scala | 63 +- .../beam/router/r5/NetworkCoordinator.scala | 43 +- .../beam/router/r5/R5RoutingWorker.scala | 275 +-- .../scoring/BeamScoringFunctionFactory.scala | 24 +- .../scala/beam/sim/BeamGraphComparator.scala | 74 +- src/main/scala/beam/sim/BeamHelper.scala | 33 +- src/main/scala/beam/sim/BeamMobsim.scala | 6 +- src/main/scala/beam/sim/BeamServices.scala | 49 +- src/main/scala/beam/sim/BeamSim.scala | 53 +- .../sim/LoggingParallelEventsManager.scala | 3 +- .../scala/beam/sim/config/BeamConfig.scala | 1621 +++++++++++------ ...ffusionPotentialPopulationAdjustment.scala | 4 +- .../sim/population/PopulationAdjustment.scala | 61 +- .../sim/population/PopulationAttributes.scala | 38 +- .../scala/beam/utils/BeamConfigUtils.scala | 2 +- src/main/scala/beam/utils/SpatialPlot.scala | 3 - src/main/scala/beam/utils/StuckFinder.scala | 36 +- .../MatsimPlanConversion.scala | 11 +- .../VehiclesDataConversion.scala | 4 +- .../scala/beam/utils/plan/PlansBuilder.scala | 32 +- .../plan/sampling/AvailableModeUtils.scala | 8 +- .../utils/plan/sampling/PlansSamplerApp.scala | 16 +- .../scala/beam/agentsim/SingleModeSpec.scala | 64 +- .../agentsim/agents/GenericEventsSpec.scala | 1 - .../agents/OtherPersonAgentSpec.scala | 26 +- .../agentsim/agents/PersonAgentSpec.scala | 221 ++- .../RideHailPassengersEventsSpec.scala | 1 - .../graph/ModeChosenStatsGraphSpec.scala | 6 +- .../PersonTravelTimeStatsGraphSpec.scala | 5 +- .../RideHailingWaitingSingleStatsSpec.scala | 5 +- .../IndexerForZonalParkingManagerTest.scala | 37 +- .../calibration/BeamSigoptTunerSpec.scala | 28 +- .../scala/beam/router/RoutingModelSpec.scala | 84 +- .../router/TimeDependentRoutingSpec.scala | 120 +- .../scala/beam/router/TollRoutingSpec.scala | 96 +- .../beam/router/WarmStartRoutingSpec.scala | 63 +- .../beam/router/osm/TollCalculatorSpec.scala | 3 +- .../scala/beam/utils/StuckFinderSpec.scala | 14 +- 74 files changed, 2556 insertions(+), 1527 deletions(-) diff --git a/src/main/scala/beam/agentsim/agents/Population.scala b/src/main/scala/beam/agentsim/agents/Population.scala index d7a66f1b3f1..1630d442b22 100755 --- a/src/main/scala/beam/agentsim/agents/Population.scala +++ b/src/main/scala/beam/agentsim/agents/Population.scala @@ -111,10 +111,13 @@ class Population( .asInstanceOf[Double] ) - val householdVehicles: Map[Id[BeamVehicle], BeamVehicle] = JavaConverters.collectionAsScalaIterable(household.getVehicleIds).map{ vid=> - val bvid = BeamVehicle.createId(vid) - bvid->beamServices.privateVehicles(bvid) - }.toMap + val householdVehicles: Map[Id[BeamVehicle], BeamVehicle] = JavaConverters + .collectionAsScalaIterable(household.getVehicleIds) + .map { vid => + val bvid = BeamVehicle.createId(vid) + bvid -> beamServices.privateVehicles(bvid) + } + .toMap householdVehicles.foreach(x => beamServices.vehicles.update(x._1, x._2)) val householdActor = context.actorOf( HouseholdActor.props( diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceDriveIfAvailable.scala b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceDriveIfAvailable.scala index 54effc754e2..d0a5bbfe79a 100755 --- a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceDriveIfAvailable.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceDriveIfAvailable.scala @@ -15,7 +15,10 @@ import org.matsim.api.core.v01.population.Person */ class ModeChoiceDriveIfAvailable(val beamServices: BeamServices) extends ModeChoiceCalculator { - def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = { + def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = { val containsDriveAlt = alternatives.zipWithIndex.collect { case (trip, idx) if trip.tripClassifier == CAR => idx } diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceLCCM.scala b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceLCCM.scala index 64af0275d29..901c077d19c 100755 --- a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceLCCM.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceLCCM.scala @@ -41,7 +41,10 @@ class ModeChoiceLCCM( var expectedMaximumUtility: Double = Double.NaN var classMembershipDistribution: Map[String, Double] = Map() - override def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = { + override def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = { choose(alternatives, attributesOfIndividual, Mandatory) } @@ -66,19 +69,19 @@ class ModeChoiceLCCM( } val attribIndivData: AlternativeAttributes = { - val theParams: Map[String, Double] = Map( - "income" -> attributesOfIndividual.householdAttributes.householdIncome, - "householdSize" -> attributesOfIndividual.householdAttributes.householdSize, - "male" -> (if (attributesOfIndividual.isMale) { - 1.0 - } else { - 0.0 - }), - "numCars" -> attributesOfIndividual.householdAttributes.numCars, - "numBikes" -> attributesOfIndividual.householdAttributes.numBikes - ) - AlternativeAttributes("dummy", theParams) - } + val theParams: Map[String, Double] = Map( + "income" -> attributesOfIndividual.householdAttributes.householdIncome, + "householdSize" -> attributesOfIndividual.householdAttributes.householdSize, + "male" -> (if (attributesOfIndividual.isMale) { + 1.0 + } else { + 0.0 + }), + "numCars" -> attributesOfIndividual.householdAttributes.numCars, + "numBikes" -> attributesOfIndividual.householdAttributes.numBikes + ) + AlternativeAttributes("dummy", theParams) + } val classMembershipInputData = lccm.classMembershipModels.head._2.alternativeParams.keySet.map { theClassName => diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceMultinomialLogit.scala b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceMultinomialLogit.scala index a504b6d18c0..967ae631f49 100755 --- a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceMultinomialLogit.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceMultinomialLogit.scala @@ -20,20 +20,24 @@ import scala.util.Random * BEAM */ class ModeChoiceMultinomialLogit(val beamServices: BeamServices, val model: MultinomialLogit) - extends ModeChoiceCalculator with LazyLogging { + extends ModeChoiceCalculator + with LazyLogging { var expectedMaximumUtility: Double = 0.0 - override def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = { + override def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = { if (alternatives.isEmpty) { None } else { val modeCostTimeTransfers = altsToModeCostTimeTransfers(alternatives, attributesOfIndividual) val bestInGroup = - modeCostTimeTransfers groupBy (_.mode) map { - case (_, group) => group minBy timeAndCost - } + modeCostTimeTransfers groupBy (_.mode) map { + case (_, group) => group minBy timeAndCost + } val inputData = bestInGroup.map { mct => val theParams: Map[String, Double] = @@ -69,7 +73,10 @@ class ModeChoiceMultinomialLogit(val beamServices: BeamServices, val model: Mult mct.scaledTime + mct.cost } - def altsToModeCostTimeTransfers(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): IndexedSeq[ModeCostTimeTransfer] = { + def altsToModeCostTimeTransfers( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): IndexedSeq[ModeCostTimeTransfer] = { val walkTripStartTime = alternatives .find(_.tripClassifier == WALK) .map(_.legs.head.beamLeg.startTime) @@ -84,7 +91,7 @@ class ModeChoiceMultinomialLogit(val beamServices: BeamServices, val model: Mult val totalCost: Double = mode match { case TRANSIT | WALK_TRANSIT | DRIVE_TRANSIT => (altAndIdx._1.costEstimate + transitFareDefaults(altAndIdx._2)) * beamServices.beamConfig.beam.agentsim.tuning.transitPrice + - gasolineCostDefaults(altAndIdx._2) + gasolineCostDefaults(altAndIdx._2) case RIDE_HAIL => (altAndIdx._1.costEstimate + rideHailDefaults(altAndIdx._2)) * beamServices.beamConfig.beam.agentsim.tuning.rideHailPrice case RIDE_HAIL_TRANSIT => @@ -103,11 +110,21 @@ class ModeChoiceMultinomialLogit(val beamServices: BeamServices, val model: Mult case _ => altAndIdx._1.costEstimate } - val subsidy = beamServices.modeSubsidies.getSubsidy(mode, attributesOfIndividual.age, attributesOfIndividual.income.map(x => x.toInt)) + val subsidy = beamServices.modeSubsidies.getSubsidy( + mode, + attributesOfIndividual.age, + attributesOfIndividual.income.map(x => x.toInt) + ) val subsidisedCost = Math.max(0, totalCost.toDouble - subsidy) - if (totalCost < subsidy) logger.warn("Mode subsidy is even higher then the cost, setting cost to zero. Mode: {}, Cost: {}, Subsidy: {}", mode, totalCost, subsidy) + if (totalCost < subsidy) + logger.warn( + "Mode subsidy is even higher then the cost, setting cost to zero. Mode: {}, Cost: {}, Subsidy: {}", + mode, + totalCost, + subsidy + ) val numTransfers = mode match { case TRANSIT | WALK_TRANSIT | DRIVE_TRANSIT | RIDE_HAIL_TRANSIT => @@ -158,7 +175,7 @@ class ModeChoiceMultinomialLogit(val beamServices: BeamServices, val model: Mult val variables = Map( "transfer" -> numTransfers.toDouble, - "cost" -> (cost + scaleTimeByVot(time, Option(mode))) + "cost" -> (cost + scaleTimeByVot(time, Option(mode))) ) model.getUtilityOfAlternative(AlternativeAttributes(mode.value, variables)) } @@ -205,11 +222,11 @@ object ModeChoiceMultinomialLogit { } case class ModeCostTimeTransfer( - mode: BeamMode, - cost: Double, - scaledTime: Double, - numTransfers: Int, - index: Int = -1 - ) + mode: BeamMode, + cost: Double, + scaledTime: Double, + numTransfers: Int, + index: Int = -1 + ) } diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceRideHailIfAvailable.scala b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceRideHailIfAvailable.scala index f9582a696bf..12f4e66e693 100755 --- a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceRideHailIfAvailable.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceRideHailIfAvailable.scala @@ -15,7 +15,10 @@ import org.matsim.api.core.v01.population.Person */ class ModeChoiceRideHailIfAvailable(val beamServices: BeamServices) extends ModeChoiceCalculator { - override def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = { + override def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = { val containsRideHailAlt = alternatives.zipWithIndex.collect { case (trip, idx) if trip.tripClassifier == RIDE_HAIL => idx } diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceTransitIfAvailable.scala b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceTransitIfAvailable.scala index b82debb6f30..0f91d836dd2 100755 --- a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceTransitIfAvailable.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceTransitIfAvailable.scala @@ -14,7 +14,10 @@ class ModeChoiceTransitIfAvailable(val beamServices: BeamServices) extends ModeC override def clone(): ModeChoiceCalculator = new ModeChoiceTransitIfAvailable(beamServices) - override def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = { + override def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = { val containsTransitAlt = alternatives.zipWithIndex.collect { case (trip, idx) if trip.tripClassifier.isTransit => idx } diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceUniformRandom.scala b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceUniformRandom.scala index f7f3ad9a3b5..8c1fd8d639b 100755 --- a/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceUniformRandom.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/ModeChoiceUniformRandom.scala @@ -11,7 +11,10 @@ import beam.sim.population.AttributesOfIndividual */ class ModeChoiceUniformRandom(val beamServices: BeamServices) extends ModeChoiceCalculator { - override def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = { + override def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = { if (alternatives.nonEmpty) { Some(alternatives(chooseRandomAlternativeIndex(alternatives))) } else { diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/ModeSubsidy.scala b/src/main/scala/beam/agentsim/agents/choice/mode/ModeSubsidy.scala index 23c9e2d2ba9..ba5f0df29c4 100644 --- a/src/main/scala/beam/agentsim/agents/choice/mode/ModeSubsidy.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/ModeSubsidy.scala @@ -17,13 +17,12 @@ case class ModeSubsidy(modeSubsidies: Map[BeamMode, List[Subsidy]]) { .filter( s => (age.fold(true)(s.age.hasOrEmpty) && income.fold(false)(s.income.hasOrEmpty)) || - (age.fold(false)(s.age.hasOrEmpty) && income.fold(true)(s.income.hasOrEmpty)) + (age.fold(false)(s.age.hasOrEmpty) && income.fold(true)(s.income.hasOrEmpty)) ) .map(_.amount) .sum } - } object ModeSubsidy { diff --git a/src/main/scala/beam/agentsim/agents/choice/mode/Range.scala b/src/main/scala/beam/agentsim/agents/choice/mode/Range.scala index 69fb0c116f4..769ee5920a3 100644 --- a/src/main/scala/beam/agentsim/agents/choice/mode/Range.scala +++ b/src/main/scala/beam/agentsim/agents/choice/mode/Range.scala @@ -21,11 +21,11 @@ object Range { val bounds = pattern.split(":") val lowerBound = Try( bounds(0).substring(1).toInt - + (if (bounds(0).startsWith("(")) 1 else 0) + + (if (bounds(0).startsWith("(")) 1 else 0) ).getOrElse(0) val upperBound = Try( bounds(1).substring(0, bounds(1).length - 1).toInt - - (if (bounds(1).endsWith(")")) 1 else 0) + - (if (bounds(1).endsWith(")")) 1 else 0) ).getOrElse(Int.MaxValue) Range(lowerBound, upperBound) } diff --git a/src/main/scala/beam/agentsim/agents/household/HouseholdActor.scala b/src/main/scala/beam/agentsim/agents/household/HouseholdActor.scala index 38a643b165e..533909c76a2 100755 --- a/src/main/scala/beam/agentsim/agents/household/HouseholdActor.scala +++ b/src/main/scala/beam/agentsim/agents/household/HouseholdActor.scala @@ -35,20 +35,20 @@ object HouseholdActor { } def props( - beamServices: BeamServices, - modeChoiceCalculator: AttributesOfIndividual => ModeChoiceCalculator, - schedulerRef: ActorRef, - transportNetwork: TransportNetwork, - router: ActorRef, - rideHailManager: ActorRef, - parkingManager: ActorRef, - eventsManager: EventsManager, - population: org.matsim.api.core.v01.population.Population, - householdId: Id[Household], - matSimHousehold: Household, - houseHoldVehicles: Map[Id[BeamVehicle], BeamVehicle], - homeCoord: Coord - ): Props = { + beamServices: BeamServices, + modeChoiceCalculator: AttributesOfIndividual => ModeChoiceCalculator, + schedulerRef: ActorRef, + transportNetwork: TransportNetwork, + router: ActorRef, + rideHailManager: ActorRef, + parkingManager: ActorRef, + eventsManager: EventsManager, + population: org.matsim.api.core.v01.population.Population, + householdId: Id[Household], + matSimHousehold: Household, + houseHoldVehicles: Map[Id[BeamVehicle], BeamVehicle], + homeCoord: Coord + ): Props = { Props( new HouseholdActor( beamServices, @@ -76,7 +76,6 @@ object HouseholdActor { case class InitializeRideHailAgent(b: Id[Person]) - /** * Implementation of intra-household interaction in BEAM using actors. * @@ -92,28 +91,27 @@ object HouseholdActor { * @see [[ChoosesMode]] */ class HouseholdActor( - beamServices: BeamServices, - modeChoiceCalculatorFactory: AttributesOfIndividual => ModeChoiceCalculator, - schedulerRef: ActorRef, - transportNetwork: TransportNetwork, - router: ActorRef, - rideHailManager: ActorRef, - parkingManager: ActorRef, - eventsManager: EventsManager, - val population: org.matsim.api.core.v01.population.Population, - id: Id[households.Household], - val household: Household, - vehicles: Map[Id[BeamVehicle], BeamVehicle], - homeCoord: Coord - ) extends VehicleManager - with ActorLogging { + beamServices: BeamServices, + modeChoiceCalculatorFactory: AttributesOfIndividual => ModeChoiceCalculator, + schedulerRef: ActorRef, + transportNetwork: TransportNetwork, + router: ActorRef, + rideHailManager: ActorRef, + parkingManager: ActorRef, + eventsManager: EventsManager, + val population: org.matsim.api.core.v01.population.Population, + id: Id[households.Household], + val household: Household, + vehicles: Map[Id[BeamVehicle], BeamVehicle], + homeCoord: Coord + ) extends VehicleManager + with ActorLogging { import beam.agentsim.agents.memberships.Memberships.RankedGroup._ implicit val pop: org.matsim.api.core.v01.population.Population = population household.members.foreach { person => - val attributes = person.getCustomAttributes.get("beam-attributes").asInstanceOf[AttributesOfIndividual] val modeChoiceCalculator = modeChoiceCalculatorFactory(attributes) @@ -199,12 +197,12 @@ object HouseholdActor { override def receive: Receive = { case NotifyVehicleResourceIdle( - vId, - whenWhere, - _, - _, - _ - ) => + vId, + whenWhere, + _, + _, + _ + ) => val vehId = vId.asInstanceOf[Id[BeamVehicle]] _vehicleToStreetVehicle += (vehId -> StreetVehicle(vehId, whenWhere.get, CAR, asDriver = true)) log.debug("updated vehicle {} with location {}", vehId, whenWhere.get) @@ -313,7 +311,7 @@ object HouseholdActor { private def lookupAvailableVehicles(): Vector[StreetVehicle] = Vector( for { - availableVehicle <- _availableVehicles + availableVehicle <- _availableVehicles availableStreetVehicle <- _vehicleToStreetVehicle.get(availableVehicle) } yield availableStreetVehicle ).flatten @@ -363,7 +361,7 @@ object HouseholdActor { //Initialize all vehicles to have a stationary trajectory starting at time zero val initialLocation = SpaceTime(homeCoord.getX, homeCoord.getY, 0) - for {veh <- _vehicles} yield { + for { veh <- _vehicles } yield { //TODO following mode should match exhaustively val mode = BeamVehicleType.getMode(vehicles(veh)) @@ -384,5 +382,4 @@ object HouseholdActor { ) } - } diff --git a/src/main/scala/beam/agentsim/agents/modalbehaviors/ChoosesMode.scala b/src/main/scala/beam/agentsim/agents/modalbehaviors/ChoosesMode.scala index d9eba111629..b118cdf9260 100755 --- a/src/main/scala/beam/agentsim/agents/modalbehaviors/ChoosesMode.scala +++ b/src/main/scala/beam/agentsim/agents/modalbehaviors/ChoosesMode.scala @@ -48,7 +48,7 @@ trait ChoosesMode { onTransition { case (PerformingActivity | Waiting | WaitingForReservationConfirmation | - ProcessingNextLegOrStartActivity) -> ChoosingMode => + ProcessingNextLegOrStartActivity) -> ChoosingMode => stateData.asInstanceOf[BasePersonData].currentTourMode match { case Some(CAR | BIKE | DRIVE_TRANSIT) => // Only need to get available street vehicles from household if our mode requires such a vehicle @@ -104,10 +104,10 @@ trait ChoosesMode { } def makeRequestWith( - transitModes: Vector[BeamMode], - vehicles: Vector[StreetVehicle], - streetVehiclesIntermodalUse: IntermodalUse = Access - ): Unit = { + transitModes: Vector[BeamMode], + vehicles: Vector[StreetVehicle], + streetVehiclesIntermodalUse: IntermodalUse = Access + ): Unit = { router ! RoutingRequest( currentPersonLocation.loc, nextAct.getCoord, @@ -150,9 +150,9 @@ trait ChoosesMode { } def filterStreetVehiclesForQuery( - streetVehicles: Vector[StreetVehicle], - byMode: BeamMode - ): Vector[StreetVehicle] = { + streetVehicles: Vector[StreetVehicle], + byMode: BeamMode + ): Vector[StreetVehicle] = { choosesModeData.personData.currentTourPersonalVehicle match { case Some(personalVeh) => // We already have a vehicle we're using on this tour, so filter down to that @@ -192,12 +192,12 @@ trait ChoosesMode { case Some(WALK_TRANSIT) => responsePlaceholders = makeResponsePlaceholders(withRouting = true) makeRequestWith(Vector(TRANSIT), Vector(bodyStreetVehicle)) - case Some(mode@(CAR | BIKE)) => + case Some(mode @ (CAR | BIKE)) => responsePlaceholders = makeResponsePlaceholders(withRouting = true) val maybeLeg = _experiencedBeamPlan.getPlanElements .get(_experiencedBeamPlan.getPlanElements.indexOf(nextAct) - 1) match { case l: Leg => Some(l) - case _ => None + case _ => None } maybeLeg.map(l => (l, l.getRoute)) match { case Some((l, r: NetworkRoute)) => @@ -287,9 +287,9 @@ trait ChoosesMode { * Receive and store data needed for choice. */ case Event( - theRouterResult@RoutingResponse(_, _, Some(requestId)), - choosesModeData: ChoosesModeData - ) if choosesModeData.rideHail2TransitRoutingRequestId.contains(requestId) => + theRouterResult @ RoutingResponse(_, _, Some(requestId)), + choosesModeData: ChoosesModeData + ) if choosesModeData.rideHail2TransitRoutingRequestId.contains(requestId) => val driveTransitTrip = theRouterResult.itineraries.view .dropWhile(_.tripClassifier != DRIVE_TRANSIT) @@ -297,9 +297,9 @@ trait ChoosesMode { // If there's a drive-transit trip AND we don't have an error RH2Tr response (due to no desire to use RH) then seek RH on access and egress val newPersonData = if (shouldAttemptRideHail2Transit( - driveTransitTrip, - choosesModeData.rideHail2TransitAccessResult - )) { + driveTransitTrip, + choosesModeData.rideHail2TransitAccessResult + )) { val accessSegment = driveTransitTrip.get.legs.view .takeWhile(!_.beamLeg.mode.isMassTransit) @@ -349,8 +349,22 @@ trait ChoosesMode { val correctedItins = theRouterResult.itineraries.map { trip => if (trip.legs.head.beamLeg.mode == CAR) { - val startLeg = EmbodiedBeamLeg(BeamLeg.dummyWalk(trip.legs.head.beamLeg.startTime), bodyId, asDriver = true, None, 0, unbecomeDriverOnCompletion = false) - val endLeg = EmbodiedBeamLeg(BeamLeg.dummyWalk(trip.legs.last.beamLeg.endTime), bodyId, asDriver = true, None, 0, unbecomeDriverOnCompletion = true) + val startLeg = EmbodiedBeamLeg( + BeamLeg.dummyWalk(trip.legs.head.beamLeg.startTime), + bodyId, + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = false + ) + val endLeg = EmbodiedBeamLeg( + BeamLeg.dummyWalk(trip.legs.last.beamLeg.endTime), + bodyId, + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = true + ) trip.copy(legs = (startLeg +: trip.legs) :+ endLeg) } else { trip @@ -376,12 +390,12 @@ trait ChoosesMode { } def shouldAttemptRideHail2Transit( - driveTransitTrip: Option[EmbodiedBeamTrip], - rideHail2TransitResult: Option[RideHailResponse] - ): Boolean = { + driveTransitTrip: Option[EmbodiedBeamTrip], + rideHail2TransitResult: Option[RideHailResponse] + ): Boolean = { driveTransitTrip.isDefined && driveTransitTrip.get.legs .exists(_.beamLeg.mode.isMassTransit) && - rideHail2TransitResult.getOrElse(RideHailResponse.DUMMY).error.isEmpty + rideHail2TransitResult.getOrElse(RideHailResponse.DUMMY).error.isEmpty } def makeRideHailRequestFromBeamLeg(legs: Seq[BeamLeg]): Option[Int] = { @@ -400,17 +414,17 @@ trait ChoosesMode { case object FinishingModeChoice extends BeamAgentState def createRideHail2TransitItin( - rideHail2TransitAccessResult: RideHailResponse, - rideHail2TransitEgressResult: RideHailResponse, - driveTransitTrip: EmbodiedBeamTrip - ): Option[EmbodiedBeamTrip] = { + rideHail2TransitAccessResult: RideHailResponse, + rideHail2TransitEgressResult: RideHailResponse, + driveTransitTrip: EmbodiedBeamTrip + ): Option[EmbodiedBeamTrip] = { if (rideHail2TransitAccessResult.error.isEmpty) { val tncAccessLeg = rideHail2TransitAccessResult.travelProposal.head.responseRideHail2Dest.itineraries.head.legs .dropRight(1) // Replacing drive access leg with TNC changes the travel time. val extraWaitTimeBuffer = driveTransitTrip.legs.head.beamLeg.endTime - _currentTick.get - - tncAccessLeg.last.beamLeg.duration - rideHail2TransitAccessResult.travelProposal.get.timeToCustomer.toInt + tncAccessLeg.last.beamLeg.duration - rideHail2TransitAccessResult.travelProposal.get.timeToCustomer.toInt if (extraWaitTimeBuffer < 300) { // We filter out all options that don't allow at least 5 minutes of time for unexpected waiting None @@ -423,8 +437,10 @@ trait ChoosesMode { ) // tncAccessLeg.head.beamLeg.startTime - _currentTick.get.longValue() val accessAndTransit = tncAccessLeg.map( leg => - leg.copy(leg.beamLeg - .updateStartTime(startTimeAdjustment - startTimeBufferForWaiting.intValue())) + leg.copy( + leg.beamLeg + .updateStartTime(startTimeAdjustment - startTimeBufferForWaiting.intValue()) + ) ) ++ driveTransitTrip.legs.tail val fullTrip = if (rideHail2TransitEgressResult.error.isEmpty) { accessAndTransit.dropRight(2) ++ rideHail2TransitEgressResult.travelProposal.head.responseRideHail2Dest.itineraries.head.legs.tail @@ -440,27 +456,27 @@ trait ChoosesMode { def completeChoiceIfReady: PartialFunction[State, State] = { case FSM.State( - _, - choosesModeData@ChoosesModeData( - personData, - _, - None, - Some(routingResponse), - Some(rideHailResult), - Some(rideHail2TransitRoutingResponse), - _, - Some(rideHail2TransitAccessResult), - _, - Some(rideHail2TransitEgressResult), - _, - _, - _, - _ - ), - _, - _, - _ - ) => + _, + choosesModeData @ ChoosesModeData( + personData, + _, + None, + Some(routingResponse), + Some(rideHailResult), + Some(rideHail2TransitRoutingResponse), + _, + Some(rideHail2TransitAccessResult), + _, + Some(rideHail2TransitEgressResult), + _, + _, + _, + _ + ), + _, + _, + _ + ) => val currentPersonLocation = choosesModeData.currentLocation.getOrElse( SpaceTime(currentActivity(choosesModeData.personData).getCoord, _currentTick.get) ) @@ -506,7 +522,11 @@ trait ChoosesMode { combinedItinerariesForChoice }).filter(itin => availableModes.contains(itin.tripClassifier)) - val attributesOfIndividual = beamServices.matsimServices.getScenario.getPopulation.getPersons.get(id).getCustomAttributes.get("beam-attributes").asInstanceOf[AttributesOfIndividual] + val attributesOfIndividual = beamServices.matsimServices.getScenario.getPopulation.getPersons + .get(id) + .getCustomAttributes + .get("beam-attributes") + .asInstanceOf[AttributesOfIndividual] modeChoiceCalculator(filteredItinerariesForChoice.toIndexedSeq, attributesOfIndividual) match { case Some(chosenTrip) => @@ -648,21 +668,21 @@ trait ChoosesMode { object ChoosesMode { case class ChoosesModeData( - personData: BasePersonData, - currentLocation: Option[SpaceTime] = None, - pendingChosenTrip: Option[EmbodiedBeamTrip] = None, - routingResponse: Option[RoutingResponse] = None, - rideHailResult: Option[RideHailResponse] = None, - rideHail2TransitRoutingResponse: Option[EmbodiedBeamTrip] = None, - rideHail2TransitRoutingRequestId: Option[Int] = None, - rideHail2TransitAccessResult: Option[RideHailResponse] = None, - rideHail2TransitAccessInquiryId: Option[Int] = None, - rideHail2TransitEgressResult: Option[RideHailResponse] = None, - rideHail2TransitEgressInquiryId: Option[Int] = None, - availablePersonalStreetVehicles: Vector[StreetVehicle] = Vector(), - expectedMaxUtilityOfLatestChoice: Option[Double] = None, - isWithinTripReplanning: Boolean = false - ) extends PersonData { + personData: BasePersonData, + currentLocation: Option[SpaceTime] = None, + pendingChosenTrip: Option[EmbodiedBeamTrip] = None, + routingResponse: Option[RoutingResponse] = None, + rideHailResult: Option[RideHailResponse] = None, + rideHail2TransitRoutingResponse: Option[EmbodiedBeamTrip] = None, + rideHail2TransitRoutingRequestId: Option[Int] = None, + rideHail2TransitAccessResult: Option[RideHailResponse] = None, + rideHail2TransitAccessInquiryId: Option[Int] = None, + rideHail2TransitEgressResult: Option[RideHailResponse] = None, + rideHail2TransitEgressInquiryId: Option[Int] = None, + availablePersonalStreetVehicles: Vector[StreetVehicle] = Vector(), + expectedMaxUtilityOfLatestChoice: Option[Double] = None, + isWithinTripReplanning: Boolean = false + ) extends PersonData { override def currentVehicle: VehicleStack = personData.currentVehicle override def currentLegPassengerScheduleIndex: Int = @@ -675,8 +695,8 @@ object ChoosesMode { copy(personData = personData.copy(passengerSchedule = newPassengerSchedule)) override def withCurrentLegPassengerScheduleIndex( - currentLegPassengerScheduleIndex: Int - ): DrivingData = + currentLegPassengerScheduleIndex: Int + ): DrivingData = copy( personData = personData.copy(currentLegPassengerScheduleIndex = currentLegPassengerScheduleIndex) ) @@ -685,18 +705,18 @@ object ChoosesMode { } case class ChoosesModeResponsePlaceholders( - routingResponse: Option[RoutingResponse] = None, - rideHailResult: Option[RideHailResponse] = None, - rideHail2TransitRoutingResponse: Option[EmbodiedBeamTrip] = None, - rideHail2TransitAccessResult: Option[RideHailResponse] = None, - rideHail2TransitEgressResult: Option[RideHailResponse] = None - ) + routingResponse: Option[RoutingResponse] = None, + rideHailResult: Option[RideHailResponse] = None, + rideHail2TransitRoutingResponse: Option[EmbodiedBeamTrip] = None, + rideHail2TransitAccessResult: Option[RideHailResponse] = None, + rideHail2TransitEgressResult: Option[RideHailResponse] = None + ) def makeResponsePlaceholders( - withRouting: Boolean = false, - withRideHail: Boolean = false, - withRideHailTransit: Boolean = false - ): ChoosesModeResponsePlaceholders = { + withRouting: Boolean = false, + withRideHail: Boolean = false, + withRideHailTransit: Boolean = false + ): ChoosesModeResponsePlaceholders = { ChoosesModeResponsePlaceholders( routingResponse = if (withRouting) { None diff --git a/src/main/scala/beam/agentsim/agents/modalbehaviors/ModeChoiceCalculator.scala b/src/main/scala/beam/agentsim/agents/modalbehaviors/ModeChoiceCalculator.scala index 7660ecc5a71..c38a2b21320 100755 --- a/src/main/scala/beam/agentsim/agents/modalbehaviors/ModeChoiceCalculator.scala +++ b/src/main/scala/beam/agentsim/agents/modalbehaviors/ModeChoiceCalculator.scala @@ -33,10 +33,10 @@ trait ModeChoiceCalculator extends HasServices { // Note: We use BigDecimal here as we're dealing with monetary values requiring exact precision. // Could be refactored if this is a performance issue, but prefer not to. lazy val valuesOfTime: mutable.Map[VotType, Double] = - mutable.Map[VotType, Double]( - DefaultVot -> beamServices.beamConfig.beam.agentsim.agents.modalBehaviors.defaultValueOfTime, - GeneralizedVot -> beamServices.beamConfig.beam.agentsim.agents.modalBehaviors.defaultValueOfTime - ) + mutable.Map[VotType, Double]( + DefaultVot -> beamServices.beamConfig.beam.agentsim.agents.modalBehaviors.defaultValueOfTime, + GeneralizedVot -> beamServices.beamConfig.beam.agentsim.agents.modalBehaviors.defaultValueOfTime + ) def scaleTimeByVot(time: Double, beamMode: Option[BeamMode] = None): Double = { time / 3600 * getVot(beamMode) @@ -71,21 +71,24 @@ trait ModeChoiceCalculator extends HasServices { // NOTE: Could have implemented as a Map[BeamMode->VotType], but prefer exhaustive // matching enforced by sealed traits. private def matchMode2Vot(beamMode: Option[BeamMode]): VotType = beamMode match { - case Some(CAR) => DriveVot - case Some(WALK) => WalkVot - case Some(BIKE) => BikeVot - case Some(WALK_TRANSIT) => WalkToTransitVot - case Some(DRIVE_TRANSIT) => DriveToTransitVot - case Some(RIDE_HAIL) => RideHailVot - case a@Some(_) if BeamMode.transitModes.contains(a) => OnTransitVot - case Some(RIDE_HAIL_TRANSIT) => RideHailVot - case Some(_) => GeneralizedVot - case None => DefaultVot + case Some(CAR) => DriveVot + case Some(WALK) => WalkVot + case Some(BIKE) => BikeVot + case Some(WALK_TRANSIT) => WalkToTransitVot + case Some(DRIVE_TRANSIT) => DriveToTransitVot + case Some(RIDE_HAIL) => RideHailVot + case a @ Some(_) if BeamMode.transitModes.contains(a) => OnTransitVot + case Some(RIDE_HAIL_TRANSIT) => RideHailVot + case Some(_) => GeneralizedVot + case None => DefaultVot } ///~ - def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] + def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] def utilityOf(alternative: EmbodiedBeamTrip, attributesOfIndividual: AttributesOfIndividual): Double @@ -110,7 +113,7 @@ object ModeChoiceCalculator { val lccm = new LatentClassChoiceModel(beamServices) (attributesOfIndividual: AttributesOfIndividual) => attributesOfIndividual match { - case AttributesOfIndividual(_,Some(modalityStyle), _, _, _,_,_) => + case AttributesOfIndividual(_, Some(modalityStyle), _, _, _, _, _) => new ModeChoiceMultinomialLogit( beamServices, lccm.modeChoiceModels(Mandatory)(modalityStyle) diff --git a/src/main/scala/beam/agentsim/agents/ridehail/RideHailManager.scala b/src/main/scala/beam/agentsim/agents/ridehail/RideHailManager.scala index 81a85c8a217..fc7d4d42e2b 100755 --- a/src/main/scala/beam/agentsim/agents/ridehail/RideHailManager.scala +++ b/src/main/scala/beam/agentsim/agents/ridehail/RideHailManager.scala @@ -477,14 +477,19 @@ class RideHailManager( customerTripPlan.copy( legs = customerTripPlan.legs.zipWithIndex.map( legWithInd => - legWithInd._1.copy(beamLeg = legWithInd._1.beamLeg.updateStartTime(legWithInd._1.beamLeg.startTime + timeToCustomer), asDriver = legWithInd._1.beamLeg.mode == WALK, cost = - if (legWithInd._1.beamLeg == customerTripPlan - .legs(1) - .beamLeg) { - cost - } else { - 0.0 - }, unbecomeDriverOnCompletion = legWithInd._2 == 2) + legWithInd._1.copy( + beamLeg = legWithInd._1.beamLeg.updateStartTime(legWithInd._1.beamLeg.startTime + timeToCustomer), + asDriver = legWithInd._1.beamLeg.mode == WALK, + cost = + if (legWithInd._1.beamLeg == customerTripPlan + .legs(1) + .beamLeg) { + cost + } else { + 0.0 + }, + unbecomeDriverOnCompletion = legWithInd._2 == 2 + ) ) ) ), @@ -808,11 +813,13 @@ class RideHailManager( responses: List[RoutingResponse] = List() ): Unit = { if (log.isDebugEnabled) { - log.debug("Finding driver at tick {}, available: {}, inService: {}, outOfService: {}", + log.debug( + "Finding driver at tick {}, available: {}, inService: {}, outOfService: {}", request.departAt, availableRideHailVehicles.size, inServiceRideHailVehicles.size, - outOfServiceRideHailVehicles.size) + outOfServiceRideHailVehicles.size + ) } val vehicleAllocationRequest = VehicleAllocationRequest(request, responses) @@ -866,19 +873,25 @@ class RideHailManager( val diff1 = end - start start = System.currentTimeMillis() - val times2RideHailAgents = nearbyAvailableRideHailAgents.map { rideHailAgentLocation => - val distance = CoordUtils.calcProjectedEuclideanDistance(pickupLocation, rideHailAgentLocation.currentLocation.loc) - // we consider the time to travel to the customer and the time before the vehicle is actually ready (due to - // already moving or dropping off a customer, etc.) - val extra = Math.max(rideHailAgentLocation.currentLocation.time - customerRequestTime, 0) - val timeToCustomer = distance * secondsPerEuclideanMeterFactor + extra - RideHailAgentETA(rideHailAgentLocation, distance, timeToCustomer) - }.toVector.sortBy(_.timeToCustomer) + val times2RideHailAgents = nearbyAvailableRideHailAgents + .map { rideHailAgentLocation => + val distance = + CoordUtils.calcProjectedEuclideanDistance(pickupLocation, rideHailAgentLocation.currentLocation.loc) + // we consider the time to travel to the customer and the time before the vehicle is actually ready (due to + // already moving or dropping off a customer, etc.) + val extra = Math.max(rideHailAgentLocation.currentLocation.time - customerRequestTime, 0) + val timeToCustomer = distance * secondsPerEuclideanMeterFactor + extra + RideHailAgentETA(rideHailAgentLocation, distance, timeToCustomer) + } + .toVector + .sortBy(_.timeToCustomer) end = System.currentTimeMillis() val diff2 = end - start if (diff1 + diff2 > 100) - log.debug(s"getClosestIdleVehiclesWithinRadiusByETA for $pickupLocation with $radius nearbyAvailableRideHailAgents: $diff1, diff2: $diff2. Total: ${diff1 + diff2} ms") + log.debug( + s"getClosestIdleVehiclesWithinRadiusByETA for $pickupLocation with $radius nearbyAvailableRideHailAgents: $diff1, diff2: $diff2. Total: ${diff1 + diff2} ms" + ) times2RideHailAgents } diff --git a/src/main/scala/beam/agentsim/agents/ridehail/allocation/EVFleetAllocationManager.scala b/src/main/scala/beam/agentsim/agents/ridehail/allocation/EVFleetAllocationManager.scala index 087ba32e9f7..5ff0cc7c993 100644 --- a/src/main/scala/beam/agentsim/agents/ridehail/allocation/EVFleetAllocationManager.scala +++ b/src/main/scala/beam/agentsim/agents/ridehail/allocation/EVFleetAllocationManager.scala @@ -70,7 +70,7 @@ class EVFleetAllocationManager(val rideHailManager: RideHailManager) if (rideHailManager .getVehicleState(agentLocation.vehicleId) - .remainingRangeInM < routedDisanceInM){ + .remainingRangeInM < routedDisanceInM) { requestToExcludedDrivers.put( reqId, requestToExcludedDrivers.getOrElse(reqId, Set()) + agentLocation.vehicleId diff --git a/src/main/scala/beam/agentsim/agents/vehicles/BeamVehicleType.scala b/src/main/scala/beam/agentsim/agents/vehicles/BeamVehicleType.scala index deb1eb6b2b9..4a79bec90b2 100755 --- a/src/main/scala/beam/agentsim/agents/vehicles/BeamVehicleType.scala +++ b/src/main/scala/beam/agentsim/agents/vehicles/BeamVehicleType.scala @@ -14,22 +14,22 @@ import org.matsim.vehicles.Vehicle * @author saf */ case class BeamVehicleType( - vehicleTypeId: String, - seatingCapacity: Double, - standingRoomCapacity: Double, - lengthInMeter: Double, - primaryFuelType: FuelType, - primaryFuelConsumptionInJoulePerMeter: Double, - primaryFuelCapacityInJoule: Double, - secondaryFuelType: Option[FuelType] = None, - secondaryFuelConsumptionInJoulePerMeter: Option[Double] = None, - secondaryFuelCapacityInJoule: Option[Double] = None, - automationLevel: Option[String] = None, - maxVelocity: Option[Double] = None, - passengerCarUnit: Double = 1, - rechargeLevel2RateLimitInWatts: Option[Double] = None, - rechargeLevel3RateLimitInWatts: Option[Double] = None, - vehicleCategory: Option[VehicleCategory] = None + vehicleTypeId: String, + seatingCapacity: Double, + standingRoomCapacity: Double, + lengthInMeter: Double, + primaryFuelType: FuelType, + primaryFuelConsumptionInJoulePerMeter: Double, + primaryFuelCapacityInJoule: Double, + secondaryFuelType: Option[FuelType] = None, + secondaryFuelConsumptionInJoulePerMeter: Option[Double] = None, + secondaryFuelCapacityInJoule: Option[Double] = None, + automationLevel: Option[String] = None, + maxVelocity: Option[Double] = None, + passengerCarUnit: Double = 1, + rechargeLevel2RateLimitInWatts: Option[Double] = None, + rechargeLevel3RateLimitInWatts: Option[Double] = None, + vehicleCategory: Option[VehicleCategory] = None ) { def getCost(distance: Double): Double = { @@ -66,7 +66,10 @@ object BeamVehicleType { 2.21e6, null ) - val powerTrainForHumanBody: Powertrain = new Powertrain(BeamVehicleType.defaultHumanBodyBeamVehicleType.primaryFuelConsumptionInJoulePerMeter) + + val powerTrainForHumanBody: Powertrain = new Powertrain( + BeamVehicleType.defaultHumanBodyBeamVehicleType.primaryFuelConsumptionInJoulePerMeter + ) //TODO val defaultTransitBeamVehicleType: BeamVehicleType = @@ -103,9 +106,9 @@ object BeamVehicleType { def getMode(beamVehicle: BeamVehicle): BeamMode = { beamVehicle.beamVehicleType.vehicleTypeId match { //TODO complete list - case vid if vid.toLowerCase.contains("bike") => BIKE + case vid if vid.toLowerCase.contains("bike") => BIKE case vid if vid.toLowerCase.contains("ridehail") => RIDE_HAIL - case vid if vid.toLowerCase.contains("car") => CAR + case vid if vid.toLowerCase.contains("car") => CAR } // diff --git a/src/main/scala/beam/agentsim/agents/vehicles/EnergyEconomyAttributes.scala b/src/main/scala/beam/agentsim/agents/vehicles/EnergyEconomyAttributes.scala index 42a203f8bcd..ea553a94c42 100755 --- a/src/main/scala/beam/agentsim/agents/vehicles/EnergyEconomyAttributes.scala +++ b/src/main/scala/beam/agentsim/agents/vehicles/EnergyEconomyAttributes.scala @@ -86,7 +86,8 @@ case object EnergyEconomyAttributes extends Enum[EnergyEconomyAttributes] { val AverageMilesPerGallon = 24.8 def apply(engineInformation: EngineInformation): Powertrain = { - val jpm = litersPerMeterToJoulesPerMeter(engineInformation.getFuelType.name(), engineInformation.getGasConsumption) + val jpm = + litersPerMeterToJoulesPerMeter(engineInformation.getFuelType.name(), engineInformation.getGasConsumption) new Powertrain(jpm) } diff --git a/src/main/scala/beam/agentsim/events/handling/BeamEventsWriterXML.scala b/src/main/scala/beam/agentsim/events/handling/BeamEventsWriterXML.scala index be0503a478f..1721c6844aa 100644 --- a/src/main/scala/beam/agentsim/events/handling/BeamEventsWriterXML.scala +++ b/src/main/scala/beam/agentsim/events/handling/BeamEventsWriterXML.scala @@ -17,10 +17,12 @@ import scala.collection.JavaConverters._ * @param beamServices beam services * @param eventTypeToLog type of event to log */ -class BeamEventsWriterXML(var outFileName: String, - beamEventLogger: BeamEventsLogger, - beamServices: BeamServices, - eventTypeToLog: Class[_]) extends BeamEventsWriterBase(outFileName,beamEventLogger,beamServices,eventTypeToLog) { +class BeamEventsWriterXML( + var outFileName: String, + beamEventLogger: BeamEventsLogger, + beamServices: BeamServices, + eventTypeToLog: Class[_] +) extends BeamEventsWriterBase(outFileName, beamEventLogger, beamServices, eventTypeToLog) { writeHeaders() @@ -41,8 +43,7 @@ class BeamEventsWriterXML(var outFileName: String, //write the event tag to the xml file val eventElem = s"\t\n" this.out.append(eventElem) - } - catch { + } catch { case e: Exception => throw e } @@ -58,8 +59,7 @@ class BeamEventsWriterXML(var outFileName: String, try { this.out.write(header) this.out.write("\n") - } - catch { + } catch { case e: IOException => throw new UncheckedIOException(e) } @@ -85,7 +85,7 @@ class BeamEventsWriterXML(var outFileName: String, */ private def encodeAttributeValue(attributeValue: String): String = { // Replace special characters(if any) with encoded strings - attributeValue.find(List('<','>','\"','&').contains(_)) match { + attributeValue.find(List('<', '>', '\"', '&').contains(_)) match { case Some(_) => attributeValue .replaceAll("<", "<") diff --git a/src/main/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManager.scala b/src/main/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManager.scala index 031bf1020ee..ac41c82561f 100644 --- a/src/main/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManager.scala +++ b/src/main/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManager.scala @@ -4,14 +4,12 @@ import beam.agentsim.infrastructure.ParkingStall._ import beam.agentsim.infrastructure.TAZTreeMap.TAZ import org.matsim.api.core.v01.Id -private[infrastructure] case class IndexForFilter -( +private[infrastructure] case class IndexForFilter( tazId: Id[TAZ], reservedFor: ReservedParkingType ) -private[infrastructure] case class IndexForFind -( +private[infrastructure] case class IndexForFind( tazId: Id[TAZ], parkingType: ParkingType, pricingModel: PricingModel, @@ -25,11 +23,18 @@ class IndexerForZonalParkingManager(resources: Map[StallAttributes, StallValues] private[this] val mapForFind: Map[IndexForFind, Array[StallValues]] = idxForFind(resources) - def find(tazId: Id[TAZ], parkingType: ParkingType, reservedFor: ReservedParkingType): Option[(IndexForFind, StallValues)] = { + def find( + tazId: Id[TAZ], + parkingType: ParkingType, + reservedFor: ReservedParkingType + ): Option[(IndexForFind, StallValues)] = { def find(key: IndexForFind): Option[(IndexForFind, StallValues)] = { mapForFind.get(key).flatMap { arr => - arr.find(stallValue => stallValue.numStalls > 0 && stallValue.feeInCents == 0) - .map { found => (key, found) } + arr + .find(stallValue => stallValue.numStalls > 0 && stallValue.feeInCents == 0) + .map { found => + (key, found) + } } } @@ -39,13 +44,17 @@ class IndexerForZonalParkingManager(resources: Map[StallAttributes, StallValues] // We still have to do two look-ups by key because we don't know exact pricing model allPricingModels.view - .map { pricingModel => find(key(pricingModel)) } + .map { pricingModel => + find(key(pricingModel)) + } .filter(_.isDefined) .head } - def filter(tazWithDistance: Vector[(TAZ, Double)], - reservedFor: ReservedParkingType): Option[Map[StallAttributes, StallValues]] = { + def filter( + tazWithDistance: Vector[(TAZ, Double)], + reservedFor: ReservedParkingType + ): Option[Map[StallAttributes, StallValues]] = { def find(idx: IndexForFilter): Option[Map[StallAttributes, StallValues]] = { mapForFilter.get(idx).map { map => map.filter { @@ -65,7 +74,6 @@ class IndexerForZonalParkingManager(resources: Map[StallAttributes, StallValues] .head } - } object IndexerForZonalParkingManager { @@ -73,15 +81,25 @@ object IndexerForZonalParkingManager { val allPricingModels: Array[PricingModel] = Array(FlatFee, Block) def idxForFind(resources: Map[StallAttributes, StallValues]): Map[IndexForFind, Array[StallValues]] = { - resources.groupBy { case (key, _) => - IndexForFind(tazId = key.tazId, parkingType = key.parkingType, pricingModel = key.pricingModel, - reservedFor = key.reservedFor) - }.map { case (key, map) => key -> map.values.toArray } + resources + .groupBy { + case (key, _) => + IndexForFind( + tazId = key.tazId, + parkingType = key.parkingType, + pricingModel = key.pricingModel, + reservedFor = key.reservedFor + ) + } + .map { case (key, map) => key -> map.values.toArray } } - def idxForFilter(resources: Map[StallAttributes, StallValues]): Map[IndexForFilter, Map[StallAttributes, StallValues]] = { - resources.groupBy { case (key, _) => - IndexForFilter(tazId = key.tazId, reservedFor = key.reservedFor) + def idxForFilter( + resources: Map[StallAttributes, StallValues] + ): Map[IndexForFilter, Map[StallAttributes, StallValues]] = { + resources.groupBy { + case (key, _) => + IndexForFilter(tazId = key.tazId, reservedFor = key.reservedFor) } } -} \ No newline at end of file +} diff --git a/src/main/scala/beam/agentsim/infrastructure/ZonalParkingManager.scala b/src/main/scala/beam/agentsim/infrastructure/ZonalParkingManager.scala index b7e63e05597..878877768b8 100755 --- a/src/main/scala/beam/agentsim/infrastructure/ZonalParkingManager.scala +++ b/src/main/scala/beam/agentsim/infrastructure/ZonalParkingManager.scala @@ -24,8 +24,6 @@ import scala.collection.JavaConverters._ import scala.collection.mutable import scala.util.Random - - class ZonalParkingManager( override val beamServices: BeamServices, val beamRouter: ActorRef, @@ -106,7 +104,7 @@ class ZonalParkingManager( val indexer: IndexerForZonalParkingManager = new IndexerForZonalParkingManager(pooledResources.toMap) -override def receive: Receive = { + override def receive: Receive = { case RegisterResource => // For Zonal Parking, stalls are created internally @@ -223,8 +221,6 @@ override def receive: Receive = { ) } - - private def maybeCreateNewStall( attrib: StallAttributes, atLocation: Location, diff --git a/src/main/scala/beam/agentsim/scheduler/TriggerMeasurer.scala b/src/main/scala/beam/agentsim/scheduler/TriggerMeasurer.scala index 48facef44f9..41936c274e4 100644 --- a/src/main/scala/beam/agentsim/scheduler/TriggerMeasurer.scala +++ b/src/main/scala/beam/agentsim/scheduler/TriggerMeasurer.scala @@ -77,19 +77,22 @@ class TriggerMeasurer extends LazyLogging { val groupedByActorType = actorTypeToTriggers .groupBy { case (actorType, _) => actorType } - val maxPerActorType = groupedByActorType.map { case (actorType, seq) => - val typeToCount: Iterable[(Class[_], Int)] = seq.flatMap { case (key, value) => value } - val classToMaxMsgCount = typeToCount.groupBy { case (clazz, _) => - clazz - }.map { case (clazz, iter) => clazz -> iter.map { case (k, v) => v}.max } - actorType -> classToMaxMsgCount + val maxPerActorType = groupedByActorType.map { + case (actorType, seq) => + val typeToCount: Iterable[(Class[_], Int)] = seq.flatMap { case (key, value) => value } + val classToMaxMsgCount = typeToCount + .groupBy { + case (clazz, _) => + clazz + } + .map { case (clazz, iter) => clazz -> iter.map { case (k, v) => v }.max } + actorType -> classToMaxMsgCount } maxPerActorType.foreach { case (actorType, triggetTypeToMaxMsgs) => val s = triggetTypeToMaxMsgs.map { case (key, v) => s"\t\t${key} => $v$nl" }.mkString - val str = s"""\t$actorType => ${ - triggetTypeToMaxMsgs.map { case (_, v) => v }.sum } + val str = s"""\t$actorType => ${triggetTypeToMaxMsgs.map { case (_, v) => v }.sum} |$s""".stripMargin sb.append(str) } diff --git a/src/main/scala/beam/calibration/BeamSigoptTuner.scala b/src/main/scala/beam/calibration/BeamSigoptTuner.scala index 3fb79240ec3..003b455cb1e 100755 --- a/src/main/scala/beam/calibration/BeamSigoptTuner.scala +++ b/src/main/scala/beam/calibration/BeamSigoptTuner.scala @@ -16,7 +16,6 @@ import com.typesafe.scalalogging.LazyLogging import scala.collection.JavaConverters import scala.util.Try - object BeamSigoptTuner { val client = new Client(Sigopt.clientToken) @@ -32,9 +31,9 @@ object BeamSigoptTuner { */ @throws[SigoptException] def fetchExperiment( - experimentId: String, - development: Boolean = false - ): Option[Experiment] = { + experimentId: String, + development: Boolean = false + ): Option[Experiment] = { val experimentList = Experiment.list().call().getData val optExperiment = experimentList.stream diff --git a/src/main/scala/beam/calibration/CalibrationArguments.scala b/src/main/scala/beam/calibration/CalibrationArguments.scala index 89f01566cbd..46ea8d33f04 100644 --- a/src/main/scala/beam/calibration/CalibrationArguments.scala +++ b/src/main/scala/beam/calibration/CalibrationArguments.scala @@ -1,13 +1,13 @@ package beam.calibration object CalibrationArguments { - val BENCHMARK_EXPERIMENTS_TAG: String = "benchmark" - val NUM_ITERATIONS_TAG: String = "num_iters" - val EXPERIMENT_ID_TAG: String = "experiment_id" - val NEW_EXPERIMENT_FLAG: String = "00000" - val RUN_TYPE: String = "run_type" - val SIGOPT_API_TOKEN_TAG: String = "sigopt_api_token" + val BENCHMARK_EXPERIMENTS_TAG: String = "benchmark" + val NUM_ITERATIONS_TAG: String = "num_iters" + val EXPERIMENT_ID_TAG: String = "experiment_id" + val NEW_EXPERIMENT_FLAG: String = "00000" + val RUN_TYPE: String = "run_type" + val SIGOPT_API_TOKEN_TAG: String = "sigopt_api_token" - val RUN_TYPE_LOCAL: String = "local" - val RUN_TYPE_REMOTE: String = "remote" + val RUN_TYPE_LOCAL: String = "local" + val RUN_TYPE_REMOTE: String = "remote" } diff --git a/src/main/scala/beam/calibration/ExperimentRunner.scala b/src/main/scala/beam/calibration/ExperimentRunner.scala index 49c79900896..16377b81a7d 100755 --- a/src/main/scala/beam/calibration/ExperimentRunner.scala +++ b/src/main/scala/beam/calibration/ExperimentRunner.scala @@ -4,14 +4,19 @@ import java.io.File import java.nio.file.{Path, Paths} import beam.analysis.plots.GraphsStatsAgentSimEventsListener -import beam.calibration.impl.example.{CountsObjectiveFunction, ErrorComparisonType, ModeChoiceObjectiveFunction, RideHailObjectiveFunction} +import beam.calibration.impl.example.{ + CountsObjectiveFunction, + ErrorComparisonType, + ModeChoiceObjectiveFunction, + RideHailObjectiveFunction +} import beam.sim.BeamHelper import beam.utils.reflection.ReflectionUtils import com.sigopt.model.{Observation, Suggestion} import com.typesafe.config.{Config, ConfigValueFactory} import org.matsim.core.config.{Config => MatsimConfig} -import scala.collection.{JavaConverters, mutable} +import scala.collection.{mutable, JavaConverters} object ObjectiveFunctionClassBuilder extends ReflectionUtils { override def packageName: String = "beam.calibration" @@ -91,8 +96,8 @@ case class ExperimentRunner(implicit experimentData: SigoptExperimentData) exten new ModeChoiceObjectiveFunction(benchmarkData.toAbsolutePath.toString) .evaluateFromRun(outpath.toAbsolutePath.toString, ErrorComparisonType.AbsoluteError) } else if (objectiveFunctionClassName.equals( - "ModeChoiceObjectiveFunction_AbsolutErrorWithPreferrenceForModeDiversity" - )) { + "ModeChoiceObjectiveFunction_AbsolutErrorWithPreferrenceForModeDiversity" + )) { val benchmarkData = Paths.get(experimentData.benchmarkFileLoc).toAbsolutePath val outpath = Paths.get(GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputFilename("modeChoice.csv")) new ModeChoiceObjectiveFunction(benchmarkData.toAbsolutePath.toString) @@ -101,8 +106,8 @@ case class ExperimentRunner(implicit experimentData: SigoptExperimentData) exten ErrorComparisonType.AbsoluteErrorWithPreferenceForModeDiversity ) } else if (objectiveFunctionClassName.equals( - "ModeChoiceObjectiveFunction_AbsoluteErrorWithMinLevelRepresentationOfMode" - )) { + "ModeChoiceObjectiveFunction_AbsoluteErrorWithMinLevelRepresentationOfMode" + )) { val benchmarkData = Paths.get(experimentData.benchmarkFileLoc).toAbsolutePath val outpath = Paths.get(GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputFilename("modeChoice.csv")) new ModeChoiceObjectiveFunction(benchmarkData.toAbsolutePath.toString) @@ -131,8 +136,8 @@ case class ExperimentRunner(implicit experimentData: SigoptExperimentData) exten -(countsWeight * Math.abs(countsObjVal) + modeWeight * Math.abs(modesObjVal)) } else if (objectiveFunctionClassName.equals( - "RideHail_maximizeReservationCount" - )) { + "RideHail_maximizeReservationCount" + )) { val outpath = Paths.get(GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputFilename("ridehailStats.csv")) RideHailObjectiveFunction.evaluateFromRun(outpath.toAbsolutePath.toString) } else { @@ -142,8 +147,8 @@ case class ExperimentRunner(implicit experimentData: SigoptExperimentData) exten } def createConfigBasedOnSuggestion( - suggestion: Suggestion - )(implicit experimentData: SigoptExperimentData): Config = { + suggestion: Suggestion + )(implicit experimentData: SigoptExperimentData): Config = { val assignments = suggestion.getAssignments val experimentName: String = suggestion.getExperiment @@ -153,15 +158,16 @@ case class ExperimentRunner(implicit experimentData: SigoptExperimentData) exten val configParams: mutable.Map[String, Object] = JavaConverters.mapAsScalaMap( experimentData.experimentDef.defaultParams ) ++ - JavaConverters - .iterableAsScalaIterable(assignments.entrySet()) - .seq - .map { e => - e.getKey -> e.getValue - } - .toMap + JavaConverters + .iterableAsScalaIterable(assignments.entrySet()) + .seq + .map { e => + e.getKey -> e.getValue + } + .toMap - val experimentBaseDir: Path = new File(experimentData.experimentDef.header.beamTemplateConfPath).toPath.getParent.toAbsolutePath + val experimentBaseDir + : Path = new File(experimentData.experimentDef.header.beamTemplateConfPath).toPath.getParent.toAbsolutePath val runDirectory = experimentData.experimentDef.projectRoot.relativize( Paths.get(experimentBaseDir.toString, "experiments", experimentName, "suggestions") @@ -172,10 +178,10 @@ case class ExperimentRunner(implicit experimentData: SigoptExperimentData) exten ) (Map( - "beam.agentsim.simulationName" -> s"$suggestionId", - "beam.outputs.baseOutputDirectory" -> beamOutputDir.getParent.toString, + "beam.agentsim.simulationName" -> s"$suggestionId", + "beam.outputs.baseOutputDirectory" -> beamOutputDir.getParent.toString, "beam.outputs.addTimestampToOutputDirectory" -> "false", - "beam.inputDirectory" -> experimentData.experimentDef.getTemplateConfigParentDirAsString + "beam.inputDirectory" -> experimentData.experimentDef.getTemplateConfigParentDirAsString ) ++ configParams).foldLeft(experimentData.baseConfig) { case (prevConfig, (paramName, paramValue)) => val configValue = ConfigValueFactory.fromAnyRef(paramValue) diff --git a/src/main/scala/beam/calibration/RunCalibration.scala b/src/main/scala/beam/calibration/RunCalibration.scala index 98eb158f719..f3ee734c585 100755 --- a/src/main/scala/beam/calibration/RunCalibration.scala +++ b/src/main/scala/beam/calibration/RunCalibration.scala @@ -22,7 +22,6 @@ import org.apache.commons.lang.SystemUtils */ object RunCalibration extends ExperimentApp with LazyLogging { - // requirement: /* --runType local|remote @@ -58,7 +57,6 @@ object RunCalibration extends ExperimentApp with LazyLogging { } } - // Aux Methods // override def parseArgs(args: Array[String]): Map[String, String] = { args @@ -133,5 +131,4 @@ object RunCalibration extends ExperimentApp with LazyLogging { logger.error("{} unknown", RUN_TYPE) } - } diff --git a/src/main/scala/beam/calibration/SigoptExperimentData.scala b/src/main/scala/beam/calibration/SigoptExperimentData.scala index 392438ca7d4..f01626fc544 100644 --- a/src/main/scala/beam/calibration/SigoptExperimentData.scala +++ b/src/main/scala/beam/calibration/SigoptExperimentData.scala @@ -11,12 +11,11 @@ import com.typesafe.scalalogging.LazyLogging import scala.util.Try case class SigoptExperimentData( - experimentDef: ExperimentDef, - benchmarkFileLoc: String, - experimentId: String, - development: Boolean = false - ) extends LazyLogging { - + experimentDef: ExperimentDef, + benchmarkFileLoc: String, + experimentId: String, + development: Boolean = false +) extends LazyLogging { val baseConfig: Config = ConfigFactory.parseFile(Paths.get(experimentDef.getHeader.getBeamTemplateConfPath).toFile) diff --git a/src/main/scala/beam/calibration/utils/CreateExperiment.scala b/src/main/scala/beam/calibration/utils/CreateExperiment.scala index 5c1148c62aa..2797e0bdd1a 100644 --- a/src/main/scala/beam/calibration/utils/CreateExperiment.scala +++ b/src/main/scala/beam/calibration/utils/CreateExperiment.scala @@ -20,5 +20,4 @@ object CreateExperiment extends ExperimentApp { SigoptExperimentData(experimentDef, benchmarkLoc, NEW_EXPERIMENT_FLAG, development = false) } - } diff --git a/src/main/scala/beam/calibration/utils/DeleteSuggestion.scala b/src/main/scala/beam/calibration/utils/DeleteSuggestion.scala index a721ec4e35b..db20b0ccfe7 100644 --- a/src/main/scala/beam/calibration/utils/DeleteSuggestion.scala +++ b/src/main/scala/beam/calibration/utils/DeleteSuggestion.scala @@ -57,8 +57,8 @@ object DeleteSuggestion extends LazyLogging { logger.info(s"Experiment with id $experimentId has no suggestion") } data.filter(_.getState == "open").foreach { d => - logger.info("DELETING SUGGESTION ID ({}) - {}", d.getId, d) - _experiment.suggestions().delete(d.getId).call() + logger.info("DELETING SUGGESTION ID ({}) - {}", d.getId, d) + _experiment.suggestions().delete(d.getId).call() } case None => logger.info(s"Experiment with id $experimentId not found") diff --git a/src/main/scala/beam/experiment/ExperimentApp.scala b/src/main/scala/beam/experiment/ExperimentApp.scala index 89fab2fd318..f10b9af6def 100644 --- a/src/main/scala/beam/experiment/ExperimentApp.scala +++ b/src/main/scala/beam/experiment/ExperimentApp.scala @@ -20,7 +20,7 @@ class ExperimentApp extends App { .collect { case Array("--experiments", filePath: String) if filePath.trim.nonEmpty => (EXPERIMENTS_TAG, filePath) - case arg@_ => + case arg @ _ => throw new IllegalArgumentException(arg.mkString(" ")) } .toMap @@ -71,8 +71,6 @@ object ExperimentApp { experimentPath } - - def loadExperimentDefs(file: File): ExperimentDef = { import org.yaml.snakeyaml.{TypeDescription, Yaml} val constructor = new Constructor(classOf[ExperimentDef]) @@ -94,7 +92,4 @@ object ExperimentApp { experiment } - - - } diff --git a/src/main/scala/beam/experiment/ExperimentDef.scala b/src/main/scala/beam/experiment/ExperimentDef.scala index 39caf946f66..75a8406bca7 100755 --- a/src/main/scala/beam/experiment/ExperimentDef.scala +++ b/src/main/scala/beam/experiment/ExperimentDef.scala @@ -25,7 +25,7 @@ case class ExperimentDef( } } - def defaultParams_= (params: JavaMap[String, Object]): Unit = { + def defaultParams_=(params: JavaMap[String, Object]): Unit = { _defaultParams.clear() if (params != null) { _defaultParams.putAll(params) @@ -42,7 +42,7 @@ case class ExperimentDef( } } - def factors_= (newFactors: JavaList[Factor]): Unit = { + def factors_=(newFactors: JavaList[Factor]): Unit = { _factors.clear() if (newFactors != null) { _factors.addAll(newFactors) @@ -124,17 +124,17 @@ case class ExperimentRun(experiment: ExperimentDef, combinations: Seq[(Level, Fa val overrideParams = experiment.defaultParams.asScala.clone() ++ runParams overrideParams.toMap } - + lazy val levels: Map[String, String] = { combinations.map(tup => tup._2.title -> tup._1.name).toMap } - + lazy val name: String = { combinations.map(lf => s"${lf._2.title}_${lf._1.name}").mkString("__") } def getParam(name: String) = params(name) - + def getLevelTitle(name: String) = levels(name) override def toString: String = { diff --git a/src/main/scala/beam/experiment/ExperimentGenerator.scala b/src/main/scala/beam/experiment/ExperimentGenerator.scala index 25bd5819ab6..c7c2162f225 100755 --- a/src/main/scala/beam/experiment/ExperimentGenerator.scala +++ b/src/main/scala/beam/experiment/ExperimentGenerator.scala @@ -24,7 +24,6 @@ import scala.collection.JavaConverters._ object ExperimentGenerator extends ExperimentApp { import beam.experiment.ExperimentApp - override def validateExperimentConfig(experiment: ExperimentDef): Unit = { if (!Files.exists(Paths.get(experiment.header.beamTemplateConfPath))) { throw new IllegalArgumentException( @@ -40,7 +39,6 @@ object ExperimentGenerator extends ExperimentApp { } } - def getExperimentPath(): Path = { Paths.get(experimentPath.getParent.toString, "runs") } @@ -49,7 +47,6 @@ object ExperimentGenerator extends ExperimentApp { Paths.get(getExperimentPath.toString, "batchRunExperiment.sh") } - val baseConfig = ConfigFactory.parseFile(Paths.get(experimentDef.header.beamTemplateConfPath).toFile) val experimentVariations = experimentDef.combinationsOfLevels() diff --git a/src/main/scala/beam/replanning/utilitybased/ChangeModeForTour.scala b/src/main/scala/beam/replanning/utilitybased/ChangeModeForTour.scala index 86a46ce617a..93425ccffde 100755 --- a/src/main/scala/beam/replanning/utilitybased/ChangeModeForTour.scala +++ b/src/main/scala/beam/replanning/utilitybased/ChangeModeForTour.scala @@ -23,13 +23,13 @@ import org.matsim.core.router.TripStructureUtils.Subtour import org.matsim.core.router.{CompositeStageActivityTypes, TripRouter, TripStructureUtils} import scala.collection.JavaConverters._ -import scala.collection.{JavaConverters, mutable} +import scala.collection.{mutable, JavaConverters} import scala.util.Random class ChangeModeForTour( - beamServices: BeamServices, - chainBasedTourVehicleAllocator: ChainBasedTourVehicleAllocator - ) extends PlanAlgorithm { + beamServices: BeamServices, + chainBasedTourVehicleAllocator: ChainBasedTourVehicleAllocator +) extends PlanAlgorithm { val rng = new MersenneTwister(3004568) // Random.org val random = new Random(3004568) @@ -59,25 +59,30 @@ class ChangeModeForTour( val res = weightedRandom.sample(1, Array()) chainBasedTourVehicleAllocator.identifyChainBasedModesForAgent(person.getId) ++ Vector[ BeamMode - ](res(0)) ++ - Vector[BeamMode](WALK, RIDE_HAIL) + ](res(0)) ++ + Vector[BeamMode](WALK, RIDE_HAIL) } def scoreTour( - tour: Subtour, - person: Person, - modeChoiceCalculator: ModeChoiceCalculator - ): Map[BeamMode, Double] = { + tour: Subtour, + person: Person, + modeChoiceCalculator: ModeChoiceCalculator + ): Map[BeamMode, Double] = { val alternativesForTour = findAlternativesForTour(tour, person) - (for {alt <- alternativesForTour} yield { + (for { alt <- alternativesForTour } yield { alt -> JavaConverters .collectionAsScalaIterable(tour.getTrips) .map(trip => { val timeDist = getCostAndTimeForMode(alt, trip.getOriginActivity, trip.getDestinationActivity) if (alt.isTransit) { - modeChoiceCalculator.utilityOf(if (alternativesForTour.contains(CAR)) DRIVE_TRANSIT - else WALK_TRANSIT, timeDist._1, timeDist._2, numTransfers = rng.nextInt(4) + 1) + modeChoiceCalculator.utilityOf( + if (alternativesForTour.contains(CAR)) DRIVE_TRANSIT + else WALK_TRANSIT, + timeDist._1, + timeDist._2, + numTransfers = rng.nextInt(4) + 1 + ) } else { modeChoiceCalculator.utilityOf(alt, timeDist._1, timeDist._2) } @@ -87,10 +92,10 @@ class ChangeModeForTour( } def getCostAndTimeForMode( - beamMode: BeamMode, - origin: Activity, - dest: Activity - ): (Double, Double) = { + beamMode: BeamMode, + origin: Activity, + dest: Activity + ): (Double, Double) = { val originCoord = origin.getCoord val destCoord = dest.getCoord val tripDistanceInMeters = beamServices.geo @@ -129,9 +134,9 @@ class ChangeModeForTour( } def rankAlternatives( - plan: Plan, - attributesOfIndividual: AttributesOfIndividual - ): Map[Int, Map[BeamMode, Double]] = { + plan: Plan, + attributesOfIndividual: AttributesOfIndividual + ): Map[Int, Map[BeamMode, Double]] = { val modeChoiceCalculator = beamServices.modeChoiceCalculatorFactory(attributesOfIndividual) val subTours = JavaConverters.collectionAsScalaIterable( @@ -155,7 +160,7 @@ class ChangeModeForTour( ) if (legs.isEmpty) { - for {trip <- trips} yield { + for { trip <- trips } yield { insertEmptyTrip( plan, trip.getOriginActivity, @@ -186,12 +191,12 @@ class ChangeModeForTour( } def insertEmptyTrip( - plan: Plan, - fromActivity: Activity, - toActivity: Activity, - mainMode: String, - pf: PopulationFactory - ): Unit = { + plan: Plan, + fromActivity: Activity, + toActivity: Activity, + mainMode: String, + pf: PopulationFactory + ): Unit = { val list: util.List[Leg] = Collections.singletonList(pf.createLeg(mainMode)) TripRouter.insertTrip(plan, fromActivity, list, toActivity) } @@ -210,7 +215,7 @@ class ChangeModeForTour( acts(1), "car", chainBasedTourVehicleAllocator.population.getFactory - ) + ) ) } @@ -236,18 +241,31 @@ class ChangeModeForTour( specifiedVot.asInstanceOf[Double] } - val availableModes: Seq[BeamMode] = Option(beamServices.matsimServices.getScenario - .getPopulation.getPersonAttributes.getAttribute(person.getId.toString, "available-modes") + val availableModes: Seq[BeamMode] = Option( + beamServices.matsimServices.getScenario.getPopulation.getPersonAttributes + .getAttribute(person.getId.toString, "available-modes") ).fold(BeamMode.availableModes)( attr => availableModeParser(attr.toString) ) - val income = Option(beamServices.matsimServices.getScenario.getPopulation.getPersonAttributes.getAttribute(person.getId.toString, "income").asInstanceOf[Int]) + val income = Option( + beamServices.matsimServices.getScenario.getPopulation.getPersonAttributes + .getAttribute(person.getId.toString, "income") + .asInstanceOf[Int] + ) val attributesOfIndividual = - AttributesOfIndividual(HouseholdAttributes(household, householdVehicles), - modalityStyle, PersonUtils.getSex(person).equalsIgnoreCase("M"), availableModes, - valueOfTime, Option(PersonUtils.getAge(person)), income.map{x=>x}) + AttributesOfIndividual( + HouseholdAttributes(household, householdVehicles), + modalityStyle, + PersonUtils.getSex(person).equalsIgnoreCase("M"), + availableModes, + valueOfTime, + Option(PersonUtils.getAge(person)), + income.map { x => + x + } + ) person.getCustomAttributes.put("beam-attributes", attributesOfIndividual) @@ -278,8 +296,8 @@ class ChangeModeForTour( private def maybeFixPlans(plan: Plan): Unit = { if (JavaConverters - .collectionAsScalaIterable(TripStructureUtils.getLegs(plan)) - .isEmpty) { + .collectionAsScalaIterable(TripStructureUtils.getLegs(plan)) + .isEmpty) { addTripsBetweenActivities(plan) } plan.getPlanElements.asScala.foreach { diff --git a/src/main/scala/beam/router/BeamRouter.scala b/src/main/scala/beam/router/BeamRouter.scala index 90f0c8350e8..d8445d323dc 100755 --- a/src/main/scala/beam/router/BeamRouter.scala +++ b/src/main/scala/beam/router/BeamRouter.scala @@ -5,7 +5,18 @@ import java.util.UUID import java.util.concurrent.TimeUnit import akka.actor.Status.{Status, Success} -import akka.actor.{Actor, ActorLogging, ActorRef, Address, Cancellable, ExtendedActorSystem, Props, RelativeActorPath, RootActorPath, Stash} +import akka.actor.{ + Actor, + ActorLogging, + ActorRef, + Address, + Cancellable, + ExtendedActorSystem, + Props, + RelativeActorPath, + RootActorPath, + Stash +} import akka.cluster.ClusterEvent._ import akka.cluster.{Cluster, Member, MemberStatus} import akka.pattern._ @@ -124,8 +135,6 @@ class BeamRouter( //TODO: Add Deathwatch to remove node } - - private var traveTimeOpt: Option[TravelTime] = None val kryoSerializer = new KryoSerializer(context.system.asInstanceOf[ExtendedActorSystem]) diff --git a/src/main/scala/beam/router/LinkTravelTimeContainer.scala b/src/main/scala/beam/router/LinkTravelTimeContainer.scala index b87554ced62..73b58938dcd 100755 --- a/src/main/scala/beam/router/LinkTravelTimeContainer.scala +++ b/src/main/scala/beam/router/LinkTravelTimeContainer.scala @@ -12,7 +12,9 @@ import org.matsim.vehicles.Vehicle import scala.collection.mutable -class LinkTravelTimeContainer(fileName: String, timeBinSizeInSeconds: Int, maxHour: Int) extends TravelTime with LazyLogging { +class LinkTravelTimeContainer(fileName: String, timeBinSizeInSeconds: Int, maxHour: Int) + extends TravelTime + with LazyLogging { val linkTravelTimeMap: scala.collection.Map[Id[Link], Array[Double]] = loadLinkStats() def loadLinkStats(): scala.collection.Map[Id[Link], Array[Double]] = { @@ -43,8 +45,7 @@ class LinkTravelTimeContainer(fileName: String, timeBinSizeInSeconds: Int, maxHo } } } - } - finally { + } finally { bufferedReader.close() gzipStream.close() } diff --git a/src/main/scala/beam/router/TransitInitializer.scala b/src/main/scala/beam/router/TransitInitializer.scala index ee1879c019a..3f426e39857 100644 --- a/src/main/scala/beam/router/TransitInitializer.scala +++ b/src/main/scala/beam/router/TransitInitializer.scala @@ -189,7 +189,8 @@ class TransitInitializer( Source .fromFile(services.beamConfig.beam.agentsim.agents.vehicles.transitVehicleTypesByRouteFile) .getLines() - .toList.tail + .toList + .tail ).getOrElse(List()) .map(_.trim.split(",")) .filter(_.length > 2) diff --git a/src/main/scala/beam/router/osm/TollCalculator.scala b/src/main/scala/beam/router/osm/TollCalculator.scala index 56113472826..a17ede8f1a0 100755 --- a/src/main/scala/beam/router/osm/TollCalculator.scala +++ b/src/main/scala/beam/router/osm/TollCalculator.scala @@ -17,23 +17,25 @@ class TollCalculator(val config: BeamConfig, val directory: String) extends Lazy type TimeDependentToll = Seq[Toll] - private val tollsByLinkId: Map[Int, TimeDependentToll] = readTollPrices(config.beam.agentsim.toll.file).withDefaultValue(Vector()) + private val tollsByLinkId: Map[Int, TimeDependentToll] = + readTollPrices(config.beam.agentsim.toll.file).withDefaultValue(Vector()) private val tollsByWayId: Map[Long, TimeDependentToll] = readFromCacheFileOrOSM().withDefaultValue(Vector()) logger.info("Ways keys size: {}", tollsByWayId.keys.size) - def calcTollByOsmIds(osmIds: Seq[Long]): Double = osmIds.view.map(tollsByWayId).map(toll => applyTimeDependentTollAtTime(toll, 0)).sum + def calcTollByOsmIds(osmIds: Seq[Long]): Double = + osmIds.view.map(tollsByWayId).map(toll => applyTimeDependentTollAtTime(toll, 0)).sum def calcTollByLinkIds(path: BeamPath): Double = { val linkEnterTimes = path.linkTravelTime.scanLeft(path.startPoint.time)(_ + _) - path - .linkIds + path.linkIds .zip(linkEnterTimes) .map(calcTollByLinkId _ tupled) .sum } - def calcTollByLinkId(linkId: Int, time: Int): Double = applyTimeDependentTollAtTime(tollsByLinkId(linkId), time) * config.beam.agentsim.tuning.tollPrice + def calcTollByLinkId(linkId: Int, time: Int): Double = + applyTimeDependentTollAtTime(tollsByLinkId(linkId), time) * config.beam.agentsim.tuning.tollPrice private def applyTimeDependentTollAtTime(tolls: TimeDependentToll, time: Int) = { tolls.view.filter(toll => toll.timeRange.has(time)).map(toll => toll.amount).sum @@ -46,8 +48,7 @@ class TollCalculator(val config: BeamConfig, val directory: String) extends Lazy .getLines() .drop(1) // table header .toList - rowList - .view + rowList.view .map(_.split(",")) .groupBy(t => t(0).toInt) .mapValues(lines => lines.map(t => Toll(t(1).toDouble, Range(t(2))))) @@ -88,7 +89,8 @@ class TollCalculator(val config: BeamConfig, val directory: String) extends Lazy def readTolls(osm: OSM): Map[Long, Seq[Toll]] = { osm.ways.asScala.view.flatMap { case (id, way) if way.tags != null => - val tolls = way.tags.asScala.find(_.key == "charge") + val tolls = way.tags.asScala + .find(_.key == "charge") .map(chargeTag => parseTolls(chargeTag.value)) .getOrElse(Nil) if (tolls.nonEmpty) Some(Long2long(id) -> tolls) else None @@ -105,8 +107,7 @@ class TollCalculator(val config: BeamConfig, val directory: String) extends Lazy .flatMap(c => { c.split(" ") .headOption - .flatMap(token => - Some(Toll(token.toDouble, Range("[:]")))) + .flatMap(token => Some(Toll(token.toDouble, Range("[:]")))) }) } @@ -115,4 +116,3 @@ class TollCalculator(val config: BeamConfig, val directory: String) extends Lazy object TollCalculator { case class Toll(amount: Double, timeRange: Range) extends Serializable } - diff --git a/src/main/scala/beam/router/r5/DefaultNetworkCoordinator.scala b/src/main/scala/beam/router/r5/DefaultNetworkCoordinator.scala index 8602d26541e..c431f88ead2 100755 --- a/src/main/scala/beam/router/r5/DefaultNetworkCoordinator.scala +++ b/src/main/scala/beam/router/r5/DefaultNetworkCoordinator.scala @@ -5,7 +5,6 @@ import com.conveyal.r5.transit.TransportNetwork import com.typesafe.scalalogging.LazyLogging import org.matsim.api.core.v01.network.Network - case class DefaultNetworkCoordinator(beamConfig: BeamConfig) extends LazyLogging with NetworkCoordinator { var transportNetwork: TransportNetwork = _ diff --git a/src/main/scala/beam/router/r5/FrequencyAdjustingNetworkCoordinator.scala b/src/main/scala/beam/router/r5/FrequencyAdjustingNetworkCoordinator.scala index 54b2fef6c14..1ce4949f598 100644 --- a/src/main/scala/beam/router/r5/FrequencyAdjustingNetworkCoordinator.scala +++ b/src/main/scala/beam/router/r5/FrequencyAdjustingNetworkCoordinator.scala @@ -25,31 +25,38 @@ case class FrequencyAdjustingNetworkCoordinator(beamConfig: BeamConfig) extends def loadFrequencyData(): Set[FrequencyAdjustmentInput] = { val lines = Source.fromFile(beamConfig.beam.agentsim.scenarios.frequencyAdjustmentFile).getLines().drop(1) - val dataRows = for{line<-lines}yield{ + val dataRows = for { line <- lines } yield { line.split(",") }.toSeq - (for{row<-dataRows}yield{FrequencyAdjustmentInput(row(0),row(1).toInt,row(2).toInt,row(3).toInt,row(4).toInt)}).toSet + (for { row <- dataRows } yield { + FrequencyAdjustmentInput(row(0), row(1).toInt, row(2).toInt, row(3).toInt, row(4).toInt) + }).toSet } def buildFrequencyAdjustmentScenario(adjustmentInputs: Set[FrequencyAdjustmentInput]): Scenario = { val scenario = new Scenario() - val adjustmentsByRouteId: Map[String, Set[FrequencyAdjustmentInput]] = adjustmentInputs.groupBy(adjustment => s"${feeds.head.feedId}:${getTripForId(adjustment.tripId).route_id}") - util.Arrays.asList(adjustmentsByRouteId.foreach { case (rid, adjustments) => - val adjustFrequency: AdjustFrequency = new AdjustFrequency - adjustFrequency.route = rid - val entries: util.Set[AddTrips.PatternTimetable] = adjustments.map { adjustmentInput => adjustTripFrequency(adjustmentInput) }.asJava - val listEntries: util.List[AddTrips.PatternTimetable] = new util.ArrayList[AddTrips.PatternTimetable]() - listEntries.addAll(entries) - adjustFrequency.entries = listEntries - scenario.modifications.add(adjustFrequency) + val adjustmentsByRouteId: Map[String, Set[FrequencyAdjustmentInput]] = + adjustmentInputs.groupBy(adjustment => s"${feeds.head.feedId}:${getTripForId(adjustment.tripId).route_id}") + util.Arrays.asList(adjustmentsByRouteId.foreach { + case (rid, adjustments) => + val adjustFrequency: AdjustFrequency = new AdjustFrequency + adjustFrequency.route = rid + val entries: util.Set[AddTrips.PatternTimetable] = adjustments.map { adjustmentInput => + adjustTripFrequency(adjustmentInput) + }.asJava + val listEntries: util.List[AddTrips.PatternTimetable] = new util.ArrayList[AddTrips.PatternTimetable]() + listEntries.addAll(entries) + adjustFrequency.entries = listEntries + scenario.modifications.add(adjustFrequency) }) scenario } - def getTripForId(tripId: String): Trip = { - feeds.map { feed => feed.trips.asScala(tripId) }.head + feeds.map { feed => + feed.trips.asScala(tripId) + }.head } def adjustTripFrequency(adjustmentInput: FrequencyAdjustmentInput): AddTrips.PatternTimetable = { @@ -69,23 +76,28 @@ case class FrequencyAdjustingNetworkCoordinator(beamConfig: BeamConfig) extends entry } - case class FrequencyAdjustmentInput(tripId: String, - startTime: Int, - endTime: Int, - headwaySecs: Int, - exactTimes: Int = 0) + case class FrequencyAdjustmentInput( + tripId: String, + startTime: Int, + endTime: Int, + headwaySecs: Int, + exactTimes: Int = 0 + ) def getAllGTFSFiles(pathToR5Dir: String): ArrayBuffer[Path] = { val files = ArrayBuffer.empty[Path] val r5Path = Paths.get(s"$pathToR5Dir") - Files.walkFileTree(r5Path, new SimpleFileVisitor[Path] { - override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = { - if (file.getFileName.toString.endsWith(".zip")) { - files += file + Files.walkFileTree( + r5Path, + new SimpleFileVisitor[Path] { + override def visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult = { + if (file.getFileName.toString.endsWith(".zip")) { + files += file + } + FileVisitResult.CONTINUE } - FileVisitResult.CONTINUE } - }) + ) files } @@ -99,7 +111,8 @@ case class FrequencyAdjustingNetworkCoordinator(beamConfig: BeamConfig) extends override def postProcessing(): Unit = { this.transportNetwork.transitLayer.buildDistanceTables(null) - this.transportNetwork = buildFrequencyAdjustmentScenario(this.frequencyData).applyToTransportNetwork(transportNetwork) + this.transportNetwork = + buildFrequencyAdjustmentScenario(this.frequencyData).applyToTransportNetwork(transportNetwork) convertFrequenciesToTrips() } } diff --git a/src/main/scala/beam/router/r5/NetworkCoordinator.scala b/src/main/scala/beam/router/r5/NetworkCoordinator.scala index dcdee0909cb..27f7ab27d2c 100644 --- a/src/main/scala/beam/router/r5/NetworkCoordinator.scala +++ b/src/main/scala/beam/router/r5/NetworkCoordinator.scala @@ -12,17 +12,17 @@ import org.matsim.core.network.io.MatsimNetworkReader import scala.collection.JavaConverters._ -trait NetworkCoordinator extends LazyLogging{ +trait NetworkCoordinator extends LazyLogging { - val beamConfig:BeamConfig + val beamConfig: BeamConfig var transportNetwork: TransportNetwork var network: Network - protected def preprocessing():Unit + protected def preprocessing(): Unit - def init():Unit = { + def init(): Unit = { preprocessing() loadNetwork() postProcessing() @@ -69,23 +69,24 @@ trait NetworkCoordinator extends LazyLogging{ if (tp.hasFrequencies) { val toAdd: Vector[TripSchedule] = tp.tripSchedules.asScala.toVector.flatMap { ts => val tripStartTimes = ts.startTimes(0).until(ts.endTimes(0)).by(ts.headwaySeconds(0)).toVector - tripStartTimes.zipWithIndex.map { case (startTime, ind) => - val tsNew = ts.clone() - val newTripId = s"${tsNew.tripId}-$ind" - val newArrivals = new Array[Int](ts.arrivals.length) - val newDepartures = new Array[Int](ts.arrivals.length) - for (i <- tsNew.arrivals.indices) { - newArrivals(i) = tsNew.arrivals(i) + startTime - newDepartures(i) = tsNew.departures(i) + startTime - } - tsNew.arrivals = newArrivals - tsNew.departures = newDepartures - tsNew.tripId = newTripId - tsNew.frequencyEntryIds = null - tsNew.headwaySeconds = null - tsNew.startTimes = null - tsNew.endTimes = null - tsNew + tripStartTimes.zipWithIndex.map { + case (startTime, ind) => + val tsNew = ts.clone() + val newTripId = s"${tsNew.tripId}-$ind" + val newArrivals = new Array[Int](ts.arrivals.length) + val newDepartures = new Array[Int](ts.arrivals.length) + for (i <- tsNew.arrivals.indices) { + newArrivals(i) = tsNew.arrivals(i) + startTime + newDepartures(i) = tsNew.departures(i) + startTime + } + tsNew.arrivals = newArrivals + tsNew.departures = newDepartures + tsNew.tripId = newTripId + tsNew.frequencyEntryIds = null + tsNew.headwaySeconds = null + tsNew.startTimes = null + tsNew.endTimes = null + tsNew } } tp.tripSchedules.clear() diff --git a/src/main/scala/beam/router/r5/R5RoutingWorker.scala b/src/main/scala/beam/router/r5/R5RoutingWorker.scala index 02b9506c6c9..c267be663cc 100755 --- a/src/main/scala/beam/router/r5/R5RoutingWorker.scala +++ b/src/main/scala/beam/router/r5/R5RoutingWorker.scala @@ -61,10 +61,10 @@ import scala.language.postfixOps import scala.util.{Failure, Success, Try} case class WorkerParameters( - beamServices: BeamServices, - transportNetwork: TransportNetwork, - network: Network, - scenario: Scenario, + beamServices: BeamServices, + transportNetwork: TransportNetwork, + network: Network, + scenario: Scenario, fareCalculator: FareCalculator, tollCalculator: TollCalculator, transitVehicles: Vehicles, @@ -114,7 +114,8 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo BeamServices.readBeamVehicleTypeFile(beamConfig.beam.agentsim.agents.vehicles.beamVehicleTypesFile, fuelTypes) val privateVehicles: TrieMap[Id[BeamVehicle], BeamVehicle] = BeamServices.readVehiclesFile(beamConfig.beam.agentsim.agents.vehicles.beamVehiclesFile, vehicleTypes) - override val modeSubsidies: ModeSubsidy = ModeSubsidy(ModeSubsidy.loadSubsidies(beamConfig.beam.agentsim.agents.modeSubsidy.file)) + override val modeSubsidies: ModeSubsidy = + ModeSubsidy(ModeSubsidy.loadSubsidies(beamConfig.beam.agentsim.agents.modeSubsidy.file)) override def startNewIteration(): Unit = throw new Exception("???") @@ -131,7 +132,8 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo override def rideHailIterationHistoryActor: akka.actor.ActorRef = ??? - override val travelTimeCalculatorConfigGroup: TravelTimeCalculatorConfigGroup = matsimConfig.travelTimeCalculator() + override val travelTimeCalculatorConfigGroup: TravelTimeCalculatorConfigGroup = + matsimConfig.travelTimeCalculator() } val initializer = new TransitInitializer(beamServices, transportNetwork, scenario.getTransitVehicles) @@ -153,10 +155,10 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo } val WorkerParameters( - beamServices, - transportNetwork, - network, - scenario, + beamServices, + transportNetwork, + network, + scenario, fareCalculator, tollCalculator, transitVehicles, @@ -194,7 +196,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo private val linkIdMap: HashMap[Int, Link] = { val start = System.currentTimeMillis() val pairs = links.asScala.map { case (k, v) => k.toString.toInt -> v }.toSeq - val map = HashMap(pairs :_*) + val map = HashMap(pairs: _*) val end = System.currentTimeMillis() log.info("linkIdMap is built in {} ms", end - start) map @@ -271,18 +273,23 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo askForMoreWork() case UpdateTravelTimeRemote(map) => - val travelTimeCalc = TravelTimeCalculatorHelper.CreateTravelTimeCalculator(beamServices.beamConfig.beam.agentsim.timeBinSize, map) + val travelTimeCalc = + TravelTimeCalculatorHelper.CreateTravelTimeCalculator(beamServices.beamConfig.beam.agentsim.timeBinSize, map) maybeTravelTime = Some(travelTimeCalc) - log.info(s"{} UpdateTravelTimeRemote. Set new travel time from map with size {}", getNameAndHashCode, map.keySet().size()) + log.info( + s"{} UpdateTravelTimeRemote. Set new travel time from map with size {}", + getNameAndHashCode, + map.keySet().size() + ) cache.invalidateAll() askForMoreWork case EmbodyWithCurrentTravelTime( - leg: BeamLeg, - vehicleId: Id[Vehicle], - embodyRequestId: UUID, - mustParkAtEnd: Boolean - ) => + leg: BeamLeg, + vehicleId: Id[Vehicle], + embodyRequestId: UUID, + mustParkAtEnd: Boolean + ) => val now = ZonedDateTime.now(ZoneOffset.UTC) val travelTime = (time: Int, linkId: Int) => maybeTravelTime match { @@ -294,7 +301,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo new ProfileRequest, StreetMode.valueOf(leg.mode.r5Mode.get.left.get.toString) )).toInt - } + } val duration = RoutingModel .traverseStreetLeg(leg, vehicleId, travelTime) .maxBy(e => e.getTime) @@ -313,7 +320,14 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo } } else { Vector( - EmbodiedBeamLeg(leg.copy(duration = duration.toInt), vehicleId, asDriver = true, None, 0, unbecomeDriverOnCompletion = true) + EmbodiedBeamLeg( + leg.copy(duration = duration.toInt), + vehicleId, + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = true + ) ) } @@ -465,7 +479,16 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo val profileResponse = latency("walkToVehicleRoute-router-time", Metrics.RegularLevel) { cache.get( - R5Request(from, to, time, directMode, accessMode, transitModes, egressMode, routingRequest.timeValueOfMoney) + R5Request( + from, + to, + time, + directMode, + accessMode, + transitModes, + egressMode, + routingRequest.timeValueOfMoney + ) ) } if (profileResponse.options.isEmpty) { @@ -525,7 +548,16 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo val profileResponse = latency("vehicleOnEgressRoute-router-time", Metrics.RegularLevel) { cache.get( - R5Request(from, to, time, directMode, accessMode, transitModes, egressMode, routingRequest.timeValueOfMoney) + R5Request( + from, + to, + time, + directMode, + accessMode, + transitModes, + egressMode, + routingRequest.timeValueOfMoney + ) ) } if (!profileResponse.options.isEmpty) { @@ -596,26 +628,35 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo val transitModes: IndexedSeq[TransitModes] = routingRequest.transitModes.map(_.r5Mode.get.right.get) val latencyTag = (if (transitModes.isEmpty) - "mainVehicleToDestinationRoute" - else "mainTransitRoute") + "-router-time" + "mainVehicleToDestinationRoute" + else "mainTransitRoute") + "-router-time" val profileResponse: ProfileResponse = latency(latencyTag, Metrics.RegularLevel) { cache.get( - R5Request(from, to, time, directMode, accessMode, transitModes, egressMode, routingRequest.timeValueOfMoney) + R5Request( + from, + to, + time, + directMode, + accessMode, + transitModes, + egressMode, + routingRequest.timeValueOfMoney + ) ) } val tripsWithFares = profileResponse.options.asScala.flatMap(option => { /* - * Iterating all itinerary from a ProfileOption to construct the BeamTrip, - * itinerary has a PointToPointConnection object that help relating access, - * egress and transit for the particular itinerary. That contains indexes of - * access and egress and actual object could be located from lists under option object, - * as there are separate collections for each. - * - * And after locating through these indexes, constructing BeamLeg for each and - * finally add these legs back to BeamTrip. - */ + * Iterating all itinerary from a ProfileOption to construct the BeamTrip, + * itinerary has a PointToPointConnection object that help relating access, + * egress and transit for the particular itinerary. That contains indexes of + * access and egress and actual object could be located from lists under option object, + * as there are separate collections for each. + * + * And after locating through these indexes, constructing BeamLeg for each and + * finally add these legs back to BeamTrip. + */ option.itinerary.asScala.view .filter { itin => val startTime = beamServices.dates.toBaseMidnightSeconds( @@ -639,7 +680,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo // If there's a gap between access leg start time and walk leg, we need to move that ahead // this covers the various contingencies for doing this. val delayStartTime = - Math.max(0.0, (tripStartTime - routingRequest.departureTime.atTime) - walkLeg.duration) + Math.max(0.0, (tripStartTime - routingRequest.departureTime.atTime) - walkLeg.duration) legsWithFares += ((walkLeg.updateStartTime(walkLeg.startTime + delayStartTime.toInt), 0.0)) }) @@ -659,19 +700,19 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo val isTransit = itinerary.connection.transit != null && !itinerary.connection.transit.isEmpty val theLeg = BeamLeg( - tripStartTime, - mapLegMode(access.mode), - theTravelPath.duration, - travelPath = theTravelPath - ) - val splitLegs = if (access.mode != LegMode.WALK && routingRequest.mustParkAtEnd) { - splitLegForParking(theLeg) - } else { - Vector(theLeg) - } - // assign toll to first part of the split - legsWithFares += ((splitLegs.head, toll)) - splitLegs.tail.foreach(leg => legsWithFares += ((leg, 0.0))) + tripStartTime, + mapLegMode(access.mode), + theTravelPath.duration, + travelPath = theTravelPath + ) + val splitLegs = if (access.mode != LegMode.WALK && routingRequest.mustParkAtEnd) { + splitLegForParking(theLeg) + } else { + Vector(theLeg) + } + // assign toll to first part of the split + legsWithFares += ((splitLegs.head, toll)) + splitLegs.tail.foreach(leg => legsWithFares += ((leg, 0.0))) //add a Dummy walk BeamLeg to the end of that trip if (isRouteForPerson && access.mode != LegMode.WALK) { @@ -684,7 +725,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo /* Based on "Index in transit list specifies transit with same index" (comment from PointToPointConnection line 14) assuming that: For each transit in option there is a TransitJourneyID in connection - */ + */ val segments = option.transit.asScala zip itinerary.connection.transit.asScala val fares = latency("fare-transit-time", Metrics.VerboseLevel) { val fareSegments = getFareSegments(segments.toVector) @@ -729,7 +770,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo ), 0.0 ) - ) + ) arrivalTime = arrivalTime + transitSegment.middle.duration // in case of middle arrival time would update } } @@ -748,7 +789,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo ), 0.0 ) - ) + ) if (isRouteForPerson && egress.mode != LegMode.WALK) legsWithFares += ((dummyWalk(arrivalTime + egress.duration), 0.0)) } @@ -774,12 +815,19 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo for ((beamLeg, index) <- tripWithFares.trip.legs.zipWithIndex) yield { val cost = tripWithFares.legFares.getOrElse(index, 0.0) // FIXME this value is never used. if (Modes.isR5TransitMode(beamLeg.mode)) { - EmbodiedBeamLeg(beamLeg, beamLeg.travelPath.transitStops.get.vehicleId, asDriver = false, None, cost, unbecomeDriverOnCompletion = false) + EmbodiedBeamLeg( + beamLeg, + beamLeg.travelPath.transitStops.get.vehicleId, + asDriver = false, + None, + cost, + unbecomeDriverOnCompletion = false + ) } else { val unbecomeDriverAtComplete = Modes .isR5LegMode(beamLeg.mode) && vehicle.asDriver && ((beamLeg.mode == CAR && (indexOfFirstCarLegInParkingTrip < 0 || index != indexOfFirstCarLegInParkingTrip)) || - (beamLeg.mode != CAR && beamLeg.mode != WALK) || - (beamLeg.mode == WALK && index == tripWithFares.trip.legs.size - 1)) + (beamLeg.mode != CAR && beamLeg.mode != WALK) || + (beamLeg.mode == WALK && index == tripWithFares.trip.legs.size - 1)) if (beamLeg.mode == WALK) { val body = routingRequest.streetVehicles.find(_.mode == WALK).get @@ -793,7 +841,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo }) } case Failure(e) if e == DestinationUnreachableException => Nil - case Failure(e) => throw e + case Failure(e) => throw e } } @@ -869,10 +917,10 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo } private def buildStreetPath( - segment: StreetSegment, - tripStartTime: Int, - mode: StreetMode - ): BeamPath = { + segment: StreetSegment, + tripStartTime: Int, + mode: StreetMode + ): BeamPath = { var activeLinkIds = ArrayBuffer[Int]() for (edge: StreetEdgeInfo <- segment.streetEdges.asScala) { if (!links.containsKey(Id.createLinkId(edge.edgeId.longValue()))) { @@ -908,9 +956,9 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo } private def buildStreetPath( - linksTimesDistances: LinksTimesDistances, - tripStartTime: Int - ): BeamPath = { + linksTimesDistances: LinksTimesDistances, + tripStartTime: Int + ): BeamPath = { val startLoc = beamServices.geo.coordOfR5Edge(transportNetwork.streetLayer, linksTimesDistances.linkIds.head) val endLoc = beamServices.geo.coordOfR5Edge(transportNetwork.streetLayer, linksTimesDistances.linkIds.last) BeamPath( @@ -934,8 +982,8 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo * @return a collection of FareSegments for an itinerary. */ private def getFareSegments( - segments: IndexedSeq[(TransitSegment, TransitJourneyID)] - ): IndexedSeq[BeamFareSegment] = { + segments: IndexedSeq[(TransitSegment, TransitJourneyID)] + ): IndexedSeq[BeamFareSegment] = { segments .groupBy(s => getRoute(s._1, s._2).agency_id) .flatMap(t => { @@ -970,10 +1018,10 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo } private def getFareSegments( - transitSegment: TransitSegment, - transitJourneyID: TransitJourneyID, - fromTime: ZonedDateTime - ): IndexedSeq[BeamFareSegment] = { + transitSegment: TransitSegment, + transitJourneyID: TransitJourneyID, + fromTime: ZonedDateTime + ): IndexedSeq[BeamFareSegment] = { val pattern = getPattern(transitSegment, transitJourneyID) val route = getRoute(pattern) val routeId = route.route_id @@ -994,12 +1042,12 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo } private def getFareSegments( - agencyId: String, - routeId: String, - fromId: String, - toId: String, - containsIds: Set[String] = null - ): IndexedSeq[BeamFareSegment] = + agencyId: String, + routeId: String, + fromId: String, + toId: String, + containsIds: Set[String] = null + ): IndexedSeq[BeamFareSegment] = fareCalculator.getFareSegments(agencyId, routeId, fromId, toId, containsIds) private def getRoute(transitSegment: TransitSegment, transitJourneyID: TransitJourneyID) = @@ -1019,15 +1067,16 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo private def travelTimeCalculator(startTime: Int): TravelTimeCalculator = maybeTravelTime match { case Some(travelTime) => - (edge: EdgeStore#Edge, durationSeconds: Int, streetMode: StreetMode, req: ProfileRequest) => { - if (streetMode != StreetMode.CAR || edge.getOSMID < 0) { - // An R5 internal edge, probably connecting transit to the street network. We don't have those in the - // MATSim network. - (edge.getLengthM / edge.calculateSpeed(req, streetMode)).toFloat - } else { - getTravelTime(startTime + durationSeconds, edge.getEdgeIndex, travelTime).toFloat + (edge: EdgeStore#Edge, durationSeconds: Int, streetMode: StreetMode, req: ProfileRequest) => + { + if (streetMode != StreetMode.CAR || edge.getOSMID < 0) { + // An R5 internal edge, probably connecting transit to the street network. We don't have those in the + // MATSim network. + (edge.getLengthM / edge.calculateSpeed(req, streetMode)).toFloat + } else { + getTravelTime(startTime + durationSeconds, edge.getEdgeIndex, travelTime).toFloat + } } - } case None => new EdgeStore.DefaultTravelTimeCalculator } @@ -1046,7 +1095,7 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo private def getTravelTime(time: Int, linkId: Int, travelTime: TravelTime): Double = { val link = linkIdMap(linkId) - val tt = travelTime.getLinkTravelTime(link, time,null,null) + val tt = travelTime.getLinkTravelTime(link, time, null, null) val travelSpeed = link.getLength / tt if (travelSpeed < beamServices.beamConfig.beam.physsim.quick_fix_minCarSpeedInMetersPerSecond) { link.getLength / beamServices.beamConfig.beam.physsim.quick_fix_minCarSpeedInMetersPerSecond @@ -1062,7 +1111,10 @@ class R5RoutingWorker(workerParams: WorkerParameters) extends Actor with ActorLo private def travelCostCalculator(timeValueOfMoney: Double, startTime: Int): TravelCostCalculator = (edge: EdgeStore#Edge, legDurationSeconds: Int, traversalTimeSeconds: Float) => { - traversalTimeSeconds + (timeValueOfMoney * tollCalculator.calcTollByLinkId(edge.getEdgeIndex, startTime + legDurationSeconds)).toFloat + traversalTimeSeconds + (timeValueOfMoney * tollCalculator.calcTollByLinkId( + edge.getEdgeIndex, + startTime + legDurationSeconds + )).toFloat } @@ -1257,10 +1309,10 @@ object R5RoutingWorker { val BUSHWHACKING_SPEED_IN_METERS_PER_SECOND = 0.447 // 1 mile per hour def props( - beamServices: BeamServices, - transportNetwork: TransportNetwork, - network: Network, - scenario: Scenario, + beamServices: BeamServices, + transportNetwork: TransportNetwork, + network: Network, + scenario: Scenario, fareCalculator: FareCalculator, tollCalculator: TollCalculator, transitVehicles: Vehicles @@ -1283,13 +1335,13 @@ object R5RoutingWorker { case class TripWithFares(trip: BeamTrip, legFares: Map[Int, Double]) case class R5Request( - from: Coord, - to: Coord, - time: WindowTime, - directMode: LegMode, - accessMode: LegMode, - transitModes: Seq[TransitModes], - egressMode: LegMode, + from: Coord, + to: Coord, + time: WindowTime, + directMode: LegMode, + accessMode: LegMode, + transitModes: Seq[TransitModes], + egressMode: LegMode, timeValueOfMoney: Double ) @@ -1300,26 +1352,33 @@ object R5RoutingWorker { } def createBushwackingBeamLeg( - atTime: Int, - duration: Int, - start: Location, - end: Location, - distance: Double - ): BeamLeg = { + atTime: Int, + duration: Int, + start: Location, + end: Location, + distance: Double + ): BeamLeg = { val path = BeamPath(Vector(), Vector(), None, SpaceTime(start, atTime), SpaceTime(end, atTime + duration), distance) BeamLeg(atTime, WALK, duration, path) } def createBushwackingTrip( - origin: Location, - dest: Location, - atTime: Int, - bodyId: Id[Vehicle], - beamServices: BeamServices - ): EmbodiedBeamTrip = { + origin: Location, + dest: Location, + atTime: Int, + bodyId: Id[Vehicle], + beamServices: BeamServices + ): EmbodiedBeamTrip = { EmbodiedBeamTrip( Vector( - EmbodiedBeamLeg(createBushwackingBeamLeg(atTime, origin, dest, beamServices), bodyId, asDriver = true, None, 0, unbecomeDriverOnCompletion = false) + EmbodiedBeamLeg( + createBushwackingBeamLeg(atTime, origin, dest, beamServices), + bodyId, + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = false + ) ) ) } diff --git a/src/main/scala/beam/scoring/BeamScoringFunctionFactory.scala b/src/main/scala/beam/scoring/BeamScoringFunctionFactory.scala index fbfea757250..785b19319b5 100755 --- a/src/main/scala/beam/scoring/BeamScoringFunctionFactory.scala +++ b/src/main/scala/beam/scoring/BeamScoringFunctionFactory.scala @@ -58,7 +58,7 @@ class BeamScoringFunctionFactory @Inject()(beamServices: BeamServices) extends S val scoreOfBeingInClassGivenThisOutcome = if (beamServices.beamConfig.beam.agentsim.agents.modalBehaviors.modeChoiceClass - .equals("ModeChoiceLCCM")) { + .equals("ModeChoiceLCCM")) { // Compute and log all-day score w.r.t. all modality styles // One of them has many suspicious-looking 0.0 values. Probably something which // should be minus infinity or exception instead. @@ -70,7 +70,8 @@ class BeamScoringFunctionFactory @Inject()(beamServices: BeamServices) extends S } .toMap .mapValues( - modeChoiceCalculatorForStyle => trips.map(trip => modeChoiceCalculatorForStyle.utilityOf(trip, attributes)).sum + modeChoiceCalculatorForStyle => + trips.map(trip => modeChoiceCalculatorForStyle.utilityOf(trip, attributes)).sum ) .toArray .toMap // to force computation DO NOT TOUCH IT, because here is call-by-name and it's lazy which will hold a lot of memory !!! :) @@ -83,10 +84,7 @@ class BeamScoringFunctionFactory @Inject()(beamServices: BeamServices) extends S val logsum = Option( math.log( - person - .getPlans - .asScala - .view + person.getPlans.asScala.view .map( plan => plan.getAttributes @@ -106,16 +104,16 @@ class BeamScoringFunctionFactory @Inject()(beamServices: BeamServices) extends S AlternativeAttributes( attributes.modalityStyle.get, Map( - "income" -> attributes.householdAttributes.householdIncome, + "income" -> attributes.householdAttributes.householdIncome, "householdSize" -> attributes.householdAttributes.householdSize.toDouble, "male" -> (if (attributes.isMale) { - 1.0 - } else { - 0.0 - }), - "numCars" -> attributes.householdAttributes.numCars.toDouble, + 1.0 + } else { + 0.0 + }), + "numCars" -> attributes.householdAttributes.numCars.toDouble, "numBikes" -> attributes.householdAttributes.numBikes.toDouble, - "surplus" -> logsum // not the logsum-thing (yet), but the conditional utility of this actual plan given the class + "surplus" -> logsum // not the logsum-thing (yet), but the conditional utility of this actual plan given the class ) ) ) diff --git a/src/main/scala/beam/sim/BeamGraphComparator.scala b/src/main/scala/beam/sim/BeamGraphComparator.scala index 6c5d468c0cf..d73d611d52f 100644 --- a/src/main/scala/beam/sim/BeamGraphComparator.scala +++ b/src/main/scala/beam/sim/BeamGraphComparator.scala @@ -23,7 +23,10 @@ object BeamGraphComparator { * @param iterationsCount Total number of iterations. * @return Graph html as scala elem */ - private def generateHtml(files : mutable.HashMap[(String,String), Map[String, Array[(String, File)]]],iterationsCount : Int): Elem = { + private def generateHtml( + files: mutable.HashMap[(String, String), Map[String, Array[(String, File)]]], + iterationsCount: Int + ): Elem = { val scriptToDisplayAllImages = """function displayAllGraphs(images){ var counter = 0; @@ -43,7 +46,8 @@ object BeamGraphComparator { * @param imageObjects A json object containing required details of the image file * @return */ - def displayAllGraphs(imageObjects: Array[JsObject]) = s"displayAllGraphs(${Json.stringify(Json.toJson(imageObjects))});" + def displayAllGraphs(imageObjects: Array[JsObject]) = + s"displayAllGraphs(${Json.stringify(Json.toJson(imageObjects))});" // Main menu for graph selection val graphMenu: Elem = // Generate holder blocks to display the selected images and their titles - val imageHolders: Seq[NodeBuffer] = for(i <- 0 to iterationsCount) yield { + val imageHolders: Seq[NodeBuffer] = for (i <- 0 to iterationsCount) yield { val holderId = "imageHolder" + i val imageName = "imageName" + i

@@ -122,15 +126,19 @@ object BeamGraphComparator { * @param firstIteration value of first iteration * @param lastIteration value of last iteration */ - def generateGraphComparisonHtmlPage(event: ControlerEvent,firstIteration: Int,lastIteration: Int): Unit = { + def generateGraphComparisonHtmlPage(event: ControlerEvent, firstIteration: Int, lastIteration: Int): Unit = { val existingIterations = (firstIteration to lastIteration).filter { i => FileUtils.getFile(new File(event.getServices.getControlerIO.getIterationPath(i))).listFiles() != null } // Yield all the png files (graph images) across all iterations - val files: Seq[Array[File]] = for(i <- existingIterations) yield { - (FileUtils.getFile(new File(event.getServices.getControlerIO.getIterationPath(i))).listFiles.filterNot(_ == null).filter(f => - f.isDirectory && f.getName.equalsIgnoreCase("tripHistogram")).flatMap(_.listFiles()) ++ - FileUtils.getFile(new File(event.getServices.getControlerIO.getIterationPath(i))).listFiles()) + val files: Seq[Array[File]] = for (i <- existingIterations) yield { + (FileUtils + .getFile(new File(event.getServices.getControlerIO.getIterationPath(i))) + .listFiles + .filterNot(_ == null) + .filter(f => f.isDirectory && f.getName.equalsIgnoreCase("tripHistogram")) + .flatMap(_.listFiles()) ++ + FileUtils.getFile(new File(event.getServices.getControlerIO.getIterationPath(i))).listFiles()) .filter(f => FilenameUtils.getExtension(f.getName).equalsIgnoreCase("png")) } val numberOfIterations = files.size @@ -138,40 +146,52 @@ object BeamGraphComparator { // Group all yielded files based on the graph names (file name w/o iteration prefixes) val fileNames = files.reduce(_ ++ _) map { f => (f.getName match { - case fileNameRegex(_,name,_) => name - case _ => "" + case fileNameRegex(_, name, _) => name + case _ => "" }) -> f } - val knownChartPrefixes = List("rideHail", "passengerPerTrip","legHistogram","averageTravelTimes","energyUse","modeChoice","physsim","realizedMode","tripHistogram","freeFlowSpeedDistribution") - val chartsGroupedByPrefix: Map[String, Map[String, Array[(String, File)]]] = fileNames.groupBy(_._1) groupBy(grouping => - knownChartPrefixes.collectFirst{ case prefix if grouping._1.startsWith(prefix) => prefix.capitalize } - .getOrElse("Misc")) - val subGroups = mutable.HashMap.empty[(String ,String), Map[String, Array[(String, File)]]] + val knownChartPrefixes = List( + "rideHail", + "passengerPerTrip", + "legHistogram", + "averageTravelTimes", + "energyUse", + "modeChoice", + "physsim", + "realizedMode", + "tripHistogram", + "freeFlowSpeedDistribution" + ) + val chartsGroupedByPrefix: Map[String, Map[String, Array[(String, File)]]] = fileNames.groupBy(_._1) groupBy ( + grouping => + knownChartPrefixes + .collectFirst { case prefix if grouping._1.startsWith(prefix) => prefix.capitalize } + .getOrElse("Misc") + ) + val subGroups = mutable.HashMap.empty[(String, String), Map[String, Array[(String, File)]]] // set priorities for the grouped chart files chartsGroupedByPrefix.foreach(gc => { - if (gc._2.size == 1){ + if (gc._2.size == 1) { val key = gc._2.headOption.map(_._1).getOrElse("") key match { - case "modeChoice" => subGroups.put("P01" -> key,gc._2) - case "energyUse" => subGroups.put("P02" -> key,gc._2) + case "modeChoice" => subGroups.put("P01" -> key, gc._2) + case "energyUse" => subGroups.put("P02" -> key, gc._2) case "realizedMode" => subGroups.put("P03" -> key, gc._2) - case "misc" => subGroups.put("P50" -> key, gc._2) + case "misc" => subGroups.put("P50" -> key, gc._2) case _ => - val map = subGroups.getOrElse("P04" -> key,Map.empty) - subGroups.put("P04" -> key,gc._2 ++ map ) + val map = subGroups.getOrElse("P04" -> key, Map.empty) + subGroups.put("P04" -> key, gc._2 ++ map) } - } - else - subGroups.put("P04"+gc._1.headOption.getOrElse("") -> gc._1,gc._2) + } else + subGroups.put("P04" + gc._1.headOption.getOrElse("") -> gc._1, gc._2) }) //Generate graph comparison html element and write it to the html page at desired location val bw = new BufferedWriter(new FileWriter(event.getServices.getControlerIO.getOutputPath + "/comparison.html")) - val htmlElem = this.generateHtml(subGroups,numberOfIterations) + val htmlElem = this.generateHtml(subGroups, numberOfIterations) try { bw.write(htmlElem.mkString) - } - catch { + } catch { case e: IOException => e.printStackTrace() } finally { diff --git a/src/main/scala/beam/sim/BeamHelper.scala b/src/main/scala/beam/sim/BeamHelper.scala index 8e7ac1b3eeb..679dd7cee4e 100755 --- a/src/main/scala/beam/sim/BeamHelper.scala +++ b/src/main/scala/beam/sim/BeamHelper.scala @@ -10,7 +10,7 @@ import beam.agentsim.events.handling.BeamEventsHandling import beam.analysis.plots.{GraphSurgePricing, RideHailRevenueAnalysis} import beam.replanning._ import beam.replanning.utilitybased.UtilityBasedModeChoice -import beam.router.r5.{FrequencyAdjustingNetworkCoordinator, DefaultNetworkCoordinator, NetworkCoordinator} +import beam.router.r5.{DefaultNetworkCoordinator, FrequencyAdjustingNetworkCoordinator, NetworkCoordinator} import beam.scoring.BeamScoringFunctionFactory import beam.sim.config.{BeamConfig, ConfigModule, MatSimBeamConfigBuilder} import beam.sim.metrics.Metrics._ @@ -299,7 +299,12 @@ trait BeamHelper extends LazyLogging { if (isMetricsEnable) Kamon.start(clusterConfig.withFallback(ConfigFactory.defaultReference())) import akka.actor.{ActorSystem, DeadLetter, PoisonPill, Props} - import akka.cluster.singleton.{ClusterSingletonManager, ClusterSingletonManagerSettings, ClusterSingletonProxy, ClusterSingletonProxySettings} + import akka.cluster.singleton.{ + ClusterSingletonManager, + ClusterSingletonManagerSettings, + ClusterSingletonProxy, + ClusterSingletonProxySettings + } import beam.router.ClusterWorkerRouter import beam.sim.monitoring.DeadLetterReplayer @@ -342,14 +347,12 @@ trait BeamHelper extends LazyLogging { scenario.setNetwork(networkCoordinator.network) val beamServices = injector.getInstance(classOf[BeamServices]) - samplePopulation(scenario,beamServices.beamConfig,scenario.getConfig,beamServices) + samplePopulation(scenario, beamServices.beamConfig, scenario.getConfig, beamServices) run(beamServices) (scenario.getConfig, outputDir) } - - def setupBeamWithConfig(config: TypesafeConfig): (MutableScenario, String, NetworkCoordinator) = { val beamConfig = BeamConfig(config) level = beamConfig.beam.metrics.level @@ -376,11 +379,12 @@ trait BeamHelper extends LazyLogging { val outConf = Paths.get(outputDirectory, "beam.conf") Files.write(outConf, config.root().render(ConfigRenderOptions.concise()).getBytes) logger.info("Config [{}] copied to {}.", beamConfig.beam.agentsim.simulationName, outConf) - val networkCoordinator: NetworkCoordinator = if(Files.exists(Paths.get(beamConfig.beam.agentsim.scenarios.frequencyAdjustmentFile))){ - FrequencyAdjustingNetworkCoordinator(beamConfig) - }else { - DefaultNetworkCoordinator(beamConfig) - } + val networkCoordinator: NetworkCoordinator = + if (Files.exists(Paths.get(beamConfig.beam.agentsim.scenarios.frequencyAdjustmentFile))) { + FrequencyAdjustingNetworkCoordinator(beamConfig) + } else { + DefaultNetworkCoordinator(beamConfig) + } networkCoordinator.init() val maxHour = TimeUnit.SECONDS.toHours(matsimConfig.travelTimeCalculator().getMaxTime).toInt @@ -389,7 +393,6 @@ trait BeamHelper extends LazyLogging { val scenario = ScenarioUtils.loadScenario(matsimConfig).asInstanceOf[MutableScenario] - // TODO ASIF // If ours is set we will use that and if in addition matsim is set too then give a warning so that we can remove that from config if (beamConfig.beam.agentsim.agents.population.beamPopulationFile != null && !beamConfig.beam.agentsim.agents.population.beamPopulationFile.isEmpty) { @@ -399,14 +402,16 @@ trait BeamHelper extends LazyLogging { scenario.setPopulation(population) if (beamConfig.matsim.modules.plans.inputPlansFile != null && !beamConfig.matsim.modules.plans.inputPlansFile.isEmpty) { - logger.warn("The config file has specified two plans file as input: beam.agentsim.agents.population.beamPopulationFile and matsim.modules.plans.inputPlansFile. The beamPopulationFile will be used, unset the beamPopulationFile if you would rather use the inputPlansFile, or unset the inputPlansFile to avoid this warning.") + logger.warn( + "The config file has specified two plans file as input: beam.agentsim.agents.population.beamPopulationFile and matsim.modules.plans.inputPlansFile. The beamPopulationFile will be used, unset the beamPopulationFile if you would rather use the inputPlansFile, or unset the inputPlansFile to avoid this warning." + ) } } (scenario, outputDirectory, networkCoordinator) } - def run(beamServices: BeamServices){ + def run(beamServices: BeamServices) { beamServices.controler.run() if (isMetricsEnable) Kamon.shutdown() } @@ -462,7 +467,7 @@ trait BeamHelper extends LazyLogging { val populationAdjustment = PopulationAdjustment.getPopulationAdjustment(beamServices) populationAdjustment.update(scenario) - }else { + } else { val populationAdjustment = PopulationAdjustment.getPopulationAdjustment(beamServices) populationAdjustment.update(scenario) beamServices.personHouseholds = scenario.getHouseholds.getHouseholds diff --git a/src/main/scala/beam/sim/BeamMobsim.scala b/src/main/scala/beam/sim/BeamMobsim.scala index a4f9d81f605..a6d099beffa 100755 --- a/src/main/scala/beam/sim/BeamMobsim.scala +++ b/src/main/scala/beam/sim/BeamMobsim.scala @@ -12,7 +12,11 @@ import akka.pattern.ask import akka.util.Timeout import beam.agentsim.agents.BeamAgent.Finish import beam.agentsim.agents.modalbehaviors.DrivesVehicle.BeamVehicleStateUpdate -import beam.agentsim.agents.ridehail.RideHailManager.{BufferedRideHailRequestsTimeout, NotifyIterationEnds, RideHailAllocationManagerTimeout} +import beam.agentsim.agents.ridehail.RideHailManager.{ + BufferedRideHailRequestsTimeout, + NotifyIterationEnds, + RideHailAllocationManagerTimeout +} import beam.agentsim.agents.ridehail.{RideHailAgent, RideHailManager, RideHailSurgePricingManager} import beam.agentsim.agents.vehicles.EnergyEconomyAttributes.Powertrain import beam.agentsim.agents.vehicles._ diff --git a/src/main/scala/beam/sim/BeamServices.scala b/src/main/scala/beam/sim/BeamServices.scala index 702cd2f8029..c607170901c 100755 --- a/src/main/scala/beam/sim/BeamServices.scala +++ b/src/main/scala/beam/sim/BeamServices.scala @@ -72,7 +72,8 @@ class BeamServicesImpl @Inject()(val injector: Injector) extends BeamServices { val geo: GeoUtils = injector.getInstance(classOf[GeoUtils]) - val travelTimeCalculatorConfigGroup: TravelTimeCalculatorConfigGroup = injector.getInstance(classOf[TravelTimeCalculatorConfigGroup]) + val travelTimeCalculatorConfigGroup: TravelTimeCalculatorConfigGroup = + injector.getInstance(classOf[TravelTimeCalculatorConfigGroup]) val dates: DateUtils = DateUtils( ZonedDateTime.parse(beamConfig.beam.routing.baseDate).toLocalDateTime, @@ -90,7 +91,6 @@ class BeamServicesImpl @Inject()(val injector: Injector) extends BeamServices { val fuelTypes: TrieMap[Id[FuelType], FuelType] = readFuelTypeFile(beamConfig.beam.agentsim.agents.vehicles.beamFuelTypesFile) - val vehicleTypes: TrieMap[Id[BeamVehicleType], BeamVehicleType] = maybeScaleTransit(readBeamVehicleTypeFile(beamConfig.beam.agentsim.agents.vehicles.beamVehicleTypesFile, fuelTypes)) @@ -116,12 +116,21 @@ class BeamServicesImpl @Inject()(val injector: Injector) extends BeamServices { // Note that this assumes standing room is only available on transit vehicles. Not sure of any counterexamples modulo // say, a yacht or personal bus, but I think this will be fine for now. - def maybeScaleTransit(vehicleTypes: TrieMap[Id[BeamVehicleType], BeamVehicleType]): TrieMap[Id[BeamVehicleType], BeamVehicleType] = { + def maybeScaleTransit( + vehicleTypes: TrieMap[Id[BeamVehicleType], BeamVehicleType] + ): TrieMap[Id[BeamVehicleType], BeamVehicleType] = { beamConfig.beam.agentsim.tuning.transitCapacity match { - case Some(scalingFactor) => vehicleTypes.map { case (id, bvt) => id -> (if(bvt.standingRoomCapacity > 0) - bvt.copy(seatingCapacity = - Math.ceil(bvt.seatingCapacity * scalingFactor), standingRoomCapacity = Math.ceil(bvt.standingRoomCapacity * scalingFactor)) else - bvt) } + case Some(scalingFactor) => + vehicleTypes.map { + case (id, bvt) => + id -> (if (bvt.standingRoomCapacity > 0) + bvt.copy( + seatingCapacity = Math.ceil(bvt.seatingCapacity * scalingFactor), + standingRoomCapacity = Math.ceil(bvt.standingRoomCapacity * scalingFactor) + ) + else + bvt) + } case None => vehicleTypes } } @@ -155,9 +164,9 @@ object BeamServices { } def readVehiclesFile( - filePath: String, - vehiclesTypeMap: TrieMap[Id[BeamVehicleType], BeamVehicleType] - ): TrieMap[Id[BeamVehicle], BeamVehicle] = { + filePath: String, + vehiclesTypeMap: TrieMap[Id[BeamVehicleType], BeamVehicleType] + ): TrieMap[Id[BeamVehicle], BeamVehicle] = { readCsvFileByLine(filePath, TrieMap[Id[BeamVehicle], BeamVehicle]()) { case (line, acc) => val vehicleIdString = line.get("vehicleId") @@ -187,18 +196,18 @@ object BeamServices { private def getFuelTypeId(fuelType: String): FuelTypeId = { fuelType match { - case "gasoline" => BeamVehicleType.Gasoline - case "diesel" => BeamVehicleType.Diesel + case "gasoline" => BeamVehicleType.Gasoline + case "diesel" => BeamVehicleType.Diesel case "electricity" => BeamVehicleType.Electricity - case "biodiesel" => BeamVehicleType.Biodiesel - case _ => throw new RuntimeException("Invalid fuel type id") + case "biodiesel" => BeamVehicleType.Biodiesel + case _ => throw new RuntimeException("Invalid fuel type id") } } def readBeamVehicleTypeFile( - filePath: String, - fuelTypeMap: TrieMap[Id[FuelType], FuelType] - ): TrieMap[Id[BeamVehicleType], BeamVehicleType] = { + filePath: String, + fuelTypeMap: TrieMap[Id[FuelType], FuelType] + ): TrieMap[Id[BeamVehicleType], BeamVehicleType] = { readCsvFileByLine(filePath, TrieMap[Id[BeamVehicleType], BeamVehicleType]()) { case (line, z) => val vIdString = line.get("vehicleTypeId") @@ -247,10 +256,10 @@ object BeamServices { private def getVehicleCategory(vehicleCategory: String): VehicleCategory = { vehicleCategory match { - case "car" => BeamVehicleType.Car - case "bike" => BeamVehicleType.Bike + case "car" => BeamVehicleType.Car + case "bike" => BeamVehicleType.Bike case "ridehail" => BeamVehicleType.RideHail - case _ => throw new RuntimeException("Invalid vehicleCategory") + case _ => throw new RuntimeException("Invalid vehicleCategory") } } diff --git a/src/main/scala/beam/sim/BeamSim.scala b/src/main/scala/beam/sim/BeamSim.scala index de134656286..17d749e7d4e 100755 --- a/src/main/scala/beam/sim/BeamSim.scala +++ b/src/main/scala/beam/sim/BeamSim.scala @@ -41,16 +41,16 @@ import scala.concurrent.duration.Duration import scala.concurrent.{Await, Future} class BeamSim @Inject()( - private val actorSystem: ActorSystem, - private val transportNetwork: TransportNetwork, - private val beamServices: BeamServices, - private val eventsManager: EventsManager, - private val scenario: Scenario, - ) extends StartupListener - with IterationEndsListener - with ShutdownListener - with LazyLogging - with MetricsSupport { + private val actorSystem: ActorSystem, + private val transportNetwork: TransportNetwork, + private val beamServices: BeamServices, + private val eventsManager: EventsManager, + private val scenario: Scenario, +) extends StartupListener + with IterationEndsListener + with ShutdownListener + with LazyLogging + with MetricsSupport { private var agentSimToPhysSimPlanConverter: AgentSimToPhysSimPlanConverter = _ private implicit val timeout: Timeout = Timeout(50000, TimeUnit.SECONDS) @@ -257,33 +257,46 @@ class BeamSim @Inject()( val filesToBeRenamed: Array[File] = event match { case _ if event.isInstanceOf[IterationEndsEvent] => val iterationEvent = event.asInstanceOf[IterationEndsEvent] - val outputIterationFileNameRegex = List(s"legHistogram(.*)","experienced(.*)") + val outputIterationFileNameRegex = List(s"legHistogram(.*)", "experienced(.*)") // filter files that match output file name regex and are to be renamed - FileUtils.getFile(new File(event.getServices.getControlerIO.getIterationPath(iterationEvent.getIteration))) + FileUtils + .getFile(new File(event.getServices.getControlerIO.getIterationPath(iterationEvent.getIteration))) .listFiles() - .filter(f => outputIterationFileNameRegex.exists(f.getName - .replace(event.getServices.getIterationNumber.toInt + ".","").matches(_))) + .filter( + f => + outputIterationFileNameRegex.exists( + f.getName + .replace(event.getServices.getIterationNumber.toInt + ".", "") + .matches(_) + ) + ) case _ if event.isInstanceOf[ShutdownEvent] => val shutdownEvent = event.asInstanceOf[ShutdownEvent] val outputFileNameRegex = List("output(.*)") // filter files that match output file name regex and are to be renamed - FileUtils.getFile(new File(shutdownEvent.getServices.getControlerIO.getOutputPath)) + FileUtils + .getFile(new File(shutdownEvent.getServices.getControlerIO.getOutputPath)) .listFiles() .filter(f => outputFileNameRegex.exists(f.getName.matches(_))) } filesToBeRenamed .foreach { file => //rename each file to follow the camel case - val newFile = FileUtils.getFile(file.getAbsolutePath.replace(file.getName,WordUtils - .uncapitalize(file.getName.split("_").map(_.capitalize).mkString("")))) + val newFile = FileUtils.getFile( + file.getAbsolutePath.replace( + file.getName, + WordUtils + .uncapitalize(file.getName.split("_").map(_.capitalize).mkString("")) + ) + ) logger.info(s"Renaming file - ${file.getName} to follow camel case notation : " + newFile.getAbsoluteFile) try { - if(file != newFile && !newFile.exists()) { + if (file != newFile && !newFile.exists()) { file.renameTo(newFile) } } catch { - case e : Exception => - logger.error(s"Error while renaming file - ${file.getName} to ${newFile.getName}",e) + case e: Exception => + logger.error(s"Error while renaming file - ${file.getName} to ${newFile.getName}", e) } } } diff --git a/src/main/scala/beam/sim/LoggingParallelEventsManager.scala b/src/main/scala/beam/sim/LoggingParallelEventsManager.scala index 831209acb13..01d33344ba0 100644 --- a/src/main/scala/beam/sim/LoggingParallelEventsManager.scala +++ b/src/main/scala/beam/sim/LoggingParallelEventsManager.scala @@ -99,5 +99,6 @@ class LoggingParallelEventsManager @Inject()(config: Config) extends EventsManag eventManager.processEvent(event) } val end = System.currentTimeMillis() - logger.info("Stopped dedicated handler(handleBlocking). Took {} ms to process after stop", end - start) } + logger.info("Stopped dedicated handler(handleBlocking). Took {} ms to process after stop", end - start) + } } diff --git a/src/main/scala/beam/sim/config/BeamConfig.scala b/src/main/scala/beam/sim/config/BeamConfig.scala index 6e0d2c8db34..7cdeadbf519 100755 --- a/src/main/scala/beam/sim/config/BeamConfig.scala +++ b/src/main/scala/beam/sim/config/BeamConfig.scala @@ -4,1106 +4,1581 @@ package beam.sim.config case class BeamConfig( - beam : BeamConfig.Beam, - matsim : BeamConfig.Matsim + beam: BeamConfig.Beam, + matsim: BeamConfig.Matsim ) + object BeamConfig { case class Beam( - agentsim : BeamConfig.Beam.Agentsim, - calibration : BeamConfig.Beam.Calibration, - cluster : BeamConfig.Beam.Cluster, - debug : BeamConfig.Beam.Debug, - inputDirectory : java.lang.String, - metrics : BeamConfig.Beam.Metrics, - outputs : BeamConfig.Beam.Outputs, - physsim : BeamConfig.Beam.Physsim, - routing : BeamConfig.Beam.Routing, - spatial : BeamConfig.Beam.Spatial, - useLocalWorker : scala.Boolean, - warmStart : BeamConfig.Beam.WarmStart + agentsim: BeamConfig.Beam.Agentsim, + calibration: BeamConfig.Beam.Calibration, + cluster: BeamConfig.Beam.Cluster, + debug: BeamConfig.Beam.Debug, + inputDirectory: java.lang.String, + metrics: BeamConfig.Beam.Metrics, + outputs: BeamConfig.Beam.Outputs, + physsim: BeamConfig.Beam.Physsim, + routing: BeamConfig.Beam.Routing, + spatial: BeamConfig.Beam.Spatial, + useLocalWorker: scala.Boolean, + warmStart: BeamConfig.Beam.WarmStart ) + object Beam { case class Agentsim( - agents : BeamConfig.Beam.Agentsim.Agents, - numAgents : scala.Int, - populationAdjustment : java.lang.String, - scenarios : BeamConfig.Beam.Agentsim.Scenarios, - schedulerParallelismWindow : scala.Int, - simulationName : java.lang.String, - taz : BeamConfig.Beam.Agentsim.Taz, - thresholdForMakingParkingChoiceInMeters : scala.Int, - thresholdForWalkingInMeters : scala.Int, - timeBinSize : scala.Int, - toll : BeamConfig.Beam.Agentsim.Toll, - tuning : BeamConfig.Beam.Agentsim.Tuning + agents: BeamConfig.Beam.Agentsim.Agents, + numAgents: scala.Int, + populationAdjustment: java.lang.String, + scenarios: BeamConfig.Beam.Agentsim.Scenarios, + schedulerParallelismWindow: scala.Int, + simulationName: java.lang.String, + taz: BeamConfig.Beam.Agentsim.Taz, + thresholdForMakingParkingChoiceInMeters: scala.Int, + thresholdForWalkingInMeters: scala.Int, + timeBinSize: scala.Int, + toll: BeamConfig.Beam.Agentsim.Toll, + tuning: BeamConfig.Beam.Agentsim.Tuning ) + object Agentsim { case class Agents( - drivingCost : BeamConfig.Beam.Agentsim.Agents.DrivingCost, - modalBehaviors : BeamConfig.Beam.Agentsim.Agents.ModalBehaviors, - modeSubsidy : BeamConfig.Beam.Agentsim.Agents.ModeSubsidy, - population : BeamConfig.Beam.Agentsim.Agents.Population, - rideHail : BeamConfig.Beam.Agentsim.Agents.RideHail, - vehicles : BeamConfig.Beam.Agentsim.Agents.Vehicles + drivingCost: BeamConfig.Beam.Agentsim.Agents.DrivingCost, + modalBehaviors: BeamConfig.Beam.Agentsim.Agents.ModalBehaviors, + modeSubsidy: BeamConfig.Beam.Agentsim.Agents.ModeSubsidy, + population: BeamConfig.Beam.Agentsim.Agents.Population, + rideHail: BeamConfig.Beam.Agentsim.Agents.RideHail, + vehicles: BeamConfig.Beam.Agentsim.Agents.Vehicles ) + object Agents { case class DrivingCost( - defaultLitersPerMeter : scala.Double, - defaultPricePerGallon : scala.Double + defaultLitersPerMeter: scala.Double, + defaultPricePerGallon: scala.Double ) + object DrivingCost { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.DrivingCost = { BeamConfig.Beam.Agentsim.Agents.DrivingCost( - defaultLitersPerMeter = if(c.hasPathOrNull("defaultLitersPerMeter")) c.getDouble("defaultLitersPerMeter") else 0.0001069, - defaultPricePerGallon = if(c.hasPathOrNull("defaultPricePerGallon")) c.getDouble("defaultPricePerGallon") else 3.115 + defaultLitersPerMeter = + if (c.hasPathOrNull("defaultLitersPerMeter")) c.getDouble("defaultLitersPerMeter") else 0.0001069, + defaultPricePerGallon = + if (c.hasPathOrNull("defaultPricePerGallon")) c.getDouble("defaultPricePerGallon") else 3.115 ) } } - + case class ModalBehaviors( - defaultValueOfTime : scala.Double, - lccm : BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.Lccm, - modeChoiceClass : java.lang.String, - mulitnomialLogit : BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit + defaultValueOfTime: scala.Double, + lccm: BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.Lccm, + modeChoiceClass: java.lang.String, + mulitnomialLogit: BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit ) + object ModalBehaviors { case class Lccm( - paramFile : java.lang.String + paramFile: java.lang.String ) + object Lccm { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.Lccm = { BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.Lccm( - paramFile = if(c.hasPathOrNull("paramFile")) c.getString("paramFile") else "/test/input/beamville/lccm-long.csv" + paramFile = + if (c.hasPathOrNull("paramFile")) c.getString("paramFile") else "/test/input/beamville/lccm-long.csv" ) } } - + case class MulitnomialLogit( - params : BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit.Params + params: BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit.Params ) + object MulitnomialLogit { case class Params( - bike_intercept : scala.Double, - car_intercept : scala.Double, - drive_transit_intercept : scala.Double, - ride_hail_intercept : scala.Double, - ride_hail_transit_intercept : scala.Double, - transfer : scala.Double, - walk_intercept : scala.Double, - walk_transit_intercept : scala.Double + bike_intercept: scala.Double, + car_intercept: scala.Double, + drive_transit_intercept: scala.Double, + ride_hail_intercept: scala.Double, + ride_hail_transit_intercept: scala.Double, + transfer: scala.Double, + walk_intercept: scala.Double, + walk_transit_intercept: scala.Double ) + object Params { - def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit.Params = { + + def apply( + c: com.typesafe.config.Config + ): BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit.Params = { BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit.Params( - bike_intercept = if(c.hasPathOrNull("bike_intercept")) c.getDouble("bike_intercept") else 0.0, - car_intercept = if(c.hasPathOrNull("car_intercept")) c.getDouble("car_intercept") else 0.0, - drive_transit_intercept = if(c.hasPathOrNull("drive_transit_intercept")) c.getDouble("drive_transit_intercept") else 0.0, - ride_hail_intercept = if(c.hasPathOrNull("ride_hail_intercept")) c.getDouble("ride_hail_intercept") else -2.0, - ride_hail_transit_intercept = if(c.hasPathOrNull("ride_hail_transit_intercept")) c.getDouble("ride_hail_transit_intercept") else 0.0, - transfer = if(c.hasPathOrNull("transfer")) c.getDouble("transfer") else -1.4, - walk_intercept = if(c.hasPathOrNull("walk_intercept")) c.getDouble("walk_intercept") else 0.0, - walk_transit_intercept = if(c.hasPathOrNull("walk_transit_intercept")) c.getDouble("walk_transit_intercept") else 0.0 + bike_intercept = if (c.hasPathOrNull("bike_intercept")) c.getDouble("bike_intercept") else 0.0, + car_intercept = if (c.hasPathOrNull("car_intercept")) c.getDouble("car_intercept") else 0.0, + drive_transit_intercept = + if (c.hasPathOrNull("drive_transit_intercept")) c.getDouble("drive_transit_intercept") else 0.0, + ride_hail_intercept = + if (c.hasPathOrNull("ride_hail_intercept")) c.getDouble("ride_hail_intercept") else -2.0, + ride_hail_transit_intercept = + if (c.hasPathOrNull("ride_hail_transit_intercept")) c.getDouble("ride_hail_transit_intercept") + else 0.0, + transfer = if (c.hasPathOrNull("transfer")) c.getDouble("transfer") else -1.4, + walk_intercept = if (c.hasPathOrNull("walk_intercept")) c.getDouble("walk_intercept") else 0.0, + walk_transit_intercept = + if (c.hasPathOrNull("walk_transit_intercept")) c.getDouble("walk_transit_intercept") else 0.0 ) } } - - def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit = { + + def apply( + c: com.typesafe.config.Config + ): BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit = { BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit( - params = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit.Params(if(c.hasPathOrNull("params")) c.getConfig("params") else com.typesafe.config.ConfigFactory.parseString("params{}")) + params = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit.Params( + if (c.hasPathOrNull("params")) c.getConfig("params") + else com.typesafe.config.ConfigFactory.parseString("params{}") + ) ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.ModalBehaviors = { BeamConfig.Beam.Agentsim.Agents.ModalBehaviors( - defaultValueOfTime = if(c.hasPathOrNull("defaultValueOfTime")) c.getDouble("defaultValueOfTime") else 8.0, - lccm = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.Lccm(if(c.hasPathOrNull("lccm")) c.getConfig("lccm") else com.typesafe.config.ConfigFactory.parseString("lccm{}")), - modeChoiceClass = if(c.hasPathOrNull("modeChoiceClass")) c.getString("modeChoiceClass") else "ModeChoiceMultinomialLogit", - mulitnomialLogit = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit(if(c.hasPathOrNull("mulitnomialLogit")) c.getConfig("mulitnomialLogit") else com.typesafe.config.ConfigFactory.parseString("mulitnomialLogit{}")) + defaultValueOfTime = + if (c.hasPathOrNull("defaultValueOfTime")) c.getDouble("defaultValueOfTime") else 8.0, + lccm = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.Lccm( + if (c.hasPathOrNull("lccm")) c.getConfig("lccm") + else com.typesafe.config.ConfigFactory.parseString("lccm{}") + ), + modeChoiceClass = + if (c.hasPathOrNull("modeChoiceClass")) c.getString("modeChoiceClass") + else "ModeChoiceMultinomialLogit", + mulitnomialLogit = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors.MulitnomialLogit( + if (c.hasPathOrNull("mulitnomialLogit")) c.getConfig("mulitnomialLogit") + else com.typesafe.config.ConfigFactory.parseString("mulitnomialLogit{}") + ) ) } } - + case class ModeSubsidy( - file : java.lang.String + file: java.lang.String ) + object ModeSubsidy { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.ModeSubsidy = { BeamConfig.Beam.Agentsim.Agents.ModeSubsidy( - file = if(c.hasPathOrNull("file")) c.getString("file") else "/test/input/beamville/subsidies.csv" + file = if (c.hasPathOrNull("file")) c.getString("file") else "/test/input/beamville/subsidies.csv" ) } } - + case class Population( - beamPopulationFile : java.lang.String + beamPopulationFile: java.lang.String ) + object Population { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.Population = { BeamConfig.Beam.Agentsim.Agents.Population( - beamPopulationFile = if(c.hasPathOrNull("beamPopulationFile")) c.getString("beamPopulationFile") else "" + beamPopulationFile = if (c.hasPathOrNull("beamPopulationFile")) c.getString("beamPopulationFile") else "" ) } } - + case class RideHail( - allocationManager : BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager, - defaultCostPerMile : scala.Double, - defaultCostPerMinute : scala.Double, - initialLocation : BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation, - iterationStats : BeamConfig.Beam.Agentsim.Agents.RideHail.IterationStats, - numDriversAsFractionOfPopulation : scala.Double, - refuelLocationType : java.lang.String, - refuelThresholdInMeters : scala.Double, - rideHailManager : BeamConfig.Beam.Agentsim.Agents.RideHail.RideHailManager, - surgePricing : BeamConfig.Beam.Agentsim.Agents.RideHail.SurgePricing, - vehicleTypeId : java.lang.String + allocationManager: BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager, + defaultCostPerMile: scala.Double, + defaultCostPerMinute: scala.Double, + initialLocation: BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation, + iterationStats: BeamConfig.Beam.Agentsim.Agents.RideHail.IterationStats, + numDriversAsFractionOfPopulation: scala.Double, + refuelLocationType: java.lang.String, + refuelThresholdInMeters: scala.Double, + rideHailManager: BeamConfig.Beam.Agentsim.Agents.RideHail.RideHailManager, + surgePricing: BeamConfig.Beam.Agentsim.Agents.RideHail.SurgePricing, + vehicleTypeId: java.lang.String ) + object RideHail { case class AllocationManager( - name : java.lang.String, - randomRepositioning : BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RandomRepositioning, - repositionLowWaitingTimes : BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RepositionLowWaitingTimes, - timeoutInSeconds : scala.Int + name: java.lang.String, + randomRepositioning: BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RandomRepositioning, + repositionLowWaitingTimes: BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RepositionLowWaitingTimes, + timeoutInSeconds: scala.Int ) + object AllocationManager { case class RandomRepositioning( - repositioningShare : scala.Double + repositioningShare: scala.Double ) + object RandomRepositioning { - def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RandomRepositioning = { + + def apply( + c: com.typesafe.config.Config + ): BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RandomRepositioning = { BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RandomRepositioning( - repositioningShare = if(c.hasPathOrNull("repositioningShare")) c.getDouble("repositioningShare") else 0.1 + repositioningShare = + if (c.hasPathOrNull("repositioningShare")) c.getDouble("repositioningShare") else 0.1 ) } } - + case class RepositionLowWaitingTimes( - allowIncreasingRadiusIfDemandInRadiusLow : scala.Boolean, - demandWeight : scala.Double, - distanceWeight : scala.Double, - keepMaxTopNScores : scala.Int, - minDemandPercentageInRadius : scala.Double, - minScoreThresholdForRepositioning : scala.Double, - minimumNumberOfIdlingVehiclesThresholdForRepositioning : scala.Int, - percentageOfVehiclesToReposition : scala.Double, - produceDebugImages : scala.Boolean, - repositionCircleRadiusInMeters : scala.Double, - repositioningMethod : java.lang.String, - timeWindowSizeInSecForDecidingAboutRepositioning : scala.Double, - waitingTimeWeight : scala.Double + allowIncreasingRadiusIfDemandInRadiusLow: scala.Boolean, + demandWeight: scala.Double, + distanceWeight: scala.Double, + keepMaxTopNScores: scala.Int, + minDemandPercentageInRadius: scala.Double, + minScoreThresholdForRepositioning: scala.Double, + minimumNumberOfIdlingVehiclesThresholdForRepositioning: scala.Int, + percentageOfVehiclesToReposition: scala.Double, + produceDebugImages: scala.Boolean, + repositionCircleRadiusInMeters: scala.Double, + repositioningMethod: java.lang.String, + timeWindowSizeInSecForDecidingAboutRepositioning: scala.Double, + waitingTimeWeight: scala.Double ) + object RepositionLowWaitingTimes { - def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RepositionLowWaitingTimes = { + + def apply( + c: com.typesafe.config.Config + ): BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RepositionLowWaitingTimes = { BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RepositionLowWaitingTimes( - allowIncreasingRadiusIfDemandInRadiusLow = !c.hasPathOrNull("allowIncreasingRadiusIfDemandInRadiusLow") || c.getBoolean("allowIncreasingRadiusIfDemandInRadiusLow"), - demandWeight = if(c.hasPathOrNull("demandWeight")) c.getDouble("demandWeight") else 4.0, - distanceWeight = if(c.hasPathOrNull("distanceWeight")) c.getDouble("distanceWeight") else 0.01, - keepMaxTopNScores = if(c.hasPathOrNull("keepMaxTopNScores")) c.getInt("keepMaxTopNScores") else 1, - minDemandPercentageInRadius = if(c.hasPathOrNull("minDemandPercentageInRadius")) c.getDouble("minDemandPercentageInRadius") else 0.1, - minScoreThresholdForRepositioning = if(c.hasPathOrNull("minScoreThresholdForRepositioning")) c.getDouble("minScoreThresholdForRepositioning") else 0.1, - minimumNumberOfIdlingVehiclesThresholdForRepositioning = if(c.hasPathOrNull("minimumNumberOfIdlingVehiclesThresholdForRepositioning")) c.getInt("minimumNumberOfIdlingVehiclesThresholdForRepositioning") else 1, - percentageOfVehiclesToReposition = if(c.hasPathOrNull("percentageOfVehiclesToReposition")) c.getDouble("percentageOfVehiclesToReposition") else 0.01, - produceDebugImages = !c.hasPathOrNull("produceDebugImages") || c.getBoolean("produceDebugImages"), - repositionCircleRadiusInMeters = if(c.hasPathOrNull("repositionCircleRadiusInMeters")) c.getDouble("repositionCircleRadiusInMeters") else 3000, - repositioningMethod = if(c.hasPathOrNull("repositioningMethod")) c.getString("repositioningMethod") else "TOP_SCORES", - timeWindowSizeInSecForDecidingAboutRepositioning = if(c.hasPathOrNull("timeWindowSizeInSecForDecidingAboutRepositioning")) c.getDouble("timeWindowSizeInSecForDecidingAboutRepositioning") else 1200, - waitingTimeWeight = if(c.hasPathOrNull("waitingTimeWeight")) c.getDouble("waitingTimeWeight") else 4.0 + allowIncreasingRadiusIfDemandInRadiusLow = !c.hasPathOrNull( + "allowIncreasingRadiusIfDemandInRadiusLow" + ) || c.getBoolean("allowIncreasingRadiusIfDemandInRadiusLow"), + demandWeight = if (c.hasPathOrNull("demandWeight")) c.getDouble("demandWeight") else 4.0, + distanceWeight = if (c.hasPathOrNull("distanceWeight")) c.getDouble("distanceWeight") else 0.01, + keepMaxTopNScores = if (c.hasPathOrNull("keepMaxTopNScores")) c.getInt("keepMaxTopNScores") else 1, + minDemandPercentageInRadius = + if (c.hasPathOrNull("minDemandPercentageInRadius")) c.getDouble("minDemandPercentageInRadius") + else 0.1, + minScoreThresholdForRepositioning = + if (c.hasPathOrNull("minScoreThresholdForRepositioning")) + c.getDouble("minScoreThresholdForRepositioning") + else 0.1, + minimumNumberOfIdlingVehiclesThresholdForRepositioning = + if (c.hasPathOrNull("minimumNumberOfIdlingVehiclesThresholdForRepositioning")) + c.getInt("minimumNumberOfIdlingVehiclesThresholdForRepositioning") + else 1, + percentageOfVehiclesToReposition = + if (c.hasPathOrNull("percentageOfVehiclesToReposition")) + c.getDouble("percentageOfVehiclesToReposition") + else 0.01, + produceDebugImages = !c.hasPathOrNull("produceDebugImages") || c.getBoolean("produceDebugImages"), + repositionCircleRadiusInMeters = + if (c.hasPathOrNull("repositionCircleRadiusInMeters")) c.getDouble("repositionCircleRadiusInMeters") + else 3000, + repositioningMethod = + if (c.hasPathOrNull("repositioningMethod")) c.getString("repositioningMethod") else "TOP_SCORES", + timeWindowSizeInSecForDecidingAboutRepositioning = + if (c.hasPathOrNull("timeWindowSizeInSecForDecidingAboutRepositioning")) + c.getDouble("timeWindowSizeInSecForDecidingAboutRepositioning") + else 1200, + waitingTimeWeight = + if (c.hasPathOrNull("waitingTimeWeight")) c.getDouble("waitingTimeWeight") else 4.0 ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager = { BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager( - name = if(c.hasPathOrNull("name")) c.getString("name") else "DEFAULT_MANAGER", - randomRepositioning = BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RandomRepositioning(if(c.hasPathOrNull("randomRepositioning")) c.getConfig("randomRepositioning") else com.typesafe.config.ConfigFactory.parseString("randomRepositioning{}")), - repositionLowWaitingTimes = BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RepositionLowWaitingTimes(if(c.hasPathOrNull("repositionLowWaitingTimes")) c.getConfig("repositionLowWaitingTimes") else com.typesafe.config.ConfigFactory.parseString("repositionLowWaitingTimes{}")), - timeoutInSeconds = if(c.hasPathOrNull("timeoutInSeconds")) c.getInt("timeoutInSeconds") else 120 + name = if (c.hasPathOrNull("name")) c.getString("name") else "DEFAULT_MANAGER", + randomRepositioning = BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RandomRepositioning( + if (c.hasPathOrNull("randomRepositioning")) c.getConfig("randomRepositioning") + else com.typesafe.config.ConfigFactory.parseString("randomRepositioning{}") + ), + repositionLowWaitingTimes = + BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager.RepositionLowWaitingTimes( + if (c.hasPathOrNull("repositionLowWaitingTimes")) c.getConfig("repositionLowWaitingTimes") + else com.typesafe.config.ConfigFactory.parseString("repositionLowWaitingTimes{}") + ), + timeoutInSeconds = if (c.hasPathOrNull("timeoutInSeconds")) c.getInt("timeoutInSeconds") else 120 ) } } - + case class InitialLocation( - home : BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation.Home, - name : java.lang.String + home: BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation.Home, + name: java.lang.String ) + object InitialLocation { case class Home( - radiusInMeters : scala.Double + radiusInMeters: scala.Double ) + object Home { - def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation.Home = { + + def apply( + c: com.typesafe.config.Config + ): BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation.Home = { BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation.Home( - radiusInMeters = if(c.hasPathOrNull("radiusInMeters")) c.getDouble("radiusInMeters") else 10000 + radiusInMeters = if (c.hasPathOrNull("radiusInMeters")) c.getDouble("radiusInMeters") else 10000 ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation = { BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation( - home = BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation.Home(if(c.hasPathOrNull("home")) c.getConfig("home") else com.typesafe.config.ConfigFactory.parseString("home{}")), - name = if(c.hasPathOrNull("name")) c.getString("name") else "HOME" + home = BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation.Home( + if (c.hasPathOrNull("home")) c.getConfig("home") + else com.typesafe.config.ConfigFactory.parseString("home{}") + ), + name = if (c.hasPathOrNull("name")) c.getString("name") else "HOME" ) } } - + case class IterationStats( - timeBinSizeInSec : scala.Double + timeBinSizeInSec: scala.Double ) + object IterationStats { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.IterationStats = { BeamConfig.Beam.Agentsim.Agents.RideHail.IterationStats( - timeBinSizeInSec = if(c.hasPathOrNull("timeBinSizeInSec")) c.getDouble("timeBinSizeInSec") else 3600.0 + timeBinSizeInSec = if (c.hasPathOrNull("timeBinSizeInSec")) c.getDouble("timeBinSizeInSec") else 3600.0 ) } } - + case class RideHailManager( - radiusInMeters : scala.Double + radiusInMeters: scala.Double ) + object RideHailManager { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.RideHailManager = { BeamConfig.Beam.Agentsim.Agents.RideHail.RideHailManager( - radiusInMeters = if(c.hasPathOrNull("radiusInMeters")) c.getDouble("radiusInMeters") else 5000 + radiusInMeters = if (c.hasPathOrNull("radiusInMeters")) c.getDouble("radiusInMeters") else 5000 ) } } - + case class SurgePricing( - minimumSurgeLevel : scala.Double, - numberOfCategories : scala.Int, - priceAdjustmentStrategy : java.lang.String, - surgeLevelAdaptionStep : scala.Double + minimumSurgeLevel: scala.Double, + numberOfCategories: scala.Int, + priceAdjustmentStrategy: java.lang.String, + surgeLevelAdaptionStep: scala.Double ) + object SurgePricing { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail.SurgePricing = { BeamConfig.Beam.Agentsim.Agents.RideHail.SurgePricing( - minimumSurgeLevel = if(c.hasPathOrNull("minimumSurgeLevel")) c.getDouble("minimumSurgeLevel") else 0.1, - numberOfCategories = if(c.hasPathOrNull("numberOfCategories")) c.getInt("numberOfCategories") else 6, - priceAdjustmentStrategy = if(c.hasPathOrNull("priceAdjustmentStrategy")) c.getString("priceAdjustmentStrategy") else "KEEP_PRICE_LEVEL_FIXED_AT_ONE", - surgeLevelAdaptionStep = if(c.hasPathOrNull("surgeLevelAdaptionStep")) c.getDouble("surgeLevelAdaptionStep") else 0.1 + minimumSurgeLevel = if (c.hasPathOrNull("minimumSurgeLevel")) c.getDouble("minimumSurgeLevel") else 0.1, + numberOfCategories = if (c.hasPathOrNull("numberOfCategories")) c.getInt("numberOfCategories") else 6, + priceAdjustmentStrategy = + if (c.hasPathOrNull("priceAdjustmentStrategy")) c.getString("priceAdjustmentStrategy") + else "KEEP_PRICE_LEVEL_FIXED_AT_ONE", + surgeLevelAdaptionStep = + if (c.hasPathOrNull("surgeLevelAdaptionStep")) c.getDouble("surgeLevelAdaptionStep") else 0.1 ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.RideHail = { BeamConfig.Beam.Agentsim.Agents.RideHail( - allocationManager = BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager(if(c.hasPathOrNull("allocationManager")) c.getConfig("allocationManager") else com.typesafe.config.ConfigFactory.parseString("allocationManager{}")), - defaultCostPerMile = if(c.hasPathOrNull("defaultCostPerMile")) c.getDouble("defaultCostPerMile") else 1.25, - defaultCostPerMinute = if(c.hasPathOrNull("defaultCostPerMinute")) c.getDouble("defaultCostPerMinute") else 0.75, - initialLocation = BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation(if(c.hasPathOrNull("initialLocation")) c.getConfig("initialLocation") else com.typesafe.config.ConfigFactory.parseString("initialLocation{}")), - iterationStats = BeamConfig.Beam.Agentsim.Agents.RideHail.IterationStats(if(c.hasPathOrNull("iterationStats")) c.getConfig("iterationStats") else com.typesafe.config.ConfigFactory.parseString("iterationStats{}")), - numDriversAsFractionOfPopulation = if(c.hasPathOrNull("numDriversAsFractionOfPopulation")) c.getDouble("numDriversAsFractionOfPopulation") else 0.5, - refuelLocationType = if(c.hasPathOrNull("refuelLocationType")) c.getString("refuelLocationType") else "AtTAZCenter", - refuelThresholdInMeters = if(c.hasPathOrNull("refuelThresholdInMeters")) c.getDouble("refuelThresholdInMeters") else 5000.0, - rideHailManager = BeamConfig.Beam.Agentsim.Agents.RideHail.RideHailManager(if(c.hasPathOrNull("rideHailManager")) c.getConfig("rideHailManager") else com.typesafe.config.ConfigFactory.parseString("rideHailManager{}")), - surgePricing = BeamConfig.Beam.Agentsim.Agents.RideHail.SurgePricing(if(c.hasPathOrNull("surgePricing")) c.getConfig("surgePricing") else com.typesafe.config.ConfigFactory.parseString("surgePricing{}")), - vehicleTypeId = if(c.hasPathOrNull("vehicleTypeId")) c.getString("vehicleTypeId") else "Car" + allocationManager = BeamConfig.Beam.Agentsim.Agents.RideHail.AllocationManager( + if (c.hasPathOrNull("allocationManager")) c.getConfig("allocationManager") + else com.typesafe.config.ConfigFactory.parseString("allocationManager{}") + ), + defaultCostPerMile = + if (c.hasPathOrNull("defaultCostPerMile")) c.getDouble("defaultCostPerMile") else 1.25, + defaultCostPerMinute = + if (c.hasPathOrNull("defaultCostPerMinute")) c.getDouble("defaultCostPerMinute") else 0.75, + initialLocation = BeamConfig.Beam.Agentsim.Agents.RideHail.InitialLocation( + if (c.hasPathOrNull("initialLocation")) c.getConfig("initialLocation") + else com.typesafe.config.ConfigFactory.parseString("initialLocation{}") + ), + iterationStats = BeamConfig.Beam.Agentsim.Agents.RideHail.IterationStats( + if (c.hasPathOrNull("iterationStats")) c.getConfig("iterationStats") + else com.typesafe.config.ConfigFactory.parseString("iterationStats{}") + ), + numDriversAsFractionOfPopulation = + if (c.hasPathOrNull("numDriversAsFractionOfPopulation")) c.getDouble("numDriversAsFractionOfPopulation") + else 0.5, + refuelLocationType = + if (c.hasPathOrNull("refuelLocationType")) c.getString("refuelLocationType") else "AtTAZCenter", + refuelThresholdInMeters = + if (c.hasPathOrNull("refuelThresholdInMeters")) c.getDouble("refuelThresholdInMeters") else 5000.0, + rideHailManager = BeamConfig.Beam.Agentsim.Agents.RideHail.RideHailManager( + if (c.hasPathOrNull("rideHailManager")) c.getConfig("rideHailManager") + else com.typesafe.config.ConfigFactory.parseString("rideHailManager{}") + ), + surgePricing = BeamConfig.Beam.Agentsim.Agents.RideHail.SurgePricing( + if (c.hasPathOrNull("surgePricing")) c.getConfig("surgePricing") + else com.typesafe.config.ConfigFactory.parseString("surgePricing{}") + ), + vehicleTypeId = if (c.hasPathOrNull("vehicleTypeId")) c.getString("vehicleTypeId") else "Car" ) } } - + case class Vehicles( - beamFuelTypesFile : java.lang.String, - beamVehicleTypesFile : java.lang.String, - beamVehiclesFile : java.lang.String, - bicycles : BeamConfig.Beam.Agentsim.Agents.Vehicles.Bicycles, - transitVehicleTypesByRouteFile : java.lang.String + beamFuelTypesFile: java.lang.String, + beamVehicleTypesFile: java.lang.String, + beamVehiclesFile: java.lang.String, + bicycles: BeamConfig.Beam.Agentsim.Agents.Vehicles.Bicycles, + transitVehicleTypesByRouteFile: java.lang.String ) + object Vehicles { case class Bicycles( - useBikes : scala.Boolean + useBikes: scala.Boolean ) + object Bicycles { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.Vehicles.Bicycles = { BeamConfig.Beam.Agentsim.Agents.Vehicles.Bicycles( useBikes = c.hasPathOrNull("useBikes") && c.getBoolean("useBikes") ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents.Vehicles = { BeamConfig.Beam.Agentsim.Agents.Vehicles( - beamFuelTypesFile = if(c.hasPathOrNull("beamFuelTypesFile")) c.getString("beamFuelTypesFile") else "/test/input/beamville/beamFuelTypes.csv", - beamVehicleTypesFile = if(c.hasPathOrNull("beamVehicleTypesFile")) c.getString("beamVehicleTypesFile") else "/test/input/beamville/vehicleTypes.csv", - beamVehiclesFile = if(c.hasPathOrNull("beamVehiclesFile")) c.getString("beamVehiclesFile") else "/test/input/beamville/vehicles.csv", - bicycles = BeamConfig.Beam.Agentsim.Agents.Vehicles.Bicycles(if(c.hasPathOrNull("bicycles")) c.getConfig("bicycles") else com.typesafe.config.ConfigFactory.parseString("bicycles{}")), - transitVehicleTypesByRouteFile = if(c.hasPathOrNull("transitVehicleTypesByRouteFile")) c.getString("transitVehicleTypesByRouteFile") else "" + beamFuelTypesFile = + if (c.hasPathOrNull("beamFuelTypesFile")) c.getString("beamFuelTypesFile") + else "/test/input/beamville/beamFuelTypes.csv", + beamVehicleTypesFile = + if (c.hasPathOrNull("beamVehicleTypesFile")) c.getString("beamVehicleTypesFile") + else "/test/input/beamville/vehicleTypes.csv", + beamVehiclesFile = + if (c.hasPathOrNull("beamVehiclesFile")) c.getString("beamVehiclesFile") + else "/test/input/beamville/vehicles.csv", + bicycles = BeamConfig.Beam.Agentsim.Agents.Vehicles.Bicycles( + if (c.hasPathOrNull("bicycles")) c.getConfig("bicycles") + else com.typesafe.config.ConfigFactory.parseString("bicycles{}") + ), + transitVehicleTypesByRouteFile = + if (c.hasPathOrNull("transitVehicleTypesByRouteFile")) c.getString("transitVehicleTypesByRouteFile") + else "" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Agents = { BeamConfig.Beam.Agentsim.Agents( - drivingCost = BeamConfig.Beam.Agentsim.Agents.DrivingCost(if(c.hasPathOrNull("drivingCost")) c.getConfig("drivingCost") else com.typesafe.config.ConfigFactory.parseString("drivingCost{}")), - modalBehaviors = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors(if(c.hasPathOrNull("modalBehaviors")) c.getConfig("modalBehaviors") else com.typesafe.config.ConfigFactory.parseString("modalBehaviors{}")), - modeSubsidy = BeamConfig.Beam.Agentsim.Agents.ModeSubsidy(if(c.hasPathOrNull("modeSubsidy")) c.getConfig("modeSubsidy") else com.typesafe.config.ConfigFactory.parseString("modeSubsidy{}")), - population = BeamConfig.Beam.Agentsim.Agents.Population(if(c.hasPathOrNull("population")) c.getConfig("population") else com.typesafe.config.ConfigFactory.parseString("population{}")), - rideHail = BeamConfig.Beam.Agentsim.Agents.RideHail(if(c.hasPathOrNull("rideHail")) c.getConfig("rideHail") else com.typesafe.config.ConfigFactory.parseString("rideHail{}")), - vehicles = BeamConfig.Beam.Agentsim.Agents.Vehicles(if(c.hasPathOrNull("vehicles")) c.getConfig("vehicles") else com.typesafe.config.ConfigFactory.parseString("vehicles{}")) + drivingCost = BeamConfig.Beam.Agentsim.Agents.DrivingCost( + if (c.hasPathOrNull("drivingCost")) c.getConfig("drivingCost") + else com.typesafe.config.ConfigFactory.parseString("drivingCost{}") + ), + modalBehaviors = BeamConfig.Beam.Agentsim.Agents.ModalBehaviors( + if (c.hasPathOrNull("modalBehaviors")) c.getConfig("modalBehaviors") + else com.typesafe.config.ConfigFactory.parseString("modalBehaviors{}") + ), + modeSubsidy = BeamConfig.Beam.Agentsim.Agents.ModeSubsidy( + if (c.hasPathOrNull("modeSubsidy")) c.getConfig("modeSubsidy") + else com.typesafe.config.ConfigFactory.parseString("modeSubsidy{}") + ), + population = BeamConfig.Beam.Agentsim.Agents.Population( + if (c.hasPathOrNull("population")) c.getConfig("population") + else com.typesafe.config.ConfigFactory.parseString("population{}") + ), + rideHail = BeamConfig.Beam.Agentsim.Agents.RideHail( + if (c.hasPathOrNull("rideHail")) c.getConfig("rideHail") + else com.typesafe.config.ConfigFactory.parseString("rideHail{}") + ), + vehicles = BeamConfig.Beam.Agentsim.Agents.Vehicles( + if (c.hasPathOrNull("vehicles")) c.getConfig("vehicles") + else com.typesafe.config.ConfigFactory.parseString("vehicles{}") + ) ) } } - + case class Scenarios( - frequencyAdjustmentFile : java.lang.String + frequencyAdjustmentFile: java.lang.String ) + object Scenarios { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Scenarios = { BeamConfig.Beam.Agentsim.Scenarios( - frequencyAdjustmentFile = if(c.hasPathOrNull("frequencyAdjustmentFile")) c.getString("frequencyAdjustmentFile") else "/test/input/beamville/r5/FrequencyAdjustment.csv" + frequencyAdjustmentFile = + if (c.hasPathOrNull("frequencyAdjustmentFile")) c.getString("frequencyAdjustmentFile") + else "/test/input/beamville/r5/FrequencyAdjustment.csv" ) } } - + case class Taz( - file : java.lang.String, - parking : java.lang.String + file: java.lang.String, + parking: java.lang.String ) + object Taz { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Taz = { BeamConfig.Beam.Agentsim.Taz( - file = if(c.hasPathOrNull("file")) c.getString("file") else "/test/input/beamville/taz-centers.csv", - parking = if(c.hasPathOrNull("parking")) c.getString("parking") else "/test/input/beamville/taz-parking.csv" + file = if (c.hasPathOrNull("file")) c.getString("file") else "/test/input/beamville/taz-centers.csv", + parking = + if (c.hasPathOrNull("parking")) c.getString("parking") else "/test/input/beamville/taz-parking.csv" ) } } - + case class Toll( - file : java.lang.String + file: java.lang.String ) + object Toll { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Toll = { BeamConfig.Beam.Agentsim.Toll( - file = if(c.hasPathOrNull("file")) c.getString("file") else "/test/input/beamville/toll-prices.csv" + file = if (c.hasPathOrNull("file")) c.getString("file") else "/test/input/beamville/toll-prices.csv" ) } } - + case class Tuning( - fuelCapacityInJoules : scala.Double, - rideHailPrice : scala.Double, - tollPrice : scala.Double, - transitCapacity : scala.Option[scala.Double], - transitPrice : scala.Double + fuelCapacityInJoules: scala.Double, + rideHailPrice: scala.Double, + tollPrice: scala.Double, + transitCapacity: scala.Option[scala.Double], + transitPrice: scala.Double ) + object Tuning { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim.Tuning = { BeamConfig.Beam.Agentsim.Tuning( - fuelCapacityInJoules = if(c.hasPathOrNull("fuelCapacityInJoules")) c.getDouble("fuelCapacityInJoules") else 86400000, - rideHailPrice = if(c.hasPathOrNull("rideHailPrice")) c.getDouble("rideHailPrice") else 1.0, - tollPrice = if(c.hasPathOrNull("tollPrice")) c.getDouble("tollPrice") else 1.0, - transitCapacity = if(c.hasPathOrNull("transitCapacity")) Some(c.getDouble("transitCapacity")) else None, - transitPrice = if(c.hasPathOrNull("transitPrice")) c.getDouble("transitPrice") else 1.0 + fuelCapacityInJoules = + if (c.hasPathOrNull("fuelCapacityInJoules")) c.getDouble("fuelCapacityInJoules") else 86400000, + rideHailPrice = if (c.hasPathOrNull("rideHailPrice")) c.getDouble("rideHailPrice") else 1.0, + tollPrice = if (c.hasPathOrNull("tollPrice")) c.getDouble("tollPrice") else 1.0, + transitCapacity = if (c.hasPathOrNull("transitCapacity")) Some(c.getDouble("transitCapacity")) else None, + transitPrice = if (c.hasPathOrNull("transitPrice")) c.getDouble("transitPrice") else 1.0 ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Agentsim = { BeamConfig.Beam.Agentsim( - agents = BeamConfig.Beam.Agentsim.Agents(if(c.hasPathOrNull("agents")) c.getConfig("agents") else com.typesafe.config.ConfigFactory.parseString("agents{}")), - numAgents = if(c.hasPathOrNull("numAgents")) c.getInt("numAgents") else 100, - populationAdjustment = if(c.hasPathOrNull("populationAdjustment")) c.getString("populationAdjustment") else "DEFAULT_ADJUSTMENT", - scenarios = BeamConfig.Beam.Agentsim.Scenarios(if(c.hasPathOrNull("scenarios")) c.getConfig("scenarios") else com.typesafe.config.ConfigFactory.parseString("scenarios{}")), - schedulerParallelismWindow = if(c.hasPathOrNull("schedulerParallelismWindow")) c.getInt("schedulerParallelismWindow") else 30, - simulationName = if(c.hasPathOrNull("simulationName")) c.getString("simulationName") else "beamville", - taz = BeamConfig.Beam.Agentsim.Taz(if(c.hasPathOrNull("taz")) c.getConfig("taz") else com.typesafe.config.ConfigFactory.parseString("taz{}")), - thresholdForMakingParkingChoiceInMeters = if(c.hasPathOrNull("thresholdForMakingParkingChoiceInMeters")) c.getInt("thresholdForMakingParkingChoiceInMeters") else 100, - thresholdForWalkingInMeters = if(c.hasPathOrNull("thresholdForWalkingInMeters")) c.getInt("thresholdForWalkingInMeters") else 100, - timeBinSize = if(c.hasPathOrNull("timeBinSize")) c.getInt("timeBinSize") else 3600, - toll = BeamConfig.Beam.Agentsim.Toll(if(c.hasPathOrNull("toll")) c.getConfig("toll") else com.typesafe.config.ConfigFactory.parseString("toll{}")), - tuning = BeamConfig.Beam.Agentsim.Tuning(if(c.hasPathOrNull("tuning")) c.getConfig("tuning") else com.typesafe.config.ConfigFactory.parseString("tuning{}")) + agents = BeamConfig.Beam.Agentsim.Agents( + if (c.hasPathOrNull("agents")) c.getConfig("agents") + else com.typesafe.config.ConfigFactory.parseString("agents{}") + ), + numAgents = if (c.hasPathOrNull("numAgents")) c.getInt("numAgents") else 100, + populationAdjustment = + if (c.hasPathOrNull("populationAdjustment")) c.getString("populationAdjustment") else "DEFAULT_ADJUSTMENT", + scenarios = BeamConfig.Beam.Agentsim.Scenarios( + if (c.hasPathOrNull("scenarios")) c.getConfig("scenarios") + else com.typesafe.config.ConfigFactory.parseString("scenarios{}") + ), + schedulerParallelismWindow = + if (c.hasPathOrNull("schedulerParallelismWindow")) c.getInt("schedulerParallelismWindow") else 30, + simulationName = if (c.hasPathOrNull("simulationName")) c.getString("simulationName") else "beamville", + taz = BeamConfig.Beam.Agentsim.Taz( + if (c.hasPathOrNull("taz")) c.getConfig("taz") else com.typesafe.config.ConfigFactory.parseString("taz{}") + ), + thresholdForMakingParkingChoiceInMeters = + if (c.hasPathOrNull("thresholdForMakingParkingChoiceInMeters")) + c.getInt("thresholdForMakingParkingChoiceInMeters") + else 100, + thresholdForWalkingInMeters = + if (c.hasPathOrNull("thresholdForWalkingInMeters")) c.getInt("thresholdForWalkingInMeters") else 100, + timeBinSize = if (c.hasPathOrNull("timeBinSize")) c.getInt("timeBinSize") else 3600, + toll = BeamConfig.Beam.Agentsim.Toll( + if (c.hasPathOrNull("toll")) c.getConfig("toll") + else com.typesafe.config.ConfigFactory.parseString("toll{}") + ), + tuning = BeamConfig.Beam.Agentsim.Tuning( + if (c.hasPathOrNull("tuning")) c.getConfig("tuning") + else com.typesafe.config.ConfigFactory.parseString("tuning{}") + ) ) } } - + case class Calibration( - meanToCountsWeightRatio : scala.Double, - mode : BeamConfig.Beam.Calibration.Mode, - objectiveFunction : java.lang.String + meanToCountsWeightRatio: scala.Double, + mode: BeamConfig.Beam.Calibration.Mode, + objectiveFunction: java.lang.String ) + object Calibration { case class Mode( - benchmarkFileLoc : java.lang.String + benchmarkFileLoc: java.lang.String ) + object Mode { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Calibration.Mode = { BeamConfig.Beam.Calibration.Mode( - benchmarkFileLoc = if(c.hasPathOrNull("benchmarkFileLoc")) c.getString("benchmarkFileLoc") else "" + benchmarkFileLoc = if (c.hasPathOrNull("benchmarkFileLoc")) c.getString("benchmarkFileLoc") else "" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Calibration = { BeamConfig.Beam.Calibration( - meanToCountsWeightRatio = if(c.hasPathOrNull("meanToCountsWeightRatio")) c.getDouble("meanToCountsWeightRatio") else 0.5, - mode = BeamConfig.Beam.Calibration.Mode(if(c.hasPathOrNull("mode")) c.getConfig("mode") else com.typesafe.config.ConfigFactory.parseString("mode{}")), - objectiveFunction = if(c.hasPathOrNull("objectiveFunction")) c.getString("objectiveFunction") else "ModeChoiceObjectiveFunction" + meanToCountsWeightRatio = + if (c.hasPathOrNull("meanToCountsWeightRatio")) c.getDouble("meanToCountsWeightRatio") else 0.5, + mode = BeamConfig.Beam.Calibration.Mode( + if (c.hasPathOrNull("mode")) c.getConfig("mode") + else com.typesafe.config.ConfigFactory.parseString("mode{}") + ), + objectiveFunction = + if (c.hasPathOrNull("objectiveFunction")) c.getString("objectiveFunction") + else "ModeChoiceObjectiveFunction" ) } } - + case class Cluster( - clusterType : scala.Option[java.lang.String], - enabled : scala.Boolean + clusterType: scala.Option[java.lang.String], + enabled: scala.Boolean ) + object Cluster { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Cluster = { BeamConfig.Beam.Cluster( - clusterType = if(c.hasPathOrNull("clusterType")) Some(c.getString("clusterType")) else None, - enabled = c.hasPathOrNull("enabled") && c.getBoolean("enabled") + clusterType = if (c.hasPathOrNull("clusterType")) Some(c.getString("clusterType")) else None, + enabled = c.hasPathOrNull("enabled") && c.getBoolean("enabled") ) } } - + case class Debug( - actor : BeamConfig.Beam.Debug.Actor, - clearRoutedOutstandingWorkEnabled : scala.Boolean, - debugActorTimerIntervalInSec : scala.Int, - debugEnabled : scala.Boolean, - memoryConsumptionDisplayTimeoutInSec : scala.Int, - secondsToWaitToClearRoutedOutstandingWork : scala.Int, - stuckAgentDetection : BeamConfig.Beam.Debug.StuckAgentDetection + actor: BeamConfig.Beam.Debug.Actor, + clearRoutedOutstandingWorkEnabled: scala.Boolean, + debugActorTimerIntervalInSec: scala.Int, + debugEnabled: scala.Boolean, + memoryConsumptionDisplayTimeoutInSec: scala.Int, + secondsToWaitToClearRoutedOutstandingWork: scala.Int, + stuckAgentDetection: BeamConfig.Beam.Debug.StuckAgentDetection ) + object Debug { case class Actor( - logDepth : scala.Int + logDepth: scala.Int ) + object Actor { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Debug.Actor = { BeamConfig.Beam.Debug.Actor( - logDepth = if(c.hasPathOrNull("logDepth")) c.getInt("logDepth") else 0 + logDepth = if (c.hasPathOrNull("logDepth")) c.getInt("logDepth") else 0 ) } } - + case class StuckAgentDetection( - checkIntervalMs : scala.Long, - checkMaxNumberOfMessagesEnabled : scala.Boolean, - defaultTimeoutMs : scala.Long, - enabled : scala.Boolean, - overallSimulationTimeoutMs : scala.Long, - thresholds : scala.List[BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm] + checkIntervalMs: scala.Long, + checkMaxNumberOfMessagesEnabled: scala.Boolean, + defaultTimeoutMs: scala.Long, + enabled: scala.Boolean, + overallSimulationTimeoutMs: scala.Long, + thresholds: scala.List[BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm] ) + object StuckAgentDetection { case class Thresholds$Elm( - actorTypeToMaxNumberOfMessages : BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages, - markAsStuckAfterMs : scala.Long, - triggerType : java.lang.String + actorTypeToMaxNumberOfMessages: BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages, + markAsStuckAfterMs: scala.Long, + triggerType: java.lang.String ) + object Thresholds$Elm { case class ActorTypeToMaxNumberOfMessages( - population : scala.Option[scala.Int], - rideHailAgent : scala.Option[scala.Int], - rideHailManager : scala.Option[scala.Int], - transitDriverAgent : scala.Option[scala.Int] + population: scala.Option[scala.Int], + rideHailAgent: scala.Option[scala.Int], + rideHailManager: scala.Option[scala.Int], + transitDriverAgent: scala.Option[scala.Int] ) + object ActorTypeToMaxNumberOfMessages { - def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages = { + + def apply( + c: com.typesafe.config.Config + ): BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages = { BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages( - population = if(c.hasPathOrNull("population")) Some(c.getInt("population")) else None, - rideHailAgent = if(c.hasPathOrNull("rideHailAgent")) Some(c.getInt("rideHailAgent")) else None, - rideHailManager = if(c.hasPathOrNull("rideHailManager")) Some(c.getInt("rideHailManager")) else None, - transitDriverAgent = if(c.hasPathOrNull("transitDriverAgent")) Some(c.getInt("transitDriverAgent")) else None + population = if (c.hasPathOrNull("population")) Some(c.getInt("population")) else None, + rideHailAgent = if (c.hasPathOrNull("rideHailAgent")) Some(c.getInt("rideHailAgent")) else None, + rideHailManager = if (c.hasPathOrNull("rideHailManager")) Some(c.getInt("rideHailManager")) else None, + transitDriverAgent = + if (c.hasPathOrNull("transitDriverAgent")) Some(c.getInt("transitDriverAgent")) else None ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm = { BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm( - actorTypeToMaxNumberOfMessages = BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages(if(c.hasPathOrNull("actorTypeToMaxNumberOfMessages")) c.getConfig("actorTypeToMaxNumberOfMessages") else com.typesafe.config.ConfigFactory.parseString("actorTypeToMaxNumberOfMessages{}")), - markAsStuckAfterMs = if(c.hasPathOrNull("markAsStuckAfterMs")) c.getDuration("markAsStuckAfterMs", java.util.concurrent.TimeUnit.MILLISECONDS) else 20000, - triggerType = if(c.hasPathOrNull("triggerType")) c.getString("triggerType") else "beam.agentsim.agents.PersonAgent$ActivityStartTrigger" + actorTypeToMaxNumberOfMessages = + BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages( + if (c.hasPathOrNull("actorTypeToMaxNumberOfMessages")) c.getConfig("actorTypeToMaxNumberOfMessages") + else com.typesafe.config.ConfigFactory.parseString("actorTypeToMaxNumberOfMessages{}") + ), + markAsStuckAfterMs = + if (c.hasPathOrNull("markAsStuckAfterMs")) + c.getDuration("markAsStuckAfterMs", java.util.concurrent.TimeUnit.MILLISECONDS) + else 20000, + triggerType = + if (c.hasPathOrNull("triggerType")) c.getString("triggerType") + else "beam.agentsim.agents.PersonAgent$ActivityStartTrigger" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Debug.StuckAgentDetection = { BeamConfig.Beam.Debug.StuckAgentDetection( - checkIntervalMs = if(c.hasPathOrNull("checkIntervalMs")) c.getDuration("checkIntervalMs", java.util.concurrent.TimeUnit.MILLISECONDS) else 200, - checkMaxNumberOfMessagesEnabled = c.hasPathOrNull("checkMaxNumberOfMessagesEnabled") && c.getBoolean("checkMaxNumberOfMessagesEnabled"), - defaultTimeoutMs = if(c.hasPathOrNull("defaultTimeoutMs")) c.getDuration("defaultTimeoutMs", java.util.concurrent.TimeUnit.MILLISECONDS) else 60000, - enabled = c.hasPathOrNull("enabled") && c.getBoolean("enabled"), - overallSimulationTimeoutMs = if(c.hasPathOrNull("overallSimulationTimeoutMs")) c.getDuration("overallSimulationTimeoutMs", java.util.concurrent.TimeUnit.MILLISECONDS) else 100000, - thresholds = $_LBeamConfig_Beam_Debug_StuckAgentDetection_Thresholds$Elm(c.getList("thresholds")) + checkIntervalMs = + if (c.hasPathOrNull("checkIntervalMs")) + c.getDuration("checkIntervalMs", java.util.concurrent.TimeUnit.MILLISECONDS) + else 200, + checkMaxNumberOfMessagesEnabled = c.hasPathOrNull("checkMaxNumberOfMessagesEnabled") && c.getBoolean( + "checkMaxNumberOfMessagesEnabled" + ), + defaultTimeoutMs = + if (c.hasPathOrNull("defaultTimeoutMs")) + c.getDuration("defaultTimeoutMs", java.util.concurrent.TimeUnit.MILLISECONDS) + else 60000, + enabled = c.hasPathOrNull("enabled") && c.getBoolean("enabled"), + overallSimulationTimeoutMs = + if (c.hasPathOrNull("overallSimulationTimeoutMs")) + c.getDuration("overallSimulationTimeoutMs", java.util.concurrent.TimeUnit.MILLISECONDS) + else 100000, + thresholds = $_LBeamConfig_Beam_Debug_StuckAgentDetection_Thresholds$Elm(c.getList("thresholds")) ) } - private def $_LBeamConfig_Beam_Debug_StuckAgentDetection_Thresholds$Elm(cl:com.typesafe.config.ConfigList): scala.List[BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm] = { + private def $_LBeamConfig_Beam_Debug_StuckAgentDetection_Thresholds$Elm( + cl: com.typesafe.config.ConfigList + ): scala.List[BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm] = { import scala.collection.JavaConverters._ - cl.asScala.map(cv => BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm(cv.asInstanceOf[com.typesafe.config.ConfigObject].toConfig)).toList + cl.asScala + .map( + cv => + BeamConfig.Beam.Debug.StuckAgentDetection + .Thresholds$Elm(cv.asInstanceOf[com.typesafe.config.ConfigObject].toConfig) + ) + .toList } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Debug = { BeamConfig.Beam.Debug( - actor = BeamConfig.Beam.Debug.Actor(if(c.hasPathOrNull("actor")) c.getConfig("actor") else com.typesafe.config.ConfigFactory.parseString("actor{}")), - clearRoutedOutstandingWorkEnabled = c.hasPathOrNull("clearRoutedOutstandingWorkEnabled") && c.getBoolean("clearRoutedOutstandingWorkEnabled"), - debugActorTimerIntervalInSec = if(c.hasPathOrNull("debugActorTimerIntervalInSec")) c.getInt("debugActorTimerIntervalInSec") else 0, - debugEnabled = c.hasPathOrNull("debugEnabled") && c.getBoolean("debugEnabled"), - memoryConsumptionDisplayTimeoutInSec = if(c.hasPathOrNull("memoryConsumptionDisplayTimeoutInSec")) c.getInt("memoryConsumptionDisplayTimeoutInSec") else 0, - secondsToWaitToClearRoutedOutstandingWork = if(c.hasPathOrNull("secondsToWaitToClearRoutedOutstandingWork")) c.getInt("secondsToWaitToClearRoutedOutstandingWork") else 60, - stuckAgentDetection = BeamConfig.Beam.Debug.StuckAgentDetection(if(c.hasPathOrNull("stuckAgentDetection")) c.getConfig("stuckAgentDetection") else com.typesafe.config.ConfigFactory.parseString("stuckAgentDetection{}")) + actor = BeamConfig.Beam.Debug.Actor( + if (c.hasPathOrNull("actor")) c.getConfig("actor") + else com.typesafe.config.ConfigFactory.parseString("actor{}") + ), + clearRoutedOutstandingWorkEnabled = c.hasPathOrNull("clearRoutedOutstandingWorkEnabled") && c.getBoolean( + "clearRoutedOutstandingWorkEnabled" + ), + debugActorTimerIntervalInSec = + if (c.hasPathOrNull("debugActorTimerIntervalInSec")) c.getInt("debugActorTimerIntervalInSec") else 0, + debugEnabled = c.hasPathOrNull("debugEnabled") && c.getBoolean("debugEnabled"), + memoryConsumptionDisplayTimeoutInSec = + if (c.hasPathOrNull("memoryConsumptionDisplayTimeoutInSec")) + c.getInt("memoryConsumptionDisplayTimeoutInSec") + else 0, + secondsToWaitToClearRoutedOutstandingWork = + if (c.hasPathOrNull("secondsToWaitToClearRoutedOutstandingWork")) + c.getInt("secondsToWaitToClearRoutedOutstandingWork") + else 60, + stuckAgentDetection = BeamConfig.Beam.Debug.StuckAgentDetection( + if (c.hasPathOrNull("stuckAgentDetection")) c.getConfig("stuckAgentDetection") + else com.typesafe.config.ConfigFactory.parseString("stuckAgentDetection{}") + ) ) } } - + case class Metrics( - level : java.lang.String + level: java.lang.String ) + object Metrics { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Metrics = { BeamConfig.Beam.Metrics( - level = if(c.hasPathOrNull("level")) c.getString("level") else "verbose" + level = if (c.hasPathOrNull("level")) c.getString("level") else "verbose" ) } } - + case class Outputs( - addTimestampToOutputDirectory : scala.Boolean, - baseOutputDirectory : java.lang.String, - events : BeamConfig.Beam.Outputs.Events, - stats : BeamConfig.Beam.Outputs.Stats, - writeEventsInterval : scala.Int, - writePlansInterval : scala.Int + addTimestampToOutputDirectory: scala.Boolean, + baseOutputDirectory: java.lang.String, + events: BeamConfig.Beam.Outputs.Events, + stats: BeamConfig.Beam.Outputs.Stats, + writeEventsInterval: scala.Int, + writePlansInterval: scala.Int ) + object Outputs { case class Events( - eventsToWrite : java.lang.String, - explodeIntoFiles : scala.Boolean, - fileOutputFormats : java.lang.String + eventsToWrite: java.lang.String, + explodeIntoFiles: scala.Boolean, + fileOutputFormats: java.lang.String ) + object Events { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Outputs.Events = { BeamConfig.Beam.Outputs.Events( - eventsToWrite = if(c.hasPathOrNull("eventsToWrite")) c.getString("eventsToWrite") else "ActivityEndEvent,ActivityStartEvent,PersonEntersVehicleEvent,PersonLeavesVehicleEvent,ModeChoiceEvent,PathTraversalEvent,ReserveRideHailEvent,ReplanningEvent,RefuelEvent,ParkEvent,LeavingParkingEvent", - explodeIntoFiles = c.hasPathOrNull("explodeIntoFiles") && c.getBoolean("explodeIntoFiles"), - fileOutputFormats = if(c.hasPathOrNull("fileOutputFormats")) c.getString("fileOutputFormats") else "csv" + eventsToWrite = + if (c.hasPathOrNull("eventsToWrite")) c.getString("eventsToWrite") + else + "ActivityEndEvent,ActivityStartEvent,PersonEntersVehicleEvent,PersonLeavesVehicleEvent,ModeChoiceEvent,PathTraversalEvent,ReserveRideHailEvent,ReplanningEvent,RefuelEvent,ParkEvent,LeavingParkingEvent", + explodeIntoFiles = c.hasPathOrNull("explodeIntoFiles") && c.getBoolean("explodeIntoFiles"), + fileOutputFormats = if (c.hasPathOrNull("fileOutputFormats")) c.getString("fileOutputFormats") else "csv" ) } } - + case class Stats( - binSize : scala.Int + binSize: scala.Int ) + object Stats { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Outputs.Stats = { BeamConfig.Beam.Outputs.Stats( - binSize = if(c.hasPathOrNull("binSize")) c.getInt("binSize") else 3600 + binSize = if (c.hasPathOrNull("binSize")) c.getInt("binSize") else 3600 ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Outputs = { BeamConfig.Beam.Outputs( - addTimestampToOutputDirectory = !c.hasPathOrNull("addTimestampToOutputDirectory") || c.getBoolean("addTimestampToOutputDirectory"), - baseOutputDirectory = if(c.hasPathOrNull("baseOutputDirectory")) c.getString("baseOutputDirectory") else "output", - events = BeamConfig.Beam.Outputs.Events(if(c.hasPathOrNull("events")) c.getConfig("events") else com.typesafe.config.ConfigFactory.parseString("events{}")), - stats = BeamConfig.Beam.Outputs.Stats(if(c.hasPathOrNull("stats")) c.getConfig("stats") else com.typesafe.config.ConfigFactory.parseString("stats{}")), - writeEventsInterval = if(c.hasPathOrNull("writeEventsInterval")) c.getInt("writeEventsInterval") else 1, - writePlansInterval = if(c.hasPathOrNull("writePlansInterval")) c.getInt("writePlansInterval") else 0 + addTimestampToOutputDirectory = !c.hasPathOrNull("addTimestampToOutputDirectory") || c.getBoolean( + "addTimestampToOutputDirectory" + ), + baseOutputDirectory = + if (c.hasPathOrNull("baseOutputDirectory")) c.getString("baseOutputDirectory") else "output", + events = BeamConfig.Beam.Outputs.Events( + if (c.hasPathOrNull("events")) c.getConfig("events") + else com.typesafe.config.ConfigFactory.parseString("events{}") + ), + stats = BeamConfig.Beam.Outputs.Stats( + if (c.hasPathOrNull("stats")) c.getConfig("stats") + else com.typesafe.config.ConfigFactory.parseString("stats{}") + ), + writeEventsInterval = if (c.hasPathOrNull("writeEventsInterval")) c.getInt("writeEventsInterval") else 1, + writePlansInterval = if (c.hasPathOrNull("writePlansInterval")) c.getInt("writePlansInterval") else 0 ) } } - + case class Physsim( - eventsForFullVersionOfVia : scala.Boolean, - flowCapacityFactor : scala.Double, - jdeqsim : BeamConfig.Beam.Physsim.Jdeqsim, - linkStatsBinSize : scala.Int, - linkStatsWriteInterval : scala.Int, - ptSampleSize : scala.Double, - quick_fix_minCarSpeedInMetersPerSecond : scala.Double, - skipPhysSim : scala.Boolean, - storageCapacityFactor : scala.Double, - writeEventsInterval : scala.Int, - writeMATSimNetwork : scala.Boolean, - writePlansInterval : scala.Int + eventsForFullVersionOfVia: scala.Boolean, + flowCapacityFactor: scala.Double, + jdeqsim: BeamConfig.Beam.Physsim.Jdeqsim, + linkStatsBinSize: scala.Int, + linkStatsWriteInterval: scala.Int, + ptSampleSize: scala.Double, + quick_fix_minCarSpeedInMetersPerSecond: scala.Double, + skipPhysSim: scala.Boolean, + storageCapacityFactor: scala.Double, + writeEventsInterval: scala.Int, + writeMATSimNetwork: scala.Boolean, + writePlansInterval: scala.Int ) + object Physsim { case class Jdeqsim( - agentSimPhysSimInterfaceDebugger : BeamConfig.Beam.Physsim.Jdeqsim.AgentSimPhysSimInterfaceDebugger + agentSimPhysSimInterfaceDebugger: BeamConfig.Beam.Physsim.Jdeqsim.AgentSimPhysSimInterfaceDebugger ) + object Jdeqsim { case class AgentSimPhysSimInterfaceDebugger( - enabled : scala.Boolean + enabled: scala.Boolean ) + object AgentSimPhysSimInterfaceDebugger { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Physsim.Jdeqsim.AgentSimPhysSimInterfaceDebugger = { BeamConfig.Beam.Physsim.Jdeqsim.AgentSimPhysSimInterfaceDebugger( enabled = c.hasPathOrNull("enabled") && c.getBoolean("enabled") ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Physsim.Jdeqsim = { BeamConfig.Beam.Physsim.Jdeqsim( - agentSimPhysSimInterfaceDebugger = BeamConfig.Beam.Physsim.Jdeqsim.AgentSimPhysSimInterfaceDebugger(if(c.hasPathOrNull("agentSimPhysSimInterfaceDebugger")) c.getConfig("agentSimPhysSimInterfaceDebugger") else com.typesafe.config.ConfigFactory.parseString("agentSimPhysSimInterfaceDebugger{}")) + agentSimPhysSimInterfaceDebugger = BeamConfig.Beam.Physsim.Jdeqsim.AgentSimPhysSimInterfaceDebugger( + if (c.hasPathOrNull("agentSimPhysSimInterfaceDebugger")) c.getConfig("agentSimPhysSimInterfaceDebugger") + else com.typesafe.config.ConfigFactory.parseString("agentSimPhysSimInterfaceDebugger{}") + ) ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Physsim = { BeamConfig.Beam.Physsim( - eventsForFullVersionOfVia = !c.hasPathOrNull("eventsForFullVersionOfVia") || c.getBoolean("eventsForFullVersionOfVia"), - flowCapacityFactor = if(c.hasPathOrNull("flowCapacityFactor")) c.getDouble("flowCapacityFactor") else 1.0, - jdeqsim = BeamConfig.Beam.Physsim.Jdeqsim(if(c.hasPathOrNull("jdeqsim")) c.getConfig("jdeqsim") else com.typesafe.config.ConfigFactory.parseString("jdeqsim{}")), - linkStatsBinSize = if(c.hasPathOrNull("linkStatsBinSize")) c.getInt("linkStatsBinSize") else 3600, - linkStatsWriteInterval = if(c.hasPathOrNull("linkStatsWriteInterval")) c.getInt("linkStatsWriteInterval") else 1, - ptSampleSize = if(c.hasPathOrNull("ptSampleSize")) c.getDouble("ptSampleSize") else 1.0, - quick_fix_minCarSpeedInMetersPerSecond = if(c.hasPathOrNull("quick_fix_minCarSpeedInMetersPerSecond")) c.getDouble("quick_fix_minCarSpeedInMetersPerSecond") else 0.5, - skipPhysSim = c.hasPathOrNull("skipPhysSim") && c.getBoolean("skipPhysSim"), - storageCapacityFactor = if(c.hasPathOrNull("storageCapacityFactor")) c.getDouble("storageCapacityFactor") else 1.0, - writeEventsInterval = if(c.hasPathOrNull("writeEventsInterval")) c.getInt("writeEventsInterval") else 0, - writeMATSimNetwork = c.hasPathOrNull("writeMATSimNetwork") && c.getBoolean("writeMATSimNetwork"), - writePlansInterval = if(c.hasPathOrNull("writePlansInterval")) c.getInt("writePlansInterval") else 0 + eventsForFullVersionOfVia = !c.hasPathOrNull("eventsForFullVersionOfVia") || c.getBoolean( + "eventsForFullVersionOfVia" + ), + flowCapacityFactor = if (c.hasPathOrNull("flowCapacityFactor")) c.getDouble("flowCapacityFactor") else 1.0, + jdeqsim = BeamConfig.Beam.Physsim.Jdeqsim( + if (c.hasPathOrNull("jdeqsim")) c.getConfig("jdeqsim") + else com.typesafe.config.ConfigFactory.parseString("jdeqsim{}") + ), + linkStatsBinSize = if (c.hasPathOrNull("linkStatsBinSize")) c.getInt("linkStatsBinSize") else 3600, + linkStatsWriteInterval = + if (c.hasPathOrNull("linkStatsWriteInterval")) c.getInt("linkStatsWriteInterval") else 1, + ptSampleSize = if (c.hasPathOrNull("ptSampleSize")) c.getDouble("ptSampleSize") else 1.0, + quick_fix_minCarSpeedInMetersPerSecond = + if (c.hasPathOrNull("quick_fix_minCarSpeedInMetersPerSecond")) + c.getDouble("quick_fix_minCarSpeedInMetersPerSecond") + else 0.5, + skipPhysSim = c.hasPathOrNull("skipPhysSim") && c.getBoolean("skipPhysSim"), + storageCapacityFactor = + if (c.hasPathOrNull("storageCapacityFactor")) c.getDouble("storageCapacityFactor") else 1.0, + writeEventsInterval = if (c.hasPathOrNull("writeEventsInterval")) c.getInt("writeEventsInterval") else 0, + writeMATSimNetwork = c.hasPathOrNull("writeMATSimNetwork") && c.getBoolean("writeMATSimNetwork"), + writePlansInterval = if (c.hasPathOrNull("writePlansInterval")) c.getInt("writePlansInterval") else 0 ) } } - + case class Routing( - baseDate : java.lang.String, - gtfs : BeamConfig.Beam.Routing.Gtfs, - r5 : BeamConfig.Beam.Routing.R5, - transitOnStreetNetwork : scala.Boolean + baseDate: java.lang.String, + gtfs: BeamConfig.Beam.Routing.Gtfs, + r5: BeamConfig.Beam.Routing.R5, + transitOnStreetNetwork: scala.Boolean ) + object Routing { case class Gtfs( - crs : java.lang.String, - operatorsFile : java.lang.String, - outputDir : java.lang.String + crs: java.lang.String, + operatorsFile: java.lang.String, + outputDir: java.lang.String ) + object Gtfs { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Routing.Gtfs = { BeamConfig.Beam.Routing.Gtfs( - crs = if(c.hasPathOrNull("crs")) c.getString("crs") else "epsg:26910", - operatorsFile = if(c.hasPathOrNull("operatorsFile")) c.getString("operatorsFile") else "src/main/resources/GTFSOperators.csv", - outputDir = if(c.hasPathOrNull("outputDir")) c.getString("outputDir") else "output/gtfs" + crs = if (c.hasPathOrNull("crs")) c.getString("crs") else "epsg:26910", + operatorsFile = + if (c.hasPathOrNull("operatorsFile")) c.getString("operatorsFile") + else "src/main/resources/GTFSOperators.csv", + outputDir = if (c.hasPathOrNull("outputDir")) c.getString("outputDir") else "output/gtfs" ) } } - + case class R5( - departureWindow : scala.Double, - directory : java.lang.String, - mNetBuilder : BeamConfig.Beam.Routing.R5.MNetBuilder, - numberOfSamples : scala.Int, - osmFile : java.lang.String, - osmMapdbFile : java.lang.String + departureWindow: scala.Double, + directory: java.lang.String, + mNetBuilder: BeamConfig.Beam.Routing.R5.MNetBuilder, + numberOfSamples: scala.Int, + osmFile: java.lang.String, + osmMapdbFile: java.lang.String ) + object R5 { case class MNetBuilder( - fromCRS : java.lang.String, - toCRS : java.lang.String + fromCRS: java.lang.String, + toCRS: java.lang.String ) + object MNetBuilder { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Routing.R5.MNetBuilder = { BeamConfig.Beam.Routing.R5.MNetBuilder( - fromCRS = if(c.hasPathOrNull("fromCRS")) c.getString("fromCRS") else "EPSG:4326", - toCRS = if(c.hasPathOrNull("toCRS")) c.getString("toCRS") else "EPSG:26910" + fromCRS = if (c.hasPathOrNull("fromCRS")) c.getString("fromCRS") else "EPSG:4326", + toCRS = if (c.hasPathOrNull("toCRS")) c.getString("toCRS") else "EPSG:26910" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Routing.R5 = { BeamConfig.Beam.Routing.R5( - departureWindow = if(c.hasPathOrNull("departureWindow")) c.getDouble("departureWindow") else 15.0, - directory = if(c.hasPathOrNull("directory")) c.getString("directory") else "/test/input/beamville/r5", - mNetBuilder = BeamConfig.Beam.Routing.R5.MNetBuilder(if(c.hasPathOrNull("mNetBuilder")) c.getConfig("mNetBuilder") else com.typesafe.config.ConfigFactory.parseString("mNetBuilder{}")), - numberOfSamples = if(c.hasPathOrNull("numberOfSamples")) c.getInt("numberOfSamples") else 1, - osmFile = if(c.hasPathOrNull("osmFile")) c.getString("osmFile") else "/test/input/beamville/r5/beamville.osm.pbf", - osmMapdbFile = if(c.hasPathOrNull("osmMapdbFile")) c.getString("osmMapdbFile") else "/test/input/beamville/r5/osm.mapdb" + departureWindow = if (c.hasPathOrNull("departureWindow")) c.getDouble("departureWindow") else 15.0, + directory = if (c.hasPathOrNull("directory")) c.getString("directory") else "/test/input/beamville/r5", + mNetBuilder = BeamConfig.Beam.Routing.R5.MNetBuilder( + if (c.hasPathOrNull("mNetBuilder")) c.getConfig("mNetBuilder") + else com.typesafe.config.ConfigFactory.parseString("mNetBuilder{}") + ), + numberOfSamples = if (c.hasPathOrNull("numberOfSamples")) c.getInt("numberOfSamples") else 1, + osmFile = + if (c.hasPathOrNull("osmFile")) c.getString("osmFile") else "/test/input/beamville/r5/beamville.osm.pbf", + osmMapdbFile = + if (c.hasPathOrNull("osmMapdbFile")) c.getString("osmMapdbFile") else "/test/input/beamville/r5/osm.mapdb" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Routing = { BeamConfig.Beam.Routing( - baseDate = if(c.hasPathOrNull("baseDate")) c.getString("baseDate") else "2016-10-17T00:00:00-07:00", - gtfs = BeamConfig.Beam.Routing.Gtfs(if(c.hasPathOrNull("gtfs")) c.getConfig("gtfs") else com.typesafe.config.ConfigFactory.parseString("gtfs{}")), - r5 = BeamConfig.Beam.Routing.R5(if(c.hasPathOrNull("r5")) c.getConfig("r5") else com.typesafe.config.ConfigFactory.parseString("r5{}")), + baseDate = if (c.hasPathOrNull("baseDate")) c.getString("baseDate") else "2016-10-17T00:00:00-07:00", + gtfs = BeamConfig.Beam.Routing.Gtfs( + if (c.hasPathOrNull("gtfs")) c.getConfig("gtfs") + else com.typesafe.config.ConfigFactory.parseString("gtfs{}") + ), + r5 = BeamConfig.Beam.Routing.R5( + if (c.hasPathOrNull("r5")) c.getConfig("r5") else com.typesafe.config.ConfigFactory.parseString("r5{}") + ), transitOnStreetNetwork = !c.hasPathOrNull("transitOnStreetNetwork") || c.getBoolean("transitOnStreetNetwork") ) } } - + case class Spatial( - boundingBoxBuffer : scala.Int, - localCRS : java.lang.String + boundingBoxBuffer: scala.Int, + localCRS: java.lang.String ) + object Spatial { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.Spatial = { BeamConfig.Beam.Spatial( - boundingBoxBuffer = if(c.hasPathOrNull("boundingBoxBuffer")) c.getInt("boundingBoxBuffer") else 5000, - localCRS = if(c.hasPathOrNull("localCRS")) c.getString("localCRS") else "epsg:32631" + boundingBoxBuffer = if (c.hasPathOrNull("boundingBoxBuffer")) c.getInt("boundingBoxBuffer") else 5000, + localCRS = if (c.hasPathOrNull("localCRS")) c.getString("localCRS") else "epsg:32631" ) } } - + case class WarmStart( - enabled : scala.Boolean, - path : java.lang.String + enabled: scala.Boolean, + path: java.lang.String ) + object WarmStart { + def apply(c: com.typesafe.config.Config): BeamConfig.Beam.WarmStart = { BeamConfig.Beam.WarmStart( enabled = c.hasPathOrNull("enabled") && c.getBoolean("enabled"), - path = if(c.hasPathOrNull("path")) c.getString("path") else "output" + path = if (c.hasPathOrNull("path")) c.getString("path") else "output" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Beam = { BeamConfig.Beam( - agentsim = BeamConfig.Beam.Agentsim(if(c.hasPathOrNull("agentsim")) c.getConfig("agentsim") else com.typesafe.config.ConfigFactory.parseString("agentsim{}")), - calibration = BeamConfig.Beam.Calibration(if(c.hasPathOrNull("calibration")) c.getConfig("calibration") else com.typesafe.config.ConfigFactory.parseString("calibration{}")), - cluster = BeamConfig.Beam.Cluster(if(c.hasPathOrNull("cluster")) c.getConfig("cluster") else com.typesafe.config.ConfigFactory.parseString("cluster{}")), - debug = BeamConfig.Beam.Debug(if(c.hasPathOrNull("debug")) c.getConfig("debug") else com.typesafe.config.ConfigFactory.parseString("debug{}")), - inputDirectory = if(c.hasPathOrNull("inputDirectory")) c.getString("inputDirectory") else "/test/input/beamville", - metrics = BeamConfig.Beam.Metrics(if(c.hasPathOrNull("metrics")) c.getConfig("metrics") else com.typesafe.config.ConfigFactory.parseString("metrics{}")), - outputs = BeamConfig.Beam.Outputs(if(c.hasPathOrNull("outputs")) c.getConfig("outputs") else com.typesafe.config.ConfigFactory.parseString("outputs{}")), - physsim = BeamConfig.Beam.Physsim(if(c.hasPathOrNull("physsim")) c.getConfig("physsim") else com.typesafe.config.ConfigFactory.parseString("physsim{}")), - routing = BeamConfig.Beam.Routing(if(c.hasPathOrNull("routing")) c.getConfig("routing") else com.typesafe.config.ConfigFactory.parseString("routing{}")), - spatial = BeamConfig.Beam.Spatial(if(c.hasPathOrNull("spatial")) c.getConfig("spatial") else com.typesafe.config.ConfigFactory.parseString("spatial{}")), + agentsim = BeamConfig.Beam.Agentsim( + if (c.hasPathOrNull("agentsim")) c.getConfig("agentsim") + else com.typesafe.config.ConfigFactory.parseString("agentsim{}") + ), + calibration = BeamConfig.Beam.Calibration( + if (c.hasPathOrNull("calibration")) c.getConfig("calibration") + else com.typesafe.config.ConfigFactory.parseString("calibration{}") + ), + cluster = BeamConfig.Beam.Cluster( + if (c.hasPathOrNull("cluster")) c.getConfig("cluster") + else com.typesafe.config.ConfigFactory.parseString("cluster{}") + ), + debug = BeamConfig.Beam.Debug( + if (c.hasPathOrNull("debug")) c.getConfig("debug") + else com.typesafe.config.ConfigFactory.parseString("debug{}") + ), + inputDirectory = + if (c.hasPathOrNull("inputDirectory")) c.getString("inputDirectory") else "/test/input/beamville", + metrics = BeamConfig.Beam.Metrics( + if (c.hasPathOrNull("metrics")) c.getConfig("metrics") + else com.typesafe.config.ConfigFactory.parseString("metrics{}") + ), + outputs = BeamConfig.Beam.Outputs( + if (c.hasPathOrNull("outputs")) c.getConfig("outputs") + else com.typesafe.config.ConfigFactory.parseString("outputs{}") + ), + physsim = BeamConfig.Beam.Physsim( + if (c.hasPathOrNull("physsim")) c.getConfig("physsim") + else com.typesafe.config.ConfigFactory.parseString("physsim{}") + ), + routing = BeamConfig.Beam.Routing( + if (c.hasPathOrNull("routing")) c.getConfig("routing") + else com.typesafe.config.ConfigFactory.parseString("routing{}") + ), + spatial = BeamConfig.Beam.Spatial( + if (c.hasPathOrNull("spatial")) c.getConfig("spatial") + else com.typesafe.config.ConfigFactory.parseString("spatial{}") + ), useLocalWorker = !c.hasPathOrNull("useLocalWorker") || c.getBoolean("useLocalWorker"), - warmStart = BeamConfig.Beam.WarmStart(if(c.hasPathOrNull("warmStart")) c.getConfig("warmStart") else com.typesafe.config.ConfigFactory.parseString("warmStart{}")) + warmStart = BeamConfig.Beam.WarmStart( + if (c.hasPathOrNull("warmStart")) c.getConfig("warmStart") + else com.typesafe.config.ConfigFactory.parseString("warmStart{}") + ) ) } } - + case class Matsim( - conversion : BeamConfig.Matsim.Conversion, - modules : BeamConfig.Matsim.Modules + conversion: BeamConfig.Matsim.Conversion, + modules: BeamConfig.Matsim.Modules ) + object Matsim { case class Conversion( - defaultHouseholdIncome : BeamConfig.Matsim.Conversion.DefaultHouseholdIncome, - generateVehicles : scala.Boolean, - matsimNetworkFile : java.lang.String, - osmFile : java.lang.String, - populationFile : java.lang.String, - scenarioDirectory : java.lang.String, - shapeConfig : BeamConfig.Matsim.Conversion.ShapeConfig, - vehiclesFile : java.lang.String + defaultHouseholdIncome: BeamConfig.Matsim.Conversion.DefaultHouseholdIncome, + generateVehicles: scala.Boolean, + matsimNetworkFile: java.lang.String, + osmFile: java.lang.String, + populationFile: java.lang.String, + scenarioDirectory: java.lang.String, + shapeConfig: BeamConfig.Matsim.Conversion.ShapeConfig, + vehiclesFile: java.lang.String ) + object Conversion { case class DefaultHouseholdIncome( - currency : java.lang.String, - period : java.lang.String, - value : scala.Int + currency: java.lang.String, + period: java.lang.String, + value: scala.Int ) + object DefaultHouseholdIncome { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Conversion.DefaultHouseholdIncome = { BeamConfig.Matsim.Conversion.DefaultHouseholdIncome( - currency = if(c.hasPathOrNull("currency")) c.getString("currency") else "usd", - period = if(c.hasPathOrNull("period")) c.getString("period") else "year", - value = if(c.hasPathOrNull("value")) c.getInt("value") else 50000 + currency = if (c.hasPathOrNull("currency")) c.getString("currency") else "usd", + period = if (c.hasPathOrNull("period")) c.getString("period") else "year", + value = if (c.hasPathOrNull("value")) c.getInt("value") else 50000 ) } } - + case class ShapeConfig( - shapeFile : java.lang.String, - tazIdFieldName : java.lang.String + shapeFile: java.lang.String, + tazIdFieldName: java.lang.String ) + object ShapeConfig { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Conversion.ShapeConfig = { BeamConfig.Matsim.Conversion.ShapeConfig( - shapeFile = if(c.hasPathOrNull("shapeFile")) c.getString("shapeFile") else "tz46_d00.shp", - tazIdFieldName = if(c.hasPathOrNull("tazIdFieldName")) c.getString("tazIdFieldName") else "TZ46_D00_I" + shapeFile = if (c.hasPathOrNull("shapeFile")) c.getString("shapeFile") else "tz46_d00.shp", + tazIdFieldName = if (c.hasPathOrNull("tazIdFieldName")) c.getString("tazIdFieldName") else "TZ46_D00_I" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Conversion = { BeamConfig.Matsim.Conversion( - defaultHouseholdIncome = BeamConfig.Matsim.Conversion.DefaultHouseholdIncome(if(c.hasPathOrNull("defaultHouseholdIncome")) c.getConfig("defaultHouseholdIncome") else com.typesafe.config.ConfigFactory.parseString("defaultHouseholdIncome{}")), - generateVehicles = !c.hasPathOrNull("generateVehicles") || c.getBoolean("generateVehicles"), - matsimNetworkFile = if(c.hasPathOrNull("matsimNetworkFile")) c.getString("matsimNetworkFile") else "Siouxfalls_network_PT.xml", - osmFile = if(c.hasPathOrNull("osmFile")) c.getString("osmFile") else "south-dakota-latest.osm.pbf", - populationFile = if(c.hasPathOrNull("populationFile")) c.getString("populationFile") else "Siouxfalls_population.xml", - scenarioDirectory = if(c.hasPathOrNull("scenarioDirectory")) c.getString("scenarioDirectory") else "/path/to/scenario/directory", - shapeConfig = BeamConfig.Matsim.Conversion.ShapeConfig(if(c.hasPathOrNull("shapeConfig")) c.getConfig("shapeConfig") else com.typesafe.config.ConfigFactory.parseString("shapeConfig{}")), - vehiclesFile = if(c.hasPathOrNull("vehiclesFile")) c.getString("vehiclesFile") else "Siouxfalls_vehicles.xml" + defaultHouseholdIncome = BeamConfig.Matsim.Conversion.DefaultHouseholdIncome( + if (c.hasPathOrNull("defaultHouseholdIncome")) c.getConfig("defaultHouseholdIncome") + else com.typesafe.config.ConfigFactory.parseString("defaultHouseholdIncome{}") + ), + generateVehicles = !c.hasPathOrNull("generateVehicles") || c.getBoolean("generateVehicles"), + matsimNetworkFile = + if (c.hasPathOrNull("matsimNetworkFile")) c.getString("matsimNetworkFile") else "Siouxfalls_network_PT.xml", + osmFile = if (c.hasPathOrNull("osmFile")) c.getString("osmFile") else "south-dakota-latest.osm.pbf", + populationFile = + if (c.hasPathOrNull("populationFile")) c.getString("populationFile") else "Siouxfalls_population.xml", + scenarioDirectory = + if (c.hasPathOrNull("scenarioDirectory")) c.getString("scenarioDirectory") + else "/path/to/scenario/directory", + shapeConfig = BeamConfig.Matsim.Conversion.ShapeConfig( + if (c.hasPathOrNull("shapeConfig")) c.getConfig("shapeConfig") + else com.typesafe.config.ConfigFactory.parseString("shapeConfig{}") + ), + vehiclesFile = if (c.hasPathOrNull("vehiclesFile")) c.getString("vehiclesFile") else "Siouxfalls_vehicles.xml" ) } } - + case class Modules( - changeMode : BeamConfig.Matsim.Modules.ChangeMode, - controler : BeamConfig.Matsim.Modules.Controler, - counts : BeamConfig.Matsim.Modules.Counts, - global : BeamConfig.Matsim.Modules.Global, - households : BeamConfig.Matsim.Modules.Households, - network : BeamConfig.Matsim.Modules.Network, - parallelEventHandling : BeamConfig.Matsim.Modules.ParallelEventHandling, - planCalcScore : BeamConfig.Matsim.Modules.PlanCalcScore, - plans : BeamConfig.Matsim.Modules.Plans, - qsim : BeamConfig.Matsim.Modules.Qsim, - strategy : BeamConfig.Matsim.Modules.Strategy, - transit : BeamConfig.Matsim.Modules.Transit, - vehicles : BeamConfig.Matsim.Modules.Vehicles + changeMode: BeamConfig.Matsim.Modules.ChangeMode, + controler: BeamConfig.Matsim.Modules.Controler, + counts: BeamConfig.Matsim.Modules.Counts, + global: BeamConfig.Matsim.Modules.Global, + households: BeamConfig.Matsim.Modules.Households, + network: BeamConfig.Matsim.Modules.Network, + parallelEventHandling: BeamConfig.Matsim.Modules.ParallelEventHandling, + planCalcScore: BeamConfig.Matsim.Modules.PlanCalcScore, + plans: BeamConfig.Matsim.Modules.Plans, + qsim: BeamConfig.Matsim.Modules.Qsim, + strategy: BeamConfig.Matsim.Modules.Strategy, + transit: BeamConfig.Matsim.Modules.Transit, + vehicles: BeamConfig.Matsim.Modules.Vehicles ) + object Modules { case class ChangeMode( - modes : java.lang.String + modes: java.lang.String ) + object ChangeMode { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.ChangeMode = { BeamConfig.Matsim.Modules.ChangeMode( - modes = if(c.hasPathOrNull("modes")) c.getString("modes") else "car,pt" + modes = if (c.hasPathOrNull("modes")) c.getString("modes") else "car,pt" ) } } - + case class Controler( - eventsFileFormat : java.lang.String, - firstIteration : scala.Int, - lastIteration : scala.Int, - mobsim : java.lang.String, - outputDirectory : java.lang.String, - overwriteFiles : java.lang.String + eventsFileFormat: java.lang.String, + firstIteration: scala.Int, + lastIteration: scala.Int, + mobsim: java.lang.String, + outputDirectory: java.lang.String, + overwriteFiles: java.lang.String ) + object Controler { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Controler = { BeamConfig.Matsim.Modules.Controler( - eventsFileFormat = if(c.hasPathOrNull("eventsFileFormat")) c.getString("eventsFileFormat") else "xml", - firstIteration = if(c.hasPathOrNull("firstIteration")) c.getInt("firstIteration") else 0, - lastIteration = if(c.hasPathOrNull("lastIteration")) c.getInt("lastIteration") else 0, - mobsim = if(c.hasPathOrNull("mobsim")) c.getString("mobsim") else "metasim", - outputDirectory = if(c.hasPathOrNull("outputDirectory")) c.getString("outputDirectory") else "output/pt-tutorial", - overwriteFiles = if(c.hasPathOrNull("overwriteFiles")) c.getString("overwriteFiles") else "overwriteExistingFiles" + eventsFileFormat = if (c.hasPathOrNull("eventsFileFormat")) c.getString("eventsFileFormat") else "xml", + firstIteration = if (c.hasPathOrNull("firstIteration")) c.getInt("firstIteration") else 0, + lastIteration = if (c.hasPathOrNull("lastIteration")) c.getInt("lastIteration") else 0, + mobsim = if (c.hasPathOrNull("mobsim")) c.getString("mobsim") else "metasim", + outputDirectory = + if (c.hasPathOrNull("outputDirectory")) c.getString("outputDirectory") else "output/pt-tutorial", + overwriteFiles = + if (c.hasPathOrNull("overwriteFiles")) c.getString("overwriteFiles") else "overwriteExistingFiles" ) } } - + case class Counts( - averageCountsOverIterations : scala.Int, - countsScaleFactor : scala.Double, - inputCountsFile : java.lang.String, - outputformat : java.lang.String, - writeCountsInterval : scala.Int + averageCountsOverIterations: scala.Int, + countsScaleFactor: scala.Double, + inputCountsFile: java.lang.String, + outputformat: java.lang.String, + writeCountsInterval: scala.Int ) + object Counts { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Counts = { BeamConfig.Matsim.Modules.Counts( - averageCountsOverIterations = if(c.hasPathOrNull("averageCountsOverIterations")) c.getInt("averageCountsOverIterations") else 0, - countsScaleFactor = if(c.hasPathOrNull("countsScaleFactor")) c.getDouble("countsScaleFactor") else 10.355, - inputCountsFile = if(c.hasPathOrNull("inputCountsFile")) c.getString("inputCountsFile") else "", - outputformat = if(c.hasPathOrNull("outputformat")) c.getString("outputformat") else "all", - writeCountsInterval = if(c.hasPathOrNull("writeCountsInterval")) c.getInt("writeCountsInterval") else 0 + averageCountsOverIterations = + if (c.hasPathOrNull("averageCountsOverIterations")) c.getInt("averageCountsOverIterations") else 0, + countsScaleFactor = if (c.hasPathOrNull("countsScaleFactor")) c.getDouble("countsScaleFactor") else 10.355, + inputCountsFile = if (c.hasPathOrNull("inputCountsFile")) c.getString("inputCountsFile") else "", + outputformat = if (c.hasPathOrNull("outputformat")) c.getString("outputformat") else "all", + writeCountsInterval = if (c.hasPathOrNull("writeCountsInterval")) c.getInt("writeCountsInterval") else 0 ) } } - + case class Global( - coordinateSystem : java.lang.String, - randomSeed : scala.Int + coordinateSystem: java.lang.String, + randomSeed: scala.Int ) + object Global { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Global = { BeamConfig.Matsim.Modules.Global( - coordinateSystem = if(c.hasPathOrNull("coordinateSystem")) c.getString("coordinateSystem") else "Atlantis", - randomSeed = if(c.hasPathOrNull("randomSeed")) c.getInt("randomSeed") else 4711 + coordinateSystem = if (c.hasPathOrNull("coordinateSystem")) c.getString("coordinateSystem") else "Atlantis", + randomSeed = if (c.hasPathOrNull("randomSeed")) c.getInt("randomSeed") else 4711 ) } } - + case class Households( - inputFile : java.lang.String, - inputHouseholdAttributesFile : java.lang.String + inputFile: java.lang.String, + inputHouseholdAttributesFile: java.lang.String ) + object Households { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Households = { BeamConfig.Matsim.Modules.Households( - inputFile = if(c.hasPathOrNull("inputFile")) c.getString("inputFile") else "/test/input/beamville/households.xml", - inputHouseholdAttributesFile = if(c.hasPathOrNull("inputHouseholdAttributesFile")) c.getString("inputHouseholdAttributesFile") else "/test/input/beamville/householdAttributes.xml" + inputFile = + if (c.hasPathOrNull("inputFile")) c.getString("inputFile") else "/test/input/beamville/households.xml", + inputHouseholdAttributesFile = + if (c.hasPathOrNull("inputHouseholdAttributesFile")) c.getString("inputHouseholdAttributesFile") + else "/test/input/beamville/householdAttributes.xml" ) } } - + case class Network( - inputNetworkFile : java.lang.String + inputNetworkFile: java.lang.String ) + object Network { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Network = { BeamConfig.Matsim.Modules.Network( - inputNetworkFile = if(c.hasPathOrNull("inputNetworkFile")) c.getString("inputNetworkFile") else "/test/input/beamville/physsim-network.xml" + inputNetworkFile = + if (c.hasPathOrNull("inputNetworkFile")) c.getString("inputNetworkFile") + else "/test/input/beamville/physsim-network.xml" ) } } - + case class ParallelEventHandling( - estimatedNumberOfEvents : scala.Int, - numberOfThreads : scala.Int, - oneThreadPerHandler : scala.Boolean, - synchronizeOnSimSteps : scala.Boolean + estimatedNumberOfEvents: scala.Int, + numberOfThreads: scala.Int, + oneThreadPerHandler: scala.Boolean, + synchronizeOnSimSteps: scala.Boolean ) + object ParallelEventHandling { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.ParallelEventHandling = { BeamConfig.Matsim.Modules.ParallelEventHandling( - estimatedNumberOfEvents = if(c.hasPathOrNull("estimatedNumberOfEvents")) c.getInt("estimatedNumberOfEvents") else 1000000000, - numberOfThreads = if(c.hasPathOrNull("numberOfThreads")) c.getInt("numberOfThreads") else 1, - oneThreadPerHandler = c.hasPathOrNull("oneThreadPerHandler") && c.getBoolean("oneThreadPerHandler"), - synchronizeOnSimSteps = c.hasPathOrNull("synchronizeOnSimSteps") && c.getBoolean("synchronizeOnSimSteps") + estimatedNumberOfEvents = + if (c.hasPathOrNull("estimatedNumberOfEvents")) c.getInt("estimatedNumberOfEvents") else 1000000000, + numberOfThreads = if (c.hasPathOrNull("numberOfThreads")) c.getInt("numberOfThreads") else 1, + oneThreadPerHandler = c.hasPathOrNull("oneThreadPerHandler") && c.getBoolean("oneThreadPerHandler"), + synchronizeOnSimSteps = c.hasPathOrNull("synchronizeOnSimSteps") && c.getBoolean("synchronizeOnSimSteps") ) } } - + case class PlanCalcScore( - BrainExpBeta : scala.Long, - earlyDeparture : scala.Long, - lateArrival : scala.Long, - learningRate : scala.Long, - parameterset : scala.List[BeamConfig.Matsim.Modules.PlanCalcScore.Parameterset$Elm], - performing : scala.Long, - traveling : scala.Long, - waiting : scala.Long + BrainExpBeta: scala.Long, + earlyDeparture: scala.Long, + lateArrival: scala.Long, + learningRate: scala.Long, + parameterset: scala.List[BeamConfig.Matsim.Modules.PlanCalcScore.Parameterset$Elm], + performing: scala.Long, + traveling: scala.Long, + waiting: scala.Long ) + object PlanCalcScore { case class Parameterset$Elm( - activityType : java.lang.String, - priority : scala.Int, - scoringThisActivityAtAll : scala.Boolean, - `type` : java.lang.String, - typicalDuration : java.lang.String, - typicalDurationScoreComputation : java.lang.String + activityType: java.lang.String, + priority: scala.Int, + scoringThisActivityAtAll: scala.Boolean, + `type`: java.lang.String, + typicalDuration: java.lang.String, + typicalDurationScoreComputation: java.lang.String ) + object Parameterset$Elm { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.PlanCalcScore.Parameterset$Elm = { BeamConfig.Matsim.Modules.PlanCalcScore.Parameterset$Elm( - activityType = if(c.hasPathOrNull("activityType")) c.getString("activityType") else "Home", - priority = if(c.hasPathOrNull("priority")) c.getInt("priority") else 1, - scoringThisActivityAtAll = !c.hasPathOrNull("scoringThisActivityAtAll") || c.getBoolean("scoringThisActivityAtAll"), - `type` = if(c.hasPathOrNull("type")) c.getString("type") else "activityParams", - typicalDuration = if(c.hasPathOrNull("typicalDuration")) c.getString("typicalDuration") else "01:00:00", - typicalDurationScoreComputation = if(c.hasPathOrNull("typicalDurationScoreComputation")) c.getString("typicalDurationScoreComputation") else "uniform" + activityType = if (c.hasPathOrNull("activityType")) c.getString("activityType") else "Home", + priority = if (c.hasPathOrNull("priority")) c.getInt("priority") else 1, + scoringThisActivityAtAll = !c.hasPathOrNull("scoringThisActivityAtAll") || c.getBoolean( + "scoringThisActivityAtAll" + ), + `type` = if (c.hasPathOrNull("type")) c.getString("type") else "activityParams", + typicalDuration = if (c.hasPathOrNull("typicalDuration")) c.getString("typicalDuration") else "01:00:00", + typicalDurationScoreComputation = + if (c.hasPathOrNull("typicalDurationScoreComputation")) c.getString("typicalDurationScoreComputation") + else "uniform" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.PlanCalcScore = { BeamConfig.Matsim.Modules.PlanCalcScore( - BrainExpBeta = if(c.hasPathOrNull("BrainExpBeta")) c.getDuration("BrainExpBeta", java.util.concurrent.TimeUnit.MILLISECONDS) else 2, - earlyDeparture = if(c.hasPathOrNull("earlyDeparture")) c.getDuration("earlyDeparture", java.util.concurrent.TimeUnit.MILLISECONDS) else 0, - lateArrival = if(c.hasPathOrNull("lateArrival")) c.getDuration("lateArrival", java.util.concurrent.TimeUnit.MILLISECONDS) else -18, - learningRate = if(c.hasPathOrNull("learningRate")) c.getDuration("learningRate", java.util.concurrent.TimeUnit.MILLISECONDS) else 1, - parameterset = $_LBeamConfig_Matsim_Modules_PlanCalcScore_Parameterset$Elm(c.getList("parameterset")), - performing = if(c.hasPathOrNull("performing")) c.getDuration("performing", java.util.concurrent.TimeUnit.MILLISECONDS) else 6, - traveling = if(c.hasPathOrNull("traveling")) c.getDuration("traveling", java.util.concurrent.TimeUnit.MILLISECONDS) else -6, - waiting = if(c.hasPathOrNull("waiting")) c.getDuration("waiting", java.util.concurrent.TimeUnit.MILLISECONDS) else 0 + BrainExpBeta = + if (c.hasPathOrNull("BrainExpBeta")) + c.getDuration("BrainExpBeta", java.util.concurrent.TimeUnit.MILLISECONDS) + else 2, + earlyDeparture = + if (c.hasPathOrNull("earlyDeparture")) + c.getDuration("earlyDeparture", java.util.concurrent.TimeUnit.MILLISECONDS) + else 0, + lateArrival = + if (c.hasPathOrNull("lateArrival")) + c.getDuration("lateArrival", java.util.concurrent.TimeUnit.MILLISECONDS) + else -18, + learningRate = + if (c.hasPathOrNull("learningRate")) + c.getDuration("learningRate", java.util.concurrent.TimeUnit.MILLISECONDS) + else 1, + parameterset = $_LBeamConfig_Matsim_Modules_PlanCalcScore_Parameterset$Elm(c.getList("parameterset")), + performing = + if (c.hasPathOrNull("performing")) c.getDuration("performing", java.util.concurrent.TimeUnit.MILLISECONDS) + else 6, + traveling = + if (c.hasPathOrNull("traveling")) c.getDuration("traveling", java.util.concurrent.TimeUnit.MILLISECONDS) + else -6, + waiting = + if (c.hasPathOrNull("waiting")) c.getDuration("waiting", java.util.concurrent.TimeUnit.MILLISECONDS) + else 0 ) } - private def $_LBeamConfig_Matsim_Modules_PlanCalcScore_Parameterset$Elm(cl:com.typesafe.config.ConfigList): scala.List[BeamConfig.Matsim.Modules.PlanCalcScore.Parameterset$Elm] = { + private def $_LBeamConfig_Matsim_Modules_PlanCalcScore_Parameterset$Elm( + cl: com.typesafe.config.ConfigList + ): scala.List[BeamConfig.Matsim.Modules.PlanCalcScore.Parameterset$Elm] = { import scala.collection.JavaConverters._ - cl.asScala.map(cv => BeamConfig.Matsim.Modules.PlanCalcScore.Parameterset$Elm(cv.asInstanceOf[com.typesafe.config.ConfigObject].toConfig)).toList + cl.asScala + .map( + cv => + BeamConfig.Matsim.Modules.PlanCalcScore + .Parameterset$Elm(cv.asInstanceOf[com.typesafe.config.ConfigObject].toConfig) + ) + .toList } } - + case class Plans( - inputPersonAttributesFile : java.lang.String, - inputPlansFile : java.lang.String + inputPersonAttributesFile: java.lang.String, + inputPlansFile: java.lang.String ) + object Plans { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Plans = { BeamConfig.Matsim.Modules.Plans( - inputPersonAttributesFile = if(c.hasPathOrNull("inputPersonAttributesFile")) c.getString("inputPersonAttributesFile") else "/test/input/beamville/populationAttributes.xml", - inputPlansFile = if(c.hasPathOrNull("inputPlansFile")) c.getString("inputPlansFile") else "/test/input/beamville/population.xml" + inputPersonAttributesFile = + if (c.hasPathOrNull("inputPersonAttributesFile")) c.getString("inputPersonAttributesFile") + else "/test/input/beamville/populationAttributes.xml", + inputPlansFile = + if (c.hasPathOrNull("inputPlansFile")) c.getString("inputPlansFile") + else "/test/input/beamville/population.xml" ) } } - + case class Qsim( - endTime : java.lang.String, - snapshotperiod : java.lang.String, - startTime : java.lang.String + endTime: java.lang.String, + snapshotperiod: java.lang.String, + startTime: java.lang.String ) + object Qsim { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Qsim = { BeamConfig.Matsim.Modules.Qsim( - endTime = if(c.hasPathOrNull("endTime")) c.getString("endTime") else "30:00:00", - snapshotperiod = if(c.hasPathOrNull("snapshotperiod")) c.getString("snapshotperiod") else "00:00:00", - startTime = if(c.hasPathOrNull("startTime")) c.getString("startTime") else "00:00:00" + endTime = if (c.hasPathOrNull("endTime")) c.getString("endTime") else "30:00:00", + snapshotperiod = if (c.hasPathOrNull("snapshotperiod")) c.getString("snapshotperiod") else "00:00:00", + startTime = if (c.hasPathOrNull("startTime")) c.getString("startTime") else "00:00:00" ) } } - + case class Strategy( - ModuleProbability_1 : scala.Double, - ModuleProbability_3 : scala.Double, - Module_1 : java.lang.String, - Module_3 : java.lang.String, - maxAgentPlanMemorySize : scala.Int + ModuleProbability_1: scala.Double, + ModuleProbability_3: scala.Double, + Module_1: java.lang.String, + Module_3: java.lang.String, + maxAgentPlanMemorySize: scala.Int ) + object Strategy { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Strategy = { BeamConfig.Matsim.Modules.Strategy( - ModuleProbability_1 = if(c.hasPathOrNull("ModuleProbability_1")) c.getDouble("ModuleProbability_1") else 0.7, - ModuleProbability_3 = if(c.hasPathOrNull("ModuleProbability_3")) c.getDouble("ModuleProbability_3") else 0.1, - Module_1 = if(c.hasPathOrNull("Module_1")) c.getString("Module_1") else "BestScore", - Module_3 = if(c.hasPathOrNull("Module_3")) c.getString("Module_3") else "TimeAllocationMutator", - maxAgentPlanMemorySize = if(c.hasPathOrNull("maxAgentPlanMemorySize")) c.getInt("maxAgentPlanMemorySize") else 5 + ModuleProbability_1 = + if (c.hasPathOrNull("ModuleProbability_1")) c.getDouble("ModuleProbability_1") else 0.7, + ModuleProbability_3 = + if (c.hasPathOrNull("ModuleProbability_3")) c.getDouble("ModuleProbability_3") else 0.1, + Module_1 = if (c.hasPathOrNull("Module_1")) c.getString("Module_1") else "BestScore", + Module_3 = if (c.hasPathOrNull("Module_3")) c.getString("Module_3") else "TimeAllocationMutator", + maxAgentPlanMemorySize = + if (c.hasPathOrNull("maxAgentPlanMemorySize")) c.getInt("maxAgentPlanMemorySize") else 5 ) } } - + case class Transit( - transitModes : java.lang.String, - useTransit : scala.Boolean, - vehiclesFile : java.lang.String + transitModes: java.lang.String, + useTransit: scala.Boolean, + vehiclesFile: java.lang.String ) + object Transit { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Transit = { BeamConfig.Matsim.Modules.Transit( - transitModes = if(c.hasPathOrNull("transitModes")) c.getString("transitModes") else "pt", - useTransit = c.hasPathOrNull("useTransit") && c.getBoolean("useTransit"), - vehiclesFile = if(c.hasPathOrNull("vehiclesFile")) c.getString("vehiclesFile") else "/test/input/beamville/transitVehicles.xml" + transitModes = if (c.hasPathOrNull("transitModes")) c.getString("transitModes") else "pt", + useTransit = c.hasPathOrNull("useTransit") && c.getBoolean("useTransit"), + vehiclesFile = + if (c.hasPathOrNull("vehiclesFile")) c.getString("vehiclesFile") + else "/test/input/beamville/transitVehicles.xml" ) } } - + case class Vehicles( - vehiclesFile : java.lang.String + vehiclesFile: java.lang.String ) + object Vehicles { + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules.Vehicles = { BeamConfig.Matsim.Modules.Vehicles( - vehiclesFile = if(c.hasPathOrNull("vehiclesFile")) c.getString("vehiclesFile") else "/test/input/beamville/vehicles.xml" + vehiclesFile = + if (c.hasPathOrNull("vehiclesFile")) c.getString("vehiclesFile") else "/test/input/beamville/vehicles.xml" ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim.Modules = { BeamConfig.Matsim.Modules( - changeMode = BeamConfig.Matsim.Modules.ChangeMode(if(c.hasPathOrNull("changeMode")) c.getConfig("changeMode") else com.typesafe.config.ConfigFactory.parseString("changeMode{}")), - controler = BeamConfig.Matsim.Modules.Controler(if(c.hasPathOrNull("controler")) c.getConfig("controler") else com.typesafe.config.ConfigFactory.parseString("controler{}")), - counts = BeamConfig.Matsim.Modules.Counts(if(c.hasPathOrNull("counts")) c.getConfig("counts") else com.typesafe.config.ConfigFactory.parseString("counts{}")), - global = BeamConfig.Matsim.Modules.Global(if(c.hasPathOrNull("global")) c.getConfig("global") else com.typesafe.config.ConfigFactory.parseString("global{}")), - households = BeamConfig.Matsim.Modules.Households(if(c.hasPathOrNull("households")) c.getConfig("households") else com.typesafe.config.ConfigFactory.parseString("households{}")), - network = BeamConfig.Matsim.Modules.Network(if(c.hasPathOrNull("network")) c.getConfig("network") else com.typesafe.config.ConfigFactory.parseString("network{}")), - parallelEventHandling = BeamConfig.Matsim.Modules.ParallelEventHandling(if(c.hasPathOrNull("parallelEventHandling")) c.getConfig("parallelEventHandling") else com.typesafe.config.ConfigFactory.parseString("parallelEventHandling{}")), - planCalcScore = BeamConfig.Matsim.Modules.PlanCalcScore(if(c.hasPathOrNull("planCalcScore")) c.getConfig("planCalcScore") else com.typesafe.config.ConfigFactory.parseString("planCalcScore{}")), - plans = BeamConfig.Matsim.Modules.Plans(if(c.hasPathOrNull("plans")) c.getConfig("plans") else com.typesafe.config.ConfigFactory.parseString("plans{}")), - qsim = BeamConfig.Matsim.Modules.Qsim(if(c.hasPathOrNull("qsim")) c.getConfig("qsim") else com.typesafe.config.ConfigFactory.parseString("qsim{}")), - strategy = BeamConfig.Matsim.Modules.Strategy(if(c.hasPathOrNull("strategy")) c.getConfig("strategy") else com.typesafe.config.ConfigFactory.parseString("strategy{}")), - transit = BeamConfig.Matsim.Modules.Transit(if(c.hasPathOrNull("transit")) c.getConfig("transit") else com.typesafe.config.ConfigFactory.parseString("transit{}")), - vehicles = BeamConfig.Matsim.Modules.Vehicles(if(c.hasPathOrNull("vehicles")) c.getConfig("vehicles") else com.typesafe.config.ConfigFactory.parseString("vehicles{}")) + changeMode = BeamConfig.Matsim.Modules.ChangeMode( + if (c.hasPathOrNull("changeMode")) c.getConfig("changeMode") + else com.typesafe.config.ConfigFactory.parseString("changeMode{}") + ), + controler = BeamConfig.Matsim.Modules.Controler( + if (c.hasPathOrNull("controler")) c.getConfig("controler") + else com.typesafe.config.ConfigFactory.parseString("controler{}") + ), + counts = BeamConfig.Matsim.Modules.Counts( + if (c.hasPathOrNull("counts")) c.getConfig("counts") + else com.typesafe.config.ConfigFactory.parseString("counts{}") + ), + global = BeamConfig.Matsim.Modules.Global( + if (c.hasPathOrNull("global")) c.getConfig("global") + else com.typesafe.config.ConfigFactory.parseString("global{}") + ), + households = BeamConfig.Matsim.Modules.Households( + if (c.hasPathOrNull("households")) c.getConfig("households") + else com.typesafe.config.ConfigFactory.parseString("households{}") + ), + network = BeamConfig.Matsim.Modules.Network( + if (c.hasPathOrNull("network")) c.getConfig("network") + else com.typesafe.config.ConfigFactory.parseString("network{}") + ), + parallelEventHandling = BeamConfig.Matsim.Modules.ParallelEventHandling( + if (c.hasPathOrNull("parallelEventHandling")) c.getConfig("parallelEventHandling") + else com.typesafe.config.ConfigFactory.parseString("parallelEventHandling{}") + ), + planCalcScore = BeamConfig.Matsim.Modules.PlanCalcScore( + if (c.hasPathOrNull("planCalcScore")) c.getConfig("planCalcScore") + else com.typesafe.config.ConfigFactory.parseString("planCalcScore{}") + ), + plans = BeamConfig.Matsim.Modules.Plans( + if (c.hasPathOrNull("plans")) c.getConfig("plans") + else com.typesafe.config.ConfigFactory.parseString("plans{}") + ), + qsim = BeamConfig.Matsim.Modules.Qsim( + if (c.hasPathOrNull("qsim")) c.getConfig("qsim") + else com.typesafe.config.ConfigFactory.parseString("qsim{}") + ), + strategy = BeamConfig.Matsim.Modules.Strategy( + if (c.hasPathOrNull("strategy")) c.getConfig("strategy") + else com.typesafe.config.ConfigFactory.parseString("strategy{}") + ), + transit = BeamConfig.Matsim.Modules.Transit( + if (c.hasPathOrNull("transit")) c.getConfig("transit") + else com.typesafe.config.ConfigFactory.parseString("transit{}") + ), + vehicles = BeamConfig.Matsim.Modules.Vehicles( + if (c.hasPathOrNull("vehicles")) c.getConfig("vehicles") + else com.typesafe.config.ConfigFactory.parseString("vehicles{}") + ) ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig.Matsim = { BeamConfig.Matsim( - conversion = BeamConfig.Matsim.Conversion(if(c.hasPathOrNull("conversion")) c.getConfig("conversion") else com.typesafe.config.ConfigFactory.parseString("conversion{}")), - modules = BeamConfig.Matsim.Modules(if(c.hasPathOrNull("modules")) c.getConfig("modules") else com.typesafe.config.ConfigFactory.parseString("modules{}")) + conversion = BeamConfig.Matsim.Conversion( + if (c.hasPathOrNull("conversion")) c.getConfig("conversion") + else com.typesafe.config.ConfigFactory.parseString("conversion{}") + ), + modules = BeamConfig.Matsim.Modules( + if (c.hasPathOrNull("modules")) c.getConfig("modules") + else com.typesafe.config.ConfigFactory.parseString("modules{}") + ) ) } } - + def apply(c: com.typesafe.config.Config): BeamConfig = { BeamConfig( - beam = BeamConfig.Beam(if(c.hasPathOrNull("beam")) c.getConfig("beam") else com.typesafe.config.ConfigFactory.parseString("beam{}")), - matsim = BeamConfig.Matsim(if(c.hasPathOrNull("matsim")) c.getConfig("matsim") else com.typesafe.config.ConfigFactory.parseString("matsim{}")) + beam = BeamConfig.Beam( + if (c.hasPathOrNull("beam")) c.getConfig("beam") else com.typesafe.config.ConfigFactory.parseString("beam{}") + ), + matsim = BeamConfig.Matsim( + if (c.hasPathOrNull("matsim")) c.getConfig("matsim") + else com.typesafe.config.ConfigFactory.parseString("matsim{}") + ) ) } } - diff --git a/src/main/scala/beam/sim/population/DiffusionPotentialPopulationAdjustment.scala b/src/main/scala/beam/sim/population/DiffusionPotentialPopulationAdjustment.scala index e70962ed34b..1c40a8e3a44 100644 --- a/src/main/scala/beam/sim/population/DiffusionPotentialPopulationAdjustment.scala +++ b/src/main/scala/beam/sim/population/DiffusionPotentialPopulationAdjustment.scala @@ -157,12 +157,12 @@ object DiffusionPotentialPopulationAdjustment { def findPerson(population: Population, personId: Id[Person]): Option[Person] = { val persons = population.getPersons.values().asScala - persons.collectFirst{ case person if person.getId.equals(personId) => person } + persons.collectFirst { case person if person.getId.equals(personId) => person } } def findHousehold(scenario: Scenario, personId: Id[Person]): Option[Household] = { val households = scenario.getHouseholds.getHouseholds.values().asScala - households.collectFirst{ case household if household.getMemberIds.contains(personId) => household } + households.collectFirst { case household if household.getMemberIds.contains(personId) => household } } /*val dependentVariables = Map( diff --git a/src/main/scala/beam/sim/population/PopulationAdjustment.scala b/src/main/scala/beam/sim/population/PopulationAdjustment.scala index 4ec96ef7fe6..4f15ff42956 100644 --- a/src/main/scala/beam/sim/population/PopulationAdjustment.scala +++ b/src/main/scala/beam/sim/population/PopulationAdjustment.scala @@ -22,10 +22,11 @@ trait PopulationAdjustment extends LazyLogging { def updateAttributes(population: MPopulation): MPopulation = { val personAttributes: ObjectAttributes = population.getPersonAttributes - JavaConverters.mapAsScalaMap(population.getPersons) + JavaConverters + .mapAsScalaMap(population.getPersons) .values - .map { - person => { + .map { person => + { val valueOfTime: Double = personAttributes.getAttribute(person.getId.toString, "valueOfTime") match { @@ -35,29 +36,37 @@ trait PopulationAdjustment extends LazyLogging { specifiedVot.asInstanceOf[Double] } - val availableModes: Seq[BeamMode] = Option(personAttributes.getAttribute(person.getId.toString, "available-modes") + val availableModes: Seq[BeamMode] = Option( + personAttributes.getAttribute(person.getId.toString, "available-modes") ).fold(BeamMode.availableModes)( attr => availableModeParser(attr.toString) ) - val income = Try{personAttributes.getAttribute(person.getId.toString, "income")} match { - case scala.util.Success(value) => Option(value.asInstanceOf[Double]) + val income = Try { personAttributes.getAttribute(person.getId.toString, "income") } match { + case scala.util.Success(value) => Option(value.asInstanceOf[Double]) case scala.util.Failure(exception) => Some(0.0) } val modalityStyle = Option(person.getSelectedPlan.getAttributes.getAttribute("modality-style")) .map(_.asInstanceOf[String]) - val householdAttributes = beamServices.personHouseholds.get(person.getId).fold(HouseholdAttributes.EMPTY) { household => - - val houseHoldVehicles: Map[Id[BeamVehicle], BeamVehicle] = - agentsim.agents.Population.getVehiclesFromHousehold(household, beamServices) - HouseholdAttributes(household, houseHoldVehicles) + val householdAttributes = beamServices.personHouseholds.get(person.getId).fold(HouseholdAttributes.EMPTY) { + household => + val houseHoldVehicles: Map[Id[BeamVehicle], BeamVehicle] = + agentsim.agents.Population.getVehiclesFromHousehold(household, beamServices) + HouseholdAttributes(household, houseHoldVehicles) } - val attributes = - AttributesOfIndividual(householdAttributes, modalityStyle, Option(PersonUtils.getSex(person)).getOrElse("M").equalsIgnoreCase("M"), availableModes, valueOfTime, Option(PersonUtils.getAge(person)), income) - - person.getCustomAttributes.put("beam-attributes", attributes) + val attributes = + AttributesOfIndividual( + householdAttributes, + modalityStyle, + Option(PersonUtils.getSex(person)).getOrElse("M").equalsIgnoreCase("M"), + availableModes, + valueOfTime, + Option(PersonUtils.getAge(person)), + income + ) + person.getCustomAttributes.put("beam-attributes", attributes) } } @@ -102,7 +111,11 @@ trait PopulationAdjustment extends LazyLogging { protected def updatePopulation(scenario: Scenario): MPopulation protected def addMode(population: MPopulation, personId: String, mode: String): Unit = { - val modes = population.getPersonAttributes.getAttribute(personId, "beam-attributes").asInstanceOf[AttributesOfIndividual].availableModes.toString + val modes = population.getPersonAttributes + .getAttribute(personId, "beam-attributes") + .asInstanceOf[AttributesOfIndividual] + .availableModes + .toString if (!existsMode(population, personId, mode)) { population.getPersonAttributes .putAttribute( @@ -120,7 +133,11 @@ trait PopulationAdjustment extends LazyLogging { protected def removeMode(population: MPopulation, personId: String, modeToRemove: String*): Unit = { - val modes = population.getPersonAttributes.getAttribute(personId, "beam-attributes").asInstanceOf[AttributesOfIndividual].availableModes.toString + val modes = population.getPersonAttributes + .getAttribute(personId, "beam-attributes") + .asInstanceOf[AttributesOfIndividual] + .availableModes + .toString modeToRemove.foreach( mode => population.getPersonAttributes @@ -128,14 +145,18 @@ trait PopulationAdjustment extends LazyLogging { personId, AVAILABLE_MODES, modes.split(",").filterNot(_.equalsIgnoreCase(mode)).mkString(",") - ) + ) ) } // remove mode from all attributes protected def removeModeAll(population: MPopulation, modeToRemove: String*): Unit = { population.getPersons.keySet().forEach { person => - val modes = population.getPersonAttributes.getAttribute(person.toString, "beam-attributes").asInstanceOf[AttributesOfIndividual].availableModes.toString + val modes = population.getPersonAttributes + .getAttribute(person.toString, "beam-attributes") + .asInstanceOf[AttributesOfIndividual] + .availableModes + .toString modeToRemove.foreach( mode => population.getPersonAttributes @@ -143,7 +164,7 @@ trait PopulationAdjustment extends LazyLogging { person.toString, AVAILABLE_MODES, modes.split(",").filterNot(_.equalsIgnoreCase(mode)).mkString(",") - ) + ) ) } } diff --git a/src/main/scala/beam/sim/population/PopulationAttributes.scala b/src/main/scala/beam/sim/population/PopulationAttributes.scala index c178bfca885..a2fa6e6890d 100644 --- a/src/main/scala/beam/sim/population/PopulationAttributes.scala +++ b/src/main/scala/beam/sim/population/PopulationAttributes.scala @@ -9,30 +9,28 @@ import scala.collection.JavaConverters._ sealed trait PopulationAttributes - - case class AttributesOfIndividual(householdAttributes: HouseholdAttributes, - modalityStyle: Option[String], - isMale: Boolean, - availableModes: Seq[BeamMode], - valueOfTime: Double, - age: Option[Int], - income: Option[Double] - ) extends PopulationAttributes - { - lazy val hasModalityStyle: Boolean = modalityStyle.nonEmpty - } - - +case class AttributesOfIndividual( + householdAttributes: HouseholdAttributes, + modalityStyle: Option[String], + isMale: Boolean, + availableModes: Seq[BeamMode], + valueOfTime: Double, + age: Option[Int], + income: Option[Double] +) extends PopulationAttributes { + lazy val hasModalityStyle: Boolean = modalityStyle.nonEmpty +} case class HouseholdAttributes( - householdIncome: Double, - householdSize: Int, - numCars: Int, - numBikes: Int - ) extends PopulationAttributes + householdIncome: Double, + householdSize: Int, + numCars: Int, + numBikes: Int +) extends PopulationAttributes + object HouseholdAttributes { - val EMPTY = HouseholdAttributes(0.0,0,0,0) + val EMPTY = HouseholdAttributes(0.0, 0, 0, 0) def apply(household: Household, vehicles: Map[Id[BeamVehicle], BeamVehicle]): HouseholdAttributes = { new HouseholdAttributes( diff --git a/src/main/scala/beam/utils/BeamConfigUtils.scala b/src/main/scala/beam/utils/BeamConfigUtils.scala index 80b7093e295..ec36741c904 100755 --- a/src/main/scala/beam/utils/BeamConfigUtils.scala +++ b/src/main/scala/beam/utils/BeamConfigUtils.scala @@ -12,7 +12,7 @@ object BeamConfigUtils extends LazyLogging { def parseFileSubstitutingInputDirectory(fileName: String): com.typesafe.config.Config = { val file = Paths.get(fileName).toFile - if(!file.exists()) throw new Exception(s"Missing config file on path $fileName") + if (!file.exists()) throw new Exception(s"Missing config file on path $fileName") logger.debug(s"Loading beam config from $file.") parseFileSubstitutingInputDirectory(file) } diff --git a/src/main/scala/beam/utils/SpatialPlot.scala b/src/main/scala/beam/utils/SpatialPlot.scala index 9117b2316de..d3b6c89e88b 100755 --- a/src/main/scala/beam/utils/SpatialPlot.scala +++ b/src/main/scala/beam/utils/SpatialPlot.scala @@ -14,13 +14,11 @@ case class RideHailAgentInitCoord(agentId: Id[RideHailAgent], coord: Coord) case class Bounds(minx: Double, miny: Double, maxx: Double, maxy: Double) - // frame is good for text labels as they can be outside of the area otherwise class SpatialPlot(width: Int, height: Int, frame: Int) extends Plot(width, height, frame) { val rideHailAgentInitCoordBuffer: ListBuffer[RideHailAgentInitCoord] = ListBuffer() - def addAgentWithCoord(rideHailAgentInitCoord: RideHailAgentInitCoord): Unit = { rideHailAgentInitCoordBuffer += rideHailAgentInitCoord } @@ -36,5 +34,4 @@ class SpatialPlot(width: Int, height: Int, frame: Int) extends Plot(width, heigh out.close() } - } diff --git a/src/main/scala/beam/utils/StuckFinder.scala b/src/main/scala/beam/utils/StuckFinder.scala index 4727f9ef3b3..9a8b060c8ee 100644 --- a/src/main/scala/beam/utils/StuckFinder.scala +++ b/src/main/scala/beam/utils/StuckFinder.scala @@ -27,7 +27,7 @@ class StuckFinder(val cfg: StuckAgentDetection) extends LazyLogging { verifyTypesExist() } - private val triggerTypeToActorThreshold: Map[Class[_], Map[String, Int]] = if (!cfg.checkMaxNumberOfMessagesEnabled){ + private val triggerTypeToActorThreshold: Map[Class[_], Map[String, Int]] = if (!cfg.checkMaxNumberOfMessagesEnabled) { Map.empty } else { getPerActorTypeThreshold(cfg.thresholds) @@ -117,7 +117,9 @@ class StuckFinder(val cfg: StuckAgentDetection) extends LazyLogging { } } if (cfg.checkMaxNumberOfMessagesEnabled) { - result.appendAll(exceedMaxNumberOfMessages.map { x => ValueWithTime(x, -1)}) + result.appendAll(exceedMaxNumberOfMessages.map { x => + ValueWithTime(x, -1) + }) exceedMaxNumberOfMessages.clear() } result @@ -162,19 +164,29 @@ class StuckFinder(val cfg: StuckAgentDetection) extends LazyLogging { val actor = st.agent val triggerClazz = st.triggerWithId.trigger.getClass val msgCount = updateAndGetNumOfTriggerMessagesPerActor(actor, triggerClazz) - val maxMsgPerActorType = triggerTypeToActorThreshold.get(triggerClazz).flatMap { m => m.get(getActorType(actor)) } - .getOrElse { - logger.warn("Can't get max number of messages with trigger class '{}' for actor '{}' which has type '{}'", - triggerClazz, actor, getActorType(actor)) - Int.MaxValue - } + val maxMsgPerActorType = triggerTypeToActorThreshold + .get(triggerClazz) + .flatMap { m => + m.get(getActorType(actor)) + } + .getOrElse { + logger.warn( + "Can't get max number of messages with trigger class '{}' for actor '{}' which has type '{}'", + triggerClazz, + actor, + getActorType(actor) + ) + Int.MaxValue + } if (msgCount > maxMsgPerActorType) { exceedMaxNumberOfMessages.append(st) - logger.warn(s"$st is exceed max number of messages threshold. Trigger type: '$triggerClazz', current count: $msgCount, max: $maxMsgPerActorType") + logger.warn( + s"$st is exceed max number of messages threshold. Trigger type: '$triggerClazz', current count: $msgCount, max: $maxMsgPerActorType" + ) } } - private def updateAndGetNumOfTriggerMessagesPerActor(actor:ActorRef, triggerClazz: Class[_ <: Trigger]): Int = { + private def updateAndGetNumOfTriggerMessagesPerActor(actor: ActorRef, triggerClazz: Class[_ <: Trigger]): Int = { val newCount = actorToTriggerMessages.get(actor) match { case Some(triggerTypeToOccur) => triggerTypeToOccur.get(triggerClazz) match { @@ -206,8 +218,8 @@ class StuckFinder(val cfg: StuckAgentDetection) extends LazyLogging { val transitDriverAgentOpt = t.actorTypeToMaxNumberOfMessages.transitDriverAgent.map { n => "TransitDriverAgent" -> n } - val actorTypeToMaxNumOfMessages = Seq(popilationOpt, rideHailManagerOpt, - rideHailAgentOpt, transitDriverAgentOpt).flatten.toMap + val actorTypeToMaxNumOfMessages = + Seq(popilationOpt, rideHailManagerOpt, rideHailAgentOpt, transitDriverAgentOpt).flatten.toMap val clazz = Class.forName(t.triggerType) (clazz, actorTypeToMaxNumOfMessages) }.toMap diff --git a/src/main/scala/beam/utils/matsim_conversion/MatsimPlanConversion.scala b/src/main/scala/beam/utils/matsim_conversion/MatsimPlanConversion.scala index 6a2875c7603..518f12cfb3b 100755 --- a/src/main/scala/beam/utils/matsim_conversion/MatsimPlanConversion.scala +++ b/src/main/scala/beam/utils/matsim_conversion/MatsimPlanConversion.scala @@ -22,7 +22,10 @@ object MatsimPlanConversion { //Generate vehicles data VehiclesDataConversion.generateFuelTypesDefaults(conversionConfig.scenarioDirectory) val vehiclesWithTypeId = if (conversionConfig.generateVehicles) { - VehiclesDataConversion.generateVehicleTypesDefaults(conversionConfig.scenarioDirectory, VehiclesDataConversion.beamVehicleTypes) + VehiclesDataConversion.generateVehicleTypesDefaults( + conversionConfig.scenarioDirectory, + VehiclesDataConversion.beamVehicleTypes + ) VehiclesDataConversion.generateVehiclesDataFromPersons(persons, conversionConfig) } else { val vehiclesFile = conversionConfig.vehiclesInput.get @@ -60,11 +63,7 @@ object MatsimPlanConversion { XML.save(populationAttrsOutput, populationAttrs, UTF8, xmlDecl = true, populationAttrDoctype) } - def safeGzip(filename: String, - node: Node, - enc: String, - xmlDecl: Boolean = false, - doctype: DocType = null) = { + def safeGzip(filename: String, node: Node, enc: String, xmlDecl: Boolean = false, doctype: DocType = null) = { val output = new FileOutputStream(filename); try { diff --git a/src/main/scala/beam/utils/matsim_conversion/VehiclesDataConversion.scala b/src/main/scala/beam/utils/matsim_conversion/VehiclesDataConversion.scala index 671871c6ccb..915eb97ccc7 100644 --- a/src/main/scala/beam/utils/matsim_conversion/VehiclesDataConversion.scala +++ b/src/main/scala/beam/utils/matsim_conversion/VehiclesDataConversion.scala @@ -279,7 +279,9 @@ object VehiclesDataConversion extends App { val vehicles = (vehiclesDoc \ "vehicle").map { vehicle => Seq(vehicle \@ "id", vehicle \@ "type") } - val beamVehiclesPath = new File("C:\\Users\\sidfe\\current_code\\scala\\BeamCompetitions\\fixed-data\\siouxfalls\\sample\\1k\\vehicles.csv").toString + val beamVehiclesPath = new File( + "C:\\Users\\sidfe\\current_code\\scala\\BeamCompetitions\\fixed-data\\siouxfalls\\sample\\1k\\vehicles.csv" + ).toString writeCsvFile(beamVehiclesPath, vehicles, beamVehicleTitles) vehicles } diff --git a/src/main/scala/beam/utils/plan/PlansBuilder.scala b/src/main/scala/beam/utils/plan/PlansBuilder.scala index d4fac2ca7ff..91bd99ba105 100644 --- a/src/main/scala/beam/utils/plan/PlansBuilder.scala +++ b/src/main/scala/beam/utils/plan/PlansBuilder.scala @@ -22,7 +22,7 @@ import org.matsim.households._ import org.matsim.utils.objectattributes.{ObjectAttributes, ObjectAttributesXmlWriter} import org.matsim.vehicles.{Vehicle, VehicleUtils, VehicleWriterV1, Vehicles} -import scala.collection.{JavaConverters, immutable} +import scala.collection.{immutable, JavaConverters} import scala.collection.JavaConverters._ import scala.util.Random @@ -75,23 +75,24 @@ object PlansBuilder { ScenarioUtils.loadScenario(sc) outDir = args(4) - val srcCSR = if(args.length > 5) args(5) else "epsg:4326" - val tgtCSR = if(args.length > 6) args(6) else "epsg:26910" + val srcCSR = if (args.length > 5) args(5) else "epsg:4326" + val tgtCSR = if (args.length > 6) args(6) else "epsg:26910" utmConverter = UTMConverter(srcCSR, tgtCSR) pop ++= scala.collection.JavaConverters .mapAsScalaMap(sc.getPopulation.getPersons) .values .toVector - val households = new SynthHouseholdParser(utmConverter){ + val households = new SynthHouseholdParser(utmConverter) { override def parseFile(synthFileName: String): Vector[SynthHousehold] = { val resHHMap = scala.collection.mutable.Map[String, SynthHousehold]() val nodes = sc.getNetwork.getNodes.values().toArray(new Array[Node](0)) for (indId <- 0 to sampleNumber) { - val node = nodes(rand.nextInt(nodes.length-1)).getCoord - val row = Array(indId.toString, //indId + val node = nodes(rand.nextInt(nodes.length - 1)).getCoord + val row = Array( + indId.toString, //indId rand.nextInt(sampleNumber).toString, //hhId rand.nextInt(4).toString, //hhNum rand.nextInt(3).toString, //carNum @@ -102,14 +103,15 @@ object PlansBuilder { 0.toString, //hhTract node.getX.toString, //coord.x node.getY.toString, //coord.y - (rand.nextDouble() * 23).toString) //time + (rand.nextDouble() * 23).toString + ) //time - val hhIdStr = row(1) - resHHMap.get(hhIdStr) match { - case Some(hh: SynthHousehold) => hh.addIndividual(parseIndividual(row)) - case None => resHHMap += (hhIdStr -> parseHousehold(row, hhIdStr)) - } + val hhIdStr = row(1) + resHHMap.get(hhIdStr) match { + case Some(hh: SynthHousehold) => hh.addIndividual(parseIndividual(row)) + case None => resHHMap += (hhIdStr -> parseHousehold(row, hhIdStr)) } + } resHHMap.values.toVector } @@ -179,7 +181,7 @@ object PlansBuilder { var ranks: immutable.Seq[Int] = 0 to sh.individuals.length ranks = Random.shuffle(ranks) - for(idx <- 0 until numPersons) { + for (idx <- 0 until numPersons) { val synthPerson = sh.individuals.toVector(idx) val newPersonId = synthPerson.indId val newPerson = newPop.getFactory.createPerson(newPersonId) @@ -193,7 +195,7 @@ object PlansBuilder { newPerson.addPlan(newPlan) PopulationUtils.copyFromTo(pop(idx % pop.size).getPlans.get(0), newPlan) val homeActs = newPlan.getPlanElements.asScala - .collect{ case activity: Activity if activity.getType.equalsIgnoreCase("Home") => activity } + .collect { case activity: Activity if activity.getType.equalsIgnoreCase("Home") => activity } homePlan match { case None => @@ -225,7 +227,6 @@ object PlansBuilder { counter.printCounter() counter.reset() - new HouseholdsWriterV10(newHH).writeFile(s"$outDir/households.xml.gz") new PopulationWriter(newPop).write(s"$outDir/population.xml.gz") PopulationWriterCSV(newPop).write(s"$outDir/population.csv.gz") @@ -237,7 +238,6 @@ object PlansBuilder { out.close() } - /** * This script is designed to create input data for BEAM. It expects the following inputs [provided in order of * command-line args]: diff --git a/src/main/scala/beam/utils/plan/sampling/AvailableModeUtils.scala b/src/main/scala/beam/utils/plan/sampling/AvailableModeUtils.scala index 48304e8211c..560050ad531 100644 --- a/src/main/scala/beam/utils/plan/sampling/AvailableModeUtils.scala +++ b/src/main/scala/beam/utils/plan/sampling/AvailableModeUtils.scala @@ -41,10 +41,10 @@ object AvailableModeUtils { } def isModeAvailableForPerson[T <: BeamMode]( - person: Person, - vehicleId: Id[Vehicle], - mode: BeamMode - ): Boolean = { + person: Person, + vehicleId: Id[Vehicle], + mode: BeamMode + ): Boolean = { AvailableModeUtils.availableModesForPerson(person).contains(mode) } diff --git a/src/main/scala/beam/utils/plan/sampling/PlansSamplerApp.scala b/src/main/scala/beam/utils/plan/sampling/PlansSamplerApp.scala index 547a35b938d..8cd1fb97e8b 100644 --- a/src/main/scala/beam/utils/plan/sampling/PlansSamplerApp.scala +++ b/src/main/scala/beam/utils/plan/sampling/PlansSamplerApp.scala @@ -32,7 +32,7 @@ import org.matsim.vehicles.{Vehicle, VehicleUtils, VehicleWriterV1, Vehicles} import org.opengis.feature.simple.SimpleFeature import org.opengis.referencing.crs.CoordinateReferenceSystem -import scala.collection.{JavaConverters, immutable} +import scala.collection.{immutable, JavaConverters} import scala.collection.JavaConverters._ import scala.util.Random @@ -51,7 +51,7 @@ case class SynthHousehold( } } -case class SynthIndividual(indId: Id[Person], sex: Int, age: Int, valueOfTime: Double, income:Double) +case class SynthIndividual(indId: Id[Person], sex: Int, age: Int, valueOfTime: Double, income: Double) class SynthHouseholdParser(geoConverter: GeoConverter) { @@ -81,8 +81,8 @@ class SynthHouseholdParser(geoConverter: GeoConverter) { resHHMap.values.toVector } - def parseSex(raw_sex:String):Int={ - if(raw_sex=="M") 0 else 1 + def parseSex(raw_sex: String): Int = { + if (raw_sex == "M") 0 else 1 } def parseIndividual(row: Array[String]): SynthIndividual = { @@ -90,7 +90,7 @@ class SynthHouseholdParser(geoConverter: GeoConverter) { Id.createPersonId(row(indIdIdx)), parseSex(row(indSexIdx)), row(indAgeIdx).toInt, - if(row.length==12) {row(indValTime).toDouble} else 18.0, + if (row.length == 12) { row(indValTime).toDouble } else 18.0, row(indIncomeIdx).toDouble ) } @@ -190,7 +190,7 @@ object HasXY { } trait GeoConverter { - def transform(coord: Coord) : Coord + def transform(coord: Coord): Coord } case class WGSConverter(sourceCRS: String, targetCRS: String) extends GeoConverter { @@ -489,7 +489,7 @@ object PlansSampler { newPerson.addPlan(newPlan) PopulationUtils.copyFromTo(plan, newPlan) val homeActs = newPlan.getPlanElements.asScala - .collect{ case activity: Activity if activity.getType.equalsIgnoreCase("Home") => activity } + .collect { case activity: Activity if activity.getType.equalsIgnoreCase("Home") => activity } homePlan match { case None => @@ -515,7 +515,7 @@ object PlansSampler { PersonUtils.setSex(newPerson, sex) newPopAttributes .putAttribute(newPerson.getId.toString, "valueOfTime", synthPerson.valueOfTime) - newPopAttributes.putAttribute(newPerson.getId.toString, "income",synthPerson.income) + newPopAttributes.putAttribute(newPerson.getId.toString, "income", synthPerson.income) addModeExclusions(newPerson) } diff --git a/src/test/scala/beam/agentsim/SingleModeSpec.scala b/src/test/scala/beam/agentsim/SingleModeSpec.scala index ea78101ba80..e87ec36bd7c 100755 --- a/src/test/scala/beam/agentsim/SingleModeSpec.scala +++ b/src/test/scala/beam/agentsim/SingleModeSpec.scala @@ -37,16 +37,16 @@ import scala.language.postfixOps // TODO: probably test needs to be updated due to update in rideHailManager @Ignore class SingleModeSpec - extends TestKit( - ActorSystem( - "single-mode-test", - ConfigFactory.parseString( - """ + extends TestKit( + ActorSystem( + "single-mode-test", + ConfigFactory.parseString( + """ akka.test.timefactor=10 """ + ) ) ) - ) with WordSpecLike with Matchers with ImplicitSender @@ -132,13 +132,14 @@ class SingleModeSpec "let everybody walk when their plan says so" in { scenario.getPopulation.getPersons .values() - .forEach { person => { - person.getSelectedPlan.getPlanElements.asScala.collect { - case leg: Leg => - leg.setMode("walk") + .forEach { person => + { + person.getSelectedPlan.getPlanElements.asScala.collect { + case leg: Leg => + leg.setMode("walk") + } } } - } val events = mutable.ListBuffer[Event]() val eventsManager = EventsUtils.createEventsManager() eventsManager.addHandler( @@ -210,34 +211,35 @@ class SingleModeSpec // We want to make sure that our car is returned home. scenario.getPopulation.getPersons .values() - .forEach { person => { - val newPlanElements = person.getSelectedPlan.getPlanElements.asScala.collect { - case activity: Activity if activity.getType == "Home" => - Seq(activity, scenario.getPopulation.getFactory.createLeg("drive_transit")) - case activity: Activity => - Seq(activity) - case leg: Leg => - Nil - }.flatten - if (newPlanElements.last.isInstanceOf[Leg]) { - newPlanElements.remove(newPlanElements.size - 1) - } - person.getSelectedPlan.getPlanElements.clear() - newPlanElements.foreach { - case activity: Activity => - person.getSelectedPlan.addActivity(activity) - case leg: Leg => - person.getSelectedPlan.addLeg(leg) + .forEach { person => + { + val newPlanElements = person.getSelectedPlan.getPlanElements.asScala.collect { + case activity: Activity if activity.getType == "Home" => + Seq(activity, scenario.getPopulation.getFactory.createLeg("drive_transit")) + case activity: Activity => + Seq(activity) + case leg: Leg => + Nil + }.flatten + if (newPlanElements.last.isInstanceOf[Leg]) { + newPlanElements.remove(newPlanElements.size - 1) + } + person.getSelectedPlan.getPlanElements.clear() + newPlanElements.foreach { + case activity: Activity => + person.getSelectedPlan.addActivity(activity) + case leg: Leg => + person.getSelectedPlan.addLeg(leg) + } } } - } val events = mutable.ListBuffer[Event]() val eventsManager = EventsUtils.createEventsManager() eventsManager.addHandler( new BasicEventHandler { override def handleEvent(event: Event): Unit = { event match { - case event@(_: PersonDepartureEvent | _: ActivityEndEvent) => + case event @ (_: PersonDepartureEvent | _: ActivityEndEvent) => events += event case _ => } diff --git a/src/test/scala/beam/agentsim/agents/GenericEventsSpec.scala b/src/test/scala/beam/agentsim/agents/GenericEventsSpec.scala index f74755da881..fb628ead2ed 100755 --- a/src/test/scala/beam/agentsim/agents/GenericEventsSpec.scala +++ b/src/test/scala/beam/agentsim/agents/GenericEventsSpec.scala @@ -38,7 +38,6 @@ trait GenericEventsSpec extends WordSpecLike with IntegrationSpecCommon with Bea module(baseConfig, scenario, networkCoordinator) ) - beamServices = injector.getInstance(classOf[BeamServices]) val popAdjustment = DefaultPopulationAdjustment(beamServices) popAdjustment.update(scenario) diff --git a/src/test/scala/beam/agentsim/agents/OtherPersonAgentSpec.scala b/src/test/scala/beam/agentsim/agents/OtherPersonAgentSpec.scala index 6b3fc7025d0..3942a1192f3 100755 --- a/src/test/scala/beam/agentsim/agents/OtherPersonAgentSpec.scala +++ b/src/test/scala/beam/agentsim/agents/OtherPersonAgentSpec.scala @@ -53,17 +53,16 @@ import scala.concurrent.Await * Created by sfeygin on 2/7/17. */ class OtherPersonAgentSpec - extends TestKit( - ActorSystem( - "OtherPersonAgentSpec", - ConfigFactory.parseString( - """ + extends TestKit( + ActorSystem( + "OtherPersonAgentSpec", + ConfigFactory.parseString(""" akka.log-dead-letters = 10 akka.actor.debug.fsm = true akka.loglevel = debug """).withFallback(testConfig("test/input/beamville/beam.conf")) + ) ) - ) with FunSpecLike with BeforeAndAfterAll with MockitoSugar @@ -95,7 +94,10 @@ class OtherPersonAgentSpec } private lazy val modeChoiceCalculator = new ModeChoiceCalculator { - override def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = + override def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = Some(alternatives.head) override val beamServices: BeamServices = beamSvc @@ -103,11 +105,11 @@ class OtherPersonAgentSpec override def utilityOf(alternative: EmbodiedBeamTrip, attributesOfIndividual: AttributesOfIndividual): Double = 0.0 override def utilityOf( - mode: BeamMode, - cost: Double, - time: Double, - numTransfers: Int - ): Double = 0.0 + mode: BeamMode, + cost: Double, + time: Double, + numTransfers: Int + ): Double = 0.0 } // Mock a transit driver (who has to be a child of a mock router) diff --git a/src/test/scala/beam/agentsim/agents/PersonAgentSpec.scala b/src/test/scala/beam/agentsim/agents/PersonAgentSpec.scala index 18fbdf5ea8e..9e05a3c35e7 100644 --- a/src/test/scala/beam/agentsim/agents/PersonAgentSpec.scala +++ b/src/test/scala/beam/agentsim/agents/PersonAgentSpec.scala @@ -55,20 +55,20 @@ import scala.collection.{mutable, JavaConverters} import scala.concurrent.Await class PersonAgentSpec - extends TestKit( - ActorSystem( - name = "PersonAgentSpec", - config = ConfigFactory - .parseString( - """ + extends TestKit( + ActorSystem( + name = "PersonAgentSpec", + config = ConfigFactory + .parseString( + """ akka.log-dead-letters = 10 akka.actor.debug.fsm = true akka.loglevel = debug """ - ) - .withFallback(testConfig("test/input/beamville/beam.conf")) + ) + .withFallback(testConfig("test/input/beamville/beam.conf")) + ) ) - ) with FunSpecLike with BeforeAndAfterAll with MockitoSugar @@ -97,7 +97,10 @@ class PersonAgentSpec } private lazy val modeChoiceCalculator = new ModeChoiceCalculator { - override def apply(alternatives: IndexedSeq[EmbodiedBeamTrip], attributesOfIndividual: AttributesOfIndividual): Option[EmbodiedBeamTrip] = + override def apply( + alternatives: IndexedSeq[EmbodiedBeamTrip], + attributesOfIndividual: AttributesOfIndividual + ): Option[EmbodiedBeamTrip] = Some(alternatives.head) override val beamServices: BeamServices = beamSvc @@ -266,19 +269,26 @@ class PersonAgentSpec itineraries = Vector( EmbodiedBeamTrip( legs = Vector( - EmbodiedBeamLeg(beamLeg = BeamLeg( - startTime = 28800, - mode = BeamMode.WALK, - duration = 100, - travelPath = BeamPath( - linkIds = Vector(1, 2), - linkTravelTime = Vector(10, 10), // TODO FIXME - transitStops = None, - startPoint = SpaceTime(0.0, 0.0, 28800), - endPoint = SpaceTime(1.0, 1.0, 28900), - distanceInM = 1000D - ) - ), beamVehicleId = dummyAgentVehicleId, asDriver = true, passengerSchedule = None, cost = ZERO, unbecomeDriverOnCompletion = true) + EmbodiedBeamLeg( + beamLeg = BeamLeg( + startTime = 28800, + mode = BeamMode.WALK, + duration = 100, + travelPath = BeamPath( + linkIds = Vector(1, 2), + linkTravelTime = Vector(10, 10), // TODO FIXME + transitStops = None, + startPoint = SpaceTime(0.0, 0.0, 28800), + endPoint = SpaceTime(1.0, 1.0, 28900), + distanceInM = 1000D + ) + ), + beamVehicleId = dummyAgentVehicleId, + asDriver = true, + passengerSchedule = None, + cost = ZERO, + unbecomeDriverOnCompletion = true + ) ) ) ), @@ -484,45 +494,66 @@ class PersonAgentSpec vehicles.put(bus.getId, bus) vehicles.put(tram.getId, tram) - val busLeg = EmbodiedBeamLeg(BeamLeg( - startTime = 28800, - mode = BeamMode.BUS, - duration = 600, - travelPath = BeamPath( - Vector(), - Vector(), - Some(TransitStopsInfo(1, busId, 2)), - SpaceTime(new Coord(166321.9, 1568.87), 28800), - SpaceTime(new Coord(167138.4, 1117), 29400), - 1.0 - ) - ), beamVehicleId = busId, asDriver = false, passengerSchedule = None, cost = ZERO, unbecomeDriverOnCompletion = false) - val busLeg2 = EmbodiedBeamLeg(beamLeg = BeamLeg( - startTime = 29400, - mode = BeamMode.BUS, - duration = 600, - travelPath = BeamPath( - Vector(), - Vector(), - Some(TransitStopsInfo(2, busId, 3)), - SpaceTime(new Coord(167138.4, 1117), 29400), - SpaceTime(new Coord(180000.4, 1200), 30000), - 1.0 - ) - ), beamVehicleId = busId, asDriver = false, passengerSchedule = None, cost = ZERO, unbecomeDriverOnCompletion = false) - val tramLeg = EmbodiedBeamLeg(beamLeg = BeamLeg( - startTime = 30000, - mode = BeamMode.TRAM, - duration = 600, - travelPath = BeamPath( - linkIds = Vector(), - linkTravelTime = Vector(), - transitStops = Some(TransitStopsInfo(3, tramId, 4)), - startPoint = SpaceTime(new Coord(180000.4, 1200), 30000), - endPoint = SpaceTime(new Coord(190000.4, 1300), 30600), - distanceInM = 1.0 - ) - ), beamVehicleId = tramId, asDriver = false, passengerSchedule = None, cost = ZERO, unbecomeDriverOnCompletion = false) + val busLeg = EmbodiedBeamLeg( + BeamLeg( + startTime = 28800, + mode = BeamMode.BUS, + duration = 600, + travelPath = BeamPath( + Vector(), + Vector(), + Some(TransitStopsInfo(1, busId, 2)), + SpaceTime(new Coord(166321.9, 1568.87), 28800), + SpaceTime(new Coord(167138.4, 1117), 29400), + 1.0 + ) + ), + beamVehicleId = busId, + asDriver = false, + passengerSchedule = None, + cost = ZERO, + unbecomeDriverOnCompletion = false + ) + val busLeg2 = EmbodiedBeamLeg( + beamLeg = BeamLeg( + startTime = 29400, + mode = BeamMode.BUS, + duration = 600, + travelPath = BeamPath( + Vector(), + Vector(), + Some(TransitStopsInfo(2, busId, 3)), + SpaceTime(new Coord(167138.4, 1117), 29400), + SpaceTime(new Coord(180000.4, 1200), 30000), + 1.0 + ) + ), + beamVehicleId = busId, + asDriver = false, + passengerSchedule = None, + cost = ZERO, + unbecomeDriverOnCompletion = false + ) + val tramLeg = EmbodiedBeamLeg( + beamLeg = BeamLeg( + startTime = 30000, + mode = BeamMode.TRAM, + duration = 600, + travelPath = BeamPath( + linkIds = Vector(), + linkTravelTime = Vector(), + transitStops = Some(TransitStopsInfo(3, tramId, 4)), + startPoint = SpaceTime(new Coord(180000.4, 1200), 30000), + endPoint = SpaceTime(new Coord(190000.4, 1300), 30600), + distanceInM = 1.0 + ) + ), + beamVehicleId = tramId, + asDriver = false, + passengerSchedule = None, + cost = ZERO, + unbecomeDriverOnCompletion = false + ) val household = householdsFactory.createHousehold(hoseHoldDummyId) val population = PopulationUtils.createPopulation(ConfigUtils.createConfig()) @@ -605,35 +636,49 @@ class PersonAgentSpec itineraries = Vector( EmbodiedBeamTrip( legs = Vector( - EmbodiedBeamLeg(beamLeg = BeamLeg( - startTime = 28800, - mode = BeamMode.WALK, - duration = 0, - travelPath = BeamPath( - linkIds = Vector(), - linkTravelTime = Vector(), - transitStops = None, - startPoint = SpaceTime(new Coord(166321.9, 1568.87), 28800), - endPoint = SpaceTime(new Coord(167138.4, 1117), 28800), - distanceInM = 1D - ) - ), beamVehicleId = dummyAgentVehicleId, asDriver = true, passengerSchedule = None, cost = ZERO, unbecomeDriverOnCompletion = false), + EmbodiedBeamLeg( + beamLeg = BeamLeg( + startTime = 28800, + mode = BeamMode.WALK, + duration = 0, + travelPath = BeamPath( + linkIds = Vector(), + linkTravelTime = Vector(), + transitStops = None, + startPoint = SpaceTime(new Coord(166321.9, 1568.87), 28800), + endPoint = SpaceTime(new Coord(167138.4, 1117), 28800), + distanceInM = 1D + ) + ), + beamVehicleId = dummyAgentVehicleId, + asDriver = true, + passengerSchedule = None, + cost = ZERO, + unbecomeDriverOnCompletion = false + ), busLeg, busLeg2, tramLeg, - EmbodiedBeamLeg(beamLeg = BeamLeg( - startTime = 30600, - mode = BeamMode.WALK, - duration = 0, - travelPath = BeamPath( - linkIds = Vector(), - linkTravelTime = Vector(), - transitStops = None, - startPoint = SpaceTime(new Coord(167138.4, 1117), 30600), - endPoint = SpaceTime(new Coord(167138.4, 1117), 30600), - distanceInM = 1D - ) - ), beamVehicleId = dummyAgentVehicleId, asDriver = true, passengerSchedule = None, cost = ZERO, unbecomeDriverOnCompletion = false) + EmbodiedBeamLeg( + beamLeg = BeamLeg( + startTime = 30600, + mode = BeamMode.WALK, + duration = 0, + travelPath = BeamPath( + linkIds = Vector(), + linkTravelTime = Vector(), + transitStops = None, + startPoint = SpaceTime(new Coord(167138.4, 1117), 30600), + endPoint = SpaceTime(new Coord(167138.4, 1117), 30600), + distanceInM = 1D + ) + ), + beamVehicleId = dummyAgentVehicleId, + asDriver = true, + passengerSchedule = None, + cost = ZERO, + unbecomeDriverOnCompletion = false + ) ) ) ), diff --git a/src/test/scala/beam/agentsim/agents/ridehail/RideHailPassengersEventsSpec.scala b/src/test/scala/beam/agentsim/agents/ridehail/RideHailPassengersEventsSpec.scala index 1f4ceb21603..e229f16fffc 100755 --- a/src/test/scala/beam/agentsim/agents/ridehail/RideHailPassengersEventsSpec.scala +++ b/src/test/scala/beam/agentsim/agents/ridehail/RideHailPassengersEventsSpec.scala @@ -43,7 +43,6 @@ class RideHailPassengersEventsSpec extends WordSpecLike with Matchers with BeamH val beamServices: BeamServices = injector.getInstance(classOf[BeamServices]) - val eventManager: EventsManager = injector.getInstance(classOf[EventsManager]) eventManager.addHandler(eventHandler) diff --git a/src/test/scala/beam/agentsim/agents/ridehail/graph/ModeChosenStatsGraphSpec.scala b/src/test/scala/beam/agentsim/agents/ridehail/graph/ModeChosenStatsGraphSpec.scala index d64048dea27..d06368809fd 100644 --- a/src/test/scala/beam/agentsim/agents/ridehail/graph/ModeChosenStatsGraphSpec.scala +++ b/src/test/scala/beam/agentsim/agents/ridehail/graph/ModeChosenStatsGraphSpec.scala @@ -25,8 +25,10 @@ import scala.concurrent.Promise object ModeChosenStatsGraphSpec { - class ModeChosenStatsGraph(compute: ModeChosenAnalysis.ModeChosenComputation with EventAnalyzer, beamConfig: BeamConfig) - extends BasicEventHandler + class ModeChosenStatsGraph( + compute: ModeChosenAnalysis.ModeChosenComputation with EventAnalyzer, + beamConfig: BeamConfig + ) extends BasicEventHandler with IterationEndsListener { private lazy val modeChosenStats = diff --git a/src/test/scala/beam/agentsim/agents/ridehail/graph/PersonTravelTimeStatsGraphSpec.scala b/src/test/scala/beam/agentsim/agents/ridehail/graph/PersonTravelTimeStatsGraphSpec.scala index 7157debc10f..f952742f687 100644 --- a/src/test/scala/beam/agentsim/agents/ridehail/graph/PersonTravelTimeStatsGraphSpec.scala +++ b/src/test/scala/beam/agentsim/agents/ridehail/graph/PersonTravelTimeStatsGraphSpec.scala @@ -1,7 +1,10 @@ package beam.agentsim.agents.ridehail.graph import java.{lang, util} -import beam.agentsim.agents.ridehail.graph.PersonTravelTimeStatsGraphSpec.{PersonTravelTimeStatsGraph, StatsValidationHandler} +import beam.agentsim.agents.ridehail.graph.PersonTravelTimeStatsGraphSpec.{ + PersonTravelTimeStatsGraph, + StatsValidationHandler +} import beam.analysis.plots.PersonTravelTimeAnalysis import beam.integration.IntegrationSpecCommon import beam.utils.MathUtils diff --git a/src/test/scala/beam/agentsim/agents/ridehail/graph/RideHailingWaitingSingleStatsSpec.scala b/src/test/scala/beam/agentsim/agents/ridehail/graph/RideHailingWaitingSingleStatsSpec.scala index 988ac53a1e9..d02ec263865 100644 --- a/src/test/scala/beam/agentsim/agents/ridehail/graph/RideHailingWaitingSingleStatsSpec.scala +++ b/src/test/scala/beam/agentsim/agents/ridehail/graph/RideHailingWaitingSingleStatsSpec.scala @@ -1,7 +1,10 @@ package beam.agentsim.agents.ridehail.graph import java.{lang, util} -import beam.agentsim.agents.ridehail.graph.RideHailingWaitingSingleStatsSpec.{RideHailingWaitingSingleGraph, StatsValidationHandler} +import beam.agentsim.agents.ridehail.graph.RideHailingWaitingSingleStatsSpec.{ + RideHailingWaitingSingleGraph, + StatsValidationHandler +} import beam.agentsim.events.ModeChoiceEvent import beam.analysis.plots.RideHailingWaitingSingleAnalysis import beam.integration.IntegrationSpecCommon diff --git a/src/test/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManagerTest.scala b/src/test/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManagerTest.scala index 8eb455b19d0..11a02fdf7fe 100644 --- a/src/test/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManagerTest.scala +++ b/src/test/scala/beam/agentsim/infrastructure/IndexerForZonalParkingManagerTest.scala @@ -4,8 +4,11 @@ import beam.sim.BeamServices import org.scalatest.{Matchers, WordSpec} import scala.collection.JavaConverters._ + class IndexerForZonalParkingManagerTest extends WordSpec with Matchers { - val tazTreeMap: TAZTreeMap = BeamServices.getTazTreeMap("test/test-resources/beam/agentsim/infrastructure/taz-centers.csv") + + val tazTreeMap: TAZTreeMap = + BeamServices.getTazTreeMap("test/test-resources/beam/agentsim/infrastructure/taz-centers.csv") val tazes = tazTreeMap.tazQuadTree.values().asScala.toVector val map = getMap(tazTreeMap) @@ -46,12 +49,13 @@ class IndexerForZonalParkingManagerTest extends WordSpec with Matchers { // Index for filter has two dimensions: // tazId: Id[TAZ] , |tazId| = number of unique taz ids // reservedFor: ReservedParkingType, |ReservedParkingType| = 2 - idxForFilter.keys.groupBy(_.tazId).size should be (numOfTazIds) - idxForFilter.keys.groupBy(_.reservedFor).size should be (numOfReservedParkingType) + idxForFilter.keys.groupBy(_.tazId).size should be(numOfTazIds) + idxForFilter.keys.groupBy(_.reservedFor).size should be(numOfReservedParkingType) - map.foreach { case (attr, _) => - val key = IndexForFilter(tazId = attr.tazId, reservedFor = attr.reservedFor) - idxForFilter.contains(key) should be (true) + map.foreach { + case (attr, _) => + val key = IndexForFilter(tazId = attr.tazId, reservedFor = attr.reservedFor) + idxForFilter.contains(key) should be(true) } } @@ -64,15 +68,20 @@ class IndexerForZonalParkingManagerTest extends WordSpec with Matchers { // pricingModel: PricingModel , |PricingModel| = 2 // reservedFor: ReservedParkingType , |ReservedParkingType| = 2 - idxForFind.keys.groupBy(_.tazId).size should be (numOfTazIds) - idxForFind.keys.groupBy(_.parkingType).size should be (numOfParkingTypes) - idxForFind.keys.groupBy(_.pricingModel).size should be (numOfPricingModels) - idxForFind.keys.groupBy(_.reservedFor).size should be (numOfReservedParkingType) + idxForFind.keys.groupBy(_.tazId).size should be(numOfTazIds) + idxForFind.keys.groupBy(_.parkingType).size should be(numOfParkingTypes) + idxForFind.keys.groupBy(_.pricingModel).size should be(numOfPricingModels) + idxForFind.keys.groupBy(_.reservedFor).size should be(numOfReservedParkingType) - map.foreach { case (attr, _) => - val key = IndexForFind(tazId = attr.tazId, parkingType = attr.parkingType, pricingModel = attr.pricingModel, - reservedFor = attr.reservedFor) - idxForFind.contains(key) should be (true) + map.foreach { + case (attr, _) => + val key = IndexForFind( + tazId = attr.tazId, + parkingType = attr.parkingType, + pricingModel = attr.pricingModel, + reservedFor = attr.reservedFor + ) + idxForFind.contains(key) should be(true) } } } diff --git a/src/test/scala/beam/calibration/BeamSigoptTunerSpec.scala b/src/test/scala/beam/calibration/BeamSigoptTunerSpec.scala index 111d29409ca..92dc0ab4cec 100755 --- a/src/test/scala/beam/calibration/BeamSigoptTunerSpec.scala +++ b/src/test/scala/beam/calibration/BeamSigoptTunerSpec.scala @@ -26,7 +26,6 @@ class BeamSigoptTunerSpec extends WordSpecLike with Matchers with BeforeAndAfter val TEST_BEAM_EXPERIMENT_LOC = "test/input/beamville/example-calibration/experiment.yml" val TEST_BEAM_BENCHMARK_DATA_LOC = "test/input/beamville/example-calibration/benchmark.csv" - "BeamSigoptTuner" ignore { "create a proper experiment def from the test experiment specification file" taggedAs Periodic in { @@ -38,19 +37,20 @@ class BeamSigoptTunerSpec extends WordSpecLike with Matchers with BeforeAndAfter } "create an experiment in the SigOpt API" taggedAs Periodic in { - wrapWithTestExperiment { experimentData => { - val expParams = experimentData.experiment.getParameters - // First is the rideHailParams - val rideHailParams = expParams.iterator.next - rideHailParams.getName equals "beam.agentsim.agents.rideHail.numDriversAsFractionOfPopulation" - rideHailParams.getBounds.getMax equals 0.1 - rideHailParams.getBounds.getMin equals 0.001 - // Second is transitCapacityParams - val transitCapacityParams = expParams.iterator.next - transitCapacityParams.getName equals "beam.agentsim.agents.rideHail.numDriversAsFractionOfPopulation" - transitCapacityParams.getBounds.getMax equals 0.1 - transitCapacityParams.getBounds.getMin equals 0.001 - } + wrapWithTestExperiment { experimentData => + { + val expParams = experimentData.experiment.getParameters + // First is the rideHailParams + val rideHailParams = expParams.iterator.next + rideHailParams.getName equals "beam.agentsim.agents.rideHail.numDriversAsFractionOfPopulation" + rideHailParams.getBounds.getMax equals 0.1 + rideHailParams.getBounds.getMin equals 0.001 + // Second is transitCapacityParams + val transitCapacityParams = expParams.iterator.next + transitCapacityParams.getName equals "beam.agentsim.agents.rideHail.numDriversAsFractionOfPopulation" + transitCapacityParams.getBounds.getMax equals 0.1 + transitCapacityParams.getBounds.getMin equals 0.001 + } } } diff --git a/src/test/scala/beam/router/RoutingModelSpec.scala b/src/test/scala/beam/router/RoutingModelSpec.scala index eb1e9825ddf..3c7915b26ee 100755 --- a/src/test/scala/beam/router/RoutingModelSpec.scala +++ b/src/test/scala/beam/router/RoutingModelSpec.scala @@ -13,12 +13,19 @@ class RoutingModelSpec extends FlatSpec with Matchers { it should "produce link events from a typical car leg, given a constant travel time function" in { def travelTime(enterTime: Int, linkId: Int) = 1000 - val leg = EmbodiedBeamLeg(BeamLeg( - 0, - BeamMode.CAR, - 0, - BeamPath(Vector(1, 2, 3, 4, 5), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0) - ), Id.createVehicleId(13), asDriver = true, None, 0, unbecomeDriverOnCompletion = true) + val leg = EmbodiedBeamLeg( + BeamLeg( + 0, + BeamMode.CAR, + 0, + BeamPath(Vector(1, 2, 3, 4, 5), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0) + ), + Id.createVehicleId(13), + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = true + ) RoutingModel .traverseStreetLeg(leg.beamLeg, leg.beamVehicleId, travelTime) .toStream should contain theSameElementsAs Vector( @@ -37,12 +44,19 @@ class RoutingModelSpec extends FlatSpec with Matchers { def travelTime(enterTime: Int, linkId: Int) = if (enterTime < 2000) 1000 else 2000 - val leg = EmbodiedBeamLeg(BeamLeg( - 0, - BeamMode.CAR, - 0, - BeamPath(Vector(1, 2, 3, 4, 5), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0) - ), Id.createVehicleId(13), asDriver = true, None, 0, unbecomeDriverOnCompletion = true) + val leg = EmbodiedBeamLeg( + BeamLeg( + 0, + BeamMode.CAR, + 0, + BeamPath(Vector(1, 2, 3, 4, 5), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0) + ), + Id.createVehicleId(13), + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = true + ) RoutingModel .traverseStreetLeg(leg.beamLeg, leg.beamVehicleId, travelTime) .toStream should contain theSameElementsAs Vector( @@ -60,12 +74,19 @@ class RoutingModelSpec extends FlatSpec with Matchers { it should "produce just one pair of link events for a leg which crosses just one node, spending no time" in { def travelTime(enterTime: Int, linkId: Int) = 1000 - val leg = EmbodiedBeamLeg(BeamLeg( - 0, - BeamMode.CAR, - 0, - BeamPath(Vector(1, 2), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0) - ), Id.createVehicleId(13), asDriver = true, None, 0, unbecomeDriverOnCompletion = true) + val leg = EmbodiedBeamLeg( + BeamLeg( + 0, + BeamMode.CAR, + 0, + BeamPath(Vector(1, 2), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0) + ), + Id.createVehicleId(13), + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = true + ) RoutingModel .traverseStreetLeg(leg.beamLeg, leg.beamVehicleId, travelTime) .toStream should contain theSameElementsAs Vector( @@ -77,7 +98,14 @@ class RoutingModelSpec extends FlatSpec with Matchers { it should "produce an empty sequence of link events from a car leg which stays on one link" in { def travelTime(enterTime: Int, linkId: Int) = 1000 - val leg = EmbodiedBeamLeg(BeamLeg(0, BeamMode.CAR, 0, BeamPath(Vector(1), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0)), Id.createVehicleId(13), asDriver = true, None, 0, unbecomeDriverOnCompletion = true) + val leg = EmbodiedBeamLeg( + BeamLeg(0, BeamMode.CAR, 0, BeamPath(Vector(1), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0)), + Id.createVehicleId(13), + asDriver = true, + None, + 0, + unbecomeDriverOnCompletion = true + ) RoutingModel .traverseStreetLeg(leg.beamLeg, leg.beamVehicleId, travelTime) .toStream should be( @@ -88,7 +116,14 @@ class RoutingModelSpec extends FlatSpec with Matchers { it should "produce an empty sequence of link events from a car leg which is empty" in { def travelTime(enterTime: Int, linkId: Int) = 1000 - val leg = EmbodiedBeamLeg(beamLeg = BeamLeg(0, BeamMode.CAR, 0, BeamPath(Vector(), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0)), beamVehicleId = Id.createVehicleId(13), asDriver = true, passengerSchedule = None, cost = 0, unbecomeDriverOnCompletion = true) + val leg = EmbodiedBeamLeg( + beamLeg = BeamLeg(0, BeamMode.CAR, 0, BeamPath(Vector(), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0)), + beamVehicleId = Id.createVehicleId(13), + asDriver = true, + passengerSchedule = None, + cost = 0, + unbecomeDriverOnCompletion = true + ) RoutingModel .traverseStreetLeg(leg.beamLeg, leg.beamVehicleId, travelTime) .toStream should be( @@ -98,7 +133,14 @@ class RoutingModelSpec extends FlatSpec with Matchers { it should "produce travel and distance estimates from links that match router" in { def travelTime(enterTime: Int, linkId: Int) = 1000 - val leg = EmbodiedBeamLeg(beamLeg = BeamLeg(0, BeamMode.CAR, 0, BeamPath(Vector(), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0)), beamVehicleId = Id.createVehicleId(13), asDriver = true, passengerSchedule = None, cost = 0, unbecomeDriverOnCompletion = true) + val leg = EmbodiedBeamLeg( + beamLeg = BeamLeg(0, BeamMode.CAR, 0, BeamPath(Vector(), Vector(), None, SpaceTime.zero, SpaceTime.zero, 10.0)), + beamVehicleId = Id.createVehicleId(13), + asDriver = true, + passengerSchedule = None, + cost = 0, + unbecomeDriverOnCompletion = true + ) RoutingModel.traverseStreetLeg(leg.beamLeg, leg.beamVehicleId, travelTime).toStream should be( 'empty ) diff --git a/src/test/scala/beam/router/TimeDependentRoutingSpec.scala b/src/test/scala/beam/router/TimeDependentRoutingSpec.scala index 75f9cce2631..63de41fa0fa 100755 --- a/src/test/scala/beam/router/TimeDependentRoutingSpec.scala +++ b/src/test/scala/beam/router/TimeDependentRoutingSpec.scala @@ -57,7 +57,12 @@ class TimeDependentRoutingSpec val scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()) when(services.beamConfig).thenReturn(beamConfig) when(services.geo).thenReturn(new GeoUtilsImpl(services)) - when(services.dates).thenReturn(DateUtils(ZonedDateTime.parse(beamConfig.beam.routing.baseDate).toLocalDateTime, ZonedDateTime.parse(beamConfig.beam.routing.baseDate))) + when(services.dates).thenReturn( + DateUtils( + ZonedDateTime.parse(beamConfig.beam.routing.baseDate).toLocalDateTime, + ZonedDateTime.parse(beamConfig.beam.routing.baseDate) + ) + ) networkCoordinator = new DefaultNetworkCoordinator(beamConfig) networkCoordinator.loadNetwork() networkCoordinator.convertFrequenciesToTrips() @@ -66,8 +71,18 @@ class TimeDependentRoutingSpec when(fareCalculator.getFareSegments(any(), any(), any(), any(), any())).thenReturn(Vector[BeamFareSegment]()) val tollCalculator = mock[TollCalculator] when(tollCalculator.calcTollByOsmIds(any())).thenReturn(0.0) - router = system.actorOf(BeamRouter.props(services, networkCoordinator.transportNetwork, networkCoordinator.network, scenario, - new EventsManagerImpl(), scenario.getTransitVehicles, fareCalculator, tollCalculator)) + router = system.actorOf( + BeamRouter.props( + services, + networkCoordinator.transportNetwork, + networkCoordinator.network, + scenario, + new EventsManagerImpl(), + scenario.getTransitVehicles, + fareCalculator, + tollCalculator + ) + ) within(60 seconds) { // Router can take a while to initialize router ! Identify(0) @@ -81,7 +96,19 @@ class TimeDependentRoutingSpec val time = RoutingModel.DiscreteTime(3000) "give updated travel times for a given route" in { - val leg = BeamLeg(3000, BeamMode.CAR, 0, BeamPath(Vector(143, 60, 58, 62, 80, 74, 68, 154), Vector(), None, SpaceTime(166321.9, 1568.87, 3000), SpaceTime(167138.4, 1117, 3000), 0.0)) + val leg = BeamLeg( + 3000, + BeamMode.CAR, + 0, + BeamPath( + Vector(143, 60, 58, 62, 80, 74, 68, 154), + Vector(), + None, + SpaceTime(166321.9, 1568.87, 3000), + SpaceTime(167138.4, 1117, 3000), + 0.0 + ) + ) router ! EmbodyWithCurrentTravelTime(leg, Id.createVehicleId(1)) val response = expectMsgType[RoutingResponse] assert(response.itineraries.head.beamLegs().head.duration == 70) @@ -90,21 +117,60 @@ class TimeDependentRoutingSpec } "take given link traversal times into account" in { - router ! RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(Id.createVehicleId("car"), new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.CAR, asDriver = true))) + router ! RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + Id.createVehicleId("car"), + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.CAR, + asDriver = true + ) + ) + ) val response = expectMsgType[RoutingResponse] assert(response.itineraries.exists(_.tripClassifier == CAR)) val carOption = response.itineraries.find(_.tripClassifier == CAR).get assert(carOption.totalTravelTimeInSecs == 76) router ! UpdateTravelTimeLocal((_: Link, _: Double, _: Person, _: Vehicle) => 0) // Nice, we can teleport! - router ! RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(Id.createVehicleId("car"), new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.CAR, asDriver = true))) + router ! RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + Id.createVehicleId("car"), + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.CAR, + asDriver = true + ) + ) + ) val response2 = expectMsgType[RoutingResponse] assert(response2.itineraries.exists(_.tripClassifier == CAR)) val carOption2 = response2.itineraries.find(_.tripClassifier == CAR).get assert(carOption2.totalTravelTimeInSecs < 7) // isn't exactly 0, probably rounding errors? router ! UpdateTravelTimeLocal((_: Link, _: Double, _: Person, _: Vehicle) => 1000) // Every link takes 1000 sec to traverse. - router ! RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(Id.createVehicleId("car"), new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.CAR, asDriver = true))) + router ! RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + Id.createVehicleId("car"), + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.CAR, + asDriver = true + ) + ) + ) val response3 = expectMsgType[RoutingResponse] assert(response3.itineraries.exists(_.tripClassifier == CAR)) val carOption3 = response3.itineraries.find(_.tripClassifier == CAR).get @@ -115,11 +181,25 @@ class TimeDependentRoutingSpec // Start with travel times as calculated by a pristine TravelTimeCalculator. // (Should be MATSim free flow travel times) val eventsForTravelTimeCalculator = EventsUtils.createEventsManager() - val travelTimeCalculator = new TravelTimeCalculator(networkCoordinator.network, ConfigUtils.createConfig().travelTimeCalculator()) + val travelTimeCalculator = + new TravelTimeCalculator(networkCoordinator.network, ConfigUtils.createConfig().travelTimeCalculator()) eventsForTravelTimeCalculator.addHandler(travelTimeCalculator) router ! UpdateTravelTimeLocal(travelTimeCalculator.getLinkTravelTimes) val vehicleId = Id.createVehicleId("car") - router ! RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(vehicleId, new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.CAR, asDriver = true))) + router ! RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + vehicleId, + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.CAR, + asDriver = true + ) + ) + ) var carOption = expectMsgType[RoutingResponse].itineraries.find(_.tripClassifier == CAR).get // Now feed the TravelTimeCalculator events resulting from me traversing the proposed route, @@ -140,7 +220,20 @@ class TimeDependentRoutingSpec // Now send the router the travel times resulting from that, and try again. router ! UpdateTravelTimeLocal(travelTimeCalculator.getLinkTravelTimes) - router ! RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(Id.createVehicleId("car"), new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.CAR, asDriver = true))) + router ! RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + Id.createVehicleId("car"), + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.CAR, + asDriver = true + ) + ) + ) carOption = expectMsgType[RoutingResponse].itineraries.find(_.tripClassifier == CAR).getOrElse(carOption) } @@ -149,7 +242,12 @@ class TimeDependentRoutingSpec "give updated travel times for a given route after travel times were updated" in { router ! UpdateTravelTimeLocal((_: Link, _: Double, _: Person, _: Vehicle) => 1000) // Every link takes 1000 sec to traverse. - val leg = BeamLeg(28800, BeamMode.WALK, 0, BeamPath(Vector(1, 2, 3, 4), Vector(), None, SpaceTime(0.0, 0.0, 28800), SpaceTime(1.0, 1.0, 28900), 1000.0)) + val leg = BeamLeg( + 28800, + BeamMode.WALK, + 0, + BeamPath(Vector(1, 2, 3, 4), Vector(), None, SpaceTime(0.0, 0.0, 28800), SpaceTime(1.0, 1.0, 28900), 1000.0) + ) router ! EmbodyWithCurrentTravelTime(leg, Id.createVehicleId(1)) val response = expectMsgType[RoutingResponse] assert(response.itineraries.head.beamLegs().head.duration == 2000) // Contains two full links (excluding 1 and 4) diff --git a/src/test/scala/beam/router/TollRoutingSpec.scala b/src/test/scala/beam/router/TollRoutingSpec.scala index efd25193068..9837eec9e7a 100755 --- a/src/test/scala/beam/router/TollRoutingSpec.scala +++ b/src/test/scala/beam/router/TollRoutingSpec.scala @@ -54,16 +54,31 @@ class TollRoutingSpec scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()) when(services.beamConfig).thenReturn(beamConfig) when(services.geo).thenReturn(new GeoUtilsImpl(services)) - when(services.dates).thenReturn(DateUtils(ZonedDateTime.parse(beamConfig.beam.routing.baseDate).toLocalDateTime, ZonedDateTime.parse(beamConfig.beam.routing.baseDate))) + when(services.dates).thenReturn( + DateUtils( + ZonedDateTime.parse(beamConfig.beam.routing.baseDate).toLocalDateTime, + ZonedDateTime.parse(beamConfig.beam.routing.baseDate) + ) + ) networkCoordinator = new DefaultNetworkCoordinator(beamConfig) networkCoordinator.loadNetwork() networkCoordinator.convertFrequenciesToTrips() fareCalculator = mock[FareCalculator] when(fareCalculator.getFareSegments(any(), any(), any(), any(), any())).thenReturn(Vector[BeamFareSegment]()) - val tollCalculator = new TollCalculator(beamConfig,"test/input/beamville/r5") - router = system.actorOf(BeamRouter.props(services, networkCoordinator.transportNetwork, networkCoordinator.network, - scenario, new EventsManagerImpl(), scenario.getTransitVehicles, fareCalculator, tollCalculator)) + val tollCalculator = new TollCalculator(beamConfig, "test/input/beamville/r5") + router = system.actorOf( + BeamRouter.props( + services, + networkCoordinator.transportNetwork, + networkCoordinator.network, + scenario, + new EventsManagerImpl(), + scenario.getTransitVehicles, + fareCalculator, + tollCalculator + ) + ) } "A time-dependent router with toll calculator" must { @@ -73,7 +88,23 @@ class TollRoutingSpec "report a toll on a route where the fastest route has tolls" in { val timeValueOfMoney = 0.0 // I don't mind tolls - val request = RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(Id.createVehicleId("car"), new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.CAR, asDriver = true)), Access, false, timeValueOfMoney) + val request = RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + Id.createVehicleId("car"), + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.CAR, + asDriver = true + ) + ), + Access, + false, + timeValueOfMoney + ) router ! request val response = expectMsgType[RoutingResponse] val carOption = response.itineraries.find(_.tripClassifier == CAR).get @@ -86,11 +117,23 @@ class TollRoutingSpec val earlierCarOption = earlierResponse.itineraries.find(_.tripClassifier == CAR).get assert(earlierCarOption.costEstimate == 2.0, "the link toll starts at 3000; when we go earlier, we don't pay it") - val configWithTollTurnedUp = BeamConfig(system.settings.config - .withValue("beam.agentsim.tuning.tollPrice", ConfigValueFactory.fromAnyRef(2.0))) - val moreExpensiveTollCalculator = new TollCalculator(configWithTollTurnedUp,"test/input/beamville/r5") - val moreExpensiveRouter = system.actorOf(BeamRouter.props(services, networkCoordinator.transportNetwork, networkCoordinator.network, - scenario, new EventsManagerImpl(), scenario.getTransitVehicles, fareCalculator, moreExpensiveTollCalculator)) + val configWithTollTurnedUp = BeamConfig( + system.settings.config + .withValue("beam.agentsim.tuning.tollPrice", ConfigValueFactory.fromAnyRef(2.0)) + ) + val moreExpensiveTollCalculator = new TollCalculator(configWithTollTurnedUp, "test/input/beamville/r5") + val moreExpensiveRouter = system.actorOf( + BeamRouter.props( + services, + networkCoordinator.transportNetwork, + networkCoordinator.network, + scenario, + new EventsManagerImpl(), + scenario.getTransitVehicles, + fareCalculator, + moreExpensiveTollCalculator + ) + ) moreExpensiveRouter ! request val moreExpensiveResponse = expectMsgType[RoutingResponse] val moreExpensiveCarOption = moreExpensiveResponse.itineraries.find(_.tripClassifier == CAR).get @@ -100,7 +143,23 @@ class TollRoutingSpec // If 1$ is worth more than 144 seconds to me, I should be sent on the alternative route // (which takes 288 seconds) val higherTimeValueOfMoney = 145.0 - val tollSensitiveRequest = RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(Id.createVehicleId("car"), new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.CAR, asDriver = true)), Access, false, higherTimeValueOfMoney) + val tollSensitiveRequest = RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + Id.createVehicleId("car"), + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.CAR, + asDriver = true + ) + ), + Access, + false, + higherTimeValueOfMoney + ) router ! tollSensitiveRequest val tollSensitiveResponse = expectMsgType[RoutingResponse] val tollSensitiveCarOption = tollSensitiveResponse.itineraries.find(_.tripClassifier == CAR).get @@ -109,7 +168,20 @@ class TollRoutingSpec } "not report a toll when walking" in { - val request = RoutingRequest(origin, destination, time, Vector(), Vector(StreetVehicle(Id.createVehicleId("body"), new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), Modes.BeamMode.WALK, asDriver = true))) + val request = RoutingRequest( + origin, + destination, + time, + Vector(), + Vector( + StreetVehicle( + Id.createVehicleId("body"), + new SpaceTime(new Coord(origin.getX, origin.getY), time.atTime), + Modes.BeamMode.WALK, + asDriver = true + ) + ) + ) router ! request val response = expectMsgType[RoutingResponse] val walkOption = response.itineraries.find(_.tripClassifier == WALK).get diff --git a/src/test/scala/beam/router/WarmStartRoutingSpec.scala b/src/test/scala/beam/router/WarmStartRoutingSpec.scala index 77c71e735d3..8ba22302551 100755 --- a/src/test/scala/beam/router/WarmStartRoutingSpec.scala +++ b/src/test/scala/beam/router/WarmStartRoutingSpec.scala @@ -39,18 +39,18 @@ import scala.concurrent.duration._ import scala.language.postfixOps class WarmStartRoutingSpec - extends TestKit( - ActorSystem( - "WarmStartRoutingSpec", - testConfig("test/input/beamville/beam.conf") - .withValue("beam.warmStart.enabled", ConfigValueFactory.fromAnyRef(true)) - .withValue( - "beam.warmStart.path", - ConfigValueFactory - .fromAnyRef("test/input/beamville/test-data/") - ) + extends TestKit( + ActorSystem( + "WarmStartRoutingSpec", + testConfig("test/input/beamville/beam.conf") + .withValue("beam.warmStart.enabled", ConfigValueFactory.fromAnyRef(true)) + .withValue( + "beam.warmStart.path", + ConfigValueFactory + .fromAnyRef("test/input/beamville/test-data/") + ) + ) ) - ) with BeamHelper with WordSpecLike with Matchers @@ -79,7 +79,7 @@ class WarmStartRoutingSpec scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()) when(services.beamConfig).thenReturn(beamConfig) when(services.geo).thenReturn(new GeoUtilsImpl(services)) - when(services.personHouseholds).thenReturn(Map[Id[Person],Household]()) + when(services.personHouseholds).thenReturn(Map[Id[Person], Household]()) when(services.dates).thenReturn( DateUtils( ZonedDateTime.parse(beamConfig.beam.routing.baseDate).toLocalDateTime, @@ -153,13 +153,11 @@ class WarmStartRoutingSpec } } - "A warmStart router" must { val origin = new BeamRouter.Location(166321.9, 1568.87) val destination = new BeamRouter.Location(167138.4, 1117) val time = RoutingModel.DiscreteTime(3000) - "take given link traversal times into account" in { router ! RoutingRequest( origin, @@ -180,7 +178,7 @@ class WarmStartRoutingSpec val carOption = response.itineraries.find(_.tripClassifier == CAR).get assert(carOption.totalTravelTimeInSecs == 76) - BeamWarmStart(services.beamConfig, maxHour).warmStartTravelTime(router, scenario) + BeamWarmStart(services.beamConfig, maxHour).warmStartTravelTime(router, scenario) router ! RoutingRequest( origin, @@ -204,10 +202,15 @@ class WarmStartRoutingSpec } "show a decrease in travel time after three iterations if warm start times are doubled" in { - BeamWarmStart(BeamConfig( - config.withValue("beam.warmStart.path", ConfigValueFactory.fromAnyRef("test/input/beamville/test-data/double-time"))), + BeamWarmStart( + BeamConfig( + config.withValue( + "beam.warmStart.path", + ConfigValueFactory.fromAnyRef("test/input/beamville/test-data/double-time") + ) + ), maxHour - ).warmStartTravelTime(router, scenario) + ).warmStartTravelTime(router, scenario) router ! RoutingRequest( origin, @@ -228,7 +231,7 @@ class WarmStartRoutingSpec val carOption = response.itineraries.find(_.tripClassifier == CAR).get assert(carOption.totalTravelTimeInSecs == 110) - BeamWarmStart(BeamConfig(iterationConfig), maxHour).warmStartTravelTime(router, scenario) + BeamWarmStart(BeamConfig(iterationConfig), maxHour).warmStartTravelTime(router, scenario) router1 ! RoutingRequest( origin, destination, @@ -251,10 +254,13 @@ class WarmStartRoutingSpec "show an increase in travel time after three iterations if warm start times are cut in half" in { - BeamWarmStart(BeamConfig( - config.withValue("beam.warmStart.path", ConfigValueFactory.fromAnyRef("test/input/beamville/test-data/half-time"))), + BeamWarmStart( + BeamConfig( + config + .withValue("beam.warmStart.path", ConfigValueFactory.fromAnyRef("test/input/beamville/test-data/half-time")) + ), maxHour - ).warmStartTravelTime(router, scenario) + ).warmStartTravelTime(router, scenario) router ! RoutingRequest( origin, @@ -274,7 +280,7 @@ class WarmStartRoutingSpec assert(response.itineraries.exists(_.tripClassifier == CAR)) val carOption = response.itineraries.find(_.tripClassifier == CAR).get - BeamWarmStart(BeamConfig(iterationConfig), maxHour).warmStartTravelTime(router, scenario) + BeamWarmStart(BeamConfig(iterationConfig), maxHour).warmStartTravelTime(router, scenario) router1 ! RoutingRequest( origin, destination, @@ -321,10 +327,15 @@ class WarmStartRoutingSpec val links = carOption.beamLegs().head.travelPath.linkIds val travelTime1 = carOption.beamLegs().head.travelPath.linkTravelTime.sum - BeamWarmStart(BeamConfig( - config.withValue("beam.warmStart.path", ConfigValueFactory.fromAnyRef("test/input/beamville/test-data/reduce10x-time"))), + BeamWarmStart( + BeamConfig( + config.withValue( + "beam.warmStart.path", + ConfigValueFactory.fromAnyRef("test/input/beamville/test-data/reduce10x-time") + ) + ), maxHour - ).warmStartTravelTime(router, scenario) + ).warmStartTravelTime(router, scenario) router ! RoutingRequest( origin, diff --git a/src/test/scala/beam/router/osm/TollCalculatorSpec.scala b/src/test/scala/beam/router/osm/TollCalculatorSpec.scala index 729b06b0a7f..64bcbb905ec 100755 --- a/src/test/scala/beam/router/osm/TollCalculatorSpec.scala +++ b/src/test/scala/beam/router/osm/TollCalculatorSpec.scala @@ -12,7 +12,8 @@ import scala.language.postfixOps class TollCalculatorSpec extends WordSpecLike { "Using beamville as input" when { val beamvillePath: Path = Paths.get("test", "input", "beamville", "r5") - val beamvilleTollCalc = new TollCalculator(BeamConfig(testConfig("test/input/beamville/beam.conf")), beamvillePath.toString) + val beamvilleTollCalc = + new TollCalculator(BeamConfig(testConfig("test/input/beamville/beam.conf")), beamvillePath.toString) "calculate toll for a single trunk road, it" should { "return value $1." in { assert(beamvilleTollCalc.calcTollByOsmIds(Vector(109)) == 1.0) diff --git a/src/test/scala/beam/utils/StuckFinderSpec.scala b/src/test/scala/beam/utils/StuckFinderSpec.scala index a79a0ea3c05..9db83007b44 100644 --- a/src/test/scala/beam/utils/StuckFinderSpec.scala +++ b/src/test/scala/beam/utils/StuckFinderSpec.scala @@ -10,15 +10,21 @@ import beam.sim.config.BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm import beam.sim.config.BeamConfig.Beam.Debug.StuckAgentDetection.Thresholds$Elm.ActorTypeToMaxNumberOfMessages import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike} -class StuckFinderSpec extends TestKit(ActorSystem("StuckFinderSpec")) - with WordSpecLike with Matchers with BeforeAndAfterAll { +class StuckFinderSpec + extends TestKit(ActorSystem("StuckFinderSpec")) + with WordSpecLike + with Matchers + with BeforeAndAfterAll { override def afterAll: Unit = { TestKit.shutdownActorSystem(system) } - val threshold = Thresholds$Elm(ActorTypeToMaxNumberOfMessages(Some(100), Some(100), Some(100), Some(100)), - 100, classOf[InitializeTrigger].getCanonicalName) + val threshold = Thresholds$Elm( + ActorTypeToMaxNumberOfMessages(Some(100), Some(100), Some(100), Some(100)), + 100, + classOf[InitializeTrigger].getCanonicalName + ) val stuckAgentDetectionCfg = StuckAgentDetection( From 608fab1bf3917a12ed6f788c64546d73ad5a0b55 Mon Sep 17 00:00:00 2001 From: Colin Sheppard Date: Tue, 13 Nov 2018 12:40:43 -0800 Subject: [PATCH 2/2] fmt --- .../scala/beam/sim/BeamGraphComparator.scala | 1 + src/main/scala/beam/sim/BeamMobsim.scala | 34 +- .../BeamOutputDataDescriptionGenerator.scala | 1208 ++++++++++++++--- src/main/scala/beam/sim/BeamSim.scala | 22 +- .../beam/sim/OutputDataDescription.scala | 5 +- 5 files changed, 1093 insertions(+), 177 deletions(-) diff --git a/src/main/scala/beam/sim/BeamGraphComparator.scala b/src/main/scala/beam/sim/BeamGraphComparator.scala index b2bc7c394d9..d73d611d52f 100644 --- a/src/main/scala/beam/sim/BeamGraphComparator.scala +++ b/src/main/scala/beam/sim/BeamGraphComparator.scala @@ -16,6 +16,7 @@ import scala.xml.{Elem, NodeBuffer} */ object BeamGraphComparator { + /** * Generates the html page for graph comparison * @param files Map that maps file name to the absolute file path across all iterations. diff --git a/src/main/scala/beam/sim/BeamMobsim.scala b/src/main/scala/beam/sim/BeamMobsim.scala index aadd623f47e..d7d203c7cdf 100755 --- a/src/main/scala/beam/sim/BeamMobsim.scala +++ b/src/main/scala/beam/sim/BeamMobsim.scala @@ -62,7 +62,8 @@ class BeamMobsim @Inject()( val rideHailSurgePricingManager: RideHailSurgePricingManager ) extends Mobsim with LazyLogging - with MetricsSupport with OutputDataDescriptor { + with MetricsSupport + with OutputDataDescriptor { private implicit val timeout: Timeout = Timeout(50000, TimeUnit.SECONDS) var memoryLoggingTimerActorRef: ActorRef = _ @@ -348,11 +349,11 @@ class BeamMobsim @Inject()( if (beamServices.matsimServices != null) { rideHailinitialLocationSpatialPlot.writeCSV( beamServices.matsimServices.getControlerIO - .getIterationFilename(beamServices.iterationNumber, fileBaseName+".csv") + .getIterationFilename(beamServices.iterationNumber, fileBaseName + ".csv") ) rideHailinitialLocationSpatialPlot.writeImage( beamServices.matsimServices.getControlerIO - .getIterationFilename(beamServices.iterationNumber, fileBaseName+".png") + .getIterationFilename(beamServices.iterationNumber, fileBaseName + ".png") ) } log.info("Initialized {} people", beamServices.personRefs.size) @@ -472,9 +473,30 @@ class BeamMobsim @Inject()( val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new util.ArrayList[OutputDataDescription] - list.add(OutputDataDescription(this.getClass.getSimpleName, relativePath, "rideHailAgentID", "Unique id of the given ride hail agent")) - list.add(OutputDataDescription(this.getClass.getSimpleName, relativePath, "xCoord", "X co-ordinate of the starting location of the ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName, relativePath, "yCoord", "Y co-ordinate of the starting location of the ride hail")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName, + relativePath, + "rideHailAgentID", + "Unique id of the given ride hail agent" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName, + relativePath, + "xCoord", + "X co-ordinate of the starting location of the ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName, + relativePath, + "yCoord", + "Y co-ordinate of the starting location of the ride hail" + ) + ) list } } diff --git a/src/main/scala/beam/sim/BeamOutputDataDescriptionGenerator.scala b/src/main/scala/beam/sim/BeamOutputDataDescriptionGenerator.scala index 40afbdb1102..7bffed9ff7b 100644 --- a/src/main/scala/beam/sim/BeamOutputDataDescriptionGenerator.scala +++ b/src/main/scala/beam/sim/BeamOutputDataDescriptionGenerator.scala @@ -19,12 +19,13 @@ import scala.collection.JavaConverters._ /** * Generate data descriptions table for all output file generating classes. */ -class BeamOutputDataDescriptionGenerator @Inject() -(private val actorSystem: ActorSystem, - private val transportNetwork: TransportNetwork, - private val beamServices: BeamServices, - private val eventsManager: EventsManager, - private val scenario: Scenario) { +class BeamOutputDataDescriptionGenerator @Inject()( + private val actorSystem: ActorSystem, + private val transportNetwork: TransportNetwork, + private val beamServices: BeamServices, + private val eventsManager: EventsManager, + private val scenario: Scenario +) { private final val outputFileName = "dataDescriptors.csv" private final val outputFileHeader = "ClassName,OutputFile,Field,Description\n" @@ -33,7 +34,7 @@ class BeamOutputDataDescriptionGenerator @Inject() * Generates the data descriptors and writes them to the output file. * @param event a controller event */ - def generateDescriptors(event : ControlerEvent): Unit = { + def generateDescriptors(event: ControlerEvent): Unit = { //get all the required class file instances val descriptors: Seq[OutputDataDescription] = getClassesGeneratingOutputs(event) flatMap { classRef => classRef.getOutputDataDescriptions.asScala.toList @@ -44,14 +45,14 @@ class BeamOutputDataDescriptionGenerator @Inject() } mkString "\n" //write the generated csv to an external file in the output folder val filePath = event.getServices.getControlerIO.getOutputPath + "/" + outputFileName - writeToFile(filePath,Some(outputFileHeader),descriptionsAsCSV,None) + writeToFile(filePath, Some(outputFileHeader), descriptionsAsCSV, None) } /** * creates and collects instances of all output file generating classes * @return collected class instances */ - private def getClassesGeneratingOutputs(event : ControlerEvent): List[OutputDataDescriptor] = List( + private def getClassesGeneratingOutputs(event: ControlerEvent): List[OutputDataDescriptor] = List( new ModeChosenAnalysis(new ModeChosenAnalysis.ModeChosenComputation, this.beamServices.beamConfig), new RealizedModeAnalysis(new RealizedModeAnalysis.RealizedModesStatsComputation), new RideHailRevenueAnalysis(new RideHailSurgePricingManager(this.beamServices)), @@ -64,10 +65,17 @@ class BeamOutputDataDescriptionGenerator @Inject() this.beamServices.beamConfig.beam.outputs.writeEventsInterval ), new PhyssimCalcLinkSpeedStats(scenario.getNetwork, event.getServices.getControlerIO, beamServices.beamConfig), - new PhyssimCalcLinkSpeedDistributionStats(scenario.getNetwork, event.getServices.getControlerIO, beamServices.beamConfig), + new PhyssimCalcLinkSpeedDistributionStats( + scenario.getNetwork, + event.getServices.getControlerIO, + beamServices.beamConfig + ), new RideHailWaitingAnalysis(new RideHailWaitingAnalysis.WaitingStatsComputation, beamServices.beamConfig), new GraphSurgePricing(new RideHailSurgePricingManager(beamServices)), - new RideHailingWaitingSingleAnalysis(beamServices.beamConfig, new RideHailingWaitingSingleAnalysis.RideHailingWaitingSingleComputation), + new RideHailingWaitingSingleAnalysis( + beamServices.beamConfig, + new RideHailingWaitingSingleAnalysis.RideHailingWaitingSingleComputation + ), new BeamMobsim( beamServices, transportNetwork, @@ -95,16 +103,20 @@ class BeamOutputDataDescriptionGenerator @Inject() * @param data data to be written to the file * @param fileFooter an optional footer to be appended (if any) */ - private def writeToFile(filePath : String,fileHeader : Option[String],data : String,fileFooter : Option[String]): Unit = { + private def writeToFile( + filePath: String, + fileHeader: Option[String], + data: String, + fileFooter: Option[String] + ): Unit = { val bw = new BufferedWriter(new FileWriter(filePath)) try { - if(fileHeader.isDefined) + if (fileHeader.isDefined) bw.append(fileHeader.get) bw.append(data) - if(fileFooter.isDefined) + if (fileFooter.isDefined) bw.append(fileFooter.get) - } - catch { + } catch { case e: IOException => e.printStackTrace() } finally { @@ -115,6 +127,7 @@ class BeamOutputDataDescriptionGenerator @Inject() } object ScoreStatsOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * @@ -125,16 +138,47 @@ object ScoreStatsOutputs extends OutputDataDescriptor { val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "ITERATION", "Iteration number")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "avg. EXECUTED", "Average of the total execution time for the given iteration")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "avg. WORST", "Average of worst case time complexities for the given iteration")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "avg. AVG", "Average of average case time complexities for the given iteration")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "avg. BEST", "Average of best case time complexities for the given iteration")) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "ITERATION", "Iteration number") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "avg. EXECUTED", + "Average of the total execution time for the given iteration" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "avg. WORST", + "Average of worst case time complexities for the given iteration" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "avg. AVG", + "Average of average case time complexities for the given iteration" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "avg. BEST", + "Average of best case time complexities for the given iteration" + ) + ) list } } object StopWatchOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * @@ -145,31 +189,167 @@ object StopWatchOutputs extends OutputDataDescriptor { val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Iteration", "Iteration number")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN iteration", "Begin time of the iteration")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN iterationStartsListeners", "Time at which the iteration start event listeners started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END iterationStartsListeners", "Time at which the iteration start event listeners ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN replanning", "Time at which the replanning event started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END replanning", "Time at which the replanning event ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN beforeMobsimListeners", "Time at which the beforeMobsim event listeners started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN dump all plans", "Begin dump all plans")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END dump all plans", "End dump all plans")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END beforeMobsimListeners", "Time at which the beforeMobsim event listeners ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN mobsim", "Time at which the mobsim run started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END mobsim", "Time at which the mobsim run ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN afterMobsimListeners", "Time at which the afterMobsim event listeners started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END afterMobsimListeners", "Time at which the afterMobsim event listeners ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN scoring", "Time at which the scoring event started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END scoring", "Time at which the scoring event ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN iterationEndsListeners", "Time at which the iteration ends event listeners ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "BEGIN compare with counts", "Time at which compare with counts started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END compare with counts", "Time at which compare with counts ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "END iteration", "Time at which the iteration ended")) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Iteration", "Iteration number") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN iteration", + "Begin time of the iteration" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN iterationStartsListeners", + "Time at which the iteration start event listeners started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END iterationStartsListeners", + "Time at which the iteration start event listeners ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN replanning", + "Time at which the replanning event started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END replanning", + "Time at which the replanning event ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN beforeMobsimListeners", + "Time at which the beforeMobsim event listeners started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN dump all plans", + "Begin dump all plans" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END dump all plans", + "End dump all plans" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END beforeMobsimListeners", + "Time at which the beforeMobsim event listeners ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN mobsim", + "Time at which the mobsim run started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END mobsim", + "Time at which the mobsim run ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN afterMobsimListeners", + "Time at which the afterMobsim event listeners started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END afterMobsimListeners", + "Time at which the afterMobsim event listeners ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN scoring", + "Time at which the scoring event started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END scoring", + "Time at which the scoring event ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN iterationEndsListeners", + "Time at which the iteration ends event listeners ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "BEGIN compare with counts", + "Time at which compare with counts started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END compare with counts", + "Time at which compare with counts ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "END iteration", + "Time at which the iteration ended" + ) + ) list } } object SummaryStatsOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * @@ -180,191 +360,885 @@ object SummaryStatsOutputs extends OutputDataDescriptor { val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Iteration", "Iteration number")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "agentHoursOnCrowdedTransit", "Time taken by the agent to travel in a crowded transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "fuelConsumedInMJ_Diesel", "Amount of diesel consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "fuelConsumedInMJ_Food", "Amount of food consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "fuelConsumedInMJ_Electricity", "Amount of electricity consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "fuelConsumedInMJ_Gasoline", "Amount of gasoline consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "numberOfVehicles_BEV", "Time at which the beforeMobsim event listeners started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "numberOfVehicles_BODY-TYPE-DEFAULT", "Number of vehicles of type BODY-TYPE-DEFAULT")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "numberOfVehicles_BUS-DEFAULT", "Number of vehicles of type BUS-DEFAULT")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "numberOfVehicles_Car", "Time at which the beforeMobsim event listeners ended")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "numberOfVehicles_SUBWAY-DEFAULT", "Time at which the mobsim run started")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "personTravelTime_car", "Time taken by the passenger to travel by car")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "personTravelTime_drive_transit", "Time taken by the passenger to drive to the transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "personTravelTime_others", "Time taken by the passenger to travel by other means")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "personTravelTime_walk", "Time taken by the passenger to travel on foot")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "personTravelTime_walk_transit", "Time taken by the passenger to walk to the transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "totalCostIncludingSubsidy_walk_transit", "Total cost (including subsidy) paid by the passenger to reach destination by walking to transit and then transit to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "totalCostIncludingSubsidy_ride_hail", "Total cost (including subsidy) paid by the passenger to reach destination on a ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "totalSubsidy_drive_transit", "Total subsidy amount paid to passenger to reach destination by driving to transit and then transit to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "totalSubsidy_ride_hail", "Total subsidy amount paid to passenger to reach destination by ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "totalSubsidy_walk_transit", "Total subsidy amount paid to passenger to reach destination by walking to transit and then transit to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "totalTravelTime", "Total time taken by the passenger to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "totalVehicleDelay", "Sum of all the delay times incurred by the vehicle during the travel")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleHoursTraveled_BEV", "Time taken (in hours) by the vehicle to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleHoursTraveled_BODY-TYPE-DEFAULT", "Time taken (in hours) by the vehicle to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleHoursTraveled_BUS-DEFAULT", "Time taken (in hours) by the vehicle(bus) to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleHoursTraveled_Car", "Time taken (in hours) by the vehicle(car) to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleHoursTraveled_SUBWAY-DEFAULT", "Time taken (in hours) by the vehicle (subway) to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleMilesTraveled_BEV", "Miles covered by the vehicle to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleMilesTraveled_BODY-TYPE-DEFAULT", "Miles covered by the vehicle to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleMilesTraveled_BUS-DEFAULT", "Miles covered by the vehicle(bus) to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleMilesTraveled_Car", "Miles covered by the vehicle(car) to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleMilesTraveled_SUBWAY-DEFAULT", "Miles covered by the vehicle(subway) to travel from source to destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicleMilesTraveled_total", "Miles covered by the vehicles(all modes) to travel from source to destination")) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Iteration", "Iteration number") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "agentHoursOnCrowdedTransit", + "Time taken by the agent to travel in a crowded transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "fuelConsumedInMJ_Diesel", + "Amount of diesel consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "fuelConsumedInMJ_Food", + "Amount of food consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "fuelConsumedInMJ_Electricity", + "Amount of electricity consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "fuelConsumedInMJ_Gasoline", + "Amount of gasoline consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "numberOfVehicles_BEV", + "Time at which the beforeMobsim event listeners started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "numberOfVehicles_BODY-TYPE-DEFAULT", + "Number of vehicles of type BODY-TYPE-DEFAULT" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "numberOfVehicles_BUS-DEFAULT", + "Number of vehicles of type BUS-DEFAULT" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "numberOfVehicles_Car", + "Time at which the beforeMobsim event listeners ended" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "numberOfVehicles_SUBWAY-DEFAULT", + "Time at which the mobsim run started" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "personTravelTime_car", + "Time taken by the passenger to travel by car" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "personTravelTime_drive_transit", + "Time taken by the passenger to drive to the transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "personTravelTime_others", + "Time taken by the passenger to travel by other means" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "personTravelTime_walk", + "Time taken by the passenger to travel on foot" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "personTravelTime_walk_transit", + "Time taken by the passenger to walk to the transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "totalCostIncludingSubsidy_walk_transit", + "Total cost (including subsidy) paid by the passenger to reach destination by walking to transit and then transit to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "totalCostIncludingSubsidy_ride_hail", + "Total cost (including subsidy) paid by the passenger to reach destination on a ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "totalSubsidy_drive_transit", + "Total subsidy amount paid to passenger to reach destination by driving to transit and then transit to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "totalSubsidy_ride_hail", + "Total subsidy amount paid to passenger to reach destination by ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "totalSubsidy_walk_transit", + "Total subsidy amount paid to passenger to reach destination by walking to transit and then transit to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "totalTravelTime", + "Total time taken by the passenger to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "totalVehicleDelay", + "Sum of all the delay times incurred by the vehicle during the travel" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleHoursTraveled_BEV", + "Time taken (in hours) by the vehicle to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleHoursTraveled_BODY-TYPE-DEFAULT", + "Time taken (in hours) by the vehicle to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleHoursTraveled_BUS-DEFAULT", + "Time taken (in hours) by the vehicle(bus) to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleHoursTraveled_Car", + "Time taken (in hours) by the vehicle(car) to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleHoursTraveled_SUBWAY-DEFAULT", + "Time taken (in hours) by the vehicle (subway) to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleMilesTraveled_BEV", + "Miles covered by the vehicle to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleMilesTraveled_BODY-TYPE-DEFAULT", + "Miles covered by the vehicle to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleMilesTraveled_BUS-DEFAULT", + "Miles covered by the vehicle(bus) to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleMilesTraveled_Car", + "Miles covered by the vehicle(car) to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleMilesTraveled_SUBWAY-DEFAULT", + "Miles covered by the vehicle(subway) to travel from source to destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vehicleMilesTraveled_total", + "Miles covered by the vehicles(all modes) to travel from source to destination" + ) + ) list } } object CountsCompareOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * * @return list of data description objects */ override def getOutputDataDescriptions: java.util.List[OutputDataDescription] = { - val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0,"countsCompare.txt") + val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0, "countsCompare.txt") val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Link Id", "Iteration number")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Count", "Time taken by the agent to travel in a crowded transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Station Id", "Amount of diesel consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Hour", "Amount of food consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "MATSIM volumes", "Amount of electricity consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Relative Error", "Amount of gasoline consumed in megajoule")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Normalized Relative Error", "Time at which the beforeMobsim event listeners started")) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "Link Id", "Iteration number") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "Count", + "Time taken by the agent to travel in a crowded transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "Station Id", + "Amount of diesel consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "Hour", + "Amount of food consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "MATSIM volumes", + "Amount of electricity consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "Relative Error", + "Amount of gasoline consumed in megajoule" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "Normalized Relative Error", + "Time at which the beforeMobsim event listeners started" + ) + ) list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "GEH", "GEH")) list } } object EventOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * * @return list of data description objects */ override def getOutputDataDescriptions: java.util.List[OutputDataDescription] = { - val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0,"events.csv") + val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0, "events.csv") val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "person", "Person(Agent) Id")) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "person", "Person(Agent) Id") + ) list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicle", "vehicle id")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "time", "Start time of the vehicle")) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "time", "Start time of the vehicle") + ) list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "type", "Type of the event")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "fuel", "Type of fuel used in the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "duration", "Duration of the travel")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "fuel", + "Type of fuel used in the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "duration", + "Duration of the travel" + ) + ) list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "cost", "Cost of travel")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "location.x", "X co-ordinate of the location")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "location.y", "Y co-ordinate of the location")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "parking_type", "Parking type chosen by the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "pricing_model", "Pricing model")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "charging_type", "Charging type of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "parking_taz", "Parking TAZ")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "distance", "Distance between source and destination")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "location", "Location of the vehicle")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "location.x", + "X co-ordinate of the location" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "location.y", + "Y co-ordinate of the location" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "parking_type", + "Parking type chosen by the vehicle" + ) + ) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "pricing_model", "Pricing model") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "charging_type", + "Charging type of the vehicle" + ) + ) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "parking_taz", "Parking TAZ") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "distance", + "Distance between source and destination" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "location", + "Location of the vehicle" + ) + ) list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "mode", "Mode of travel")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "currentTourMode", "Current tour mode")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "expectedMaximumUtility", "Expected maximum utility of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "availableAlternatives", "Available alternatives for travel for the passenger")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "personalVehicleAvailable", "Whether the passenger possesses a personal vehicle")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "currentTourMode", + "Current tour mode" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "expectedMaximumUtility", + "Expected maximum utility of the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "availableAlternatives", + "Available alternatives for travel for the passenger" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "personalVehicleAvailable", + "Whether the passenger possesses a personal vehicle" + ) + ) list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "tourIndex", "Tour index")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "facility", "Facility availed by the passenger")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departTime", "Time of departure of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "originX", "X ordinate of the passenger origin point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "originY", "Y ordinate of the passenger origin point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "destinationX", "X ordinate of the passenger destination point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "destinationY", "Y ordinate of the passenger destination point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "fuelType", "Fuel type of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "num_passengers", "Num of passengers travelling in the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "links", "Number of links in the network")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departure_time", "Departure time of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "arrival_time", "Arrival time of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicle_type", "Type of vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "capacity", "Total capacity of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "start.x", "X ordinate of the start point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "start.y", "Y ordinate of the start point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "end.x", "X ordinate of the vehicle end point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "end.y", "Y ordinate of the vehicle end point")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "end_leg_fuel_level", "Fuel level at the end of the travel")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "seating_capacity", "Seating capacity of the vehicle")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "costType", "Type of cost of travel incurred on the passenger")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "facility", + "Facility availed by the passenger" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departTime", + "Time of departure of the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "originX", + "X ordinate of the passenger origin point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "originY", + "Y ordinate of the passenger origin point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "destinationX", + "X ordinate of the passenger destination point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "destinationY", + "Y ordinate of the passenger destination point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "fuelType", + "Fuel type of the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "num_passengers", + "Num of passengers travelling in the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "links", + "Number of links in the network" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departure_time", + "Departure time of the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "arrival_time", + "Arrival time of the vehicle" + ) + ) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vehicle_type", "Type of vehicle") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "capacity", + "Total capacity of the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "start.x", + "X ordinate of the start point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "start.y", + "Y ordinate of the start point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "end.x", + "X ordinate of the vehicle end point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "end.y", + "Y ordinate of the vehicle end point" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "end_leg_fuel_level", + "Fuel level at the end of the travel" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "seating_capacity", + "Seating capacity of the vehicle" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "costType", + "Type of cost of travel incurred on the passenger" + ) + ) list } } object LegHistogramOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * * @return list of data description objects */ override def getOutputDataDescriptions: java.util.List[OutputDataDescription] = { - val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0,"legHistogram.txt") + val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0, "legHistogram.txt") val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "time", "Time")) list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "time", "Time")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departures_all", "Total number of departures on all modes")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "arrivals_all", "Total number of arrivals on all modes")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "duration", "Duration of travel")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "stuck_all", "Total number of travels that got stuck on all modes")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "en-route_all", "Total number of travels by all modes")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departures_car", "Total number of departures by car")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "arrivals_car", "Total number of departures by car")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "stuck_car", "Total number of travels that got stuck while travelling by car")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "en-route_car", "Total number of travels made by car")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departures_drive_transit", "Total number of departures by drive to transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "arrivals_drive_transit", "Total number of arrivals by drive to transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "stuck_drive_transit", "Total number of travels that got stuck while travelling by drive to transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "en-route_drive_transit", "Total number of travels made by drive to transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departures_ride_hail", "Total number of departures by ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "arrivals_ride_hail", "Total number of arrivals by ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "stuck_ride_hail", "Total number of travels that got stuck while travelling by ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "en-route_ride_hail", "Total number of travels made by ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departures_walk", "Total number of departures on foot")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "arrivals_walk", "Total number of arrivals on foot")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "stuck_walk", "Total number of travels that got stuck while travelling on foot")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "en-route_walk", "Total number of travels made on foot")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "departures_walk_transit", "Total number of departures by walk to transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "arrivals_walk_transit", "Total number of arrivals by walk to transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "stuck_walk_transit", "Total number of travels that got stuck while travelling by walk to transit")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "en-route_walk_transit", "Total number of travels made by walk to transit")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departures_all", + "Total number of departures on all modes" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "arrivals_all", + "Total number of arrivals on all modes" + ) + ) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "duration", "Duration of travel") + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "stuck_all", + "Total number of travels that got stuck on all modes" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "en-route_all", + "Total number of travels by all modes" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departures_car", + "Total number of departures by car" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "arrivals_car", + "Total number of departures by car" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "stuck_car", + "Total number of travels that got stuck while travelling by car" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "en-route_car", + "Total number of travels made by car" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departures_drive_transit", + "Total number of departures by drive to transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "arrivals_drive_transit", + "Total number of arrivals by drive to transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "stuck_drive_transit", + "Total number of travels that got stuck while travelling by drive to transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "en-route_drive_transit", + "Total number of travels made by drive to transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departures_ride_hail", + "Total number of departures by ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "arrivals_ride_hail", + "Total number of arrivals by ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "stuck_ride_hail", + "Total number of travels that got stuck while travelling by ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "en-route_ride_hail", + "Total number of travels made by ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departures_walk", + "Total number of departures on foot" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "arrivals_walk", + "Total number of arrivals on foot" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "stuck_walk", + "Total number of travels that got stuck while travelling on foot" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "en-route_walk", + "Total number of travels made on foot" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "departures_walk_transit", + "Total number of departures by walk to transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "arrivals_walk_transit", + "Total number of arrivals by walk to transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "stuck_walk_transit", + "Total number of travels that got stuck while travelling by walk to transit" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "en-route_walk_transit", + "Total number of travels made by walk to transit" + ) + ) list } } object RideHailTripDistanceOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * * @return list of data description objects */ override def getOutputDataDescriptions: java.util.List[OutputDataDescription] = { - val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0,"rideHailTripDistance.csv") + val outputFilePath = + GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0, "rideHailTripDistance.csv") val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "hour", "Hour of the day")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "numPassengers", "Number of passengers travelling in the ride hail")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "vkt", "Total number of kilometers travelled by the ride hail vehicle")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "numPassengers", + "Number of passengers travelling in the ride hail" + ) + ) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "vkt", + "Total number of kilometers travelled by the ride hail vehicle" + ) + ) list } } object TripDurationOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * * @return list of data description objects */ override def getOutputDataDescriptions: java.util.List[OutputDataDescription] = { - val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0,"tripDuration.txt") + val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0, "tripDuration.txt") val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] @@ -375,37 +1249,59 @@ object TripDurationOutputs extends OutputDataDescriptor { } object BiasErrorGraphDataOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * * @return list of data description objects */ override def getOutputDataDescriptions: java.util.List[OutputDataDescription] = { - val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0,"biasErrorGraphData.txt") + val outputFilePath = + GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0, "biasErrorGraphData.txt") val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "hour", "Hour of the day")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "mean relative error", "Mean relative error")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "mean bias", "Mean bias value")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "mean relative error", + "Mean relative error" + ) + ) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "mean bias", "Mean bias value") + ) list } } object BiasNormalizedErrorGraphDataOutputs extends OutputDataDescriptor { + /** * Get description of fields written to the output files. * * @return list of data description objects */ override def getOutputDataDescriptions: java.util.List[OutputDataDescription] = { - val outputFilePath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0,"biasNormalizedErrorGraphData.txt") + val outputFilePath = + GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getIterationFilename(0, "biasNormalizedErrorGraphData.txt") val outputDirPath = GraphsStatsAgentSimEventsListener.CONTROLLER_IO.getOutputPath val relativePath = outputFilePath.replace(outputDirPath, "") val list = new java.util.ArrayList[OutputDataDescription] list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "hour", "Hour of the day")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "mean normalized relative error", "Mean normalized relative error")) - list.add(OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "mean bias", "Mean bias value")) + list.add( + OutputDataDescription( + this.getClass.getSimpleName.dropRight(1), + relativePath, + "mean normalized relative error", + "Mean normalized relative error" + ) + ) + list.add( + OutputDataDescription(this.getClass.getSimpleName.dropRight(1), relativePath, "mean bias", "Mean bias value") + ) list } } diff --git a/src/main/scala/beam/sim/BeamSim.scala b/src/main/scala/beam/sim/BeamSim.scala index f914e1d8ce4..8c5b241f4e1 100755 --- a/src/main/scala/beam/sim/BeamSim.scala +++ b/src/main/scala/beam/sim/BeamSim.scala @@ -41,17 +41,17 @@ import scala.concurrent.duration.Duration import scala.concurrent.{Await, Future} class BeamSim @Inject()( - private val actorSystem: ActorSystem, - private val transportNetwork: TransportNetwork, - private val beamServices: BeamServices, - private val eventsManager: EventsManager, - private val scenario: Scenario, - private val beamOutputDataDescriptionGenerator: BeamOutputDataDescriptionGenerator, - ) extends StartupListener - with IterationEndsListener - with ShutdownListener - with LazyLogging - with MetricsSupport { + private val actorSystem: ActorSystem, + private val transportNetwork: TransportNetwork, + private val beamServices: BeamServices, + private val eventsManager: EventsManager, + private val scenario: Scenario, + private val beamOutputDataDescriptionGenerator: BeamOutputDataDescriptionGenerator, +) extends StartupListener + with IterationEndsListener + with ShutdownListener + with LazyLogging + with MetricsSupport { private var agentSimToPhysSimPlanConverter: AgentSimToPhysSimPlanConverter = _ private implicit val timeout: Timeout = Timeout(50000, TimeUnit.SECONDS) diff --git a/src/main/scala/beam/sim/OutputDataDescription.scala b/src/main/scala/beam/sim/OutputDataDescription.scala index ec41115aa76..d6ed58c80ca 100644 --- a/src/main/scala/beam/sim/OutputDataDescription.scala +++ b/src/main/scala/beam/sim/OutputDataDescription.scala @@ -7,7 +7,4 @@ package beam.sim * @param field field to be described * @param description description of the field */ -case class OutputDataDescription(className : String, - outputFile:String, - field:String, - description:String) +case class OutputDataDescription(className: String, outputFile: String, field: String, description: String)