Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/do/#3441-mode-choice-strategy' i…
Browse files Browse the repository at this point in the history
…nto zn/nyc-runs-new-r5-and-current-tour-mode
  • Loading branch information
zneedell committed Mar 29, 2022
2 parents 9bb0b46 + 103a0c3 commit f021150
Show file tree
Hide file tree
Showing 12 changed files with 317 additions and 317 deletions.
1 change: 0 additions & 1 deletion docs/inputs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,6 @@ beam.routing {
# Departure window in min
departureWindow = "double | 15.0"
numberOfSamples = "int | 1"
osmFile = ${beam.routing.r5.directory}"/beamville.osm.pbf"
osmMapdbFile = ${beam.routing.r5.directory}"/osm.mapdb"
mNetBuilder.fromCRS = "EPSG:4326" # WGS84
mNetBuilder.toCRS = "EPSG:26910" # UTM10N
Expand Down
77 changes: 48 additions & 29 deletions src/main/scala/beam/agentsim/agents/PersonAgent.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import beam.agentsim.agents.parking.ChoosesParking.{
ChoosingParkingSpot,
ReleasingParkingSpot
}
import beam.agentsim.agents.planning.BeamPlan.atHome
import beam.agentsim.agents.planning.Strategy.ModeChoiceStrategy
import beam.agentsim.agents.planning.{BeamPlan, Tour}
import beam.agentsim.agents.ridehail.RideHailManager.TravelProposal
import beam.agentsim.agents.ridehail._
Expand Down Expand Up @@ -188,7 +190,7 @@ object PersonAgent {
currentTrip: Option[EmbodiedBeamTrip] = None,
restOfCurrentTrip: List[EmbodiedBeamLeg] = List(),
currentVehicle: VehicleStack = Vector(),
currentTourMode: Option[BeamMode] = None,
currentTripMode: Option[BeamMode] = None,
currentTourPersonalVehicle: Option[Id[BeamVehicle]] = None,
passengerSchedule: PassengerSchedule = PassengerSchedule(),
currentLegPassengerScheduleIndex: Int = 0,
Expand Down Expand Up @@ -406,7 +408,7 @@ class PersonAgent(
// which is used in place of our real remaining tour distance of 0.0
// which should help encourage residential end-of-day charging
val tomorrowFirstLegDistance =
if (nextAct.getType.toLowerCase == "home") {
if (atHome(nextAct)) {
findFirstCarLegOfTrip(personData) match {
case Some(carLeg) =>
carLeg.beamLeg.travelPath.distanceInM
Expand Down Expand Up @@ -475,6 +477,30 @@ class PersonAgent(
}
}

def isFirstTripWithinTour(personData: BasePersonData, nextAct: Activity): Boolean = {
val (tripIndexOfElement: Int, _) = currentTripIndexWithinTour(personData, nextAct)
tripIndexOfElement == 0
}

def isLastTripWithinTour(personData: BasePersonData, nextAct: Activity): Boolean = {
val (tripIndexOfElement: Int, lastTripIndex: Int) = currentTripIndexWithinTour(personData, nextAct)
tripIndexOfElement == lastTripIndex
}

def isFirstOrLastTripWithinTour(personData: BasePersonData, nextAct: Activity): Boolean = {
val (tripIndexOfElement: Int, lastTripIndex: Int) = currentTripIndexWithinTour(personData, nextAct)
tripIndexOfElement == 0 || tripIndexOfElement == lastTripIndex
}

def currentTripIndexWithinTour(personData: BasePersonData, nextAct: Activity): (Int, Int) = {
val tour = currentTour(personData)
val lastTripIndex = tour.trips.size - 1
val tripIndexOfElement = tour
.tripIndexOfElement(nextAct)
.getOrElse(throw new IllegalArgumentException(s"Element [$nextAct] not found"))
(tripIndexOfElement, lastTripIndex)
}

def currentActivity(data: BasePersonData): Activity =
_experiencedBeamPlan.activities(data.currentActivityIndex)

Expand Down Expand Up @@ -577,24 +603,15 @@ class PersonAgent(
case Some(nextAct) =>
logDebug(s"wants to go to ${nextAct.getType} @ $tick")
holdTickAndTriggerId(tick, triggerId)
val indexOfNextActivity = _experiencedBeamPlan.getPlanElements.indexOf(nextAct)
val modeOfNextLeg = _experiencedBeamPlan.getPlanElements.get(indexOfNextActivity - 1) match {
case leg: Leg => BeamMode.fromString(leg.getMode)
case _ => None
}
val modeOfNextLeg = _experiencedBeamPlan.getTripStrategy[ModeChoiceStrategy](nextAct).flatMap(_.mode)
val currentCoord = currentActivity(data).getCoord
val nextCoord = nextActivity(data).get.getCoord
goto(ChoosingMode) using ChoosesModeData(
personData = data.copy(
// If the mode of the next leg is defined and is CAV, use it, otherwise,
// If we don't have a current tour mode (i.e. are not on a tour aka at home),
// use the mode of the next leg as the new tour mode.
currentTourMode = modeOfNextLeg match {
case Some(CAV) =>
Some(CAV)
case _ =>
data.currentTourMode.orElse(modeOfNextLeg)
},
// We current tour mode is defined in _experiencedBeamPlan.getTourStrategy
// If we have the currentTourPersonalVehicle then we should use it
// use the mode of the next leg as the new trip mode.
currentTripMode = modeOfNextLeg,
numberOfReplanningAttempts = 0,
failedTrips = IndexedSeq.empty,
enrouteData = EnrouteData()
Expand Down Expand Up @@ -625,7 +642,7 @@ class PersonAgent(

case Event(
TriggerWithId(TeleportationEndsTrigger(tick), triggerId),
data @ BasePersonData(_, Some(currentTrip), _, _, maybeCurrentTourMode, _, _, _, true, _, _, _, _, _)
data @ BasePersonData(_, Some(currentTrip), _, _, maybeCurrentTripMode, _, _, _, true, _, _, _, _, _)
) =>
holdTickAndTriggerId(tick, triggerId)

Expand All @@ -638,7 +655,7 @@ class PersonAgent(
startY = currentTrip.legs.head.beamLeg.travelPath.startPoint.loc.getY,
endX = currentTrip.legs.last.beamLeg.travelPath.endPoint.loc.getX,
endY = currentTrip.legs.last.beamLeg.travelPath.endPoint.loc.getY,
currentTourMode = maybeCurrentTourMode.map(_.value)
currentTourMode = maybeCurrentTripMode.map(_.value)
)
eventsManager.processEvent(teleportationEvent)

Expand Down Expand Up @@ -722,7 +739,7 @@ class PersonAgent(
val currentCoord = beamServices.geo.wgs2Utm(data.restOfCurrentTrip.head.beamLeg.travelPath.startPoint).loc
val nextCoord = nextActivity(data).get.getCoord
goto(ChoosingMode) using ChoosesModeData(
data.copy(currentTourMode = None, numberOfReplanningAttempts = data.numberOfReplanningAttempts + 1),
data.copy(currentTripMode = None, numberOfReplanningAttempts = data.numberOfReplanningAttempts + 1),
currentLocation = SpaceTime(
currentCoord,
tick
Expand Down Expand Up @@ -815,7 +832,7 @@ class PersonAgent(
// RIDE HAIL FAILURE
case Event(
response @ RideHailResponse(_, _, Some(error), _, _),
data @ BasePersonData(_, _, _, _, _, _, _, _, _, _, _, _, _, _)
data: BasePersonData
) =>
handleFailedRideHailReservation(error, response, data)
}
Expand Down Expand Up @@ -977,9 +994,11 @@ class PersonAgent(
val currentCoord =
beamServices.geo.wgs2Utm(basePersonData.restOfCurrentTrip.head.beamLeg.travelPath.startPoint).loc
val nextCoord = nextActivity(basePersonData).get.getCoord
// Have to give up my mode as well, perhaps there's no option left for driving.
_experiencedBeamPlan.putStrategy(currentTour(basePersonData), ModeChoiceStrategy(mode = None))
goto(ChoosingMode) using ChoosesModeData(
basePersonData.copy(
currentTourMode = None, // Have to give up my mode as well, perhaps there's no option left for driving.
currentTripMode = None,
currentTourPersonalVehicle = None,
numberOfReplanningAttempts = basePersonData.numberOfReplanningAttempts + 1
),
Expand Down Expand Up @@ -1185,7 +1204,7 @@ class PersonAgent(
val nextCoord = nextActivity(data).get.getCoord
goto(ChoosingMode) using ChoosesModeData(
personData = data
.copy(currentTourMode = Some(WALK_TRANSIT), numberOfReplanningAttempts = data.numberOfReplanningAttempts + 1),
.copy(currentTripMode = Some(WALK_TRANSIT), numberOfReplanningAttempts = data.numberOfReplanningAttempts + 1),
currentLocation = SpaceTime(currentCoord, _currentTick.get),
isWithinTripReplanning = true,
excludeModes =
Expand Down Expand Up @@ -1247,7 +1266,7 @@ class PersonAgent(
val nextCoord = nextActivity(data).get.getCoord
goto(ChoosingMode) using ChoosesModeData(
personData = data
.copy(currentTourMode = Some(WALK_TRANSIT), numberOfReplanningAttempts = data.numberOfReplanningAttempts + 1),
.copy(currentTripMode = Some(WALK_TRANSIT), numberOfReplanningAttempts = data.numberOfReplanningAttempts + 1),
currentLocation = SpaceTime(currentCoord, _currentTick.get),
isWithinTripReplanning = true,
excludeModes =
Expand Down Expand Up @@ -1276,7 +1295,7 @@ class PersonAgent(
_,
_,
_,
currentTourMode @ Some(HOV2_TELEPORTATION | HOV3_TELEPORTATION),
Some(HOV2_TELEPORTATION | HOV3_TELEPORTATION),
_,
_,
_,
Expand Down Expand Up @@ -1316,7 +1335,7 @@ class PersonAgent(
currentTrip = None,
restOfCurrentTrip = List(),
currentTourPersonalVehicle = None,
currentTourMode = if (activity.getType.equals("Home")) None else currentTourMode,
currentTripMode = None,
hasDeparted = false
)
case None =>
Expand All @@ -1333,7 +1352,7 @@ class PersonAgent(
Some(currentTrip),
_,
_,
currentTourMode,
_,
currentTourPersonalVehicle,
_,
_,
Expand Down Expand Up @@ -1404,7 +1423,7 @@ class PersonAgent(
currentTourPersonalVehicle = currentTourPersonalVehicle match {
case Some(personalVehId) =>
val personalVeh = beamVehicles(personalVehId).asInstanceOf[ActualVehicle].vehicle
if (activity.getType.equals("Home")) {
if (atHome(activity)) {
potentiallyChargingBeamVehicles.put(personalVeh.id, beamVehicles(personalVeh.id))
beamVehicles -= personalVeh.id
personalVeh.getManager.get ! ReleaseVehicle(personalVeh, triggerId)
Expand All @@ -1415,7 +1434,7 @@ class PersonAgent(
case None =>
None
},
currentTourMode = if (activity.getType.equals("Home")) None else currentTourMode,
currentTripMode = None,
hasDeparted = false
)
case None =>
Expand Down Expand Up @@ -1489,7 +1508,7 @@ class PersonAgent(
}

def getReplanningReasonFrom(data: BasePersonData, prefix: String): String = {
data.currentTourMode
data.currentTripMode
.collect { case mode =>
s"$prefix $mode"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import beam.agentsim.agents.modalbehaviors.ChoosesMode.{CavTripLegsRequest, CavT
import beam.agentsim.agents.modalbehaviors.DrivesVehicle.VehicleOrToken
import beam.agentsim.agents.modalbehaviors.ModeChoiceCalculator
import beam.agentsim.agents.planning.BeamPlan
import beam.agentsim.agents.planning.BeamPlan.atHome
import beam.agentsim.agents.ridehail.RideHailAgent.{
ModifyPassengerSchedule,
ModifyPassengerScheduleAck,
Expand Down Expand Up @@ -197,8 +198,8 @@ object HouseholdActor {
val homeCoordFromPlans = household.members
.flatMap(person =>
person.getSelectedPlan.getPlanElements.asScala.flatMap {
case act: Activity if act.getType == "Home" => Some(act.getCoord)
case _ => None
case act: Activity if atHome(act) => Some(act.getCoord)
case _ => None
}
)
.headOption
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import beam.agentsim.agents.InitializeTrigger
import beam.agentsim.agents.household.HouseholdActor._
import beam.agentsim.agents.household.HouseholdFleetManager.ResolvedParkingResponses
import beam.agentsim.agents.modalbehaviors.DrivesVehicle.ActualVehicle
import beam.agentsim.agents.planning.BeamPlan.atHome
import beam.agentsim.agents.vehicles.BeamVehicle
import beam.agentsim.events.SpaceTime
import beam.agentsim.infrastructure.{ParkingInquiry, ParkingInquiryResponse}
Expand Down Expand Up @@ -104,7 +105,7 @@ class HouseholdFleetManager(
case GetVehicleTypes(triggerId) =>
sender() ! VehicleTypesResponse(vehicles.values.map(_.beamVehicleType).toSet, triggerId)

case MobilityStatusInquiry(personId, whenWhere, _, requireVehicleCategoryAvailable, triggerId) =>
case MobilityStatusInquiry(personId, whenWhere, originActivity, requireVehicleCategoryAvailable, triggerId) =>
{
for {
neededVehicleCategory <- requireVehicleCategoryAvailable
Expand Down Expand Up @@ -157,13 +158,15 @@ class HouseholdFleetManager(
}
}.getOrElse {
availableVehicles = availableVehicles match {
case firstVehicle :: rest =>
//in case of replanning because of TRANSIT failure WALK_TRANSIT is used
//but we may want to introduce maxWalkingDistance and check that the agent is close enough to the vehicle
case firstVehicle :: rest if atHome(originActivity) =>
logger.debug("Vehicle {} is now taken", firstVehicle.id)
firstVehicle.becomeDriver(sender)
sender() ! MobilityStatusResponse(Vector(ActualVehicle(firstVehicle)), triggerId)
rest
case Nil =>
logger.debug(s"Not returning vehicle because no default is defined")
case _ =>
logger.debug(s"Not returning vehicle because no default is defined or agent is not at home")
sender() ! MobilityStatusResponse(Vector(), triggerId)
Nil
}
Expand Down
Loading

0 comments on commit f021150

Please sign in to comment.