openmobisim.contrib.policies#
Reference operator policies, one of each of Powell’s four classes, for docked bikes and taxis.
Powell (2019, A unified framework for stochastic optimization, European Journal of Operational Research 275(3) 795-821, https://doi.org/10.1016/j.ejor.2018.07.014) sorts the policies of sequential decisions into four classes:
PFA, a policy function approximation: a rule with tunable parameters. The built-in
operator.policy_thresholdandoperator.policy_charge_rule, tuned here by a grid over episodes (tune_threshold,tune_charge_rule;tunefor any policy).CFA, a cost function approximation: a deterministic optimisation each step with tuned terms.
policy_flow_targets(docked bikes: a min-cost transportation problem from docks above their band to docks below it) andpolicy_assignment(taxis: waiting requests to idle vehicles, low charge penalised, low vehicles sent to charge).VFA, a value function approximation: decisions by the reward now plus an estimated value of the state reached.
policy_value_table: a lookup table of values per (zone, fill band, hour) for docks or (zone, charge band, hour) for taxis, learned over episodes (train), decisions by one-step greedy over a small set of candidates.DLA, a direct lookahead: an optimisation over a forecast horizon, re-solved each step, its first decisions applied.
policy_lookahead(a mixed-integer program onview.expected_legs) andpolicy_lookahead_simulated(a few candidate policies simulated ahead onenvironment.fork(), the best one’s decisions applied).
They are references, simple and readable, to compare one’s own policies with: checks of sense,
not tuned for quality. Each is a policy object of openmobisim.operator (step(view),
step_s, describe()), usable in fleet_day and stepped on a fleet_environment
by evaluate. Every parameter’s default is an assumption, not calibrated.
The CFA and the DLA need SciPy (pip install "openmobisim[policies]"), imported when such a
policy is made; the rest needs numpy only.
Bikes and taxis. Each class has a reference for each service kind, chosen by the service’s kind in the view; a policy steers every service of its kind in a day.
Functions#
|
A policy's episode rewards on a fleet environment, one day per seed. |
|
CFA for taxis: waiting requests matched to idle vehicles by an assignment each step. |
|
CFA for docked bikes: bikes moved by a min-cost transportation problem each step. |
|
DLA: a mixed-integer program over the next |
|
DLA by simulation: at each step, each candidate policy is run ahead on a copy of the day. |
|
VFA: decisions by the reward now plus a learned value of the state reached. |
|
A policy's parameters chosen by a grid search over training days, scored on others. |
|
|
|
|
Module Contents#
- openmobisim.contrib.policies.evaluate(policy, environment, seeds)#
A policy’s episode rewards on a fleet environment, one day per seed.
Each seed’s day is stepped from its start to its end, the policy deciding at every step of the environment (the environment’s
step_srules, not the policy’s). The reward is the environment’s standard one (fleet_environment: minus the cancelled requests, the minutes waited and walked, the van kilometres, by their weights).- Parameters:
policy (Any) – A policy object (
step(view)), a built-innoop,thresholdorcharge_rule(operator.policy_threshold(...)or its name; stepped in its Python form, deciding the same), orNone: no decisions.environment (Any) – A
fleet_environment(n=1), or a callable returning one.seeds (collections.abc.Iterable[int]) – The days’ seeds.
- Returns:
{"policy", "seeds", "rewards", "reward_mean", "reward_std", "seconds", "seconds_episode"}: the policy’s description, the seeds and each one’s episode reward, their mean and standard deviation (0 for one seed), the wall-clock seconds in all and per episode.- Return type:
dict[str, Any]
- openmobisim.contrib.policies.policy_assignment(charge_below=0.2, charge_to=0.8, *, soc_penalty_s=300.0, step_s=300.0)#
CFA for taxis: waiting requests matched to idle vehicles by an assignment each step.
The engine matches a request to the nearest idle vehicle that can reach it within the fleet’s cancel limit
request_cancel_sless its dispatch delaydispatch_delay_sthe moment it is made; a request no vehicle can reach in time waits (waiting_nodein the view). Each step, this policy (1) sends every idle vehicle belowcharge_belowto its nearest charger, to charge tocharge_to, and (2) assigns the other idle vehicles to the waiting requests, one each, minimising the seconds to the pickup (view.travel_times) plussoc_penalty_s× the share of battery used, byscipy.optimize.linear_sum_assignment; each assigned vehicle is relocated to its request’s road node. The engine offers waiting requests, oldest first, to a vehicle that ends a relocation: the request is picked up if the vehicle, the dispatch delay included, arrives within the request’srequest_cancel_s. The engine does the match, so nothing is assigned twice; the assignment chooses which vehicle drives, not which request it takes on arrival.- Parameters:
charge_below (float) – Below this share of its battery, an idle vehicle is sent to charge.
charge_to (float) – The share it charges to (
0 <= charge_below < charge_to <= 1).soc_penalty_s (float) – The cost of a battery used up, in seconds of driving.
step_s (float) – The seconds between its steps (300: a request is cancelled after
request_cancel_s, 600 by default, so a longer step reaches few in time).
- Raises:
ImportError – Without SciPy (the
policiesextra).- Return type:
PolicyAssignment
- openmobisim.contrib.policies.policy_flow_targets(low=0.2, high=0.8, *, holding_s=1800.0, step_s=900.0)#
CFA for docked bikes: bikes moved by a min-cost transportation problem each step.
Each step, per docked service, docks holding (with the bikes on their way) more than
highof their slots can give down to the middle of the band, and docks holding fewer thanlowlack up to it (the threshold rule’s levels). The bikes moved minimise the seconds driven between docks (view.travel_timesat the step, per bike) plusholding_sper bike a dock still lacks: a bike is moved only when the drive is shorter thanholding_s, the tuned term. Solved byscipy.optimize.linprog(HiGHS); a transportation problem with whole supplies and demands has a whole optimum, so the moves are whole bikes. A move above the service’svan_bikesis cut to it by the engine.- Parameters:
low (float) – Below this share of its slots, a dock lacks bikes.
high (float) – Above this share, a dock gives bikes (
0 <= low < high <= 1).holding_s (float) – The cost of a bike a dock still lacks, in seconds of driving.
step_s (float) – The seconds between its steps.
- Raises:
ImportError – Without SciPy (the
policiesextra).- Return type:
PolicyFlowTargets
- openmobisim.contrib.policies.policy_lookahead(*, horizon_s=7200.0, bin_s=900.0, neighbours=5, van_bikes=20, vehicle_requests_bin=2.0, charge_below=0.2, charge_to=0.8, step_s=900.0, weights=None)#
DLA: a mixed-integer program over the next
horizon_s, re-solved every step.Docked bikes. Over the horizon’s bins of
bin_s, each dock’s stock follows the pickups expected (view.expected_legs), the returns forecast at the rate the dock has seen so far in the day, and the bikes moved; the stock stays within[0, slots], the pickups that find it empty find no bike and the returns that find it full go elsewhere. Moves run between each dock and itsneighboursnearest by road (view.travel_times), whole bikes, at mostvan_bikesa van trip. The program minimisesw_cancelled× the pickups with no bike,w_walk× 5 minutes per return gone elsewhere (an assumed walk), andw_km× the van kilometres (seconds driven at 8 m/s, an assumption); the first bin’s moves are applied. Moves arrive within their bin (the drive’s time is left out).Taxis. Each idle vehicle stays, drives empty to a zone where a vehicle or request was seen, or charges (when below
charge_belownot charging costsw_cancelled); per zone and bin the requests picked up are at most those expected (view.expected_legs) andvehicle_requests_binper vehicle there by the bin’s end (busy vehicles count from the second bin, in their zone). The program maximisesw_cancelled× the requests picked up less the kilometres driven.Both solved by
scipy.optimize.milp(HiGHS, at most 10 s a solve); the seconds of each solve are insolve_s. In a day without variation the expected legs are the day’s own (operator): the program then knows the future.- Parameters:
horizon_s (float) – The seconds looked ahead (7 200).
bin_s (float) – The program’s bins, in seconds.
neighbours (int) – The docks each dock may send bikes to.
van_bikes (int) – The bikes a van carries (the service’s option of that name, 20 by default).
vehicle_requests_bin (float) – The requests a taxi picks up per bin, in the program.
charge_below (float) – Below this charge a taxi not sent to charge costs a cancelled request.
charge_to (float) – The share a taxi sent to charge charges to.
step_s (float) – The seconds between its steps.
weights (collections.abc.Mapping[str, float] | None) – Reward weights by name in place of
fleet.REWARD_WEIGHTS’.
- Raises:
ImportError – Without SciPy (the
policiesextra).- Return type:
PolicyLookahead
- openmobisim.contrib.policies.policy_lookahead_simulated(environment, candidates, *, horizon_s=7200.0)#
DLA by simulation: at each step, each candidate policy is run ahead on a copy of the day.
At each step every candidate decides on the view; each candidate’s decisions are applied on
environment.fork()(a copy of the day at its clock) and the candidate then decides alone over the nexthorizon_s; the candidate whose copy earns the highest reward (the first among equals) has its decisions of now applied. The index chosen per step is inchosen. The policy stepsenvironmentitself (it forks it), so it runs withevaluate(policy, environment, seeds)on that same environment, not infleet_day.The copy simulates the day being stepped, with its seed’s own legs: the lookahead knows the day’s future, as a perfect forecast. It is a bound on what the candidates can earn by switching between them, not a policy that could run without that knowledge.
- Parameters:
environment (Any) – The
fleet_environment(n=1) the policy is stepped on.candidates (collections.abc.Sequence[Any]) – Policy objects or built-in
noop,threshold,charge_rule.horizon_s (float) – The seconds simulated ahead (7 200).
- Return type:
PolicyLookaheadSimulated
- openmobisim.contrib.policies.policy_value_table(*, bands=5, learning_rate=0.1, explore=0.1, candidates=((0.1, 0.9), (0.2, 0.8), (0.3, 0.7)), charge_to=0.8, step_s=900.0, weights=None)#
VFA: decisions by the reward now plus a learned value of the state reached.
The value of a state is a sum over the service’s units (docks, or vehicles) of a lookup table’s entry for the unit’s (zone, band, hour): the band of a dock’s fill (bikes, with those on their way, over its slots) or of a vehicle’s charge, in
bandsequal bands, and the hour of the day; an entry not yet learned is 0. Each step, per docked service, the candidates are no moves and the threshold rule’s moves for each(low, high)ofcandidates(paired nearest first); the one of highest value of the fills reached lessw_km× the van kilometres (the seconds driven at 8 m/s, an assumption) is taken. Per idle taxi the candidates are staying, charging at the nearest charger tocharge_to, and driving empty to a zone where a vehicle or request was seen (its node of smallest id).train(environment, episodes, seed)learns the table; before, every value is 0 and the policy does nothing (no moves, vehicles stay).- Parameters:
bands (int) – The fill or charge bands.
learning_rate (float) – The step of each update (a fixed rate).
explore (float) – The share of decisions taken at random while training.
candidates (collections.abc.Sequence[tuple[float, float]]) – The threshold bands a docked service’s candidate moves come from.
charge_to (float) – The share a taxi sent to charge charges to.
step_s (float) – The seconds between its steps.
weights (collections.abc.Mapping[str, float] | None) – Reward weights by name in place of
fleet.REWARD_WEIGHTS’.
- Return type:
PolicyValueTable
- openmobisim.contrib.policies.tune(policy_make, grid, environment, *, seeds_train=(0, 1, 2, 3), seeds_validate=(100, 101, 102, 103), parameters_untuned=None)#
A policy’s parameters chosen by a grid search over training days, scored on others.
Every combination of
grid’s values is evaluated onseeds_train; the one of highest mean episode reward (the first in the grid’s order among equals) is evaluated onseeds_validate, days the search did not see, beside the untuned parameters’.- Parameters:
policy_make (collections.abc.Callable[..., Any]) – Called with one combination as keywords; returns a policy, or
Noneto skip a combination that is not valid.grid (collections.abc.Mapping[str, collections.abc.Sequence[float]]) – The values to try per parameter name.
environment (Any) – A
fleet_environment(n=1) or a callable returning one; withlegs_keepbelow 1 or adeparture_jitter_s, each seed is another day.seeds_train (collections.abc.Sequence[int]) – The days the search scores on.
seeds_validate (collections.abc.Sequence[int]) – The days the chosen parameters are scored on.
parameters_untuned (collections.abc.Mapping[str, float] | None) – The parameters to compare with on the validation days, or
None: not compared.
- Returns:
the chosen parameters and policy,
evaluate’s result for them on the training and the validation days, the untuned parameters’ on the validation days (orNone), and per combination tried{"parameters", "reward_mean"}on the training days.- Return type:
{"parameters", "policy", "train", "validate", "validate_untuned", "grid"}
- openmobisim.contrib.policies.tune_charge_rule(environment, grid=None, *, seeds_train=(0, 1, 2, 3), seeds_validate=(100, 101, 102, 103), step_s=900.0)#
operator.policy_charge_rule’scharge_belowandcharge_totuned over days.As
tune_threshold, the untuned being the rule’s defaults (0.2, 0.8);charge_below = 0never sends a vehicle (the fleet’s own charging rule still acts).- Parameters:
environment (Any) – As
tune.grid (collections.abc.Mapping[str, collections.abc.Sequence[float]] | None) –
{"charge_below": [...], "charge_to": [...]}, orNone:charge_belowin 0, 0.1, 0.2, 0.3, 0.4 andcharge_toin 0.6, 0.8, 1.seeds_train (collections.abc.Sequence[int]) – As
tune.seeds_validate (collections.abc.Sequence[int]) – As
tune.step_s (float) – The policy’s step, as its built-in form records it.
- Return type:
dict[str, Any]
- openmobisim.contrib.policies.tune_threshold(environment, grid=None, *, seeds_train=(0, 1, 2, 3), seeds_validate=(100, 101, 102, 103), step_s=900.0)#
operator.policy_threshold’slowandhightuned over training days.As
tune, the untuned being the rule’s defaults (0.2, 0.8). The policy returned is the built-in one (fleet_dayruns it in Rust).low = 0never tops a dock up: the grid then holds doing nothing, and the training score can only beat it or equal it.- Parameters:
environment (Any) – As
tune.grid (collections.abc.Mapping[str, collections.abc.Sequence[float]] | None) –
{"low": [...], "high": [...]}, orNone:lowin 0, 0.1, 0.2, 0.3 andhighin 0.6, 0.7, 0.8, 0.9, 1 (pairs withlow >= highskipped).seeds_train (collections.abc.Sequence[int]) – As
tune.seeds_validate (collections.abc.Sequence[int]) – As
tune.step_s (float) – The policy’s step, as its built-in form records it.
- Return type:
dict[str, Any]