openmobisim.contrib.policies ============================ .. py:module:: openmobisim.contrib.policies .. autoapi-nested-parse:: 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_threshold`` and ``operator.policy_charge_rule``, tuned here by a grid over episodes (``tune_threshold``, ``tune_charge_rule``; ``tune`` for 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) and ``policy_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 on ``view.expected_legs``) and ``policy_lookahead_simulated`` (a few candidate policies simulated ahead on ``environment.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 --------- .. autoapisummary:: openmobisim.contrib.policies.evaluate openmobisim.contrib.policies.policy_assignment openmobisim.contrib.policies.policy_flow_targets openmobisim.contrib.policies.policy_lookahead openmobisim.contrib.policies.policy_lookahead_simulated openmobisim.contrib.policies.policy_value_table openmobisim.contrib.policies.tune openmobisim.contrib.policies.tune_charge_rule openmobisim.contrib.policies.tune_threshold Module Contents --------------- .. py:function:: 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_s`` rules, 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). :param policy: A policy object (``step(view)``), a built-in ``noop``, ``threshold`` or ``charge_rule`` (``operator.policy_threshold(...)`` or its name; stepped in its Python form, deciding the same), or ``None``: no decisions. :param environment: A ``fleet_environment`` (``n=1``), or a callable returning one. :param seeds: 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. .. py:function:: 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_s`` less its dispatch delay ``dispatch_delay_s`` the moment it is made; a request no vehicle can reach in time **waits** (``waiting_node`` in the view). Each step, this policy (1) sends every idle vehicle below ``charge_below`` to its nearest charger, to charge to ``charge_to``, and (2) assigns the other idle vehicles to the waiting requests, one each, minimising the seconds to the pickup (``view.travel_times``) plus ``soc_penalty_s`` × the share of battery used, by ``scipy.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's ``request_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. :param charge_below: Below this share of its battery, an idle vehicle is sent to charge. :param charge_to: The share it charges to (``0 <= charge_below < charge_to <= 1``). :param soc_penalty_s: The cost of a battery used up, in seconds of driving. :param step_s: 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 ``policies`` extra). .. py:function:: 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 ``high`` of their slots can give down to the middle of the band, and docks holding fewer than ``low`` lack up to it (the threshold rule's levels). The bikes moved minimise the seconds driven between docks (``view.travel_times`` at the step, per bike) plus ``holding_s`` per bike a dock still lacks: a bike is moved only when the drive is shorter than ``holding_s``, the tuned term. Solved by ``scipy.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's ``van_bikes`` is cut to it by the engine. :param low: Below this share of its slots, a dock lacks bikes. :param high: Above this share, a dock gives bikes (``0 <= low < high <= 1``). :param holding_s: The cost of a bike a dock still lacks, in seconds of driving. :param step_s: The seconds between its steps. :raises ImportError: Without SciPy (the ``policies`` extra). .. py:function:: 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 its ``neighbours`` nearest by road (``view.travel_times``), whole bikes, at most ``van_bikes`` a van trip. The program minimises ``w_cancelled`` × the pickups with no bike, ``w_walk`` × 5 minutes per return gone elsewhere (an assumed walk), and ``w_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_below`` not charging costs ``w_cancelled``); per zone and bin the requests picked up are at most those expected (``view.expected_legs``) and ``vehicle_requests_bin`` per vehicle there by the bin's end (busy vehicles count from the second bin, in their zone). The program maximises ``w_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 in ``solve_s``. In a day without variation the expected legs are the day's own (``operator``): the program then knows the future. :param horizon_s: The seconds looked ahead (7 200). :param bin_s: The program's bins, in seconds. :param neighbours: The docks each dock may send bikes to. :param van_bikes: The bikes a van carries (the service's option of that name, 20 by default). :param vehicle_requests_bin: The requests a taxi picks up per bin, in the program. :param charge_below: Below this charge a taxi not sent to charge costs a cancelled request. :param charge_to: The share a taxi sent to charge charges to. :param step_s: The seconds between its steps. :param weights: Reward weights by name in place of ``fleet.REWARD_WEIGHTS``'. :raises ImportError: Without SciPy (the ``policies`` extra). .. py:function:: 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 next ``horizon_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 in ``chosen``. The policy steps ``environment`` itself (it forks it), so it runs with ``evaluate(policy, environment, seeds)`` on that same environment, not in ``fleet_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. :param environment: The ``fleet_environment`` (``n=1``) the policy is stepped on. :param candidates: Policy objects or built-in ``noop``, ``threshold``, ``charge_rule``. :param horizon_s: The seconds simulated ahead (7 200). .. py:function:: 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 ``bands`` equal 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)`` of ``candidates`` (paired nearest first); the one of highest value of the fills reached less ``w_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 to ``charge_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). :param bands: The fill or charge bands. :param learning_rate: The step of each update (a fixed rate). :param explore: The share of decisions taken at random while training. :param candidates: The threshold bands a docked service's candidate moves come from. :param charge_to: The share a taxi sent to charge charges to. :param step_s: The seconds between its steps. :param weights: Reward weights by name in place of ``fleet.REWARD_WEIGHTS``'. .. py:function:: 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 on ``seeds_train``; the one of highest mean episode reward (the first in the grid's order among equals) is evaluated on ``seeds_validate``, days the search did not see, beside the untuned parameters'. :param policy_make: Called with one combination as keywords; returns a policy, or ``None`` to skip a combination that is not valid. :param grid: The values to try per parameter name. :param environment: A ``fleet_environment`` (``n=1``) or a callable returning one; with ``legs_keep`` below 1 or a ``departure_jitter_s``, each seed is another day. :param seeds_train: The days the search scores on. :param seeds_validate: The days the chosen parameters are scored on. :param parameters_untuned: 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 (or ``None``), and per combination tried ``{"parameters", "reward_mean"}`` on the training days. :rtype: ``{"parameters", "policy", "train", "validate", "validate_untuned", "grid"}`` .. py:function:: 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``'s ``charge_below`` and ``charge_to`` tuned over days. As ``tune_threshold``, the untuned being the rule's defaults (0.2, 0.8); ``charge_below = 0`` never sends a vehicle (the fleet's own charging rule still acts). :param environment: As ``tune``. :param grid: ``{"charge_below": [...], "charge_to": [...]}``, or ``None``: ``charge_below`` in 0, 0.1, 0.2, 0.3, 0.4 and ``charge_to`` in 0.6, 0.8, 1. :param seeds_train: As ``tune``. :param seeds_validate: As ``tune``. :param step_s: The policy's step, as its built-in form records it. .. py:function:: tune_threshold(environment, grid = None, *, seeds_train = (0, 1, 2, 3), seeds_validate = (100, 101, 102, 103), step_s = 900.0) ``operator.policy_threshold``'s ``low`` and ``high`` tuned 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_day`` runs it in Rust). ``low = 0`` never tops a dock up: the grid then holds doing nothing, and the training score can only beat it or equal it. :param environment: As ``tune``. :param grid: ``{"low": [...], "high": [...]}``, or ``None``: ``low`` in 0, 0.1, 0.2, 0.3 and ``high`` in 0.6, 0.7, 0.8, 0.9, 1 (pairs with ``low >= high`` skipped). :param seeds_train: As ``tune``. :param seeds_validate: As ``tune``. :param step_s: The policy's step, as its built-in form records it.