|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import numpy as np |
| 7 | +import optuna |
| 8 | +from optuna.study import StudyDirection |
| 9 | +from optuna.trial import TrialState |
| 10 | + |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from collections.abc import Callable |
| 14 | + from typing import Any |
| 15 | + |
| 16 | + from matplotlib.axes import Axes |
| 17 | + from matplotlib.lines import Line2D |
| 18 | + |
| 19 | + |
| 20 | +def _get_values_on_fixed_time_steps( |
| 21 | + cumtime_list: list[np.ndarray], |
| 22 | + target_list: list[np.ndarray], |
| 23 | + log_time_scale: bool, |
| 24 | + n_steps: int, |
| 25 | +) -> tuple[np.ndarray, np.ndarray]: |
| 26 | + t_min = np.min(np.stack(cumtime_list)) |
| 27 | + t_max = np.max(np.stack(cumtime_list)) |
| 28 | + if log_time_scale: |
| 29 | + ts = np.exp(np.linspace(np.log(t_min), np.log(t_max), num=n_steps)) |
| 30 | + else: |
| 31 | + ts = np.linspace(t_min, t_max, num=n_steps) |
| 32 | + v_on_grid = [] |
| 33 | + for ct, v in zip(cumtime_list, target_list): |
| 34 | + i_upper = np.minimum(np.searchsorted(ct, ts, side="left"), v.size - 1) |
| 35 | + v_on_grid.append(v[i_upper]) |
| 36 | + return ts, np.array(v_on_grid) |
| 37 | + |
| 38 | + |
| 39 | +def _validate( |
| 40 | + valid_states: tuple[TrialState, ...], |
| 41 | + states: tuple[TrialState, ...], |
| 42 | + target: Callable[[optuna.trial.FrozenTrial], float] | None, |
| 43 | + target_direction: StudyDirection | str | None, |
| 44 | +) -> None: |
| 45 | + if any(s not in valid_states for s in states): |
| 46 | + raise ValueError(f"{states=} must be in {valid_states}.") |
| 47 | + if target_direction is None: |
| 48 | + if target is not None: |
| 49 | + raise ValueError("target was specified, but got target_direction=None.") |
| 50 | + else: |
| 51 | + if target is None: |
| 52 | + raise ValueError("target_direction was provided, but got target=None.") |
| 53 | + if target_direction not in [ |
| 54 | + "minimize", |
| 55 | + "maximize", |
| 56 | + StudyDirection.MAXIMIZE, |
| 57 | + StudyDirection.MINIMIZE, |
| 58 | + ]: |
| 59 | + raise ValueError( |
| 60 | + f"target_direction must be either `minimize` or `maximize` but got {target_direction=}" |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +def plot_target_over_time( |
| 65 | + study_list: list[optuna.Study], |
| 66 | + *, |
| 67 | + color: str, |
| 68 | + ax: Axes | None = None, |
| 69 | + states: tuple[TrialState, ...] | None = None, |
| 70 | + target: Callable[[optuna.trial.FrozenTrial], float] | None = None, |
| 71 | + target_direction: optuna.study.StudyDirection | str | None = None, |
| 72 | + cumtime_func: Callable[[optuna.trial.FrozenTrial], float] | None = None, |
| 73 | + log_time_scale: bool = True, |
| 74 | + n_steps: int = 100, |
| 75 | + **plot_kwargs: Any, |
| 76 | +) -> Line2D: |
| 77 | + if ax is None: |
| 78 | + _, ax = plt.subplots() |
| 79 | + |
| 80 | + valid_states = (TrialState.COMPLETE, TrialState.PRUNED) |
| 81 | + states = states or valid_states |
| 82 | + assert states is not None, "Mypy Redefinition." |
| 83 | + _validate(valid_states, states, target, target_direction) |
| 84 | + |
| 85 | + target_list = [] |
| 86 | + cumtime_list = [] |
| 87 | + direction = target_direction or study_list[0].direction |
| 88 | + for study in study_list: |
| 89 | + trials = study.get_trials(deepcopy=False, states=states) |
| 90 | + target_vals = np.array([target(t) if target is not None else t.value for t in trials]) |
| 91 | + if cumtime_func is not None: |
| 92 | + cumtime_list.append(np.array([cumtime_func(t) for t in trials])) |
| 93 | + else: |
| 94 | + datetime_start = min(t.datetime_start for t in trials if t.datetime_start is not None) |
| 95 | + cumtimes = np.array( |
| 96 | + [ |
| 97 | + (t.datetime_complete - datetime_start).total_seconds() |
| 98 | + for t in trials |
| 99 | + if t.datetime_complete is not None |
| 100 | + ] |
| 101 | + ) |
| 102 | + cumtime_list.append(cumtimes) |
| 103 | + order = np.argsort(cumtime_list[-1]) |
| 104 | + cumtime_list[-1] = cumtime_list[-1][order] |
| 105 | + if direction in ["minimize", StudyDirection.MINIMIZE]: |
| 106 | + target_list.append(np.minimum.accumulate(target_vals[order])) |
| 107 | + else: |
| 108 | + target_list.append(np.maximum.accumulate(target_vals[order])) |
| 109 | + |
| 110 | + ts, vs = _get_values_on_fixed_time_steps( |
| 111 | + cumtime_list, |
| 112 | + target_list, |
| 113 | + log_time_scale, |
| 114 | + n_steps, |
| 115 | + ) |
| 116 | + m = np.mean(vs, axis=0) |
| 117 | + s = np.std(vs, axis=0) / np.sqrt(len(study_list)) |
| 118 | + (line,) = ax.plot(ts, m, color=color, **plot_kwargs) |
| 119 | + ax.fill_between(ts, m - s, m + s, color=color, alpha=0.2) |
| 120 | + return line |
| 121 | + |
| 122 | + |
| 123 | +__all__ = ["plot_target_over_time"] |
0 commit comments