File: test_intermediate_plot.py

package info (click to toggle)
optuna 4.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,784 kB
  • sloc: python: 40,634; sh: 97; makefile: 30
file content (131 lines) | stat: -rw-r--r-- 4,566 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from io import BytesIO
from typing import Any
from typing import Callable
from typing import Sequence

import pytest

from optuna.study import create_study
from optuna.testing.objectives import fail_objective
from optuna.trial import FrozenTrial
from optuna.trial import Trial
import optuna.visualization._intermediate_values
from optuna.visualization._intermediate_values import _get_intermediate_plot_info
from optuna.visualization._intermediate_values import _IntermediatePlotInfo
from optuna.visualization._intermediate_values import _TrialInfo
from optuna.visualization._plotly_imports import go
import optuna.visualization.matplotlib._intermediate_values
from optuna.visualization.matplotlib._matplotlib_imports import plt


def test_intermediate_plot_info() -> None:
    # Test with no trials.
    study = create_study(direction="minimize")

    assert _get_intermediate_plot_info(study) == _IntermediatePlotInfo(trial_infos=[])

    # Test with a trial with intermediate values.
    def objective(trial: Trial, report_intermediate_values: bool) -> float:
        if report_intermediate_values:
            trial.report(1.0, step=0)
            trial.report(2.0, step=1)
        return 0.0

    study = create_study()
    study.optimize(lambda t: objective(t, True), n_trials=1)

    assert _get_intermediate_plot_info(study) == _IntermediatePlotInfo(
        trial_infos=[
            _TrialInfo(
                trial_number=0, sorted_intermediate_values=[(0, 1.0), (1, 2.0)], feasible=True
            )
        ]
    )

    # Test a study with one trial with intermediate values and
    # one trial without intermediate values.
    # Expect the trial with no intermediate values to be ignored.
    study.optimize(lambda t: objective(t, False), n_trials=1)

    assert _get_intermediate_plot_info(study) == _IntermediatePlotInfo(
        trial_infos=[
            _TrialInfo(
                trial_number=0, sorted_intermediate_values=[(0, 1.0), (1, 2.0)], feasible=True
            )
        ]
    )

    # Test a study of only one trial that has no intermediate values.
    study = create_study()
    study.optimize(lambda t: objective(t, False), n_trials=1)
    assert _get_intermediate_plot_info(study) == _IntermediatePlotInfo(trial_infos=[])

    # Ignore failed trials.
    study = create_study()
    study.optimize(fail_objective, n_trials=1, catch=(ValueError,))
    assert _get_intermediate_plot_info(study) == _IntermediatePlotInfo(trial_infos=[])

    # Test a study with constraints
    def objective_with_constraints(trial: Trial) -> float:
        trial.set_user_attr("constraint", [trial.number % 2])

        trial.report(1.0, step=0)
        trial.report(2.0, step=1)
        return 0.0

    def constraints(trial: FrozenTrial) -> Sequence[float]:
        return trial.user_attrs["constraint"]

    study = create_study(sampler=optuna.samplers.NSGAIIISampler(constraints_func=constraints))
    study.optimize(objective_with_constraints, n_trials=2)
    assert _get_intermediate_plot_info(study) == _IntermediatePlotInfo(
        trial_infos=[
            _TrialInfo(
                trial_number=0, sorted_intermediate_values=[(0, 1.0), (1, 2.0)], feasible=True
            ),
            _TrialInfo(
                trial_number=1, sorted_intermediate_values=[(0, 1.0), (1, 2.0)], feasible=False
            ),
        ]
    )


@pytest.mark.parametrize(
    "plotter",
    [
        optuna.visualization._intermediate_values._get_intermediate_plot,
        optuna.visualization.matplotlib._intermediate_values._get_intermediate_plot,
    ],
)
@pytest.mark.parametrize(
    "info",
    [
        _IntermediatePlotInfo(trial_infos=[]),
        _IntermediatePlotInfo(
            trial_infos=[
                _TrialInfo(
                    trial_number=0, sorted_intermediate_values=[(0, 1.0), (1, 2.0)], feasible=True
                )
            ]
        ),
        _IntermediatePlotInfo(
            trial_infos=[
                _TrialInfo(
                    trial_number=0, sorted_intermediate_values=[(0, 1.0), (1, 2.0)], feasible=True
                ),
                _TrialInfo(
                    trial_number=1, sorted_intermediate_values=[(1, 2.0), (0, 1.0)], feasible=False
                ),
            ]
        ),
    ],
)
def test_plot_intermediate_values(
    plotter: Callable[[_IntermediatePlotInfo], Any], info: _IntermediatePlotInfo
) -> None:
    figure = plotter(info)
    if isinstance(figure, go.Figure):
        figure.write_image(BytesIO())
    else:
        plt.savefig(BytesIO())
        plt.close()