|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections.abc import Sequence |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +import optuna |
| 7 | + |
| 8 | + |
| 9 | +class ConstrainedMixin: |
| 10 | + """Mixin class for constrained optimization problems. |
| 11 | +
|
| 12 | + Example: |
| 13 | + You can define a constrained optimization problem by inheriting this class and implementing |
| 14 | + the :meth:`evaluate_constraints` method as follows. |
| 15 | +
|
| 16 | + :: |
| 17 | +
|
| 18 | + import optuna |
| 19 | + import optunahub |
| 20 | +
|
| 21 | + class BinAndKorn(optunahub.benchmarks.ConstrainedMixin, optunahub.benchmarks.BaseProblem): |
| 22 | + def evaluate(self, params: dict[str, float]) -> tuple[float]: |
| 23 | + x = params["x"] |
| 24 | + y = params["y"] |
| 25 | +
|
| 26 | + v0 = 4 * x**2 + 4 * y**2 |
| 27 | + v1 = (x - 5)**2 + (y - 5)**2 |
| 28 | +
|
| 29 | + return v0, v1 |
| 30 | +
|
| 31 | + def evaluate_constraints(self, params: dict[str, float]) -> tuple[float]: |
| 32 | + x = params["x"] |
| 33 | + y = params["y"] |
| 34 | +
|
| 35 | + # Constraints which are considered feasible if less than or equal to zero. |
| 36 | + # The feasible region is basically the intersection of a circle centered at (x=5, y=0) |
| 37 | + # and the complement to a circle centered at (x=8, y=-3). |
| 38 | + c0 = (x - 5)**2 + y**2 - 25 |
| 39 | + c1 = -((x - 8)**2) - (y + 3)**2 + 7.7 |
| 40 | +
|
| 41 | + return c0, c1 |
| 42 | +
|
| 43 | + @property |
| 44 | + def search_space(self) -> dict[str, optuna.distributions.BaseDistribution]: |
| 45 | + return { |
| 46 | + "x": optuna.distributions.FloatDistribution(low=-15, high=30), |
| 47 | + "y": optuna.distributions.FloatDistribution(low=-15, high=30) |
| 48 | + } |
| 49 | +
|
| 50 | + @property |
| 51 | + def directions(self) -> list[optuna.study.StudyDirection]: |
| 52 | + return [optuna.study.StudyDirection.MINIMIZE, optuna.study.StudyDirection.MINIMIZE] |
| 53 | +
|
| 54 | + problem = BinAndKorn() |
| 55 | + sampler = optuna.samplers.TPESampler(constraints_func=problem.constraints_func) |
| 56 | + study = optuna.create_study(sampler=sampler, directions=problem.directions) |
| 57 | + study.optimize(problem, n_trials=20) |
| 58 | + """ |
| 59 | + |
| 60 | + def constraints_func(self, trial: optuna.trial.FrozenTrial) -> Sequence[float]: |
| 61 | + """Evaluate the constraint functions. |
| 62 | +
|
| 63 | + Args: |
| 64 | + trial: Optuna trial object. |
| 65 | + Returns: |
| 66 | + List of the constraint values. |
| 67 | + """ |
| 68 | + return self.evaluate_constraints(trial.params.copy()) |
| 69 | + |
| 70 | + def evaluate_constraints(self, params: dict[str, Any]) -> Sequence[float]: |
| 71 | + """Evaluate the constraint functions. |
| 72 | +
|
| 73 | + Args: |
| 74 | + params: Dictionary of input parameters. |
| 75 | + Returns: |
| 76 | + List of the constraint values. |
| 77 | + """ |
| 78 | + raise NotImplementedError |
0 commit comments