|
| 1 | +from typing import Iterable |
| 2 | +from collections import defaultdict |
| 3 | +import warnings |
| 4 | + |
| 5 | +try: |
| 6 | + import optuna |
| 7 | +except ImportError as error: |
| 8 | + raise ImportError("Usage of Optuna Sensor Manager requires that the optional package " |
| 9 | + "`optuna`is installed") from error |
| 10 | + |
| 11 | +from ..base import Property |
| 12 | +from ..sensor.sensor import Sensor |
| 13 | +from .action import RealNumberActionGenerator, Action |
| 14 | +from . import SensorManager |
| 15 | + |
| 16 | + |
| 17 | +class OptunaSensorManager(SensorManager): |
| 18 | + """Sensor Manager that uses the optuna package to determine the best actions available within |
| 19 | + a time frame specified by :attr:`timeout`.""" |
| 20 | + timeout: float = Property( |
| 21 | + doc="Number of seconds that the sensor manager should optimise for each time-step", |
| 22 | + default=10.) |
| 23 | + |
| 24 | + def __init__(self, *args, **kwargs): |
| 25 | + super().__init__(*args, **kwargs) |
| 26 | + optuna.logging.set_verbosity(optuna.logging.CRITICAL) |
| 27 | + |
| 28 | + def choose_actions(self, tracks, timestamp, nchoose=1, **kwargs) -> Iterable[tuple[Sensor, |
| 29 | + Action]]: |
| 30 | + """Method to find the best actions for the given :attr:`sensors` to according to the |
| 31 | + :attr:`reward_function`. |
| 32 | +
|
| 33 | + Parameters |
| 34 | + ---------- |
| 35 | + tracks_list : List[Track] |
| 36 | + List of Tracks for the sensor manager to observe. |
| 37 | + timestamp: datetime.datetime |
| 38 | + The time for the actions to be produced for. |
| 39 | +
|
| 40 | + Returns |
| 41 | + ------- |
| 42 | + Iterable[Tuple[Sensor, Action]] |
| 43 | + The actions and associated sensors produced by the sensor manager.""" |
| 44 | + all_action_generators = dict() |
| 45 | + |
| 46 | + for sensor in self.sensors: |
| 47 | + action_generators = sensor.actions(timestamp) |
| 48 | + all_action_generators[sensor] = action_generators # set of generators |
| 49 | + |
| 50 | + def config_from_trial(trial): |
| 51 | + config = defaultdict(list) |
| 52 | + for i, (sensor, generators) in enumerate(all_action_generators.items()): |
| 53 | + |
| 54 | + for j, generator in enumerate(generators): |
| 55 | + if isinstance(generator, RealNumberActionGenerator): |
| 56 | + with warnings.catch_warnings(): |
| 57 | + warnings.simplefilter("ignore", UserWarning) |
| 58 | + value = trial.suggest_float( |
| 59 | + f'{i}{j}', generator.min, generator.max + generator.epsilon, |
| 60 | + step=getattr(generator, 'resolution', None)) |
| 61 | + else: |
| 62 | + raise TypeError(f"type {type(generator)} not handled yet") |
| 63 | + action = generator.action_from_value(value) |
| 64 | + if action is not None: |
| 65 | + config[sensor].append(action) |
| 66 | + else: |
| 67 | + config[sensor].append(generator.default_action) |
| 68 | + return config |
| 69 | + |
| 70 | + def optimise_func(trial): |
| 71 | + config = config_from_trial(trial) |
| 72 | + |
| 73 | + return -self.reward_function(config, tracks, timestamp) |
| 74 | + |
| 75 | + study = optuna.create_study() |
| 76 | + # will finish study after `timeout` seconds has elapsed. |
| 77 | + study.optimize(optimise_func, n_trials=None, timeout=self.timeout) |
| 78 | + |
| 79 | + best_params = study.best_params |
| 80 | + config = defaultdict(list) |
| 81 | + for i, (sensor, generators) in enumerate(all_action_generators.items()): |
| 82 | + for j, generator in enumerate(generators): |
| 83 | + if isinstance(generator, RealNumberActionGenerator): |
| 84 | + action = generator.action_from_value(best_params[f'{i}{j}']) |
| 85 | + else: |
| 86 | + raise TypeError(f"generator type {type(generator)} not supported") |
| 87 | + if action is not None: |
| 88 | + config[sensor].append(action) |
| 89 | + else: |
| 90 | + config[sensor].append(generator.default_action) |
| 91 | + |
| 92 | + # Return mapping of sensors and chosen actions for sensors |
| 93 | + return [config] |
0 commit comments