From 46530733915bd0fe693ff7474dc6467c4d860df0 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Thu, 19 Nov 2026 10:08:20 +0100 Subject: [PATCH 1/6] Add typed benchmark problems, noise, scalers and results. Implement the benchmarking section of EP-02 with a representation of benchmark problems that has two levels: - BenchmarkFunction: the core of a problem (objective function, optional derivative, supported numbers of parameters, properties like differentiability). Functions are defined by subclassing. - BenchmarkProblem: a benchmark function with start parameters and optionally bounds, a known solution, noise and scaling. Further changes: - BenchmarkNoise and BenchmarkScaler replace the noise and scaling option dictionaries of get_benchmark_problems. The old arguments are deprecated. - run_benchmark returns BenchmarkResult objects. Lists of algorithms and dictionaries of minimize keyword arguments as optimize_options are deprecated in favor of algorithms and the new OptimizeOptions. - Solutions are optional and can be marked as exact or best known. Plots and reports fall back to the best value found by any optimizer. - The More-Wild functions are converted to BenchmarkFunction subclasses; the Cartis-Roberts functions are wrapped with CallableBenchmarkFunction. Co-Authored-By: Claude Fable 5.2 --- docs/source/development/ep-02-typing.md | 20 + docs/source/how_to/how_to_benchmarking.ipynb | 270 +++-- docs/source/reference/index.md | 60 + src/optimagic/__init__.py | 31 + .../benchmarking/benchmark_problem.py | 669 ++++++++++ .../benchmarking/benchmark_reports.py | 251 ++-- .../benchmarking/benchmark_result.py | 45 + src/optimagic/benchmarking/cartis_roberts.py | 861 +++++++------ .../benchmarking/get_benchmark_problems.py | 622 ++++------ src/optimagic/benchmarking/more_wild.py | 1077 ++++++++++------- src/optimagic/benchmarking/noise.py | 284 +++++ .../benchmarking/process_benchmark_results.py | 207 +++- src/optimagic/benchmarking/run_benchmark.py | 383 ++++-- src/optimagic/benchmarking/scaling.py | 107 ++ .../optimization/optimize_options.py | 52 + .../visualization/convergence_plot.py | 26 +- src/optimagic/visualization/deviation_plot.py | 10 +- src/optimagic/visualization/profile_plot.py | 15 +- .../benchmarking/test_benchmark_problem.py | 557 +++++++++ .../benchmarking/test_benchmark_reports.py | 221 ++-- .../benchmarking/test_cartis_roberts.py | 132 +- .../test_get_benchmark_problems.py | 329 ++++- .../optimagic/benchmarking/test_more_wild.py | 128 +- tests/optimagic/benchmarking/test_noise.py | 138 +++ .../benchmarking/test_noise_distributions.py | 8 +- .../test_process_benchmark_results.py | 222 ++++ .../benchmarking/test_run_benchmark.py | 394 +++++- tests/optimagic/benchmarking/test_scaling.py | 47 + .../optimization/test_optimize_options.py | 49 + .../visualization/test_convergence_plot.py | 32 +- .../visualization/test_deviation_plot.py | 11 +- .../visualization/test_profile_plot.py | 14 +- 32 files changed, 5421 insertions(+), 1851 deletions(-) create mode 100644 src/optimagic/benchmarking/benchmark_problem.py create mode 100644 src/optimagic/benchmarking/benchmark_result.py create mode 100644 src/optimagic/benchmarking/noise.py create mode 100644 src/optimagic/benchmarking/scaling.py create mode 100644 src/optimagic/optimization/optimize_options.py create mode 100644 tests/optimagic/benchmarking/test_benchmark_problem.py create mode 100644 tests/optimagic/benchmarking/test_noise.py create mode 100644 tests/optimagic/benchmarking/test_process_benchmark_results.py create mode 100644 tests/optimagic/benchmarking/test_scaling.py create mode 100644 tests/optimagic/optimization/test_optimize_options.py diff --git a/docs/source/development/ep-02-typing.md b/docs/source/development/ep-02-typing.md index 0d8c2dcb3..1c14112bf 100644 --- a/docs/source/development/ep-02-typing.md +++ b/docs/source/development/ep-02-typing.md @@ -1485,6 +1485,26 @@ All of these will be very simple wrappers around `first_derivative` and ## Benchmarking +```{note} +The implementation in version `0.6.0` follows this section with a few changes: + +- A benchmark problem is split into two classes. A `BenchmarkFunction` is the core of a + problem (the objective function, optionally its derivative, the numbers of parameters + it supports and properties like differentiability). A `BenchmarkProblem` combines a + benchmark function with start parameters and optionally bounds, a known solution, + noise and scaling. The same function can be used in several problems, e.g. with good + and bad start parameters. Functions are defined by subclassing, i.e. `fun` is a method + and not an attribute. +- The solution of a `BenchmarkProblem` is optional and states whether it is exact or + only the best known value. Without an exact solution, plots and reports use the best + function value any of the compared optimizers found. +- `draw_noise` has no `size` argument because the size follows from `fval`. +- The result of the optimization is stored as `optimize_result` instead of `solution` + in `BenchmarkResult`, because `solution` is the known solution of a + `BenchmarkProblem`. +- The deprecated arguments are removed in version `0.7.0`. +``` + ### `get_benchmark_problems` #### Current situation diff --git a/docs/source/how_to/how_to_benchmarking.ipynb b/docs/source/how_to/how_to_benchmarking.ipynb index 7838f7c9f..e98bf6d0d 100644 --- a/docs/source/how_to/how_to_benchmarking.ipynb +++ b/docs/source/how_to/how_to_benchmarking.ipynb @@ -28,85 +28,163 @@ "\n", "optimagic includes the problems of [Moré and Wild (2009)](https://doi.org/10.1137/080724083) as well as [Cartis and Roberts](https://arxiv.org/abs/1710.11005).\n", "\n", - "Each problem consist of the `inputs` (the criterion function and the start parameters) and the `solution` (the optimal parameters and criterion value) and optionally provides more information.\n", - "\n", - "Below we load a subset of the Moré and Wild problems and look at one particular Rosenbrock problem that has difficult start parameters." + "`get_benchmark_problems` returns a dictionary that maps the names of the problems to `BenchmarkProblem` objects. Below we load a subset of the Moré and Wild problems." ] }, { "cell_type": "code", - "execution_count": null, "id": "2", "metadata": {}, - "outputs": [], "source": [ "import plotly.io as pio\n", "\n", "pio.renderers.default = \"notebook_connected\"\n", "\n", "import optimagic as om" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "code", - "execution_count": null, "id": "3", "metadata": {}, - "outputs": [], "source": [ "problems = om.get_benchmark_problems(\"example\")" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", "id": "4", "metadata": {}, "source": [ - "## 2. Specify the Optimizers\n", + "Each problem consists of the `function` that is minimized, the `start_params` and, if it is known, the `solution`. Let's look at the Rosenbrock problem:" + ] + }, + { + "cell_type": "code", + "id": "5", + "metadata": {}, + "source": [ + "problem = problems[\"rosenbrock_good_start\"]\n", + "problem.function, problem.start_params, problem.solution" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "6", + "metadata": {}, + "source": [ + "The same function can be used in several problems. For example, the full Moré and Wild set contains a second Rosenbrock problem that starts further away from the solution.\n", "\n", - "To select optimizers you want to benchmark on the set of problems, you can simply specify them as a list. Advanced examples - that do not only compare algorithms but also vary the `algo_options` - can be found below. " + "Because the problems are stored in a dictionary, you can select or combine problems with standard Python tools. For example, this keeps the problems with at most four parameters:" ] }, { "cell_type": "code", + "id": "7", + "metadata": {}, + "source": [ + "small_problems = {\n", + " name: problem for name, problem in problems.items() if problem.n_params <= 4\n", + "}\n", + "list(small_problems)" + ], "execution_count": null, - "id": "5", + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "8", + "metadata": {}, + "source": [ + "### Make the problems harder\n", + "\n", + "You can add noise to the function values and rescale the parameters to see how well optimizers cope with these difficulties. `noise=True` and `scaling=True` use default settings. For more control, pass a noise object or a scaler. Noise objects can be combined with `+`." + ] + }, + { + "cell_type": "code", + "id": "9", "metadata": {}, - "outputs": [], "source": [ - "optimizers = [\n", - " \"nag_dfols\",\n", - " \"scipy_neldermead\",\n", - " \"scipy_truncated_newton\",\n", - "]" + "hard_problems = om.get_benchmark_problems(\n", + " \"example\",\n", + " noise=om.AdditiveBenchmarkNoise(std=0.1) + om.MultiplicativeBenchmarkNoise(),\n", + " scaling=om.LinspaceBenchmarkScaler(min_scale=0.1, max_scale=10),\n", + " seed=0,\n", + ")" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "10", + "metadata": {}, + "source": [ + "## 2. Specify the Optimizers\n", + "\n", + "To select the optimizers you want to benchmark, create a dictionary that maps a name of your choice to an algorithm. The values can be algorithm classes, algorithm names or configured algorithms such as `om.algos.scipy_neldermead(stopping_maxfun=500)`. This lets you compare different options of the same algorithm." ] }, + { + "cell_type": "code", + "id": "11", + "metadata": {}, + "source": [ + "optimizers = {\n", + " \"dfols\": om.algos.nag_dfols,\n", + " \"nelder_mead\": om.algos.scipy_neldermead,\n", + " \"truncated_newton\": om.algos.scipy_truncated_newton,\n", + "}" + ], + "execution_count": null, + "outputs": [] + }, { "cell_type": "markdown", - "id": "6", + "id": "12", "metadata": {}, "source": [ + "If you need to set more than the algorithm, e.g. options for numerical derivatives, use `om.OptimizeOptions(algorithm=..., numdiff_options=...)` as value.\n", + "\n", "## 3. Run the Benchmark\n", "\n", - "Once you have your problems and your optimizers set up, you can simply use `run_benchmark`. The results are a dictionary with one entry for each (problem, algorithm) combination. Each entry not only saves the solution but also the history of the algorithm's criterion and parameter history. " + "Once you have your problems and your optimizers set up, you can simply use `run_benchmark`. The results are a dictionary with one `BenchmarkResult` for each (problem, optimizer) combination. Each result contains the history of the parameters and function values and the result of the optimization." ] }, { "cell_type": "code", - "execution_count": null, - "id": "7", + "id": "13", "metadata": {}, - "outputs": [], "source": [ "results = om.run_benchmark(\n", " problems,\n", " optimizers,\n", ")" - ] + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "14", + "metadata": {}, + "source": [ + "result = results[(\"rosenbrock_good_start\", \"dfols\")]\n", + "result.fun_history[:5]" + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "8", + "id": "15", "metadata": {}, "source": [ "## 4a. Profile plots\n", @@ -118,10 +196,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "9", + "id": "16", "metadata": {}, - "outputs": [], "source": [ "fig = om.profile_plot(\n", " problems=problems,\n", @@ -129,11 +205,13 @@ ")\n", "\n", "fig.show()" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "10", + "id": "17", "metadata": {}, "source": [ ":::{note}\n", @@ -145,7 +223,7 @@ }, { "cell_type": "markdown", - "id": "11", + "id": "18", "metadata": {}, "source": [ "The x axis shows runtime per problem. The y axis shows the share of problems each algorithm solved within that runtime. Thus, higher and further to the left values are desirable. Higher means more problems were solved and further to the left means, the algorithm found the solutions earlier. \n", @@ -161,10 +239,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "12", + "id": "19", "metadata": {}, - "outputs": [], "source": [ "fig = om.profile_plot(\n", " problems=problems,\n", @@ -175,11 +251,13 @@ ")\n", "\n", "fig.show()" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "13", + "id": "20", "metadata": {}, "source": [ "## 4b. Convergence plots\n", @@ -189,10 +267,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "14", + "id": "21", "metadata": {}, - "outputs": [], "source": [ "fig = om.convergence_plot(\n", " problems=problems,\n", @@ -202,11 +278,13 @@ ")\n", "\n", "fig.show()" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "15", + "id": "22", "metadata": {}, "source": [ "The further to the left and the lower the curve of an algorithm, the better that algorithm performed.\n", @@ -216,10 +294,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "16", + "id": "23", "metadata": {}, - "outputs": [], "source": [ "fig = om.convergence_plot(\n", " problems=problems,\n", @@ -231,11 +307,13 @@ ")\n", "\n", "fig.show()" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "17", + "id": "24", "metadata": {}, "source": [ "## 5a. Convergence report\n", @@ -246,10 +324,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "18", + "id": "25", "metadata": {}, - "outputs": [], "source": [ "df = om.convergence_report(\n", " problems=problems,\n", @@ -258,21 +334,23 @@ " x_precision=1e-4,\n", " y_precision=1e-4,\n", ")" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "code", - "execution_count": null, - "id": "19", + "id": "26", "metadata": {}, - "outputs": [], "source": [ "df" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "20", + "id": "27", "metadata": {}, "source": [ "## 5b. Rank report\n", @@ -282,10 +360,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "21", + "id": "28", "metadata": {}, - "outputs": [], "source": [ "df = om.rank_report(\n", " problems=problems,\n", @@ -295,21 +371,23 @@ " x_precision=1e-4,\n", " y_precision=1e-4,\n", ")" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "code", - "execution_count": null, - "id": "22", + "id": "29", "metadata": {}, - "outputs": [], "source": [ "df" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "23", + "id": "30", "metadata": {}, "source": [ "## 5b. Traceback report\n", @@ -319,22 +397,74 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "24", + "id": "31", "metadata": {}, - "outputs": [], "source": [ "df = om.traceback_report(problems=problems, results=results)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "32", + "metadata": {}, + "source": [ + "df" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "33", + "metadata": {}, + "source": [ + "## 6. Benchmark your own problems\n", + "\n", + "To create your own problem, define a benchmark function and combine it with start parameters in a `BenchmarkProblem`. A benchmark function is a subclass of `ScalarBenchmarkFunction`, `LeastSquaresBenchmarkFunction` or `LikelihoodBenchmarkFunction` that implements `fun`. It is not tied to one number of parameters; the number of parameters is fixed by the start parameters of the problem." ] }, { "cell_type": "code", + "id": "34", + "metadata": {}, + "source": [ + "import numpy as np\n", + "\n", + "\n", + "class ShiftedSphere(om.LeastSquaresBenchmarkFunction):\n", + " differentiable = True\n", + " convex = True\n", + "\n", + " def fun(self, x):\n", + " # the residuals; optimizers minimize the sum of their squares\n", + " return x - 1\n", + "\n", + "\n", + "own_problems = {\n", + " f\"shifted_sphere_{n}\": om.BenchmarkProblem(\n", + " function=ShiftedSphere(),\n", + " start_params=np.zeros(n),\n", + " solution=om.BenchmarkSolution(fun=0.0, params=np.ones(n), exact=True),\n", + " )\n", + " for n in [2, 10, 50]\n", + "}\n", + "\n", + "own_results = om.run_benchmark(own_problems, optimizers)\n", + "om.convergence_report(own_problems, own_results)" + ], "execution_count": null, - "id": "25", + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "35", "metadata": {}, - "outputs": [], "source": [ - "df" + "The `solution` is optional. If you leave it out, plots and reports compare each optimizer to the best function value any of the optimizers found. If the solution is the result of a long optimization run and not known exactly, leave `exact` at its default `False`. It is then replaced automatically if an optimizer finds a better value.\n", + "\n", + "To turn an existing Python function into a benchmark function without writing a class, use `om.CallableBenchmarkFunction`." ] } ], diff --git a/docs/source/reference/index.md b/docs/source/reference/index.md index 728a29d38..f673357cc 100644 --- a/docs/source/reference/index.md +++ b/docs/source/reference/index.md @@ -182,6 +182,66 @@ .. autofunction:: run_benchmark ``` +```{eval-rst} +.. dropdown:: Benchmark problems + + .. autoclass:: BenchmarkProblem + :members: + + .. autoclass:: BenchmarkSolution + :members: + +``` + +```{eval-rst} +.. dropdown:: Benchmark functions + + .. autoclass:: BenchmarkFunction + :members: + + .. autoclass:: ScalarBenchmarkFunction + + .. autoclass:: LeastSquaresBenchmarkFunction + + .. autoclass:: LikelihoodBenchmarkFunction + + .. autoclass:: CallableBenchmarkFunction + +``` + +```{eval-rst} +.. dropdown:: Noise and scaling of benchmark problems + + .. autoclass:: BenchmarkNoise + :members: + + .. autoclass:: AdditiveBenchmarkNoise + + .. autoclass:: MultiplicativeBenchmarkNoise + + .. autoclass:: BenchmarkScaler + :members: + + .. autoclass:: LinspaceBenchmarkScaler + +``` + +```{eval-rst} +.. dropdown:: BenchmarkResult + + .. autoclass:: BenchmarkResult + :members: + +``` + +```{eval-rst} +.. dropdown:: OptimizeOptions + + .. autoclass:: OptimizeOptions + :members: + +``` + ```{eval-rst} .. dropdown:: profile_plot diff --git a/src/optimagic/__init__.py b/src/optimagic/__init__.py index 5dddd83c8..4801a307a 100644 --- a/src/optimagic/__init__.py +++ b/src/optimagic/__init__.py @@ -2,13 +2,29 @@ from optimagic import constraints, mark, sandbox, timing, utilities from optimagic.algorithms import algos +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkFunction, + BenchmarkProblem, + BenchmarkSolution, + CallableBenchmarkFunction, + LeastSquaresBenchmarkFunction, + LikelihoodBenchmarkFunction, + ScalarBenchmarkFunction, +) from optimagic.benchmarking.benchmark_reports import ( convergence_report, rank_report, traceback_report, ) +from optimagic.benchmarking.benchmark_result import BenchmarkResult from optimagic.benchmarking.get_benchmark_problems import get_benchmark_problems +from optimagic.benchmarking.noise import ( + AdditiveBenchmarkNoise, + BenchmarkNoise, + MultiplicativeBenchmarkNoise, +) from optimagic.benchmarking.run_benchmark import run_benchmark +from optimagic.benchmarking.scaling import BenchmarkScaler, LinspaceBenchmarkScaler from optimagic.constraints import ( DecreasingConstraint, EqualityConstraint, @@ -42,6 +58,7 @@ from optimagic.optimization.history import History from optimagic.optimization.multistart_options import MultistartOptions from optimagic.optimization.optimize import maximize, minimize +from optimagic.optimization.optimize_options import OptimizeOptions from optimagic.optimization.optimize_result import OptimizeResult from optimagic.optimizers import pygad from optimagic.parameters.bounds import Bounds @@ -68,6 +85,20 @@ "second_derivative", "run_benchmark", "get_benchmark_problems", + "BenchmarkFunction", + "ScalarBenchmarkFunction", + "LeastSquaresBenchmarkFunction", + "LikelihoodBenchmarkFunction", + "CallableBenchmarkFunction", + "BenchmarkProblem", + "BenchmarkSolution", + "BenchmarkResult", + "BenchmarkNoise", + "AdditiveBenchmarkNoise", + "MultiplicativeBenchmarkNoise", + "BenchmarkScaler", + "LinspaceBenchmarkScaler", + "OptimizeOptions", "profile_plot", "convergence_plot", "convergence_report", diff --git a/src/optimagic/benchmarking/benchmark_problem.py b/src/optimagic/benchmarking/benchmark_problem.py new file mode 100644 index 000000000..9941f891d --- /dev/null +++ b/src/optimagic/benchmarking/benchmark_problem.py @@ -0,0 +1,669 @@ +"""Representation of benchmark functions and benchmark problems. + +There are two levels: + +- A ``BenchmarkFunction`` is the core of a problem: the objective function, optionally + its derivative, the numbers of parameters it supports and properties like + differentiability. It does not have start parameters. Example: the Rosenbrock + function. +- A ``BenchmarkProblem`` is one concrete test case: a ``BenchmarkFunction`` with start + parameters and optionally bounds, a known solution, noise and scaling. Example: the + Rosenbrock function with the start parameters ``[-1.2, 1]``. Several benchmark + problems can share the same benchmark function. + +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Callable +from dataclasses import dataclass, field, replace +from functools import cached_property +from typing import Any, TypeVar, cast + +import numpy as np +from numpy.typing import NDArray +from typing_extensions import Self + +from optimagic import mark +from optimagic.benchmarking.noise import BenchmarkNoise +from optimagic.benchmarking.scaling import BenchmarkScaler +from optimagic.parameters.bounds import Bounds +from optimagic.typing import AggregationLevel + +ObjectiveFunction = Callable[[NDArray[np.float64]], float | NDArray[np.float64]] +DerivativeFunction = Callable[[NDArray[np.float64]], NDArray[np.float64]] +FuncT = TypeVar("FuncT") + + +# ====================================================================================== +# Benchmark functions +# ====================================================================================== + + +class BenchmarkFunction(ABC): + """Base class for the functions that benchmark problems are built from. + + To define a new function, subclass one of ``ScalarBenchmarkFunction``, + ``LeastSquaresBenchmarkFunction`` or ``LikelihoodBenchmarkFunction`` and implement + ``fun``. Parameters of a family of functions (e.g. the number of residuals) are + attributes of the subclass. Use ``CallableBenchmarkFunction`` to wrap an existing + Python function instead. + + A benchmark function is not tied to one number of parameters. The number of + parameters is fixed by the start parameters of a ``BenchmarkProblem``. + + """ + + problem_type: AggregationLevel + """Whether ``fun`` returns a scalar, least-squares residuals or likelihood + contributions. Set by the base classes for the three problem types.""" + + differentiable: bool | None = None + """Whether the function is differentiable at every point where it is defined. None + if this is not known.""" + + convex: bool | None = None + """Whether the function is convex. For least-squares and likelihood functions this + refers to the sum of squared residuals or the sum of the contributions. None if this + is not known.""" + + min_n_params: int = 1 + """The smallest number of parameters the function supports.""" + + max_n_params: int | None = None + """The largest number of parameters the function supports. None if there is no upper + limit.""" + + @abstractmethod + def fun(self, x: NDArray[np.float64]) -> float | NDArray[np.float64]: + """Evaluate the function. + + Args: + x: The parameters, shape (n_params,). + + Returns: + A float for scalar functions; the residuals of shape (n_residuals,) for + least-squares functions; the contributions of shape (n_contributions,) for + likelihood functions. + + """ + + def jac(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + """Evaluate the first derivative of ``fun``. + + Subclasses override this method if a closed form derivative is available. + + Args: + x: The parameters, shape (n_params,). + + Returns: + The gradient of shape (n_params,) for scalar functions; the jacobian of + shape (n_residuals, n_params) or (n_contributions, n_params) for + least-squares and likelihood functions. + + """ + raise NotImplementedError( + f"{type(self).__name__} does not have a closed form derivative." + ) + + @property + def has_jac(self) -> bool: + """Whether a closed form derivative is available.""" + return type(self).jac is not BenchmarkFunction.jac + + def supports_n_params(self, n_params: int) -> bool: + """Check if the function can be evaluated with n_params parameters. + + The default implementation checks ``min_n_params`` and ``max_n_params``. + Override it for rules that cannot be expressed by those two numbers, e.g. if + only even numbers of parameters are supported. + + Args: + n_params: The number of parameters. + + Returns: + True if the function supports n_params parameters. + + """ + upper = self.max_n_params + return n_params >= self.min_n_params and (upper is None or n_params <= upper) + + def bounds(self, n_params: int) -> Bounds | None: # noqa: ARG002 + """Get the bounds outside of which the function cannot be evaluated. + + Subclasses override this method if the function is not defined everywhere, e.g. + because it takes the logarithm of a parameter. + + Args: + n_params: The number of parameters. + + Returns: + Bounds with arrays of shape (n_params,) or None if the function is defined + everywhere. + + """ + return None + + +class ScalarBenchmarkFunction(BenchmarkFunction): + """Base class for benchmark functions that return a scalar.""" + + problem_type = AggregationLevel.SCALAR + + @abstractmethod + def fun(self, x: NDArray[np.float64]) -> float: + """Evaluate the function. + + Args: + x: The parameters, shape (n_params,). + + Returns: + The function value. + + """ + + +class LeastSquaresBenchmarkFunction(BenchmarkFunction): + """Base class for benchmark functions that return least-squares residuals. + + The function that is minimized is the sum of the squared residuals. + + """ + + problem_type = AggregationLevel.LEAST_SQUARES + + @abstractmethod + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + """Evaluate the residuals. + + Args: + x: The parameters, shape (n_params,). + + Returns: + The residuals, shape (n_residuals,). + + """ + + +class LikelihoodBenchmarkFunction(BenchmarkFunction): + """Base class for benchmark functions that return likelihood contributions. + + The function that is minimized is the sum of the contributions. Since benchmark + problems are minimization problems, the contributions are usually negative + log-likelihood contributions. + + """ + + problem_type = AggregationLevel.LIKELIHOOD + + @abstractmethod + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + """Evaluate the contributions. + + Args: + x: The parameters, shape (n_params,). + + Returns: + The contributions, shape (n_contributions,). + + """ + + +@dataclass(frozen=True) +class CallableBenchmarkFunction(BenchmarkFunction): + """Benchmark function that wraps an existing Python function. + + This is the quickest way to turn your own objective function into a benchmark + function. In contrast to ``minimize``, the problem type is not inferred from the + ``mark`` decorators but has to be passed explicitly. + + """ + + func: ObjectiveFunction + """The function that is wrapped. Takes parameters of shape (n_params,) and returns + what ``fun`` of a benchmark function with the same ``problem_type`` returns.""" + + problem_type: AggregationLevel + """Whether ``func`` returns a scalar, least-squares residuals or likelihood + contributions.""" + + jac_func: DerivativeFunction | None = None + """The first derivative of ``func`` or None if there is no closed form + derivative.""" + + differentiable: bool | None = None + """Whether the function is differentiable at every point where it is defined. None + if this is not known.""" + + convex: bool | None = None + """Whether the function is convex. None if this is not known.""" + + min_n_params: int = 1 + """The smallest number of parameters the function supports.""" + + max_n_params: int | None = None + """The largest number of parameters the function supports. None if there is no upper + limit.""" + + def __post_init__(self) -> None: + if not isinstance(self.problem_type, AggregationLevel): + raise TypeError( + "problem_type must be an AggregationLevel, not " + f"{type(self.problem_type)}." + ) + + def fun(self, x: NDArray[np.float64]) -> float | NDArray[np.float64]: + return self.func(x) + + def jac(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + if self.jac_func is None: + return super().jac(x) + return self.jac_func(x) + + @property + def has_jac(self) -> bool: + return self.jac_func is not None + + +def aggregate_function_value( + value: float | NDArray[np.float64], problem_type: AggregationLevel +) -> float: + """Convert the output of a benchmark function to the scalar that is minimized. + + Args: + value: What ``fun`` of a benchmark function returned. + problem_type: The problem type of the benchmark function. + + Returns: + The value itself for scalar functions; the sum of squared residuals for + least-squares functions; the sum of the contributions for likelihood functions. + + """ + if problem_type == AggregationLevel.SCALAR: + return float(value) + arr = np.asarray(value, dtype=np.float64) + if problem_type == AggregationLevel.LEAST_SQUARES: + return float(arr @ arr) + return float(arr.sum()) + + +# ====================================================================================== +# Benchmark problems +# ====================================================================================== + + +@dataclass(frozen=True, eq=False) +class BenchmarkSolution: + """The known solution of a benchmark problem.""" + + fun: float + """The function value at the solution. For least-squares problems this is the sum + of squared residuals, for likelihood problems the sum of the contributions.""" + + params: NDArray[np.float64] | None = None + """The parameters at the solution, shape (n_params,). None if they are not known or + not unique.""" + + exact: bool = False + """True if ``fun`` is known to be the global minimum. False if it is only the best + value known so far, e.g. the result of a long run of a reliable optimizer. In the + second case an optimizer can find a better value during a benchmark.""" + + def __post_init__(self) -> None: + object.__setattr__(self, "fun", float(self.fun)) + if self.params is not None: + object.__setattr__(self, "params", _as_read_only_array(self.params)) + + +@dataclass(frozen=True, eq=False) +class BenchmarkProblem: + """A concrete test case for optimizers. + + All arrays (start parameters, bounds and the parameters of the solution) are in the + space the optimizer works in. If the problem is scaled, this is the scaled space. + Use ``with_scaling`` and ``with_noise`` to add scaling or noise to a problem. + + """ + + function: BenchmarkFunction + """The benchmark function that is minimized.""" + + start_params: NDArray[np.float64] + """The parameters at which optimizers start, shape (n_params,). They fix the number + of parameters of the problem. The array is read-only; copy it if you need to modify + it.""" + + solution: BenchmarkSolution | None = None + """The known solution of the problem or None if no solution is known. Without a + solution, benchmark plots and reports use the best function value any of the + compared optimizers found.""" + + bounds: Bounds | None = None + """The bounds that are passed to the optimizer, with arrays of shape (n_params,). + If None, the bounds outside of which the function cannot be evaluated are used (see + ``BenchmarkFunction.bounds``).""" + + noise: BenchmarkNoise | None = None + """The noise that is added to each function evaluation or None for no noise.""" + + scaler: BenchmarkScaler | None = None + """The scaler that was used to rescale the parameters or None if the problem is not + scaled.""" + + seed: int | None = None + """The seed for the noise. Each optimization of the problem starts with a new + random number generator with this seed, such that all optimizers see the same noise. + If None, the noise differs between optimizations.""" + + info: dict[str, Any] = field(default_factory=dict) + """Additional information about the problem. The entries depend on the benchmark + set.""" + + def __post_init__(self) -> None: + if not isinstance(self.function, BenchmarkFunction): + raise TypeError( + "function must be an instance of BenchmarkFunction, not " + f"{type(self.function)}." + ) + + start_params = _as_read_only_array(self.start_params) + if start_params.ndim != 1: + raise ValueError( + "start_params must be a one-dimensional array, not an array with " + f"{start_params.ndim} dimensions." + ) + object.__setattr__(self, "start_params", start_params) + + n_params = len(start_params) + if not self.function.supports_n_params(n_params): + raise ValueError( + f"{type(self.function).__name__} does not support {n_params} " + "parameters." + ) + + solution = self.solution + if solution is not None and solution.params is not None: + if np.shape(solution.params) != (n_params,): + raise ValueError( + f"The solution has params of shape {np.shape(solution.params)} " + f"but the start_params have shape {(n_params,)}." + ) + + function_bounds = self.function.bounds(n_params) + if self.scaler is not None: + function_bounds = _scale_bounds(function_bounds, self.scaler) + + if self.bounds is None: + object.__setattr__(self, "bounds", function_bounds) + else: + _fail_if_bounds_are_invalid( + bounds=self.bounds, function_bounds=function_bounds, n_params=n_params + ) + + @property + def n_params(self) -> int: + """The number of parameters of the problem.""" + return len(self.start_params) + + @property + def fun(self) -> ObjectiveFunction: + """The objective function as the optimizer sees it, i.e. scaled and with noise. + + The function is marked with the problem type and can be passed to ``minimize`` + together with ``start_params``. Each access returns a new function whose noise + starts from ``seed``. + + """ + rng = None if self.noise is None else np.random.default_rng(self.seed) + func = _ProblemFunction( + function=self.function, scaler=self.scaler, noise=self.noise, rng=rng + ) + return _mark_problem_type(func, self.function.problem_type) + + @property + def noise_free_fun(self) -> ObjectiveFunction: + """The objective function as the optimizer sees it but without noise.""" + func = _ProblemFunction( + function=self.function, scaler=self.scaler, noise=None, rng=None + ) + return _mark_problem_type(func, self.function.problem_type) + + @property + def jac(self) -> list[DerivativeFunction] | None: + """Closed form derivatives of ``fun`` that can be passed to ``minimize``. + + The list contains one function for each type of optimizer that can use the + derivative, e.g. the gradient of the sum of squared residuals for scalar + optimizers and the jacobian of the residuals for least-squares optimizers. + + None if the benchmark function has no closed form derivative or if the problem + is noisy or scaled. Optimizers then fall back to numerical derivatives. + + """ + if not self.function.has_jac or self.noise is not None: + return None + if self.scaler is not None: + return None + levels = _DERIVATIVE_LEVELS[self.function.problem_type] + return [ + _mark_problem_type(_ProblemDerivative(self.function, level), level) + for level in levels + ] + + @cached_property + def start_fun(self) -> float: + """The function value at the start parameters, without noise. + + For least-squares problems this is the sum of squared residuals, for likelihood + problems the sum of the contributions. + + """ + return aggregate_function_value( + self.noise_free_fun(self.start_params), + problem_type=self.function.problem_type, + ) + + def with_noise(self, noise: BenchmarkNoise | None, seed: int | None = None) -> Self: + """Create a copy of the problem with different noise. + + Args: + noise: The noise that is added to each function evaluation or None to + remove the noise. + seed: The seed for the noise. + + Returns: + The modified copy. + + """ + if noise is not None and not isinstance(noise, BenchmarkNoise): + raise TypeError( + f"noise must be an instance of BenchmarkNoise or None, not " + f"{type(noise)}." + ) + return replace(self, noise=noise, seed=seed) + + def with_scaling(self, scaler: BenchmarkScaler) -> Self: + """Create a rescaled copy of the problem. + + The start parameters, the bounds and the parameters of the solution are + converted to the scaled space. + + Args: + scaler: The scaler that is applied to the parameters. + + Returns: + The modified copy. + + Raises: + ValueError: If the problem is already scaled. + + """ + if not isinstance(scaler, BenchmarkScaler): + raise TypeError( + f"scaler must be an instance of BenchmarkScaler, not {type(scaler)}." + ) + if self.scaler is not None: + raise ValueError("The problem is already scaled.") + + solution = self.solution + if solution is not None and solution.params is not None: + solution = replace(solution, params=scaler.scale(solution.params)) + + return replace( + self, + start_params=scaler.scale(self.start_params), + solution=solution, + bounds=_scale_bounds(self.bounds, scaler), + scaler=scaler, + ) + + +class _ProblemFunction: + """Objective function of a benchmark problem. + + This is a class and not a closure such that it can be pickled, which is required for + running benchmarks in parallel. + + """ + + def __init__( + self, + function: BenchmarkFunction, + scaler: BenchmarkScaler | None, + noise: BenchmarkNoise | None, + rng: np.random.Generator | None, + ) -> None: + self._function = function + self._scaler = scaler + self._noise = noise + self._rng = rng + + def __call__(self, params: NDArray[np.float64]) -> float | NDArray[np.float64]: + x = params if self._scaler is None else self._scaler.unscale(params) + fval = self._function.fun(x) + if self._noise is None or self._rng is None: + return fval + if isinstance(fval, np.ndarray): + array = cast(NDArray[np.float64], fval) + return array + self._noise.draw_noise(array, params=x, rng=self._rng) + value = float(fval) + return value + self._noise.draw_noise(value, params=x, rng=self._rng) + + +_DERIVATIVE_LEVELS = { + AggregationLevel.SCALAR: [AggregationLevel.SCALAR], + AggregationLevel.LEAST_SQUARES: [ + AggregationLevel.SCALAR, + AggregationLevel.LIKELIHOOD, + AggregationLevel.LEAST_SQUARES, + ], + AggregationLevel.LIKELIHOOD: [ + AggregationLevel.SCALAR, + AggregationLevel.LIKELIHOOD, + ], +} +"""The types of optimizers for which a derivative can be calculated from the derivative +of a benchmark function with a given problem type.""" + + +class _ProblemDerivative: + """Derivative of a benchmark function for one type of optimizer. + + This is a class and not a closure such that it can be pickled. + + """ + + def __init__(self, function: BenchmarkFunction, level: AggregationLevel) -> None: + self._function = function + self._level = level + + def __call__(self, params: NDArray[np.float64]) -> NDArray[np.float64]: + jac = self._function.jac(params) + problem_type = self._function.problem_type + if problem_type == self._level: + return jac + if problem_type == AggregationLevel.LIKELIHOOD: + # gradient of the sum of the contributions + return jac.sum(axis=0) + residuals = np.asarray(self._function.fun(params), dtype=np.float64) + if self._level == AggregationLevel.SCALAR: + # gradient of the sum of squared residuals + return 2 * jac.T @ residuals + # jacobian of the squared residuals + return 2 * residuals.reshape(-1, 1) * jac + + +def _mark_problem_type(func: FuncT, problem_type: AggregationLevel) -> FuncT: + markers: dict[AggregationLevel, Callable[[Any], Any]] = { + AggregationLevel.SCALAR: mark.scalar, + AggregationLevel.LEAST_SQUARES: mark.least_squares, + AggregationLevel.LIKELIHOOD: mark.likelihood, + } + return markers[problem_type](func) + + +def _as_read_only_array(values: Any) -> NDArray[np.float64]: + """Copy values into a float array that cannot be modified. + + Benchmark problems are shared between all users of a problem set. Read-only arrays + make sure that nobody changes them by accident. + + """ + out = np.array(values, dtype=np.float64) + out.setflags(write=False) + return out + + +def _scale_bounds(bounds: Bounds | None, scaler: BenchmarkScaler) -> Bounds | None: + if bounds is None: + return None + + def _scale(arr: Any) -> NDArray[np.float64] | None: + if arr is None: + return None + return scaler.scale(np.asarray(arr, dtype=np.float64)) + + return Bounds( + lower=_scale(bounds.lower), + upper=_scale(bounds.upper), + soft_lower=_scale(bounds.soft_lower), + soft_upper=_scale(bounds.soft_upper), + ) + + +def _fail_if_bounds_are_invalid( + bounds: Bounds, function_bounds: Bounds | None, n_params: int +) -> None: + if not isinstance(bounds, Bounds): + raise TypeError( + f"bounds must be an instance of optimagic.Bounds, not {type(bounds)}." + ) + + lower, upper = _get_bound_arrays(bounds, n_params) + function_lower, function_upper = _get_bound_arrays(function_bounds, n_params) + if (lower < function_lower).any() or (upper > function_upper).any(): + raise ValueError( + "The bounds of a benchmark problem must not be wider than the bounds " + "outside of which its function cannot be evaluated." + ) + + +def _get_bound_arrays( + bounds: Bounds | None, n_params: int +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """Convert bounds to arrays of shape (n_params,), filling missing bounds.""" + lower = None if bounds is None else bounds.lower + upper = None if bounds is None else bounds.upper + out = [] + for bound, fill in [(lower, -np.inf), (upper, np.inf)]: + if bound is None: + out.append(np.full(n_params, fill)) + else: + arr = np.asarray(bound, dtype=np.float64) + if arr.shape != (n_params,): + raise ValueError( + f"Bounds must have shape {(n_params,)}, not {arr.shape}." + ) + out.append(arr) + return out[0], out[1] diff --git a/src/optimagic/benchmarking/benchmark_reports.py b/src/optimagic/benchmarking/benchmark_reports.py index 003761ba9..861569cbc 100644 --- a/src/optimagic/benchmarking/benchmark_reports.py +++ b/src/optimagic/benchmarking/benchmark_reports.py @@ -1,41 +1,50 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Literal, overload + import pandas as pd +from optimagic.benchmarking.benchmark_problem import BenchmarkProblem +from optimagic.benchmarking.benchmark_result import BenchmarkResult from optimagic.benchmarking.process_benchmark_results import ( + StoppingCriterion, process_benchmark_results, ) from optimagic.visualization.profile_plot import create_solution_times def convergence_report( - problems, results, *, stopping_criterion="y", x_precision=1e-4, y_precision=1e-4 -): + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], + *, + stopping_criterion: StoppingCriterion = "y", + x_precision: float = 1e-4, + y_precision: float = 1e-4, +) -> pd.DataFrame: """Create a DataFrame with convergence information for a set of problems. Args: - problems (dict): optimagic benchmarking problems dictionary. Keys are the - problem names. Values contain information on the problem, including the - solution value. - results (dict): optimagic benchmarking results dictionary. Keys are - tuples of the form (problem, algorithm), values are dictionaries of the - collected information on the benchmark run, including 'criterion_history' - and 'time_history'. - stopping_criterion (str): one of "x_and_y", "x_or_y", "x", "y". Determines + problems: Dictionary that maps names to benchmark problems. + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). + stopping_criterion: one of "x_and_y", "x_or_y", "x", "y". Determines how convergence is determined from the two precisions. Default is "y". - x_precision (float or None): how close an algorithm must have gotten to the + x_precision: how close an algorithm must have gotten to the true parameter values (as percent of the Euclidean distance between start and solution parameters) before the criterion for clipping and convergence is fulfilled. Default is 1e-4. - y_precision (float or None): how close an algorithm must have gotten to the + y_precision: how close an algorithm must have gotten to the true criterion values (as percent of the distance between start and solution criterion value) before the criterion for clipping and convergence is fulfilled. Default is 1e-4. Returns: - pandas.DataFrame: indexes are the problems, columns are the algorithms and - the dimensionality of the benchmark problems. For the algorithms column, - the values are strings that are either "success", "failed", or "error". - For the dimensionality column, the values denote the number of dimensions - of the problem. + DataFrame where indexes are the problems, columns are the algorithms and + the dimensionality of the benchmark problems. For the algorithms column, + the values are strings that are either "success", "failed", or "error". + For the dimensionality column, the values denote the number of dimensions + of the problem. """ _, converged_info = process_benchmark_results( @@ -53,46 +62,44 @@ def convergence_report( def rank_report( - problems, - results, + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], *, - runtime_measure="n_evaluations", - stopping_criterion="y", - x_precision=1e-4, - y_precision=1e-4, -): + runtime_measure: Literal["n_evaluations", "n_batches", "walltime"] = ( + "n_evaluations" + ), + stopping_criterion: StoppingCriterion = "y", + x_precision: float = 1e-4, + y_precision: float = 1e-4, +) -> pd.DataFrame: """Create a DataFrame with rank information for a set of problems. Args: - problems (dict): optimagic benchmarking problems dictionary. Keys are the - problem names. Values contain information on the problem, including the - solution value. - results (dict): optimagic benchmarking results dictionary. Keys are - tuples of the form (problem, algorithm), values are dictionaries of the - collected information on the benchmark run, including 'criterion_history' - and 'time_history'. - runtime_measure (str): "n_evaluations", "n_batches" or "walltime". + problems: Dictionary that maps names to benchmark problems. + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). + runtime_measure: "n_evaluations", "n_batches" or "walltime". This is the runtime until the desired convergence was reached by an algorithm. This is called performance measure by Moré and Wild (2009). Default is "n_evaluations". - stopping_criterion (str): one of "x_and_y", "x_or_y", "x", "y". Determines + stopping_criterion: one of "x_and_y", "x_or_y", "x", "y". Determines how convergence is determined from the two precisions. - x_precision (float or None): how close an algorithm must have gotten to the + x_precision: how close an algorithm must have gotten to the true parameter values (as percent of the Euclidean distance between start and solution parameters) before the criterion for clipping and convergence is fulfilled. Default is 1e-4. - y_precision (float or None): how close an algorithm must have gotten to the + y_precision: how close an algorithm must have gotten to the true criterion values (as percent of the distance between start and solution criterion value) before the criterion for clipping and convergence is fulfilled. Default is 1e-4. Returns: - pandas.DataFrame: indexes are the problems, columns are the algorithms and the - dimensionality of the problems. The values are the ranks of the algorithms - for each problem, where 0 means the algorithm was the fastest, 1 means it - was the second fastest and so on. If an algorithm did not converge on a - problem, the value is "failed". If an algorithm did encounter an error - during optimization, the value is "error". + DataFrame where indexes are the problems, columns are the algorithms and the + dimensionality of the problems. The values are the ranks of the algorithms + for each problem, where 0 means the algorithm was the fastest, 1 means it + was the second fastest and so on. If an algorithm did not converge on a + problem, the value is "failed". If an algorithm did encounter an error + during optimization, the value is "error". """ histories, converged_info = process_benchmark_results( @@ -125,15 +132,50 @@ def rank_report( return report -def traceback_report(problems, results, return_type="dataframe"): +@overload +def traceback_report( + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], + return_type: Literal["dataframe"] = "dataframe", +) -> pd.DataFrame: ... + + +@overload +def traceback_report( + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], + return_type: Literal["text"], +) -> list[str]: ... + + +@overload +def traceback_report( + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], + return_type: Literal["markdown"], +) -> str: ... + + +@overload +def traceback_report( + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], + return_type: Literal["dict"], +) -> dict[tuple[str, str], str]: ... + + +def traceback_report( + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], + return_type: Literal["text", "markdown", "dict", "dataframe"] = "dataframe", +) -> list[str] | str | dict[tuple[str, str], str] | pd.DataFrame: """Create traceback report for all problems that have not been solved. Args: - results (dict): optimagic benchmarking results dictionary. Keys are - tuples of the form (problem, algorithm), values are dictionaries of the - collected information on the benchmark run, including 'criterion_history' - and 'time_history'. - return_type (str): either "text", "markdown", "dict" or "dataframe". + problems: Dictionary that maps names to benchmark problems. + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). + return_type: either "text", "markdown", "dict" or "dataframe". If "text", the traceback report is returned as a string. If "markdown", it is a markdown string. If "dict", it is returned as a dictionary. If "dataframe", it is a tidy pandas DataFrame, where indexes are the @@ -141,46 +183,43 @@ def traceback_report(problems, results, return_type="dataframe"): dimensionality of the problem. Default is "dataframe". Returns: - (list or str or dict or pandas.DataFrame): traceback report. If return_type - is "text", the report is a list of strings. If "markdown", it is a - formatted markdown string with algorithms and problem names as headers. - If return_type is "dict", the report is a dictionary. If return_type is - "dataframe", it is a tidy pandas DataFrame. In the latter case, indexes - are the algorithm and problem names, the columns are the tracebacks and - the dimensionality of the problems. The values are the tracebacks of the - algorithms for problems where they stopped with an error. + The traceback report. If return_type is "text", the report is a list of + strings. If "markdown", it is a formatted markdown string with algorithms and + problem names as headers. If return_type is "dict", the report is a + dictionary. If return_type is "dataframe", it is a tidy pandas DataFrame. In + the latter case, indexes are the algorithm and problem names, the columns are + the tracebacks and the dimensionality of the problems. The values are the + tracebacks of the algorithms for problems where they stopped with an error. """ + tracebacks = { + key: result.traceback + for key, result in results.items() + if result.traceback is not None + } + if return_type == "text": - report = [] - for result in results.values(): - if isinstance(result["solution"], str): - report.append(result["solution"]) - - elif return_type == "markdown": - report = "```python" - for (problem_name, algorithm_name), result in results.items(): - if isinstance(result["solution"], str): - if f"### {algorithm_name}" not in report: - report += f"\n### {algorithm_name} \n" - report += f"\n#### {problem_name} \n" - report += f"\n{result['solution']} \n" - report += "\n```" - - elif return_type == "dict": - report = {} - for (problem_name, algorithm_name), result in results.items(): - if isinstance(result["solution"], str): - report[(problem_name, algorithm_name)] = result["solution"] - - elif return_type == "dataframe": - tracebacks = {} - for (problem_name, algorithm_name), result in results.items(): - if isinstance(result["solution"], str): - tracebacks[algorithm_name] = tracebacks.setdefault(algorithm_name, {}) - tracebacks[algorithm_name][problem_name] = result["solution"] - - report = pd.DataFrame.from_dict(tracebacks, orient="index").stack().to_frame() # ty:ignore[call-non-callable] + return list(tracebacks.values()) + + if return_type == "markdown": + markdown = "```python" + for (problem_name, algorithm_name), traceback in tracebacks.items(): + if f"### {algorithm_name}" not in markdown: + markdown += f"\n### {algorithm_name} \n" + markdown += f"\n#### {problem_name} \n" + markdown += f"\n{traceback} \n" + markdown += "\n```" + return markdown + + if return_type == "dict": + return tracebacks + + if return_type == "dataframe": + nested: dict[str, dict[str, str]] = {} + for (problem_name, algorithm_name), traceback in tracebacks.items(): + nested.setdefault(algorithm_name, {})[problem_name] = traceback + + report = pd.DataFrame.from_dict(nested, orient="index").stack().to_frame() # ty:ignore[call-non-callable] report.index.set_names(["algorithm", "problem"], inplace=True) report.columns = ["traceback"] report["dimensionality"] = 0 @@ -189,50 +228,40 @@ def traceback_report(problems, results, return_type="dataframe"): if problem_name in report.index.get_level_values("problem"): report.loc[(slice(None), problem_name), "dimensionality"] = dim - else: - raise ValueError( - f"return_type {return_type} is not supported. Must be one of " - f"'text', 'markdown', 'dict' or 'dataframe'." - ) + return report - return report + raise ValueError( + f"return_type {return_type} is not supported. Must be one of " + f"'text', 'markdown', 'dict' or 'dataframe'." + ) -def _get_success_info(results, converged_info): +def _get_success_info( + results: Mapping[tuple[str, str], BenchmarkResult], converged_info: pd.DataFrame +) -> pd.DataFrame: """Create a DataFrame with information on whether an algorithm succeeded or not. Args: - results (dict): optimagic benchmarking results dictionary. Keys are - tuples of the form (problem, algorithm), values are dictionaries of the - collected information on the benchmark run, including 'criterion_history' - and 'time_history'. - converged_info (pandas.DataFrame): columns are the algorithms, indexes are the + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). + converged_info: columns are the algorithms, indexes are the problems. The values are boolean and True when the algorithm arrived at the solution with the desired precision. Returns: - pandas.DataFrame: indexes are the problems, columns are the algorithms. - values are strings that are either "success", "failed", or "error". + DataFrame where indexes are the problems, columns are the algorithms. Values + are strings that are either "success", "failed", or "error". """ success_info = converged_info.replace({True: "success", False: "failed"}) for key, value in results.items(): - if isinstance(value["solution"], str): + if value.traceback is not None: success_info.at[key] = "error" return success_info -def _get_problem_dimensions(problems): - """Get the dimension of each problem. - - Args: - problems (dict): dictionary of problems. keys are problem names, values are - dictionaries with the problem information. - - Returns: - dict: keys are problem names, values are the dimension of the problem. - - """ - return {prob: len(problems[prob]["inputs"]["params"]) for prob in problems} +def _get_problem_dimensions(problems: Mapping[str, BenchmarkProblem]) -> dict[str, int]: + """Get the number of parameters of each problem.""" + return {name: problem.n_params for name, problem in problems.items()} diff --git a/src/optimagic/benchmarking/benchmark_result.py b/src/optimagic/benchmarking/benchmark_result.py new file mode 100644 index 000000000..b9dce6fdf --- /dev/null +++ b/src/optimagic/benchmarking/benchmark_result.py @@ -0,0 +1,45 @@ +"""Representation of the result of running one optimizer on one benchmark problem.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +from numpy.typing import NDArray + +from optimagic.optimization.optimize_result import OptimizeResult + + +@dataclass(frozen=True, eq=False) +class BenchmarkResult: + """The result of running one optimizer on one benchmark problem. + + If the optimization raised an error, the histories only contain the start + parameters, ``optimize_result`` is None and ``traceback`` contains the error. + + """ + + params_history: NDArray[np.float64] + """The parameters at which the function was evaluated, in the order of the + evaluations. Shape (n_evaluations, n_params).""" + + fun_history: NDArray[np.float64] + """The function values at ``params_history`` without noise. For least-squares + problems these are sums of squared residuals, for likelihood problems sums of + contributions. Shape (n_evaluations,).""" + + time_history: NDArray[np.float64] + """The time in seconds between the start of the optimization and the start of each + function evaluation. Shape (n_evaluations,).""" + + batches_history: NDArray[np.int64] + """The batch of each function evaluation. Evaluations in the same batch were done + in parallel. Shape (n_evaluations,).""" + + optimize_result: OptimizeResult | None + """The result returned by ``minimize`` or None if the optimization raised an + error.""" + + traceback: str | None = None + """The traceback of the error that was raised during the optimization or None if + there was no error.""" diff --git a/src/optimagic/benchmarking/cartis_roberts.py b/src/optimagic/benchmarking/cartis_roberts.py index 29e481556..83eab66a9 100644 --- a/src/optimagic/benchmarking/cartis_roberts.py +++ b/src/optimagic/benchmarking/cartis_roberts.py @@ -15,14 +15,21 @@ """ +from collections.abc import Callable from functools import partial -from typing import Any import numpy as np +from numpy.typing import NDArray from optimagic import mark +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + BenchmarkSolution, + CallableBenchmarkFunction, +) from optimagic.config import IS_NUMBA_INSTALLED from optimagic.parameters.bounds import Bounds +from optimagic.typing import AggregationLevel if IS_NUMBA_INSTALLED: from numba import njit @@ -4893,490 +4900,458 @@ def get_start_points_methanl8(): ] -CARTIS_ROBERTS_PROBLEMS = { - "arglale": { +def _problem( + fun: Callable[[NDArray[np.float64]], NDArray[np.float64]], + start_x: list[float], + solution_x: list[float] | None, + solution_fun: float, + bounds: Bounds | None = None, +) -> BenchmarkProblem: + """Create a benchmark problem from the information in the problem table. + + Args: + fun: Function that maps parameters of shape (n_params,) to least-squares + residuals of shape (n_residuals,). + start_x: The start parameters. + solution_x: The parameters at the solution or None if they are not unique. + solution_fun: The sum of squared residuals at the solution. + bounds: The bounds of the original problem. They are stored in the info of the + problem but, as in all previous versions, not passed to the optimizers. + + Returns: + The benchmark problem. The solution is marked as exact if solution_fun is zero + because a sum of squares cannot be smaller. All other solutions are the best + known values. + + """ + solution_params = None + if solution_x is not None: + solution_params = np.array(solution_x, dtype=np.float64) + + return BenchmarkProblem( + function=CallableBenchmarkFunction( + func=fun, problem_type=AggregationLevel.LEAST_SQUARES + ), + start_params=np.array(start_x, dtype=np.float64), + solution=BenchmarkSolution( + fun=float(solution_fun), params=solution_params, exact=solution_fun == 0 + ), + info={} if bounds is None else {"bounds": bounds}, + ) + + +CARTIS_ROBERTS_PROBLEMS: dict[str, BenchmarkProblem] = { + "arglale": _problem( # arglale is the same as linear_full_rank with specific settings - "fun": partial(linear_full_rank, dim_out=400), - "start_x": [1] * 100, - "solution_x": [-0.99999952] * 100, - "start_criterion": 700, - "solution_criterion": 300, - }, - "arglble": { + fun=partial(linear_full_rank, dim_out=400), + start_x=[1] * 100, + solution_x=[-0.99999952] * 100, + solution_fun=300, + ), + "arglble": _problem( # arglble is the same as linear_rank_one with specific settings - "fun": partial(linear_rank_one, dim_out=400), - "start_x": [1] * 100, - "solution_x": solution_x_arglble, - "start_criterion": 5.460944e14, - "solution_criterion": 99.62547, - }, - "argtrig": { - "fun": argtrig, - "start_x": [1 / 100] * 100, - "solution_x": [0] * 100, - "start_criterion": 32.99641, - "solution_criterion": 0, - }, - "artif": { - "fun": artif, - "start_x": [1] * 100, - "solution_x": None, - "start_criterion": 36.59115, - "solution_criterion": 0, - }, - "arwhdne": { - "fun": arwhdne, - "start_x": [1] * 100, - "solution_x": [0.706011] * 99 + [0], - "start_criterion": 495, - "solution_criterion": 27.66203, - }, - "bdvalues": { - "fun": bdvalues, - "start_x": get_start_points_bdvalues(100, 1000), - "solution_x": solution_x_bdvalues, - "start_criterion": 1.943417e7, - "solution_criterion": 0, - }, - "bratu_2d": { - "fun": partial(bratu_2d, alpha=4), - "start_x": [0] * 64, - "solution_x": solution_x_bratu_2d, - "start_criterion": 0.1560738, - "solution_criterion": 0, - }, - "bratu_2d_t": { - "fun": partial(bratu_2d, alpha=6.80812), - "start_x": [0] * 64, - "solution_x": solution_x_bratu_2d_t, - "start_criterion": 0.4521311, - "solution_criterion": 1.8534736e-05, - }, - "bratu_3d": { - "fun": partial(bratu_3d, alpha=6.80812), - "start_x": [0] * 27, - "solution_x": solution_x_bratu_3d, - "start_criterion": 4.888529, - "solution_criterion": 0, - }, - "brownale": { - "fun": brown_almost_linear, - "start_x": [0.5] * 100, - "solution_x": [1] * 100, - "start_criterion": 2.524757e5, - "solution_criterion": 0, - }, - "broydn_3d": { - "fun": broydn_3d, - "start_x": [-1] * 100, - "solution_x": solution_x_broydn_3d, - "start_criterion": 111, - "solution_criterion": 0, - }, - "cbratu_2d": { - "fun": cbratu_2d, - "start_x": [0] * (2 * 5 * 5), - "solution_x": solution_x_cbratu_2d, - "start_criterion": 0.4822531, - "solution_criterion": 0, - }, - "broydn_bd": { - "fun": broydn_bd, - "start_x": [1] * 100, - "solution_x": solution_x_broydn_bd, - "start_criterion": 2404, - "solution_criterion": 0, - }, - "chandheq": { - "fun": chandheq, - "start_x": (np.arange(1, 101) / 100).tolist(), - "solution_x": None, - "start_criterion": 6.923365, - "solution_criterion": 0, - }, - "chemrcta": { - "fun": chemrcta, - "start_x": [1] * 100, - "solution_x": None, - "start_criterion": 3.0935, - "solution_criterion": 0, - "bounds": Bounds(lower=np.concatenate([np.zeros(50), 1e-6 * np.ones(50)])), - }, - "chemrctb": { - "fun": chemrctb, - "start_x": [1] * 100, - "solution_x": solution_x_chemrctb, - "start_criterion": 1.446513, - "solution_criterion": 1.404424e-3, - "bounds": Bounds(lower=1e-6 * np.ones(100)), - }, - "chnrsbne": { - "fun": chnrsbne, - "start_x": [-1] * 50, - "solution_x": [1] * 50, - "start_criterion": 7635.84, - "solution_criterion": 0, - }, - "drcavty1": { - "fun": partial(drcavty, r=500), - "start_x": [0] * 100, - "solution_x": None, - "start_criterion": 0.4513889, - "solution_criterion": 0, - }, - "drcavty2": { - "fun": partial(drcavty, r=1000), - "start_x": [0] * 100, - "solution_x": solution_x_drcavty2, - "start_criterion": 0.4513889, - "solution_criterion": 3.988378e-4, - }, - "drcavty3": { - "fun": partial(drcavty, r=4500), - "start_x": [0] * 100, - "solution_x": solution_x_drcavty3, - "start_criterion": 0.4513889, - "solution_criterion": 0, - }, - "eigena": { - "fun": partial(eigen, param=np.diag(np.arange(1, 11))), - "start_x": [1] * 10 + np.eye(10).flatten().tolist(), - "solution_x": [*np.arange(1, 11).tolist(), 1] + ([0] * 10 + [1]) * 9, - "start_criterion": 285, - "solution_criterion": 0, - "bounds": Bounds(lower=np.zeros(110)), - }, - "eigenb": { - "fun": partial( - eigen, param=np.diag(2 * np.ones(10)) + np.diag(-np.ones(9), k=1) - ), - "start_x": [1] * 10 + np.eye(10).flatten().tolist(), - "solution_x": solution_x_eigenb, - "start_criterion": 19, - "solution_criterion": 1.55654284, + fun=partial(linear_rank_one, dim_out=400), + start_x=[1] * 100, + solution_x=solution_x_arglble, + solution_fun=99.62547, + ), + "argtrig": _problem( + fun=argtrig, + start_x=[1 / 100] * 100, + solution_x=[0] * 100, + solution_fun=0, + ), + "artif": _problem( + fun=artif, + start_x=[1] * 100, + solution_x=None, + solution_fun=0, + ), + "arwhdne": _problem( + fun=arwhdne, + start_x=[1] * 100, + solution_x=[0.706011] * 99 + [0], + solution_fun=27.66203, + ), + "bdvalues": _problem( + fun=bdvalues, + start_x=get_start_points_bdvalues(100, 1000), + solution_x=solution_x_bdvalues, + solution_fun=0, + ), + "bratu_2d": _problem( + fun=partial(bratu_2d, alpha=4), + start_x=[0] * 64, + solution_x=solution_x_bratu_2d, + solution_fun=0, + ), + "bratu_2d_t": _problem( + fun=partial(bratu_2d, alpha=6.80812), + start_x=[0] * 64, + solution_x=solution_x_bratu_2d_t, + solution_fun=1.8534736e-05, + ), + "bratu_3d": _problem( + fun=partial(bratu_3d, alpha=6.80812), + start_x=[0] * 27, + solution_x=solution_x_bratu_3d, + solution_fun=0, + ), + "brownale": _problem( + fun=brown_almost_linear, + start_x=[0.5] * 100, + solution_x=[1] * 100, + solution_fun=0, + ), + "broydn_3d": _problem( + fun=broydn_3d, + start_x=[-1] * 100, + solution_x=solution_x_broydn_3d, + solution_fun=0, + ), + "cbratu_2d": _problem( + fun=cbratu_2d, + start_x=[0] * (2 * 5 * 5), + solution_x=solution_x_cbratu_2d, + solution_fun=0, + ), + "broydn_bd": _problem( + fun=broydn_bd, + start_x=[1] * 100, + solution_x=solution_x_broydn_bd, + solution_fun=0, + ), + "chandheq": _problem( + fun=chandheq, + start_x=(np.arange(1, 101) / 100).tolist(), + solution_x=None, + solution_fun=0, + ), + "chemrcta": _problem( + fun=chemrcta, + start_x=[1] * 100, + solution_x=None, + solution_fun=0, + bounds=Bounds(lower=np.concatenate([np.zeros(50), 1e-6 * np.ones(50)])), + ), + "chemrctb": _problem( + fun=chemrctb, + start_x=[1] * 100, + solution_x=solution_x_chemrctb, + solution_fun=1.404424e-3, + bounds=Bounds(lower=1e-6 * np.ones(100)), + ), + "chnrsbne": _problem( + fun=chnrsbne, + start_x=[-1] * 50, + solution_x=[1] * 50, + solution_fun=0, + ), + "drcavty1": _problem( + fun=partial(drcavty, r=500), + start_x=[0] * 100, + solution_x=None, + solution_fun=0, + ), + "drcavty2": _problem( + fun=partial(drcavty, r=1000), + start_x=[0] * 100, + solution_x=solution_x_drcavty2, + solution_fun=3.988378e-4, + ), + "drcavty3": _problem( + fun=partial(drcavty, r=4500), + start_x=[0] * 100, + solution_x=solution_x_drcavty3, + solution_fun=0, + ), + "eigena": _problem( + fun=partial(eigen, param=np.diag(np.arange(1, 11))), + start_x=[1] * 10 + np.eye(10).flatten().tolist(), + solution_x=[*np.arange(1, 11).tolist(), 1] + ([0] * 10 + [1]) * 9, + solution_fun=0, + bounds=Bounds(lower=np.zeros(110)), + ), + "eigenb": _problem( + fun=partial(eigen, param=np.diag(2 * np.ones(10)) + np.diag(-np.ones(9), k=1)), + start_x=[1] * 10 + np.eye(10).flatten().tolist(), + solution_x=solution_x_eigenb, + solution_fun=1.55654284, # we suspect a typo in Cartis and Roberts (2019); # according to table 3 in their paper, the minimum is at 0. - }, - "flosp2hh": { - "fun": partial( + ), + "flosp2hh": _problem( + fun=partial( flosp2, a=np.array([1, 0, -1], dtype=np.int64), b=np.array([1, 0, -1], dtype=np.int64), ra=1e7, ), - "start_x": [0] * 59, - "solution_x": None, # multiple argmins - "start_criterion": 519, - "solution_criterion": 1 / 3, - }, - "flosp2hl": { - "fun": partial( + start_x=[0] * 59, + solution_x=None, # multiple argmins + solution_fun=1 / 3, + ), + "flosp2hl": _problem( + fun=partial( flosp2, a=np.array([1, 0, -1], dtype=np.float64), b=np.array([1, 0, -1], dtype=np.float64), ra=1e3, ), - "start_x": [0] * 59, - "solution_x": None, # multiple argmins - "start_criterion": 519, - "solution_criterion": 1 / 3, - }, - "flosp2hm": { - "fun": partial( + start_x=[0] * 59, + solution_x=None, # multiple argmins + solution_fun=1 / 3, + ), + "flosp2hm": _problem( + fun=partial( flosp2, a=np.array([1, 0, -1], dtype=np.float64), b=np.array([1, 0, -1], dtype=np.float64), ra=1e5, ), - "start_x": [0] * 59, - "solution_x": None, # multiple argmins - "start_criterion": 519, - "solution_criterion": 1 / 3, - }, - "flosp2th": { - "fun": partial( + start_x=[0] * 59, + solution_x=None, # multiple argmins + solution_fun=1 / 3, + ), + "flosp2th": _problem( + fun=partial( flosp2, a=np.array([0, 1, 0], dtype=np.float64), b=np.array([0, 1, 1], dtype=np.float64), ra=1e7, ), - "start_x": [0] * 59, - "solution_x": None, # multiple argmins - "start_criterion": 516, - "solution_criterion": 0, - }, - "flosp2tl": { - "fun": partial( + start_x=[0] * 59, + solution_x=None, # multiple argmins + solution_fun=0, + ), + "flosp2tl": _problem( + fun=partial( flosp2, a=np.array([0, 1, 0], dtype=np.float64), b=np.array([0, 1, 1], dtype=np.float64), ra=1e3, ), - "start_x": [0] * 59, - "solution_x": None, # multiple argmins - "start_criterion": 516, - "solution_criterion": 0, - }, - "flosp2tm": { - "fun": partial( + start_x=[0] * 59, + solution_x=None, # multiple argmins + solution_fun=0, + ), + "flosp2tm": _problem( + fun=partial( flosp2, a=np.array([0, 1, 0], dtype=np.float64), b=np.array([0, 1, 1], dtype=np.float64), ra=1e5, ), - "start_x": [0] * 59, - "solution_x": None, # multiple argmins - "start_criterion": 516, - "solution_criterion": 0, - }, - "freurone": { - "fun": freurone, - "start_x": [0.5, -2] + [0] * 98, - "solution_x": solution_x_freurone, - "start_criterion": 9.95565e4, - "solution_criterion": 1.196458e4, - }, - "hatfldg": { - "fun": hatfldg, - "start_x": [1] * 25, - "solution_x": [0] * 11 + [-1, 1] + [0] * 12, - "start_criterion": 27, - "solution_criterion": 0, - }, - "hydcar20": { - "fun": partial(hydcar, n=20, m=3, k=9), - "start_x": get_start_points_hydcar20(), - "solution_x": solution_x_hydcar20, - "start_criterion": 1341.663, - "solution_criterion": 0, - }, - "hydcar6": { - "fun": partial(hydcar, n=6, m=3, k=2), - "start_x": get_start_points_hydcar6(), - "solution_x": solution_x_hydcar6, - "start_criterion": 704.1073, - "solution_criterion": 0, - }, - "integreq": { - "fun": integreq, - "start_x": (np.arange(1, 101) / 101 * (np.arange(1, 101) / 101 - 1)).tolist(), - "solution_x": solution_x_integreq, - "start_criterion": 0.5730503, - "solution_criterion": 0, - }, - "luksan11": { - "fun": luksan11, - "start_x": [-0.8] * 100, - "solution_x": [1] * 100, - "start_criterion": 626.0640, - "solution_criterion": 0, - }, - "luksan12": { - "fun": luksan12, - "start_x": [-1] * 98, - "solution_x": None, - "start_criterion": 3.2160e4, - "solution_criterion": None, + start_x=[0] * 59, + solution_x=None, # multiple argmins + solution_fun=0, + ), + "freurone": _problem( + fun=freurone, + start_x=[0.5, -2] + [0] * 98, + solution_x=solution_x_freurone, + solution_fun=1.196458e4, + ), + "hatfldg": _problem( + fun=hatfldg, + start_x=[1] * 25, + solution_x=[0] * 11 + [-1, 1] + [0] * 12, + solution_fun=0, + ), + "hydcar20": _problem( + fun=partial(hydcar, n=20, m=3, k=9), + start_x=get_start_points_hydcar20(), + solution_x=solution_x_hydcar20, + solution_fun=0, + ), + "hydcar6": _problem( + fun=partial(hydcar, n=6, m=3, k=2), + start_x=get_start_points_hydcar6(), + solution_x=solution_x_hydcar6, + solution_fun=0, + ), + "integreq": _problem( + fun=integreq, + start_x=(np.arange(1, 101) / 101 * (np.arange(1, 101) / 101 - 1)).tolist(), + solution_x=solution_x_integreq, + solution_fun=0, + ), + "luksan11": _problem( + fun=luksan11, + start_x=[-0.8] * 100, + solution_x=[1] * 100, + solution_fun=0, + ), + "luksan12": _problem( + fun=luksan12, + start_x=[-1] * 98, + solution_x=None, # we found a lower minimum than Cartis and Roberts (2019) at 1651.837; # according to table 3 in their paper, the minimum is at 4292.197. - # We suspect, however, that the true optimum is even lower. - # That is why we disable this test function for the time being. - }, - "luksan13": { - "fun": luksan13, - "start_x": [-1] * 98, - "solution_x": solution_x_luksan13, - "start_criterion": 6.4352e4, - "solution_criterion": 24949.67040503685711883, + # We suspect, however, that the true optimum is even lower. The value is + # therefore only the best known value and gets replaced if an optimizer + # finds a lower one during a benchmark. + solution_fun=1651.837, + ), + "luksan13": _problem( + fun=luksan13, + start_x=[-1] * 98, + solution_x=solution_x_luksan13, + solution_fun=24949.67040503685711883, # we found a lower minimum than Cartis and Roberts (2019); # according to table 3 in their paper, the minimum is at 25188.86 - }, - "luksan14": { - "fun": luksan14, - "start_x": [-1] * 98, - "solution_x": solution_x_luksan14, - "start_criterion": 2.6880e4, - "solution_criterion": 123.9235, - }, - "luksan15": { - "fun": luksan15, - "start_x": [-0.8, 1.2, -1.2, 0.8] * 25, - "solution_x": solution_x_luksan15, - "start_criterion": 2.701585e4, - "solution_criterion": 3.569697, - }, - "luksan16": { - "fun": luksan16, - "start_x": [-0.8, 1.2, -1.2, 0.8] * 25, - "solution_x": solution_x_luksan16, - "start_criterion": 1.306848e4, - "solution_criterion": 3.569697, - }, - "luksan17": { - "fun": luksan17, - "start_x": [-0.8, 1.2, -1.2, 0.8] * 25, - "solution_x": None, # multiple argmins - "start_criterion": 1.687370e6, - "solution_criterion": 0.4931613, - }, - "luksan21": { - "fun": luksan21, - "start_x": [ih * (ih - 1) for ih in np.arange(1, 101) * (1 / 101)], - "solution_x": solution_x_luksan21, - "start_criterion": 99.98751, - "solution_criterion": 0, - }, - "luksan22": { - "fun": luksan22, - "start_x": [-1.2 if i % 2 == 0 else 1 for i in range(100)], - "solution_x": solution_x_luksan22, - "start_criterion": 2.487686e4, - "solution_criterion": 872.9230, - }, - "methanb8": { - "fun": methane, - "start_x": get_start_points_methanb8(), - "solution_x": solution_x_methane, - "start_criterion": 1.043105, - "solution_criterion": 0, - }, - "methanl8": { - "fun": methane, - "start_x": get_start_points_methanl8(), - "solution_x": solution_x_methane, - "start_criterion": 4345.100, - "solution_criterion": 0, - }, - "morebvne": { - "fun": morebvne, - "start_x": [t * (t - 1) for t in np.arange(1, 101) * (1 / 101)], - "solution_x": solution_x_morebvne, - "start_criterion": 3.633100e-4, - "solution_criterion": 0, - }, - "msqrta": { - "fun": msqrta, - "start_x": get_start_points_msqrta(10), - "solution_x": solution_x_msqrta, - "start_criterion": 212.7162, - "solution_criterion": 0, - }, - "msqrtb": { - "fun": msqrta, - "start_x": get_start_points_msqrta(10, flag=2), - "solution_x": solution_x_msqrtb, - "start_criterion": 205.0753, - "solution_criterion": 0, - }, - "oscigrne": { - "fun": oscigrne, - "start_x": [-2] + [1] * 99, - "solution_x": solution_x_oscigrne, - "start_criterion": 6.120720e8, - "solution_criterion": 0, - }, - "penalty_1": { - "fun": penalty_1, - "start_x": list(range(1, 101)), - "solution_x": None, - "start_criterion": 1.144806e11, - "solution_criterion": 9.025000e-9, - }, - "penalty_2": { - "fun": penalty_2, - "start_x": [0.5] * 100, - "solution_x": solution_x_penalty2, - "start_criterion": 1.591383e6, - "solution_criterion": 0.9809377, - }, - "powellse": { - "fun": powell_singular, - "start_x": [3.0, -1.0, 0.0, 1] * 25, - "solution_x": [0] * 100, - "start_criterion": 41875, - "solution_criterion": 0, - }, - "qr3d": { - "fun": partial(qr3d, m=5), - "start_x": get_start_points_qr3d(5), - "solution_x": solution_x_qr3d, - "start_criterion": 1.2, - "solution_criterion": 0, - "bounds": Bounds( + ), + "luksan14": _problem( + fun=luksan14, + start_x=[-1] * 98, + solution_x=solution_x_luksan14, + solution_fun=123.9235, + ), + "luksan15": _problem( + fun=luksan15, + start_x=[-0.8, 1.2, -1.2, 0.8] * 25, + solution_x=solution_x_luksan15, + solution_fun=3.569697, + ), + "luksan16": _problem( + fun=luksan16, + start_x=[-0.8, 1.2, -1.2, 0.8] * 25, + solution_x=solution_x_luksan16, + solution_fun=3.569697, + ), + "luksan17": _problem( + fun=luksan17, + start_x=[-0.8, 1.2, -1.2, 0.8] * 25, + solution_x=None, # multiple argmins + solution_fun=0.4931613, + ), + "luksan21": _problem( + fun=luksan21, + start_x=[ih * (ih - 1) for ih in np.arange(1, 101) * (1 / 101)], + solution_x=solution_x_luksan21, + solution_fun=0, + ), + "luksan22": _problem( + fun=luksan22, + start_x=[-1.2 if i % 2 == 0 else 1 for i in range(100)], + solution_x=solution_x_luksan22, + solution_fun=872.9230, + ), + "methanb8": _problem( + fun=methane, + start_x=get_start_points_methanb8(), + solution_x=solution_x_methane, + solution_fun=0, + ), + "methanl8": _problem( + fun=methane, + start_x=get_start_points_methanl8(), + solution_x=solution_x_methane, + solution_fun=0, + ), + "morebvne": _problem( + fun=morebvne, + start_x=[t * (t - 1) for t in np.arange(1, 101) * (1 / 101)], + solution_x=solution_x_morebvne, + solution_fun=0, + ), + "msqrta": _problem( + fun=msqrta, + start_x=get_start_points_msqrta(10), + solution_x=solution_x_msqrta, + solution_fun=0, + ), + "msqrtb": _problem( + fun=msqrta, + start_x=get_start_points_msqrta(10, flag=2), + solution_x=solution_x_msqrtb, + solution_fun=0, + ), + "oscigrne": _problem( + fun=oscigrne, + start_x=[-2] + [1] * 99, + solution_x=solution_x_oscigrne, + solution_fun=0, + ), + "penalty_1": _problem( + fun=penalty_1, + start_x=list(range(1, 101)), + solution_x=None, + solution_fun=9.025000e-9, + ), + "penalty_2": _problem( + fun=penalty_2, + start_x=[0.5] * 100, + solution_x=solution_x_penalty2, + solution_fun=0.9809377, + ), + "powellse": _problem( + fun=powell_singular, + start_x=[3.0, -1.0, 0.0, 1] * 25, + solution_x=[0] * 100, + solution_fun=0, + ), + "qr3d": _problem( + fun=partial(qr3d, m=5), + start_x=get_start_points_qr3d(5), + solution_x=solution_x_qr3d, + solution_fun=0, + bounds=Bounds( lower=[-np.inf] * 25 + [0 if i == j else -np.inf for i in range(5) for j in range(5)] ), - }, - "qr3dbd": { - "fun": partial(qr3dbd, m=5), - "start_x": get_start_points_qr3dbd(5), - "solution_x": solution_x_qr3dbd, - "start_criterion": 1.2, - "solution_criterion": 0, - "bounds": Bounds( + ), + "qr3dbd": _problem( + fun=partial(qr3dbd, m=5), + start_x=get_start_points_qr3dbd(5), + solution_x=solution_x_qr3dbd, + solution_fun=0, + bounds=Bounds( lower=[-np.inf] * 25 + [0 if i == j else -np.inf for i in range(5) for j in range(5)] ), - }, - "spmsqrt": { - "fun": spmsqrt, - "start_x": get_start_points_spmsqrt(34), - "solution_x": solution_x_spmsqrt, - "start_criterion": 74.33542, - "solution_criterion": 0, - }, - "semicn2u": { - "fun": semicon2, - "start_x": [0] * 100, - "solution_x": solution_x_semicon2, - "start_criterion": 2.025037e4, - "solution_criterion": 0, - }, - "semicon2": { - "fun": semicon2, - "start_x": [0] * 100, - "solution_x": solution_x_semicon2, - "start_criterion": 2.025037e4, - "solution_criterion": 0, - "bounds": Bounds(lower=-5 * np.ones(100), upper=0.2 * 700 * np.ones(100)), - }, - "vardimne": { - "fun": vardimne, - "start_x": [1 - i / 100 for i in range(1, 101)], - "solution_x": [1] * 100, - "start_criterion": 1.310584e14, - "solution_criterion": 0, - }, - "watsonne": { - "fun": watson, - "start_x": [0] * 31, - "solution_x": solution_x_watson, - "start_criterion": 30, - "solution_criterion": 0, - }, - "yatpsq_1": { - "fun": partial(yatpsq_1, dim_in=10), - "start_x": [6] * 100 + [0] * 20, - "solution_x": solution_x_yatpsq_1, - "start_criterion": 2.073643e6, - "solution_criterion": 0, - }, - "yatpsq_2": { - "fun": partial(yatpsq_2, dim_in=10), - "start_x": [10] * 100 + [0] * 20, - "solution_x": solution_x_yatpsq_2, - "start_criterion": 1.831687e5, - "solution_criterion": 0, - }, + ), + "spmsqrt": _problem( + fun=spmsqrt, + start_x=get_start_points_spmsqrt(34), + solution_x=solution_x_spmsqrt, + solution_fun=0, + ), + "semicn2u": _problem( + fun=semicon2, + start_x=[0] * 100, + solution_x=solution_x_semicon2, + solution_fun=0, + ), + "semicon2": _problem( + fun=semicon2, + start_x=[0] * 100, + solution_x=solution_x_semicon2, + solution_fun=0, + bounds=Bounds(lower=-5 * np.ones(100), upper=0.2 * 700 * np.ones(100)), + ), + "vardimne": _problem( + fun=vardimne, + start_x=[1 - i / 100 for i in range(1, 101)], + solution_x=[1] * 100, + solution_fun=0, + ), + "watsonne": _problem( + fun=watson, + start_x=[0] * 31, + solution_x=solution_x_watson, + solution_fun=0, + ), + "yatpsq_1": _problem( + fun=partial(yatpsq_1, dim_in=10), + start_x=[6] * 100 + [0] * 20, + solution_x=solution_x_yatpsq_1, + solution_fun=0, + ), + "yatpsq_2": _problem( + fun=partial(yatpsq_2, dim_in=10), + start_x=[10] * 100 + [0] * 20, + solution_x=solution_x_yatpsq_2, + solution_fun=0, + ), } - - -def get_raw_problems_cartis_roberts() -> dict[str, dict[str, Any]]: - """Get the specifications of the Cartis-Roberts benchmark problems. - - Returns: - A dictionary that maps the name of each problem to its specification, which - contains the criterion function, the start values and the solution. - - """ - return CARTIS_ROBERTS_PROBLEMS diff --git a/src/optimagic/benchmarking/get_benchmark_problems.py b/src/optimagic/benchmarking/get_benchmark_problems.py index e1f878408..1395fb8ea 100644 --- a/src/optimagic/benchmarking/get_benchmark_problems.py +++ b/src/optimagic/benchmarking/get_benchmark_problems.py @@ -1,404 +1,312 @@ -from functools import partial, wraps -from typing import Any +"""Get the sets of benchmark problems that are shipped with optimagic.""" -import numpy as np +from __future__ import annotations + +import warnings +from collections.abc import Sequence +from dataclasses import dataclass, replace +from typing import Any, Literal, get_args -from optimagic import mark -from optimagic.benchmarking.noise_distributions import NOISE_DISTRIBUTIONS -from optimagic.shared.process_user_function import infer_aggregation_level -from optimagic.typing import AggregationLevel +import numpy as np +from numpy.typing import NDArray + +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + LeastSquaresBenchmarkFunction, +) +from optimagic.benchmarking.noise import ( + AdditiveBenchmarkNoise, + BenchmarkNoise, + MultiplicativeBenchmarkNoise, + pre_process_noise, +) +from optimagic.benchmarking.scaling import ( + BenchmarkScaler, + LinspaceBenchmarkScaler, + pre_process_scaling, +) from optimagic.utilities import get_rng +BenchmarkSetName = Literal["more_wild", "cartis_roberts", "example", "estimagic"] + def get_benchmark_problems( - name, + name: BenchmarkSetName, *, - additive_noise=False, - additive_noise_options=None, - multiplicative_noise=False, - multiplicative_noise_options=None, - scaling=False, - scaling_options=None, - seed=None, - exclude=None, -): + noise: bool | BenchmarkNoise = False, + scaling: bool | BenchmarkScaler = False, + seed: int | np.random.Generator | None = None, + exclude: str | Sequence[str] | None = None, + # deprecated + additive_noise: bool | None = None, + additive_noise_options: dict[str, Any] | None = None, + multiplicative_noise: bool | None = None, + multiplicative_noise_options: dict[str, Any] | None = None, + scaling_options: dict[str, Any] | None = None, +) -> dict[str, BenchmarkProblem]: """Get a dictionary of test problems for a benchmark. Args: - name (str): The name of the set of test problems. Currently "more_wild" - is the only supported one. - additive_noise (bool): Whether to add additive noise to the problem. - Default False. - additive_noise_options (dict or None): Specifies the amount and distribution - of the addititve noise added to the problem. Has the entries: - - distribition (str): One of "normal", "gumbel", "uniform", "logistic", - "laplace". Default "normal". - - std (float): The standard deviation of the noise. This works for all - distributions, even if those distributions are normally not specified - via a standard deviation (e.g. uniform). - - correlation (float): Number between 0 and 1 that specifies the auto - correlation of the noise. - multiplicative_noise (bool): Whether to add multiplicative noise to the problem. - Default False. - multiplicative_noise_options (dict or None): Specifies the amount and - distribition of the multiplicative noise added to the problem. Has entries: - - distribition (str): One of "normal", "gumbel", "uniform", "logistic", - "laplace". Default "normal". - - std (float): The standard deviation of the noise. This works for all - distributions, even if those distributions are normally not specified - via a standard deviation (e.g. uniform). - - correlation (float): Number between 0 and 1 that specifies the auto - correlation of the noise. - - clipping_value (float): A non-negative float. Multiplicative noise - becomes zero if the function value is zero. To avoid this, we do not - implement multiplicative noise as `f_noisy = f * epsilon` but by - `f_noisy` = f + (epsilon - 1) * f_clipped` where f_clipped is bounded - away from zero from both sides by the clipping value. - scaling (bool): Whether the parameter space of the problem should be rescaled. - scaling_options (dict): Dict containing the keys "min_scale", and "max_scale". - If scaling is True, the parameters the optimizer sees are the standard - parameters multiplied by np.linspace(min_scale, max_scale, len(params)). - If min_scale and max_scale have very different orders of magnitude, the - problem becomes harder to solve for many optimizers. - seed (Union[None, int, numpy.random.Generator]): If seed is None or int the - numpy.random.default_rng is used seeded with seed. If seed is already a - Generator instance then that instance is used. - exclude (str or List): Problems to exclude. - + name: The name of the set of test problems. "more_wild" are the least-squares + problems of Moré and Wild (2009) with 2 to 12 parameters and one additional + problem with 100 parameters. "cartis_roberts" are the least-squares + problems of Cartis and Roberts (2019) with 25 to 120 parameters. "example" + is a small subset of "more_wild" and "estimagic" a mix of problems from + both sets. + noise: Whether and how noise is added to the function values. If False, no + noise is added. If True, normally distributed noise with a standard + deviation of 0.01 is added. Pass an ``AdditiveBenchmarkNoise`` or a + ``MultiplicativeBenchmarkNoise`` to control the noise. Noise objects can be + combined with ``+``. + scaling: Whether and how the parameter space of the problems is rescaled. If + False, the problems are not rescaled. If True, the parameters are multiplied + by ``np.linspace(0.1, 10, n_params)``. Pass a ``LinspaceBenchmarkScaler`` or + another ``BenchmarkScaler`` to control the scaling. + seed: Seed for the noise. With an int or a numpy.random.Generator, the noise + is reproducible and all optimizers see the same noise on a problem. If + None, the noise differs between optimizations. + exclude: Name or names of problems that are left out. + additive_noise: Deprecated. Use ``noise`` instead. + additive_noise_options: Deprecated. Use ``noise`` instead. + multiplicative_noise: Deprecated. Use ``noise`` instead. + multiplicative_noise_options: Deprecated. Use ``noise`` instead. + scaling_options: Deprecated. Use ``scaling`` instead. Returns: - dict: Nested dictionary with benchmark problems of the structure: - {"name": {"inputs": {...}, "solution": {...}, "info": {...}}} - where "inputs" are keyword arguments for ``minimize`` such as the criterion - function and start parameters. "solution" contains the entries "params" and - "value" and "info" might contain information about the test problem. + Dictionary that maps the names of the problems to benchmark problems. The + dictionary can be filtered or merged with other problem dictionaries before it + is passed to ``run_benchmark``. """ + # ================================================================================== + # handle deprecations + # ================================================================================== + noise = _replace_deprecated_noise_arguments( + noise=noise, + additive_noise=additive_noise, + additive_noise_options=additive_noise_options, + multiplicative_noise=multiplicative_noise, + multiplicative_noise_options=multiplicative_noise_options, + ) + scaling = _replace_deprecated_scaling_options( + scaling=scaling, scaling_options=scaling_options + ) + + # ================================================================================== + # process arguments + # ================================================================================== + processed_noise = pre_process_noise(noise) + scaler = pre_process_scaling(scaling) + if exclude is None: - exclude = {} + excluded: set[str] = set() elif isinstance(exclude, str): - exclude = [exclude] + excluded = {exclude} else: - exclude = set(exclude) + excluded = set(exclude) rng = get_rng(seed) - raw_problems = _get_raw_problems(name) - - raw_problems = {k: v for k, v in raw_problems.items() if k not in exclude} - - is_noisy = bool(additive_noise or multiplicative_noise) - - if additive_noise: - additive_options = _process_noise_options(additive_noise_options, False) - else: - additive_options = None - - if multiplicative_noise: - multiplicative_options = _process_noise_options( - multiplicative_noise_options, True - ) - else: - multiplicative_options = None - - if scaling: - scaling_options = scaling_options if scaling_options is not None else {} - scaling_options = {"min_scale": 0.1, "max_scale": 10, **scaling_options} - else: - scaling_options = None + # ================================================================================== + # create the problems + # ================================================================================== problems = {} - for prob_name, specification in raw_problems.items(): - inputs = _create_problem_inputs( - specification, - additive_options=additive_options, - multiplicative_options=multiplicative_options, - scaling_options=scaling_options, - rng=rng, - ) - - problems[prob_name] = { - "inputs": inputs, - "noise_free_fun": specification["fun"], - "solution": _create_problem_solution( - specification, scaling_options=scaling_options - ), - "noisy": is_noisy, - "info": specification.get("info", {}), - "start_criterion": specification["start_criterion"], - } + for problem_name, raw_problem in _get_problem_set(name).items(): + if problem_name in excluded: + continue + problem = raw_problem + if scaler is not None: + problem = problem.with_scaling(scaler) + if processed_noise is not None: + # Each problem gets its own seed such that the noise of a problem does not + # depend on which other problems are optimized before it. + problem_seed = None if seed is None else int(rng.integers(2**32)) + problem = problem.with_noise(processed_noise, seed=problem_seed) + problems[problem_name] = problem return problems -def _get_raw_problems(name): - # The benchmark sets are imported only when they are requested, to keep - # `import optimagic` fast. Importing the Cartis-Roberts problems imports numba, - # which takes about 0.2 seconds. - if name == "more_wild": - from optimagic.benchmarking.more_wild import get_raw_problems_more_wild - - raw_problems = get_raw_problems_more_wild() - elif name == "cartis_roberts": - from optimagic.benchmarking.cartis_roberts import ( - get_raw_problems_cartis_roberts, - ) - - raw_problems = get_raw_problems_cartis_roberts() - elif name == "example": - raw_problems = _get_raw_problems_example() - elif name == "estimagic": - raw_problems = _get_raw_problems_estimagic() - else: - raise NotImplementedError() - return raw_problems - - -def _get_raw_problems_example(): - from optimagic.benchmarking.more_wild import get_raw_problems_more_wild - - subset = { - "rosenbrock_good_start", - "helical_valley_good_start", - "powell_singular_good_start", - "freudenstein_roth_good_start", - "bard_good_start", - "box_3d", - "brown_dennis_good_start", - "chebyquad_6", - "bdqrtic_8", - "mancino_5_good_start", - } - return {k: v for k, v in get_raw_problems_more_wild().items() if k in subset} - - -def _get_raw_problems_estimagic(): - from optimagic.benchmarking.cartis_roberts import get_raw_problems_cartis_roberts - from optimagic.benchmarking.more_wild import get_raw_problems_more_wild - - subset_mw = { - "cube_8", - "chebyquad_6", - "bdqrtic_8", - "linear_full_rank_bad_start", - "chebyquad_7", - "osborne_two_bad_start", - "bdqrtic_10", - "bdqrtic_11", - "heart_eight_bad_start", - "mancino_5_bad_start", - "chebyquad_8", - "cube_6", - "cube_5", - "bdqrtic_12", - "chebyquad_10", - "chebyquad_9", - "chebyquad_11", - "mancino_8", - "mancino_10", - "mancino_12_bad_start", - } - subset_cr = { - "hatfldg", - "bratu_3d", - "cbratu_2d", - "chnrsbne", - "bratu_2d", - "vardimne", - "penalty_1", - "arglale", - "arglble", - } - subset_add_steps = { - "rosenbrock_good_start", - "cube_5", - "chebyquad_10", - } - - raw_problems = {} - for k, v in get_raw_problems_more_wild().items(): - if k in subset_mw: - raw_problems[k] = v - if k in subset_add_steps: - problem = v.copy() - raw_func = problem["fun"] - - problem["fun"] = wraps(raw_func)(partial(_step_func, raw_func=raw_func)) - raw_problems[f"{k}_with_steps"] = problem - - for k, v in get_raw_problems_cartis_roberts().items(): - if k in subset_cr: - raw_problems[k] = v - - return raw_problems - - -def _step_func(x, raw_func): - return raw_func(x.round(3)) - - -def _create_problem_inputs( - specification, additive_options, multiplicative_options, scaling_options, rng -): - _x = np.array(specification["start_x"]) - - if scaling_options is not None: - scaling_factor = _get_scaling_factor(_x, scaling_options) - _x = _x * scaling_factor - else: - scaling_factor = None +@dataclass(frozen=True) +class LeastSquaresFunctionWithSteps(LeastSquaresBenchmarkFunction): + """Least-squares function that is evaluated at rounded parameters. - problem_type = infer_aggregation_level(specification["fun"]) + Rounding makes the function piecewise constant. This is a problem for optimizers + that use numerical derivatives with small step sizes. - problem_type_to_marker = { - AggregationLevel.SCALAR: mark.scalar, - AggregationLevel.LIKELIHOOD: mark.likelihood, - AggregationLevel.LEAST_SQUARES: mark.least_squares, - } - - _criterion = partial( - _internal_criterion_template, - criterion=specification["fun"], - additive_options=additive_options, - multiplicative_options=multiplicative_options, - scaling_factor=scaling_factor, - rng=rng, - ) - - _criterion = problem_type_to_marker[problem_type](_criterion) - - inputs = {"fun": _criterion, "params": _x} - return inputs - - -def _create_problem_solution(specification, scaling_options): - _solution_x = specification.get("solution_x") - if _solution_x is None: - _solution_x = np.array(specification["start_x"]) * np.nan - elif isinstance(_solution_x, list): - _solution_x = np.array(_solution_x) - _params = _solution_x - if scaling_options is not None: - _params = _params * _get_scaling_factor(_params, scaling_options) - - _value = specification["solution_criterion"] - - solution = { - "params": _params, - "value": _value, - } - return solution + """ + function: LeastSquaresBenchmarkFunction + """The function that is evaluated at the rounded parameters.""" -def _get_scaling_factor(x, options): - return np.linspace(options["min_scale"], options["max_scale"], len(x)) + decimals: int = 3 + """The number of decimals to which the parameters are rounded.""" + differentiable = False -def _internal_criterion_template( - params, criterion, additive_options, multiplicative_options, scaling_factor, rng -): - if scaling_factor is not None: - params = params / scaling_factor + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return self.function.fun(x.round(self.decimals)) - critval = criterion(params) + def supports_n_params(self, n_params: int) -> bool: + return self.function.supports_n_params(n_params) - noise = _get_combined_noise( - critval, - additive_options=additive_options, - multiplicative_options=multiplicative_options, - rng=rng, - ) - noisy_critval = critval + noise +def _get_problem_set(name: str) -> dict[str, BenchmarkProblem]: + # The problem sets are imported here to keep `import optimagic` fast. Importing + # the Cartis-Roberts problems imports numba. + from optimagic.benchmarking.more_wild import MORE_WILD_PROBLEMS - return noisy_critval + if name == "more_wild": + problems = dict(MORE_WILD_PROBLEMS) + elif name == "cartis_roberts": + from optimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS + problems = dict(CARTIS_ROBERTS_PROBLEMS) + elif name == "example": + subset = { + "rosenbrock_good_start", + "helical_valley_good_start", + "powell_singular_good_start", + "freudenstein_roth_good_start", + "bard_good_start", + "box_3d", + "brown_dennis_good_start", + "chebyquad_6", + "bdqrtic_8", + "mancino_5_good_start", + } + problems = {k: v for k, v in MORE_WILD_PROBLEMS.items() if k in subset} + elif name == "estimagic": + from optimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS + + subset_mw = { + "cube_8", + "chebyquad_6", + "bdqrtic_8", + "linear_full_rank_bad_start", + "chebyquad_7", + "osborne_two_bad_start", + "bdqrtic_10", + "bdqrtic_11", + "heart_eight_bad_start", + "mancino_5_bad_start", + "chebyquad_8", + "cube_6", + "cube_5", + "bdqrtic_12", + "chebyquad_10", + "chebyquad_9", + "chebyquad_11", + "mancino_8", + "mancino_10", + "mancino_12_bad_start", + } + subset_cr = { + "hatfldg", + "bratu_3d", + "cbratu_2d", + "chnrsbne", + "bratu_2d", + "vardimne", + "penalty_1", + "arglale", + "arglble", + } + subset_add_steps = { + "rosenbrock_good_start", + "cube_5", + "chebyquad_10", + } + problems = {} + for k, v in MORE_WILD_PROBLEMS.items(): + if k in subset_mw: + problems[k] = v + if k in subset_add_steps: + assert isinstance(v.function, LeastSquaresBenchmarkFunction) + problems[f"{k}_with_steps"] = replace( + v, function=LeastSquaresFunctionWithSteps(v.function) + ) + + for k, v in CARTIS_ROBERTS_PROBLEMS.items(): + if k in subset_cr: + problems[k] = v -def _get_combined_noise(fval, additive_options, multiplicative_options, rng): - size = len(np.atleast_1d(fval)) - if multiplicative_options is not None: - options = multiplicative_options.copy() - std = options.pop("std") - clipval = options.pop("clipping_value") - scaled_std = std * _clip_away_from_zero(fval, clipval) - multiplicative_noise = _sample_from_distribution( - **options, std=scaled_std, size=size, rng=rng - ) else: - multiplicative_noise = 0 - - if additive_options is not None: - additive_noise = _sample_from_distribution( - **additive_options, size=size, rng=rng + raise ValueError( + f"Invalid name of a benchmark set: {name}. Valid names are " + f"{get_args(BenchmarkSetName)}." ) - else: - additive_noise = 0 - - return multiplicative_noise + additive_noise - - -def _sample_from_distribution(distribution, mean, std, size, rng, correlation=0): - sample = NOISE_DISTRIBUTIONS[distribution](size=size, rng=rng) - dim = size if isinstance(size, int) else size[1] - if correlation != 0 and dim > 1: - chol = np.linalg.cholesky(np.diag(np.ones(dim) - correlation) + correlation) - sample = (chol @ sample.T).T - sample = sample / sample.std() - sample *= std - sample += mean - return sample - - -def _process_noise_options(options, is_multiplicative): - options = {} if options is None else options + return problems - defaults: dict[str, Any] = { - "std": 0.01, - "distribution": "normal", - "correlation": 0, - "mean": 0, - } - if is_multiplicative: - defaults["clipping_value"] = 1 - processed = { - **defaults, - **options, +def _replace_deprecated_noise_arguments( + noise: bool | BenchmarkNoise, + additive_noise: bool | None, + additive_noise_options: dict[str, Any] | None, + multiplicative_noise: bool | None, + multiplicative_noise_options: dict[str, Any] | None, +) -> bool | BenchmarkNoise: + """Convert the deprecated noise arguments to a value for the noise argument.""" + deprecated = { + "additive_noise": additive_noise, + "additive_noise_options": additive_noise_options, + "multiplicative_noise": multiplicative_noise, + "multiplicative_noise_options": multiplicative_noise_options, } + used = [name for name, value in deprecated.items() if value is not None] + if not used: + return noise + + msg = ( + f"The arguments {used} of `get_benchmark_problems` are deprecated and will be " + "removed in optimagic version 0.7.0. Use the `noise` argument instead, e.g. " + "`noise=om.AdditiveBenchmarkNoise(std=0.1)` or " + "`noise=om.AdditiveBenchmarkNoise() + om.MultiplicativeBenchmarkNoise()`." + ) + warnings.warn(msg, FutureWarning) - distribution = processed["distribution"] - if distribution not in NOISE_DISTRIBUTIONS: + if noise is not False: raise ValueError( - f"Invalid distribution: {distribution}. " - "Allowed are {list(NOISE_DISTRIBUTIONS)}" + f"You cannot use the `noise` argument and the deprecated arguments {used} " + "at the same time." ) - std = processed["std"] - if std < 0: - raise ValueError(f"std must be non-negative. Not: {std}") - - corr = processed["correlation"] - if corr < 0: - raise ValueError(f"corr must be non-negative. Not: {corr}") - - if is_multiplicative: - clipping_value = processed["clipping_value"] - if clipping_value < 0: - raise ValueError( - f"clipping_value must be non-negative. Not: {clipping_value}" - ) - - return processed - - -def _clip_away_from_zero(a, clipval): - is_scalar = np.isscalar(a) - a = np.atleast_1d(a) - - is_positive = a >= 0 - - clipped = np.where(is_positive, np.clip(a, clipval, np.inf), a) - clipped = np.where(~is_positive, np.clip(clipped, -np.inf, -clipval), clipped) + components: list[BenchmarkNoise] = [] + if multiplicative_noise: + options = multiplicative_noise_options or {} + components.append(MultiplicativeBenchmarkNoise(**options)) + if additive_noise: + options = additive_noise_options or {} + components.append(AdditiveBenchmarkNoise(**options)) + + if not components: + return False + out = components[0] + for component in components[1:]: + out = out + component + return out + + +def _replace_deprecated_scaling_options( + scaling: bool | BenchmarkScaler, scaling_options: dict[str, Any] | None +) -> bool | BenchmarkScaler: + """Convert the deprecated scaling_options to a value for the scaling argument.""" + if scaling_options is None: + return scaling + + msg = ( + "The argument `scaling_options` of `get_benchmark_problems` is deprecated and " + "will be removed in optimagic version 0.7.0. Pass a scaler as `scaling` " + "instead, e.g. `scaling=om.LinspaceBenchmarkScaler(min_scale=0.1, " + "max_scale=10)`." + ) + warnings.warn(msg, FutureWarning) - if is_scalar: - clipped = clipped[0] - return clipped + if isinstance(scaling, BenchmarkScaler): + raise ValueError( + "You cannot pass a BenchmarkScaler as `scaling` and use the deprecated " + "argument `scaling_options` at the same time." + ) + if scaling: + return LinspaceBenchmarkScaler(**scaling_options) + return False diff --git a/src/optimagic/benchmarking/more_wild.py b/src/optimagic/benchmarking/more_wild.py index 235c64d49..1fa2b642f 100644 --- a/src/optimagic/benchmarking/more_wild.py +++ b/src/optimagic/benchmarking/more_wild.py @@ -21,12 +21,18 @@ """ -from functools import partial -from typing import Any +from dataclasses import dataclass import numpy as np +from numpy.typing import NDArray from optimagic import mark +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkFunction, + BenchmarkProblem, + BenchmarkSolution, + LeastSquaresBenchmarkFunction, +) @mark.least_squares @@ -786,416 +792,669 @@ def get_start_points_mancino(n, a=1): ] -MORE_WILD_PROBLEMS = { - "linear_full_rank_good_start": { - "fun": mark.least_squares(partial(linear_full_rank, dim_out=45)), - "start_x": [1] * 9, - "solution_x": linear_full_rank_solution_x, - "start_criterion": 72, - "solution_criterion": 36, - }, - "linear_full_rank_bad_start": { - "fun": mark.least_squares(partial(linear_full_rank, dim_out=45)), - "start_x": [10] * 9, - "solution_x": linear_full_rank_solution_x, - "start_criterion": 1125, - "solution_criterion": 36, - }, - "linear_rank_one_good_start": { - "fun": mark.least_squares(partial(linear_rank_one, dim_out=35)), - "start_x": [1] * 7, - # no unique solution - "solution_x": None, - "start_criterion": 1.165420e7, - "solution_criterion": 8.380281690143324, - }, - "linear_rank_one_bad_start": { - "fun": mark.least_squares(partial(linear_rank_one, dim_out=35)), - "start_x": [10] * 7, - # no unique solution - "solution_x": None, - "start_criterion": 1.168591e9, - "solution_criterion": 8.380282, - }, - "linear_rank_one_zero_columns_rows_good_start": { - "fun": mark.least_squares( - partial(linear_rank_one_zero_columns_rows, dim_out=35) - ), - "start_x": [1] * 7, - # no unique solution - "solution_x": None, - "start_criterion": 4.989195e6, - "solution_criterion": 9.880597014926506, - }, - "linear_rank_one_zero_columns_rows_bad_start": { - "fun": mark.least_squares( - partial(linear_rank_one_zero_columns_rows, dim_out=35) - ), - "start_x": [10] * 7, - # no unique solution - "solution_x": None, - "start_criterion": 5.009356e8, - "solution_criterion": 9.880597014926506, - }, - "rosenbrock_good_start": { - "fun": rosenbrock, - "start_x": [-1.2, 1], - "solution_x": [1, 1], - "start_criterion": 24.2, - "solution_criterion": 0, - }, - "rosenbrock_bad_start": { - "fun": rosenbrock, - "start_x": [-12, 10], - "solution_x": [1, 1], - "start_criterion": 1.795769e6, - "solution_criterion": 0, - }, - "helical_valley_good_start": { - "fun": helical_valley, - "start_x": [-1, 0, 0], - "solution_x": [1, 0, 0], - "start_criterion": 2500, - "solution_criterion": 0, - }, - "helical_valley_bad_start": { - "fun": helical_valley, - "start_x": [-10, 0, 0], - "solution_x": [1, 0, 0], - "start_criterion": 10600, - "solution_criterion": 0, - }, - "powell_singular_good_start": { - "fun": powell_singular, - "start_x": [3, -1, 0, 1], - "solution_x": [0] * 4, - "start_criterion": 215, - "solution_criterion": 0, - }, - "powell_singular_bad_start": { - "fun": powell_singular, - "start_x": [30, -10, 0, 10], - "solution_x": [0] * 4, - "start_criterion": 1.615400e6, - "solution_criterion": 0, - }, - "freudenstein_roth_good_start": { - "fun": freudenstein_roth, - "start_x": [0.5, -2], - "solution_x": freudenstein_roth_solution_x, - "start_criterion": 400.5, - "solution_criterion": 48.984253679240013, - }, - "freudenstein_roth_bad_start": { - "fun": freudenstein_roth, - "start_x": [5, -20], - "solution_x": freudenstein_roth_solution_x, - "start_criterion": 1.545754e8, - "solution_criterion": 48.984253679240013, - }, - "bard_good_start": { - "fun": mark.least_squares(partial(bard, y=y_vec)), - "start_x": [1] * 3, - "solution_x": bard_solution_x, - "start_criterion": 41.68170, - "solution_criterion": 0.00821487730657897, - }, - "bard_bad_start": { - "fun": mark.least_squares(partial(bard, y=y_vec)), - "start_x": [10] * 3, - "solution_x": bard_solution_x, - "start_criterion": 1306.234, - "solution_criterion": 0.00821487730657897, - }, - "kowalik_osborne": { - "fun": mark.least_squares(partial)( - kowalik_osborne, - y1=v_vec, - y2=y2_vec, - ), - "start_x": [0.25, 0.39, 0.415, 0.39], - "solution_x": kowalik_osborne_solution_x, - "start_criterion": 5.313172e-3, - "solution_criterion": 0.00030750560384924, - }, - "meyer": { - "fun": mark.least_squares(partial(meyer, y=y3_vec)), - "start_x": [0.02, 4000, 250], - "solution_x": meyer_solution_x, - "start_criterion": 1.693608e9, - "solution_criterion": 87.945855170395831, - }, - "watson_6_good_start": { - "fun": watson, - "start_x": [0.5] * 6, - "solution_x": watson_6_solution_x, - "start_criterion": 16.43083, - "solution_criterion": 0.00228767005355236, - }, - "watson_6_bad_start": { - "fun": watson, - "start_x": [5] * 6, - "solution_x": watson_6_solution_x, - "start_criterion": 2.323367e6, - "solution_criterion": 0.00228767005355236, - }, - "watson_9_good_start": { - "fun": watson, - "start_x": [0.5] * 9, - "solution_x": watson_9_solution_x, - "start_criterion": 26.90417, - "solution_criterion": 1.399760e-6, - }, - "watson_9_bad_start": { - "fun": watson, - "start_x": [5] * 9, - "solution_x": watson_9_solution_x, - "start_criterion": 8.158877e6, - "solution_criterion": 1.399760e-6, - }, - "watson_12_good_start": { - "fun": watson, - "start_x": [0.5] * 12, - "solution_x": watson_12_solution_x, - "start_criterion": 73.67821, - "solution_criterion": 4.722381e-10, - }, - "watson_12_bad_start": { - "fun": watson, - "start_x": [5] * 12, - "solution_x": watson_12_solution_x, - "start_criterion": 2.059384e7, - "solution_criterion": 4.722381e-10, - }, - "box_3d": { - "fun": mark.least_squares(partial(box_3d, dim_out=10)), - "start_x": [0, 10, 20], - "solution_x": [1, 10, 1], - "start_criterion": 1031.154, - "solution_criterion": 0, - }, - "jennrich_sampson": { - "fun": mark.least_squares(partial(jennrich_sampson, dim_out=10)), - "start_x": [0.3, 0.4], - "solution_x": [0.2578252135686162] * 2, - "start_criterion": 4171.306, - "solution_criterion": 124.3621823556148, - }, - "brown_dennis_good_start": { - "fun": mark.least_squares(partial(brown_dennis, dim_out=20)), - "start_x": [25, 5, -5, -1], - "solution_x": brown_dennis_solution_x, - "start_criterion": 7.926693e6, - "solution_criterion": 85822.20162635, - }, - "brown_dennis_bad_start": { - "fun": mark.least_squares(partial(brown_dennis, dim_out=20)), - "start_x": [250, 50, -50, -10], - "solution_x": brown_dennis_solution_x, - "start_criterion": 3.081064e11, - "solution_criterion": 85822.20162635, - }, - "chebyquad_6": { - "fun": mark.least_squares(partial(chebyquad, dim_out=6)), - "start_x": [i / 7 for i in range(1, 7)], - "solution_x": chebyquad_6_solution_x, - "start_criterion": 4.642817e-2, - "solution_criterion": 0, - }, - "chebyquad_7": { - "fun": mark.least_squares(partial(chebyquad, dim_out=7)), - "start_x": [i / 8 for i in range(1, 8)], - "solution_x": chebyquad_7_solution_x, - "start_criterion": 3.377064e-2, - "solution_criterion": 0, - }, - "chebyquad_8": { - "fun": mark.least_squares(partial(chebyquad, dim_out=8)), - "start_x": [i / 9 for i in range(1, 9)], - "solution_x": chebyquad_8_solution_x, - "start_criterion": 3.861770e-2, - "solution_criterion": 0.003516873725677, - }, - "chebyquad_9": { - "fun": mark.least_squares(partial(chebyquad, dim_out=9)), - "start_x": [i / 10 for i in range(1, 10)], - "solution_x": chebyquad_9_solution_x, - "start_criterion": 2.888298e-2, - "solution_criterion": 0, - }, - "chebyquad_10": { - "fun": mark.least_squares(partial(chebyquad, dim_out=10)), - "start_x": [i / 11 for i in range(1, 11)], - "solution_x": chebyquad_10_solution_x, - "start_criterion": 3.376327e-2, - "solution_criterion": 0.00477271369637536, - }, - "chebyquad_11": { - "fun": mark.least_squares(partial(chebyquad, dim_out=11)), - "start_x": [i / 12 for i in range(1, 12)], - "solution_x": chebyquad_11_solution_x, - "start_criterion": 2.674060e-2, - "solution_criterion": 0.00279976155186576, - }, - "brown_almost_linear": { - "fun": brown_almost_linear, - "start_x": [0.5] * 10, - "solution_x": [1] * 10, - "start_criterion": 273.2480, - "solution_criterion": 0, - }, - "osborne_one": { - "fun": mark.least_squares(partial(osborne_one, y=y4_vec)), - "start_x": [0.5, 1.5, 1, 0.01, 0.02], - "solution_x": osborne_one_solution_x, - "start_criterion": 16.17411, - "solution_criterion": 0.00005464894697483, - }, - "osborne_two_good_start": { - "fun": mark.least_squares(partial(osborne_two, y=y5_vec)), - "start_x": [1.3, 0.65, 0.65, 0.7, 0.6, 3, 5, 7, 2, 4.5, 5.5], - "solution_x": osborne_two_solution_x, - "start_criterion": 2.093420, - "solution_criterion": 0.0401377362935477, - }, - "osborne_two_bad_start": { - "fun": mark.least_squares(partial(osborne_two, y=y5_vec)), - "start_x": [13, 6.5, 6.5, 7, 6, 30, 50, 70, 20, 45, 55], - "solution_x": osborne_two_solution_x, - "start_criterion": 199.6847, - "solution_criterion": 0.0401377362935477, - }, - "bdqrtic_8": { - "fun": bdqrtic, - "start_x": [1] * 8, - "solution_x": bdqrtic_8_solution_x, - "start_criterion": 904, - "solution_criterion": 10.2389734213174, - }, - "bdqrtic_10": { - "fun": bdqrtic, - "start_x": [1] * 10, - "solution_x": bdqrtic_10_solution_x, - "start_criterion": 1356, - "solution_criterion": 18.28116175359353, - }, - "bdqrtic_11": { - "fun": bdqrtic, - "start_x": [1] * 11, - "solution_x": bdqrtic_11_solution_x, - "start_criterion": 1582, - "solution_criterion": 22.260591734883817, - }, - "bdqrtic_12": { - "fun": bdqrtic, - "start_x": [1] * 12, - "solution_x": bdqrtic_12_solution_x, - "start_criterion": 1808, - "solution_criterion": 26.2727663967939, - }, - "cube_5": { - "fun": cube, - "start_x": [0.5] * 5, - "solution_x": [1] * 5, - "start_criterion": 56.5, - "solution_criterion": 0, - }, - "cube_6": { - "fun": cube, - "start_x": [0.5] * 6, - "solution_x": [1] * 6, - "start_criterion": 70.5625, - "solution_criterion": 0, - }, - "cube_8": { - "fun": cube, - "start_x": [0.5] * 8, - "solution_x": [1] * 8, - "start_criterion": 98.6875, - "solution_criterion": 0, - }, - "mancino_5_good_start": { - "fun": mancino, - "start_x": get_start_points_mancino(5), - "solution_x": mancino_5_solution_x, - "start_criterion": 2.539084e9, - "solution_criterion": 0, - }, - "mancino_5_bad_start": { - "fun": mancino, - "start_x": get_start_points_mancino(5, 10), - "solution_x": mancino_5_solution_x, - "start_criterion": 6.873795e12, - "solution_criterion": 0, - }, - "mancino_8": { - "fun": mancino, - "start_x": get_start_points_mancino(8), - "solution_x": mancino_8_solution_x, - "start_criterion": 3.367961e9, - "solution_criterion": 0, - }, - "mancino_10": { - "fun": mancino, - "start_x": get_start_points_mancino(10), - "solution_x": mancino_10_solution_x, - "start_criterion": 3.735127e9, - "solution_criterion": 0, - }, - "mancino_12_good_start": { - "fun": mancino, - "start_x": get_start_points_mancino(12), - "solution_x": mancino_12_solution_x, - "start_criterion": 3.991072e9, - "solution_criterion": 0, - }, - "mancino_12_bad_start": { - "fun": mancino, - "start_x": get_start_points_mancino(12, 10), - "solution_x": mancino_12_solution_x, - "start_criterion": 1.130015e13, - "solution_criterion": 0, - }, - "heart_eight_good_start": { - "fun": mark.least_squares( - partial( - heart_eight, - y=np.array([-0.69, -0.044, -1.57, -1.31, -2.65, 2, -12.6, 9.48]), - ) - ), - "start_x": [-0.3, -0.39, 0.3, -0.344, -1.2, 2.69, 1.59, -1.5], - "solution_x": heart_eight_solution_x, - "start_criterion": 9.385672, - "solution_criterion": 0, - }, - "heart_eight_bad_start": { - "fun": mark.least_squares( - partial( - heart_eight, - y=np.array([-0.69, -0.044, -1.57, -1.31, -2.65, 2, -12.6, 9.48]), - ) - ), - "start_x": [-3, -3.9, 3, -3.44, -12, 26.9, 15.9, -15], - "solution_x": heart_eight_solution_x, - "start_criterion": 3.365815e10, - "solution_criterion": 0, - }, - "brown_almost_linear_medium": { - "fun": brown_almost_linear, - "start_x": [0.5] * 100, - "solution_x": [1] * 100, - "start_criterion": 2.524757e5, - "solution_criterion": 0, - }, -} +heart_eight_y_vec = np.array([-0.69, -0.044, -1.57, -1.31, -2.65, 2, -12.6, 9.48]) + + +# ====================================================================================== +# Benchmark functions +# ====================================================================================== + + +@dataclass(frozen=True) +class LinearFullRank(LeastSquaresBenchmarkFunction): + """Linear function with full rank.""" + + dim_out: int + """The number of residuals. Must not be smaller than the number of parameters.""" + + differentiable = True + convex = True + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return linear_full_rank(x, dim_out=self.dim_out) + + def supports_n_params(self, n_params: int) -> bool: + return 1 <= n_params <= self.dim_out + + +@dataclass(frozen=True) +class LinearRankOne(LeastSquaresBenchmarkFunction): + """Linear function with rank one.""" + + dim_out: int + """The number of residuals. Must not be smaller than the number of parameters.""" + + differentiable = True + convex = True + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return linear_rank_one(x, dim_out=self.dim_out) + + def supports_n_params(self, n_params: int) -> bool: + return 1 <= n_params <= self.dim_out + + +@dataclass(frozen=True) +class LinearRankOneZeroColumnsRows(LeastSquaresBenchmarkFunction): + """Linear function with rank one and zero columns and rows.""" + + dim_out: int + """The number of residuals. Must not be smaller than the number of parameters.""" + + differentiable = True + convex = True + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return linear_rank_one_zero_columns_rows(x, dim_out=self.dim_out) + + def supports_n_params(self, n_params: int) -> bool: + return 1 <= n_params <= self.dim_out + + +@dataclass(frozen=True) +class Rosenbrock(LeastSquaresBenchmarkFunction): + """Rosenbrock function with two parameters.""" + + differentiable = True + convex = False + min_n_params = 2 + max_n_params = 2 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return rosenbrock(x) + + +@dataclass(frozen=True) +class HelicalValley(LeastSquaresBenchmarkFunction): + """Helical valley function.""" + + # the first residual jumps where x[0] changes its sign and x[1] is negative + differentiable = False + min_n_params = 3 + max_n_params = 3 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return helical_valley(x) + + +@dataclass(frozen=True) +class PowellSingular(LeastSquaresBenchmarkFunction): + """Powell singular function.""" + + differentiable = True + convex = True + min_n_params = 4 + max_n_params = 4 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return powell_singular(x) + + +@dataclass(frozen=True) +class FreudensteinRoth(LeastSquaresBenchmarkFunction): + """Freudenstein and Roth function.""" + + differentiable = True + convex = False + min_n_params = 2 + max_n_params = 2 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return freudenstein_roth(x) + + +@dataclass(frozen=True) +class Bard(LeastSquaresBenchmarkFunction): + """Bard function.""" + + differentiable = True + min_n_params = 3 + max_n_params = 3 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return bard(x, y=y_vec) + + +@dataclass(frozen=True) +class KowalikOsborne(LeastSquaresBenchmarkFunction): + """Kowalik and Osborne function.""" + + differentiable = True + min_n_params = 4 + max_n_params = 4 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return kowalik_osborne(x, y1=v_vec, y2=y2_vec) + + +@dataclass(frozen=True) +class Meyer(LeastSquaresBenchmarkFunction): + """Meyer function.""" + + differentiable = True + min_n_params = 3 + max_n_params = 3 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return meyer(x, y=y3_vec) + + +@dataclass(frozen=True) +class Watson(LeastSquaresBenchmarkFunction): + """Watson function.""" + differentiable = True + min_n_params = 2 + max_n_params = 31 -def get_raw_problems_more_wild() -> dict[str, dict[str, Any]]: - """Get the specifications of the More-Wild benchmark problems. + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return watson(x) + + +@dataclass(frozen=True) +class Box3D(LeastSquaresBenchmarkFunction): + """Box three-dimensional function.""" + + dim_out: int + """The number of residuals.""" + + differentiable = True + min_n_params = 3 + max_n_params = 3 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return box_3d(x, dim_out=self.dim_out) + + +@dataclass(frozen=True) +class JennrichSampson(LeastSquaresBenchmarkFunction): + """Jennrich and Sampson function.""" + + dim_out: int + """The number of residuals.""" + + differentiable = True + min_n_params = 2 + max_n_params = 2 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return jennrich_sampson(x, dim_out=self.dim_out) + + +@dataclass(frozen=True) +class BrownDennis(LeastSquaresBenchmarkFunction): + """Brown and Dennis function.""" + + dim_out: int + """The number of residuals.""" + + differentiable = True + min_n_params = 4 + max_n_params = 4 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return brown_dennis(x, dim_out=self.dim_out) + + +@dataclass(frozen=True) +class Chebyquad(LeastSquaresBenchmarkFunction): + """Chebyquad function.""" + + dim_out: int + """The number of residuals. Must not be smaller than the number of parameters.""" + + differentiable = True + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return chebyquad(x, dim_out=self.dim_out) + + def supports_n_params(self, n_params: int) -> bool: + return 1 <= n_params <= self.dim_out + + +@dataclass(frozen=True) +class BrownAlmostLinear(LeastSquaresBenchmarkFunction): + """Brown almost-linear function.""" + + differentiable = True + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return brown_almost_linear(x) + + +@dataclass(frozen=True) +class OsborneOne(LeastSquaresBenchmarkFunction): + """Osborne 1 function.""" + + differentiable = True + min_n_params = 5 + max_n_params = 5 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return osborne_one(x, y=y4_vec) + + +@dataclass(frozen=True) +class OsborneTwo(LeastSquaresBenchmarkFunction): + """Osborne 2 function.""" + + differentiable = True + min_n_params = 11 + max_n_params = 11 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return osborne_two(x, y=y5_vec) + + +@dataclass(frozen=True) +class Bdqrtic(LeastSquaresBenchmarkFunction): + """Banded quartic function (BDQRTIC).""" + + differentiable = True + min_n_params = 5 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return bdqrtic(x) + + +@dataclass(frozen=True) +class Cube(LeastSquaresBenchmarkFunction): + """Cube function.""" + + differentiable = True + min_n_params = 2 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return cube(x) + + +@dataclass(frozen=True) +class Mancino(LeastSquaresBenchmarkFunction): + """Mancino function.""" + + differentiable = True + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return mancino(x) + + +@dataclass(frozen=True) +class HeartEight(LeastSquaresBenchmarkFunction): + """Heart function with eight parameters.""" + + differentiable = True + min_n_params = 8 + max_n_params = 8 + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return heart_eight(x, y=heart_eight_y_vec) + + +# ====================================================================================== +# Benchmark problems +# ====================================================================================== + + +def _problem( + function: BenchmarkFunction, + start_x: list[float], + solution_x: list[float] | None, + solution_fun: float, +) -> BenchmarkProblem: + """Create a benchmark problem from the information in the problem table. + + Args: + function: The benchmark function. + start_x: The start parameters. + solution_x: The parameters at the solution or None if they are not unique. + solution_fun: The sum of squared residuals at the solution. Returns: - A dictionary that maps the name of each problem to its specification, which - contains the criterion function, the start values and the solution. + The benchmark problem. The solution is marked as exact if solution_fun is zero + because a sum of squares cannot be smaller. All other solutions are the best + known values. """ - return MORE_WILD_PROBLEMS + solution_params = None + if solution_x is not None: + solution_params = np.array(solution_x, dtype=np.float64) + + return BenchmarkProblem( + function=function, + start_params=np.array(start_x, dtype=np.float64), + solution=BenchmarkSolution( + fun=float(solution_fun), params=solution_params, exact=solution_fun == 0 + ), + ) + + +MORE_WILD_PROBLEMS: dict[str, BenchmarkProblem] = { + "linear_full_rank_good_start": _problem( + function=LinearFullRank(dim_out=45), + start_x=[1] * 9, + solution_x=linear_full_rank_solution_x, + solution_fun=36, + ), + "linear_full_rank_bad_start": _problem( + function=LinearFullRank(dim_out=45), + start_x=[10] * 9, + solution_x=linear_full_rank_solution_x, + solution_fun=36, + ), + "linear_rank_one_good_start": _problem( + function=LinearRankOne(dim_out=35), + start_x=[1] * 7, + # no unique solution + solution_x=None, + solution_fun=8.380281690143324, + ), + "linear_rank_one_bad_start": _problem( + function=LinearRankOne(dim_out=35), + start_x=[10] * 7, + # no unique solution + solution_x=None, + solution_fun=8.380282, + ), + "linear_rank_one_zero_columns_rows_good_start": _problem( + function=LinearRankOneZeroColumnsRows(dim_out=35), + start_x=[1] * 7, + # no unique solution + solution_x=None, + solution_fun=9.880597014926506, + ), + "linear_rank_one_zero_columns_rows_bad_start": _problem( + function=LinearRankOneZeroColumnsRows(dim_out=35), + start_x=[10] * 7, + # no unique solution + solution_x=None, + solution_fun=9.880597014926506, + ), + "rosenbrock_good_start": _problem( + function=Rosenbrock(), + start_x=[-1.2, 1], + solution_x=[1, 1], + solution_fun=0, + ), + "rosenbrock_bad_start": _problem( + function=Rosenbrock(), + start_x=[-12, 10], + solution_x=[1, 1], + solution_fun=0, + ), + "helical_valley_good_start": _problem( + function=HelicalValley(), + start_x=[-1, 0, 0], + solution_x=[1, 0, 0], + solution_fun=0, + ), + "helical_valley_bad_start": _problem( + function=HelicalValley(), + start_x=[-10, 0, 0], + solution_x=[1, 0, 0], + solution_fun=0, + ), + "powell_singular_good_start": _problem( + function=PowellSingular(), + start_x=[3, -1, 0, 1], + solution_x=[0] * 4, + solution_fun=0, + ), + "powell_singular_bad_start": _problem( + function=PowellSingular(), + start_x=[30, -10, 0, 10], + solution_x=[0] * 4, + solution_fun=0, + ), + "freudenstein_roth_good_start": _problem( + function=FreudensteinRoth(), + start_x=[0.5, -2], + solution_x=freudenstein_roth_solution_x, + solution_fun=48.984253679240013, + ), + "freudenstein_roth_bad_start": _problem( + function=FreudensteinRoth(), + start_x=[5, -20], + solution_x=freudenstein_roth_solution_x, + solution_fun=48.984253679240013, + ), + "bard_good_start": _problem( + function=Bard(), + start_x=[1] * 3, + solution_x=bard_solution_x, + solution_fun=0.00821487730657897, + ), + "bard_bad_start": _problem( + function=Bard(), + start_x=[10] * 3, + solution_x=bard_solution_x, + solution_fun=0.00821487730657897, + ), + "kowalik_osborne": _problem( + function=KowalikOsborne(), + start_x=[0.25, 0.39, 0.415, 0.39], + solution_x=kowalik_osborne_solution_x, + solution_fun=0.00030750560384924, + ), + "meyer": _problem( + function=Meyer(), + start_x=[0.02, 4000, 250], + solution_x=meyer_solution_x, + solution_fun=87.945855170395831, + ), + "watson_6_good_start": _problem( + function=Watson(), + start_x=[0.5] * 6, + solution_x=watson_6_solution_x, + solution_fun=0.00228767005355236, + ), + "watson_6_bad_start": _problem( + function=Watson(), + start_x=[5] * 6, + solution_x=watson_6_solution_x, + solution_fun=0.00228767005355236, + ), + "watson_9_good_start": _problem( + function=Watson(), + start_x=[0.5] * 9, + solution_x=watson_9_solution_x, + solution_fun=1.399760e-6, + ), + "watson_9_bad_start": _problem( + function=Watson(), + start_x=[5] * 9, + solution_x=watson_9_solution_x, + solution_fun=1.399760e-6, + ), + "watson_12_good_start": _problem( + function=Watson(), + start_x=[0.5] * 12, + solution_x=watson_12_solution_x, + solution_fun=4.722381e-10, + ), + "watson_12_bad_start": _problem( + function=Watson(), + start_x=[5] * 12, + solution_x=watson_12_solution_x, + solution_fun=4.722381e-10, + ), + "box_3d": _problem( + function=Box3D(dim_out=10), + start_x=[0, 10, 20], + solution_x=[1, 10, 1], + solution_fun=0, + ), + "jennrich_sampson": _problem( + function=JennrichSampson(dim_out=10), + start_x=[0.3, 0.4], + solution_x=[0.2578252135686162] * 2, + solution_fun=124.3621823556148, + ), + "brown_dennis_good_start": _problem( + function=BrownDennis(dim_out=20), + start_x=[25, 5, -5, -1], + solution_x=brown_dennis_solution_x, + solution_fun=85822.20162635, + ), + "brown_dennis_bad_start": _problem( + function=BrownDennis(dim_out=20), + start_x=[250, 50, -50, -10], + solution_x=brown_dennis_solution_x, + solution_fun=85822.20162635, + ), + "chebyquad_6": _problem( + function=Chebyquad(dim_out=6), + start_x=[i / 7 for i in range(1, 7)], + solution_x=chebyquad_6_solution_x, + solution_fun=0, + ), + "chebyquad_7": _problem( + function=Chebyquad(dim_out=7), + start_x=[i / 8 for i in range(1, 8)], + solution_x=chebyquad_7_solution_x, + solution_fun=0, + ), + "chebyquad_8": _problem( + function=Chebyquad(dim_out=8), + start_x=[i / 9 for i in range(1, 9)], + solution_x=chebyquad_8_solution_x, + solution_fun=0.003516873725677, + ), + "chebyquad_9": _problem( + function=Chebyquad(dim_out=9), + start_x=[i / 10 for i in range(1, 10)], + solution_x=chebyquad_9_solution_x, + solution_fun=0, + ), + "chebyquad_10": _problem( + function=Chebyquad(dim_out=10), + start_x=[i / 11 for i in range(1, 11)], + solution_x=chebyquad_10_solution_x, + solution_fun=0.00477271369637536, + ), + "chebyquad_11": _problem( + function=Chebyquad(dim_out=11), + start_x=[i / 12 for i in range(1, 12)], + solution_x=chebyquad_11_solution_x, + solution_fun=0.00279976155186576, + ), + "brown_almost_linear": _problem( + function=BrownAlmostLinear(), + start_x=[0.5] * 10, + solution_x=[1] * 10, + solution_fun=0, + ), + "osborne_one": _problem( + function=OsborneOne(), + start_x=[0.5, 1.5, 1, 0.01, 0.02], + solution_x=osborne_one_solution_x, + solution_fun=0.00005464894697483, + ), + "osborne_two_good_start": _problem( + function=OsborneTwo(), + start_x=[1.3, 0.65, 0.65, 0.7, 0.6, 3, 5, 7, 2, 4.5, 5.5], + solution_x=osborne_two_solution_x, + solution_fun=0.0401377362935477, + ), + "osborne_two_bad_start": _problem( + function=OsborneTwo(), + start_x=[13, 6.5, 6.5, 7, 6, 30, 50, 70, 20, 45, 55], + solution_x=osborne_two_solution_x, + solution_fun=0.0401377362935477, + ), + "bdqrtic_8": _problem( + function=Bdqrtic(), + start_x=[1] * 8, + solution_x=bdqrtic_8_solution_x, + solution_fun=10.2389734213174, + ), + "bdqrtic_10": _problem( + function=Bdqrtic(), + start_x=[1] * 10, + solution_x=bdqrtic_10_solution_x, + solution_fun=18.28116175359353, + ), + "bdqrtic_11": _problem( + function=Bdqrtic(), + start_x=[1] * 11, + solution_x=bdqrtic_11_solution_x, + solution_fun=22.260591734883817, + ), + "bdqrtic_12": _problem( + function=Bdqrtic(), + start_x=[1] * 12, + solution_x=bdqrtic_12_solution_x, + solution_fun=26.2727663967939, + ), + "cube_5": _problem( + function=Cube(), + start_x=[0.5] * 5, + solution_x=[1] * 5, + solution_fun=0, + ), + "cube_6": _problem( + function=Cube(), + start_x=[0.5] * 6, + solution_x=[1] * 6, + solution_fun=0, + ), + "cube_8": _problem( + function=Cube(), + start_x=[0.5] * 8, + solution_x=[1] * 8, + solution_fun=0, + ), + "mancino_5_good_start": _problem( + function=Mancino(), + start_x=get_start_points_mancino(5), + solution_x=mancino_5_solution_x, + solution_fun=0, + ), + "mancino_5_bad_start": _problem( + function=Mancino(), + start_x=get_start_points_mancino(5, 10), + solution_x=mancino_5_solution_x, + solution_fun=0, + ), + "mancino_8": _problem( + function=Mancino(), + start_x=get_start_points_mancino(8), + solution_x=mancino_8_solution_x, + solution_fun=0, + ), + "mancino_10": _problem( + function=Mancino(), + start_x=get_start_points_mancino(10), + solution_x=mancino_10_solution_x, + solution_fun=0, + ), + "mancino_12_good_start": _problem( + function=Mancino(), + start_x=get_start_points_mancino(12), + solution_x=mancino_12_solution_x, + solution_fun=0, + ), + "mancino_12_bad_start": _problem( + function=Mancino(), + start_x=get_start_points_mancino(12, 10), + solution_x=mancino_12_solution_x, + solution_fun=0, + ), + "heart_eight_good_start": _problem( + function=HeartEight(), + start_x=[-0.3, -0.39, 0.3, -0.344, -1.2, 2.69, 1.59, -1.5], + solution_x=heart_eight_solution_x, + solution_fun=0, + ), + "heart_eight_bad_start": _problem( + function=HeartEight(), + start_x=[-3, -3.9, 3, -3.44, -12, 26.9, 15.9, -15], + solution_x=heart_eight_solution_x, + solution_fun=0, + ), + "brown_almost_linear_medium": _problem( + function=BrownAlmostLinear(), + start_x=[0.5] * 100, + solution_x=[1] * 100, + solution_fun=0, + ), +} diff --git a/src/optimagic/benchmarking/noise.py b/src/optimagic/benchmarking/noise.py new file mode 100644 index 000000000..bbaaae218 --- /dev/null +++ b/src/optimagic/benchmarking/noise.py @@ -0,0 +1,284 @@ +"""Noise that can be added to the function values of benchmark problems.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Literal, TypeVar, cast, get_args + +import numpy as np +from numpy.typing import NDArray + +from optimagic.benchmarking.noise_distributions import NOISE_DISTRIBUTIONS + +NoiseDistribution = Literal["normal", "gumbel", "uniform", "logistic", "laplace"] + +FvalT = TypeVar("FvalT", float, NDArray[np.float64]) +"""Type of a function value: a float or an array of residuals or contributions.""" + + +class BenchmarkNoise(ABC): + """Base class for noise that is added to the function values of benchmark problems. + + Subclasses implement ``draw_noise``. Noise objects can be combined with ``+``, e.g. + ``AdditiveBenchmarkNoise() + MultiplicativeBenchmarkNoise()``. + + """ + + @abstractmethod + def draw_noise( + self, + fval: FvalT, + params: NDArray[np.float64], + rng: np.random.Generator, + ) -> FvalT: + """Draw the noise that is added to one function evaluation. + + Args: + fval: The function value without noise. A float for scalar functions; an + array of shape (n_residuals,) for least-squares functions and of shape + (n_contributions,) for likelihood functions. + params: The parameters at which the function was evaluated, shape + (n_params,). Can be used for noise that depends on the parameters. + rng: The random number generator that is used to draw the noise. + + Returns: + The noise. A float if fval is a float, otherwise an array with the same + shape as fval. + + """ + + def __add__(self, other: BenchmarkNoise) -> CombinedBenchmarkNoise: + if not isinstance(other, BenchmarkNoise): + return NotImplemented + return CombinedBenchmarkNoise((*_get_components(self), *_get_components(other))) + + +@dataclass(frozen=True) +class AdditiveBenchmarkNoise(BenchmarkNoise): + """Noise whose standard deviation does not depend on the function value.""" + + distribution: NoiseDistribution = "normal" + """The distribution the noise is drawn from.""" + + std: float = 0.01 + """The standard deviation of the noise. This works for all distributions, even if + they are normally not specified via a standard deviation (e.g. uniform).""" + + correlation: float = 0.0 + """Number between 0 and 1. The correlation between the noise terms of the residuals + or likelihood contributions of one function evaluation. Has no effect on scalar + functions.""" + + def __post_init__(self) -> None: + _fail_if_invalid_noise_arguments( + distribution=self.distribution, std=self.std, correlation=self.correlation + ) + + def draw_noise( + self, + fval: FvalT, + params: NDArray[np.float64], # noqa: ARG002 + rng: np.random.Generator, + ) -> FvalT: + return _draw_noise_like( + fval, + distribution=self.distribution, + std=self.std, + correlation=self.correlation, + rng=rng, + ) + + +@dataclass(frozen=True) +class MultiplicativeBenchmarkNoise(BenchmarkNoise): + """Noise whose standard deviation is proportional to the function value. + + Multiplicative noise would become zero if the function value is zero. To avoid + this, the noise is not implemented as ``f_noisy = f * epsilon`` but as ``f_noisy = f + + (epsilon - 1) * f_clipped``, where ``f_clipped`` is bounded away from zero from + both sides by ``clipping_value``. + + """ + + distribution: NoiseDistribution = "normal" + """The distribution the noise is drawn from.""" + + std: float = 0.01 + """The standard deviation of the noise, relative to the absolute function value. + This works for all distributions, even if they are normally not specified via a + standard deviation (e.g. uniform).""" + + correlation: float = 0.0 + """Number between 0 and 1. The correlation between the noise terms of the residuals + or likelihood contributions of one function evaluation. Has no effect on scalar + functions.""" + + clipping_value: float = 1.0 + """Non-negative number. Function values that are closer to zero than this are + replaced by this number (with the sign of the function value) when the standard + deviation of the noise is calculated.""" + + def __post_init__(self) -> None: + _fail_if_invalid_noise_arguments( + distribution=self.distribution, std=self.std, correlation=self.correlation + ) + if self.clipping_value < 0: + raise ValueError( + f"clipping_value must be non-negative, not {self.clipping_value}." + ) + + def draw_noise( + self, + fval: FvalT, + params: NDArray[np.float64], # noqa: ARG002 + rng: np.random.Generator, + ) -> FvalT: + scaled_std = self.std * _clip_away_from_zero(fval, self.clipping_value) + return _draw_noise_like( + fval, + distribution=self.distribution, + std=scaled_std, + correlation=self.correlation, + rng=rng, + ) + + +@dataclass(frozen=True) +class CombinedBenchmarkNoise(BenchmarkNoise): + """The sum of several sources of noise. + + Instances are created by adding noise objects with ``+``. + + """ + + components: tuple[BenchmarkNoise, ...] + """The sources of noise. All of them are drawn for the function value without + noise and then added up.""" + + def __post_init__(self) -> None: + if len(self.components) == 0: + raise ValueError("components must contain at least one source of noise.") + + def draw_noise( + self, + fval: FvalT, + params: NDArray[np.float64], + rng: np.random.Generator, + ) -> FvalT: + draws = [ + component.draw_noise(fval, params=params, rng=rng) + for component in self.components + ] + out = draws[0] + for draw in draws[1:]: + out = out + draw + return out + + +def pre_process_noise(noise: bool | BenchmarkNoise) -> BenchmarkNoise | None: + """Convert all valid ways of specifying noise to a BenchmarkNoise or None. + + Args: + noise: False for no noise, True for additive normally distributed noise with + default settings or a BenchmarkNoise. + + Returns: + The noise or None if no noise is added. + + Raises: + TypeError: If noise is neither a bool nor a BenchmarkNoise. + + """ + if isinstance(noise, BenchmarkNoise): + return noise + if noise is True: + return AdditiveBenchmarkNoise() + if noise is False: + return None + raise TypeError( + f"noise must be a bool or an instance of BenchmarkNoise, not {type(noise)}." + ) + + +def sample_from_distribution( + distribution: NoiseDistribution, + std: float | NDArray[np.float64], + size: int | tuple[int, int], + rng: np.random.Generator, + correlation: float = 0.0, +) -> NDArray[np.float64]: + """Draw noise with mean zero from a distribution. + + Args: + distribution: The distribution to draw from. + std: The standard deviation of the noise. A float or an array of shape + (n_columns,). + size: The shape of the sample, either n_columns or (n_draws, n_columns). + rng: The random number generator. + correlation: The correlation between the columns of the sample. + + Returns: + The sample of shape (n_columns,) or (n_draws, n_columns). + + """ + sample = NOISE_DISTRIBUTIONS[distribution](size=size, rng=rng) + dim = size if isinstance(size, int) else size[1] + if correlation != 0 and dim > 1: + chol = np.linalg.cholesky(np.diag(np.ones(dim) - correlation) + correlation) + sample = (chol @ sample.T).T + sample = sample / sample.std() + return sample * std + + +def _draw_noise_like( + fval: FvalT, + distribution: NoiseDistribution, + std: float | NDArray[np.float64], + correlation: float, + rng: np.random.Generator, +) -> FvalT: + """Draw noise that has the same type and shape as fval.""" + if isinstance(fval, np.ndarray): + sample = sample_from_distribution( + distribution, std=std, size=len(fval), rng=rng, correlation=correlation + ) + return cast(FvalT, sample) + sample = sample_from_distribution(distribution, std=std, size=1, rng=rng) + return cast(FvalT, float(sample[0])) + + +def _get_components(noise: BenchmarkNoise) -> tuple[BenchmarkNoise, ...]: + if isinstance(noise, CombinedBenchmarkNoise): + return noise.components + return (noise,) + + +def _fail_if_invalid_noise_arguments( + distribution: str, std: float, correlation: float +) -> None: + valid_distributions = get_args(NoiseDistribution) + if distribution not in valid_distributions: + raise ValueError( + f"Invalid distribution: {distribution}. Allowed are {valid_distributions}." + ) + if std < 0: + raise ValueError(f"std must be non-negative, not {std}.") + if not 0 <= correlation <= 1: + raise ValueError(f"correlation must be between 0 and 1, not {correlation}.") + + +def _clip_away_from_zero( + a: float | NDArray[np.float64], clipval: float +) -> float | NDArray[np.float64]: + is_scalar = np.isscalar(a) + arr = np.atleast_1d(a) + + is_positive = arr >= 0 + + clipped = np.where(is_positive, np.clip(arr, clipval, np.inf), arr) + clipped = np.where(~is_positive, np.clip(clipped, -np.inf, -clipval), clipped) + + if is_scalar: + return float(clipped[0]) + return clipped diff --git a/src/optimagic/benchmarking/process_benchmark_results.py b/src/optimagic/benchmarking/process_benchmark_results.py index e7d493400..d991fa4ab 100644 --- a/src/optimagic/benchmarking/process_benchmark_results.py +++ b/src/optimagic/benchmarking/process_benchmark_results.py @@ -1,48 +1,74 @@ +"""Process benchmark results for plots and reports.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Literal, cast + import numpy as np import pandas as pd +from numpy.typing import NDArray + +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + BenchmarkSolution, +) +from optimagic.benchmarking.benchmark_result import BenchmarkResult + +StoppingCriterion = Literal["x_and_y", "x_or_y", "x", "y"] def process_benchmark_results( - problems, results, stopping_criterion, x_precision=1e-4, y_precision=1e-4 -): + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], + stopping_criterion: StoppingCriterion | None, + x_precision: float = 1e-4, + y_precision: float = 1e-4, +) -> tuple[pd.DataFrame, pd.DataFrame]: """Create tidy DataFrame with all information needed for the benchmarking plots. + The results of each problem are compared to a reference solution, see + ``get_reference_solutions``. + Args: - problems (dict): optimagic benchmarking problems dictionary. Keys are the - problem names. Values contain information on the problem, including the - solution value. - results (dict): optimagic benchmarking results dictionary. Keys are - tuples of the form (problem, algorithm), values are dictionaries of the - collected information on the benchmark run, including 'criterion_history' - and 'time_history'. - stopping_criterion (str): one of "x_and_y", "x_or_y", "x", "y", or None. + problems: Dictionary that maps names to benchmark problems. + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). + stopping_criterion: one of "x_and_y", "x_or_y", "x", "y", or None. Determines how convergence is determined from the two precisions. If None, no convergence criterion is applied. - x_precision (float): how close an algorithm must have gotten to the + x_precision: how close an algorithm must have gotten to the true parameter values (as percent of the Euclidean distance between start and solution parameters) before the criterion for clipping and convergence is fulfilled. Default is 1e-4. - y_precision (float): how close an algorithm must have gotten to the + y_precision: how close an algorithm must have gotten to the true criterion values (as percent of the distance between start and solution criterion value) before the criterion for clipping and convergence is fulfilled. Default is 1e-4. Returns: - pandas.DataFrame: tidy DataFrame with the following columns: - - problem - - algorithm - - n_evaluations - - walltime - - criterion - - criterion_normalized - - monotone_criterion - - monotone_criterion_normalized - - parameter_distance - - parameter_distance_normalized - - monotone_parameter_distance - - monotone_parameter_distance_normalized + Tuple of two DataFrames. The first is a tidy DataFrame with the columns + + - problem + - algorithm + - n_evaluations + - n_batches + - walltime + - criterion + - criterion_normalized + - monotone_criterion + - monotone_criterion_normalized + - parameter_distance + - parameter_distance_normalized + - monotone_parameter_distance + - monotone_parameter_distance_normalized + + The second has the problems as index and the algorithms as columns. Its values + are True if the algorithm converged on the problem. """ + references = get_reference_solutions(problems, results) + histories = [] infos = [] @@ -50,6 +76,7 @@ def process_benchmark_results( history, is_converged = _process_one_result( problem=problems[problem_name], result=result, + reference=references[problem_name], stopping_criterion=stopping_criterion, x_precision=x_precision, y_precision=y_precision, @@ -65,48 +92,107 @@ def process_benchmark_results( } infos.append(info) - histories = pd.concat(histories, ignore_index=True) - infos = pd.DataFrame(infos).set_index(["problem", "algorithm"]).unstack() - infos.columns = [tup[1] for tup in infos.columns] # ty:ignore[invalid-assignment] + tidy_histories = pd.concat(histories, ignore_index=True) + converged_info = cast( + pd.DataFrame, pd.DataFrame(infos).set_index(["problem", "algorithm"]).unstack() + ) + converged_info.columns = pd.Index([tup[1] for tup in converged_info.columns]) + + return tidy_histories, converged_info + + +def get_reference_solutions( + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], +) -> dict[str, BenchmarkSolution]: + """Get the solutions to which benchmark results are compared. - return histories, infos + The reference solution of a problem is + + - its stored solution if that solution is exact. + - the best function value any optimizer in results found if the problem has no + stored solution. The parameters of the reference solution are then None, i.e. + convergence can only be measured in terms of function values. + - the better one of the two if the stored solution is only the best known value. + If an optimizer found a better value and the stored solution has parameters, the + parameters at which the better value was found become the reference parameters. + + Args: + problems: Dictionary that maps names to benchmark problems. + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). + + Returns: + Dictionary that maps the names of all problems that occur in results to their + reference solutions. + + """ + best_found: dict[str, tuple[float, NDArray[np.float64]]] = {} + for (problem_name, _), result in results.items(): + fun_history = np.asarray(result.fun_history, dtype=np.float64) + candidates = np.where(np.isnan(fun_history), np.inf, fun_history) + idx = int(np.argmin(candidates)) + value = float(candidates[idx]) + if problem_name not in best_found or value < best_found[problem_name][0]: + best_found[problem_name] = (value, np.asarray(result.params_history)[idx]) + + references = {} + for problem_name, (best_fun, best_params) in best_found.items(): + solution = problems[problem_name].solution + if solution is None: + references[problem_name] = BenchmarkSolution(fun=best_fun) + elif solution.exact or solution.fun <= best_fun: + references[problem_name] = solution + else: + params = None if solution.params is None else best_params + references[problem_name] = BenchmarkSolution(fun=best_fun, params=params) + + return references def _process_one_result( - problem, - result, - stopping_criterion, - x_precision, - y_precision, -): + problem: BenchmarkProblem, + result: BenchmarkResult, + reference: BenchmarkSolution, + stopping_criterion: StoppingCriterion | None, + x_precision: float, + y_precision: float, +) -> tuple[pd.DataFrame, bool]: # input processing assert isinstance(x_precision, float) assert isinstance(y_precision, float) # extract information - _params_hist = result["params_history"] - _solution_crit = problem["solution"]["value"] - _start_crit = problem["start_criterion"] - _solution_x = problem["solution"].get("params") - _start_x = problem["inputs"]["params"] - _needed_step = np.linalg.norm(_solution_x - _start_x) - if isinstance(_solution_x, np.ndarray) and not np.isfinite(_solution_x).all(): + _params_hist = np.asarray(result.params_history, dtype=np.float64) + _solution_crit = reference.fun + _start_crit = problem.start_fun + _solution_x = reference.params + _start_x = problem.start_params + if _solution_x is not None and not np.isfinite(_solution_x).all(): _solution_x = None # calculate the different transformations of criterion values - crit_hist = np.array(result["criterion_history"]) + crit_hist = np.array(result.fun_history, dtype=np.float64) + if reference.exact: + # values below an exact solution can only be caused by numerical imprecision + crit_hist = np.clip(crit_hist, _solution_crit, np.inf) monotone_crit_hist = np.minimum.accumulate(crit_hist) - normalized_crit_hist = (crit_hist - _solution_crit) / (_start_crit - _solution_crit) - normalized_monotone_crit_hist = (monotone_crit_hist - _solution_crit) / ( - _start_crit - _solution_crit - ) + with np.errstate(divide="ignore", invalid="ignore"): + normalized_crit_hist = (crit_hist - _solution_crit) / ( + _start_crit - _solution_crit + ) + normalized_monotone_crit_hist = (monotone_crit_hist - _solution_crit) / ( + _start_crit - _solution_crit + ) # calculate the different versions of params distance if we have a solution if _solution_x is not None: - params_dist = np.linalg.norm(np.array(_params_hist - _solution_x), axis=1) + _needed_step = np.linalg.norm(_solution_x - _start_x) + params_dist = np.linalg.norm(_params_hist - _solution_x, axis=1) monotone_params_dist = np.minimum.accumulate(params_dist) - params_dist_normalized = params_dist / _needed_step - monotone_params_dist_normalized = monotone_params_dist / _needed_step + with np.errstate(divide="ignore", invalid="ignore"): + params_dist_normalized = params_dist / _needed_step + monotone_params_dist_normalized = monotone_params_dist / _needed_step else: params_dist = np.full(len(_params_hist), np.nan) monotone_params_dist = np.full(len(_params_hist), np.nan) @@ -116,8 +202,8 @@ def _process_one_result( # put everything together in a dict out_dict = { "n_evaluations": np.arange(len(crit_hist)), - "n_batches": result["batches_history"], - "walltime": result["time_history"], + "n_batches": np.asarray(result.batches_history), + "walltime": np.asarray(result.time_history), "criterion": crit_hist, "criterion_normalized": normalized_crit_hist, "monotone_criterion": monotone_crit_hist, @@ -129,6 +215,7 @@ def _process_one_result( } # calculate at which iteration the problem has been solved + is_converged = False if stopping_criterion is not None: is_converged_x, x_idx = _check_convergence(params_dist_normalized, x_precision) is_converged_y, y_idx = _check_convergence(normalized_crit_hist, y_precision) @@ -161,18 +248,16 @@ def _process_one_result( return out, is_converged -def _check_convergence(values, threshold): +def _check_convergence( + values: NDArray[np.float64], threshold: float +) -> tuple[bool, int | None]: boo = values <= threshold if boo.any(): - is_converged = True - idx = np.argmax(boo) - else: - is_converged = False - idx = None - return is_converged, idx + return True, int(np.argmax(boo)) + return False, None -def _aggregate_idxs_with_and(x, y): +def _aggregate_idxs_with_and(x: int | None, y: int | None) -> int | None: if x is None or y is None: out = None else: @@ -180,7 +265,7 @@ def _aggregate_idxs_with_and(x, y): return out -def _aggregate_idxs_with_or(x, y): +def _aggregate_idxs_with_or(x: int | None, y: int | None) -> int | None: if x is None and y is None: out = None elif x is None: diff --git a/src/optimagic/benchmarking/run_benchmark.py b/src/optimagic/benchmarking/run_benchmark.py index b4c619e25..75b10a74a 100644 --- a/src/optimagic/benchmarking/run_benchmark.py +++ b/src/optimagic/benchmarking/run_benchmark.py @@ -1,4 +1,4 @@ -"""Functions to create, run and visualize optimization benchmarks. +"""Run optimizers on sets of benchmark problems. TO-DO: - Add other benchmark sets: @@ -8,74 +8,97 @@ """ +from __future__ import annotations + +import warnings +from collections.abc import Mapping, Sequence +from typing import Any, Literal, TypeVar, cast + import numpy as np -from optimagic import batch_evaluators -from optimagic.algorithms import AVAILABLE_ALGORITHMS +from optimagic.batch_evaluators import process_batch_evaluator +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + aggregate_function_value, +) +from optimagic.benchmarking.benchmark_result import BenchmarkResult +from optimagic.optimization.algorithm import Algorithm +from optimagic.optimization.create_optimization_problem import ( + pre_process_user_algorithm, +) from optimagic.optimization.optimize import minimize -from optimagic.pytree import tree_leaves -from optimagic.typing import PyTreeNamespace +from optimagic.optimization.optimize_options import OptimizeOptions +from optimagic.optimization.optimize_result import OptimizeResult +from optimagic.typing import BatchEvaluator, BatchEvaluatorLiteral + +AlgorithmT = TypeVar("AlgorithmT", bound=Algorithm) + +# Mapping and Sequence are used instead of dict and list such that, for example, a +# dictionary whose values are all algorithm classes is accepted by type checkers. +OptimizeOptionsType = ( + Mapping[ + str, + str | Algorithm | type[Algorithm] | OptimizeOptions | dict[str, Any], + ] + | Sequence[str | Algorithm | type[Algorithm]] +) def run_benchmark( - problems, - optimize_options, + problems: Mapping[str, BenchmarkProblem], + optimize_options: OptimizeOptionsType, *, - batch_evaluator="joblib", - n_cores=1, - error_handling="continue", - max_criterion_evaluations=1_000, - disable_convergence=True, -): + batch_evaluator: BatchEvaluatorLiteral | BatchEvaluator = "joblib", + n_cores: int = 1, + error_handling: Literal["raise", "continue"] = "continue", + max_criterion_evaluations: int | None = 1_000, + disable_convergence: bool = True, +) -> dict[tuple[str, str], BenchmarkResult]: """Run problems with different optimize options. Args: - problems (dict): Nested dictionary with benchmark problems of the structure: - {"name": {"inputs": {...}, "solution": {...}, "info": {...}}} - where "inputs" are keyword arguments for ``minimize`` such as the criterion - function and start parameters. "solution" contains the entries "params" and - "value" and "info" might contain information about the test problem. - optimize_options (list or dict): Either a list of algorithms or a Nested - dictionary that maps a name for optimizer settings - (e.g. ``"lbfgsb_strict_criterion"``) to a dictionary of keyword arguments - for arguments for ``minimize`` (e.g. ``{"algorithm": "scipy_lbfgsb", - "algo_options": {"convergence.ftol_rel": 1e-12}}``). - Alternatively, the values can just be an algorithm which is then benchmarked - at default settings. - batch_evaluator (str or callable): See :ref:`batch_evaluators`. - n_cores (int): Number of optimizations that is run in parallel. Note that in + problems: Dictionary that maps names to benchmark problems, e.g. the result of + ``get_benchmark_problems``. + optimize_options: Dictionary that maps a name you choose (e.g. + ``"lbfgsb_few_evaluations"``) to what is benchmarked under that name. The + values can be the name of an algorithm (``"scipy_lbfgsb"``), an algorithm + class (``om.algos.scipy_lbfgsb``), a configured algorithm + (``om.algos.scipy_lbfgsb(stopping_maxfun=50)``) or ``om.OptimizeOptions`` + if you want to set more than the algorithm, e.g. options for numerical + derivatives. Passing a list of algorithms or dictionaries with keyword + arguments for ``minimize`` as values is deprecated. + batch_evaluator: See :ref:`batch_evaluators`. + n_cores: Number of optimizations that is run in parallel. Note that in addition to that an optimizer might parallelize. - error_handling (str): One of "raise", "continue". - max_criterion_evaluations (int): Shortcut to set the maximum number of - criterion evaluations instead of passing them in via algo options. In case - an optimizer does not support this stopping criterion, we also use this as - max iterations. - disable_convergence (bool): If True, we set extremely strict convergence - convergence criteria by default, such that most optimizers will exploit - their full computation budget set by max_criterion_evaluations. + error_handling: One of "raise", "continue". + max_criterion_evaluations: Shortcut to set the maximum number of function + evaluations instead of passing them in via algo options. In case an + optimizer does not support this stopping criterion, we also use this as + max iterations. Options you set yourself take precedence. + disable_convergence: If True, we set extremely strict convergence criteria by + default, such that most optimizers will exploit their full computation + budget set by max_criterion_evaluations. Options you set yourself take + precedence. Returns: - dict: Nested Dictionary with information on the benchmark run. The outer keys - are tuples where the first entry is the name of the problem and the second - the name of the optimize options. The values are dicts with the entries: - "params_history", "criterion_history", "time_history" and "solution". + Dictionary with one benchmark result for each combination of problem and + optimize options. The keys are tuples where the first entry is the name of the + problem and the second the name of the optimize options. """ - if isinstance(batch_evaluator, str): - batch_evaluator = getattr( - batch_evaluators, f"{batch_evaluator}_batch_evaluator" - ) - opt_options = _process_optimize_options( + evaluator = process_batch_evaluator(batch_evaluator) + + minimize_options = _process_optimize_options( optimize_options, max_evals=max_criterion_evaluations, disable_convergence=disable_convergence, ) minimize_arguments, keys = _get_optimization_arguments_and_keys( - problems, opt_options + problems, minimize_options ) - raw_results = batch_evaluator( + raw_results = evaluator( func=minimize, arguments=minimize_arguments, n_cores=n_cores, @@ -84,12 +107,12 @@ def run_benchmark( ) processing_arguments = [] - for name, raw_result in zip(keys, raw_results, strict=False): + for name, raw_result in zip(keys, raw_results, strict=True): processing_arguments.append( {"optimize_result": raw_result, "problem": problems[name[0]]} ) - results = batch_evaluator( + results = evaluator( func=_process_one_result, arguments=processing_arguments, n_cores=n_cores, @@ -97,123 +120,219 @@ def run_benchmark( unpack_symbol="**", ) - results = dict(zip(keys, results, strict=False)) + return dict(zip(keys, results, strict=True)) - return results +def _process_optimize_options( + raw_options: OptimizeOptionsType, + max_evals: int | None, + disable_convergence: bool, +) -> dict[str, dict[str, Any]]: + """Convert optimize_options to keyword arguments for minimize. -def _process_optimize_options(raw_options, max_evals, disable_convergence): - if not isinstance(raw_options, dict): + Args: + raw_options: The optimize_options passed to run_benchmark. + max_evals: Default for the maximum number of function evaluations and + iterations of each algorithm. + disable_convergence: Whether very strict convergence criteria are set as + default. + + Returns: + Dictionary that maps the names of the optimize options to keyword arguments + for minimize. The keyword arguments do not contain the entries that depend on + the benchmark problem. + + """ + dict_options: dict[str, Any] + if isinstance(raw_options, Mapping): + dict_options = dict(cast(Mapping[str, Any], raw_options)) + elif isinstance(raw_options, str): + raise TypeError( + "optimize_options must be a dictionary that maps names to algorithms or " + f"OptimizeOptions, not the string {raw_options!r}." + ) + else: + _throw_list_of_algorithms_future_warning() dict_options = {} for option in raw_options: if isinstance(option, str): dict_options[option] = option + elif isinstance(option, Algorithm): + dict_options[option.name] = option else: dict_options[option.__name__] = option - else: - dict_options = raw_options - default_algo_options = {} - if max_evals is not None: - default_algo_options["stopping.maxfun"] = max_evals - default_algo_options["stopping.maxiter"] = max_evals - if disable_convergence: - default_algo_options["convergence.ftol_rel"] = 1e-14 - default_algo_options["convergence.xtol_rel"] = 1e-14 - default_algo_options["convergence.gtol_rel"] = 1e-14 - - out_options = {} - for name, _option in dict_options.items(): - if not isinstance(_option, dict): - option = {"algorithm": _option} + out = {} + for name, option in dict_options.items(): + extra_kwargs: dict[str, Any] = {} + if isinstance(option, dict): + _throw_dict_options_future_warning() + kwargs = cast(dict[str, Any], option) + if "algorithm" not in kwargs: + raise ValueError( + f"The optimize options {name} do not contain an algorithm." + ) + extra_kwargs = { + k: v + for k, v in kwargs.items() + if k not in ("algorithm", "algo_options") + } + options = OptimizeOptions( + algorithm=kwargs["algorithm"], algo_options=kwargs.get("algo_options") + ) + elif isinstance(option, OptimizeOptions): + options = option else: - option = _option.copy() + options = OptimizeOptions(algorithm=option) - algo_options = {**default_algo_options, **option.get("algo_options", {})} - algo_options = {k.replace(".", "_"): v for k, v in algo_options.items()} - option["algo_options"] = algo_options - if isinstance(option.get("algo_options"), dict): - option["algo_options"] = {**default_algo_options, **option["algo_options"]} - else: - option["algo_options"] = default_algo_options + algorithm = _set_benchmark_defaults( + pre_process_user_algorithm(options.algorithm), + max_evals=max_evals, + disable_convergence=disable_convergence, + ) - out_options[name] = option + out[name] = { + "algorithm": algorithm, + "algo_options": options.algo_options, + "numdiff_options": options.numdiff_options, + "scaling": options.scaling, + "multistart": options.multistart, + **extra_kwargs, + } - return out_options + return out -def _get_optimization_arguments_and_keys(problems, opt_options): - kwargs_list = [] - names = [] +def _set_benchmark_defaults( + algorithm: AlgorithmT, max_evals: int | None, disable_convergence: bool +) -> AlgorithmT: + """Set the stopping and convergence criteria that are used in benchmarks. - for prob_name, problem in problems.items(): - for option_name, options in opt_options.items(): - algo = options["algorithm"] - if isinstance(algo, str): - if algo not in AVAILABLE_ALGORITHMS: - raise ValueError(f"Invalid algorithm: {algo}") - else: - valid_options = set(AVAILABLE_ALGORITHMS[algo].__dataclass_fields__) + Options the algorithm does not have are skipped. Options that were changed by the + user are not overwritten. An option counts as changed if its value differs from the + default value of the algorithm. - else: - valid_options = set(algo.__dataclass_fields__) + """ + defaults: dict[str, Any] = {} + if max_evals is not None: + defaults["stopping_maxfun"] = max_evals + defaults["stopping_maxiter"] = max_evals + if disable_convergence: + defaults["convergence_ftol_rel"] = 1e-14 + defaults["convergence_xtol_rel"] = 1e-14 + defaults["convergence_gtol_rel"] = 1e-14 + + untouched = type(algorithm)() + applicable = {} + for name, value in defaults.items(): + if not hasattr(untouched, name): + continue + if getattr(algorithm, name) == getattr(untouched, name): + applicable[name] = value - algo_options = options["algo_options"] - algo_options = {k: v for k, v in algo_options.items() if k in valid_options} + return algorithm.with_option(**applicable) - kwargs = {**options, **problem["inputs"]} - kwargs["algo_options"] = algo_options + +def _get_optimization_arguments_and_keys( + problems: Mapping[str, BenchmarkProblem], + minimize_options: dict[str, dict[str, Any]], +) -> tuple[list[dict[str, Any]], list[tuple[str, str]]]: + kwargs_list = [] + names = [] + + for problem_name, problem in problems.items(): + for option_name, options in minimize_options.items(): + kwargs = { + **options, + # Each optimization gets a new function such that all optimizers see + # the same noise if the problem has a seed. + "fun": problem.fun, + # The start parameters of a problem are read-only. + "params": problem.start_params.copy(), + "bounds": problem.bounds, + "jac": problem.jac, + } kwargs_list.append(kwargs) - names.append((prob_name, option_name)) + names.append((problem_name, option_name)) return kwargs_list, names -def _process_one_result(optimize_result, problem): +def _process_one_result( + optimize_result: OptimizeResult | str, problem: BenchmarkProblem +) -> BenchmarkResult: """Process the result of one optimization run. Args: - optimize_result (OptimizeResult): Result of one optimization run. - problem (dict): Problem specification. + optimize_result: Result of one optimization run or the traceback of the error + that was raised during the optimization. + problem: The problem that was optimized. Returns: - dict: Processed result. + The benchmark result. """ - _criterion = problem["noise_free_fun"] - _start_x = problem["inputs"]["params"] - _start_crit_value = _criterion(_start_x) - if isinstance(_start_crit_value, np.ndarray): - _start_crit_value = (_start_crit_value**2).sum() - _is_noisy = problem["noisy"] - _solution_crit = problem["solution"]["value"] + problem_type = problem.function.problem_type + noise_free_fun = problem.noise_free_fun # This will happen if the optimization raised an error if isinstance(optimize_result, str): - params_history_flat = [tree_leaves(_start_x, namespace=PyTreeNamespace.VALUE)] - criterion_history = [_start_crit_value] - time_history = [np.inf] - batches_history = [0] + return BenchmarkResult( + params_history=problem.start_params.reshape(1, -1), + fun_history=np.array([problem.start_fun]), + time_history=np.array([np.inf]), + batches_history=np.array([0], dtype=np.int64), + optimize_result=None, + traceback=optimize_result, + ) + + history = optimize_result.history + if history is None or len(history.fun) == 0: + raise ValueError( + "Benchmark results can only be created for optimizations that collect a " + "history." + ) + + # Only keep function evaluations. Evaluations of derivatives have no function + # value. + is_fun_evaluation = np.array([value is not None for value in history.fun]) + params_history = np.array(history.flat_params, dtype=np.float64)[is_fun_evaluation] + + if problem.noise is None: + fun_history = np.array(history.fun, dtype=np.float64)[is_fun_evaluation] else: - history = optimize_result.history - params_history = history.params - params_history_flat = [ - tree_leaves(p, namespace=PyTreeNamespace.VALUE) for p in params_history - ] - if _is_noisy: - criterion_history = np.array([_criterion(p) for p in params_history]) - if criterion_history.ndim == 2: - criterion_history = (criterion_history**2).sum(axis=1) - else: - criterion_history = history.fun - criterion_history = np.clip(criterion_history, _solution_crit, np.inf) - batches_history = history.batches - time_history = history.start_time - - return { - "params_history": params_history_flat, - "criterion_history": criterion_history, - "time_history": time_history, - "batches_history": batches_history, - "solution": optimize_result, - } + fun_history = np.array( + [ + aggregate_function_value(noise_free_fun(p), problem_type=problem_type) + for p in params_history + ] + ) + + return BenchmarkResult( + params_history=params_history, + fun_history=fun_history, + time_history=np.array(history.start_time, dtype=np.float64)[is_fun_evaluation], + batches_history=np.array(history.batches, dtype=np.int64)[is_fun_evaluation], + optimize_result=optimize_result, + ) + + +def _throw_list_of_algorithms_future_warning() -> None: + msg = ( + "Passing a list of algorithms as `optimize_options` to `run_benchmark` is " + "deprecated and will be removed in optimagic version 0.7.0. Pass a dictionary " + "that maps names to algorithms instead, e.g. " + '`{"lbfgsb": om.algos.scipy_lbfgsb, "nelder_mead": om.algos.scipy_neldermead}`.' + ) + warnings.warn(msg, FutureWarning) + + +def _throw_dict_options_future_warning() -> None: + msg = ( + "Specifying the entries of `optimize_options` in `run_benchmark` as " + "dictionaries with keyword arguments for `minimize` is deprecated and will be " + "removed in optimagic version 0.7.0. Use a configured algorithm instead, e.g. " + "`om.algos.scipy_lbfgsb(stopping_maxfun=100)`, or `om.OptimizeOptions` if you " + "need to set more than the algorithm." + ) + warnings.warn(msg, FutureWarning) diff --git a/src/optimagic/benchmarking/scaling.py b/src/optimagic/benchmarking/scaling.py new file mode 100644 index 000000000..3d7387f7e --- /dev/null +++ b/src/optimagic/benchmarking/scaling.py @@ -0,0 +1,107 @@ +"""Scalers that make benchmark problems badly scaled.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass + +import numpy as np +from numpy.typing import NDArray + + +class BenchmarkScaler(ABC): + """Base class for rescaling the parameters of benchmark problems. + + A scaler changes the parameters an optimizer works with. The optimizer sees + ``scale(params)`` and the benchmark function is evaluated at ``unscale`` of what the + optimizer proposes. Scaling is used to make a problem harder without changing its + solution. + + Subclasses implement ``scale`` and ``unscale``. Both have to work element by element + and be strictly increasing, such that bounds can be scaled like parameters. + + """ + + @abstractmethod + def scale(self, params: NDArray[np.float64]) -> NDArray[np.float64]: + """Convert parameters of the original problem to what the optimizer sees. + + Args: + params: Parameters of the original problem, shape (n_params,). + + Returns: + The scaled parameters, shape (n_params,). + + """ + + @abstractmethod + def unscale(self, params: NDArray[np.float64]) -> NDArray[np.float64]: + """Convert parameters the optimizer sees to those of the original problem. + + Args: + params: Scaled parameters, shape (n_params,). + + Returns: + Parameters of the original problem, shape (n_params,). + + """ + + +@dataclass(frozen=True) +class LinspaceBenchmarkScaler(BenchmarkScaler): + """Multiply the parameters by evenly spaced numbers. + + The parameters the optimizer sees are the original parameters multiplied by + ``np.linspace(min_scale, max_scale, n_params)``. If ``min_scale`` and ``max_scale`` + have very different orders of magnitude, the problem becomes harder to solve for + many optimizers. + + """ + + min_scale: float = 0.1 + """The factor by which the first parameter is multiplied. Must be positive.""" + + max_scale: float = 10.0 + """The factor by which the last parameter is multiplied. Must be positive.""" + + def __post_init__(self) -> None: + if self.min_scale <= 0 or self.max_scale <= 0: + raise ValueError( + "min_scale and max_scale must be positive, not " + f"{self.min_scale} and {self.max_scale}." + ) + + def scale(self, params: NDArray[np.float64]) -> NDArray[np.float64]: + return params * self._get_scaling_factor(len(params)) + + def unscale(self, params: NDArray[np.float64]) -> NDArray[np.float64]: + return params / self._get_scaling_factor(len(params)) + + def _get_scaling_factor(self, n_params: int) -> NDArray[np.float64]: + return np.linspace(self.min_scale, self.max_scale, n_params) + + +def pre_process_scaling(scaling: bool | BenchmarkScaler) -> BenchmarkScaler | None: + """Convert all valid ways of specifying scaling to a BenchmarkScaler or None. + + Args: + scaling: False for no scaling, True for a LinspaceBenchmarkScaler with default + settings or a BenchmarkScaler. + + Returns: + The scaler or None if the problems are not rescaled. + + Raises: + TypeError: If scaling is neither a bool nor a BenchmarkScaler. + + """ + if isinstance(scaling, BenchmarkScaler): + return scaling + if scaling is True: + return LinspaceBenchmarkScaler() + if scaling is False: + return None + raise TypeError( + "scaling must be a bool or an instance of BenchmarkScaler, not " + f"{type(scaling)}." + ) diff --git a/src/optimagic/optimization/optimize_options.py b/src/optimagic/optimization/optimize_options.py new file mode 100644 index 000000000..111f8e599 --- /dev/null +++ b/src/optimagic/optimization/optimize_options.py @@ -0,0 +1,52 @@ +"""Options of an optimization that do not depend on the optimization problem.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from optimagic.differentiation.numdiff_options import NumdiffOptions +from optimagic.optimization.algorithm import Algorithm +from optimagic.optimization.multistart_options import MultistartOptions +from optimagic.parameters.scaling import ScalingOptions + + +@dataclass(frozen=True) +class OptimizeOptions: + """Options for ``minimize`` or ``maximize`` that do not depend on the problem. + + The attributes have the same meaning as the arguments of ``minimize`` with the same + name. ``OptimizeOptions`` are used where a function runs optimizations for you, e.g. + in ``run_benchmark``. + + """ + + algorithm: str | Algorithm | type[Algorithm] + """The optimization algorithm.""" + + algo_options: dict[str, Any] | None = None + """Options of the algorithm. Only needed if ``algorithm`` is not a configured + instance of ``Algorithm``.""" + + numdiff_options: NumdiffOptions | None = None + """Options for the calculation of numerical derivatives.""" + + scaling: bool | ScalingOptions = False + """Whether and how the parameters are rescaled by optimagic.""" + + multistart: bool | MultistartOptions = False + """Whether and how a multistart optimization is done.""" + + def __post_init__(self) -> None: + is_algorithm_class = isinstance(self.algorithm, type) and issubclass( + self.algorithm, Algorithm + ) + if not (isinstance(self.algorithm, str | Algorithm) or is_algorithm_class): + raise TypeError( + "algorithm must be the name of an algorithm, a subclass of Algorithm " + f"or an instance of Algorithm, not {type(self.algorithm)}." + ) + if not isinstance(self.algo_options, dict | None): + raise TypeError( + f"algo_options must be a dict or None, not {type(self.algo_options)}." + ) diff --git a/src/optimagic/visualization/convergence_plot.py b/src/optimagic/visualization/convergence_plot.py index b22db9f79..21f86dc45 100644 --- a/src/optimagic/visualization/convergence_plot.py +++ b/src/optimagic/visualization/convergence_plot.py @@ -1,9 +1,16 @@ +from collections.abc import Mapping from typing import Any, Literal import numpy as np import pandas as pd +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + BenchmarkSolution, +) +from optimagic.benchmarking.benchmark_result import BenchmarkResult from optimagic.benchmarking.process_benchmark_results import ( + get_reference_solutions, process_benchmark_results, ) from optimagic.config import DEFAULT_PALETTE @@ -60,8 +67,8 @@ def convergence_plot( - problems: dict[str, dict[str, Any]], - results: dict[tuple[str, str], dict[str, Any]], + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], *, problem_subset: list[str] | None = None, algorithm_subset: list[str] | None = None, @@ -95,12 +102,9 @@ def convergence_plot( solution is one. Args: - problems: optimagic benchmarking problems dictionary. Keys are the problem - names. Values contain information on the problem, including the solution - value. - results: optimagic benchmarking results dictionary. Keys are tuples of the form - (problem, algorithm), values are dictionaries of the collected information - on the benchmark run, including 'criterion_history' and 'time_history'. + problems: Dictionary that maps names to benchmark problems. + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). problem_subset: List of problem names. These must be a subset of the keys of the problems dictionary. If provided the convergence plot is only created for the problems specified in this list. @@ -176,7 +180,7 @@ def convergence_plot( lines_list, titles = _extract_convergence_plot_lines( df=df, - problems=problems, + references=get_reference_solutions(problems, results), runtime_measure=runtime_measure, outcome=outcome, palette=palette, @@ -243,7 +247,7 @@ def convergence_plot( def _extract_convergence_plot_lines( df: pd.DataFrame, - problems: dict[str, dict[str, Any]], + references: dict[str, BenchmarkSolution], runtime_measure: str, outcome: str, palette: list[str] | str, @@ -285,7 +289,7 @@ def _extract_convergence_plot_lines( subplot_lines.append(line_data) if outcome in ("criterion", "monotone_criterion"): - f_opt = problems[prob_name]["solution"]["value"] + f_opt = references[prob_name].fun line_data = LineData( x=to_plot[runtime_measure].to_numpy(), y=np.full(to_plot[runtime_measure].shape, f_opt), diff --git a/src/optimagic/visualization/deviation_plot.py b/src/optimagic/visualization/deviation_plot.py index bb820e3de..5721809ed 100644 --- a/src/optimagic/visualization/deviation_plot.py +++ b/src/optimagic/visualization/deviation_plot.py @@ -28,13 +28,9 @@ def deviation_plot( best value. Args: - problems (dict): optimagic benchmarking problems dictionary. Keys are the - problem names. Values contain information on the problem, including the - solution value. - results (dict): optimagic benchmarking results dictionary. Keys are - tuples of the form (problem, algorithm), values are dictionaries of the - collected information on the benchmark run, including 'criterion_history' - and 'time_history'. + problems (dict): Dictionary that maps names to benchmark problems. + results (dict): Dictionary with benchmark results. Keys are tuples of the + form (problem, algorithm). runtime_measure (str): One of "n_evaluations", "n_batches". distance_measure (str): One of "criterion", "parameter_distance". monotone (bool): If True the best found criterion value so far is plotted. diff --git a/src/optimagic/visualization/profile_plot.py b/src/optimagic/visualization/profile_plot.py index 65060dc72..3d4f2c58e 100644 --- a/src/optimagic/visualization/profile_plot.py +++ b/src/optimagic/visualization/profile_plot.py @@ -1,10 +1,13 @@ import itertools +from collections.abc import Mapping from typing import Any, Literal import numpy as np import pandas as pd from numpy.typing import NDArray +from optimagic.benchmarking.benchmark_problem import BenchmarkProblem +from optimagic.benchmarking.benchmark_result import BenchmarkResult from optimagic.benchmarking.process_benchmark_results import ( process_benchmark_results, ) @@ -35,8 +38,8 @@ def profile_plot( - problems: dict[str, dict[str, Any]], - results: dict[tuple[str, str], dict[str, Any]], + problems: Mapping[str, BenchmarkProblem], + results: Mapping[tuple[str, str], BenchmarkResult], *, runtime_measure: Literal[ "walltime", "n_evaluations", "n_batches" @@ -69,11 +72,9 @@ def profile_plot( Moré and Wild (2009). Args: - problems: A dictionary where keys are the problem names. Values contain - information on the problem, including the solution value. - results: A dictionary where keys are tuples of the form (problem, algorithm), - values are dictionaries of the collected information on the benchmark - run, including 'criterion_history' and 'time_history'. + problems: Dictionary that maps names to benchmark problems. + results: Dictionary with benchmark results. Keys are tuples of the form + (problem, algorithm). runtime_measure: This is the runtime until the desired convergence was reached by an algorithm. This is called performance measure by Moré and Wild (2009). normalize_runtime: If True the runtime each algorithm needed for each problem is diff --git a/tests/optimagic/benchmarking/test_benchmark_problem.py b/tests/optimagic/benchmarking/test_benchmark_problem.py new file mode 100644 index 000000000..a4aba568b --- /dev/null +++ b/tests/optimagic/benchmarking/test_benchmark_problem.py @@ -0,0 +1,557 @@ +from dataclasses import dataclass + +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal as aaae + +import optimagic as om +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + BenchmarkSolution, + CallableBenchmarkFunction, + LeastSquaresBenchmarkFunction, + LikelihoodBenchmarkFunction, + ScalarBenchmarkFunction, + aggregate_function_value, +) +from optimagic.benchmarking.noise import AdditiveBenchmarkNoise +from optimagic.benchmarking.scaling import LinspaceBenchmarkScaler +from optimagic.shared.process_user_function import infer_aggregation_level +from optimagic.typing import AggregationLevel + +# ====================================================================================== +# Benchmark functions used in the tests +# ====================================================================================== + + +class Sphere(ScalarBenchmarkFunction): + differentiable = True + convex = True + + def fun(self, x): + return float(x @ x) + + def jac(self, x): + return 2 * x + + +@dataclass(frozen=True) +class ShiftedResiduals(LeastSquaresBenchmarkFunction): + shift: float = 1.0 + + min_n_params = 2 + max_n_params = 4 + + def fun(self, x): + return np.append(x - self.shift, x[0] * x[1]) + + def jac(self, x): + last_row = np.zeros(len(x)) + last_row[0] = x[1] + last_row[1] = x[0] + return np.vstack([np.eye(len(x)), last_row]) + + +class Contributions(LikelihoodBenchmarkFunction): + def fun(self, x): + return np.array([x[0] ** 2, x[1] ** 2 + x[0], 3.0]) + + def jac(self, x): + return np.array([[2 * x[0], 0.0], [1.0, 2 * x[1]], [0.0, 0.0]]) + + +class EvenSphere(ScalarBenchmarkFunction): + def fun(self, x): + return float(x @ x) + + def supports_n_params(self, n_params): + return n_params % 2 == 0 + + +class LogSum(ScalarBenchmarkFunction): + def fun(self, x): + return float(np.log(x).sum() + x @ x) + + def bounds(self, n_params): + return om.Bounds(lower=np.zeros(n_params)) + + +FUNCTIONS_WITH_JAC = [Sphere(), ShiftedResiduals(), Contributions()] + + +# ====================================================================================== +# BenchmarkFunction +# ====================================================================================== + + +def test_problem_type_is_set_by_base_classes(): + assert Sphere().problem_type == AggregationLevel.SCALAR + assert ShiftedResiduals().problem_type == AggregationLevel.LEAST_SQUARES + assert Contributions().problem_type == AggregationLevel.LIKELIHOOD + + +def test_default_properties_are_unknown(): + function = Contributions() + assert function.differentiable is None + assert function.convex is None + assert function.min_n_params == 1 + assert function.max_n_params is None + assert function.bounds(3) is None + + +def test_properties_can_be_set_in_subclasses(): + assert Sphere().differentiable is True + assert Sphere().convex is True + + +def test_has_jac(): + assert Sphere().has_jac + assert not EvenSphere().has_jac + + +def test_jac_raises_if_not_available(): + with pytest.raises(NotImplementedError, match="EvenSphere does not have"): + EvenSphere().jac(np.ones(2)) + + +def test_supports_n_params_without_limits(): + assert Sphere().supports_n_params(1) + assert Sphere().supports_n_params(10_000) + assert not Sphere().supports_n_params(0) + + +def test_supports_n_params_with_limits(): + function = ShiftedResiduals() + assert not function.supports_n_params(1) + assert function.supports_n_params(2) + assert function.supports_n_params(4) + assert not function.supports_n_params(5) + + +def test_supports_n_params_can_be_overridden(): + assert EvenSphere().supports_n_params(4) + assert not EvenSphere().supports_n_params(3) + + +@pytest.mark.parametrize( + "value, problem_type, expected", + [ + (3.0, AggregationLevel.SCALAR, 3.0), + (np.array([1.0, 2.0]), AggregationLevel.LEAST_SQUARES, 5.0), + (np.array([1.0, 2.0]), AggregationLevel.LIKELIHOOD, 3.0), + ], +) +def test_aggregate_function_value(value, problem_type, expected): + got = aggregate_function_value(value, problem_type=problem_type) + assert isinstance(got, float) + assert got == expected + + +# ====================================================================================== +# CallableBenchmarkFunction +# ====================================================================================== + + +def test_callable_benchmark_function(): + function = CallableBenchmarkFunction( + func=lambda x: x - 1, + problem_type=AggregationLevel.LEAST_SQUARES, + jac_func=lambda x: np.eye(len(x)), + differentiable=True, + min_n_params=2, + max_n_params=3, + ) + aaae(function.fun(np.array([1.0, 3.0])), np.array([0.0, 2.0])) + aaae(function.jac(np.array([1.0, 3.0])), np.eye(2)) + assert function.has_jac + assert function.differentiable is True + assert function.convex is None + assert function.supports_n_params(3) + assert not function.supports_n_params(4) + + +def test_callable_benchmark_function_without_jac(): + function = CallableBenchmarkFunction( + func=lambda x: float(x @ x), problem_type=AggregationLevel.SCALAR + ) + assert not function.has_jac + with pytest.raises(NotImplementedError): + function.jac(np.ones(2)) + + +def test_callable_benchmark_function_with_invalid_problem_type_raises(): + with pytest.raises(TypeError, match="problem_type must be an AggregationLevel"): + CallableBenchmarkFunction( + func=lambda x: x, + problem_type="least_squares", # ty: ignore[invalid-argument-type] + ) + + +# ====================================================================================== +# BenchmarkProblem: construction +# ====================================================================================== + + +def test_benchmark_problem_defaults(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(3)) + assert problem.n_params == 3 + assert problem.solution is None + assert problem.bounds is None + assert problem.noise is None + assert problem.scaler is None + assert problem.seed is None + assert problem.info == {} + + +def test_number_of_params_is_fixed_by_start_params(): + function = Sphere() + assert BenchmarkProblem(function, np.ones(2)).n_params == 2 + assert BenchmarkProblem(function, np.ones(100)).n_params == 100 + + +def test_start_params_are_converted_and_copied(): + start = [1, 2, 3] + problem = BenchmarkProblem( + function=Sphere(), + start_params=start, # ty: ignore[invalid-argument-type] + ) + assert isinstance(problem.start_params, np.ndarray) + assert problem.start_params.dtype == np.float64 + + arr = np.ones(3) + problem = BenchmarkProblem(function=Sphere(), start_params=arr) + arr[0] = 100 + aaae(problem.start_params, np.ones(3)) + + +def test_arrays_of_problems_and_solutions_are_read_only(): + solution = BenchmarkSolution(fun=0, params=[0, 0, 0]) # ty: ignore[invalid-argument-type] + assert isinstance(solution.fun, float) + assert isinstance(solution.params, np.ndarray) + with pytest.raises(ValueError, match="read-only"): + solution.params[0] = 1 + + problem = BenchmarkProblem( + function=Sphere(), start_params=np.ones(3), solution=solution + ) + with pytest.raises(ValueError, match="read-only"): + problem.start_params[0] = 100 + + scaled = problem.with_scaling(LinspaceBenchmarkScaler()) + with pytest.raises(ValueError, match="read-only"): + scaled.start_params[0] = 100 + + +def test_invalid_function_raises(): + with pytest.raises(TypeError, match="function must be an instance"): + BenchmarkProblem( + function=lambda x: x @ x, # ty: ignore[invalid-argument-type] + start_params=np.ones(3), + ) + + +def test_start_params_with_two_dimensions_raise(): + with pytest.raises(ValueError, match="one-dimensional array"): + BenchmarkProblem(function=Sphere(), start_params=np.ones((2, 2))) + + +@pytest.mark.parametrize("function", [ShiftedResiduals(), EvenSphere()]) +def test_unsupported_number_of_params_raises(function): + with pytest.raises(ValueError, match="does not support 5 parameters"): + BenchmarkProblem(function=function, start_params=np.ones(5)) + + +def test_solution_with_wrong_number_of_params_raises(): + with pytest.raises(ValueError, match="The solution has params of shape"): + BenchmarkProblem( + function=Sphere(), + start_params=np.ones(3), + solution=BenchmarkSolution(fun=0.0, params=np.zeros(2)), + ) + + +def test_bounds_default_to_bounds_of_function(): + problem = BenchmarkProblem(function=LogSum(), start_params=np.ones(3)) + assert isinstance(problem.bounds, om.Bounds) + aaae(np.asarray(problem.bounds.lower), np.zeros(3)) + assert problem.bounds.upper is None + + +def test_bounds_can_be_tighter_than_bounds_of_function(): + bounds = om.Bounds(lower=np.full(3, 0.5), upper=np.full(3, 2.0)) + problem = BenchmarkProblem( + function=LogSum(), start_params=np.ones(3), bounds=bounds + ) + assert problem.bounds is bounds + + +def test_bounds_wider_than_bounds_of_function_raise(): + with pytest.raises(ValueError, match="must not be wider"): + BenchmarkProblem( + function=LogSum(), + start_params=np.ones(3), + bounds=om.Bounds(lower=np.full(3, -1.0)), + ) + + +def test_bounds_with_wrong_shape_raise(): + with pytest.raises(ValueError, match="Bounds must have shape"): + BenchmarkProblem( + function=Sphere(), + start_params=np.ones(3), + bounds=om.Bounds(lower=np.zeros(2)), + ) + + +def test_bounds_with_wrong_type_raise(): + with pytest.raises(TypeError, match="bounds must be an instance"): + BenchmarkProblem( + function=Sphere(), + start_params=np.ones(3), + bounds=[(0, 1)] * 3, # ty: ignore[invalid-argument-type] + ) + + +# ====================================================================================== +# BenchmarkProblem: functions +# ====================================================================================== + + +@pytest.mark.parametrize("function", FUNCTIONS_WITH_JAC) +def test_fun_is_marked_with_problem_type(function): + problem = BenchmarkProblem(function=function, start_params=np.ones(2)) + assert infer_aggregation_level(problem.fun) == function.problem_type + assert infer_aggregation_level(problem.noise_free_fun) == function.problem_type + + +@pytest.mark.parametrize("function", FUNCTIONS_WITH_JAC) +def test_fun_without_noise_and_scaling_is_the_benchmark_function(function): + x = np.array([0.5, -2.0]) + problem = BenchmarkProblem(function=function, start_params=np.ones(2)) + aaae(problem.fun(x), function.fun(x)) + aaae(problem.noise_free_fun(x), function.fun(x)) + + +def test_start_fun(): + scalar = BenchmarkProblem(function=Sphere(), start_params=np.array([1.0, 2.0])) + assert scalar.start_fun == 5.0 + + least_squares = BenchmarkProblem(ShiftedResiduals(), np.array([2.0, 3.0])) + assert least_squares.start_fun == 1.0 + 4.0 + 36.0 + + likelihood = BenchmarkProblem(Contributions(), np.array([2.0, 3.0])) + assert likelihood.start_fun == 4.0 + 11.0 + 3.0 + + +def test_noisy_fun_differs_between_evaluations(): + problem = BenchmarkProblem( + function=ShiftedResiduals(), + start_params=np.ones(2), + noise=AdditiveBenchmarkNoise(std=0.1), + seed=0, + ) + fun = problem.fun + first = fun(problem.start_params) + second = fun(problem.start_params) + assert not np.allclose(first, second) + assert not np.allclose(first, problem.noise_free_fun(problem.start_params)) + + +def test_noise_restarts_from_seed_for_each_new_fun(): + problem = BenchmarkProblem( + function=Sphere(), + start_params=np.ones(2), + noise=AdditiveBenchmarkNoise(std=0.1), + seed=3, + ) + assert problem.fun(problem.start_params) == problem.fun(problem.start_params) + + +def test_noise_without_seed_differs_for_each_new_fun(): + problem = BenchmarkProblem( + function=Sphere(), + start_params=np.ones(2), + noise=AdditiveBenchmarkNoise(std=0.1), + ) + assert problem.fun(problem.start_params) != problem.fun(problem.start_params) + + +def test_start_fun_ignores_noise(): + problem = BenchmarkProblem( + function=Sphere(), + start_params=np.array([1.0, 2.0]), + noise=AdditiveBenchmarkNoise(std=10), + ) + assert problem.start_fun == 5.0 + + +# ====================================================================================== +# BenchmarkProblem: with_noise and with_scaling +# ====================================================================================== + + +def test_with_noise(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(2)) + noise = AdditiveBenchmarkNoise(std=0.5) + noisy = problem.with_noise(noise, seed=4) + + assert noisy.noise is noise + assert noisy.seed == 4 + assert problem.noise is None + + without_noise = noisy.with_noise(None) + assert without_noise.noise is None + assert without_noise.seed is None + + +def test_with_noise_with_invalid_type_raises(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(2)) + with pytest.raises(TypeError, match="noise must be an instance"): + problem.with_noise(True) # ty: ignore[invalid-argument-type] + + +def test_with_scaling(): + scaler = LinspaceBenchmarkScaler(min_scale=2, max_scale=4) + problem = BenchmarkProblem( + function=LogSum(), + start_params=np.array([1.0, 2.0, 3.0]), + solution=BenchmarkSolution(fun=-1.0, params=np.array([0.5, 0.5, 0.5])), + bounds=om.Bounds(lower=np.full(3, 0.1), upper=np.full(3, 10.0)), + ) + scaled = problem.with_scaling(scaler) + + assert scaled.scaler is scaler + aaae(scaled.start_params, np.array([2.0, 6.0, 12.0])) + assert scaled.solution is not None + assert scaled.bounds is not None + aaae(np.asarray(scaled.solution.params), np.array([1.0, 1.5, 2.0])) + assert scaled.solution.fun == -1.0 + aaae(np.asarray(scaled.bounds.lower), np.array([0.2, 0.3, 0.4])) + aaae(np.asarray(scaled.bounds.upper), np.array([20.0, 30.0, 40.0])) + + # the original problem is not changed + assert problem.scaler is None + aaae(problem.start_params, np.array([1.0, 2.0, 3.0])) + + +def test_scaling_does_not_change_function_values(): + """Ported from #723, where the noise free function ignored the scaling.""" + problem = BenchmarkProblem( + function=ShiftedResiduals(), + start_params=np.array([1.0, 2.0, 3.0]), + noise=AdditiveBenchmarkNoise(), + ) + scaled = problem.with_scaling(LinspaceBenchmarkScaler()) + + assert np.allclose(scaled.start_fun, problem.start_fun) + aaae( + scaled.noise_free_fun(scaled.start_params), + problem.noise_free_fun(problem.start_params), + ) + + +def test_scaling_of_default_bounds(): + scaler = LinspaceBenchmarkScaler(min_scale=2, max_scale=4) + problem = BenchmarkProblem(function=LogSum(), start_params=np.ones(3)) + scaled = problem.with_scaling(scaler) + assert scaled.bounds is not None + aaae(np.asarray(scaled.bounds.lower), np.zeros(3)) + + # bounds that are valid in the scaled space but not in the original space + with pytest.raises(ValueError, match="must not be wider"): + BenchmarkProblem( + function=LogSum(), + start_params=np.ones(3), + bounds=om.Bounds(lower=np.full(3, -1.0)), + scaler=scaler, + ) + + +def test_scaling_twice_raises(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(2)) + scaled = problem.with_scaling(LinspaceBenchmarkScaler()) + with pytest.raises(ValueError, match="The problem is already scaled"): + scaled.with_scaling(LinspaceBenchmarkScaler()) + + +def test_with_scaling_with_invalid_type_raises(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(2)) + with pytest.raises(TypeError, match="scaler must be an instance"): + problem.with_scaling(True) # ty: ignore[invalid-argument-type] + + +# ====================================================================================== +# BenchmarkProblem: derivatives +# ====================================================================================== + +EXPECTED_DERIVATIVE_LEVELS = { + AggregationLevel.SCALAR: [AggregationLevel.SCALAR], + AggregationLevel.LEAST_SQUARES: [ + AggregationLevel.SCALAR, + AggregationLevel.LIKELIHOOD, + AggregationLevel.LEAST_SQUARES, + ], + AggregationLevel.LIKELIHOOD: [AggregationLevel.SCALAR, AggregationLevel.LIKELIHOOD], +} + + +def _evaluate_at_level(function, x, level): + """Evaluate a benchmark function as an optimizer of the given level sees it.""" + raw = function.fun(x) + if level == function.problem_type: + return raw + if level == AggregationLevel.SCALAR: + return aggregate_function_value(raw, function.problem_type) + # least-squares function seen by a likelihood optimizer + return raw**2 + + +@pytest.mark.parametrize("function", FUNCTIONS_WITH_JAC) +def test_jac_matches_numerical_derivatives(function): + x = np.array([0.7, -1.3]) + problem = BenchmarkProblem(function=function, start_params=np.ones(2)) + + derivatives = problem.jac + assert derivatives is not None + levels = [infer_aggregation_level(derivative) for derivative in derivatives] + assert levels == EXPECTED_DERIVATIVE_LEVELS[function.problem_type] + + for derivative, level in zip(derivatives, levels, strict=True): + expected = om.first_derivative( + lambda x, level=level: _evaluate_at_level(function, x, level), x + ).derivative + aaae(derivative(x), expected, decimal=5) + + +def test_jac_is_none_without_closed_form_derivative(): + problem = BenchmarkProblem(function=EvenSphere(), start_params=np.ones(2)) + assert problem.jac is None + + +def test_jac_is_none_with_noise_or_scaling(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(2)) + assert problem.with_noise(AdditiveBenchmarkNoise()).jac is None + assert problem.with_scaling(LinspaceBenchmarkScaler()).jac is None + + +@pytest.mark.parametrize("algorithm", ["scipy_lbfgsb", "scipy_ls_lm"]) +def test_problem_can_be_passed_to_minimize(algorithm): + problem = BenchmarkProblem( + function=ShiftedResiduals(shift=2.0), start_params=np.array([3.0, 0.0]) + ) + derivatives = problem.jac + assert derivatives is not None + res = om.minimize( + fun=problem.fun, + params=problem.start_params, + algorithm=algorithm, + jac=derivatives, + bounds=problem.bounds, + ) + assert res.fun < problem.start_fun + expected_fun = aggregate_function_value( + problem.function.fun(res.params), AggregationLevel.LEAST_SQUARES + ) + assert np.allclose(res.fun, expected_fun) + # the first entry of jac is the gradient of the sum of squared residuals + aaae(derivatives[0](res.params), np.zeros(2), decimal=4) diff --git a/tests/optimagic/benchmarking/test_benchmark_reports.py b/tests/optimagic/benchmarking/test_benchmark_reports.py index d069966bd..ec60060f0 100644 --- a/tests/optimagic/benchmarking/test_benchmark_reports.py +++ b/tests/optimagic/benchmarking/test_benchmark_reports.py @@ -3,13 +3,25 @@ import numpy as np import pytest +import optimagic as om from optimagic import ( - OptimizeResult, convergence_report, get_benchmark_problems, rank_report, traceback_report, ) +from optimagic.benchmarking.benchmark_result import BenchmarkResult + + +def _result(params_history, fun_history, time_history, batches_history, traceback): + return BenchmarkResult( + params_history=np.array(params_history, dtype=np.float64), + fun_history=np.array(fun_history, dtype=np.float64), + time_history=np.array(time_history, dtype=np.float64), + batches_history=np.array(batches_history, dtype=np.int64), + optimize_result=None, + traceback=traceback, + ) @pytest.fixture @@ -20,125 +32,78 @@ def benchmark_example(): for k, v in all_problems.items() if k in ["bard_good_start", "box_3d", "rosenbrock_good_start"] } - _stop_after_10 = { - "stopping_max_criterion_evaluations": 10, - "stopping_max_iterations": 10, - } optimizers = { - "lbfgsb": {"algorithm": "scipy_lbfgsb", "algo_options": _stop_after_10}, - "nm": {"algorithm": "scipy_neldermead", "algo_options": _stop_after_10}, + "lbfgsb": om.algos.scipy_lbfgsb(stopping_maxfun=10, stopping_maxiter=10), + "nm": om.algos.scipy_neldermead(stopping_maxfun=10, stopping_maxiter=10), } results = { - ("bard_good_start", "lbfgsb"): { - "params_history": [ + # success + ("bard_good_start", "lbfgsb"): _result( + params_history=[ [1.0, 1.0, 1.0], [0.48286315298120086, 1.6129119244711858, 1.5974181569859445], [0.09754340799557773, 1.7558262514618663, 1.7403560082627973], ], - "criterion_history": np.array( - [ - 4.16816959e01, - 3.20813118e00, - 9.97263708e-03, - ] - ), - "time_history": [ - 0.0, - 0.0003762839987757616, - 0.0007037959985609632, - ], - "batches_history": [0, 1, 2], - "solution": OptimizeResult, # success - }, - ("box_3d", "lbfgsb"): { - "params_history": [ + fun_history=[4.16816959e01, 3.20813118e00, 9.97263708e-03], + time_history=[0.0, 0.0003762839987757616, 0.0007037959985609632], + batches_history=[0, 1, 2], + traceback=None, + ), + # failed + ("box_3d", "lbfgsb"): _result( + params_history=[ [0.0, 10.0, 20.0], [-0.6579976970071755, 10.014197643614924, 19.247113914560085], [-3.2899884850358774, 10.070988218074623, 16.235569572800433], ], - "criterion_history": np.array( - [ - 1.03115381e03, - 8.73640769e02, - 9.35093416e02, - ] - ), - "time_history": [ - 0.0, - 0.000555748996703187, - 0.0009771709992492106, - ], - "batches_history": [0, 1, 2], - "solution": OptimizeResult, # failed - }, - ("rosenbrock_good_start", "lbfgsb"): { - "params_history": [ - [-1.2, 1.0], - [0.0, 0.0], - ], - "criterion_history": np.array([1.795769e6, 1e3]), - "time_history": [ - 0.0, - 5.73799989069812e-04, - ], - "batches_history": [0, 1], - "solution": "lbfgsb traceback", # error - }, - ("bard_good_start", "nm"): { - "params_history": [ + fun_history=[1.03115381e03, 8.73640769e02, 9.35093416e02], + time_history=[0.0, 0.000555748996703187, 0.0009771709992492106], + batches_history=[0, 1, 2], + traceback=None, + ), + # error + ("rosenbrock_good_start", "lbfgsb"): _result( + params_history=[[-1.2, 1.0], [0.0, 0.0]], + fun_history=[1.795769e6, 1e3], + time_history=[0.0, 5.73799989069812e-04], + batches_history=[0, 1], + traceback="lbfgsb traceback", + ), + # success + ("bard_good_start", "nm"): _result( + params_history=[ [1.0, 1.0, 1.0], [1.05, 1.0, 1.0], [0.7999999999999998, 1.1999999999999993, 1.0499999999999994], [0.08241056, 1.13303608, 2.34369519], ], - "criterion_history": np.array( - [ - 41.68169586, - 43.90748158, - 23.92563745, - 0.00821487730657897, - ] - ), - "time_history": [ + fun_history=[41.68169586, 43.90748158, 23.92563745, 0.00821487730657897], + time_history=[ 0.0, 3.603900040616281e-05, 0.0004506860022956971, 0.00015319500016630627, ], - "batches_history": [0, 1, 2, 4], - "solution": OptimizeResult, # success - }, - ("box_3d", "nm"): { - "params_history": [ - [0.0, 10.0, 20.0], - [0.025, 10.0, 20.0], - [0.0, 10.5, 20.0], - ], - "criterion_history": np.array( - [1031.15381061, 1031.17836473, 1030.15033678] - ), - "time_history": [ - 0.0, - 5.73799989069812e-05, - 0.00010679600018193014, - ], - "batches_history": [0, 1, 2], - "solution": "some traceback", # error - }, - ("rosenbrock_good_start", "nm"): { - "params_history": [ - [-1.2, 1.0], - [0.0, 0.0], - ], - "criterion_history": np.array([1.795769e6, 1e3]), - "time_history": [ - 0.0, - 5.73799989069812e-04, - ], - "batches_history": [0, 1], - "solution": "another traceback", # error - }, + batches_history=[0, 1, 2, 4], + traceback=None, + ), + # error + ("box_3d", "nm"): _result( + params_history=[[0.0, 10.0, 20.0], [0.025, 10.0, 20.0], [0.0, 10.5, 20.0]], + fun_history=[1031.15381061, 1031.17836473, 1030.15033678], + time_history=[0.0, 5.73799989069812e-05, 0.00010679600018193014], + batches_history=[0, 1, 2], + traceback="some traceback", + ), + # error + ("rosenbrock_good_start", "nm"): _result( + params_history=[[-1.2, 1.0], [0.0, 0.0]], + fun_history=[1.795769e6, 1e3], + time_history=[0.0, 5.73799989069812e-04], + batches_history=[0, 1], + traceback="another traceback", + ), } return problems, optimizers, results @@ -172,6 +137,27 @@ def test_convergence_report(options, benchmark_example): assert df["nm"].loc["box_3d"] == "error" +def test_convergence_report_values(benchmark_example): + problems, _, results = benchmark_example + df = convergence_report(problems=problems, results=results, stopping_criterion="y") + + assert df["nm"].to_dict() == { + "bard_good_start": "success", + "box_3d": "error", + "rosenbrock_good_start": "error", + } + assert df["lbfgsb"].to_dict() == { + "bard_good_start": "success", + "box_3d": "failed", + "rosenbrock_good_start": "error", + } + assert df["dimensionality"].to_dict() == { + "bard_good_start": 3, + "box_3d": 3, + "rosenbrock_good_start": 2, + } + + # ==================================================================================== # Rank report # ==================================================================================== @@ -221,3 +207,42 @@ def test_traceback_report(return_type, benchmark_example): elif return_type == "dataframe": assert report.shape == (n_failed_problems, 2) assert list(report.index.names) == ["algorithm", "problem"] + + +def test_traceback_report_contents(benchmark_example): + problems, _, results = benchmark_example + + as_dict = traceback_report(problems=problems, results=results, return_type="dict") + assert as_dict == { + ("rosenbrock_good_start", "lbfgsb"): "lbfgsb traceback", + ("box_3d", "nm"): "some traceback", + ("rosenbrock_good_start", "nm"): "another traceback", + } + + as_text = traceback_report(problems=problems, results=results, return_type="text") + assert as_text == ["lbfgsb traceback", "some traceback", "another traceback"] + + +def test_traceback_report_with_invalid_return_type_raises(benchmark_example): + problems, _, results = benchmark_example + with pytest.raises(ValueError, match="return_type bla is not supported"): + traceback_report( # ty: ignore[no-matching-overload] + problems=problems, results=results, return_type="bla" + ) + + +def test_reports_with_real_benchmark_results(): + all_problems = get_benchmark_problems("example") + problems = {name: all_problems[name] for name in ["box_3d", "bard_good_start"]} + results = om.run_benchmark( + problems, {"lbfgsb": om.algos.scipy_lbfgsb, "nm": om.algos.scipy_neldermead} + ) + + convergence = convergence_report(problems, results) + assert set(convergence["lbfgsb"]) <= {"success", "failed"} + + ranks = rank_report(problems, results) + assert ranks.shape == (2, 3) + + tracebacks = traceback_report(problems, results) + assert len(tracebacks) == 0 diff --git a/tests/optimagic/benchmarking/test_cartis_roberts.py b/tests/optimagic/benchmarking/test_cartis_roberts.py index c399d89d7..bd667a9aa 100644 --- a/tests/optimagic/benchmarking/test_cartis_roberts.py +++ b/tests/optimagic/benchmarking/test_cartis_roberts.py @@ -2,36 +2,122 @@ import pytest from numpy.testing import assert_array_almost_equal +from optimagic.benchmarking.benchmark_problem import BenchmarkProblem from optimagic.benchmarking.cartis_roberts import ( CARTIS_ROBERTS_PROBLEMS, get_start_points_bdvalues, get_start_points_msqrta, ) +from optimagic.parameters.bounds import Bounds +from optimagic.typing import AggregationLevel +# Sum of squared residuals at the start parameters, taken from the literature. They +# are used to check the implementation of the benchmark functions. +START_FUN = { + "arglale": 700, + "arglble": 5.460944e14, + "argtrig": 32.99641, + "artif": 36.59115, + "arwhdne": 495, + "bdvalues": 1.943417e7, + "bratu_2d": 0.1560738, + "bratu_2d_t": 0.4521311, + "bratu_3d": 4.888529, + "brownale": 2.524757e5, + "broydn_3d": 111, + "cbratu_2d": 0.4822531, + "broydn_bd": 2404, + "chandheq": 6.923365, + "chemrcta": 3.0935, + "chemrctb": 1.446513, + "chnrsbne": 7635.84, + "drcavty1": 0.4513889, + "drcavty2": 0.4513889, + "drcavty3": 0.4513889, + "eigena": 285, + "eigenb": 19, + "flosp2hh": 519, + "flosp2hl": 519, + "flosp2hm": 519, + "flosp2th": 516, + "flosp2tl": 516, + "flosp2tm": 516, + "freurone": 9.95565e4, + "hatfldg": 27, + "hydcar20": 1341.663, + "hydcar6": 704.1073, + "integreq": 0.5730503, + "luksan11": 626.0640, + "luksan12": 3.2160e4, + "luksan13": 6.4352e4, + "luksan14": 2.6880e4, + "luksan15": 2.701585e4, + "luksan16": 1.306848e4, + "luksan17": 1.687370e6, + "luksan21": 99.98751, + "luksan22": 2.487686e4, + "methanb8": 1.043105, + "methanl8": 4345.100, + "morebvne": 3.633100e-4, + "msqrta": 212.7162, + "msqrtb": 205.0753, + "oscigrne": 6.120720e8, + "penalty_1": 1.144806e11, + "penalty_2": 1.591383e6, + "powellse": 41875, + "qr3d": 1.2, + "qr3dbd": 1.2, + "spmsqrt": 74.33542, + "semicn2u": 2.025037e4, + "semicon2": 2.025037e4, + "vardimne": 1.310584e14, + "watsonne": 30, + "yatpsq_1": 2.073643e6, + "yatpsq_2": 1.831687e5, +} -@pytest.mark.parametrize("name, specification", list(CARTIS_ROBERTS_PROBLEMS.items())) -def test_cartis_roberts_function_at_start_x(name, specification): # noqa: ARG001 - _criterion = specification["fun"] - _x = np.array(specification["start_x"]) - assert isinstance(specification["start_x"], list) - _contributions = _criterion(_x) - calculated = _contributions @ _contributions - expected = specification["start_criterion"] - assert np.allclose(calculated, expected) - assert isinstance(specification["start_x"], list) - - -@pytest.mark.parametrize("name, specification", list(CARTIS_ROBERTS_PROBLEMS.items())) -def test_cartis_roberts_function_at_solution_x(name, specification): # noqa: ARG001 - _criterion = specification["fun"] - _x = specification["solution_x"] - if _x is not None: - assert isinstance(_x, list) - _x = np.array(_x) - _contributions = _criterion(_x) - calculated = _contributions @ _contributions - expected = specification["solution_criterion"] - assert np.allclose(calculated, expected, atol=1e-7) + +def test_start_values_are_known_for_all_problems(): + assert set(START_FUN) == set(CARTIS_ROBERTS_PROBLEMS) + + +@pytest.mark.parametrize("name, problem", list(CARTIS_ROBERTS_PROBLEMS.items())) +def test_cartis_roberts_function_at_start_x(name, problem): + assert isinstance(problem, BenchmarkProblem) + assert np.allclose(problem.start_fun, START_FUN[name]) + + +@pytest.mark.parametrize("name, problem", list(CARTIS_ROBERTS_PROBLEMS.items())) +def test_cartis_roberts_function_at_solution_x(name, problem): # noqa: ARG001 + solution = problem.solution + if solution.params is not None: + residuals = problem.function.fun(solution.params) + assert np.allclose(residuals @ residuals, solution.fun, atol=1e-7) + + +@pytest.mark.parametrize("name, problem", list(CARTIS_ROBERTS_PROBLEMS.items())) +def test_cartis_roberts_function_is_least_squares_function(name, problem): # noqa: ARG001 + """Ported from #723, where functions defined via partial were scalar functions.""" + assert problem.function.problem_type == AggregationLevel.LEAST_SQUARES + assert problem.function.fun(problem.start_params).ndim == 1 + + +def test_bounds_of_original_problems_are_only_stored_in_info(): + with_bounds = { + name for name, problem in CARTIS_ROBERTS_PROBLEMS.items() if problem.info + } + assert with_bounds == { + "chemrcta", + "chemrctb", + "eigena", + "qr3d", + "qr3dbd", + "semicon2", + } + for name in with_bounds: + problem = CARTIS_ROBERTS_PROBLEMS[name] + assert isinstance(problem.info["bounds"], Bounds) + assert problem.bounds is None def test_get_start_points_bdvalues(): diff --git a/tests/optimagic/benchmarking/test_get_benchmark_problems.py b/tests/optimagic/benchmarking/test_get_benchmark_problems.py index 134ae4f41..69b61e86d 100644 --- a/tests/optimagic/benchmarking/test_get_benchmark_problems.py +++ b/tests/optimagic/benchmarking/test_get_benchmark_problems.py @@ -1,50 +1,325 @@ +import warnings from itertools import product import numpy as np import pytest +from numpy.testing import assert_array_almost_equal as aaae +from optimagic import minimize +from optimagic.benchmarking.benchmark_problem import BenchmarkProblem from optimagic.benchmarking.get_benchmark_problems import ( - _step_func, + LeastSquaresFunctionWithSteps, get_benchmark_problems, ) +from optimagic.benchmarking.more_wild import Rosenbrock +from optimagic.benchmarking.noise import ( + AdditiveBenchmarkNoise, + CombinedBenchmarkNoise, + MultiplicativeBenchmarkNoise, +) +from optimagic.benchmarking.scaling import LinspaceBenchmarkScaler + +NAMES = ["more_wild", "cartis_roberts", "example", "estimagic"] PARMETRIZATION = [] -for name in ["more_wild", "cartis_roberts", "example", "estimagic"]: - for additive, multiplicative, scaling in product([False, True], repeat=3): - PARMETRIZATION.append((name, additive, multiplicative, scaling)) +for name in NAMES: + for noise, scaling in product([False, True], repeat=2): + PARMETRIZATION.append((name, noise, scaling)) -@pytest.mark.parametrize( - "name, additive_noise, multiplicative_noise, scaling", PARMETRIZATION -) -def test_get_problems(name, additive_noise, multiplicative_noise, scaling): - is_noisy = any((additive_noise, multiplicative_noise)) - problems = get_benchmark_problems( - name=name, - additive_noise=additive_noise, - multiplicative_noise=multiplicative_noise, - scaling=scaling, - ) - first_name = list(problems)[0] - first = problems[first_name] - func = first["inputs"]["fun"] - params = first["inputs"]["params"] +@pytest.mark.parametrize("name, noise, scaling", PARMETRIZATION) +def test_get_problems(name, noise, scaling): + problems = get_benchmark_problems(name=name, noise=noise, scaling=scaling) + first = problems[list(problems)[0]] + func = first.fun + params = first.start_params first_eval = func(params) second_eval = func(params) - if is_noisy: + if noise: assert not np.allclose(first_eval, second_eval) else: assert np.allclose(first_eval, second_eval) for problem in problems.values(): - assert isinstance(problem["inputs"]["params"], np.ndarray) - assert isinstance(problem["solution"]["params"], np.ndarray) + assert isinstance(problem, BenchmarkProblem) + assert isinstance(problem.start_params, np.ndarray) + assert (problem.noise is not None) == noise + assert (problem.scaler is not None) == scaling + + +@pytest.mark.parametrize("name", NAMES) +def test_number_of_problems(name): + expected = {"more_wild": 54, "cartis_roberts": 60, "example": 10, "estimagic": 32} + assert len(get_benchmark_problems(name)) == expected[name] + + +def test_invalid_name_raises(): + with pytest.raises(ValueError, match="Invalid name of a benchmark set: bla"): + get_benchmark_problems("bla") # ty: ignore[invalid-argument-type] + + +@pytest.mark.parametrize("exclude", ["box_3d", ["box_3d"], ("box_3d", "chebyquad_6")]) +def test_exclude(exclude): + problems = get_benchmark_problems("example", exclude=exclude) + excluded = {exclude} if isinstance(exclude, str) else set(exclude) + assert set(problems) == set(get_benchmark_problems("example")) - excluded + + +def test_problems_can_be_filtered_and_merged_like_dicts(): + example = get_benchmark_problems("example") + cartis_roberts = get_benchmark_problems("cartis_roberts") + + small = {name: p for name, p in example.items() if p.n_params <= 3} + assert set(small) == { + "rosenbrock_good_start", + "helical_valley_good_start", + "freudenstein_roth_good_start", + "bard_good_start", + "box_3d", + } + + merged = small | {"arglale": cartis_roberts["arglale"]} + assert len(merged) == 6 + + +def test_shipped_problem_sets_are_not_modified(): + get_benchmark_problems("example", noise=True, scaling=True) + problem = get_benchmark_problems("example")["rosenbrock_good_start"] + assert problem.noise is None + assert problem.scaler is None + aaae(problem.start_params, np.array([-1.2, 1.0])) + + +# ====================================================================================== +# noise and scaling +# ====================================================================================== + + +def test_noise_true_is_additive_noise_with_defaults(): + problems = get_benchmark_problems("example", noise=True) + for problem in problems.values(): + assert problem.noise == AdditiveBenchmarkNoise() + + +def test_custom_noise(): + noise = MultiplicativeBenchmarkNoise(std=0.3) + AdditiveBenchmarkNoise(std=0.1) + problems = get_benchmark_problems("example", noise=noise) + for problem in problems.values(): + assert problem.noise is noise + + +def test_noise_with_invalid_type_raises(): + with pytest.raises(TypeError, match="noise must be a bool or an instance"): + get_benchmark_problems( + "example", + noise={"std": 0.1}, # ty: ignore[invalid-argument-type] + ) + + +def test_scaling_true_is_linspace_scaler_with_defaults(): + problems = get_benchmark_problems("example", scaling=True) + for problem in problems.values(): + assert problem.scaler == LinspaceBenchmarkScaler() + + +def test_custom_scaling(): + scaler = LinspaceBenchmarkScaler(min_scale=1, max_scale=3) + problem = get_benchmark_problems("example", scaling=scaler)["rosenbrock_good_start"] + assert problem.scaler is scaler + aaae(problem.start_params, np.array([-1.2, 3.0])) + assert problem.solution is not None + aaae(np.asarray(problem.solution.params), np.array([1.0, 3.0])) + + +def test_scaling_with_invalid_type_raises(): + with pytest.raises(TypeError, match="scaling must be a bool or an instance"): + get_benchmark_problems( + "example", + scaling="linspace", # ty: ignore[invalid-argument-type] + ) + + +@pytest.mark.parametrize("name", ["more_wild", "cartis_roberts"]) +def test_noise_free_fun_is_scaled_like_start_params(name): + """Ported from #723, where the noise free function ignored the scaling.""" + unscaled = get_benchmark_problems(name) + problems = get_benchmark_problems(name, noise=True, scaling=True) + for problem_name, problem in problems.items(): + assert np.allclose(problem.start_fun, unscaled[problem_name].start_fun) + + +def test_seed_makes_noise_reproducible(): + first = get_benchmark_problems("example", noise=True, seed=0) + second = get_benchmark_problems("example", noise=True, seed=0) + other = get_benchmark_problems("example", noise=True, seed=1) + + for name, problem in first.items(): + x = problem.start_params + assert np.array_equal(problem.fun(x), second[name].fun(x)) + assert not np.array_equal(problem.fun(x), other[name].fun(x)) + + +def test_each_problem_has_its_own_seed(): + problems = get_benchmark_problems("example", noise=True, seed=0) + seeds = [problem.seed for problem in problems.values()] + assert len(set(seeds)) == len(problems) + + +def test_seed_can_be_a_generator(): + first = get_benchmark_problems("example", noise=True, seed=np.random.default_rng(3)) + second = get_benchmark_problems( + "example", noise=True, seed=np.random.default_rng(3) + ) + assert [p.seed for p in first.values()] == [p.seed for p in second.values()] + + +def test_without_seed_problems_have_no_seed(): + problems = get_benchmark_problems("example", noise=True) + assert all(problem.seed is None for problem in problems.values()) + + +# ====================================================================================== +# problems with steps +# ====================================================================================== + + +def test_function_with_steps(): + function = LeastSquaresFunctionWithSteps(Rosenbrock()) + x = np.array([0.0001, 0.0002]) + aaae(function.fun(x), Rosenbrock().fun(np.zeros(2))) + assert not np.allclose(Rosenbrock().fun(x), Rosenbrock().fun(np.zeros(2))) + + assert function.differentiable is False + assert function.supports_n_params(2) + assert not function.supports_n_params(3) + + +def test_estimagic_set_contains_problems_with_steps(): + problems = get_benchmark_problems("estimagic") + with_steps = {name for name in problems if name.endswith("_with_steps")} + assert with_steps == { + "rosenbrock_good_start_with_steps", + "cube_5_with_steps", + "chebyquad_10_with_steps", + } + problem = problems["rosenbrock_good_start_with_steps"] + assert problem.function == LeastSquaresFunctionWithSteps(Rosenbrock()) + assert problem.solution is not None + assert problem.solution.fun == 0 + + +# ====================================================================================== +# problems can be solved +# ====================================================================================== + + +def test_minimize_problem_with_partialled_criterion(): + """Ported from #723, where this problem was treated as scalar problem.""" + problem = get_benchmark_problems("cartis_roberts")["bratu_2d"] + res = minimize( + fun=problem.fun, params=problem.start_params, algorithm="scipy_ls_trf" + ) + assert problem.solution is not None + assert np.allclose(res.fun, problem.solution.fun, atol=1e-8) + + +# ====================================================================================== +# deprecations +# ====================================================================================== + + +def test_additive_noise_is_deprecated(): + with pytest.warns(FutureWarning, match="'additive_noise'"): + problems = get_benchmark_problems("example", additive_noise=True) + assert problems["box_3d"].noise == AdditiveBenchmarkNoise() + + +def test_additive_noise_options_are_deprecated(): + options = {"distribution": "uniform", "std": 0.3, "correlation": 0.2} + with pytest.warns(FutureWarning, match="will be removed in optimagic version 0.7"): + problems = get_benchmark_problems( + "example", additive_noise=True, additive_noise_options=options + ) + assert problems["box_3d"].noise == AdditiveBenchmarkNoise( + distribution="uniform", std=0.3, correlation=0.2 + ) + + +def test_multiplicative_noise_is_deprecated(): + options = {"std": 0.3, "clipping_value": 2.0} + with pytest.warns(FutureWarning, match="'multiplicative_noise'"): + problems = get_benchmark_problems( + "example", multiplicative_noise=True, multiplicative_noise_options=options + ) + assert problems["box_3d"].noise == MultiplicativeBenchmarkNoise( + std=0.3, clipping_value=2.0 + ) + + +def test_deprecated_additive_and_multiplicative_noise_are_combined(): + with pytest.warns(FutureWarning, match="Use the `noise` argument instead"): + problems = get_benchmark_problems( + "example", additive_noise=True, multiplicative_noise=True + ) + noise = problems["box_3d"].noise + assert isinstance(noise, CombinedBenchmarkNoise) + assert noise.components == ( + MultiplicativeBenchmarkNoise(), + AdditiveBenchmarkNoise(), + ) + + +def test_deprecated_noise_options_without_noise_are_ignored(): + with pytest.warns(FutureWarning, match="'additive_noise_options'"): + problems = get_benchmark_problems( + "example", additive_noise=False, additive_noise_options={"std": 0.3} + ) + assert problems["box_3d"].noise is None + + +def test_deprecated_noise_arguments_cannot_be_combined_with_noise(): + with pytest.warns(FutureWarning): + with pytest.raises(ValueError, match="at the same time"): + get_benchmark_problems("example", noise=True, additive_noise=True) + + +def test_scaling_options_are_deprecated(): + options = {"min_scale": 1, "max_scale": 3} + with pytest.warns(FutureWarning, match="`scaling_options`"): + problems = get_benchmark_problems( + "example", scaling=True, scaling_options=options + ) + assert problems["box_3d"].scaler == LinspaceBenchmarkScaler( + min_scale=1, max_scale=3 + ) + + +def test_deprecated_scaling_options_without_scaling_are_ignored(): + with pytest.warns(FutureWarning, match="`scaling_options`"): + problems = get_benchmark_problems( + "example", scaling_options={"min_scale": 1, "max_scale": 3} + ) + assert problems["box_3d"].scaler is None + + +def test_deprecated_scaling_options_cannot_be_combined_with_scaler(): + with pytest.warns(FutureWarning): + with pytest.raises(ValueError, match="at the same time"): + get_benchmark_problems( + "example", + scaling=LinspaceBenchmarkScaler(), + scaling_options={"min_scale": 1}, + ) -def test_step_func(): - p = np.array([0.0001, 0.0002]) - got = _step_func(p, lambda x: x @ x) - assert np.allclose(got, 0) - assert not np.allclose(p @ p, 0) +def test_new_arguments_do_not_warn(): + with warnings.catch_warnings(): + warnings.simplefilter("error") + get_benchmark_problems( + "example", + noise=AdditiveBenchmarkNoise(), + scaling=LinspaceBenchmarkScaler(), + seed=0, + ) diff --git a/tests/optimagic/benchmarking/test_more_wild.py b/tests/optimagic/benchmarking/test_more_wild.py index bb3515574..9fd26bf00 100644 --- a/tests/optimagic/benchmarking/test_more_wild.py +++ b/tests/optimagic/benchmarking/test_more_wild.py @@ -1,29 +1,123 @@ import numpy as np import pytest +from optimagic.benchmarking.benchmark_problem import BenchmarkProblem from optimagic.benchmarking.more_wild import ( MORE_WILD_PROBLEMS, + Chebyquad, + HelicalValley, + LinearFullRank, + Watson, get_start_points_mancino, ) +from optimagic.typing import AggregationLevel +# Sum of squared residuals at the start parameters, taken from the literature. They +# are used to check the implementation of the benchmark functions. +START_FUN = { + "linear_full_rank_good_start": 72, + "linear_full_rank_bad_start": 1125, + "linear_rank_one_good_start": 1.165420e7, + "linear_rank_one_bad_start": 1.168591e9, + "linear_rank_one_zero_columns_rows_good_start": 4.989195e6, + "linear_rank_one_zero_columns_rows_bad_start": 5.009356e8, + "rosenbrock_good_start": 24.2, + "rosenbrock_bad_start": 1.795769e6, + "helical_valley_good_start": 2500, + "helical_valley_bad_start": 10600, + "powell_singular_good_start": 215, + "powell_singular_bad_start": 1.615400e6, + "freudenstein_roth_good_start": 400.5, + "freudenstein_roth_bad_start": 1.545754e8, + "bard_good_start": 41.68170, + "bard_bad_start": 1306.234, + "kowalik_osborne": 5.313172e-3, + "meyer": 1.693608e9, + "watson_6_good_start": 16.43083, + "watson_6_bad_start": 2.323367e6, + "watson_9_good_start": 26.90417, + "watson_9_bad_start": 8.158877e6, + "watson_12_good_start": 73.67821, + "watson_12_bad_start": 2.059384e7, + "box_3d": 1031.154, + "jennrich_sampson": 4171.306, + "brown_dennis_good_start": 7.926693e6, + "brown_dennis_bad_start": 3.081064e11, + "chebyquad_6": 4.642817e-2, + "chebyquad_7": 3.377064e-2, + "chebyquad_8": 3.861770e-2, + "chebyquad_9": 2.888298e-2, + "chebyquad_10": 3.376327e-2, + "chebyquad_11": 2.674060e-2, + "brown_almost_linear": 273.2480, + "osborne_one": 16.17411, + "osborne_two_good_start": 2.093420, + "osborne_two_bad_start": 199.6847, + "bdqrtic_8": 904, + "bdqrtic_10": 1356, + "bdqrtic_11": 1582, + "bdqrtic_12": 1808, + "cube_5": 56.5, + "cube_6": 70.5625, + "cube_8": 98.6875, + "mancino_5_good_start": 2.539084e9, + "mancino_5_bad_start": 6.873795e12, + "mancino_8": 3.367961e9, + "mancino_10": 3.735127e9, + "mancino_12_good_start": 3.991072e9, + "mancino_12_bad_start": 1.130015e13, + "heart_eight_good_start": 9.385672, + "heart_eight_bad_start": 3.365815e10, + "brown_almost_linear_medium": 2.524757e5, +} -@pytest.mark.parametrize("name, specification", list(MORE_WILD_PROBLEMS.items())) -def test_more_wild_function_at_start_x(name, specification): # noqa: ARG001 - _criterion = specification["fun"] - assert isinstance(specification["start_x"], list) - _x = np.array(specification["start_x"]) - _contributions = _criterion(_x) - calculated = _contributions @ _contributions - expected = specification["start_criterion"] - assert np.allclose(calculated, expected) - - if specification.get("solution_x") is not None: - assert isinstance(specification["solution_x"], list) - _x = np.array(specification["solution_x"]) - _contributions = _criterion(_x) - calculated = _contributions @ _contributions - expected = specification["solution_criterion"] - assert np.allclose(calculated, expected, rtol=1e-8, atol=1e-8) + +def test_start_values_are_known_for_all_problems(): + assert set(START_FUN) == set(MORE_WILD_PROBLEMS) + + +@pytest.mark.parametrize("name, problem", list(MORE_WILD_PROBLEMS.items())) +def test_more_wild_function_at_start_x(name, problem): + assert isinstance(problem, BenchmarkProblem) + assert np.allclose(problem.start_fun, START_FUN[name]) + + solution = problem.solution + if solution.params is not None: + residuals = problem.function.fun(solution.params) + assert np.allclose(residuals @ residuals, solution.fun, rtol=1e-8, atol=1e-8) + + +@pytest.mark.parametrize("name, problem", list(MORE_WILD_PROBLEMS.items())) +def test_more_wild_function_is_least_squares_function(name, problem): # noqa: ARG001 + assert problem.function.problem_type == AggregationLevel.LEAST_SQUARES + assert problem.function.fun(problem.start_params).ndim == 1 + + +@pytest.mark.parametrize("name, problem", list(MORE_WILD_PROBLEMS.items())) +def test_more_wild_solutions_are_exact_if_zero(name, problem): # noqa: ARG001 + assert problem.solution.exact == (problem.solution.fun == 0) + + +def test_same_function_is_used_for_good_and_bad_start(): + good = MORE_WILD_PROBLEMS["linear_full_rank_good_start"] + bad = MORE_WILD_PROBLEMS["linear_full_rank_bad_start"] + assert good.function == bad.function == LinearFullRank(dim_out=45) + assert not np.allclose(good.start_params, bad.start_params) + + +def test_supported_numbers_of_params(): + assert HelicalValley().supports_n_params(3) + assert not HelicalValley().supports_n_params(4) + + assert Watson().supports_n_params(2) + assert Watson().supports_n_params(31) + assert not Watson().supports_n_params(32) + + assert LinearFullRank(dim_out=5).supports_n_params(5) + assert not LinearFullRank(dim_out=5).supports_n_params(6) + + assert Chebyquad(dim_out=8).supports_n_params(8) + assert not Chebyquad(dim_out=8).supports_n_params(9) def test_get_start_points_mancino(): diff --git a/tests/optimagic/benchmarking/test_noise.py b/tests/optimagic/benchmarking/test_noise.py new file mode 100644 index 000000000..ad302e531 --- /dev/null +++ b/tests/optimagic/benchmarking/test_noise.py @@ -0,0 +1,138 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal as aaae + +from optimagic.benchmarking.noise import ( + AdditiveBenchmarkNoise, + BenchmarkNoise, + CombinedBenchmarkNoise, + MultiplicativeBenchmarkNoise, + pre_process_noise, +) +from optimagic.utilities import get_rng + +NOISE_CLASSES = [AdditiveBenchmarkNoise, MultiplicativeBenchmarkNoise] + + +@pytest.mark.parametrize("noise_class", NOISE_CLASSES) +def test_noise_has_type_and_shape_of_function_value(noise_class): + noise = noise_class() + params = np.arange(3.0) + + scalar_draw = noise.draw_noise(2.0, params=params, rng=get_rng(0)) + assert isinstance(scalar_draw, float) + + array_draw = noise.draw_noise(np.arange(5.0), params=params, rng=get_rng(0)) + assert isinstance(array_draw, np.ndarray) + assert array_draw.shape == (5,) + + +@pytest.mark.parametrize("noise_class", NOISE_CLASSES) +def test_noise_is_reproducible_with_same_rng(noise_class): + noise = noise_class(distribution="laplace", correlation=0.3) + fval = np.arange(5.0) + first = noise.draw_noise(fval, params=np.ones(2), rng=get_rng(1)) + second = noise.draw_noise(fval, params=np.ones(2), rng=get_rng(1)) + aaae(first, second) + + +def test_additive_noise_has_requested_std(): + noise = AdditiveBenchmarkNoise(std=0.5) + draw = noise.draw_noise(np.zeros(100_000), params=np.ones(2), rng=get_rng(0)) + assert np.allclose(draw.mean(), 0, atol=0.01) + assert np.allclose(draw.std(), 0.5, atol=0.01) + + +def test_multiplicative_noise_scales_with_function_value(): + noise = MultiplicativeBenchmarkNoise(std=0.1, clipping_value=1.0) + fval = np.concatenate([np.full(100_000, 10.0), np.full(100_000, -50.0)]) + draw = noise.draw_noise(fval, params=np.ones(2), rng=get_rng(0)) + assert np.allclose(draw[:100_000].std(), 1.0, atol=0.02) + assert np.allclose(draw[100_000:].std(), 5.0, atol=0.1) + + +def test_multiplicative_noise_is_not_zero_at_zero(): + noise = MultiplicativeBenchmarkNoise(std=0.1, clipping_value=2.0) + draw = noise.draw_noise(np.zeros(100_000), params=np.ones(2), rng=get_rng(0)) + assert np.allclose(draw.std(), 0.2, atol=0.01) + + scalar_draw = noise.draw_noise(0.0, params=np.ones(2), rng=get_rng(0)) + assert scalar_draw != 0 + + +def test_adding_noise_combines_the_components(): + additive = AdditiveBenchmarkNoise(std=0.3) + multiplicative = MultiplicativeBenchmarkNoise(std=0.2) + combined = additive + multiplicative + + assert isinstance(combined, CombinedBenchmarkNoise) + assert combined.components == (additive, multiplicative) + + fval = np.arange(4.0) + params = np.ones(2) + rng = get_rng(5) + expected = additive.draw_noise(fval, params, rng) + multiplicative.draw_noise( + fval, params, rng + ) + aaae(combined.draw_noise(fval, params, get_rng(5)), expected) + + +def test_adding_combined_noise_keeps_a_flat_list_of_components(): + first = AdditiveBenchmarkNoise(std=0.3) + second = MultiplicativeBenchmarkNoise(std=0.2) + third = AdditiveBenchmarkNoise(distribution="uniform") + + assert ((first + second) + third).components == (first, second, third) + assert (first + (second + third)).components == (first, second, third) + + +def test_combined_noise_without_components_raises(): + with pytest.raises(ValueError, match="at least one source of noise"): + CombinedBenchmarkNoise(components=()) + + +def test_adding_something_else_to_noise_raises(): + with pytest.raises(TypeError): + AdditiveBenchmarkNoise() + 1 # ty: ignore[unsupported-operator] + + +def test_custom_noise_can_depend_on_params(): + class Wiggle(BenchmarkNoise): + def draw_noise(self, fval, params, rng): # noqa: ARG002 + return 0.1 * np.sin(params.sum()) + 0 * fval + + combined = Wiggle() + AdditiveBenchmarkNoise(std=0.0) + got = combined.draw_noise(3.0, params=np.array([0.5, 0.5]), rng=get_rng(0)) + assert np.allclose(got, 0.1 * np.sin(1.0)) + + +@pytest.mark.parametrize("noise_class", NOISE_CLASSES) +@pytest.mark.parametrize( + "kwargs, match", + [ + ({"distribution": "cauchy"}, "Invalid distribution"), + ({"std": -1.0}, "std must be non-negative"), + ({"correlation": -0.1}, "correlation must be between 0 and 1"), + ({"correlation": 1.1}, "correlation must be between 0 and 1"), + ], +) +def test_invalid_noise_arguments_raise(noise_class, kwargs, match): + with pytest.raises(ValueError, match=match): + noise_class(**kwargs) + + +def test_negative_clipping_value_raises(): + with pytest.raises(ValueError, match="clipping_value must be non-negative"): + MultiplicativeBenchmarkNoise(clipping_value=-1.0) + + +def test_pre_process_noise(): + noise = MultiplicativeBenchmarkNoise() + assert pre_process_noise(noise) is noise + assert pre_process_noise(False) is None + assert pre_process_noise(True) == AdditiveBenchmarkNoise() + + +def test_pre_process_noise_with_invalid_type_raises(): + with pytest.raises(TypeError, match="noise must be a bool or an instance"): + pre_process_noise("normal") # ty: ignore[invalid-argument-type] diff --git a/tests/optimagic/benchmarking/test_noise_distributions.py b/tests/optimagic/benchmarking/test_noise_distributions.py index f3d549a36..6204d216f 100644 --- a/tests/optimagic/benchmarking/test_noise_distributions.py +++ b/tests/optimagic/benchmarking/test_noise_distributions.py @@ -2,19 +2,17 @@ import pandas as pd import pytest -from optimagic.benchmarking.get_benchmark_problems import _sample_from_distribution +from optimagic.benchmarking.noise import sample_from_distribution from optimagic.benchmarking.noise_distributions import NOISE_DISTRIBUTIONS from optimagic.utilities import get_rng @pytest.mark.parametrize("distribution", NOISE_DISTRIBUTIONS) def test_sample_from_distribution(distribution): - mean = 0.33 std = 0.55 correlation = 0.44 - sample = _sample_from_distribution( + sample = sample_from_distribution( distribution=distribution, - mean=mean, std=std, size=(100_000, 5), correlation=correlation, @@ -25,6 +23,6 @@ def test_sample_from_distribution(distribution): corrmat = pd.DataFrame(sample).corr().to_numpy().round(2) calculated_avgcorr = corrmat[~np.eye(len(corrmat)).astype(bool)].mean() - assert np.allclose(calculated_mean, mean, atol=0.001) + assert np.allclose(calculated_mean, 0, atol=0.001) assert np.allclose(calculated_std, std, atol=0.001) assert np.allclose(calculated_avgcorr, correlation, atol=0.001) diff --git a/tests/optimagic/benchmarking/test_process_benchmark_results.py b/tests/optimagic/benchmarking/test_process_benchmark_results.py new file mode 100644 index 000000000..2db9da9ce --- /dev/null +++ b/tests/optimagic/benchmarking/test_process_benchmark_results.py @@ -0,0 +1,222 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal as aaae + +import optimagic as om +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + BenchmarkSolution, + ScalarBenchmarkFunction, +) +from optimagic.benchmarking.benchmark_result import BenchmarkResult +from optimagic.benchmarking.process_benchmark_results import ( + get_reference_solutions, + process_benchmark_results, +) + + +class ShiftedSphere(ScalarBenchmarkFunction): + """Sphere with minimum 1 at [1, 1, ...].""" + + def fun(self, x): + return float((x - 1) @ (x - 1)) + 1.0 + + +def _problem(solution): + return BenchmarkProblem( + function=ShiftedSphere(), start_params=np.array([3.0, 1.0]), solution=solution + ) + + +def _result(params_history, traceback=None): + function = ShiftedSphere() + params_history = np.array(params_history, dtype=np.float64) + n_evals = len(params_history) + return BenchmarkResult( + params_history=params_history, + fun_history=np.array([function.fun(p) for p in params_history]), + time_history=np.arange(n_evals, dtype=np.float64), + batches_history=np.arange(n_evals), + optimize_result=None, + traceback=traceback, + ) + + +@pytest.fixture +def results(): + return { + # gets close to the solution + ("sphere", "good"): _result([[3.0, 1.0], [2.0, 1.0], [1.001, 1.0]]), + # only gets half way + ("sphere", "bad"): _result([[3.0, 1.0], [2.5, 1.0], [2.0, 1.0]]), + } + + +# ====================================================================================== +# get_reference_solutions +# ====================================================================================== + + +def test_reference_is_stored_solution_if_exact(results): + solution = BenchmarkSolution(fun=1.0, params=np.ones(2), exact=True) + references = get_reference_solutions({"sphere": _problem(solution)}, results) + assert references == {"sphere": solution} + + +def test_reference_is_exact_solution_even_if_a_lower_value_was_found(results): + solution = BenchmarkSolution(fun=1.5, params=np.ones(2), exact=True) + references = get_reference_solutions({"sphere": _problem(solution)}, results) + assert references["sphere"] is solution + + +def test_reference_is_best_found_value_without_stored_solution(results): + references = get_reference_solutions({"sphere": _problem(None)}, results) + reference = references["sphere"] + assert np.allclose(reference.fun, 1.0 + 1e-6) + assert reference.params is None + assert reference.exact is False + + +def test_reference_is_best_known_solution_if_nothing_better_was_found(results): + solution = BenchmarkSolution(fun=1.0, params=np.ones(2)) + references = get_reference_solutions({"sphere": _problem(solution)}, results) + assert references["sphere"] is solution + + +def test_best_known_solution_is_replaced_if_something_better_was_found(results): + solution = BenchmarkSolution(fun=1.2, params=np.array([1.4, 1.0])) + references = get_reference_solutions({"sphere": _problem(solution)}, results) + reference = references["sphere"] + assert np.allclose(reference.fun, 1.0 + 1e-6) + aaae(np.asarray(reference.params), np.array([1.001, 1.0])) + assert reference.exact is False + + +def test_best_known_solution_without_params_stays_without_params(results): + solution = BenchmarkSolution(fun=1.2, params=None) + references = get_reference_solutions({"sphere": _problem(solution)}, results) + assert np.allclose(references["sphere"].fun, 1.0 + 1e-6) + assert references["sphere"].params is None + + +def test_references_only_contain_problems_with_results(results): + problems = {"sphere": _problem(None), "unused": _problem(None)} + assert set(get_reference_solutions(problems, results)) == {"sphere"} + + +def test_nan_function_values_are_ignored_for_references(): + result = _result([[3.0, 1.0], [2.0, 1.0]]) + fun_history = result.fun_history.copy() + fun_history[1] = np.nan + result = BenchmarkResult( + params_history=result.params_history, + fun_history=fun_history, + time_history=result.time_history, + batches_history=result.batches_history, + optimize_result=None, + ) + references = get_reference_solutions( + {"sphere": _problem(None)}, {("sphere", "a"): result} + ) + assert references["sphere"].fun == 5.0 + + +# ====================================================================================== +# process_benchmark_results +# ====================================================================================== + + +def test_process_benchmark_results_with_exact_solution(results): + solution = BenchmarkSolution(fun=1.0, params=np.ones(2), exact=True) + df, converged = process_benchmark_results( + {"sphere": _problem(solution)}, + results, + stopping_criterion="y", + y_precision=1e-4, + ) + + assert converged.loc["sphere"].to_dict() == {"good": True, "bad": False} + + good = df.query("algorithm == 'good'") + aaae(good["criterion"], [5.0, 2.0, 1.000001]) + aaae(good["criterion_normalized"], [1.0, 0.25, 2.5e-7]) + aaae(good["parameter_distance"], [2.0, 1.0, 0.001]) + aaae(good["parameter_distance_normalized"], [1.0, 0.5, 0.0005]) + assert good["n_evaluations"].tolist() == [0, 1, 2] + + +def test_process_benchmark_results_without_solution(results): + df, converged = process_benchmark_results( + {"sphere": _problem(None)}, results, stopping_criterion="y" + ) + + # the best optimizer defines the solution and therefore always converges + assert converged.loc["sphere"].to_dict() == {"good": True, "bad": False} + + good = df.query("algorithm == 'good'") + aaae(good["criterion_normalized"], [1.0, 0.25, 0.0], decimal=5) + assert good["parameter_distance"].isna().all() + + +@pytest.mark.parametrize("stopping_criterion", ["x", "x_and_y"]) +def test_convergence_in_params_is_impossible_without_solution_params( + results, stopping_criterion +): + _, converged = process_benchmark_results( + {"sphere": _problem(None)}, results, stopping_criterion=stopping_criterion + ) + assert converged.loc["sphere"].to_dict() == {"good": False, "bad": False} + + +def test_x_or_y_works_without_solution_params(results): + _, converged = process_benchmark_results( + {"sphere": _problem(None)}, results, stopping_criterion="x_or_y" + ) + assert converged.loc["sphere"].to_dict() == {"good": True, "bad": False} + + +def test_values_below_an_exact_solution_are_clipped(results): + solution = BenchmarkSolution(fun=1.5, params=np.ones(2), exact=True) + df, _ = process_benchmark_results( + {"sphere": _problem(solution)}, results, stopping_criterion=None + ) + good = df.query("algorithm == 'good'") + aaae(good["criterion"], [5.0, 2.0, 1.5]) + assert (good["criterion_normalized"] >= 0).all() + + +def test_histories_are_cut_after_convergence(): + results = { + ("sphere", "a"): _result([[3.0, 1.0], [1.0, 1.0], [1.5, 1.0], [1.0, 1.0]]) + } + solution = BenchmarkSolution(fun=1.0, params=np.ones(2), exact=True) + df, converged = process_benchmark_results( + {"sphere": _problem(solution)}, results, stopping_criterion="y" + ) + assert converged.loc["sphere", "a"] + assert len(df) == 2 + + +def test_without_stopping_criterion_nothing_converges(results): + solution = BenchmarkSolution(fun=1.0, params=np.ones(2), exact=True) + df, converged = process_benchmark_results( + {"sphere": _problem(solution)}, results, stopping_criterion=None + ) + assert converged.loc["sphere"].to_dict() == {"good": False, "bad": False} + assert len(df) == 6 + + +def test_problem_without_solution_in_plots_and_reports(): + problem = BenchmarkProblem(function=ShiftedSphere(), start_params=np.full(3, 4.0)) + problems = {"sphere": problem} + results = om.run_benchmark( + problems, + {"lbfgsb": om.algos.scipy_lbfgsb, "nm": om.algos.scipy_neldermead}, + max_criterion_evaluations=100, + ) + + report = om.convergence_report(problems, results) + assert "success" in set(report.loc["sphere"]) + + om.profile_plot(problems, results) + om.convergence_plot(problems, results, normalize_distance=False) diff --git a/tests/optimagic/benchmarking/test_run_benchmark.py b/tests/optimagic/benchmarking/test_run_benchmark.py index d501dd17e..607f9cf5b 100644 --- a/tests/optimagic/benchmarking/test_run_benchmark.py +++ b/tests/optimagic/benchmarking/test_run_benchmark.py @@ -1,27 +1,243 @@ +import warnings +from dataclasses import replace + +import numpy as np import pytest +from numpy.testing import assert_array_almost_equal as aaae +import optimagic as om from optimagic import get_benchmark_problems -from optimagic.benchmarking.run_benchmark import run_benchmark +from optimagic.benchmarking.benchmark_problem import ( + BenchmarkProblem, + LeastSquaresBenchmarkFunction, + ScalarBenchmarkFunction, + aggregate_function_value, +) +from optimagic.benchmarking.benchmark_result import BenchmarkResult +from optimagic.benchmarking.run_benchmark import ( + _process_one_result, + _process_optimize_options, + _set_benchmark_defaults, + run_benchmark, +) +from optimagic.optimization.optimize_options import OptimizeOptions +from optimagic.optimization.optimize_result import OptimizeResult +from optimagic.typing import AggregationLevel + + +def _get_two_problems(name="more_wild"): + all_problems = get_benchmark_problems(name) + return {name: all_problems[name] for name in list(all_problems)[:2]} + + +# ====================================================================================== +# run_benchmark +# ====================================================================================== + + +def test_run_benchmark_with_all_types_of_options(): + optimize_options = { + "name": "scipy_lbfgsb", + "class": om.algos.scipy_lbfgsb, + "instance": om.algos.scipy_lbfgsb(convergence_ftol_rel=1e-10), + "options": OptimizeOptions( + algorithm="scipy_lbfgsb", algo_options={"stopping_maxfun": 30} + ), + } + + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + result = run_benchmark( + problems=_get_two_problems(), + optimize_options=optimize_options, + error_handling="raise", + ) + + expected_keys = { + (problem, options) + for problem in ["linear_full_rank_good_start", "linear_full_rank_bad_start"] + for options in optimize_options + } + assert set(result) == expected_keys + for res in result.values(): + assert isinstance(res, BenchmarkResult) + assert isinstance(res.optimize_result, OptimizeResult) + assert res.traceback is None + n_evals = len(res.fun_history) + assert res.params_history.shape == (n_evals, 9) + assert res.time_history.shape == (n_evals,) + assert res.batches_history.shape == (n_evals,) -def test_run_benchmark_dict_options(): + +def test_run_benchmark_history_starts_at_start_params(): + problems = _get_two_problems("example") + result = run_benchmark(problems, {"nm": om.algos.scipy_neldermead}) + for (problem_name, _), res in result.items(): + problem = problems[problem_name] + aaae(res.params_history[0], problem.start_params) + assert np.allclose(res.fun_history[0], problem.start_fun) + + +def test_run_benchmark_failing(): all_problems = get_benchmark_problems("more_wild") - first_two_names = list(all_problems)[:2] - first_two = {name: all_problems[name] for name in first_two_names} + failing_name = "jennrich_sampson" + failing = {failing_name: all_problems[failing_name]} + + with pytest.warns(): + result = run_benchmark( + problems=failing, optimize_options={"lbfgsb": "scipy_lbfgsb"} + ) + + res = result[(failing_name, "lbfgsb")] + assert res.optimize_result is None + assert isinstance(res.traceback, str) + aaae(res.params_history, failing[failing_name].start_params.reshape(1, -1)) + aaae(res.fun_history, [failing[failing_name].start_fun]) + assert res.time_history[0] == np.inf + + +def test_run_benchmark_noisy_scaled_problem(): + """Ported from #723, where the first function value was calculated wrongly.""" + all_problems = get_benchmark_problems("example", noise=True, scaling=True, seed=0) + name = "rosenbrock_good_start" + problems = {name: all_problems[name]} + + result = run_benchmark( + problems=problems, + optimize_options={"nm": "scipy_neldermead"}, + max_criterion_evaluations=20, + ) + + res = result[(name, "nm")] + assert np.allclose(res.fun_history[0], 24.2) + # the history contains function values without noise + noise_free_fun = problems[name].noise_free_fun + expected = [ + aggregate_function_value(noise_free_fun(p), AggregationLevel.LEAST_SQUARES) + for p in res.params_history + ] + aaae(res.fun_history, expected) + + +def test_all_optimizers_see_the_same_noise(): + problem = get_benchmark_problems("example", noise=True, seed=5)["box_3d"] + options = { + "first": om.algos.scipy_neldermead, + "second": om.algos.scipy_neldermead, + } + result = run_benchmark({"box_3d": problem}, options, max_criterion_evaluations=30) + aaae( + result[("box_3d", "first")].params_history, + result[("box_3d", "second")].params_history, + ) + + +def test_run_benchmark_passes_bounds(): + class LogSum(ScalarBenchmarkFunction): + def fun(self, x): + return float(x @ x - np.log(x).sum()) + + def bounds(self, n_params): + return om.Bounds(lower=np.full(n_params, 1e-8)) + + problem = BenchmarkProblem(function=LogSum(), start_params=np.array([3.0, 0.5])) + result = run_benchmark( + {"log_sum": problem}, {"lbfgsb": om.algos.scipy_lbfgsb}, error_handling="raise" + ) + res = result[("log_sum", "lbfgsb")] + assert (res.params_history > 0).all() + assert res.optimize_result is not None + aaae(res.optimize_result.params, np.sqrt([0.5, 0.5]), decimal=4) + + +def test_run_benchmark_uses_closed_form_derivatives(): + n_jac_calls = [] + + class Residuals(LeastSquaresBenchmarkFunction): + def fun(self, x): + return x - 1 + + def jac(self, x): + n_jac_calls.append(1) + return np.eye(len(x)) + + problem = BenchmarkProblem(function=Residuals(), start_params=np.zeros(3)) + result = run_benchmark( + {"residuals": problem}, + {"lbfgsb": om.algos.scipy_lbfgsb, "ls_lm": om.algos.scipy_ls_lm}, + error_handling="raise", + batch_evaluator="threading", + ) + + assert len(n_jac_calls) > 0 + for res in result.values(): + # derivative evaluations are not part of the histories + assert not np.isnan(res.fun_history).any() + assert len(res.fun_history) == len(res.params_history) + assert res.optimize_result is not None + aaae(res.optimize_result.params, np.ones(3), decimal=5) + + +def test_process_one_result_without_history_raises(): + problem = get_benchmark_problems("example")["box_3d"] + res = om.minimize( + fun=problem.fun, params=problem.start_params, algorithm="scipy_lbfgsb" + ) + with pytest.raises(ValueError, match="collect a history"): + _process_one_result(replace(res, history=None), problem=problem) + + +# ====================================================================================== +# deprecated optimize_options +# ====================================================================================== + +def test_list_of_algorithms_is_deprecated(): + msg = "Passing a list of algorithms as `optimize_options`" + with pytest.warns(FutureWarning, match=msg): + result = run_benchmark( + problems=_get_two_problems("example"), + optimize_options=["scipy_lbfgsb", om.algos.scipy_neldermead], + ) + + # as in previous versions, algorithm classes are named after the class + expected_keys = { + ("helical_valley_good_start", "scipy_lbfgsb"), + ("rosenbrock_good_start", "scipy_lbfgsb"), + ("helical_valley_good_start", "ScipyNelderMead"), + ("rosenbrock_good_start", "ScipyNelderMead"), + } + assert set(result) == expected_keys + + +def test_list_of_configured_algorithms_uses_algorithm_names(): + with pytest.warns(FutureWarning): + processed = _process_optimize_options( + [om.algos.scipy_lbfgsb(stopping_maxfun=3)], + max_evals=10, + disable_convergence=True, + ) + assert list(processed) == ["scipy_lbfgsb"] + assert processed["scipy_lbfgsb"]["algorithm"].stopping_maxfun == 3 + + +def test_dict_options_are_deprecated(): optimize_options = { "default_lbfgsb": "scipy_lbfgsb", "tuned_lbfgsb": { "algorithm": "scipy_lbfgsb", - "algo_options": {"convergence.relative_criterion_tolerance": 1e-10}, + "algo_options": {"convergence_ftol_rel": 1e-10}, }, } - result = run_benchmark( - problems=first_two, - optimize_options=optimize_options, - error_handling="raise", - ) + msg = "dictionaries with keyword arguments for `minimize` is deprecated" + with pytest.warns(FutureWarning, match=msg): + result = run_benchmark( + problems=_get_two_problems(), + optimize_options=optimize_options, + error_handling="raise", + ) expected_keys = { ("linear_full_rank_good_start", "default_lbfgsb"), @@ -32,35 +248,145 @@ def test_run_benchmark_dict_options(): assert set(result) == expected_keys -def test_run_benchmark_list_options(): - all_problems = get_benchmark_problems("example") - first_two_names = list(all_problems)[:2] - first_two = {name: all_problems[name] for name in first_two_names} - optimize_options = ["scipy_lbfgsb", "scipy_neldermead"] +def test_deprecation_messages_name_the_version_of_removal(): + with pytest.warns(FutureWarning, match="removed in optimagic version 0.7.0"): + _process_optimize_options( + ["scipy_lbfgsb"], max_evals=10, disable_convergence=True + ) + with pytest.warns(FutureWarning, match="removed in optimagic version 0.7.0"): + _process_optimize_options( + {"a": {"algorithm": "scipy_lbfgsb"}}, + max_evals=10, + disable_convergence=True, + ) - result = run_benchmark( - problems=first_two, - optimize_options=optimize_options, + +# ====================================================================================== +# processing of optimize_options +# ====================================================================================== + + +def test_process_optimize_options_returns_configured_algorithms(): + processed = _process_optimize_options( + {"a": "scipy_lbfgsb", "b": om.algos.scipy_neldermead}, + max_evals=50, + disable_convergence=True, ) + assert isinstance(processed["a"]["algorithm"], om.algos.scipy_lbfgsb) + assert isinstance(processed["b"]["algorithm"], om.algos.scipy_neldermead) + assert processed["a"]["algorithm"].stopping_maxfun == 50 + assert processed["a"]["algorithm"].convergence_ftol_rel == 1e-14 - expected_keys = { - ("helical_valley_good_start", "scipy_lbfgsb"), - ("rosenbrock_good_start", "scipy_lbfgsb"), - ("helical_valley_good_start", "scipy_neldermead"), - ("rosenbrock_good_start", "scipy_neldermead"), - } - assert set(result) == expected_keys +def test_process_optimize_options_passes_on_optimize_options(): + options = OptimizeOptions( + algorithm=om.algos.scipy_lbfgsb, + algo_options={"stopping_maxfun": 7}, + numdiff_options=om.NumdiffOptions(method="central"), + scaling=True, + ) + processed = _process_optimize_options( + {"a": options}, max_evals=50, disable_convergence=False + )["a"] + assert processed["algo_options"] == {"stopping_maxfun": 7} + assert processed["numdiff_options"] == om.NumdiffOptions(method="central") + assert processed["scaling"] is True + assert processed["multistart"] is False -def test_run_benchmark_failing(): - all_problems = get_benchmark_problems("more_wild") - failing_name = "jennrich_sampson" - failing = {failing_name: all_problems[failing_name]} - optimize_options = ["scipy_lbfgsb"] +def test_process_optimize_options_with_deprecated_dict_keeps_other_entries(): + with pytest.warns(FutureWarning): + processed = _process_optimize_options( + {"a": {"algorithm": "scipy_lbfgsb", "scaling": True, "skip_checks": True}}, + max_evals=50, + disable_convergence=False, + )["a"] + assert processed["scaling"] is True + assert processed["skip_checks"] is True + + +def test_dict_options_without_algorithm_raise(): + with pytest.warns(FutureWarning): + with pytest.raises(ValueError, match="do not contain an algorithm"): + _process_optimize_options( + {"a": {"algo_options": {}}}, max_evals=50, disable_convergence=False + ) + + +def test_invalid_algorithm_name_raises(): + with pytest.raises(ValueError, match="Invalid algorithm: scipy_bla"): + _process_optimize_options( + {"a": "scipy_bla"}, max_evals=50, disable_convergence=False + ) + + +def test_invalid_type_of_options_raises(): + with pytest.raises(TypeError, match="algorithm must be the name"): + _process_optimize_options( + {"a": 1}, # ty: ignore[invalid-argument-type] + max_evals=50, + disable_convergence=False, + ) + + +def test_benchmark_defaults_are_set(): + algorithm = _set_benchmark_defaults( + om.algos.scipy_lbfgsb(), max_evals=20, disable_convergence=True + ) + assert algorithm.stopping_maxfun == 20 + assert algorithm.stopping_maxiter == 20 + assert algorithm.convergence_ftol_rel == 1e-14 + + algorithm = _set_benchmark_defaults( + om.algos.scipy_trust_constr(), max_evals=20, disable_convergence=True + ) + assert algorithm.convergence_xtol_rel == 1e-14 + + +def test_benchmark_defaults_can_be_switched_off(): + default = om.algos.scipy_lbfgsb() + algorithm = _set_benchmark_defaults( + default, max_evals=None, disable_convergence=False + ) + assert algorithm == default + + +def test_benchmark_defaults_do_not_overwrite_user_options(): + configured = om.algos.scipy_lbfgsb(stopping_maxfun=5, convergence_ftol_rel=1e-3) + algorithm = _set_benchmark_defaults( + configured, max_evals=20, disable_convergence=True + ) + assert algorithm.stopping_maxfun == 5 + assert algorithm.convergence_ftol_rel == 1e-3 + assert algorithm.stopping_maxiter == 20 + + +def test_benchmark_defaults_skip_options_an_algorithm_does_not_have(): + # scipy_neldermead has no gradient based convergence criterion + algorithm = _set_benchmark_defaults( + om.algos.scipy_neldermead(), max_evals=20, disable_convergence=True + ) + assert algorithm.stopping_maxfun == 20 + assert not hasattr(algorithm, "convergence_gtol_rel") + + +def test_configured_algorithm_limits_number_of_evaluations(): + problems = _get_two_problems("example") + result = run_benchmark( + problems, {"nm": om.algos.scipy_neldermead(stopping_maxfun=15)} + ) + for res in result.values(): + assert len(res.fun_history) <= 16 + + +# ====================================================================================== +# _process_one_result +# ====================================================================================== - with pytest.warns(): - result = run_benchmark(problems=failing, optimize_options=optimize_options) - key = (failing_name, "scipy_lbfgsb") - assert isinstance(result[key]["solution"], str) +def test_process_one_result_with_traceback(): + problem = get_benchmark_problems("example")["box_3d"] + res = _process_one_result("some traceback", problem=problem) + assert res.traceback == "some traceback" + assert res.optimize_result is None + assert res.batches_history.tolist() == [0] diff --git a/tests/optimagic/benchmarking/test_scaling.py b/tests/optimagic/benchmarking/test_scaling.py new file mode 100644 index 000000000..2876af667 --- /dev/null +++ b/tests/optimagic/benchmarking/test_scaling.py @@ -0,0 +1,47 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal as aaae + +from optimagic.benchmarking.scaling import ( + LinspaceBenchmarkScaler, + pre_process_scaling, +) + + +def test_linspace_scaler_scale(): + scaler = LinspaceBenchmarkScaler(min_scale=1, max_scale=3) + aaae(scaler.scale(np.array([1.0, 1.0, 1.0])), np.array([1.0, 2.0, 3.0])) + + +def test_linspace_scaler_unscale_inverts_scale(): + scaler = LinspaceBenchmarkScaler() + params = np.array([-1.0, 0.5, 2.0, 7.0]) + aaae(scaler.unscale(scaler.scale(params)), params) + + +def test_linspace_scaler_keeps_infinite_values(): + scaler = LinspaceBenchmarkScaler() + bounds = np.array([-np.inf, np.inf, 1.0]) + scaled = scaler.scale(bounds) + assert scaled[0] == -np.inf + assert scaled[1] == np.inf + + +@pytest.mark.parametrize( + "kwargs", [{"min_scale": 0}, {"max_scale": -1.0}, {"min_scale": -1, "max_scale": 0}] +) +def test_linspace_scaler_with_non_positive_scale_raises(kwargs): + with pytest.raises(ValueError, match="min_scale and max_scale must be positive"): + LinspaceBenchmarkScaler(**kwargs) + + +def test_pre_process_scaling(): + scaler = LinspaceBenchmarkScaler(min_scale=2, max_scale=4) + assert pre_process_scaling(scaler) is scaler + assert pre_process_scaling(False) is None + assert pre_process_scaling(True) == LinspaceBenchmarkScaler() + + +def test_pre_process_scaling_with_invalid_type_raises(): + with pytest.raises(TypeError, match="scaling must be a bool or an instance"): + pre_process_scaling({"min_scale": 1}) # ty: ignore[invalid-argument-type] diff --git a/tests/optimagic/optimization/test_optimize_options.py b/tests/optimagic/optimization/test_optimize_options.py new file mode 100644 index 000000000..4ccf073ce --- /dev/null +++ b/tests/optimagic/optimization/test_optimize_options.py @@ -0,0 +1,49 @@ +import pytest + +import optimagic as om +from optimagic.optimization.optimize_options import OptimizeOptions + + +@pytest.mark.parametrize( + "algorithm", + ["scipy_lbfgsb", om.algos.scipy_lbfgsb, om.algos.scipy_lbfgsb(stopping_maxfun=5)], +) +def test_optimize_options_with_valid_algorithms(algorithm): + options = OptimizeOptions(algorithm=algorithm) + assert options.algorithm is algorithm + assert options.algo_options is None + assert options.numdiff_options is None + assert options.scaling is False + assert options.multistart is False + + +def test_optimize_options_with_all_fields(): + options = OptimizeOptions( + algorithm="scipy_lbfgsb", + algo_options={"stopping_maxfun": 10}, + numdiff_options=om.NumdiffOptions(method="central"), + scaling=om.ScalingOptions(method="bounds"), + multistart=om.MultistartOptions(n_samples=10), + ) + assert options.algo_options == {"stopping_maxfun": 10} + assert options.numdiff_options == om.NumdiffOptions(method="central") + assert options.scaling == om.ScalingOptions(method="bounds") + assert options.multistart == om.MultistartOptions(n_samples=10) + + +def test_optimize_options_are_exported(): + assert om.OptimizeOptions is OptimizeOptions + + +@pytest.mark.parametrize("algorithm", [1, None, {"algorithm": "scipy_lbfgsb"}, dict]) +def test_optimize_options_with_invalid_algorithm_raise(algorithm): + with pytest.raises(TypeError, match="algorithm must be the name of an algorithm"): + OptimizeOptions(algorithm=algorithm) + + +def test_optimize_options_with_invalid_algo_options_raise(): + with pytest.raises(TypeError, match="algo_options must be a dict or None"): + OptimizeOptions( + algorithm="scipy_lbfgsb", + algo_options=[("stopping_maxfun", 10)], # ty: ignore[invalid-argument-type] + ) diff --git a/tests/optimagic/visualization/test_convergence_plot.py b/tests/optimagic/visualization/test_convergence_plot.py index 28290ef68..6b84e66d6 100644 --- a/tests/optimagic/visualization/test_convergence_plot.py +++ b/tests/optimagic/visualization/test_convergence_plot.py @@ -1,7 +1,10 @@ import pytest -from optimagic import get_benchmark_problems -from optimagic.benchmarking.process_benchmark_results import process_benchmark_results +from optimagic import algos, get_benchmark_problems +from optimagic.benchmarking.process_benchmark_results import ( + get_reference_solutions, + process_benchmark_results, +) from optimagic.benchmarking.run_benchmark import run_benchmark from optimagic.visualization.convergence_plot import ( _check_only_allowed_subset_provided, @@ -13,14 +16,7 @@ @pytest.fixture() def benchmark_results(): problems = get_benchmark_problems("example") - stop_after_10 = { - "stopping_max_criterion_evaluations": 10, - "stopping_max_iterations": 10, - } - optimizers = { - "lbfgsb": {"algorithm": "scipy_lbfgsb", "algo_options": stop_after_10}, - "nm": {"algorithm": "scipy_neldermead", "algo_options": stop_after_10}, - } + optimizers = {"lbfgsb": algos.scipy_lbfgsb, "nm": algos.scipy_neldermead} results = run_benchmark( problems, optimizers, @@ -75,13 +71,13 @@ def test_convergence_plot_options(options, grid, benchmark_results, close_mpl_fi def test_convergence_plot_stopping_criterion_none(benchmark_results): problems, results = benchmark_results - with pytest.raises(UnboundLocalError): - convergence_plot( - problems=problems, - results=results, - problem_subset=["bard_good_start"], - stopping_criterion=None, # ty:ignore[invalid-argument-type] - ) + # Without a stopping criterion, the lines are not cut where an optimizer converged. + convergence_plot( + problems=problems, + results=results, + problem_subset=["bard_good_start"], + stopping_criterion=None, # ty:ignore[invalid-argument-type] + ) def test_check_only_allowed_subset_provided_none(): @@ -109,7 +105,7 @@ def test_extract_convergence_plot_lines(benchmark_results): lines_list, titles = _extract_convergence_plot_lines( df=df, - problems=problems, + references=get_reference_solutions(problems, results), runtime_measure="n_evaluations", outcome="criterion_normalized", palette=["red", "green", "blue"], diff --git a/tests/optimagic/visualization/test_deviation_plot.py b/tests/optimagic/visualization/test_deviation_plot.py index 41ec73907..beab5016b 100644 --- a/tests/optimagic/visualization/test_deviation_plot.py +++ b/tests/optimagic/visualization/test_deviation_plot.py @@ -1,6 +1,6 @@ import pytest -from optimagic import get_benchmark_problems +from optimagic import algos, get_benchmark_problems from optimagic.benchmarking.run_benchmark import run_benchmark from optimagic.visualization.deviation_plot import ( deviation_plot, @@ -20,14 +20,7 @@ @pytest.mark.parametrize("options", profile_options) def test_convergence_plot_options(options): problems = get_benchmark_problems("example") - stop_after_10 = { - "stopping_max_criterion_evaluations": 10, - "stopping_max_iterations": 10, - } - optimizers = { - "lbfgsb": {"algorithm": "scipy_lbfgsb", "algo_options": stop_after_10}, - "nm": {"algorithm": "scipy_neldermead", "algo_options": stop_after_10}, - } + optimizers = {"lbfgsb": algos.scipy_lbfgsb, "nm": algos.scipy_neldermead} results = run_benchmark( problems, optimizers, diff --git a/tests/optimagic/visualization/test_profile_plot.py b/tests/optimagic/visualization/test_profile_plot.py index a5f482455..a61c182a3 100644 --- a/tests/optimagic/visualization/test_profile_plot.py +++ b/tests/optimagic/visualization/test_profile_plot.py @@ -5,7 +5,7 @@ import pytest from numpy.testing import assert_allclose -from optimagic import get_benchmark_problems +from optimagic import algos, get_benchmark_problems from optimagic.benchmarking.run_benchmark import run_benchmark from optimagic.visualization.profile_plot import ( _determine_alpha_grid, @@ -189,17 +189,7 @@ def test_extract_profile_plot_lines(): @pytest.mark.parametrize("options", profile_options) def test_profile_plot_options(options, close_mpl_figures): problems = get_benchmark_problems("example") - stop_after_10 = { - "stopping_max_criterion_evaluations": 10, - "stopping_max_iterations": 10, - } - optimizers = { - "lbfgsb": {"algorithm": "scipy_lbfgsb", "algo_options": stop_after_10}, - "neldermead": { - "algorithm": "scipy_neldermead", - "algo_options": stop_after_10, - }, - } + optimizers = {"lbfgsb": algos.scipy_lbfgsb, "neldermead": algos.scipy_neldermead} results = run_benchmark( problems, optimizers, From ffaaaaf12ad71587a1bf46a8aa934447665da162 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Thu, 19 Nov 2026 11:09:43 +0100 Subject: [PATCH 2/6] Use mark decorators, solver specific derivatives and selection properties. - The problem type of a BenchmarkFunction is set with the mark decorators on fun instead of three base classes. - BenchmarkFunction.jac(solver_type) returns the derivative function for one type of optimizer. run_benchmark requests the version that matches each optimizer. - Add properties that correspond to the filters for selecting algorithms: multimodal on functions, has_bounds and has_nonlinear_constraints on problems. - Benchmark functions and problems can have constraints, which are passed to minimize. Co-Authored-By: Claude Fable 5.2 --- docs/source/development/ep-02-typing.md | 3 +- docs/source/how_to/how_to_benchmarking.ipynb | 28 +- docs/source/reference/index.md | 6 - src/optimagic/__init__.py | 6 - .../benchmarking/benchmark_problem.py | 306 ++++++++------- src/optimagic/benchmarking/cartis_roberts.py | 6 +- .../benchmarking/get_benchmark_problems.py | 18 +- src/optimagic/benchmarking/more_wild.py | 75 ++-- src/optimagic/benchmarking/run_benchmark.py | 7 +- .../benchmarking/test_benchmark_problem.py | 354 +++++++++++++----- .../test_get_benchmark_problems.py | 30 +- .../test_process_benchmark_results.py | 4 +- .../benchmarking/test_run_benchmark.py | 73 +++- 13 files changed, 607 insertions(+), 309 deletions(-) diff --git a/docs/source/development/ep-02-typing.md b/docs/source/development/ep-02-typing.md index 1c14112bf..a9c5320e4 100644 --- a/docs/source/development/ep-02-typing.md +++ b/docs/source/development/ep-02-typing.md @@ -1494,7 +1494,8 @@ The implementation in version `0.6.0` follows this section with a few changes: benchmark function with start parameters and optionally bounds, a known solution, noise and scaling. The same function can be used in several problems, e.g. with good and bad start parameters. Functions are defined by subclassing, i.e. `fun` is a method - and not an attribute. + and not an attribute. As for `minimize`, the problem type is set with the `mark` + decorators. - The solution of a `BenchmarkProblem` is optional and states whether it is exact or only the best known value. Without an exact solution, plots and reports use the best function value any of the compared optimizers found. diff --git a/docs/source/how_to/how_to_benchmarking.ipynb b/docs/source/how_to/how_to_benchmarking.ipynb index e98bf6d0d..b902f4386 100644 --- a/docs/source/how_to/how_to_benchmarking.ipynb +++ b/docs/source/how_to/how_to_benchmarking.ipynb @@ -81,7 +81,22 @@ "source": [ "The same function can be used in several problems. For example, the full Moré and Wild set contains a second Rosenbrock problem that starts further away from the solution.\n", "\n", - "Because the problems are stored in a dictionary, you can select or combine problems with standard Python tools. For example, this keeps the problems with at most four parameters:" + "### Select problems\n", + "\n", + "Because the problems are stored in a dictionary, you can select or combine problems with standard Python tools. Problems and their functions have properties for this. They correspond to the filters you can use to select algorithms:\n", + "\n", + "| Property | Meaning |\n", + "|---|---|\n", + "| `problem.n_params` | Number of parameters |\n", + "| `problem.has_bounds` | At least one parameter has a finite bound |\n", + "| `problem.has_nonlinear_constraints` | The problem has nonlinear constraints |\n", + "| `problem.function.problem_type` | Scalar, least-squares or likelihood problem |\n", + "| `problem.function.differentiable` | The function is differentiable |\n", + "| `problem.function.has_jac` | A closed form derivative is available |\n", + "| `problem.function.multimodal` | The function has local minima that are not global, i.e. it is a test case for global optimizers |\n", + "| `problem.function.convex` | The function is convex |\n", + "\n", + "`differentiable`, `multimodal` and `convex` are `None` if the property is not known for a function. For example, this keeps the differentiable problems with at most four parameters:" ] }, { @@ -90,7 +105,9 @@ "metadata": {}, "source": [ "small_problems = {\n", - " name: problem for name, problem in problems.items() if problem.n_params <= 4\n", + " name: problem\n", + " for name, problem in problems.items()\n", + " if problem.n_params <= 4 and problem.function.differentiable\n", "}\n", "list(small_problems)" ], @@ -422,7 +439,7 @@ "source": [ "## 6. Benchmark your own problems\n", "\n", - "To create your own problem, define a benchmark function and combine it with start parameters in a `BenchmarkProblem`. A benchmark function is a subclass of `ScalarBenchmarkFunction`, `LeastSquaresBenchmarkFunction` or `LikelihoodBenchmarkFunction` that implements `fun`. It is not tied to one number of parameters; the number of parameters is fixed by the start parameters of the problem." + "To create your own problem, define a benchmark function and combine it with start parameters in a `BenchmarkProblem`. A benchmark function is a subclass of `BenchmarkFunction` that implements `fun`. As for `minimize`, mark `fun` with `om.mark.least_squares` or `om.mark.likelihood` if it returns least-squares residuals or likelihood contributions. A function is not tied to one number of parameters; the number of parameters is fixed by the start parameters of the problem." ] }, { @@ -433,10 +450,11 @@ "import numpy as np\n", "\n", "\n", - "class ShiftedSphere(om.LeastSquaresBenchmarkFunction):\n", + "class ShiftedSphere(om.BenchmarkFunction):\n", " differentiable = True\n", " convex = True\n", "\n", + " @om.mark.least_squares\n", " def fun(self, x):\n", " # the residuals; optimizers minimize the sum of their squares\n", " return x - 1\n", @@ -464,6 +482,8 @@ "source": [ "The `solution` is optional. If you leave it out, plots and reports compare each optimizer to the best function value any of the optimizers found. If the solution is the result of a long optimization run and not known exactly, leave `exact` at its default `False`. It is then replaced automatically if an optimizer finds a better value.\n", "\n", + "If you have a closed form derivative, override `jac(solver_type)`. It returns the derivative function for one type of optimizer, e.g. the jacobian of the residuals for least-squares optimizers and the gradient of the sum of squared residuals for scalar optimizers, or `None` if there is no closed form derivative for that type.\n", + "\n", "To turn an existing Python function into a benchmark function without writing a class, use `om.CallableBenchmarkFunction`." ] } diff --git a/docs/source/reference/index.md b/docs/source/reference/index.md index f673357cc..61f0a8d4d 100644 --- a/docs/source/reference/index.md +++ b/docs/source/reference/index.md @@ -199,12 +199,6 @@ .. autoclass:: BenchmarkFunction :members: - .. autoclass:: ScalarBenchmarkFunction - - .. autoclass:: LeastSquaresBenchmarkFunction - - .. autoclass:: LikelihoodBenchmarkFunction - .. autoclass:: CallableBenchmarkFunction ``` diff --git a/src/optimagic/__init__.py b/src/optimagic/__init__.py index 4801a307a..e056e75a0 100644 --- a/src/optimagic/__init__.py +++ b/src/optimagic/__init__.py @@ -7,9 +7,6 @@ BenchmarkProblem, BenchmarkSolution, CallableBenchmarkFunction, - LeastSquaresBenchmarkFunction, - LikelihoodBenchmarkFunction, - ScalarBenchmarkFunction, ) from optimagic.benchmarking.benchmark_reports import ( convergence_report, @@ -86,9 +83,6 @@ "run_benchmark", "get_benchmark_problems", "BenchmarkFunction", - "ScalarBenchmarkFunction", - "LeastSquaresBenchmarkFunction", - "LikelihoodBenchmarkFunction", "CallableBenchmarkFunction", "BenchmarkProblem", "BenchmarkSolution", diff --git a/src/optimagic/benchmarking/benchmark_problem.py b/src/optimagic/benchmarking/benchmark_problem.py index 9941f891d..a78e203a7 100644 --- a/src/optimagic/benchmarking/benchmark_problem.py +++ b/src/optimagic/benchmarking/benchmark_problem.py @@ -7,16 +7,16 @@ differentiability. It does not have start parameters. Example: the Rosenbrock function. - A ``BenchmarkProblem`` is one concrete test case: a ``BenchmarkFunction`` with start - parameters and optionally bounds, a known solution, noise and scaling. Example: the - Rosenbrock function with the start parameters ``[-1.2, 1]``. Several benchmark - problems can share the same benchmark function. + parameters and optionally bounds, constraints, a known solution, noise and scaling. + Example: the Rosenbrock function with the start parameters ``[-1.2, 1]``. Several + benchmark problems can share the same benchmark function. """ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable +from collections.abc import Callable, Sequence from dataclasses import dataclass, field, replace from functools import cached_property from typing import Any, TypeVar, cast @@ -28,7 +28,9 @@ from optimagic import mark from optimagic.benchmarking.noise import BenchmarkNoise from optimagic.benchmarking.scaling import BenchmarkScaler +from optimagic.constraints import Constraint, NonlinearConstraint from optimagic.parameters.bounds import Bounds +from optimagic.shared.process_user_function import infer_aggregation_level from optimagic.typing import AggregationLevel ObjectiveFunction = Callable[[NDArray[np.float64]], float | NDArray[np.float64]] @@ -44,21 +46,20 @@ class BenchmarkFunction(ABC): """Base class for the functions that benchmark problems are built from. - To define a new function, subclass one of ``ScalarBenchmarkFunction``, - ``LeastSquaresBenchmarkFunction`` or ``LikelihoodBenchmarkFunction`` and implement - ``fun``. Parameters of a family of functions (e.g. the number of residuals) are - attributes of the subclass. Use ``CallableBenchmarkFunction`` to wrap an existing - Python function instead. + To define a new function, create a subclass and implement ``fun``. As for + ``minimize``, ``fun`` has to be marked with ``om.mark.least_squares`` or + ``om.mark.likelihood`` if it returns least-squares residuals or likelihood + contributions. Without a mark it is a scalar function. + + Parameters of a family of functions (e.g. the number of residuals) are attributes + of the subclass. Use ``CallableBenchmarkFunction`` to wrap an existing Python + function instead of writing a class. A benchmark function is not tied to one number of parameters. The number of parameters is fixed by the start parameters of a ``BenchmarkProblem``. """ - problem_type: AggregationLevel - """Whether ``fun`` returns a scalar, least-squares residuals or likelihood - contributions. Set by the base classes for the three problem types.""" - differentiable: bool | None = None """Whether the function is differentiable at every point where it is defined. None if this is not known.""" @@ -68,6 +69,10 @@ class BenchmarkFunction(ABC): refers to the sum of squared residuals or the sum of the contributions. None if this is not known.""" + multimodal: bool | None = None + """Whether the function has local minima that are not global minima. Such functions + are test cases for global optimizers. None if this is not known.""" + min_n_params: int = 1 """The smallest number of parameters the function supports.""" @@ -85,36 +90,59 @@ def fun(self, x: NDArray[np.float64]) -> float | NDArray[np.float64]: Returns: A float for scalar functions; the residuals of shape (n_residuals,) for least-squares functions; the contributions of shape (n_contributions,) for - likelihood functions. + likelihood functions. Since benchmark problems are minimization problems, + the contributions are usually negative log-likelihood contributions. + + """ + + @property + def problem_type(self) -> AggregationLevel: + """Whether ``fun`` returns a scalar, residuals or likelihood contributions. + + The problem type is read from the mark of ``fun``. """ + return infer_aggregation_level(self.fun) - def jac(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - """Evaluate the first derivative of ``fun``. + def jac(self, solver_type: AggregationLevel) -> DerivativeFunction | None: # noqa: ARG002 + """Get the closed form first derivative for one type of optimizer. - Subclasses override this method if a closed form derivative is available. + Optimizers of different types need different derivatives of the same function. + For a least-squares function, a least-squares optimizer needs the jacobian of + the residuals, whereas a scalar optimizer needs the gradient of the sum of + squared residuals. + + Subclasses override this method, define the derivative function for the + requested solver type inside of it and return it. Return None for solver types + without a closed form derivative; optimizers of that type then use numerical + derivatives. Args: - x: The parameters, shape (n_params,). + solver_type: The type of optimizer the derivative is for. Returns: - The gradient of shape (n_params,) for scalar functions; the jacobian of - shape (n_residuals, n_params) or (n_contributions, n_params) for - least-squares and likelihood functions. + None or a function that maps parameters of shape (n_params,) to the + derivative: the gradient of shape (n_params,) for scalar optimizers; the + jacobian of the residuals of shape (n_residuals, n_params) for least-squares + optimizers; the jacobian of the contributions of shape (n_contributions, + n_params) for likelihood optimizers. """ - raise NotImplementedError( - f"{type(self).__name__} does not have a closed form derivative." - ) + return None @property def has_jac(self) -> bool: - """Whether a closed form derivative is available.""" - return type(self).jac is not BenchmarkFunction.jac + """Whether a closed form derivative is available for any type of optimizer.""" + return any( + self.jac(solver_type) is not None for solver_type in AggregationLevel + ) def supports_n_params(self, n_params: int) -> bool: """Check if the function can be evaluated with n_params parameters. + A ``BenchmarkProblem`` can only be created if its function supports the number + of start parameters. + The default implementation checks ``min_n_params`` and ``max_n_params``. Override it for rules that cannot be expressed by those two numbers, e.g. if only even numbers of parameters are supported. @@ -145,92 +173,39 @@ def bounds(self, n_params: int) -> Bounds | None: # noqa: ARG002 """ return None + def constraints(self, n_params: int) -> list[Constraint]: # noqa: ARG002 + """Get the constraints that are part of the function. -class ScalarBenchmarkFunction(BenchmarkFunction): - """Base class for benchmark functions that return a scalar.""" - - problem_type = AggregationLevel.SCALAR - - @abstractmethod - def fun(self, x: NDArray[np.float64]) -> float: - """Evaluate the function. + Subclasses override this method for constrained functions. Args: - x: The parameters, shape (n_params,). - - Returns: - The function value. - - """ - - -class LeastSquaresBenchmarkFunction(BenchmarkFunction): - """Base class for benchmark functions that return least-squares residuals. - - The function that is minimized is the sum of the squared residuals. - - """ - - problem_type = AggregationLevel.LEAST_SQUARES - - @abstractmethod - def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - """Evaluate the residuals. - - Args: - x: The parameters, shape (n_params,). - - Returns: - The residuals, shape (n_residuals,). - - """ - - -class LikelihoodBenchmarkFunction(BenchmarkFunction): - """Base class for benchmark functions that return likelihood contributions. - - The function that is minimized is the sum of the contributions. Since benchmark - problems are minimization problems, the contributions are usually negative - log-likelihood contributions. - - """ - - problem_type = AggregationLevel.LIKELIHOOD - - @abstractmethod - def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - """Evaluate the contributions. - - Args: - x: The parameters, shape (n_params,). + n_params: The number of parameters. Returns: - The contributions, shape (n_contributions,). + List of optimagic constraints. Empty if the function is unconstrained. """ + return [] @dataclass(frozen=True) class CallableBenchmarkFunction(BenchmarkFunction): - """Benchmark function that wraps an existing Python function. + """Benchmark function that wraps existing Python functions. This is the quickest way to turn your own objective function into a benchmark - function. In contrast to ``minimize``, the problem type is not inferred from the - ``mark`` decorators but has to be passed explicitly. + function. The functions are marked in the same way as for ``minimize``. """ func: ObjectiveFunction - """The function that is wrapped. Takes parameters of shape (n_params,) and returns - what ``fun`` of a benchmark function with the same ``problem_type`` returns.""" - - problem_type: AggregationLevel - """Whether ``func`` returns a scalar, least-squares residuals or likelihood - contributions.""" + """The function that is wrapped. Takes parameters of shape (n_params,). It has to be + marked with ``om.mark.least_squares`` or ``om.mark.likelihood`` if it returns + least-squares residuals or likelihood contributions.""" - jac_func: DerivativeFunction | None = None - """The first derivative of ``func`` or None if there is no closed form - derivative.""" + jac_funcs: Sequence[DerivativeFunction] = () + """Closed form first derivatives of ``func``. Each function is marked with the type + of optimizer it is for (``om.mark.scalar``, ``om.mark.least_squares`` or + ``om.mark.likelihood``); functions without a mark are for scalar optimizers.""" differentiable: bool | None = None """Whether the function is differentiable at every point where it is defined. None @@ -239,6 +214,10 @@ class CallableBenchmarkFunction(BenchmarkFunction): convex: bool | None = None """Whether the function is convex. None if this is not known.""" + multimodal: bool | None = None + """Whether the function has local minima that are not global minima. None if this is + not known.""" + min_n_params: int = 1 """The smallest number of parameters the function supports.""" @@ -247,23 +226,27 @@ class CallableBenchmarkFunction(BenchmarkFunction): limit.""" def __post_init__(self) -> None: - if not isinstance(self.problem_type, AggregationLevel): - raise TypeError( - "problem_type must be an AggregationLevel, not " - f"{type(self.problem_type)}." + if not callable(self.func): + raise TypeError(f"func must be callable, not {type(self.func)}.") + solver_types = [infer_aggregation_level(func) for func in self.jac_funcs] + if len(set(solver_types)) < len(solver_types): + raise ValueError( + "jac_funcs contains more than one derivative for the same type of " + "optimizer." ) def fun(self, x: NDArray[np.float64]) -> float | NDArray[np.float64]: return self.func(x) - def jac(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - if self.jac_func is None: - return super().jac(x) - return self.jac_func(x) - @property - def has_jac(self) -> bool: - return self.jac_func is not None + def problem_type(self) -> AggregationLevel: + return infer_aggregation_level(self.func) + + def jac(self, solver_type: AggregationLevel) -> DerivativeFunction | None: + for func in self.jac_funcs: + if infer_aggregation_level(func) == solver_type: + return func + return None def aggregate_function_value( @@ -279,9 +262,19 @@ def aggregate_function_value( The value itself for scalar functions; the sum of squared residuals for least-squares functions; the sum of the contributions for likelihood functions. + Raises: + ValueError: If a scalar function returned an array with more than one entry. + """ if problem_type == AggregationLevel.SCALAR: - return float(value) + if np.size(value) != 1: + raise ValueError( + "A scalar benchmark function returned an array with " + f"{np.size(value)} entries. If the function returns least-squares " + "residuals or likelihood contributions, mark `fun` with " + "`om.mark.least_squares` or `om.mark.likelihood`." + ) + return float(np.asarray(value, dtype=np.float64).reshape(-1)[0]) arr = np.asarray(value, dtype=np.float64) if problem_type == AggregationLevel.LEAST_SQUARES: return float(arr @ arr) @@ -344,6 +337,10 @@ class BenchmarkProblem: If None, the bounds outside of which the function cannot be evaluated are used (see ``BenchmarkFunction.bounds``).""" + constraints: Sequence[Constraint] | None = None + """The constraints that are passed to the optimizer. If None, the constraints of + the function are used (see ``BenchmarkFunction.constraints``). Stored as tuple.""" + noise: BenchmarkNoise | None = None """The noise that is added to each function evaluation or None for no noise.""" @@ -401,11 +398,39 @@ def __post_init__(self) -> None: bounds=self.bounds, function_bounds=function_bounds, n_params=n_params ) + if self.constraints is None: + constraints = tuple(self.function.constraints(n_params)) + else: + constraints = tuple(self.constraints) + for constraint in constraints: + if not isinstance(constraint, Constraint): + raise TypeError( + "constraints must be optimagic constraints, not " + f"{type(constraint)}." + ) + if constraints and self.scaler is not None: + raise NotImplementedError( + "Scaling of benchmark problems with constraints is not supported yet." + ) + object.__setattr__(self, "constraints", constraints) + @property def n_params(self) -> int: """The number of parameters of the problem.""" return len(self.start_params) + @property + def has_bounds(self) -> bool: + """Whether at least one parameter has a finite lower or upper bound.""" + lower, upper = _get_bound_arrays(self.bounds, self.n_params) + return bool(np.isfinite(lower).any() or np.isfinite(upper).any()) + + @property + def has_nonlinear_constraints(self) -> bool: + """Whether the problem has nonlinear constraints.""" + constraints = self.constraints or () + return any(isinstance(c, NonlinearConstraint) for c in constraints) + @property def fun(self) -> ObjectiveFunction: """The objective function as the optimizer sees it, i.e. scaled and with noise. @@ -429,27 +454,25 @@ def noise_free_fun(self) -> ObjectiveFunction: ) return _mark_problem_type(func, self.function.problem_type) - @property - def jac(self) -> list[DerivativeFunction] | None: - """Closed form derivatives of ``fun`` that can be passed to ``minimize``. + def jac(self, solver_type: AggregationLevel) -> DerivativeFunction | None: + """Get the closed form derivative of ``fun`` for one type of optimizer. - The list contains one function for each type of optimizer that can use the - derivative, e.g. the gradient of the sum of squared residuals for scalar - optimizers and the jacobian of the residuals for least-squares optimizers. + Args: + solver_type: The type of optimizer the derivative is for. - None if the benchmark function has no closed form derivative or if the problem - is noisy or scaled. Optimizers then fall back to numerical derivatives. + Returns: + A function that is marked with the solver type and can be passed to + ``minimize`` as ``jac``. None if the benchmark function has no closed form + derivative for this type of optimizer or if the problem is noisy or scaled. + Optimizers then use numerical derivatives. """ - if not self.function.has_jac or self.noise is not None: + if self.noise is not None or self.scaler is not None: return None - if self.scaler is not None: + derivative = self.function.jac(solver_type) + if derivative is None: return None - levels = _DERIVATIVE_LEVELS[self.function.problem_type] - return [ - _mark_problem_type(_ProblemDerivative(self.function, level), level) - for level in levels - ] + return _mark_problem_type(_ProblemDerivative(derivative), solver_type) @cached_property def start_fun(self) -> float: @@ -497,6 +520,7 @@ def with_scaling(self, scaler: BenchmarkScaler) -> Self: Raises: ValueError: If the problem is already scaled. + NotImplementedError: If the problem has constraints. """ if not isinstance(scaler, BenchmarkScaler): @@ -551,47 +575,19 @@ def __call__(self, params: NDArray[np.float64]) -> float | NDArray[np.float64]: return value + self._noise.draw_noise(value, params=x, rng=self._rng) -_DERIVATIVE_LEVELS = { - AggregationLevel.SCALAR: [AggregationLevel.SCALAR], - AggregationLevel.LEAST_SQUARES: [ - AggregationLevel.SCALAR, - AggregationLevel.LIKELIHOOD, - AggregationLevel.LEAST_SQUARES, - ], - AggregationLevel.LIKELIHOOD: [ - AggregationLevel.SCALAR, - AggregationLevel.LIKELIHOOD, - ], -} -"""The types of optimizers for which a derivative can be calculated from the derivative -of a benchmark function with a given problem type.""" - - class _ProblemDerivative: - """Derivative of a benchmark function for one type of optimizer. + """Derivative of a benchmark problem for one type of optimizer. - This is a class and not a closure such that it can be pickled. + The wrapper makes sure that marking the derivative with the solver type does not + modify the function that was returned by ``BenchmarkFunction.jac``. """ - def __init__(self, function: BenchmarkFunction, level: AggregationLevel) -> None: - self._function = function - self._level = level + def __init__(self, derivative: DerivativeFunction) -> None: + self._derivative = derivative def __call__(self, params: NDArray[np.float64]) -> NDArray[np.float64]: - jac = self._function.jac(params) - problem_type = self._function.problem_type - if problem_type == self._level: - return jac - if problem_type == AggregationLevel.LIKELIHOOD: - # gradient of the sum of the contributions - return jac.sum(axis=0) - residuals = np.asarray(self._function.fun(params), dtype=np.float64) - if self._level == AggregationLevel.SCALAR: - # gradient of the sum of squared residuals - return 2 * jac.T @ residuals - # jacobian of the squared residuals - return 2 * residuals.reshape(-1, 1) * jac + return self._derivative(params) def _mark_problem_type(func: FuncT, problem_type: AggregationLevel) -> FuncT: diff --git a/src/optimagic/benchmarking/cartis_roberts.py b/src/optimagic/benchmarking/cartis_roberts.py index 83eab66a9..edf732c6d 100644 --- a/src/optimagic/benchmarking/cartis_roberts.py +++ b/src/optimagic/benchmarking/cartis_roberts.py @@ -29,7 +29,6 @@ ) from optimagic.config import IS_NUMBA_INSTALLED from optimagic.parameters.bounds import Bounds -from optimagic.typing import AggregationLevel if IS_NUMBA_INSTALLED: from numba import njit @@ -4929,9 +4928,8 @@ def _problem( solution_params = np.array(solution_x, dtype=np.float64) return BenchmarkProblem( - function=CallableBenchmarkFunction( - func=fun, problem_type=AggregationLevel.LEAST_SQUARES - ), + # Mark the function here because marks get lost when a function is partialled. + function=CallableBenchmarkFunction(func=mark.least_squares(fun)), start_params=np.array(start_x, dtype=np.float64), solution=BenchmarkSolution( fun=float(solution_fun), params=solution_params, exact=solution_fun == 0 diff --git a/src/optimagic/benchmarking/get_benchmark_problems.py b/src/optimagic/benchmarking/get_benchmark_problems.py index 1395fb8ea..5885bb662 100644 --- a/src/optimagic/benchmarking/get_benchmark_problems.py +++ b/src/optimagic/benchmarking/get_benchmark_problems.py @@ -11,8 +11,8 @@ from numpy.typing import NDArray from optimagic.benchmarking.benchmark_problem import ( + BenchmarkFunction, BenchmarkProblem, - LeastSquaresBenchmarkFunction, ) from optimagic.benchmarking.noise import ( AdditiveBenchmarkNoise, @@ -25,6 +25,7 @@ LinspaceBenchmarkScaler, pre_process_scaling, ) +from optimagic.typing import AggregationLevel from optimagic.utilities import get_rng BenchmarkSetName = Literal["more_wild", "cartis_roberts", "example", "estimagic"] @@ -128,15 +129,15 @@ def get_benchmark_problems( @dataclass(frozen=True) -class LeastSquaresFunctionWithSteps(LeastSquaresBenchmarkFunction): - """Least-squares function that is evaluated at rounded parameters. +class BenchmarkFunctionWithSteps(BenchmarkFunction): + """Benchmark function that is evaluated at rounded parameters. Rounding makes the function piecewise constant. This is a problem for optimizers that use numerical derivatives with small step sizes. """ - function: LeastSquaresBenchmarkFunction + function: BenchmarkFunction """The function that is evaluated at the rounded parameters.""" decimals: int = 3 @@ -144,9 +145,13 @@ class LeastSquaresFunctionWithSteps(LeastSquaresBenchmarkFunction): differentiable = False - def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + def fun(self, x: NDArray[np.float64]) -> float | NDArray[np.float64]: return self.function.fun(x.round(self.decimals)) + @property + def problem_type(self) -> AggregationLevel: + return self.function.problem_type + def supports_n_params(self, n_params: int) -> bool: return self.function.supports_n_params(n_params) @@ -222,9 +227,8 @@ def _get_problem_set(name: str) -> dict[str, BenchmarkProblem]: if k in subset_mw: problems[k] = v if k in subset_add_steps: - assert isinstance(v.function, LeastSquaresBenchmarkFunction) problems[f"{k}_with_steps"] = replace( - v, function=LeastSquaresFunctionWithSteps(v.function) + v, function=BenchmarkFunctionWithSteps(v.function) ) for k, v in CARTIS_ROBERTS_PROBLEMS.items(): diff --git a/src/optimagic/benchmarking/more_wild.py b/src/optimagic/benchmarking/more_wild.py index 1fa2b642f..f654d4a43 100644 --- a/src/optimagic/benchmarking/more_wild.py +++ b/src/optimagic/benchmarking/more_wild.py @@ -31,7 +31,6 @@ BenchmarkFunction, BenchmarkProblem, BenchmarkSolution, - LeastSquaresBenchmarkFunction, ) @@ -801,7 +800,7 @@ def get_start_points_mancino(n, a=1): @dataclass(frozen=True) -class LinearFullRank(LeastSquaresBenchmarkFunction): +class LinearFullRank(BenchmarkFunction): """Linear function with full rank.""" dim_out: int @@ -809,7 +808,9 @@ class LinearFullRank(LeastSquaresBenchmarkFunction): differentiable = True convex = True + multimodal = False + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return linear_full_rank(x, dim_out=self.dim_out) @@ -818,7 +819,7 @@ def supports_n_params(self, n_params: int) -> bool: @dataclass(frozen=True) -class LinearRankOne(LeastSquaresBenchmarkFunction): +class LinearRankOne(BenchmarkFunction): """Linear function with rank one.""" dim_out: int @@ -826,7 +827,9 @@ class LinearRankOne(LeastSquaresBenchmarkFunction): differentiable = True convex = True + multimodal = False + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return linear_rank_one(x, dim_out=self.dim_out) @@ -835,7 +838,7 @@ def supports_n_params(self, n_params: int) -> bool: @dataclass(frozen=True) -class LinearRankOneZeroColumnsRows(LeastSquaresBenchmarkFunction): +class LinearRankOneZeroColumnsRows(BenchmarkFunction): """Linear function with rank one and zero columns and rows.""" dim_out: int @@ -843,7 +846,9 @@ class LinearRankOneZeroColumnsRows(LeastSquaresBenchmarkFunction): differentiable = True convex = True + multimodal = False + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return linear_rank_one_zero_columns_rows(x, dim_out=self.dim_out) @@ -852,20 +857,22 @@ def supports_n_params(self, n_params: int) -> bool: @dataclass(frozen=True) -class Rosenbrock(LeastSquaresBenchmarkFunction): +class Rosenbrock(BenchmarkFunction): """Rosenbrock function with two parameters.""" differentiable = True convex = False + multimodal = False min_n_params = 2 max_n_params = 2 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return rosenbrock(x) @dataclass(frozen=True) -class HelicalValley(LeastSquaresBenchmarkFunction): +class HelicalValley(BenchmarkFunction): """Helical valley function.""" # the first residual jumps where x[0] changes its sign and x[1] is negative @@ -873,86 +880,97 @@ class HelicalValley(LeastSquaresBenchmarkFunction): min_n_params = 3 max_n_params = 3 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return helical_valley(x) @dataclass(frozen=True) -class PowellSingular(LeastSquaresBenchmarkFunction): +class PowellSingular(BenchmarkFunction): """Powell singular function.""" differentiable = True convex = True + multimodal = False min_n_params = 4 max_n_params = 4 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return powell_singular(x) @dataclass(frozen=True) -class FreudensteinRoth(LeastSquaresBenchmarkFunction): +class FreudensteinRoth(BenchmarkFunction): """Freudenstein and Roth function.""" differentiable = True convex = False + # has a local minimum with a function value of about 48.98 and a global minimum + # with a function value of zero + multimodal = True min_n_params = 2 max_n_params = 2 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return freudenstein_roth(x) @dataclass(frozen=True) -class Bard(LeastSquaresBenchmarkFunction): +class Bard(BenchmarkFunction): """Bard function.""" differentiable = True min_n_params = 3 max_n_params = 3 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return bard(x, y=y_vec) @dataclass(frozen=True) -class KowalikOsborne(LeastSquaresBenchmarkFunction): +class KowalikOsborne(BenchmarkFunction): """Kowalik and Osborne function.""" differentiable = True min_n_params = 4 max_n_params = 4 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return kowalik_osborne(x, y1=v_vec, y2=y2_vec) @dataclass(frozen=True) -class Meyer(LeastSquaresBenchmarkFunction): +class Meyer(BenchmarkFunction): """Meyer function.""" differentiable = True min_n_params = 3 max_n_params = 3 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return meyer(x, y=y3_vec) @dataclass(frozen=True) -class Watson(LeastSquaresBenchmarkFunction): +class Watson(BenchmarkFunction): """Watson function.""" differentiable = True min_n_params = 2 max_n_params = 31 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return watson(x) @dataclass(frozen=True) -class Box3D(LeastSquaresBenchmarkFunction): +class Box3D(BenchmarkFunction): """Box three-dimensional function.""" dim_out: int @@ -962,12 +980,13 @@ class Box3D(LeastSquaresBenchmarkFunction): min_n_params = 3 max_n_params = 3 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return box_3d(x, dim_out=self.dim_out) @dataclass(frozen=True) -class JennrichSampson(LeastSquaresBenchmarkFunction): +class JennrichSampson(BenchmarkFunction): """Jennrich and Sampson function.""" dim_out: int @@ -977,12 +996,13 @@ class JennrichSampson(LeastSquaresBenchmarkFunction): min_n_params = 2 max_n_params = 2 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return jennrich_sampson(x, dim_out=self.dim_out) @dataclass(frozen=True) -class BrownDennis(LeastSquaresBenchmarkFunction): +class BrownDennis(BenchmarkFunction): """Brown and Dennis function.""" dim_out: int @@ -992,12 +1012,13 @@ class BrownDennis(LeastSquaresBenchmarkFunction): min_n_params = 4 max_n_params = 4 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return brown_dennis(x, dim_out=self.dim_out) @dataclass(frozen=True) -class Chebyquad(LeastSquaresBenchmarkFunction): +class Chebyquad(BenchmarkFunction): """Chebyquad function.""" dim_out: int @@ -1005,6 +1026,7 @@ class Chebyquad(LeastSquaresBenchmarkFunction): differentiable = True + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return chebyquad(x, dim_out=self.dim_out) @@ -1013,79 +1035,86 @@ def supports_n_params(self, n_params: int) -> bool: @dataclass(frozen=True) -class BrownAlmostLinear(LeastSquaresBenchmarkFunction): +class BrownAlmostLinear(BenchmarkFunction): """Brown almost-linear function.""" differentiable = True + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return brown_almost_linear(x) @dataclass(frozen=True) -class OsborneOne(LeastSquaresBenchmarkFunction): +class OsborneOne(BenchmarkFunction): """Osborne 1 function.""" differentiable = True min_n_params = 5 max_n_params = 5 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return osborne_one(x, y=y4_vec) @dataclass(frozen=True) -class OsborneTwo(LeastSquaresBenchmarkFunction): +class OsborneTwo(BenchmarkFunction): """Osborne 2 function.""" differentiable = True min_n_params = 11 max_n_params = 11 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return osborne_two(x, y=y5_vec) @dataclass(frozen=True) -class Bdqrtic(LeastSquaresBenchmarkFunction): +class Bdqrtic(BenchmarkFunction): """Banded quartic function (BDQRTIC).""" differentiable = True min_n_params = 5 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return bdqrtic(x) @dataclass(frozen=True) -class Cube(LeastSquaresBenchmarkFunction): +class Cube(BenchmarkFunction): """Cube function.""" differentiable = True min_n_params = 2 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return cube(x) @dataclass(frozen=True) -class Mancino(LeastSquaresBenchmarkFunction): +class Mancino(BenchmarkFunction): """Mancino function.""" differentiable = True + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return mancino(x) @dataclass(frozen=True) -class HeartEight(LeastSquaresBenchmarkFunction): +class HeartEight(BenchmarkFunction): """Heart function with eight parameters.""" differentiable = True min_n_params = 8 max_n_params = 8 + @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return heart_eight(x, y=heart_eight_y_vec) diff --git a/src/optimagic/benchmarking/run_benchmark.py b/src/optimagic/benchmarking/run_benchmark.py index 75b10a74a..b172a39ae 100644 --- a/src/optimagic/benchmarking/run_benchmark.py +++ b/src/optimagic/benchmarking/run_benchmark.py @@ -242,6 +242,8 @@ def _get_optimization_arguments_and_keys( for problem_name, problem in problems.items(): for option_name, options in minimize_options.items(): + algorithm = cast(Algorithm, options["algorithm"]) + constraints = list(problem.constraints or ()) kwargs = { **options, # Each optimization gets a new function such that all optimizers see @@ -250,7 +252,10 @@ def _get_optimization_arguments_and_keys( # The start parameters of a problem are read-only. "params": problem.start_params.copy(), "bounds": problem.bounds, - "jac": problem.jac, + "constraints": constraints if constraints else None, + # The derivative depends on the type of the optimizer, e.g. scalar + # optimizers need a gradient and least-squares optimizers a jacobian. + "jac": problem.jac(algorithm.algo_info.solver_type), } kwargs_list.append(kwargs) names.append((problem_name, option_name)) diff --git a/tests/optimagic/benchmarking/test_benchmark_problem.py b/tests/optimagic/benchmarking/test_benchmark_problem.py index a4aba568b..5a4c1cccb 100644 --- a/tests/optimagic/benchmarking/test_benchmark_problem.py +++ b/tests/optimagic/benchmarking/test_benchmark_problem.py @@ -6,12 +6,10 @@ import optimagic as om from optimagic.benchmarking.benchmark_problem import ( + BenchmarkFunction, BenchmarkProblem, BenchmarkSolution, CallableBenchmarkFunction, - LeastSquaresBenchmarkFunction, - LikelihoodBenchmarkFunction, - ScalarBenchmarkFunction, aggregate_function_value, ) from optimagic.benchmarking.noise import AdditiveBenchmarkNoise @@ -19,48 +17,77 @@ from optimagic.shared.process_user_function import infer_aggregation_level from optimagic.typing import AggregationLevel +SCALAR = AggregationLevel.SCALAR +LEAST_SQUARES = AggregationLevel.LEAST_SQUARES +LIKELIHOOD = AggregationLevel.LIKELIHOOD + # ====================================================================================== # Benchmark functions used in the tests # ====================================================================================== -class Sphere(ScalarBenchmarkFunction): +class Sphere(BenchmarkFunction): differentiable = True convex = True + multimodal = False def fun(self, x): return float(x @ x) - def jac(self, x): - return 2 * x + def jac(self, solver_type): + if solver_type != SCALAR: + return None + + def gradient(x): + return 2 * x + + return gradient @dataclass(frozen=True) -class ShiftedResiduals(LeastSquaresBenchmarkFunction): +class ShiftedResiduals(BenchmarkFunction): shift: float = 1.0 min_n_params = 2 max_n_params = 4 + @om.mark.least_squares def fun(self, x): return np.append(x - self.shift, x[0] * x[1]) - def jac(self, x): - last_row = np.zeros(len(x)) - last_row[0] = x[1] - last_row[1] = x[0] - return np.vstack([np.eye(len(x)), last_row]) + def jac(self, solver_type): + def residual_jac(x): + last_row = np.zeros(len(x)) + last_row[0] = x[1] + last_row[1] = x[0] + return np.vstack([np.eye(len(x)), last_row]) + + def gradient(x): + return 2 * residual_jac(x).T @ self.fun(x) + + if solver_type == LEAST_SQUARES: + return residual_jac + if solver_type == SCALAR: + return gradient + return None -class Contributions(LikelihoodBenchmarkFunction): +class Contributions(BenchmarkFunction): + @om.mark.likelihood def fun(self, x): return np.array([x[0] ** 2, x[1] ** 2 + x[0], 3.0]) - def jac(self, x): - return np.array([[2 * x[0], 0.0], [1.0, 2 * x[1]], [0.0, 0.0]]) + def jac(self, solver_type): + if solver_type != LIKELIHOOD: + return None + def contribution_jac(x): + return np.array([[2 * x[0], 0.0], [1.0, 2 * x[1]], [0.0, 0.0]]) -class EvenSphere(ScalarBenchmarkFunction): + return contribution_jac + + +class EvenSphere(BenchmarkFunction): def fun(self, x): return float(x @ x) @@ -68,7 +95,7 @@ def supports_n_params(self, n_params): return n_params % 2 == 0 -class LogSum(ScalarBenchmarkFunction): +class LogSum(BenchmarkFunction): def fun(self, x): return float(np.log(x).sum() + x @ x) @@ -76,7 +103,19 @@ def bounds(self, n_params): return om.Bounds(lower=np.zeros(n_params)) -FUNCTIONS_WITH_JAC = [Sphere(), ShiftedResiduals(), Contributions()] +def _sum_is_one(x): + return x.sum() + + +class ConstrainedSphere(BenchmarkFunction): + def fun(self, x): + return float(x @ x) + + def constraints(self, n_params): # noqa: ARG002 + return [om.NonlinearConstraint(func=_sum_is_one, value=1.0)] + + +ALL_FUNCTIONS = [Sphere(), ShiftedResiduals(), Contributions()] # ====================================================================================== @@ -84,34 +123,62 @@ def bounds(self, n_params): # ====================================================================================== -def test_problem_type_is_set_by_base_classes(): - assert Sphere().problem_type == AggregationLevel.SCALAR - assert ShiftedResiduals().problem_type == AggregationLevel.LEAST_SQUARES - assert Contributions().problem_type == AggregationLevel.LIKELIHOOD +def test_problem_type_is_read_from_mark_of_fun(): + assert Sphere().problem_type == SCALAR + assert ShiftedResiduals().problem_type == LEAST_SQUARES + assert Contributions().problem_type == LIKELIHOOD def test_default_properties_are_unknown(): function = Contributions() assert function.differentiable is None assert function.convex is None + assert function.multimodal is None assert function.min_n_params == 1 assert function.max_n_params is None assert function.bounds(3) is None + assert function.constraints(3) == [] def test_properties_can_be_set_in_subclasses(): assert Sphere().differentiable is True assert Sphere().convex is True + assert Sphere().multimodal is False + + +def test_jac_is_none_by_default(): + function = EvenSphere() + assert not function.has_jac + for solver_type in AggregationLevel: + assert function.jac(solver_type) is None def test_has_jac(): assert Sphere().has_jac - assert not EvenSphere().has_jac + assert ShiftedResiduals().has_jac + assert Contributions().has_jac -def test_jac_raises_if_not_available(): - with pytest.raises(NotImplementedError, match="EvenSphere does not have"): - EvenSphere().jac(np.ones(2)) +@pytest.mark.parametrize( + "function, solver_type, expected", + [ + (Sphere(), SCALAR, True), + (Sphere(), LEAST_SQUARES, False), + (Sphere(), LIKELIHOOD, False), + (ShiftedResiduals(), SCALAR, True), + (ShiftedResiduals(), LEAST_SQUARES, True), + (ShiftedResiduals(), LIKELIHOOD, False), + (Contributions(), SCALAR, False), + (Contributions(), LIKELIHOOD, True), + ], +) +def test_jac_returns_a_function_or_none_for_each_solver_type( + function, solver_type, expected +): + derivative = function.jac(solver_type) + assert (derivative is not None) == expected + if expected: + assert callable(derivative) def test_supports_n_params_without_limits(): @@ -136,9 +203,10 @@ def test_supports_n_params_can_be_overridden(): @pytest.mark.parametrize( "value, problem_type, expected", [ - (3.0, AggregationLevel.SCALAR, 3.0), - (np.array([1.0, 2.0]), AggregationLevel.LEAST_SQUARES, 5.0), - (np.array([1.0, 2.0]), AggregationLevel.LIKELIHOOD, 3.0), + (3.0, SCALAR, 3.0), + (np.array([3.0]), SCALAR, 3.0), + (np.array([1.0, 2.0]), LEAST_SQUARES, 5.0), + (np.array([1.0, 2.0]), LIKELIHOOD, 3.0), ], ) def test_aggregate_function_value(value, problem_type, expected): @@ -147,46 +215,75 @@ def test_aggregate_function_value(value, problem_type, expected): assert got == expected +def test_function_that_returns_residuals_without_mark_raises(): + class ForgottenMark(BenchmarkFunction): + def fun(self, x): + return x - 1 + + problem = BenchmarkProblem(function=ForgottenMark(), start_params=np.zeros(3)) + with pytest.raises(ValueError, match=r"mark `fun` with `om.mark.least_squares`"): + problem.start_fun # noqa: B018 + + # ====================================================================================== # CallableBenchmarkFunction # ====================================================================================== def test_callable_benchmark_function(): + @om.mark.least_squares + def residuals(x): + return x - 1 + + @om.mark.least_squares + def residual_jac(x): + return np.eye(len(x)) + + def gradient(x): + return 2 * (x - 1) + function = CallableBenchmarkFunction( - func=lambda x: x - 1, - problem_type=AggregationLevel.LEAST_SQUARES, - jac_func=lambda x: np.eye(len(x)), + func=residuals, + jac_funcs=[residual_jac, gradient], differentiable=True, + multimodal=False, min_n_params=2, max_n_params=3, ) + assert function.problem_type == LEAST_SQUARES aaae(function.fun(np.array([1.0, 3.0])), np.array([0.0, 2.0])) - aaae(function.jac(np.array([1.0, 3.0])), np.eye(2)) assert function.has_jac + assert function.jac(LEAST_SQUARES) is residual_jac + # functions without a mark are for scalar optimizers + assert function.jac(SCALAR) is gradient + assert function.jac(LIKELIHOOD) is None assert function.differentiable is True assert function.convex is None + assert function.multimodal is False assert function.supports_n_params(3) assert not function.supports_n_params(4) -def test_callable_benchmark_function_without_jac(): - function = CallableBenchmarkFunction( - func=lambda x: float(x @ x), problem_type=AggregationLevel.SCALAR - ) +def test_callable_benchmark_function_without_mark_is_scalar(): + function = CallableBenchmarkFunction(func=lambda x: float(x @ x)) + assert function.problem_type == SCALAR assert not function.has_jac - with pytest.raises(NotImplementedError): - function.jac(np.ones(2)) + assert function.jac(SCALAR) is None -def test_callable_benchmark_function_with_invalid_problem_type_raises(): - with pytest.raises(TypeError, match="problem_type must be an AggregationLevel"): +def test_callable_benchmark_function_with_two_jacs_for_one_solver_type_raises(): + with pytest.raises(ValueError, match="more than one derivative"): CallableBenchmarkFunction( - func=lambda x: x, - problem_type="least_squares", # ty: ignore[invalid-argument-type] + func=lambda x: float(x @ x), + jac_funcs=[lambda x: 2 * x, om.mark.scalar(lambda x: 2 * x)], ) +def test_callable_benchmark_function_with_invalid_func_raises(): + with pytest.raises(TypeError, match="func must be callable"): + CallableBenchmarkFunction(func=1) # ty: ignore[invalid-argument-type] + + # ====================================================================================== # BenchmarkProblem: construction # ====================================================================================== @@ -197,6 +294,7 @@ def test_benchmark_problem_defaults(): assert problem.n_params == 3 assert problem.solution is None assert problem.bounds is None + assert problem.constraints == () assert problem.noise is None assert problem.scaler is None assert problem.seed is None @@ -270,6 +368,11 @@ def test_solution_with_wrong_number_of_params_raises(): ) +# ====================================================================================== +# BenchmarkProblem: bounds and constraints +# ====================================================================================== + + def test_bounds_default_to_bounds_of_function(): problem = BenchmarkProblem(function=LogSum(), start_params=np.ones(3)) assert isinstance(problem.bounds, om.Bounds) @@ -312,19 +415,84 @@ def test_bounds_with_wrong_type_raise(): ) +def test_has_bounds(): + unbounded = BenchmarkProblem(function=Sphere(), start_params=np.ones(3)) + assert not unbounded.has_bounds + + infinite = BenchmarkProblem( + function=Sphere(), + start_params=np.ones(3), + bounds=om.Bounds(lower=np.full(3, -np.inf)), + ) + assert not infinite.has_bounds + + from_function = BenchmarkProblem(function=LogSum(), start_params=np.ones(3)) + assert from_function.has_bounds + + one_bound = BenchmarkProblem( + function=Sphere(), + start_params=np.ones(3), + bounds=om.Bounds(upper=np.array([np.inf, 5.0, np.inf])), + ) + assert one_bound.has_bounds + + +def test_constraints_default_to_constraints_of_function(): + problem = BenchmarkProblem(function=ConstrainedSphere(), start_params=np.ones(3)) + assert isinstance(problem.constraints, tuple) + assert len(problem.constraints) == 1 + assert isinstance(problem.constraints[0], om.NonlinearConstraint) + assert problem.has_nonlinear_constraints + + +def test_constraints_can_be_set_on_the_problem(): + constraint = om.LinearConstraint(weights=np.ones(3), value=1.0) + problem = BenchmarkProblem( + function=Sphere(), start_params=np.ones(3), constraints=[constraint] + ) + assert problem.constraints == (constraint,) + assert not problem.has_nonlinear_constraints + + +def test_problem_without_constraints_has_no_nonlinear_constraints(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(3)) + assert not problem.has_nonlinear_constraints + + +def test_invalid_constraints_raise(): + with pytest.raises(TypeError, match="constraints must be optimagic constraints"): + BenchmarkProblem( + function=Sphere(), + start_params=np.ones(3), + constraints=[{"type": "fixed"}], # ty: ignore[invalid-argument-type] + ) + + +def test_scaling_a_problem_with_constraints_raises(): + problem = BenchmarkProblem(function=ConstrainedSphere(), start_params=np.ones(3)) + with pytest.raises(NotImplementedError, match="constraints is not supported"): + problem.with_scaling(LinspaceBenchmarkScaler()) + + +def test_noise_keeps_constraints(): + problem = BenchmarkProblem(function=ConstrainedSphere(), start_params=np.ones(3)) + noisy = problem.with_noise(AdditiveBenchmarkNoise()) + assert noisy.constraints == problem.constraints + + # ====================================================================================== # BenchmarkProblem: functions # ====================================================================================== -@pytest.mark.parametrize("function", FUNCTIONS_WITH_JAC) +@pytest.mark.parametrize("function", ALL_FUNCTIONS) def test_fun_is_marked_with_problem_type(function): problem = BenchmarkProblem(function=function, start_params=np.ones(2)) assert infer_aggregation_level(problem.fun) == function.problem_type assert infer_aggregation_level(problem.noise_free_fun) == function.problem_type -@pytest.mark.parametrize("function", FUNCTIONS_WITH_JAC) +@pytest.mark.parametrize("function", ALL_FUNCTIONS) def test_fun_without_noise_and_scaling_is_the_benchmark_function(function): x = np.array([0.5, -2.0]) problem = BenchmarkProblem(function=function, start_params=np.ones(2)) @@ -484,74 +652,88 @@ def test_with_scaling_with_invalid_type_raises(): # BenchmarkProblem: derivatives # ====================================================================================== -EXPECTED_DERIVATIVE_LEVELS = { - AggregationLevel.SCALAR: [AggregationLevel.SCALAR], - AggregationLevel.LEAST_SQUARES: [ - AggregationLevel.SCALAR, - AggregationLevel.LIKELIHOOD, - AggregationLevel.LEAST_SQUARES, - ], - AggregationLevel.LIKELIHOOD: [AggregationLevel.SCALAR, AggregationLevel.LIKELIHOOD], -} - -def _evaluate_at_level(function, x, level): - """Evaluate a benchmark function as an optimizer of the given level sees it.""" +def _evaluate_for_solver_type(function, x, solver_type): + """Evaluate a benchmark function as an optimizer of solver_type sees it.""" raw = function.fun(x) - if level == function.problem_type: + if solver_type == function.problem_type: return raw - if level == AggregationLevel.SCALAR: - return aggregate_function_value(raw, function.problem_type) - # least-squares function seen by a likelihood optimizer - return raw**2 + return aggregate_function_value(raw, function.problem_type) -@pytest.mark.parametrize("function", FUNCTIONS_WITH_JAC) -def test_jac_matches_numerical_derivatives(function): +@pytest.mark.parametrize( + "function, solver_type", + [ + (Sphere(), SCALAR), + (ShiftedResiduals(), SCALAR), + (ShiftedResiduals(), LEAST_SQUARES), + (Contributions(), LIKELIHOOD), + ], +) +def test_jac_of_problem_matches_numerical_derivative(function, solver_type): x = np.array([0.7, -1.3]) problem = BenchmarkProblem(function=function, start_params=np.ones(2)) - derivatives = problem.jac - assert derivatives is not None - levels = [infer_aggregation_level(derivative) for derivative in derivatives] - assert levels == EXPECTED_DERIVATIVE_LEVELS[function.problem_type] + derivative = problem.jac(solver_type) + assert derivative is not None + assert infer_aggregation_level(derivative) == solver_type + + expected = om.first_derivative( + lambda x: _evaluate_for_solver_type(function, x, solver_type), x + ).derivative + aaae(derivative(x), expected, decimal=5) - for derivative, level in zip(derivatives, levels, strict=True): - expected = om.first_derivative( - lambda x, level=level: _evaluate_at_level(function, x, level), x - ).derivative - aaae(derivative(x), expected, decimal=5) +def test_jac_of_problem_is_none_without_derivative_for_solver_type(): + problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(2)) + assert problem.jac(LEAST_SQUARES) is None -def test_jac_is_none_without_closed_form_derivative(): problem = BenchmarkProblem(function=EvenSphere(), start_params=np.ones(2)) - assert problem.jac is None + assert problem.jac(SCALAR) is None -def test_jac_is_none_with_noise_or_scaling(): +def test_jac_of_problem_is_none_with_noise_or_scaling(): problem = BenchmarkProblem(function=Sphere(), start_params=np.ones(2)) - assert problem.with_noise(AdditiveBenchmarkNoise()).jac is None - assert problem.with_scaling(LinspaceBenchmarkScaler()).jac is None + assert problem.jac(SCALAR) is not None + assert problem.with_noise(AdditiveBenchmarkNoise()).jac(SCALAR) is None + assert problem.with_scaling(LinspaceBenchmarkScaler()).jac(SCALAR) is None + + +def test_marking_the_jac_of_a_problem_does_not_modify_the_function(): + def gradient(x): + return 2 * x + + function = CallableBenchmarkFunction( + func=lambda x: float(x @ x), jac_funcs=[gradient] + ) + problem = BenchmarkProblem(function=function, start_params=np.ones(2)) + derivative = problem.jac(SCALAR) + assert derivative is not None + assert derivative is not gradient + assert not hasattr(gradient, "_problem_type") + aaae(derivative(np.ones(2)), 2 * np.ones(2)) -@pytest.mark.parametrize("algorithm", ["scipy_lbfgsb", "scipy_ls_lm"]) -def test_problem_can_be_passed_to_minimize(algorithm): +@pytest.mark.parametrize( + "algorithm, solver_type", + [("scipy_lbfgsb", SCALAR), ("scipy_ls_lm", LEAST_SQUARES)], +) +def test_problem_can_be_passed_to_minimize(algorithm, solver_type): problem = BenchmarkProblem( function=ShiftedResiduals(shift=2.0), start_params=np.array([3.0, 0.0]) ) - derivatives = problem.jac - assert derivatives is not None res = om.minimize( fun=problem.fun, params=problem.start_params, algorithm=algorithm, - jac=derivatives, + jac=problem.jac(solver_type), bounds=problem.bounds, ) assert res.fun < problem.start_fun expected_fun = aggregate_function_value( - problem.function.fun(res.params), AggregationLevel.LEAST_SQUARES + problem.function.fun(res.params), LEAST_SQUARES ) assert np.allclose(res.fun, expected_fun) - # the first entry of jac is the gradient of the sum of squared residuals - aaae(derivatives[0](res.params), np.zeros(2), decimal=4) + gradient = problem.jac(SCALAR) + assert gradient is not None + aaae(gradient(res.params), np.zeros(2), decimal=4) diff --git a/tests/optimagic/benchmarking/test_get_benchmark_problems.py b/tests/optimagic/benchmarking/test_get_benchmark_problems.py index 69b61e86d..7f6da6842 100644 --- a/tests/optimagic/benchmarking/test_get_benchmark_problems.py +++ b/tests/optimagic/benchmarking/test_get_benchmark_problems.py @@ -8,7 +8,7 @@ from optimagic import minimize from optimagic.benchmarking.benchmark_problem import BenchmarkProblem from optimagic.benchmarking.get_benchmark_problems import ( - LeastSquaresFunctionWithSteps, + BenchmarkFunctionWithSteps, get_benchmark_problems, ) from optimagic.benchmarking.more_wild import Rosenbrock @@ -18,6 +18,7 @@ MultiplicativeBenchmarkNoise, ) from optimagic.benchmarking.scaling import LinspaceBenchmarkScaler +from optimagic.typing import AggregationLevel NAMES = ["more_wild", "cartis_roberts", "example", "estimagic"] @@ -84,6 +85,29 @@ def test_problems_can_be_filtered_and_merged_like_dicts(): assert len(merged) == 6 +def test_problems_can_be_selected_by_properties(): + problems = get_benchmark_problems("example") + + # counterparts of the algorithm filters GradientBased, Global, Bounded, + # NonlinearConstrained and LeastSquares + differentiable = {k for k, p in problems.items() if p.function.differentiable} + assert "rosenbrock_good_start" in differentiable + assert "helical_valley_good_start" not in differentiable + + multimodal = {k for k, p in problems.items() if p.function.multimodal} + assert multimodal == {"freudenstein_roth_good_start"} + + convex = {k for k, p in problems.items() if p.function.convex} + assert convex == {"powell_singular_good_start"} + + assert not any(p.has_bounds for p in problems.values()) + assert not any(p.has_nonlinear_constraints for p in problems.values()) + assert not any(p.function.has_jac for p in problems.values()) + assert {p.function.problem_type for p in problems.values()} == { + AggregationLevel.LEAST_SQUARES + } + + def test_shipped_problem_sets_are_not_modified(): get_benchmark_problems("example", noise=True, scaling=True) problem = get_benchmark_problems("example")["rosenbrock_good_start"] @@ -186,7 +210,7 @@ def test_without_seed_problems_have_no_seed(): def test_function_with_steps(): - function = LeastSquaresFunctionWithSteps(Rosenbrock()) + function = BenchmarkFunctionWithSteps(Rosenbrock()) x = np.array([0.0001, 0.0002]) aaae(function.fun(x), Rosenbrock().fun(np.zeros(2))) assert not np.allclose(Rosenbrock().fun(x), Rosenbrock().fun(np.zeros(2))) @@ -205,7 +229,7 @@ def test_estimagic_set_contains_problems_with_steps(): "chebyquad_10_with_steps", } problem = problems["rosenbrock_good_start_with_steps"] - assert problem.function == LeastSquaresFunctionWithSteps(Rosenbrock()) + assert problem.function == BenchmarkFunctionWithSteps(Rosenbrock()) assert problem.solution is not None assert problem.solution.fun == 0 diff --git a/tests/optimagic/benchmarking/test_process_benchmark_results.py b/tests/optimagic/benchmarking/test_process_benchmark_results.py index 2db9da9ce..0350c426e 100644 --- a/tests/optimagic/benchmarking/test_process_benchmark_results.py +++ b/tests/optimagic/benchmarking/test_process_benchmark_results.py @@ -4,9 +4,9 @@ import optimagic as om from optimagic.benchmarking.benchmark_problem import ( + BenchmarkFunction, BenchmarkProblem, BenchmarkSolution, - ScalarBenchmarkFunction, ) from optimagic.benchmarking.benchmark_result import BenchmarkResult from optimagic.benchmarking.process_benchmark_results import ( @@ -15,7 +15,7 @@ ) -class ShiftedSphere(ScalarBenchmarkFunction): +class ShiftedSphere(BenchmarkFunction): """Sphere with minimum 1 at [1, 1, ...].""" def fun(self, x): diff --git a/tests/optimagic/benchmarking/test_run_benchmark.py b/tests/optimagic/benchmarking/test_run_benchmark.py index 607f9cf5b..742c4b61b 100644 --- a/tests/optimagic/benchmarking/test_run_benchmark.py +++ b/tests/optimagic/benchmarking/test_run_benchmark.py @@ -8,9 +8,8 @@ import optimagic as om from optimagic import get_benchmark_problems from optimagic.benchmarking.benchmark_problem import ( + BenchmarkFunction, BenchmarkProblem, - LeastSquaresBenchmarkFunction, - ScalarBenchmarkFunction, aggregate_function_value, ) from optimagic.benchmarking.benchmark_result import BenchmarkResult @@ -134,7 +133,7 @@ def test_all_optimizers_see_the_same_noise(): def test_run_benchmark_passes_bounds(): - class LogSum(ScalarBenchmarkFunction): + class LogSum(BenchmarkFunction): def fun(self, x): return float(x @ x - np.log(x).sum()) @@ -151,26 +150,54 @@ def bounds(self, n_params): aaae(res.optimize_result.params, np.sqrt([0.5, 0.5]), decimal=4) -def test_run_benchmark_uses_closed_form_derivatives(): - n_jac_calls = [] +def test_run_benchmark_uses_the_derivative_for_the_solver_type(): + requested = [] + called = [] - class Residuals(LeastSquaresBenchmarkFunction): + class Residuals(BenchmarkFunction): + @om.mark.least_squares def fun(self, x): return x - 1 - def jac(self, x): - n_jac_calls.append(1) - return np.eye(len(x)) + def jac(self, solver_type): + requested.append(solver_type) + + def residual_jac(x): + called.append("least_squares") + return np.eye(len(x)) + + def gradient(x): + called.append("scalar") + return 2 * (x - 1) + + if solver_type == AggregationLevel.LEAST_SQUARES: + return residual_jac + if solver_type == AggregationLevel.SCALAR: + return gradient + return None problem = BenchmarkProblem(function=Residuals(), start_params=np.zeros(3)) + result = run_benchmark( {"residuals": problem}, - {"lbfgsb": om.algos.scipy_lbfgsb, "ls_lm": om.algos.scipy_ls_lm}, + {"lbfgsb": om.algos.scipy_lbfgsb}, error_handling="raise", batch_evaluator="threading", ) + assert requested == [AggregationLevel.SCALAR] + assert set(called) == {"scalar"} + + requested.clear() + called.clear() + result |= run_benchmark( + {"residuals": problem}, + {"ls_lm": om.algos.scipy_ls_lm}, + error_handling="raise", + batch_evaluator="threading", + ) + assert requested == [AggregationLevel.LEAST_SQUARES] + assert set(called) == {"least_squares"} - assert len(n_jac_calls) > 0 for res in result.values(): # derivative evaluations are not part of the histories assert not np.isnan(res.fun_history).any() @@ -179,6 +206,30 @@ def jac(self, x): aaae(res.optimize_result.params, np.ones(3), decimal=5) +def test_run_benchmark_passes_constraints(): + class ConstrainedSphere(BenchmarkFunction): + def fun(self, x): + return float(x @ x) + + def constraints(self, n_params): # noqa: ARG002 + return [om.NonlinearConstraint(func=lambda x: x.sum(), value=1.0)] + + problem = BenchmarkProblem( + function=ConstrainedSphere(), start_params=np.array([1.0, 0.0]) + ) + assert problem.has_nonlinear_constraints + + result = run_benchmark( + {"sphere": problem}, + {"slsqp": om.algos.scipy_slsqp}, + error_handling="raise", + batch_evaluator="threading", + ) + res = result[("sphere", "slsqp")] + assert res.optimize_result is not None + aaae(res.optimize_result.params, np.array([0.5, 0.5]), decimal=4) + + def test_process_one_result_without_history_raises(): problem = get_benchmark_problems("example")["box_3d"] res = om.minimize( From 2c0fa19961457687cff2b82e75d15907f9b18087 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Tue, 24 Nov 2026 09:39:08 +0100 Subject: [PATCH 3/6] Mark benchmark function classes instead of their fun method. The problem type of a BenchmarkFunction is read from a mark on the class, like differentiable or convex. Subclasses inherit the mark, so overriding fun no longer turns a least-squares function into a scalar function by accident. Co-Authored-By: Claude Opus 5.5 --- docs/source/development/ep-02-typing.md | 4 +- docs/source/how_to/how_to_benchmarking.ipynb | 4 +- .../benchmarking/benchmark_problem.py | 28 +++++++++--- src/optimagic/benchmarking/more_wild.py | 44 +++++++++---------- src/optimagic/mark.py | 18 ++++++-- .../benchmarking/test_benchmark_problem.py | 40 +++++++++++++++-- .../benchmarking/test_run_benchmark.py | 2 +- 7 files changed, 99 insertions(+), 41 deletions(-) diff --git a/docs/source/development/ep-02-typing.md b/docs/source/development/ep-02-typing.md index a9c5320e4..fbcca5853 100644 --- a/docs/source/development/ep-02-typing.md +++ b/docs/source/development/ep-02-typing.md @@ -1494,8 +1494,8 @@ The implementation in version `0.6.0` follows this section with a few changes: benchmark function with start parameters and optionally bounds, a known solution, noise and scaling. The same function can be used in several problems, e.g. with good and bad start parameters. Functions are defined by subclassing, i.e. `fun` is a method - and not an attribute. As for `minimize`, the problem type is set with the `mark` - decorators. + and not an attribute. The problem type is set by applying the `mark` decorators to + the subclass. - The solution of a `BenchmarkProblem` is optional and states whether it is exact or only the best known value. Without an exact solution, plots and reports use the best function value any of the compared optimizers found. diff --git a/docs/source/how_to/how_to_benchmarking.ipynb b/docs/source/how_to/how_to_benchmarking.ipynb index b902f4386..3a52c7fef 100644 --- a/docs/source/how_to/how_to_benchmarking.ipynb +++ b/docs/source/how_to/how_to_benchmarking.ipynb @@ -439,7 +439,7 @@ "source": [ "## 6. Benchmark your own problems\n", "\n", - "To create your own problem, define a benchmark function and combine it with start parameters in a `BenchmarkProblem`. A benchmark function is a subclass of `BenchmarkFunction` that implements `fun`. As for `minimize`, mark `fun` with `om.mark.least_squares` or `om.mark.likelihood` if it returns least-squares residuals or likelihood contributions. A function is not tied to one number of parameters; the number of parameters is fixed by the start parameters of the problem." + "To create your own problem, define a benchmark function and combine it with start parameters in a `BenchmarkProblem`. A benchmark function is a subclass of `BenchmarkFunction` that implements `fun`. Mark the class with `om.mark.least_squares` or `om.mark.likelihood` if `fun` returns least-squares residuals or likelihood contributions. A function is not tied to one number of parameters; the number of parameters is fixed by the start parameters of the problem." ] }, { @@ -450,11 +450,11 @@ "import numpy as np\n", "\n", "\n", + "@om.mark.least_squares\n", "class ShiftedSphere(om.BenchmarkFunction):\n", " differentiable = True\n", " convex = True\n", "\n", - " @om.mark.least_squares\n", " def fun(self, x):\n", " # the residuals; optimizers minimize the sum of their squares\n", " return x - 1\n", diff --git a/src/optimagic/benchmarking/benchmark_problem.py b/src/optimagic/benchmarking/benchmark_problem.py index a78e203a7..1acb6e750 100644 --- a/src/optimagic/benchmarking/benchmark_problem.py +++ b/src/optimagic/benchmarking/benchmark_problem.py @@ -46,15 +46,28 @@ class BenchmarkFunction(ABC): """Base class for the functions that benchmark problems are built from. - To define a new function, create a subclass and implement ``fun``. As for - ``minimize``, ``fun`` has to be marked with ``om.mark.least_squares`` or - ``om.mark.likelihood`` if it returns least-squares residuals or likelihood - contributions. Without a mark it is a scalar function. + To define a new function, create a subclass and implement ``fun``. The subclass has + to be marked with ``om.mark.least_squares`` or ``om.mark.likelihood`` if ``fun`` + returns least-squares residuals or likelihood contributions. Without a mark it is a + scalar function. The mark is inherited by subclasses. Parameters of a family of functions (e.g. the number of residuals) are attributes of the subclass. Use ``CallableBenchmarkFunction`` to wrap an existing Python function instead of writing a class. + Example: + A least-squares function for any number of parameters:: + + @om.mark.least_squares + @dataclass(frozen=True) + class Sphere(om.BenchmarkFunction): + differentiable = True + convex = True + multimodal = False + + def fun(self, x): + return x + A benchmark function is not tied to one number of parameters. The number of parameters is fixed by the start parameters of a ``BenchmarkProblem``. @@ -99,10 +112,10 @@ def fun(self, x: NDArray[np.float64]) -> float | NDArray[np.float64]: def problem_type(self) -> AggregationLevel: """Whether ``fun`` returns a scalar, residuals or likelihood contributions. - The problem type is read from the mark of ``fun``. + The problem type is read from the mark of the class. """ - return infer_aggregation_level(self.fun) + return infer_aggregation_level(type(self)) def jac(self, solver_type: AggregationLevel) -> DerivativeFunction | None: # noqa: ARG002 """Get the closed form first derivative for one type of optimizer. @@ -271,7 +284,8 @@ def aggregate_function_value( raise ValueError( "A scalar benchmark function returned an array with " f"{np.size(value)} entries. If the function returns least-squares " - "residuals or likelihood contributions, mark `fun` with " + "residuals or likelihood contributions, mark the benchmark function " + "class (or the function wrapped by CallableBenchmarkFunction) with " "`om.mark.least_squares` or `om.mark.likelihood`." ) return float(np.asarray(value, dtype=np.float64).reshape(-1)[0]) diff --git a/src/optimagic/benchmarking/more_wild.py b/src/optimagic/benchmarking/more_wild.py index f654d4a43..1c15f1e29 100644 --- a/src/optimagic/benchmarking/more_wild.py +++ b/src/optimagic/benchmarking/more_wild.py @@ -799,6 +799,7 @@ def get_start_points_mancino(n, a=1): # ====================================================================================== +@mark.least_squares @dataclass(frozen=True) class LinearFullRank(BenchmarkFunction): """Linear function with full rank.""" @@ -810,7 +811,6 @@ class LinearFullRank(BenchmarkFunction): convex = True multimodal = False - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return linear_full_rank(x, dim_out=self.dim_out) @@ -818,6 +818,7 @@ def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +@mark.least_squares @dataclass(frozen=True) class LinearRankOne(BenchmarkFunction): """Linear function with rank one.""" @@ -829,7 +830,6 @@ class LinearRankOne(BenchmarkFunction): convex = True multimodal = False - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return linear_rank_one(x, dim_out=self.dim_out) @@ -837,6 +837,7 @@ def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +@mark.least_squares @dataclass(frozen=True) class LinearRankOneZeroColumnsRows(BenchmarkFunction): """Linear function with rank one and zero columns and rows.""" @@ -848,7 +849,6 @@ class LinearRankOneZeroColumnsRows(BenchmarkFunction): convex = True multimodal = False - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return linear_rank_one_zero_columns_rows(x, dim_out=self.dim_out) @@ -856,6 +856,7 @@ def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +@mark.least_squares @dataclass(frozen=True) class Rosenbrock(BenchmarkFunction): """Rosenbrock function with two parameters.""" @@ -866,11 +867,11 @@ class Rosenbrock(BenchmarkFunction): min_n_params = 2 max_n_params = 2 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return rosenbrock(x) +@mark.least_squares @dataclass(frozen=True) class HelicalValley(BenchmarkFunction): """Helical valley function.""" @@ -880,11 +881,11 @@ class HelicalValley(BenchmarkFunction): min_n_params = 3 max_n_params = 3 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return helical_valley(x) +@mark.least_squares @dataclass(frozen=True) class PowellSingular(BenchmarkFunction): """Powell singular function.""" @@ -895,11 +896,11 @@ class PowellSingular(BenchmarkFunction): min_n_params = 4 max_n_params = 4 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return powell_singular(x) +@mark.least_squares @dataclass(frozen=True) class FreudensteinRoth(BenchmarkFunction): """Freudenstein and Roth function.""" @@ -912,11 +913,11 @@ class FreudensteinRoth(BenchmarkFunction): min_n_params = 2 max_n_params = 2 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return freudenstein_roth(x) +@mark.least_squares @dataclass(frozen=True) class Bard(BenchmarkFunction): """Bard function.""" @@ -925,11 +926,11 @@ class Bard(BenchmarkFunction): min_n_params = 3 max_n_params = 3 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return bard(x, y=y_vec) +@mark.least_squares @dataclass(frozen=True) class KowalikOsborne(BenchmarkFunction): """Kowalik and Osborne function.""" @@ -938,11 +939,11 @@ class KowalikOsborne(BenchmarkFunction): min_n_params = 4 max_n_params = 4 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return kowalik_osborne(x, y1=v_vec, y2=y2_vec) +@mark.least_squares @dataclass(frozen=True) class Meyer(BenchmarkFunction): """Meyer function.""" @@ -951,11 +952,11 @@ class Meyer(BenchmarkFunction): min_n_params = 3 max_n_params = 3 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return meyer(x, y=y3_vec) +@mark.least_squares @dataclass(frozen=True) class Watson(BenchmarkFunction): """Watson function.""" @@ -964,11 +965,11 @@ class Watson(BenchmarkFunction): min_n_params = 2 max_n_params = 31 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return watson(x) +@mark.least_squares @dataclass(frozen=True) class Box3D(BenchmarkFunction): """Box three-dimensional function.""" @@ -980,11 +981,11 @@ class Box3D(BenchmarkFunction): min_n_params = 3 max_n_params = 3 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return box_3d(x, dim_out=self.dim_out) +@mark.least_squares @dataclass(frozen=True) class JennrichSampson(BenchmarkFunction): """Jennrich and Sampson function.""" @@ -996,11 +997,11 @@ class JennrichSampson(BenchmarkFunction): min_n_params = 2 max_n_params = 2 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return jennrich_sampson(x, dim_out=self.dim_out) +@mark.least_squares @dataclass(frozen=True) class BrownDennis(BenchmarkFunction): """Brown and Dennis function.""" @@ -1012,11 +1013,11 @@ class BrownDennis(BenchmarkFunction): min_n_params = 4 max_n_params = 4 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return brown_dennis(x, dim_out=self.dim_out) +@mark.least_squares @dataclass(frozen=True) class Chebyquad(BenchmarkFunction): """Chebyquad function.""" @@ -1026,7 +1027,6 @@ class Chebyquad(BenchmarkFunction): differentiable = True - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return chebyquad(x, dim_out=self.dim_out) @@ -1034,17 +1034,18 @@ def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +@mark.least_squares @dataclass(frozen=True) class BrownAlmostLinear(BenchmarkFunction): """Brown almost-linear function.""" differentiable = True - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return brown_almost_linear(x) +@mark.least_squares @dataclass(frozen=True) class OsborneOne(BenchmarkFunction): """Osborne 1 function.""" @@ -1053,11 +1054,11 @@ class OsborneOne(BenchmarkFunction): min_n_params = 5 max_n_params = 5 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return osborne_one(x, y=y4_vec) +@mark.least_squares @dataclass(frozen=True) class OsborneTwo(BenchmarkFunction): """Osborne 2 function.""" @@ -1066,11 +1067,11 @@ class OsborneTwo(BenchmarkFunction): min_n_params = 11 max_n_params = 11 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return osborne_two(x, y=y5_vec) +@mark.least_squares @dataclass(frozen=True) class Bdqrtic(BenchmarkFunction): """Banded quartic function (BDQRTIC).""" @@ -1078,11 +1079,11 @@ class Bdqrtic(BenchmarkFunction): differentiable = True min_n_params = 5 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return bdqrtic(x) +@mark.least_squares @dataclass(frozen=True) class Cube(BenchmarkFunction): """Cube function.""" @@ -1090,22 +1091,22 @@ class Cube(BenchmarkFunction): differentiable = True min_n_params = 2 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return cube(x) +@mark.least_squares @dataclass(frozen=True) class Mancino(BenchmarkFunction): """Mancino function.""" differentiable = True - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return mancino(x) +@mark.least_squares @dataclass(frozen=True) class HeartEight(BenchmarkFunction): """Heart function with eight parameters.""" @@ -1114,7 +1115,6 @@ class HeartEight(BenchmarkFunction): min_n_params = 8 max_n_params = 8 - @mark.least_squares def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: return heart_eight(x, y=heart_eight_y_vec) diff --git a/src/optimagic/mark.py b/src/optimagic/mark.py index 6c43e91a1..efb116f22 100644 --- a/src/optimagic/mark.py +++ b/src/optimagic/mark.py @@ -20,17 +20,29 @@ def scalar(func: ScalarFuncT) -> ScalarFuncT: - """Mark a function as a scalar function.""" + """Mark a function as a scalar function. + + Can also be applied to a subclass of ``om.BenchmarkFunction``. + + """ return _mark_problem_type(func, AggregationLevel.SCALAR) def least_squares(func: VectorFuncT) -> VectorFuncT: - """Mark a function as a least squares function.""" + """Mark a function as a least squares function. + + Can also be applied to a subclass of ``om.BenchmarkFunction``. + + """ return _mark_problem_type(func, AggregationLevel.LEAST_SQUARES) def likelihood(func: VectorFuncT) -> VectorFuncT: - """Mark a function as a likelihood function.""" + """Mark a function as a likelihood function. + + Can also be applied to a subclass of ``om.BenchmarkFunction``. + + """ return _mark_problem_type(func, AggregationLevel.LIKELIHOOD) diff --git a/tests/optimagic/benchmarking/test_benchmark_problem.py b/tests/optimagic/benchmarking/test_benchmark_problem.py index 5a4c1cccb..67c862832 100644 --- a/tests/optimagic/benchmarking/test_benchmark_problem.py +++ b/tests/optimagic/benchmarking/test_benchmark_problem.py @@ -44,6 +44,7 @@ def gradient(x): return gradient +@om.mark.least_squares @dataclass(frozen=True) class ShiftedResiduals(BenchmarkFunction): shift: float = 1.0 @@ -51,7 +52,6 @@ class ShiftedResiduals(BenchmarkFunction): min_n_params = 2 max_n_params = 4 - @om.mark.least_squares def fun(self, x): return np.append(x - self.shift, x[0] * x[1]) @@ -72,8 +72,8 @@ def gradient(x): return None +@om.mark.likelihood class Contributions(BenchmarkFunction): - @om.mark.likelihood def fun(self, x): return np.array([x[0] ** 2, x[1] ** 2 + x[0], 3.0]) @@ -123,12 +123,44 @@ def constraints(self, n_params): # noqa: ARG002 # ====================================================================================== -def test_problem_type_is_read_from_mark_of_fun(): +def test_problem_type_is_read_from_mark_of_class(): assert Sphere().problem_type == SCALAR assert ShiftedResiduals().problem_type == LEAST_SQUARES assert Contributions().problem_type == LIKELIHOOD +def test_mark_keeps_the_class(): + assert isinstance(ShiftedResiduals, type) + assert ShiftedResiduals(shift=2.0) == ShiftedResiduals(shift=2.0) + + +def test_mark_is_inherited_by_subclasses(): + class Child(ShiftedResiduals): + def fun(self, x): + return x - self.shift + + assert Child().problem_type == LEAST_SQUARES + + +def test_mark_of_subclass_overrides_mark_of_parent(): + @om.mark.scalar + class Child(ShiftedResiduals): + def fun(self, x): + return float((x - self.shift) @ (x - self.shift)) + + assert Child().problem_type == SCALAR + assert ShiftedResiduals().problem_type == LEAST_SQUARES + + +def test_mark_on_fun_is_not_used(): + class MarkedMethod(BenchmarkFunction): + @om.mark.least_squares + def fun(self, x): + return x - 1 + + assert MarkedMethod().problem_type == SCALAR + + def test_default_properties_are_unknown(): function = Contributions() assert function.differentiable is None @@ -221,7 +253,7 @@ def fun(self, x): return x - 1 problem = BenchmarkProblem(function=ForgottenMark(), start_params=np.zeros(3)) - with pytest.raises(ValueError, match=r"mark `fun` with `om.mark.least_squares`"): + with pytest.raises(ValueError, match=r"mark the benchmark function class"): problem.start_fun # noqa: B018 diff --git a/tests/optimagic/benchmarking/test_run_benchmark.py b/tests/optimagic/benchmarking/test_run_benchmark.py index 742c4b61b..aee02fe1c 100644 --- a/tests/optimagic/benchmarking/test_run_benchmark.py +++ b/tests/optimagic/benchmarking/test_run_benchmark.py @@ -154,8 +154,8 @@ def test_run_benchmark_uses_the_derivative_for_the_solver_type(): requested = [] called = [] + @om.mark.least_squares class Residuals(BenchmarkFunction): - @om.mark.least_squares def fun(self, x): return x - 1 From 376af4bbfc641aa7a6b9765fb7cff6d1a7b4bf9f Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Tue, 24 Nov 2026 09:57:42 +0100 Subject: [PATCH 4/6] Convert the Cartis-Roberts functions to classes and drop CallableBenchmarkFunction. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each Cartis-Roberts function is a BenchmarkFunction subclass. The six functions that are jitted with numba stay functions and their classes only call them. The four problems that reuse Moré-Wild functions use the Moré-Wild classes. The residuals of all 60 problems are bit-identical before and after the conversion. CallableBenchmarkFunction has no users left and is removed, so benchmark functions are always defined as classes. Co-Authored-By: Claude Opus 5.5 --- docs/source/how_to/how_to_benchmarking.ipynb | 2 +- docs/source/reference/index.md | 2 - src/optimagic/__init__.py | 2 - .../benchmarking/benchmark_problem.py | 74 +- src/optimagic/benchmarking/cartis_roberts.py | 2505 +++++++++-------- .../benchmarking/test_benchmark_problem.py | 72 +- .../benchmarking/test_cartis_roberts.py | 7 + 7 files changed, 1397 insertions(+), 1267 deletions(-) diff --git a/docs/source/how_to/how_to_benchmarking.ipynb b/docs/source/how_to/how_to_benchmarking.ipynb index 3a52c7fef..a147ccc25 100644 --- a/docs/source/how_to/how_to_benchmarking.ipynb +++ b/docs/source/how_to/how_to_benchmarking.ipynb @@ -484,7 +484,7 @@ "\n", "If you have a closed form derivative, override `jac(solver_type)`. It returns the derivative function for one type of optimizer, e.g. the jacobian of the residuals for least-squares optimizers and the gradient of the sum of squared residuals for scalar optimizers, or `None` if there is no closed form derivative for that type.\n", "\n", - "To turn an existing Python function into a benchmark function without writing a class, use `om.CallableBenchmarkFunction`." + "If your objective function already exists as a Python function, `fun` can simply call it." ] } ], diff --git a/docs/source/reference/index.md b/docs/source/reference/index.md index 61f0a8d4d..fe741516a 100644 --- a/docs/source/reference/index.md +++ b/docs/source/reference/index.md @@ -199,8 +199,6 @@ .. autoclass:: BenchmarkFunction :members: - .. autoclass:: CallableBenchmarkFunction - ``` ```{eval-rst} diff --git a/src/optimagic/__init__.py b/src/optimagic/__init__.py index e056e75a0..db5d2b9a8 100644 --- a/src/optimagic/__init__.py +++ b/src/optimagic/__init__.py @@ -6,7 +6,6 @@ BenchmarkFunction, BenchmarkProblem, BenchmarkSolution, - CallableBenchmarkFunction, ) from optimagic.benchmarking.benchmark_reports import ( convergence_report, @@ -83,7 +82,6 @@ "run_benchmark", "get_benchmark_problems", "BenchmarkFunction", - "CallableBenchmarkFunction", "BenchmarkProblem", "BenchmarkSolution", "BenchmarkResult", diff --git a/src/optimagic/benchmarking/benchmark_problem.py b/src/optimagic/benchmarking/benchmark_problem.py index 1acb6e750..c1490f2f2 100644 --- a/src/optimagic/benchmarking/benchmark_problem.py +++ b/src/optimagic/benchmarking/benchmark_problem.py @@ -52,8 +52,11 @@ class BenchmarkFunction(ABC): scalar function. The mark is inherited by subclasses. Parameters of a family of functions (e.g. the number of residuals) are attributes - of the subclass. Use ``CallableBenchmarkFunction`` to wrap an existing Python - function instead of writing a class. + of the subclass. If the objective function already exists as a Python function, + ``fun`` simply calls it. + + A benchmark function is not tied to one number of parameters. The number of + parameters is fixed by the start parameters of a ``BenchmarkProblem``. Example: A least-squares function for any number of parameters:: @@ -68,9 +71,6 @@ class Sphere(om.BenchmarkFunction): def fun(self, x): return x - A benchmark function is not tied to one number of parameters. The number of - parameters is fixed by the start parameters of a ``BenchmarkProblem``. - """ differentiable: bool | None = None @@ -201,67 +201,6 @@ def constraints(self, n_params: int) -> list[Constraint]: # noqa: ARG002 return [] -@dataclass(frozen=True) -class CallableBenchmarkFunction(BenchmarkFunction): - """Benchmark function that wraps existing Python functions. - - This is the quickest way to turn your own objective function into a benchmark - function. The functions are marked in the same way as for ``minimize``. - - """ - - func: ObjectiveFunction - """The function that is wrapped. Takes parameters of shape (n_params,). It has to be - marked with ``om.mark.least_squares`` or ``om.mark.likelihood`` if it returns - least-squares residuals or likelihood contributions.""" - - jac_funcs: Sequence[DerivativeFunction] = () - """Closed form first derivatives of ``func``. Each function is marked with the type - of optimizer it is for (``om.mark.scalar``, ``om.mark.least_squares`` or - ``om.mark.likelihood``); functions without a mark are for scalar optimizers.""" - - differentiable: bool | None = None - """Whether the function is differentiable at every point where it is defined. None - if this is not known.""" - - convex: bool | None = None - """Whether the function is convex. None if this is not known.""" - - multimodal: bool | None = None - """Whether the function has local minima that are not global minima. None if this is - not known.""" - - min_n_params: int = 1 - """The smallest number of parameters the function supports.""" - - max_n_params: int | None = None - """The largest number of parameters the function supports. None if there is no upper - limit.""" - - def __post_init__(self) -> None: - if not callable(self.func): - raise TypeError(f"func must be callable, not {type(self.func)}.") - solver_types = [infer_aggregation_level(func) for func in self.jac_funcs] - if len(set(solver_types)) < len(solver_types): - raise ValueError( - "jac_funcs contains more than one derivative for the same type of " - "optimizer." - ) - - def fun(self, x: NDArray[np.float64]) -> float | NDArray[np.float64]: - return self.func(x) - - @property - def problem_type(self) -> AggregationLevel: - return infer_aggregation_level(self.func) - - def jac(self, solver_type: AggregationLevel) -> DerivativeFunction | None: - for func in self.jac_funcs: - if infer_aggregation_level(func) == solver_type: - return func - return None - - def aggregate_function_value( value: float | NDArray[np.float64], problem_type: AggregationLevel ) -> float: @@ -285,8 +224,7 @@ def aggregate_function_value( "A scalar benchmark function returned an array with " f"{np.size(value)} entries. If the function returns least-squares " "residuals or likelihood contributions, mark the benchmark function " - "class (or the function wrapped by CallableBenchmarkFunction) with " - "`om.mark.least_squares` or `om.mark.likelihood`." + "class with `om.mark.least_squares` or `om.mark.likelihood`." ) return float(np.asarray(value, dtype=np.float64).reshape(-1)[0]) arr = np.asarray(value, dtype=np.float64) diff --git a/src/optimagic/benchmarking/cartis_roberts.py b/src/optimagic/benchmarking/cartis_roberts.py index edf732c6d..688285f5b 100644 --- a/src/optimagic/benchmarking/cartis_roberts.py +++ b/src/optimagic/benchmarking/cartis_roberts.py @@ -15,17 +15,22 @@ """ -from collections.abc import Callable -from functools import partial +from dataclasses import dataclass import numpy as np from numpy.typing import NDArray from optimagic import mark from optimagic.benchmarking.benchmark_problem import ( + BenchmarkFunction, BenchmarkProblem, BenchmarkSolution, - CallableBenchmarkFunction, +) +from optimagic.benchmarking.more_wild import ( + BrownAlmostLinear, + LinearFullRank, + LinearRankOne, + Watson, ) from optimagic.config import IS_NUMBA_INSTALLED from optimagic.parameters.bounds import Bounds @@ -38,191 +43,223 @@ def njit(func): return func -from optimagic.benchmarking.more_wild import ( - brown_almost_linear, - linear_full_rank, - linear_rank_one, - watson, -) +@mark.least_squares +@dataclass(frozen=True) +class Luksan11(BenchmarkFunction): + """The LUKSAN11 function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(2 * (dim_in - 1)) + fvec[::2] = 20 * x[:-1] / (1 + x[:-1] ** 2) - 10 * x[1:] + fvec[1::2] = x[:-1] - 1 + return fvec @mark.least_squares -def luksan11(x): - dim_in = len(x) - fvec = np.zeros(2 * (dim_in - 1)) - fvec[::2] = 20 * x[:-1] / (1 + x[:-1] ** 2) - 10 * x[1:] - fvec[1::2] = x[:-1] - 1 - return fvec +@dataclass(frozen=True) +class Luksan12(BenchmarkFunction): + """The LUKSAN12 function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + n = (dim_in - 2) // 3 + i = np.arange(0, 3 * n, 3) + fvec = np.zeros(6 * n) + fvec[::6] = 10 * (x[i] ** 2 - x[i + 1]) + fvec[1::6] = x[i + 2] - 1 + fvec[2::6] = (x[i + 3] - 1) ** 2 + fvec[3::6] = (x[i + 4] - 1) ** 3 + fvec[4::6] = x[i] ** 2 * x[i + 3] + np.sin(x[i + 3] - x[i + 4]) - 10 + fvec[5::6] = x[i + 1] + (x[i + 2] ** 4) * (x[i + 3] ** 2) - 20 + return fvec @mark.least_squares -def luksan12(x): - dim_in = len(x) - n = (dim_in - 2) // 3 - i = np.arange(0, 3 * n, 3) - fvec = np.zeros(6 * n) - fvec[::6] = 10 * (x[i] ** 2 - x[i + 1]) - fvec[1::6] = x[i + 2] - 1 - fvec[2::6] = (x[i + 3] - 1) ** 2 - fvec[3::6] = (x[i + 4] - 1) ** 3 - fvec[4::6] = x[i] ** 2 * x[i + 3] + np.sin(x[i + 3] - x[i + 4]) - 10 - fvec[5::6] = x[i + 1] + (x[i + 2] ** 4) * (x[i + 3] ** 2) - 20 - return fvec +@dataclass(frozen=True) +class Luksan13(BenchmarkFunction): + """The LUKSAN13 function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + n = (dim_in - 2) // 3 + fvec = np.zeros(n * 7) + i = np.arange(n) + k = i * 7 + fvec[k] = 10 * (x[3 * i] ** 2 - x[3 * i + 1]) + fvec[k + 1] = 10 * (x[3 * i + 1] ** 2 - x[3 * i + 2]) + fvec[k + 2] = (x[3 * i + 2] - x[3 * i + 3]) ** 2 + fvec[k + 3] = (x[3 * i + 3] - x[3 * i + 4]) ** 2 + fvec[k + 4] = x[3 * i] + x[3 * i + 1] ** 2 + x[3 * i + 2] - 30 + fvec[k + 5] = x[3 * i + 1] - x[3 * i + 2] ** 2 + x[3 * i + 3] - 10 + fvec[k + 6] = x[3 * i + 1] * x[3 * i + 4] - 10 + + return fvec @mark.least_squares -def luksan13(x): - dim_in = len(x) - n = (dim_in - 2) // 3 - fvec = np.zeros(n * 7) - i = np.arange(n) - k = i * 7 - fvec[k] = 10 * (x[3 * i] ** 2 - x[3 * i + 1]) - fvec[k + 1] = 10 * (x[3 * i + 1] ** 2 - x[3 * i + 2]) - fvec[k + 2] = (x[3 * i + 2] - x[3 * i + 3]) ** 2 - fvec[k + 3] = (x[3 * i + 3] - x[3 * i + 4]) ** 2 - fvec[k + 4] = x[3 * i] + x[3 * i + 1] ** 2 + x[3 * i + 2] - 30 - fvec[k + 5] = x[3 * i + 1] - x[3 * i + 2] ** 2 + x[3 * i + 3] - 10 - fvec[k + 6] = x[3 * i + 1] * x[3 * i + 4] - 10 +@dataclass(frozen=True) +class Luksan14(BenchmarkFunction): + """The LUKSAN14 function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = 7 * (dim_in - 2) // 3 + fvec = np.zeros(dim_out, dtype=np.float64) + + for i in range(0, dim_in - 2, 3): + k = (i // 3) * 7 + fvec[k : k + 7] = [ + 10 * (x[i] ** 2 - x[i + 1]), + x[i + 1] + x[i + 2] - 2, + x[i + 3] - 1, + x[i + 4] - 1, + x[i] + 3 * x[i + 1], + x[i + 2] + x[i + 3] - 2 * x[i + 4], + 10 * (x[i + 1] ** 2 - x[i + 4]), + ] - return fvec + return fvec @mark.least_squares -def luksan14(x): - dim_in = len(x) - dim_out = 7 * (dim_in - 2) // 3 - fvec = np.zeros(dim_out, dtype=np.float64) - - for i in range(0, dim_in - 2, 3): - k = (i // 3) * 7 - fvec[k : k + 7] = [ - 10 * (x[i] ** 2 - x[i + 1]), - x[i + 1] + x[i + 2] - 2, - x[i + 3] - 1, - x[i + 4] - 1, - x[i] + 3 * x[i + 1], - x[i + 2] + x[i + 3] - 2 * x[i + 4], - 10 * (x[i + 1] ** 2 - x[i + 4]), - ] +@dataclass(frozen=True) +class Luksan15(BenchmarkFunction): + """The LUKSAN15 function from the CUTEst collection.""" - return fvec + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = (dim_in - 2) * 2 + temp = np.zeros((dim_out, 3), dtype=np.float64) + y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) + for p in range(1, 4): + k = 0 + for i in range(0, dim_in - 2, 2): + for j in range(1, 5): + temp[k, p - 1] = (p**2 / j) * np.abs( + x[i] * (x[i + 1] ** 2) * (x[i + 2] ** 3) * (x[i + 3] ** 4) + ) ** (1 / (p * j)) -@mark.least_squares -def luksan15(x): - dim_in = len(x) - dim_out = (dim_in - 2) * 2 - temp = np.zeros((dim_out, 3), dtype=np.float64) - y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) + k += 1 - for p in range(1, 4): - k = 0 - for i in range(0, dim_in - 2, 2): - for j in range(1, 5): - temp[k, p - 1] = (p**2 / j) * np.abs( - x[i] * (x[i + 1] ** 2) * (x[i + 2] ** 3) * (x[i + 3] ** 4) - ) ** (1 / (p * j)) + fvec = y - np.sum(temp, axis=1) - k += 1 + return fvec - fvec = y - np.sum(temp, axis=1) - return fvec +@mark.least_squares +@dataclass(frozen=True) +class Luksan16(BenchmarkFunction): + """The LUKSAN16 function from the CUTEst collection.""" + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = (dim_in - 2) * 2 + temp = np.zeros((dim_out, 3), dtype=np.float64) + y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) -@mark.least_squares -def luksan16(x): - dim_in = len(x) - dim_out = (dim_in - 2) * 2 - temp = np.zeros((dim_out, 3), dtype=np.float64) - y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) - - for p in range(1, 4): - k = 0 - for i in range(0, dim_in - 2, 2): - for j in range(1, 5): - temp[k, p - 1] = (p**2 / j) * np.exp( - (x[i] + 2 * x[i + 1] + 3 * x[i + 2] + 4 * x[i + 3]) * (1 / (p * j)) - ) - k += 1 + for p in range(1, 4): + k = 0 + for i in range(0, dim_in - 2, 2): + for j in range(1, 5): + temp[k, p - 1] = (p**2 / j) * np.exp( + (x[i] + 2 * x[i + 1] + 3 * x[i + 2] + 4 * x[i + 3]) + * (1 / (p * j)) + ) + k += 1 - fvec = y - np.sum(temp, axis=1) + fvec = y - np.sum(temp, axis=1) - return fvec + return fvec @mark.least_squares -def luksan17(x): - dim_in = len(x) - dim_out = (dim_in - 2) * 2 - temp = np.zeros((dim_out, 4), dtype=np.float64) - y = np.tile([30.6, 72.2, 124.4, 187.4], dim_out // 4) - - for q in range(1, 5): - k = 0 - for i in range(-1, dim_in - 4, 2): - for j in range(1, 5): - temp[k, q - 1] += -j * q**2 * np.sin(x[i + q]) + j**2 * q * np.cos( - x[i + q] - ) - k += 1 +@dataclass(frozen=True) +class Luksan17(BenchmarkFunction): + """The LUKSAN17 function from the CUTEst collection.""" - fvec = y - np.sum(temp, axis=1) + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = (dim_in - 2) * 2 + temp = np.zeros((dim_out, 4), dtype=np.float64) + y = np.tile([30.6, 72.2, 124.4, 187.4], dim_out // 4) - return fvec + for q in range(1, 5): + k = 0 + for i in range(-1, dim_in - 4, 2): + for j in range(1, 5): + temp[k, q - 1] += -j * q**2 * np.sin(x[i + q]) + j**2 * q * np.cos( + x[i + q] + ) + k += 1 + fvec = y - np.sum(temp, axis=1) -@mark.least_squares -def luksan21(x): - dim_out = len(x) - h = 1 / (dim_out + 1) - fvec = np.zeros(dim_out, dtype=np.float64) + return fvec - fvec[0] = 2 * x[0] + 0.5 * h**2 * (x[0] + h + 1) ** 3 - x[1] + 1 - for i in range(1, dim_out - 1): - fvec[i] = ( - 2 * x[i] - + 0.5 * h**2 * (x[i] + h * (i + 1) + 1) ** 3 - - x[i - 1] - - x[i + 1] - + 1 - ) - fvec[-1] = 2 * x[-1] + 0.5 * h**2 * (x[-1] + h * dim_out + 1) ** 3 - x[-2] + 1 - return fvec +@mark.least_squares +@dataclass(frozen=True) +class Luksan21(BenchmarkFunction): + """The LUKSAN21 function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_out = len(x) + h = 1 / (dim_out + 1) + fvec = np.zeros(dim_out, dtype=np.float64) + + fvec[0] = 2 * x[0] + 0.5 * h**2 * (x[0] + h + 1) ** 3 - x[1] + 1 + for i in range(1, dim_out - 1): + fvec[i] = ( + 2 * x[i] + + 0.5 * h**2 * (x[i] + h * (i + 1) + 1) ** 3 + - x[i - 1] + - x[i + 1] + + 1 + ) + fvec[-1] = 2 * x[-1] + 0.5 * h**2 * (x[-1] + h * dim_out + 1) ** 3 - x[-2] + 1 + + return fvec @mark.least_squares -def luksan22(x): - dim_out = 2 * len(x) - 2 - fvec = np.zeros(dim_out) - fvec[0] = x[0] - 1 - fvec[1:-1:2] = 10 * (x[:-2] ** 2 - x[1:-1]) - fvec[2:-1:2] = 2 * np.exp(-((x[:-2] - x[1:-1]) ** 2)) + np.exp( - -2 * (x[1:-1] - x[2:]) ** 2 - ) - fvec[-1] = -10 * (x[-2] ** 2) - return fvec +@dataclass(frozen=True) +class Luksan22(BenchmarkFunction): + """The LUKSAN22 function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_out = 2 * len(x) - 2 + fvec = np.zeros(dim_out) + fvec[0] = x[0] - 1 + fvec[1:-1:2] = 10 * (x[:-2] ** 2 - x[1:-1]) + fvec[2:-1:2] = 2 * np.exp(-((x[:-2] - x[1:-1]) ** 2)) + np.exp( + -2 * (x[1:-1] - x[2:]) ** 2 + ) + fvec[-1] = -10 * (x[-2] ** 2) + return fvec @mark.least_squares -def morebvne(x): - dim_in = len(x) - h = 1 / (dim_in + 1) - i = np.arange(1, dim_in + 1) - fvec = np.zeros(dim_in) - - fvec[0] = 2 * x[0] - x[1] + h**2 / 2 * (x[0] + i[0] * h + 1) ** 3 - fvec[1:-1] = ( - 2 * x[1:-1] - x[:-2] - x[2:] + h**2 / 2 * (x[1:-1] + i[1:-1] * h + 1) ** 3 - ) - fvec[-1] = 2 * x[-2] - x[-2] + h**2 / 2 * (x[-1] + i[-1] * h + 1) ** 3 +@dataclass(frozen=True) +class Morebvne(BenchmarkFunction): + """The MOREBVNE function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + h = 1 / (dim_in + 1) + i = np.arange(1, dim_in + 1) + fvec = np.zeros(dim_in) + + fvec[0] = 2 * x[0] - x[1] + h**2 / 2 * (x[0] + i[0] * h + 1) ** 3 + fvec[1:-1] = ( + 2 * x[1:-1] - x[:-2] - x[2:] + h**2 / 2 * (x[1:-1] + i[1:-1] * h + 1) ** 3 + ) + fvec[-1] = 2 * x[-2] - x[-2] + h**2 / 2 * (x[-1] + i[-1] * h + 1) ** 3 - return fvec + return fvec -@mark.least_squares @njit def flosp2(x, a, b, ra=1.0e7): n = 5 @@ -336,255 +373,320 @@ def flosp2(x, a, b, ra=1.0e7): @mark.least_squares -def oscigrne(x): - dim_in = len(x) - rho = 500 +@dataclass(frozen=True) +class Flosp2(BenchmarkFunction): + """The FLOSP2 function from the CUTEst collection.""" - fvec = np.zeros(dim_in) - fvec[0] = 0.5 * x[0] - 0.5 - 4 * rho * (x[1] - 2.0 * x[0] ** 2 + 1.0) * x[0] - fvec[1:-1] = ( - 2 * rho * (x[1:-1] - 2.0 * x[:-2] ** 2 + 1.0) - - 4 * rho * (x[2:] - 2.0 * x[:-2] ** 2 + 1.0) * x[2:] - ) - fvec[-1] = 2 * rho * (x[-1] - 2.0 * x[-2] ** 2 + 1.0) - - return fvec - - -@mark.least_squares -def spmsqrt(x): - m = (len(x) + 2) // 3 - xmat = np.diag(x[2:-1:3], -1) + np.diag(x[::3], 0) + np.diag(x[1:-2:3], 1) - - b = np.zeros((m, m), dtype=np.float64) - b[0, 0] = np.sin(1) - b[0, 1] = np.sin(4) - k = 2 - for i in range(1, m - 1): - k += 1 - b[i, i - 1] = np.sin(k**2) - k += 1 - b[i, i] = np.sin(k**2) - k += 1 - b[i, i + 1] = np.sin(k**2) - k += 1 - b[-1, -2] = np.sin(k**2) - k += 1 - b[-1, -1] = np.sin(k**2) + a: tuple[float, float, float] + """Coefficients of the boundary conditions.""" - fmat = np.zeros((m, m), dtype=np.float64) - fmat[0, 0] = xmat[0, 0] ** 2 + xmat[0, 1] * xmat[1, 0] - fmat[0, 1] = xmat[0, 0] * xmat[0, 1] + xmat[0, 1] * xmat[1, 1] - fmat[0, 2] = xmat[0, 1] * xmat[1, 2] + b: tuple[float, float, float] + """Coefficients of the boundary conditions.""" - fmat[1, 0] = xmat[1, 0] * xmat[0, 0] + xmat[1, 1] * xmat[1, 0] - fmat[1, 1] = xmat[1, 0] * xmat[0, 1] + xmat[1, 1] ** 2 + xmat[1, 2] * xmat[2, 1] - fmat[1, 2] = xmat[1, 1] * xmat[1, 2] + xmat[1, 2] * xmat[2, 2] - fmat[1, 3] = xmat[1, 2] * xmat[2, 3] + ra: float = 1.0e7 + """The Rayleigh number.""" - for i in range(2, m - 2): - fmat[i, i - 2] = xmat[i, i - 1] * xmat[i - 1, i - 2] - fmat[i, i - 1] = ( - xmat[i, i - 1] * xmat[i - 1, i - 1] + xmat[i, i] * xmat[i, i - 1] + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return flosp2( + x, + np.array(self.a, dtype=np.float64), + np.array(self.b, dtype=np.float64), + self.ra, ) - fmat[i, i] = ( - xmat[i, i - 1] * xmat[i - 1, i] - + xmat[i, i] ** 2 - + xmat[i, i + 1] * xmat[i + 1, i] - ) - fmat[i, i + 1] = ( - xmat[i, i] * xmat[i, i + 1] + xmat[i, i + 1] * xmat[i + 1, i + 1] - ) - fmat[i, i + 2] = xmat[i, i + 1] * xmat[i + 1, i + 2] - - fmat[-2, -4] = xmat[-2, -3] * xmat[-3, -4] - fmat[-2, -3] = xmat[-2, -3] * xmat[-3, -3] + xmat[-2, -2] * xmat[-2, -3] - fmat[-2, -2] = ( - xmat[-2, -3] * xmat[-3, -2] + xmat[-2, -2] ** 2 + xmat[-2, -1] * xmat[-1, -2] - ) - fmat[-2, -1] = xmat[-2, -2] * xmat[-2, -1] + xmat[-2, -1] * xmat[-1, -1] - fmat[-1, -3] = xmat[-1, -2] * xmat[-2, -3] - fmat[-1, -2] = xmat[-1, -2] * xmat[-2, -2] + xmat[-1, -1] * xmat[-1, -2] - fmat[-1, -1] = xmat[-1, -2] * xmat[-2, -1] + xmat[-1, -1] ** 2 - fmat[0, 0] -= b[0, 0] ** 2 + b[0, 1] * b[1, 0] - for i in range(1, m - 1): - fmat[i, i] -= ( - b[i, i] ** 2 + b[i - 1, i] * b[i, i - 1] + b[i + 1, i] * b[i, i + 1] +@mark.least_squares +@dataclass(frozen=True) +class Oscigrne(BenchmarkFunction): + """The OSCIGRNE function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + rho = 500 + + fvec = np.zeros(dim_in) + fvec[0] = 0.5 * x[0] - 0.5 - 4 * rho * (x[1] - 2.0 * x[0] ** 2 + 1.0) * x[0] + fvec[1:-1] = ( + 2 * rho * (x[1:-1] - 2.0 * x[:-2] ** 2 + 1.0) + - 4 * rho * (x[2:] - 2.0 * x[:-2] ** 2 + 1.0) * x[2:] ) - fmat[-1, -1] -= b[-1, -1] ** 2 + b[-2, -1] * b[-1, -2] - for i in range(m - 1): - fmat[i + 1, i] -= b[i + 1, i] * b[i, i] + b[i + 1, i + 1] * b[i + 1, i] - for i in range(1, m): - fmat[i - 1, i] -= b[i - 1, i] * b[i, i] + b[i - 1, i - 1] * b[i - 1, i] - for i in range(1, m - 1): - fmat[i + 1, i - 1] -= b[i + 1, i] * b[i, i - 1] - for i in range(1, m - 1): - fmat[i - 1, i + 1] -= b[i - 1, i] * b[i, i + 1] + fvec[-1] = 2 * rho * (x[-1] - 2.0 * x[-2] ** 2 + 1.0) - return fmat.flatten() + return fvec @mark.least_squares -def semicon2(x): - n = len(x) // 1 - ln = 9 * n // 10 - - lambda_ = 0.2 - a = -0.00009 - b = 0.00001 - ua = 0.0 - ub = 700.0 - ca = 1e12 - cb = 1e13 - beta = 40.0 - - h = (b - a) / (n + 1) - lb = lambda_ * beta - lua = lambda_ * ua - lub = lambda_ * ub - - xvec = np.zeros(n + 2, dtype=np.float64) - xvec[0] = lua - xvec[1:-1] = x - xvec[-1] = lub - - fvec = np.zeros(n, dtype=np.float64) - for i in range(1, ln + 1): - fvec[i - 1] = ( - xvec[i - 1] - - 2 * xvec[i] - + xvec[i + 1] - + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) - - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) - - lambda_ * (h**2) * ca - ) - for i in range(ln + 1, n + 1): - fvec[i - 1] = ( - xvec[i - 1] - - 2 * xvec[i] - + xvec[i + 1] - - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) - + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) - + lambda_ * (h**2) * cb +@dataclass(frozen=True) +class Spmsqrt(BenchmarkFunction): + """The SPMSQRT function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + m = (len(x) + 2) // 3 + xmat = np.diag(x[2:-1:3], -1) + np.diag(x[::3], 0) + np.diag(x[1:-2:3], 1) + + b = np.zeros((m, m), dtype=np.float64) + b[0, 0] = np.sin(1) + b[0, 1] = np.sin(4) + k = 2 + for i in range(1, m - 1): + k += 1 + b[i, i - 1] = np.sin(k**2) + k += 1 + b[i, i] = np.sin(k**2) + k += 1 + b[i, i + 1] = np.sin(k**2) + k += 1 + b[-1, -2] = np.sin(k**2) + k += 1 + b[-1, -1] = np.sin(k**2) + + fmat = np.zeros((m, m), dtype=np.float64) + fmat[0, 0] = xmat[0, 0] ** 2 + xmat[0, 1] * xmat[1, 0] + fmat[0, 1] = xmat[0, 0] * xmat[0, 1] + xmat[0, 1] * xmat[1, 1] + fmat[0, 2] = xmat[0, 1] * xmat[1, 2] + + fmat[1, 0] = xmat[1, 0] * xmat[0, 0] + xmat[1, 1] * xmat[1, 0] + fmat[1, 1] = xmat[1, 0] * xmat[0, 1] + xmat[1, 1] ** 2 + xmat[1, 2] * xmat[2, 1] + fmat[1, 2] = xmat[1, 1] * xmat[1, 2] + xmat[1, 2] * xmat[2, 2] + fmat[1, 3] = xmat[1, 2] * xmat[2, 3] + + for i in range(2, m - 2): + fmat[i, i - 2] = xmat[i, i - 1] * xmat[i - 1, i - 2] + fmat[i, i - 1] = ( + xmat[i, i - 1] * xmat[i - 1, i - 1] + xmat[i, i] * xmat[i, i - 1] + ) + fmat[i, i] = ( + xmat[i, i - 1] * xmat[i - 1, i] + + xmat[i, i] ** 2 + + xmat[i, i + 1] * xmat[i + 1, i] + ) + fmat[i, i + 1] = ( + xmat[i, i] * xmat[i, i + 1] + xmat[i, i + 1] * xmat[i + 1, i + 1] + ) + fmat[i, i + 2] = xmat[i, i + 1] * xmat[i + 1, i + 2] + + fmat[-2, -4] = xmat[-2, -3] * xmat[-3, -4] + fmat[-2, -3] = xmat[-2, -3] * xmat[-3, -3] + xmat[-2, -2] * xmat[-2, -3] + fmat[-2, -2] = ( + xmat[-2, -3] * xmat[-3, -2] + + xmat[-2, -2] ** 2 + + xmat[-2, -1] * xmat[-1, -2] ) + fmat[-2, -1] = xmat[-2, -2] * xmat[-2, -1] + xmat[-2, -1] * xmat[-1, -1] - return fvec + fmat[-1, -3] = xmat[-1, -2] * xmat[-2, -3] + fmat[-1, -2] = xmat[-1, -2] * xmat[-2, -2] + xmat[-1, -1] * xmat[-1, -2] + fmat[-1, -1] = xmat[-1, -2] * xmat[-2, -1] + xmat[-1, -1] ** 2 + fmat[0, 0] -= b[0, 0] ** 2 + b[0, 1] * b[1, 0] + for i in range(1, m - 1): + fmat[i, i] -= ( + b[i, i] ** 2 + b[i - 1, i] * b[i, i - 1] + b[i + 1, i] * b[i, i + 1] + ) + fmat[-1, -1] -= b[-1, -1] ** 2 + b[-2, -1] * b[-1, -2] + for i in range(m - 1): + fmat[i + 1, i] -= b[i + 1, i] * b[i, i] + b[i + 1, i + 1] * b[i + 1, i] + for i in range(1, m): + fmat[i - 1, i] -= b[i - 1, i] * b[i, i] + b[i - 1, i - 1] * b[i - 1, i] + for i in range(1, m - 1): + fmat[i + 1, i - 1] -= b[i + 1, i] * b[i, i - 1] + for i in range(1, m - 1): + fmat[i - 1, i + 1] -= b[i - 1, i] * b[i, i + 1] -@mark.least_squares -def qr3d(x, m=5): - q = x[: m**2].reshape(m, m) - r = np.zeros((m, m), dtype=np.float64) - r[np.triu_indices_from(r)] = x[m**2 :] - - a = ( - np.diag((1 - np.arange(2, m + 1)) / m, -1) - + np.diag(2 * np.arange(1, m + 1) / m, 0) - + np.diag((1 - np.arange(1, m)) / m, 1) - ) - a[0, 1] = 0 - a[-1, -2] = (1 - m) / m - a[-1, -1] = 2 * m + return fmat.flatten() - omat = np.zeros((m, m), dtype=np.float64) # triu - fmat = np.zeros((m, m), dtype=np.float64) - for i in range(m): - for j in range(i, m): - for k in range(m): - omat[i, j] += q[i, k] * q[j, k] +@mark.least_squares +@dataclass(frozen=True) +class Semicon2(BenchmarkFunction): + """The SEMICON2 function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + n = len(x) // 1 + ln = 9 * n // 10 + + lambda_ = 0.2 + a = -0.00009 + b = 0.00001 + ua = 0.0 + ub = 700.0 + ca = 1e12 + cb = 1e13 + beta = 40.0 + + h = (b - a) / (n + 1) + lb = lambda_ * beta + lua = lambda_ * ua + lub = lambda_ * ub + + xvec = np.zeros(n + 2, dtype=np.float64) + xvec[0] = lua + xvec[1:-1] = x + xvec[-1] = lub + + fvec = np.zeros(n, dtype=np.float64) + for i in range(1, ln + 1): + fvec[i - 1] = ( + xvec[i - 1] + - 2 * xvec[i] + + xvec[i + 1] + + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) + - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) + - lambda_ * (h**2) * ca + ) + for i in range(ln + 1, n + 1): + fvec[i - 1] = ( + xvec[i - 1] + - 2 * xvec[i] + + xvec[i + 1] + - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) + + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) + + lambda_ * (h**2) * cb + ) - for i in range(m): - for j in range(m): - for k in range(j + 1): - fmat[i, j] += q[i, k] * r[k, j] + return fvec - for i in range(m): - omat[i, i] -= 1 - fmat[0, 0] -= a[0, 0] - fmat[0, 1] -= a[0, 1] - for i in range(1, m - 1): - fmat[i, i - 1] -= a[i, i - 1] - fmat[i, i] -= a[i, i] - fmat[i, i + 1] -= a[i, i + 1] - fmat[-1, -2] -= a[-1, -2] - fmat[-1, -1] -= a[-1, -1] - return np.concatenate((omat[np.triu_indices_from(omat)].flatten(), fmat.flatten())) +@mark.least_squares +@dataclass(frozen=True) +class Qr3d(BenchmarkFunction): + """The QR3D function from the CUTEst collection.""" + + m: int = 5 + """The number of rows and columns of the matrices Q and R.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + m = self.m + q = x[: m**2].reshape(m, m) + r = np.zeros((m, m), dtype=np.float64) + r[np.triu_indices_from(r)] = x[m**2 :] + + a = ( + np.diag((1 - np.arange(2, m + 1)) / m, -1) + + np.diag(2 * np.arange(1, m + 1) / m, 0) + + np.diag((1 - np.arange(1, m)) / m, 1) + ) + a[0, 1] = 0 + a[-1, -2] = (1 - m) / m + a[-1, -1] = 2 * m + + omat = np.zeros((m, m), dtype=np.float64) # triu + fmat = np.zeros((m, m), dtype=np.float64) + + for i in range(m): + for j in range(i, m): + for k in range(m): + omat[i, j] += q[i, k] * q[j, k] + + for i in range(m): + for j in range(m): + for k in range(j + 1): + fmat[i, j] += q[i, k] * r[k, j] + + for i in range(m): + omat[i, i] -= 1 + fmat[0, 0] -= a[0, 0] + fmat[0, 1] -= a[0, 1] + for i in range(1, m - 1): + fmat[i, i - 1] -= a[i, i - 1] + fmat[i, i] -= a[i, i] + fmat[i, i + 1] -= a[i, i + 1] + fmat[-1, -2] -= a[-1, -2] + fmat[-1, -1] -= a[-1, -1] + + return np.concatenate( + (omat[np.triu_indices_from(omat)].flatten(), fmat.flatten()) + ) @mark.least_squares -def qr3dbd(x, m=5): - q = x[: m**2].reshape(m, m) - r = np.zeros((m, m), dtype=np.float64) - r[0, :-2] = x[m**2 : -9] - r[1, 1:-1] = x[-9:-6] - r[2, 2:] = x[-6:-3] - r[3, 3:] = x[-3:-1] - r[4, 4] = x[-1] - - a = ( - np.diag((1 - np.arange(2, m + 1)) / m, -1) - + np.diag(2 * np.arange(1, m + 1) / m, 0) - + np.diag((1 - np.arange(1, m)) / m, 1) - ) - a[0, 1] = 0 - a[-1, -2] = (1 - m) / m - a[-1, -1] = 2 * m +@dataclass(frozen=True) +class Qr3dbd(BenchmarkFunction): + """The QR3DBD function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + m = 5 + q = x[: m**2].reshape(m, m) + r = np.zeros((m, m), dtype=np.float64) + r[0, :-2] = x[m**2 : -9] + r[1, 1:-1] = x[-9:-6] + r[2, 2:] = x[-6:-3] + r[3, 3:] = x[-3:-1] + r[4, 4] = x[-1] + + a = ( + np.diag((1 - np.arange(2, m + 1)) / m, -1) + + np.diag(2 * np.arange(1, m + 1) / m, 0) + + np.diag((1 - np.arange(1, m)) / m, 1) + ) + a[0, 1] = 0 + a[-1, -2] = (1 - m) / m + a[-1, -1] = 2 * m + + omat = np.zeros((m, m), dtype=np.float64) # triu + fmat = np.zeros((m, m), dtype=np.float64) + + for i in range(m): + for j in range(i, m): + for k in range(m): + omat[i, j] += q[i, k] * q[j, k] + + for i in range(m): + fmat[i, 0] += q[i, 0] * r[0, 0] + fmat[i, 1] += q[i, 0] * r[0, 1] + q[i, 1] * r[1, 1] + for j in range(2, m): + for k in range(j - 2, j + 1): + fmat[i, j] += q[i, k] * r[k, j] + + for i in range(m): + omat[i, i] -= 1 + fmat[0, 0] -= a[0, 0] + fmat[0, 1] -= a[0, 1] + for i in range(1, m - 1): + fmat[i, i - 1] -= a[i, i - 1] + fmat[i, i] -= a[i, i] + fmat[i, i + 1] -= a[i, i + 1] + fmat[-1, -2] -= a[-1, -2] + fmat[-1, -1] -= a[-1, -1] + + return np.concatenate( + (omat[np.triu_indices_from(omat)].flatten(), fmat.flatten()) + ) - omat = np.zeros((m, m), dtype=np.float64) # triu - fmat = np.zeros((m, m), dtype=np.float64) - for i in range(m): - for j in range(i, m): - for k in range(m): - omat[i, j] += q[i, k] * q[j, k] +@mark.least_squares +@dataclass(frozen=True, eq=False) +class Eigen(BenchmarkFunction): + """The EIGEN function from the CUTEst collection.""" - for i in range(m): - fmat[i, 0] += q[i, 0] * r[0, 0] - fmat[i, 1] += q[i, 0] * r[0, 1] + q[i, 1] * r[1, 1] - for j in range(2, m): - for k in range(j - 2, j + 1): - fmat[i, j] += q[i, k] * r[k, j] + matrix: NDArray[np.float64] + """The symmetric matrix whose eigendecomposition is searched, shape (m, m). The + number of parameters is m * (m + 1).""" - for i in range(m): - omat[i, i] -= 1 - fmat[0, 0] -= a[0, 0] - fmat[0, 1] -= a[0, 1] - for i in range(1, m - 1): - fmat[i, i - 1] -= a[i, i - 1] - fmat[i, i] -= a[i, i] - fmat[i, i + 1] -= a[i, i + 1] - fmat[-1, -2] -= a[-1, -2] - fmat[-1, -1] -= a[-1, -1] - - return np.concatenate((omat[np.triu_indices_from(omat)].flatten(), fmat.flatten())) + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = int(np.sqrt(len(x) + 0.25)) + dvec = x[:dim_in] + qmat = x[dim_in:].reshape(dim_in, dim_in) + emat = qmat @ np.diag(dvec) @ qmat - self.matrix + omat = qmat @ qmat - np.eye(dim_in) + return np.concatenate((emat.flatten(), omat.flatten())) @mark.least_squares -def eigen(x, param): - dim_in = int(np.sqrt(len(x) + 0.25)) - dvec = x[:dim_in] - qmat = x[dim_in:].reshape(dim_in, dim_in) - emat = qmat @ np.diag(dvec) @ qmat - param - omat = qmat @ qmat - np.eye(dim_in) - return np.concatenate((emat.flatten(), omat.flatten())) - +@dataclass(frozen=True) +class ExtendedPowellSingular(BenchmarkFunction): + """The extended Powell singular function (POWELLSE in the CUTEst collection).""" -@mark.least_squares -def powell_singular(x): - dim_in = len(x) - fvec = np.zeros(dim_in) - fvec[::4] = x[::4] + 10 * x[1::4] - fvec[1::4] = 5 * (x[2::4] - x[3::4]) - fvec[2::4] = (x[1::4] - 2 * x[2::4]) ** 2 - fvec[3::4] = 10 * (x[0::4] - x[3::4]) ** 2 - return fvec + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in) + fvec[::4] = x[::4] + 10 * x[1::4] + fvec[1::4] = 5 * (x[2::4] - x[3::4]) + fvec[2::4] = (x[1::4] - 2 * x[2::4]) ** 2 + fvec[3::4] = 10 * (x[0::4] - x[3::4]) ** 2 + return fvec -@mark.least_squares @njit def hydcar( x_in, @@ -707,422 +809,464 @@ def hydcar( @mark.least_squares -def methane(x): - fvec = np.zeros(31, dtype=np.float64) - fvec[0] = 0.01 * ( - 0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - - x[4] * (693.37 + x[24]) - + 693.37 * x[1] - ) - fvec[1] = ( - 0.000869565217391304 * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) * x[19] - - x[22] - ) - fvec[2] = 0.01 * ( - -0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - - x[7] * (693.37 + x[25]) - + x[4] * (693.37 + x[24]) - + 0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - ) - fvec[3] = -4.5125 + 0.01 * ( - -0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - - x[10] * (-442.13 + x[26]) - + x[7] * (693.37 + x[25]) - + 0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - ) - fvec[4] = 0.01 * ( - -0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - - x[13] * (-442.13 + x[27]) - + x[10] * (-442.13 + x[26]) - + 0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - ) - fvec[5] = 0.01 * ( - -0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - - x[16] * (-442.13 + x[28]) - + x[13] * (-442.13 + x[27]) - + 0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - ) - fvec[6] = 0.01 * ( - -0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - - x[19] * (-442.13 + x[29]) - + x[16] * (-442.13 + x[28]) - + 0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - ) - fvec[7] = 0.01 * ( - -0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - - x[22] * (-442.13 + x[30]) - + x[19] * (-442.13 + x[29]) - + 0.000869565217391304 - * x[30] - * x[19] - * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) - ) - fvec[8] = 0.01 * ( - 0.000826446280991736 * x[24] * x[2] * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - - x[5] * (693.37 + x[24]) - + 693.37 * x[2] - ) - fvec[9] = ( - 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] - - x[23] - ) - fvec[10] = 0.01 * ( - -0.000826446280991736 - * x[24] - * x[2] - * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - - x[8] * (693.37 + x[25]) - + x[5] * (693.37 + x[24]) - + 0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - ) - fvec[11] = -6.8425 + 0.01 * ( - -0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - - x[11] * (-442.13 + x[26]) - + x[8] * (693.37 + x[25]) - + 0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - ) - fvec[12] = 0.01 * ( - -0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - - x[14] * (-442.13 + x[27]) - + x[11] * (-442.13 + x[26]) - + 0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - ) - fvec[13] = 0.01 * ( - -0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - - x[17] * (-442.13 + x[28]) - + x[14] * (-442.13 + x[27]) - + 0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - ) - fvec[14] = 0.01 * ( - -0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - - x[20] * (-442.13 + x[29]) - + x[17] * (-442.13 + x[28]) - + 0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - ) - fvec[15] = 0.01 * ( - -0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - - x[23] * (-442.13 + x[30]) - + x[20] * (-442.13 + x[29]) - + 0.000869565217391304 - * x[30] - * x[20] - * np.exp(18.3443 - 3841.2203 / (228 + x[18])) - ) - fvec[16] = ( - -1 - + 0.000826446280991736 * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) * x[1] - + 0.000826446280991736 * np.exp(18.3443 - 3841.2203 / (228 + x[0])) * x[2] - ) - fvec[17] = ( - -1 - + 0.000833333333333333 * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) * x[4] - + 0.000833333333333333 * np.exp(18.3443 - 3841.2203 / (228 + x[3])) * x[5] - ) - fvec[18] = ( - -1 - + 0.000840336134453782 * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) * x[7] - + 0.000840336134453782 * np.exp(18.3443 - 3841.2203 / (228 + x[6])) * x[8] - ) - fvec[19] = ( - -1 - + 0.000847457627118644 * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) * x[10] - + 0.000847457627118644 * np.exp(18.3443 - 3841.2203 / (228 + x[9])) * x[11] - ) - fvec[20] = ( - -1 - + 0.000854700854700855 * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) * x[13] - + 0.000854700854700855 * np.exp(18.3443 - 3841.2203 / (228 + x[12])) * x[14] - ) - fvec[21] = ( - -1 - + 0.000862068965517241 * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) * x[16] - + 0.000862068965517241 * np.exp(18.3443 - 3841.2203 / (228 + x[15])) * x[17] - ) - fvec[22] = ( - -1 - + 0.000869565217391304 * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) * x[19] - + 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] - ) - fvec[23] = ( - -1 - + 0.00087719298245614 * np.exp(18.5751 - 3632.649 / (239.2 + x[21])) * x[22] - + 0.00087719298245614 * np.exp(18.3443 - 3841.2203 / (228 + x[21])) * x[23] - ) - fvec[24] = -83.862 + 1e-5 * ( - 0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) - + 693.37 * (0.0422 * x[0] * x[0] + 15.97 * x[0]) * x[1] - - x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) - + 0.000826446280991736 - * x[24] - * x[2] - * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - * (10834.67 + 8.74 * x[0]) - + 12549.997 * x[2] * x[0] - - 18.1 * x[5] * (693.37 + x[24]) * x[3] - ) - fvec[25] = 1e-5 * ( - 0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) - + x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) - - 0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) - - x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) - + 0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - * (10834.67 + 8.74 * x[3]) - + 18.1 * x[5] * (693.37 + x[24]) * x[3] - - 0.000826446280991736 - * x[24] - * x[2] - * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - * (10834.67 + 8.74 * x[0]) - - 18.1 * x[8] * (693.37 + x[25]) * x[6] - ) - fvec[26] = -18.9447111025 + 1e-5 * ( - 0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) - + x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) - - 0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) - - x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) - + 0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - * (10834.67 + 8.74 * x[6]) - + 18.1 * x[8] * (693.37 + x[25]) * x[6] - - 0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - * (10834.67 + 8.74 * x[3]) - - 18.1 * x[11] * (-442.13 + x[26]) * x[9] - ) - fvec[27] = 1e-5 * ( - 0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) - + x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) - - 0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) - - x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) - + 0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - * (10834.67 + 8.74 * x[9]) - + 18.1 * x[11] * (-442.13 + x[26]) * x[9] - - 0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - * (10834.67 + 8.74 * x[6]) - - 18.1 * x[14] * (-442.13 + x[27]) * x[12] - ) - fvec[28] = 1e-5 * ( - 0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) - + x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) - - 0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) - - x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) - + 0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - * (10834.67 + 8.74 * x[12]) - + 18.1 * x[14] * (-442.13 + x[27]) * x[12] - - 0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - * (10834.67 + 8.74 * x[9]) - - 18.1 * x[17] * (-442.13 + x[28]) * x[15] - ) - fvec[29] = 1e-5 * ( - 0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) - + x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) - - 0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) - - x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) - + 0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - * (10834.67 + 8.74 * x[15]) - + 18.1 * x[17] * (-442.13 + x[28]) * x[15] - - 0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - * (10834.67 + 8.74 * x[12]) - - 18.1 * x[20] * (-442.13 + x[29]) * x[18] - ) - fvec[30] = 1e-5 * ( - 0.000869565217391304 - * x[30] - * x[19] - * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) - * (9566.67 + 0.0422 * x[18] * x[18] - 1.59 * x[18]) - + x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) - - 0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) - - x[22] * (-442.13 + x[30]) * (0.0422 * x[21] * x[21] + 15.97 * x[21]) - + 0.000869565217391304 - * x[30] - * x[20] - * np.exp(18.3443 - 3841.2203 / (228 + x[18])) - * (10834.67 + 8.74 * x[18]) - + 18.1 * x[20] * (-442.13 + x[29]) * x[18] - - 0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - * (10834.67 + 8.74 * x[15]) - - 18.1 * x[23] * (-442.13 + x[30]) * x[21] - ) - return fvec +@dataclass(frozen=True) +class Hydcar(BenchmarkFunction): + """The HYDCAR function from the CUTEst collection.""" + + n: int + """The number of plates.""" + + m: int + """The number of components.""" + + k: int + """The index of the feed plate.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return hydcar(x, self.n, self.m, self.k) @mark.least_squares -def argtrig(x): - dim_in = len(x) - fvec = ( - dim_in - - np.sum(np.cos(x)) - + np.arange(1, dim_in + 1) * (1 - np.cos(x) - np.sin(x)) - ) - return fvec +@dataclass(frozen=True) +class Methane(BenchmarkFunction): + """Function of the METHANB8 and METHANL8 problems from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = np.zeros(31, dtype=np.float64) + fvec[0] = 0.01 * ( + 0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + - x[4] * (693.37 + x[24]) + + 693.37 * x[1] + ) + fvec[1] = ( + 0.000869565217391304 * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) * x[19] + - x[22] + ) + fvec[2] = 0.01 * ( + -0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + - x[7] * (693.37 + x[25]) + + x[4] * (693.37 + x[24]) + + 0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + ) + fvec[3] = -4.5125 + 0.01 * ( + -0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + - x[10] * (-442.13 + x[26]) + + x[7] * (693.37 + x[25]) + + 0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + ) + fvec[4] = 0.01 * ( + -0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + - x[13] * (-442.13 + x[27]) + + x[10] * (-442.13 + x[26]) + + 0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + ) + fvec[5] = 0.01 * ( + -0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + - x[16] * (-442.13 + x[28]) + + x[13] * (-442.13 + x[27]) + + 0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + ) + fvec[6] = 0.01 * ( + -0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + - x[19] * (-442.13 + x[29]) + + x[16] * (-442.13 + x[28]) + + 0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + ) + fvec[7] = 0.01 * ( + -0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + - x[22] * (-442.13 + x[30]) + + x[19] * (-442.13 + x[29]) + + 0.000869565217391304 + * x[30] + * x[19] + * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) + ) + fvec[8] = 0.01 * ( + 0.000826446280991736 + * x[24] + * x[2] + * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + - x[5] * (693.37 + x[24]) + + 693.37 * x[2] + ) + fvec[9] = ( + 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] + - x[23] + ) + fvec[10] = 0.01 * ( + -0.000826446280991736 + * x[24] + * x[2] + * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + - x[8] * (693.37 + x[25]) + + x[5] * (693.37 + x[24]) + + 0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + ) + fvec[11] = -6.8425 + 0.01 * ( + -0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + - x[11] * (-442.13 + x[26]) + + x[8] * (693.37 + x[25]) + + 0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + ) + fvec[12] = 0.01 * ( + -0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + - x[14] * (-442.13 + x[27]) + + x[11] * (-442.13 + x[26]) + + 0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + ) + fvec[13] = 0.01 * ( + -0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + - x[17] * (-442.13 + x[28]) + + x[14] * (-442.13 + x[27]) + + 0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + ) + fvec[14] = 0.01 * ( + -0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + - x[20] * (-442.13 + x[29]) + + x[17] * (-442.13 + x[28]) + + 0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + ) + fvec[15] = 0.01 * ( + -0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + - x[23] * (-442.13 + x[30]) + + x[20] * (-442.13 + x[29]) + + 0.000869565217391304 + * x[30] + * x[20] + * np.exp(18.3443 - 3841.2203 / (228 + x[18])) + ) + fvec[16] = ( + -1 + + 0.000826446280991736 * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) * x[1] + + 0.000826446280991736 * np.exp(18.3443 - 3841.2203 / (228 + x[0])) * x[2] + ) + fvec[17] = ( + -1 + + 0.000833333333333333 * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) * x[4] + + 0.000833333333333333 * np.exp(18.3443 - 3841.2203 / (228 + x[3])) * x[5] + ) + fvec[18] = ( + -1 + + 0.000840336134453782 * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) * x[7] + + 0.000840336134453782 * np.exp(18.3443 - 3841.2203 / (228 + x[6])) * x[8] + ) + fvec[19] = ( + -1 + + 0.000847457627118644 * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) * x[10] + + 0.000847457627118644 * np.exp(18.3443 - 3841.2203 / (228 + x[9])) * x[11] + ) + fvec[20] = ( + -1 + + 0.000854700854700855 + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + * x[13] + + 0.000854700854700855 * np.exp(18.3443 - 3841.2203 / (228 + x[12])) * x[14] + ) + fvec[21] = ( + -1 + + 0.000862068965517241 + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + * x[16] + + 0.000862068965517241 * np.exp(18.3443 - 3841.2203 / (228 + x[15])) * x[17] + ) + fvec[22] = ( + -1 + + 0.000869565217391304 + * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) + * x[19] + + 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] + ) + fvec[23] = ( + -1 + + 0.00087719298245614 * np.exp(18.5751 - 3632.649 / (239.2 + x[21])) * x[22] + + 0.00087719298245614 * np.exp(18.3443 - 3841.2203 / (228 + x[21])) * x[23] + ) + fvec[24] = -83.862 + 1e-5 * ( + 0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) + + 693.37 * (0.0422 * x[0] * x[0] + 15.97 * x[0]) * x[1] + - x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) + + 0.000826446280991736 + * x[24] + * x[2] + * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + * (10834.67 + 8.74 * x[0]) + + 12549.997 * x[2] * x[0] + - 18.1 * x[5] * (693.37 + x[24]) * x[3] + ) + fvec[25] = 1e-5 * ( + 0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) + + x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) + - 0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) + - x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) + + 0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + * (10834.67 + 8.74 * x[3]) + + 18.1 * x[5] * (693.37 + x[24]) * x[3] + - 0.000826446280991736 + * x[24] + * x[2] + * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + * (10834.67 + 8.74 * x[0]) + - 18.1 * x[8] * (693.37 + x[25]) * x[6] + ) + fvec[26] = -18.9447111025 + 1e-5 * ( + 0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) + + x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) + - 0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) + - x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) + + 0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + * (10834.67 + 8.74 * x[6]) + + 18.1 * x[8] * (693.37 + x[25]) * x[6] + - 0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + * (10834.67 + 8.74 * x[3]) + - 18.1 * x[11] * (-442.13 + x[26]) * x[9] + ) + fvec[27] = 1e-5 * ( + 0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) + + x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) + - 0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) + - x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) + + 0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + * (10834.67 + 8.74 * x[9]) + + 18.1 * x[11] * (-442.13 + x[26]) * x[9] + - 0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + * (10834.67 + 8.74 * x[6]) + - 18.1 * x[14] * (-442.13 + x[27]) * x[12] + ) + fvec[28] = 1e-5 * ( + 0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) + + x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) + - 0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) + - x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) + + 0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + * (10834.67 + 8.74 * x[12]) + + 18.1 * x[14] * (-442.13 + x[27]) * x[12] + - 0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + * (10834.67 + 8.74 * x[9]) + - 18.1 * x[17] * (-442.13 + x[28]) * x[15] + ) + fvec[29] = 1e-5 * ( + 0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) + + x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) + - 0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) + - x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) + + 0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + * (10834.67 + 8.74 * x[15]) + + 18.1 * x[17] * (-442.13 + x[28]) * x[15] + - 0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + * (10834.67 + 8.74 * x[12]) + - 18.1 * x[20] * (-442.13 + x[29]) * x[18] + ) + fvec[30] = 1e-5 * ( + 0.000869565217391304 + * x[30] + * x[19] + * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) + * (9566.67 + 0.0422 * x[18] * x[18] - 1.59 * x[18]) + + x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) + - 0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) + - x[22] * (-442.13 + x[30]) * (0.0422 * x[21] * x[21] + 15.97 * x[21]) + + 0.000869565217391304 + * x[30] + * x[20] + * np.exp(18.3443 - 3841.2203 / (228 + x[18])) + * (10834.67 + 8.74 * x[18]) + + 18.1 * x[20] * (-442.13 + x[29]) * x[18] + - 0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + * (10834.67 + 8.74 * x[15]) + - 18.1 * x[23] * (-442.13 + x[30]) * x[21] + ) + return fvec @mark.least_squares -def artif(x): - dim_in = len(x) - xvec = np.zeros(dim_in + 2, dtype=np.float64) - xvec[1:-1] = x - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(dim_in): - fvec[i] = -0.05 * (xvec[i + 1] + xvec[i + 2] + xvec[i]) + np.arctan( - np.sin(np.mod(i + 1, 100) * xvec[i + 1]) +@dataclass(frozen=True) +class Argtrig(BenchmarkFunction): + """The ARGTRIG function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = ( + dim_in + - np.sum(np.cos(x)) + + np.arange(1, dim_in + 1) * (1 - np.cos(x) - np.sin(x)) ) - return fvec + return fvec @mark.least_squares -def arwhdne(x): - dim_in = len(x) - fvec = np.zeros(2 * (dim_in - 1)) - fvec[: dim_in - 1] = x[:-1] ** 2 + x[-1] ** 2 - fvec[dim_in - 1 :] = 4 * x[:-1] - 3 - return fvec +@dataclass(frozen=True) +class Artif(BenchmarkFunction): + """The ARTIF function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + xvec = np.zeros(dim_in + 2, dtype=np.float64) + xvec[1:-1] = x + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(dim_in): + fvec[i] = -0.05 * (xvec[i + 1] + xvec[i + 2] + xvec[i]) + np.arctan( + np.sin(np.mod(i + 1, 100) * xvec[i + 1]) + ) + return fvec @mark.least_squares +@dataclass(frozen=True) +class Arwhdne(BenchmarkFunction): + """The ARWHDNE function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(2 * (dim_in - 1)) + fvec[: dim_in - 1] = x[:-1] ** 2 + x[-1] ** 2 + fvec[dim_in - 1 :] = 4 * x[:-1] - 3 + return fvec + + @njit def bdvalues(x): dim_in = len(x) @@ -1142,129 +1286,171 @@ def bdvalues(x): @mark.least_squares -def bratu_2d(x, alpha): - x = x.reshape((int(np.sqrt(len(x))), int(np.sqrt(len(x))))) - p = x.shape[0] + 2 - h = 1 / (p - 1) - c = h**2 * alpha - xvec = np.zeros((x.shape[0] + 2, x.shape[1] + 2), dtype=np.float64) - xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1] = x - fvec = np.zeros(x.shape) - for i in range(2, p): - for j in range(2, p): - fvec[i - 2, j - 2] = ( - 4 * xvec[i - 1, j - 1] - - xvec[i, j - 1] - - xvec[i - 2, j - 1] - - xvec[i - 1, j] - - xvec[i - 1, j - 2] - - c * np.exp(xvec[i - 1, j - 1]) - ) - return fvec.flatten() +@dataclass(frozen=True) +class Bdvalues(BenchmarkFunction): + """The BDVALUES function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return bdvalues(x) @mark.least_squares -def bratu_3d(x, alpha): - n = int(np.cbrt(len(x))) - x = x.reshape((n, n, n)) - p = x.shape[0] + 2 - h = 1 / (p - 1) - c = h**2 * alpha - xvec = np.zeros((x.shape[0] + 2, x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64) - xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x - fvec = np.zeros(x.shape, dtype=np.float64) - for i in range(2, p): - for j in range(2, p): - for k in range(2, p): - fvec[i - 2, j - 2, k - 2] = ( - 6 * xvec[i - 1, j - 1, k - 1] - - xvec[i, j - 1, k - 1] - - xvec[i - 2, j - 1, k - 1] - - xvec[i - 1, j, k - 1] - - xvec[i - 1, j - 2, k - 1] - - xvec[i - 1, j - 1, k] - - xvec[i - 1, j - 1, k - 2] - - c * np.exp(xvec[i, j, k]) +@dataclass(frozen=True) +class Bratu2d(BenchmarkFunction): + """The BRATU2D function from the CUTEst collection.""" + + alpha: float + """The parameter of the Bratu equation.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + x = x.reshape((int(np.sqrt(len(x))), int(np.sqrt(len(x))))) + p = x.shape[0] + 2 + h = 1 / (p - 1) + c = h**2 * self.alpha + xvec = np.zeros((x.shape[0] + 2, x.shape[1] + 2), dtype=np.float64) + xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1] = x + fvec = np.zeros(x.shape) + for i in range(2, p): + for j in range(2, p): + fvec[i - 2, j - 2] = ( + 4 * xvec[i - 1, j - 1] + - xvec[i, j - 1] + - xvec[i - 2, j - 1] + - xvec[i - 1, j] + - xvec[i - 1, j - 2] + - c * np.exp(xvec[i - 1, j - 1]) ) - return fvec.flatten() + return fvec.flatten() @mark.least_squares -def broydn_3d(x): - kappa_1 = 2 - kappa_2 = 1 - fvec = np.zeros_like(x) - fvec[0] = -2 * x[1] + kappa_2 + (3 - kappa_1 * x[0]) * x[0] - fvec[1 : len(x) - 1] = ( - -x[:-2] - 2 * x[2:] + kappa_2 + (3 - kappa_1 * x[1:-1]) * x[1:-1] - ) - fvec[-1] = -x[-2] + kappa_2 + (3 - kappa_1 * x[-1]) * x[-1] - return fvec +@dataclass(frozen=True) +class Bratu3d(BenchmarkFunction): + """The BRATU3D function from the CUTEst collection.""" + + alpha: float + """The parameter of the Bratu equation.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + n = int(np.cbrt(len(x))) + x = x.reshape((n, n, n)) + p = x.shape[0] + 2 + h = 1 / (p - 1) + c = h**2 * self.alpha + xvec = np.zeros( + (x.shape[0] + 2, x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64 + ) + xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x + fvec = np.zeros(x.shape, dtype=np.float64) + for i in range(2, p): + for j in range(2, p): + for k in range(2, p): + fvec[i - 2, j - 2, k - 2] = ( + 6 * xvec[i - 1, j - 1, k - 1] + - xvec[i, j - 1, k - 1] + - xvec[i - 2, j - 1, k - 1] + - xvec[i - 1, j, k - 1] + - xvec[i - 1, j - 2, k - 1] + - xvec[i - 1, j - 1, k] + - xvec[i - 1, j - 1, k - 2] + - c * np.exp(xvec[i, j, k]) + ) + return fvec.flatten() @mark.least_squares -def broydn_bd(x): - dim_in = len(x) - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(1, 1 + dim_in): - ji = [] - lb = max(1, i - 5) - ub = min(dim_in, i + 1) - for j in range(lb, ub + 1): - if j != i: - ji.append(j) - fvec[i - 1] = x[i - 1] * (2 + 5 * x[i - 1] ** 2) - np.sum( - x[np.array(ji) - 1] * (1 + x[np.array(ji) - 1]) +@dataclass(frozen=True) +class Broydn3d(BenchmarkFunction): + """The BROYDN3D function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + kappa_1 = 2 + kappa_2 = 1 + fvec = np.zeros_like(x) + fvec[0] = -2 * x[1] + kappa_2 + (3 - kappa_1 * x[0]) * x[0] + fvec[1 : len(x) - 1] = ( + -x[:-2] - 2 * x[2:] + kappa_2 + (3 - kappa_1 * x[1:-1]) * x[1:-1] ) - return fvec + fvec[-1] = -x[-2] + kappa_2 + (3 - kappa_1 * x[-1]) * x[-1] + return fvec @mark.least_squares -def cbratu_2d(x): - n = int(np.sqrt(len(x) / 2)) - x = x.reshape((2, n, n)) - xvec = np.zeros((x.shape[0], x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64) - xvec[0, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[0, :, :] - xvec[1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[1, :, :] - p = x.shape[1] + 2 - h = 1 / (p - 1) - alpha = 5 - c = h**2 * alpha - fvec = np.zeros(x.shape, dtype=np.float64) - for i in range(2, p): - for j in range(2, p): - fvec[0, i - 2, j - 2] = ( - 4 * xvec[0, i - 1, j - 1] - - xvec[0, i, j - 1] - - xvec[0, i - 2, j - 1] - - xvec[0, i - 1, j] - - xvec[0, i - 1, j - 2] - - c * np.exp(xvec[0, i - 1, j - 1]) * np.cos(xvec[0, i - 1, j - 1]) +@dataclass(frozen=True) +class BroydnBd(BenchmarkFunction): + """The BROYDNBD function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(1, 1 + dim_in): + ji = [] + lb = max(1, i - 5) + ub = min(dim_in, i + 1) + for j in range(lb, ub + 1): + if j != i: + ji.append(j) + fvec[i - 1] = x[i - 1] * (2 + 5 * x[i - 1] ** 2) - np.sum( + x[np.array(ji) - 1] * (1 + x[np.array(ji) - 1]) ) - fvec[1, i - 2, j - 2] = ( - 4 * xvec[1, i - 1, j - 1] - - xvec[1, i, j - 1] - - xvec[1, i - 2, j - 1] - - xvec[1, i - 1, j] - - xvec[1, i - 1, j - 2] - - c * np.exp(xvec[1, i - 1, j - 1]) * np.sin(xvec[1, i - 1, j - 1]) - ) - return fvec.flatten() + return fvec @mark.least_squares -def chandheq(x): - dim_in = len(x) - constant = 1 - w = np.ones(dim_in, dtype=np.int64) / dim_in - h = np.ones(dim_in, dtype=np.int64) - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(dim_in): - fvec[i] = (-0.5 * constant * w * x[i] / (x[i] + x) * h[i] * h + h[i] - 1).sum() - return fvec +@dataclass(frozen=True) +class Cbratu2d(BenchmarkFunction): + """The CBRATU2D function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + n = int(np.sqrt(len(x) / 2)) + x = x.reshape((2, n, n)) + xvec = np.zeros((x.shape[0], x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64) + xvec[0, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[0, :, :] + xvec[1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[1, :, :] + p = x.shape[1] + 2 + h = 1 / (p - 1) + alpha = 5 + c = h**2 * alpha + fvec = np.zeros(x.shape, dtype=np.float64) + for i in range(2, p): + for j in range(2, p): + fvec[0, i - 2, j - 2] = ( + 4 * xvec[0, i - 1, j - 1] + - xvec[0, i, j - 1] + - xvec[0, i - 2, j - 1] + - xvec[0, i - 1, j] + - xvec[0, i - 1, j - 2] + - c * np.exp(xvec[0, i - 1, j - 1]) * np.cos(xvec[0, i - 1, j - 1]) + ) + fvec[1, i - 2, j - 2] = ( + 4 * xvec[1, i - 1, j - 1] + - xvec[1, i, j - 1] + - xvec[1, i - 2, j - 1] + - xvec[1, i - 1, j] + - xvec[1, i - 1, j - 2] + - c * np.exp(xvec[1, i - 1, j - 1]) * np.sin(xvec[1, i - 1, j - 1]) + ) + return fvec.flatten() @mark.least_squares +@dataclass(frozen=True) +class Chandheq(BenchmarkFunction): + """The CHANDHEQ function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + constant = 1 + w = np.ones(dim_in, dtype=np.int64) / dim_in + h = np.ones(dim_in, dtype=np.int64) + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(dim_in): + fvec[i] = ( + -0.5 * constant * w * x[i] / (x[i] + x) * h[i] * h + h[i] - 1 + ).sum() + return fvec + + @njit def chemrcta(x): dim_in = int(len(x) / 2) @@ -1308,6 +1494,14 @@ def chemrcta(x): @mark.least_squares +@dataclass(frozen=True) +class Chemrcta(BenchmarkFunction): + """The CHEMRCTA function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return chemrcta(x) + + @njit def chemrctb(x): dim_in = int(len(x)) @@ -1336,69 +1530,81 @@ def chemrctb(x): @mark.least_squares -def chnrsbne(x): - alfa = np.array( - [ - 1.25, - 1.40, - 2.40, - 1.40, - 1.75, - 1.20, - 2.25, - 1.20, - 1.00, - 1.10, - 1.50, - 1.60, - 1.25, - 1.25, - 1.20, - 1.20, - 1.40, - 0.50, - 0.50, - 1.25, - 1.80, - 0.75, - 1.25, - 1.40, - 1.60, - 2.00, - 1.00, - 1.60, - 1.25, - 2.75, - 1.25, - 1.25, - 1.25, - 3.00, - 1.50, - 2.00, - 1.25, - 1.40, - 1.80, - 1.50, - 2.20, - 1.40, - 1.50, - 1.25, - 2.00, - 1.50, - 1.25, - 1.40, - 0.60, - 1.50, - ] - ) - dim_in = len(x) - fvec = np.zeros(2 * (dim_in - 1)) - fvec[: dim_in - 1] = 4 * alfa[1:] * (x[:-1] - x[1:] ** 2) - fvec[dim_in - 1 :] = x[1:] - 1 - return fvec +@dataclass(frozen=True) +class Chemrctb(BenchmarkFunction): + """The CHEMRCTB function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return chemrctb(x) @mark.least_squares +@dataclass(frozen=True) +class Chnrsbne(BenchmarkFunction): + """The CHNRSBNE function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + alfa = np.array( + [ + 1.25, + 1.40, + 2.40, + 1.40, + 1.75, + 1.20, + 2.25, + 1.20, + 1.00, + 1.10, + 1.50, + 1.60, + 1.25, + 1.25, + 1.20, + 1.20, + 1.40, + 0.50, + 0.50, + 1.25, + 1.80, + 0.75, + 1.25, + 1.40, + 1.60, + 2.00, + 1.00, + 1.60, + 1.25, + 2.75, + 1.25, + 1.25, + 1.25, + 3.00, + 1.50, + 2.00, + 1.25, + 1.40, + 1.80, + 1.50, + 2.20, + 1.40, + 1.50, + 1.25, + 2.00, + 1.50, + 1.25, + 1.40, + 0.60, + 1.50, + ] + ) + dim_in = len(x) + fvec = np.zeros(2 * (dim_in - 1)) + fvec[: dim_in - 1] = 4 * alfa[1:] * (x[:-1] - x[1:] ** 2) + fvec[dim_in - 1 :] = x[1:] - 1 + return fvec + + @njit def drcavty(x, r): m = int(np.sqrt(len(x))) @@ -1455,144 +1661,215 @@ def drcavty(x, r): @mark.least_squares -def freurone(x): - dim_in = len(x) - fvec = np.zeros((2, dim_in - 1), dtype=np.float64) - for i in range(dim_in - 1): - fvec[0, i] = (5.0 - x[i + 1]) * x[i + 1] ** 2 + x[i] - 2 * x[i + 1] - 13.0 - fvec[1, i] = (1.0 + x[i + 1]) * x[i + 1] ** 2 + x[i] - 14 * x[i + 1] - 29.0 - return fvec.flatten() +@dataclass(frozen=True) +class Drcavty(BenchmarkFunction): + """The DRCAVTY function from the CUTEst collection.""" + + r: float + """The Reynolds number.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return drcavty(x, self.r) @mark.least_squares -def hatfldg(x): - dim_in = len(x) - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(1, dim_in - 1): - fvec[i - 1] = x[i] * (x[i - 1] - x[i + 1]) + x[i] - x[12] + 1 - fvec[-2] = x[0] - x[12] + 1 - x[0] * x[1] - fvec[-1] = x[-1] - x[12] + 1 + x[-2] * x[-1] - return fvec +@dataclass(frozen=True) +class Freurone(BenchmarkFunction): + """The FREURONE function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros((2, dim_in - 1), dtype=np.float64) + for i in range(dim_in - 1): + fvec[0, i] = (5.0 - x[i + 1]) * x[i + 1] ** 2 + x[i] - 2 * x[i + 1] - 13.0 + fvec[1, i] = (1.0 + x[i + 1]) * x[i + 1] ** 2 + x[i] - 14 * x[i + 1] - 29.0 + return fvec.flatten() @mark.least_squares -def integreq(x): - dim_in = len(x) - h = 1 / (dim_in + 1) - t = np.arange(1, dim_in + 1) * h - xvec = np.zeros(dim_in + 2, dtype=np.float64) - xvec[1:-1] = x - fvec = np.zeros_like(x) - for i in range(1, dim_in): - fvec[i - 1] = ( - xvec[i] +@dataclass(frozen=True) +class Hatfldg(BenchmarkFunction): + """The HATFLDG function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(1, dim_in - 1): + fvec[i - 1] = x[i] * (x[i - 1] - x[i + 1]) + x[i] - x[12] + 1 + fvec[-2] = x[0] - x[12] + 1 - x[0] * x[1] + fvec[-1] = x[-1] - x[12] + 1 + x[-2] * x[-1] + return fvec + + +@mark.least_squares +@dataclass(frozen=True) +class Integreq(BenchmarkFunction): + """The INTEGREQ function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + h = 1 / (dim_in + 1) + t = np.arange(1, dim_in + 1) * h + xvec = np.zeros(dim_in + 2, dtype=np.float64) + xvec[1:-1] = x + fvec = np.zeros_like(x) + for i in range(1, dim_in): + fvec[i - 1] = ( + xvec[i] + + h + * ( + (1 - t[i - 1]) * (t[:i] * (xvec[1 : i + 1] + t[:i] + 1) ** 3).sum() + + t[i - 1] + * ((1 - t[i:]) * (xvec[i + 1 : -1] + t[i:] + 1) ** 3).sum() + ) + / 2 + ) + fvec[-1] = ( + xvec[-2] + h * ( - (1 - t[i - 1]) * (t[:i] * (xvec[1 : i + 1] + t[:i] + 1) ** 3).sum() - + t[i - 1] * ((1 - t[i:]) * (xvec[i + 1 : -1] + t[i:] + 1) ** 3).sum() + (1 - t[-1]) * (t * (xvec[1:-1] + t + 1) ** 3).sum() + + t[-1] * ((1 - t[-1]) * (xvec[-2] + t[-1] + 1) ** 3) ) / 2 ) - fvec[-1] = ( - xvec[-2] - + h - * ( - (1 - t[-1]) * (t * (xvec[1:-1] + t + 1) ** 3).sum() - + t[-1] * ((1 - t[-1]) * (xvec[-2] + t[-1] + 1) ** 3) - ) - / 2 - ) - return fvec + return fvec @mark.least_squares -def msqrta(x): - dim_in = int(np.sqrt(len(x))) - xmat = x.reshape((dim_in, dim_in)) - bmat = 5 * xmat - amat = np.zeros((dim_in, dim_in), dtype=np.float64) - for i in range(1, dim_in + 1): - for j in range(1, dim_in + 1): - amat[i - 1, j - 1] = (bmat[i - 1, :] * bmat[:, j - 1]).sum() - fmat = np.zeros((dim_in, dim_in)) - for i in range(1, dim_in + 1): - for j in range(1, dim_in + 1): - fmat[i - 1, j - 1] = (xmat[i - 1, :] * xmat[:, j - 1]).sum() - amat[ - i - 1, j - 1 - ] - return fmat.flatten() +@dataclass(frozen=True) +class Msqrta(BenchmarkFunction): + """The MSQRTA function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = int(np.sqrt(len(x))) + xmat = x.reshape((dim_in, dim_in)) + bmat = 5 * xmat + amat = np.zeros((dim_in, dim_in), dtype=np.float64) + for i in range(1, dim_in + 1): + for j in range(1, dim_in + 1): + amat[i - 1, j - 1] = (bmat[i - 1, :] * bmat[:, j - 1]).sum() + fmat = np.zeros((dim_in, dim_in)) + for i in range(1, dim_in + 1): + for j in range(1, dim_in + 1): + fmat[i - 1, j - 1] = (xmat[i - 1, :] * xmat[:, j - 1]).sum() - amat[ + i - 1, j - 1 + ] + return fmat.flatten() @mark.least_squares -def penalty_1(x, a=1e-5): - fvec = np.sqrt(a) * (x - 2) - fvec = np.concatenate([fvec, [x @ x - 1 / 4]]) - return fvec +@dataclass(frozen=True) +class Penalty1(BenchmarkFunction): + """The PENALTY1 function from the CUTEst collection.""" + + a: float = 1e-5 + """Scaling factor. All residuals except the last are multiplied by its square + root.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = np.sqrt(self.a) * (x - 2) + fvec = np.concatenate([fvec, [x @ x - 1 / 4]]) + return fvec @mark.least_squares -def penalty_2(x, a=1e-10): - dim_in = len(x) - y = np.exp(np.arange(1, 2 * dim_in + 1) / 10) + np.exp(np.arange(2 * dim_in) / 10) - fvec = np.zeros(2 * dim_in) - fvec[0] = x[0] - 0.2 - fvec[1:dim_in] = np.sqrt(a) * ( - np.exp(x[1:] / 10) + np.exp(x[:-1] / 10) - y[1:dim_in] - ) - fvec[dim_in:-1] = np.sqrt(a) * (np.exp(x[1:] / 10) - np.exp(-1 / 10)) - fvec[-1] = (np.arange(1, dim_in + 1)[::-1] * x**2).sum() - 1 - return fvec +@dataclass(frozen=True) +class Penalty2(BenchmarkFunction): + """The PENALTY2 function from the CUTEst collection.""" + + a: float = 1e-10 + """Scaling factor. All residuals except the first and the last are multiplied by + its square root.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + y = np.exp(np.arange(1, 2 * dim_in + 1) / 10) + np.exp( + np.arange(2 * dim_in) / 10 + ) + fvec = np.zeros(2 * dim_in) + fvec[0] = x[0] - 0.2 + fvec[1:dim_in] = np.sqrt(self.a) * ( + np.exp(x[1:] / 10) + np.exp(x[:-1] / 10) - y[1:dim_in] + ) + fvec[dim_in:-1] = np.sqrt(self.a) * (np.exp(x[1:] / 10) - np.exp(-1 / 10)) + fvec[-1] = (np.arange(1, dim_in + 1)[::-1] * x**2).sum() - 1 + return fvec @mark.least_squares -def vardimne(x): - dim_in = len(x) - fvec = np.zeros(dim_in + 2) - fvec[:-2] = x - 1 - fvec[-2] = (np.arange(1, dim_in + 1) * (x - 1)).sum() - fvec[-1] = ((np.arange(1, dim_in + 1) * (x - 1)).sum()) ** 2 - return fvec +@dataclass(frozen=True) +class Vardimne(BenchmarkFunction): + """The VARDIMNE function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in + 2) + fvec[:-2] = x - 1 + fvec[-2] = (np.arange(1, dim_in + 1) * (x - 1)).sum() + fvec[-1] = ((np.arange(1, dim_in + 1) * (x - 1)).sum()) ** 2 + return fvec @mark.least_squares -def yatpsq_1(x, dim_in): - xvec = x[: dim_in**2] - xvec = xvec.reshape((dim_in, dim_in)) - yvec = x[dim_in**2 : dim_in**2 + dim_in] - zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] - fvec = np.zeros((dim_in, dim_in), dtype=np.float64) - for i in range(dim_in): - for j in range(dim_in): - fvec[i, j] = ( - xvec[i, j] ** 3 - - 10 * xvec[i, j] ** 2 - - (yvec[i] + zvec[j]) - * (xvec[i, j] * np.cos(xvec[i, j]) - np.sin(xvec[i, j])) - ) - fvec = fvec.flatten() - temp = (np.sin(xvec) / xvec).sum(axis=0) - 1 - fvec = np.concatenate((fvec, temp)) - temp = (np.sin(xvec) / xvec).sum(axis=1) - 1 - fvec = np.concatenate((fvec, temp)) - return fvec +@dataclass(frozen=True) +class Yatpsq1(BenchmarkFunction): + """The YATP1SQ function from the CUTEst collection.""" + + dim_in: int + """The number of rows and columns of the matrix in the parameters. The number of + parameters is dim_in**2 + 2 * dim_in.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = self.dim_in + xvec = x[: dim_in**2] + xvec = xvec.reshape((dim_in, dim_in)) + yvec = x[dim_in**2 : dim_in**2 + dim_in] + zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] + fvec = np.zeros((dim_in, dim_in), dtype=np.float64) + for i in range(dim_in): + for j in range(dim_in): + fvec[i, j] = ( + xvec[i, j] ** 3 + - 10 * xvec[i, j] ** 2 + - (yvec[i] + zvec[j]) + * (xvec[i, j] * np.cos(xvec[i, j]) - np.sin(xvec[i, j])) + ) + fvec = fvec.flatten() + temp = (np.sin(xvec) / xvec).sum(axis=0) - 1 + fvec = np.concatenate((fvec, temp)) + temp = (np.sin(xvec) / xvec).sum(axis=1) - 1 + fvec = np.concatenate((fvec, temp)) + return fvec @mark.least_squares -def yatpsq_2(x, dim_in): - xvec = x[: dim_in**2] - xvec = xvec.reshape((dim_in, dim_in)) - yvec = x[dim_in**2 : dim_in**2 + dim_in] - zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] - fvec = np.zeros((dim_in, dim_in), dtype=np.float64) - for i in range(dim_in): - for j in range(dim_in): - fvec[i, j] = xvec[i, j] - (yvec[i] + zvec[j]) * (1 + np.cos(xvec[i, j])) - 1 - fvec = fvec.flatten() - temp = (np.sin(xvec) + xvec).sum(axis=0) - 1 - fvec = np.concatenate((fvec, temp)) - temp = (np.sin(xvec) + xvec).sum(axis=1) - 1 - fvec = np.concatenate((fvec, temp)) - return fvec +@dataclass(frozen=True) +class Yatpsq2(BenchmarkFunction): + """The YATP2SQ function from the CUTEst collection.""" + + dim_in: int + """The number of rows and columns of the matrix in the parameters. The number of + parameters is dim_in**2 + 2 * dim_in.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = self.dim_in + xvec = x[: dim_in**2] + xvec = xvec.reshape((dim_in, dim_in)) + yvec = x[dim_in**2 : dim_in**2 + dim_in] + zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] + fvec = np.zeros((dim_in, dim_in), dtype=np.float64) + for i in range(dim_in): + for j in range(dim_in): + fvec[i, j] = ( + xvec[i, j] - (yvec[i] + zvec[j]) * (1 + np.cos(xvec[i, j])) - 1 + ) + fvec = fvec.flatten() + temp = (np.sin(xvec) + xvec).sum(axis=0) - 1 + fvec = np.concatenate((fvec, temp)) + temp = (np.sin(xvec) + xvec).sum(axis=1) - 1 + fvec = np.concatenate((fvec, temp)) + return fvec def get_start_points_msqrta(dim_in, flag=1): @@ -4900,7 +5177,7 @@ def get_start_points_methanl8(): def _problem( - fun: Callable[[NDArray[np.float64]], NDArray[np.float64]], + function: BenchmarkFunction, start_x: list[float], solution_x: list[float] | None, solution_fun: float, @@ -4909,8 +5186,7 @@ def _problem( """Create a benchmark problem from the information in the problem table. Args: - fun: Function that maps parameters of shape (n_params,) to least-squares - residuals of shape (n_residuals,). + function: The least-squares benchmark function. start_x: The start parameters. solution_x: The parameters at the solution or None if they are not unique. solution_fun: The sum of squared residuals at the solution. @@ -4928,8 +5204,7 @@ def _problem( solution_params = np.array(solution_x, dtype=np.float64) return BenchmarkProblem( - # Mark the function here because marks get lost when a function is partialled. - function=CallableBenchmarkFunction(func=mark.least_squares(fun)), + function=function, start_params=np.array(start_x, dtype=np.float64), solution=BenchmarkSolution( fun=float(solution_fun), params=solution_params, exact=solution_fun == 0 @@ -4941,137 +5216,137 @@ def _problem( CARTIS_ROBERTS_PROBLEMS: dict[str, BenchmarkProblem] = { "arglale": _problem( # arglale is the same as linear_full_rank with specific settings - fun=partial(linear_full_rank, dim_out=400), + function=LinearFullRank(dim_out=400), start_x=[1] * 100, solution_x=[-0.99999952] * 100, solution_fun=300, ), "arglble": _problem( # arglble is the same as linear_rank_one with specific settings - fun=partial(linear_rank_one, dim_out=400), + function=LinearRankOne(dim_out=400), start_x=[1] * 100, solution_x=solution_x_arglble, solution_fun=99.62547, ), "argtrig": _problem( - fun=argtrig, + function=Argtrig(), start_x=[1 / 100] * 100, solution_x=[0] * 100, solution_fun=0, ), "artif": _problem( - fun=artif, + function=Artif(), start_x=[1] * 100, solution_x=None, solution_fun=0, ), "arwhdne": _problem( - fun=arwhdne, + function=Arwhdne(), start_x=[1] * 100, solution_x=[0.706011] * 99 + [0], solution_fun=27.66203, ), "bdvalues": _problem( - fun=bdvalues, + function=Bdvalues(), start_x=get_start_points_bdvalues(100, 1000), solution_x=solution_x_bdvalues, solution_fun=0, ), "bratu_2d": _problem( - fun=partial(bratu_2d, alpha=4), + function=Bratu2d(alpha=4), start_x=[0] * 64, solution_x=solution_x_bratu_2d, solution_fun=0, ), "bratu_2d_t": _problem( - fun=partial(bratu_2d, alpha=6.80812), + function=Bratu2d(alpha=6.80812), start_x=[0] * 64, solution_x=solution_x_bratu_2d_t, solution_fun=1.8534736e-05, ), "bratu_3d": _problem( - fun=partial(bratu_3d, alpha=6.80812), + function=Bratu3d(alpha=6.80812), start_x=[0] * 27, solution_x=solution_x_bratu_3d, solution_fun=0, ), "brownale": _problem( - fun=brown_almost_linear, + function=BrownAlmostLinear(), start_x=[0.5] * 100, solution_x=[1] * 100, solution_fun=0, ), "broydn_3d": _problem( - fun=broydn_3d, + function=Broydn3d(), start_x=[-1] * 100, solution_x=solution_x_broydn_3d, solution_fun=0, ), "cbratu_2d": _problem( - fun=cbratu_2d, + function=Cbratu2d(), start_x=[0] * (2 * 5 * 5), solution_x=solution_x_cbratu_2d, solution_fun=0, ), "broydn_bd": _problem( - fun=broydn_bd, + function=BroydnBd(), start_x=[1] * 100, solution_x=solution_x_broydn_bd, solution_fun=0, ), "chandheq": _problem( - fun=chandheq, + function=Chandheq(), start_x=(np.arange(1, 101) / 100).tolist(), solution_x=None, solution_fun=0, ), "chemrcta": _problem( - fun=chemrcta, + function=Chemrcta(), start_x=[1] * 100, solution_x=None, solution_fun=0, bounds=Bounds(lower=np.concatenate([np.zeros(50), 1e-6 * np.ones(50)])), ), "chemrctb": _problem( - fun=chemrctb, + function=Chemrctb(), start_x=[1] * 100, solution_x=solution_x_chemrctb, solution_fun=1.404424e-3, bounds=Bounds(lower=1e-6 * np.ones(100)), ), "chnrsbne": _problem( - fun=chnrsbne, + function=Chnrsbne(), start_x=[-1] * 50, solution_x=[1] * 50, solution_fun=0, ), "drcavty1": _problem( - fun=partial(drcavty, r=500), + function=Drcavty(r=500), start_x=[0] * 100, solution_x=None, solution_fun=0, ), "drcavty2": _problem( - fun=partial(drcavty, r=1000), + function=Drcavty(r=1000), start_x=[0] * 100, solution_x=solution_x_drcavty2, solution_fun=3.988378e-4, ), "drcavty3": _problem( - fun=partial(drcavty, r=4500), + function=Drcavty(r=4500), start_x=[0] * 100, solution_x=solution_x_drcavty3, solution_fun=0, ), "eigena": _problem( - fun=partial(eigen, param=np.diag(np.arange(1, 11))), + function=Eigen(matrix=np.diag(np.arange(1.0, 11.0))), start_x=[1] * 10 + np.eye(10).flatten().tolist(), solution_x=[*np.arange(1, 11).tolist(), 1] + ([0] * 10 + [1]) * 9, solution_fun=0, bounds=Bounds(lower=np.zeros(110)), ), "eigenb": _problem( - fun=partial(eigen, param=np.diag(2 * np.ones(10)) + np.diag(-np.ones(9), k=1)), + function=Eigen(matrix=np.diag(2 * np.ones(10)) + np.diag(-np.ones(9), k=1)), start_x=[1] * 10 + np.eye(10).flatten().tolist(), solution_x=solution_x_eigenb, solution_fun=1.55654284, @@ -5079,109 +5354,79 @@ def _problem( # according to table 3 in their paper, the minimum is at 0. ), "flosp2hh": _problem( - fun=partial( - flosp2, - a=np.array([1, 0, -1], dtype=np.int64), - b=np.array([1, 0, -1], dtype=np.int64), - ra=1e7, - ), + function=Flosp2(a=(1, 0, -1), b=(1, 0, -1), ra=1e7), start_x=[0] * 59, solution_x=None, # multiple argmins solution_fun=1 / 3, ), "flosp2hl": _problem( - fun=partial( - flosp2, - a=np.array([1, 0, -1], dtype=np.float64), - b=np.array([1, 0, -1], dtype=np.float64), - ra=1e3, - ), + function=Flosp2(a=(1, 0, -1), b=(1, 0, -1), ra=1e3), start_x=[0] * 59, solution_x=None, # multiple argmins solution_fun=1 / 3, ), "flosp2hm": _problem( - fun=partial( - flosp2, - a=np.array([1, 0, -1], dtype=np.float64), - b=np.array([1, 0, -1], dtype=np.float64), - ra=1e5, - ), + function=Flosp2(a=(1, 0, -1), b=(1, 0, -1), ra=1e5), start_x=[0] * 59, solution_x=None, # multiple argmins solution_fun=1 / 3, ), "flosp2th": _problem( - fun=partial( - flosp2, - a=np.array([0, 1, 0], dtype=np.float64), - b=np.array([0, 1, 1], dtype=np.float64), - ra=1e7, - ), + function=Flosp2(a=(0, 1, 0), b=(0, 1, 1), ra=1e7), start_x=[0] * 59, solution_x=None, # multiple argmins solution_fun=0, ), "flosp2tl": _problem( - fun=partial( - flosp2, - a=np.array([0, 1, 0], dtype=np.float64), - b=np.array([0, 1, 1], dtype=np.float64), - ra=1e3, - ), + function=Flosp2(a=(0, 1, 0), b=(0, 1, 1), ra=1e3), start_x=[0] * 59, solution_x=None, # multiple argmins solution_fun=0, ), "flosp2tm": _problem( - fun=partial( - flosp2, - a=np.array([0, 1, 0], dtype=np.float64), - b=np.array([0, 1, 1], dtype=np.float64), - ra=1e5, - ), + function=Flosp2(a=(0, 1, 0), b=(0, 1, 1), ra=1e5), start_x=[0] * 59, solution_x=None, # multiple argmins solution_fun=0, ), "freurone": _problem( - fun=freurone, + function=Freurone(), start_x=[0.5, -2] + [0] * 98, solution_x=solution_x_freurone, solution_fun=1.196458e4, ), "hatfldg": _problem( - fun=hatfldg, + function=Hatfldg(), start_x=[1] * 25, solution_x=[0] * 11 + [-1, 1] + [0] * 12, solution_fun=0, ), "hydcar20": _problem( - fun=partial(hydcar, n=20, m=3, k=9), + function=Hydcar(n=20, m=3, k=9), start_x=get_start_points_hydcar20(), solution_x=solution_x_hydcar20, solution_fun=0, ), "hydcar6": _problem( - fun=partial(hydcar, n=6, m=3, k=2), + function=Hydcar(n=6, m=3, k=2), start_x=get_start_points_hydcar6(), solution_x=solution_x_hydcar6, solution_fun=0, ), "integreq": _problem( - fun=integreq, + function=Integreq(), start_x=(np.arange(1, 101) / 101 * (np.arange(1, 101) / 101 - 1)).tolist(), solution_x=solution_x_integreq, solution_fun=0, ), "luksan11": _problem( - fun=luksan11, + function=Luksan11(), start_x=[-0.8] * 100, solution_x=[1] * 100, solution_fun=0, ), "luksan12": _problem( - fun=luksan12, + function=Luksan12(), start_x=[-1] * 98, solution_x=None, # we found a lower minimum than Cartis and Roberts (2019) at 1651.837; @@ -5192,7 +5437,7 @@ def _problem( solution_fun=1651.837, ), "luksan13": _problem( - fun=luksan13, + function=Luksan13(), start_x=[-1] * 98, solution_x=solution_x_luksan13, solution_fun=24949.67040503685711883, @@ -5200,97 +5445,97 @@ def _problem( # according to table 3 in their paper, the minimum is at 25188.86 ), "luksan14": _problem( - fun=luksan14, + function=Luksan14(), start_x=[-1] * 98, solution_x=solution_x_luksan14, solution_fun=123.9235, ), "luksan15": _problem( - fun=luksan15, + function=Luksan15(), start_x=[-0.8, 1.2, -1.2, 0.8] * 25, solution_x=solution_x_luksan15, solution_fun=3.569697, ), "luksan16": _problem( - fun=luksan16, + function=Luksan16(), start_x=[-0.8, 1.2, -1.2, 0.8] * 25, solution_x=solution_x_luksan16, solution_fun=3.569697, ), "luksan17": _problem( - fun=luksan17, + function=Luksan17(), start_x=[-0.8, 1.2, -1.2, 0.8] * 25, solution_x=None, # multiple argmins solution_fun=0.4931613, ), "luksan21": _problem( - fun=luksan21, + function=Luksan21(), start_x=[ih * (ih - 1) for ih in np.arange(1, 101) * (1 / 101)], solution_x=solution_x_luksan21, solution_fun=0, ), "luksan22": _problem( - fun=luksan22, + function=Luksan22(), start_x=[-1.2 if i % 2 == 0 else 1 for i in range(100)], solution_x=solution_x_luksan22, solution_fun=872.9230, ), "methanb8": _problem( - fun=methane, + function=Methane(), start_x=get_start_points_methanb8(), solution_x=solution_x_methane, solution_fun=0, ), "methanl8": _problem( - fun=methane, + function=Methane(), start_x=get_start_points_methanl8(), solution_x=solution_x_methane, solution_fun=0, ), "morebvne": _problem( - fun=morebvne, + function=Morebvne(), start_x=[t * (t - 1) for t in np.arange(1, 101) * (1 / 101)], solution_x=solution_x_morebvne, solution_fun=0, ), "msqrta": _problem( - fun=msqrta, + function=Msqrta(), start_x=get_start_points_msqrta(10), solution_x=solution_x_msqrta, solution_fun=0, ), "msqrtb": _problem( - fun=msqrta, + function=Msqrta(), start_x=get_start_points_msqrta(10, flag=2), solution_x=solution_x_msqrtb, solution_fun=0, ), "oscigrne": _problem( - fun=oscigrne, + function=Oscigrne(), start_x=[-2] + [1] * 99, solution_x=solution_x_oscigrne, solution_fun=0, ), "penalty_1": _problem( - fun=penalty_1, + function=Penalty1(), start_x=list(range(1, 101)), solution_x=None, solution_fun=9.025000e-9, ), "penalty_2": _problem( - fun=penalty_2, + function=Penalty2(), start_x=[0.5] * 100, solution_x=solution_x_penalty2, solution_fun=0.9809377, ), "powellse": _problem( - fun=powell_singular, + function=ExtendedPowellSingular(), start_x=[3.0, -1.0, 0.0, 1] * 25, solution_x=[0] * 100, solution_fun=0, ), "qr3d": _problem( - fun=partial(qr3d, m=5), + function=Qr3d(m=5), start_x=get_start_points_qr3d(5), solution_x=solution_x_qr3d, solution_fun=0, @@ -5300,7 +5545,7 @@ def _problem( ), ), "qr3dbd": _problem( - fun=partial(qr3dbd, m=5), + function=Qr3dbd(), start_x=get_start_points_qr3dbd(5), solution_x=solution_x_qr3dbd, solution_fun=0, @@ -5310,44 +5555,44 @@ def _problem( ), ), "spmsqrt": _problem( - fun=spmsqrt, + function=Spmsqrt(), start_x=get_start_points_spmsqrt(34), solution_x=solution_x_spmsqrt, solution_fun=0, ), "semicn2u": _problem( - fun=semicon2, + function=Semicon2(), start_x=[0] * 100, solution_x=solution_x_semicon2, solution_fun=0, ), "semicon2": _problem( - fun=semicon2, + function=Semicon2(), start_x=[0] * 100, solution_x=solution_x_semicon2, solution_fun=0, bounds=Bounds(lower=-5 * np.ones(100), upper=0.2 * 700 * np.ones(100)), ), "vardimne": _problem( - fun=vardimne, + function=Vardimne(), start_x=[1 - i / 100 for i in range(1, 101)], solution_x=[1] * 100, solution_fun=0, ), "watsonne": _problem( - fun=watson, + function=Watson(), start_x=[0] * 31, solution_x=solution_x_watson, solution_fun=0, ), "yatpsq_1": _problem( - fun=partial(yatpsq_1, dim_in=10), + function=Yatpsq1(dim_in=10), start_x=[6] * 100 + [0] * 20, solution_x=solution_x_yatpsq_1, solution_fun=0, ), "yatpsq_2": _problem( - fun=partial(yatpsq_2, dim_in=10), + function=Yatpsq2(dim_in=10), start_x=[10] * 100 + [0] * 20, solution_x=solution_x_yatpsq_2, solution_fun=0, diff --git a/tests/optimagic/benchmarking/test_benchmark_problem.py b/tests/optimagic/benchmarking/test_benchmark_problem.py index 67c862832..faf2a2203 100644 --- a/tests/optimagic/benchmarking/test_benchmark_problem.py +++ b/tests/optimagic/benchmarking/test_benchmark_problem.py @@ -9,7 +9,6 @@ BenchmarkFunction, BenchmarkProblem, BenchmarkSolution, - CallableBenchmarkFunction, aggregate_function_value, ) from optimagic.benchmarking.noise import AdditiveBenchmarkNoise @@ -257,65 +256,6 @@ def fun(self, x): problem.start_fun # noqa: B018 -# ====================================================================================== -# CallableBenchmarkFunction -# ====================================================================================== - - -def test_callable_benchmark_function(): - @om.mark.least_squares - def residuals(x): - return x - 1 - - @om.mark.least_squares - def residual_jac(x): - return np.eye(len(x)) - - def gradient(x): - return 2 * (x - 1) - - function = CallableBenchmarkFunction( - func=residuals, - jac_funcs=[residual_jac, gradient], - differentiable=True, - multimodal=False, - min_n_params=2, - max_n_params=3, - ) - assert function.problem_type == LEAST_SQUARES - aaae(function.fun(np.array([1.0, 3.0])), np.array([0.0, 2.0])) - assert function.has_jac - assert function.jac(LEAST_SQUARES) is residual_jac - # functions without a mark are for scalar optimizers - assert function.jac(SCALAR) is gradient - assert function.jac(LIKELIHOOD) is None - assert function.differentiable is True - assert function.convex is None - assert function.multimodal is False - assert function.supports_n_params(3) - assert not function.supports_n_params(4) - - -def test_callable_benchmark_function_without_mark_is_scalar(): - function = CallableBenchmarkFunction(func=lambda x: float(x @ x)) - assert function.problem_type == SCALAR - assert not function.has_jac - assert function.jac(SCALAR) is None - - -def test_callable_benchmark_function_with_two_jacs_for_one_solver_type_raises(): - with pytest.raises(ValueError, match="more than one derivative"): - CallableBenchmarkFunction( - func=lambda x: float(x @ x), - jac_funcs=[lambda x: 2 * x, om.mark.scalar(lambda x: 2 * x)], - ) - - -def test_callable_benchmark_function_with_invalid_func_raises(): - with pytest.raises(TypeError, match="func must be callable"): - CallableBenchmarkFunction(func=1) # ty: ignore[invalid-argument-type] - - # ====================================================================================== # BenchmarkProblem: construction # ====================================================================================== @@ -735,10 +675,14 @@ def test_marking_the_jac_of_a_problem_does_not_modify_the_function(): def gradient(x): return 2 * x - function = CallableBenchmarkFunction( - func=lambda x: float(x @ x), jac_funcs=[gradient] - ) - problem = BenchmarkProblem(function=function, start_params=np.ones(2)) + class SphereWithGradient(BenchmarkFunction): + def fun(self, x): + return float(x @ x) + + def jac(self, solver_type): + return gradient if solver_type == SCALAR else None + + problem = BenchmarkProblem(function=SphereWithGradient(), start_params=np.ones(2)) derivative = problem.jac(SCALAR) assert derivative is not None assert derivative is not gradient diff --git a/tests/optimagic/benchmarking/test_cartis_roberts.py b/tests/optimagic/benchmarking/test_cartis_roberts.py index bd667a9aa..83ed18a4f 100644 --- a/tests/optimagic/benchmarking/test_cartis_roberts.py +++ b/tests/optimagic/benchmarking/test_cartis_roberts.py @@ -102,6 +102,13 @@ def test_cartis_roberts_function_is_least_squares_function(name, problem): # no assert problem.function.fun(problem.start_params).ndim == 1 +def test_problems_with_the_same_function_and_parameters_have_equal_functions(): + problems = CARTIS_ROBERTS_PROBLEMS + assert problems["methanb8"].function == problems["methanl8"].function + assert problems["flosp2hh"].function != problems["flosp2hl"].function + assert hash(problems["flosp2hh"].function) == hash(problems["flosp2hh"].function) + + def test_bounds_of_original_problems_are_only_stored_in_info(): with_bounds = { name for name, problem in CARTIS_ROBERTS_PROBLEMS.items() if problem.info From ffc5847ca5e5d65267f81715acea410579d8a6a9 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Tue, 24 Nov 2026 09:57:43 +0100 Subject: [PATCH 5/6] Add changelog entry for #751. Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index bae96df47..8aef38a02 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,14 @@ releases are available on [Anaconda.org](https://anaconda.org/optimagic-dev/opti This release adds experimental support for **SciPy-style callbacks**, replaces pybaum by **optree** for pytree handling and uses **pydantic** to validate algorithm options. +- {gh}`751` Adds typed benchmark problems as proposed in EP-02. A `BenchmarkFunction` + holds the objective function, its closed form derivatives and properties like + convexity; a `BenchmarkProblem` combines it with start parameters, an optional known + solution, noise and scaling. `run_benchmark` returns `BenchmarkResult` objects and + accepts `OptimizeOptions`. Lists of algorithms and dictionaries of `minimize` + arguments in `run_benchmark`, as well as the noise and scaling options of + `get_benchmark_problems`, are deprecated and will be removed in version 0.7.0 + ({ghuser}`janosg`). - {gh}`747` Reduces the time it takes to import optimagic from about 2 seconds to about 0.6 seconds. Dependencies that are only needed for some features (scipy, numba, sqlalchemy, plotly.express and joblib) are imported when they are used, the From 0f3fe72503f2932ea00f566225edfe6f3b91369e Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Tue, 24 Nov 2026 10:24:29 +0100 Subject: [PATCH 6/6] Move the calculations of benchmark functions into private pure functions. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each Moré-Wild and Cartis-Roberts class only calls a private pure function that is defined right below the class; numba-jitted functions follow the same layout. The jac docstring and the test helper classes follow the same pattern for derivatives. The residuals of all 114 problems are bit-identical before and after the change. Co-Authored-By: Claude Opus 5.5 --- .../benchmarking/benchmark_problem.py | 35 +- src/optimagic/benchmarking/cartis_roberts.py | 2323 +++++++++-------- src/optimagic/benchmarking/more_wild.py | 566 ++-- .../benchmarking/test_benchmark_problem.py | 73 +- 4 files changed, 1563 insertions(+), 1434 deletions(-) diff --git a/src/optimagic/benchmarking/benchmark_problem.py b/src/optimagic/benchmarking/benchmark_problem.py index c1490f2f2..6cdc6323e 100644 --- a/src/optimagic/benchmarking/benchmark_problem.py +++ b/src/optimagic/benchmarking/benchmark_problem.py @@ -52,24 +52,40 @@ class BenchmarkFunction(ABC): scalar function. The mark is inherited by subclasses. Parameters of a family of functions (e.g. the number of residuals) are attributes - of the subclass. If the objective function already exists as a Python function, - ``fun`` simply calls it. + of the subclass. The calculations are best defined in pure functions next to the + class; ``fun`` and ``jac`` only call or return them. A benchmark function is not tied to one number of parameters. The number of parameters is fixed by the start parameters of a ``BenchmarkProblem``. Example: - A least-squares function for any number of parameters:: + A least-squares function for any number of parameters with a closed form + jacobian for least-squares optimizers:: @om.mark.least_squares @dataclass(frozen=True) - class Sphere(om.BenchmarkFunction): + class ShiftedSphere(om.BenchmarkFunction): + shift: float = 1.0 + differentiable = True convex = True multimodal = False def fun(self, x): - return x + return _shifted_sphere(x, shift=self.shift) + + def jac(self, solver_type): + if solver_type == om.typing.AggregationLevel.LEAST_SQUARES: + return _shifted_sphere_jac + return None + + + def _shifted_sphere(x, shift): + return x - shift + + + def _shifted_sphere_jac(x): + return np.eye(len(x)) """ @@ -125,10 +141,11 @@ def jac(self, solver_type: AggregationLevel) -> DerivativeFunction | None: # no the residuals, whereas a scalar optimizer needs the gradient of the sum of squared residuals. - Subclasses override this method, define the derivative function for the - requested solver type inside of it and return it. Return None for solver types - without a closed form derivative; optimizers of that type then use numerical - derivatives. + Subclasses override this method and return the derivative function for the + requested solver type. Define the derivatives as pure functions next to the + class; attributes of the class can be bound with ``functools.partial``. Return + None for solver types without a closed form derivative; optimizers of that type + then use numerical derivatives. Args: solver_type: The type of optimizer the derivative is for. diff --git a/src/optimagic/benchmarking/cartis_roberts.py b/src/optimagic/benchmarking/cartis_roberts.py index 688285f5b..c44c09723 100644 --- a/src/optimagic/benchmarking/cartis_roberts.py +++ b/src/optimagic/benchmarking/cartis_roberts.py @@ -49,11 +49,15 @@ class Luksan11(BenchmarkFunction): """The LUKSAN11 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = np.zeros(2 * (dim_in - 1)) - fvec[::2] = 20 * x[:-1] / (1 + x[:-1] ** 2) - 10 * x[1:] - fvec[1::2] = x[:-1] - 1 - return fvec + return _luksan11(x) + + +def _luksan11(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(2 * (dim_in - 1)) + fvec[::2] = 20 * x[:-1] / (1 + x[:-1] ** 2) - 10 * x[1:] + fvec[1::2] = x[:-1] - 1 + return fvec @mark.least_squares @@ -62,17 +66,21 @@ class Luksan12(BenchmarkFunction): """The LUKSAN12 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - n = (dim_in - 2) // 3 - i = np.arange(0, 3 * n, 3) - fvec = np.zeros(6 * n) - fvec[::6] = 10 * (x[i] ** 2 - x[i + 1]) - fvec[1::6] = x[i + 2] - 1 - fvec[2::6] = (x[i + 3] - 1) ** 2 - fvec[3::6] = (x[i + 4] - 1) ** 3 - fvec[4::6] = x[i] ** 2 * x[i + 3] + np.sin(x[i + 3] - x[i + 4]) - 10 - fvec[5::6] = x[i + 1] + (x[i + 2] ** 4) * (x[i + 3] ** 2) - 20 - return fvec + return _luksan12(x) + + +def _luksan12(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + n = (dim_in - 2) // 3 + i = np.arange(0, 3 * n, 3) + fvec = np.zeros(6 * n) + fvec[::6] = 10 * (x[i] ** 2 - x[i + 1]) + fvec[1::6] = x[i + 2] - 1 + fvec[2::6] = (x[i + 3] - 1) ** 2 + fvec[3::6] = (x[i + 4] - 1) ** 3 + fvec[4::6] = x[i] ** 2 * x[i + 3] + np.sin(x[i + 3] - x[i + 4]) - 10 + fvec[5::6] = x[i + 1] + (x[i + 2] ** 4) * (x[i + 3] ** 2) - 20 + return fvec @mark.least_squares @@ -81,20 +89,24 @@ class Luksan13(BenchmarkFunction): """The LUKSAN13 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - n = (dim_in - 2) // 3 - fvec = np.zeros(n * 7) - i = np.arange(n) - k = i * 7 - fvec[k] = 10 * (x[3 * i] ** 2 - x[3 * i + 1]) - fvec[k + 1] = 10 * (x[3 * i + 1] ** 2 - x[3 * i + 2]) - fvec[k + 2] = (x[3 * i + 2] - x[3 * i + 3]) ** 2 - fvec[k + 3] = (x[3 * i + 3] - x[3 * i + 4]) ** 2 - fvec[k + 4] = x[3 * i] + x[3 * i + 1] ** 2 + x[3 * i + 2] - 30 - fvec[k + 5] = x[3 * i + 1] - x[3 * i + 2] ** 2 + x[3 * i + 3] - 10 - fvec[k + 6] = x[3 * i + 1] * x[3 * i + 4] - 10 - - return fvec + return _luksan13(x) + + +def _luksan13(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + n = (dim_in - 2) // 3 + fvec = np.zeros(n * 7) + i = np.arange(n) + k = i * 7 + fvec[k] = 10 * (x[3 * i] ** 2 - x[3 * i + 1]) + fvec[k + 1] = 10 * (x[3 * i + 1] ** 2 - x[3 * i + 2]) + fvec[k + 2] = (x[3 * i + 2] - x[3 * i + 3]) ** 2 + fvec[k + 3] = (x[3 * i + 3] - x[3 * i + 4]) ** 2 + fvec[k + 4] = x[3 * i] + x[3 * i + 1] ** 2 + x[3 * i + 2] - 30 + fvec[k + 5] = x[3 * i + 1] - x[3 * i + 2] ** 2 + x[3 * i + 3] - 10 + fvec[k + 6] = x[3 * i + 1] * x[3 * i + 4] - 10 + + return fvec @mark.least_squares @@ -103,23 +115,27 @@ class Luksan14(BenchmarkFunction): """The LUKSAN14 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - dim_out = 7 * (dim_in - 2) // 3 - fvec = np.zeros(dim_out, dtype=np.float64) - - for i in range(0, dim_in - 2, 3): - k = (i // 3) * 7 - fvec[k : k + 7] = [ - 10 * (x[i] ** 2 - x[i + 1]), - x[i + 1] + x[i + 2] - 2, - x[i + 3] - 1, - x[i + 4] - 1, - x[i] + 3 * x[i + 1], - x[i + 2] + x[i + 3] - 2 * x[i + 4], - 10 * (x[i + 1] ** 2 - x[i + 4]), - ] + return _luksan14(x) - return fvec + +def _luksan14(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = 7 * (dim_in - 2) // 3 + fvec = np.zeros(dim_out, dtype=np.float64) + + for i in range(0, dim_in - 2, 3): + k = (i // 3) * 7 + fvec[k : k + 7] = [ + 10 * (x[i] ** 2 - x[i + 1]), + x[i + 1] + x[i + 2] - 2, + x[i + 3] - 1, + x[i + 4] - 1, + x[i] + 3 * x[i + 1], + x[i + 2] + x[i + 3] - 2 * x[i + 4], + 10 * (x[i + 1] ** 2 - x[i + 4]), + ] + + return fvec @mark.least_squares @@ -128,24 +144,28 @@ class Luksan15(BenchmarkFunction): """The LUKSAN15 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - dim_out = (dim_in - 2) * 2 - temp = np.zeros((dim_out, 3), dtype=np.float64) - y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) + return _luksan15(x) - for p in range(1, 4): - k = 0 - for i in range(0, dim_in - 2, 2): - for j in range(1, 5): - temp[k, p - 1] = (p**2 / j) * np.abs( - x[i] * (x[i + 1] ** 2) * (x[i + 2] ** 3) * (x[i + 3] ** 4) - ) ** (1 / (p * j)) - k += 1 +def _luksan15(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = (dim_in - 2) * 2 + temp = np.zeros((dim_out, 3), dtype=np.float64) + y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) + + for p in range(1, 4): + k = 0 + for i in range(0, dim_in - 2, 2): + for j in range(1, 5): + temp[k, p - 1] = (p**2 / j) * np.abs( + x[i] * (x[i + 1] ** 2) * (x[i + 2] ** 3) * (x[i + 3] ** 4) + ) ** (1 / (p * j)) - fvec = y - np.sum(temp, axis=1) + k += 1 - return fvec + fvec = y - np.sum(temp, axis=1) + + return fvec @mark.least_squares @@ -154,24 +174,27 @@ class Luksan16(BenchmarkFunction): """The LUKSAN16 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - dim_out = (dim_in - 2) * 2 - temp = np.zeros((dim_out, 3), dtype=np.float64) - y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) + return _luksan16(x) + - for p in range(1, 4): - k = 0 - for i in range(0, dim_in - 2, 2): - for j in range(1, 5): - temp[k, p - 1] = (p**2 / j) * np.exp( - (x[i] + 2 * x[i + 1] + 3 * x[i + 2] + 4 * x[i + 3]) - * (1 / (p * j)) - ) - k += 1 +def _luksan16(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = (dim_in - 2) * 2 + temp = np.zeros((dim_out, 3), dtype=np.float64) + y = np.tile([35.8, 11.2, 6.2, 4.4], dim_out // 4) + + for p in range(1, 4): + k = 0 + for i in range(0, dim_in - 2, 2): + for j in range(1, 5): + temp[k, p - 1] = (p**2 / j) * np.exp( + (x[i] + 2 * x[i + 1] + 3 * x[i + 2] + 4 * x[i + 3]) * (1 / (p * j)) + ) + k += 1 - fvec = y - np.sum(temp, axis=1) + fvec = y - np.sum(temp, axis=1) - return fvec + return fvec @mark.least_squares @@ -180,23 +203,27 @@ class Luksan17(BenchmarkFunction): """The LUKSAN17 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - dim_out = (dim_in - 2) * 2 - temp = np.zeros((dim_out, 4), dtype=np.float64) - y = np.tile([30.6, 72.2, 124.4, 187.4], dim_out // 4) + return _luksan17(x) - for q in range(1, 5): - k = 0 - for i in range(-1, dim_in - 4, 2): - for j in range(1, 5): - temp[k, q - 1] += -j * q**2 * np.sin(x[i + q]) + j**2 * q * np.cos( - x[i + q] - ) - k += 1 - fvec = y - np.sum(temp, axis=1) +def _luksan17(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + dim_out = (dim_in - 2) * 2 + temp = np.zeros((dim_out, 4), dtype=np.float64) + y = np.tile([30.6, 72.2, 124.4, 187.4], dim_out // 4) + + for q in range(1, 5): + k = 0 + for i in range(-1, dim_in - 4, 2): + for j in range(1, 5): + temp[k, q - 1] += -j * q**2 * np.sin(x[i + q]) + j**2 * q * np.cos( + x[i + q] + ) + k += 1 + + fvec = y - np.sum(temp, axis=1) - return fvec + return fvec @mark.least_squares @@ -205,22 +232,26 @@ class Luksan21(BenchmarkFunction): """The LUKSAN21 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_out = len(x) - h = 1 / (dim_out + 1) - fvec = np.zeros(dim_out, dtype=np.float64) - - fvec[0] = 2 * x[0] + 0.5 * h**2 * (x[0] + h + 1) ** 3 - x[1] + 1 - for i in range(1, dim_out - 1): - fvec[i] = ( - 2 * x[i] - + 0.5 * h**2 * (x[i] + h * (i + 1) + 1) ** 3 - - x[i - 1] - - x[i + 1] - + 1 - ) - fvec[-1] = 2 * x[-1] + 0.5 * h**2 * (x[-1] + h * dim_out + 1) ** 3 - x[-2] + 1 + return _luksan21(x) - return fvec + +def _luksan21(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_out = len(x) + h = 1 / (dim_out + 1) + fvec = np.zeros(dim_out, dtype=np.float64) + + fvec[0] = 2 * x[0] + 0.5 * h**2 * (x[0] + h + 1) ** 3 - x[1] + 1 + for i in range(1, dim_out - 1): + fvec[i] = ( + 2 * x[i] + + 0.5 * h**2 * (x[i] + h * (i + 1) + 1) ** 3 + - x[i - 1] + - x[i + 1] + + 1 + ) + fvec[-1] = 2 * x[-1] + 0.5 * h**2 * (x[-1] + h * dim_out + 1) ** 3 - x[-2] + 1 + + return fvec @mark.least_squares @@ -229,15 +260,19 @@ class Luksan22(BenchmarkFunction): """The LUKSAN22 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_out = 2 * len(x) - 2 - fvec = np.zeros(dim_out) - fvec[0] = x[0] - 1 - fvec[1:-1:2] = 10 * (x[:-2] ** 2 - x[1:-1]) - fvec[2:-1:2] = 2 * np.exp(-((x[:-2] - x[1:-1]) ** 2)) + np.exp( - -2 * (x[1:-1] - x[2:]) ** 2 - ) - fvec[-1] = -10 * (x[-2] ** 2) - return fvec + return _luksan22(x) + + +def _luksan22(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_out = 2 * len(x) - 2 + fvec = np.zeros(dim_out) + fvec[0] = x[0] - 1 + fvec[1:-1:2] = 10 * (x[:-2] ** 2 - x[1:-1]) + fvec[2:-1:2] = 2 * np.exp(-((x[:-2] - x[1:-1]) ** 2)) + np.exp( + -2 * (x[1:-1] - x[2:]) ** 2 + ) + fvec[-1] = -10 * (x[-2] ** 2) + return fvec @mark.least_squares @@ -246,22 +281,51 @@ class Morebvne(BenchmarkFunction): """The MOREBVNE function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - h = 1 / (dim_in + 1) - i = np.arange(1, dim_in + 1) - fvec = np.zeros(dim_in) - - fvec[0] = 2 * x[0] - x[1] + h**2 / 2 * (x[0] + i[0] * h + 1) ** 3 - fvec[1:-1] = ( - 2 * x[1:-1] - x[:-2] - x[2:] + h**2 / 2 * (x[1:-1] + i[1:-1] * h + 1) ** 3 - ) - fvec[-1] = 2 * x[-2] - x[-2] + h**2 / 2 * (x[-1] + i[-1] * h + 1) ** 3 + return _morebvne(x) + + +def _morebvne(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + h = 1 / (dim_in + 1) + i = np.arange(1, dim_in + 1) + fvec = np.zeros(dim_in) + + fvec[0] = 2 * x[0] - x[1] + h**2 / 2 * (x[0] + i[0] * h + 1) ** 3 + fvec[1:-1] = ( + 2 * x[1:-1] - x[:-2] - x[2:] + h**2 / 2 * (x[1:-1] + i[1:-1] * h + 1) ** 3 + ) + fvec[-1] = 2 * x[-2] - x[-2] + h**2 / 2 * (x[-1] + i[-1] * h + 1) ** 3 + + return fvec + + +@mark.least_squares +@dataclass(frozen=True) +class Flosp2(BenchmarkFunction): + """The FLOSP2 function from the CUTEst collection.""" + + a: tuple[float, float, float] + """Coefficients of the boundary conditions.""" - return fvec + b: tuple[float, float, float] + """Coefficients of the boundary conditions.""" + + ra: float = 1.0e7 + """The Rayleigh number.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return _flosp2( + x, + a=np.array(self.a, dtype=np.float64), + b=np.array(self.b, dtype=np.float64), + ra=self.ra, + ) @njit -def flosp2(x, a, b, ra=1.0e7): +def _flosp2( + x: NDArray[np.float64], a: NDArray[np.float64], b: NDArray[np.float64], ra: float +) -> NDArray[np.float64]: n = 5 xvec = np.ones((3, n, n), dtype=np.float64) xvec[0] = x[: n**2].reshape(n, n) @@ -374,45 +438,26 @@ def flosp2(x, a, b, ra=1.0e7): @mark.least_squares @dataclass(frozen=True) -class Flosp2(BenchmarkFunction): - """The FLOSP2 function from the CUTEst collection.""" - - a: tuple[float, float, float] - """Coefficients of the boundary conditions.""" - - b: tuple[float, float, float] - """Coefficients of the boundary conditions.""" - - ra: float = 1.0e7 - """The Rayleigh number.""" +class Oscigrne(BenchmarkFunction): + """The OSCIGRNE function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return flosp2( - x, - np.array(self.a, dtype=np.float64), - np.array(self.b, dtype=np.float64), - self.ra, - ) + return _oscigrne(x) -@mark.least_squares -@dataclass(frozen=True) -class Oscigrne(BenchmarkFunction): - """The OSCIGRNE function from the CUTEst collection.""" +def _oscigrne(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + rho = 500 - def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - rho = 500 - - fvec = np.zeros(dim_in) - fvec[0] = 0.5 * x[0] - 0.5 - 4 * rho * (x[1] - 2.0 * x[0] ** 2 + 1.0) * x[0] - fvec[1:-1] = ( - 2 * rho * (x[1:-1] - 2.0 * x[:-2] ** 2 + 1.0) - - 4 * rho * (x[2:] - 2.0 * x[:-2] ** 2 + 1.0) * x[2:] - ) - fvec[-1] = 2 * rho * (x[-1] - 2.0 * x[-2] ** 2 + 1.0) + fvec = np.zeros(dim_in) + fvec[0] = 0.5 * x[0] - 0.5 - 4 * rho * (x[1] - 2.0 * x[0] ** 2 + 1.0) * x[0] + fvec[1:-1] = ( + 2 * rho * (x[1:-1] - 2.0 * x[:-2] ** 2 + 1.0) + - 4 * rho * (x[2:] - 2.0 * x[:-2] ** 2 + 1.0) * x[2:] + ) + fvec[-1] = 2 * rho * (x[-1] - 2.0 * x[-2] ** 2 + 1.0) - return fvec + return fvec @mark.least_squares @@ -421,79 +466,81 @@ class Spmsqrt(BenchmarkFunction): """The SPMSQRT function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - m = (len(x) + 2) // 3 - xmat = np.diag(x[2:-1:3], -1) + np.diag(x[::3], 0) + np.diag(x[1:-2:3], 1) - - b = np.zeros((m, m), dtype=np.float64) - b[0, 0] = np.sin(1) - b[0, 1] = np.sin(4) - k = 2 - for i in range(1, m - 1): - k += 1 - b[i, i - 1] = np.sin(k**2) - k += 1 - b[i, i] = np.sin(k**2) - k += 1 - b[i, i + 1] = np.sin(k**2) + return _spmsqrt(x) + + +def _spmsqrt(x: NDArray[np.float64]) -> NDArray[np.float64]: + m = (len(x) + 2) // 3 + xmat = np.diag(x[2:-1:3], -1) + np.diag(x[::3], 0) + np.diag(x[1:-2:3], 1) + + b = np.zeros((m, m), dtype=np.float64) + b[0, 0] = np.sin(1) + b[0, 1] = np.sin(4) + k = 2 + for i in range(1, m - 1): k += 1 - b[-1, -2] = np.sin(k**2) + b[i, i - 1] = np.sin(k**2) k += 1 - b[-1, -1] = np.sin(k**2) - - fmat = np.zeros((m, m), dtype=np.float64) - fmat[0, 0] = xmat[0, 0] ** 2 + xmat[0, 1] * xmat[1, 0] - fmat[0, 1] = xmat[0, 0] * xmat[0, 1] + xmat[0, 1] * xmat[1, 1] - fmat[0, 2] = xmat[0, 1] * xmat[1, 2] - - fmat[1, 0] = xmat[1, 0] * xmat[0, 0] + xmat[1, 1] * xmat[1, 0] - fmat[1, 1] = xmat[1, 0] * xmat[0, 1] + xmat[1, 1] ** 2 + xmat[1, 2] * xmat[2, 1] - fmat[1, 2] = xmat[1, 1] * xmat[1, 2] + xmat[1, 2] * xmat[2, 2] - fmat[1, 3] = xmat[1, 2] * xmat[2, 3] - - for i in range(2, m - 2): - fmat[i, i - 2] = xmat[i, i - 1] * xmat[i - 1, i - 2] - fmat[i, i - 1] = ( - xmat[i, i - 1] * xmat[i - 1, i - 1] + xmat[i, i] * xmat[i, i - 1] - ) - fmat[i, i] = ( - xmat[i, i - 1] * xmat[i - 1, i] - + xmat[i, i] ** 2 - + xmat[i, i + 1] * xmat[i + 1, i] - ) - fmat[i, i + 1] = ( - xmat[i, i] * xmat[i, i + 1] + xmat[i, i + 1] * xmat[i + 1, i + 1] - ) - fmat[i, i + 2] = xmat[i, i + 1] * xmat[i + 1, i + 2] - - fmat[-2, -4] = xmat[-2, -3] * xmat[-3, -4] - fmat[-2, -3] = xmat[-2, -3] * xmat[-3, -3] + xmat[-2, -2] * xmat[-2, -3] - fmat[-2, -2] = ( - xmat[-2, -3] * xmat[-3, -2] - + xmat[-2, -2] ** 2 - + xmat[-2, -1] * xmat[-1, -2] + b[i, i] = np.sin(k**2) + k += 1 + b[i, i + 1] = np.sin(k**2) + k += 1 + b[-1, -2] = np.sin(k**2) + k += 1 + b[-1, -1] = np.sin(k**2) + + fmat = np.zeros((m, m), dtype=np.float64) + fmat[0, 0] = xmat[0, 0] ** 2 + xmat[0, 1] * xmat[1, 0] + fmat[0, 1] = xmat[0, 0] * xmat[0, 1] + xmat[0, 1] * xmat[1, 1] + fmat[0, 2] = xmat[0, 1] * xmat[1, 2] + + fmat[1, 0] = xmat[1, 0] * xmat[0, 0] + xmat[1, 1] * xmat[1, 0] + fmat[1, 1] = xmat[1, 0] * xmat[0, 1] + xmat[1, 1] ** 2 + xmat[1, 2] * xmat[2, 1] + fmat[1, 2] = xmat[1, 1] * xmat[1, 2] + xmat[1, 2] * xmat[2, 2] + fmat[1, 3] = xmat[1, 2] * xmat[2, 3] + + for i in range(2, m - 2): + fmat[i, i - 2] = xmat[i, i - 1] * xmat[i - 1, i - 2] + fmat[i, i - 1] = ( + xmat[i, i - 1] * xmat[i - 1, i - 1] + xmat[i, i] * xmat[i, i - 1] + ) + fmat[i, i] = ( + xmat[i, i - 1] * xmat[i - 1, i] + + xmat[i, i] ** 2 + + xmat[i, i + 1] * xmat[i + 1, i] ) - fmat[-2, -1] = xmat[-2, -2] * xmat[-2, -1] + xmat[-2, -1] * xmat[-1, -1] + fmat[i, i + 1] = ( + xmat[i, i] * xmat[i, i + 1] + xmat[i, i + 1] * xmat[i + 1, i + 1] + ) + fmat[i, i + 2] = xmat[i, i + 1] * xmat[i + 1, i + 2] - fmat[-1, -3] = xmat[-1, -2] * xmat[-2, -3] - fmat[-1, -2] = xmat[-1, -2] * xmat[-2, -2] + xmat[-1, -1] * xmat[-1, -2] - fmat[-1, -1] = xmat[-1, -2] * xmat[-2, -1] + xmat[-1, -1] ** 2 + fmat[-2, -4] = xmat[-2, -3] * xmat[-3, -4] + fmat[-2, -3] = xmat[-2, -3] * xmat[-3, -3] + xmat[-2, -2] * xmat[-2, -3] + fmat[-2, -2] = ( + xmat[-2, -3] * xmat[-3, -2] + xmat[-2, -2] ** 2 + xmat[-2, -1] * xmat[-1, -2] + ) + fmat[-2, -1] = xmat[-2, -2] * xmat[-2, -1] + xmat[-2, -1] * xmat[-1, -1] - fmat[0, 0] -= b[0, 0] ** 2 + b[0, 1] * b[1, 0] - for i in range(1, m - 1): - fmat[i, i] -= ( - b[i, i] ** 2 + b[i - 1, i] * b[i, i - 1] + b[i + 1, i] * b[i, i + 1] - ) - fmat[-1, -1] -= b[-1, -1] ** 2 + b[-2, -1] * b[-1, -2] - for i in range(m - 1): - fmat[i + 1, i] -= b[i + 1, i] * b[i, i] + b[i + 1, i + 1] * b[i + 1, i] - for i in range(1, m): - fmat[i - 1, i] -= b[i - 1, i] * b[i, i] + b[i - 1, i - 1] * b[i - 1, i] - for i in range(1, m - 1): - fmat[i + 1, i - 1] -= b[i + 1, i] * b[i, i - 1] - for i in range(1, m - 1): - fmat[i - 1, i + 1] -= b[i - 1, i] * b[i, i + 1] + fmat[-1, -3] = xmat[-1, -2] * xmat[-2, -3] + fmat[-1, -2] = xmat[-1, -2] * xmat[-2, -2] + xmat[-1, -1] * xmat[-1, -2] + fmat[-1, -1] = xmat[-1, -2] * xmat[-2, -1] + xmat[-1, -1] ** 2 - return fmat.flatten() + fmat[0, 0] -= b[0, 0] ** 2 + b[0, 1] * b[1, 0] + for i in range(1, m - 1): + fmat[i, i] -= ( + b[i, i] ** 2 + b[i - 1, i] * b[i, i - 1] + b[i + 1, i] * b[i, i + 1] + ) + fmat[-1, -1] -= b[-1, -1] ** 2 + b[-2, -1] * b[-1, -2] + for i in range(m - 1): + fmat[i + 1, i] -= b[i + 1, i] * b[i, i] + b[i + 1, i + 1] * b[i + 1, i] + for i in range(1, m): + fmat[i - 1, i] -= b[i - 1, i] * b[i, i] + b[i - 1, i - 1] * b[i - 1, i] + for i in range(1, m - 1): + fmat[i + 1, i - 1] -= b[i + 1, i] * b[i, i - 1] + for i in range(1, m - 1): + fmat[i - 1, i + 1] -= b[i - 1, i] * b[i, i + 1] + + return fmat.flatten() @mark.least_squares @@ -502,49 +549,53 @@ class Semicon2(BenchmarkFunction): """The SEMICON2 function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - n = len(x) // 1 - ln = 9 * n // 10 - - lambda_ = 0.2 - a = -0.00009 - b = 0.00001 - ua = 0.0 - ub = 700.0 - ca = 1e12 - cb = 1e13 - beta = 40.0 - - h = (b - a) / (n + 1) - lb = lambda_ * beta - lua = lambda_ * ua - lub = lambda_ * ub - - xvec = np.zeros(n + 2, dtype=np.float64) - xvec[0] = lua - xvec[1:-1] = x - xvec[-1] = lub - - fvec = np.zeros(n, dtype=np.float64) - for i in range(1, ln + 1): - fvec[i - 1] = ( - xvec[i - 1] - - 2 * xvec[i] - + xvec[i + 1] - + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) - - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) - - lambda_ * (h**2) * ca - ) - for i in range(ln + 1, n + 1): - fvec[i - 1] = ( - xvec[i - 1] - - 2 * xvec[i] - + xvec[i + 1] - - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) - + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) - + lambda_ * (h**2) * cb - ) + return _semicon2(x) + + +def _semicon2(x: NDArray[np.float64]) -> NDArray[np.float64]: + n = len(x) // 1 + ln = 9 * n // 10 + + lambda_ = 0.2 + a = -0.00009 + b = 0.00001 + ua = 0.0 + ub = 700.0 + ca = 1e12 + cb = 1e13 + beta = 40.0 + + h = (b - a) / (n + 1) + lb = lambda_ * beta + lua = lambda_ * ua + lub = lambda_ * ub + + xvec = np.zeros(n + 2, dtype=np.float64) + xvec[0] = lua + xvec[1:-1] = x + xvec[-1] = lub + + fvec = np.zeros(n, dtype=np.float64) + for i in range(1, ln + 1): + fvec[i - 1] = ( + xvec[i - 1] + - 2 * xvec[i] + + xvec[i + 1] + + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) + - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) + - lambda_ * (h**2) * ca + ) + for i in range(ln + 1, n + 1): + fvec[i - 1] = ( + xvec[i - 1] + - 2 * xvec[i] + + xvec[i + 1] + - lambda_ * (h**2) * cb * np.exp(lb * (xvec[i] - lub)) + + lambda_ * (h**2) * ca * np.exp(-lb * (xvec[i] - lua)) + + lambda_ * (h**2) * cb + ) - return fvec + return fvec @mark.least_squares @@ -556,47 +607,48 @@ class Qr3d(BenchmarkFunction): """The number of rows and columns of the matrices Q and R.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - m = self.m - q = x[: m**2].reshape(m, m) - r = np.zeros((m, m), dtype=np.float64) - r[np.triu_indices_from(r)] = x[m**2 :] - - a = ( - np.diag((1 - np.arange(2, m + 1)) / m, -1) - + np.diag(2 * np.arange(1, m + 1) / m, 0) - + np.diag((1 - np.arange(1, m)) / m, 1) - ) - a[0, 1] = 0 - a[-1, -2] = (1 - m) / m - a[-1, -1] = 2 * m - - omat = np.zeros((m, m), dtype=np.float64) # triu - fmat = np.zeros((m, m), dtype=np.float64) - - for i in range(m): - for j in range(i, m): - for k in range(m): - omat[i, j] += q[i, k] * q[j, k] - - for i in range(m): - for j in range(m): - for k in range(j + 1): - fmat[i, j] += q[i, k] * r[k, j] - - for i in range(m): - omat[i, i] -= 1 - fmat[0, 0] -= a[0, 0] - fmat[0, 1] -= a[0, 1] - for i in range(1, m - 1): - fmat[i, i - 1] -= a[i, i - 1] - fmat[i, i] -= a[i, i] - fmat[i, i + 1] -= a[i, i + 1] - fmat[-1, -2] -= a[-1, -2] - fmat[-1, -1] -= a[-1, -1] - - return np.concatenate( - (omat[np.triu_indices_from(omat)].flatten(), fmat.flatten()) - ) + return _qr3d(x, m=self.m) + + +def _qr3d(x: NDArray[np.float64], m: int) -> NDArray[np.float64]: + q = x[: m**2].reshape(m, m) + r = np.zeros((m, m), dtype=np.float64) + r[np.triu_indices_from(r)] = x[m**2 :] + + a = ( + np.diag((1 - np.arange(2, m + 1)) / m, -1) + + np.diag(2 * np.arange(1, m + 1) / m, 0) + + np.diag((1 - np.arange(1, m)) / m, 1) + ) + a[0, 1] = 0 + a[-1, -2] = (1 - m) / m + a[-1, -1] = 2 * m + + omat = np.zeros((m, m), dtype=np.float64) # triu + fmat = np.zeros((m, m), dtype=np.float64) + + for i in range(m): + for j in range(i, m): + for k in range(m): + omat[i, j] += q[i, k] * q[j, k] + + for i in range(m): + for j in range(m): + for k in range(j + 1): + fmat[i, j] += q[i, k] * r[k, j] + + for i in range(m): + omat[i, i] -= 1 + fmat[0, 0] -= a[0, 0] + fmat[0, 1] -= a[0, 1] + for i in range(1, m - 1): + fmat[i, i - 1] -= a[i, i - 1] + fmat[i, i] -= a[i, i] + fmat[i, i + 1] -= a[i, i + 1] + fmat[-1, -2] -= a[-1, -2] + fmat[-1, -1] -= a[-1, -1] + + return np.concatenate((omat[np.triu_indices_from(omat)].flatten(), fmat.flatten())) @mark.least_squares @@ -605,53 +657,55 @@ class Qr3dbd(BenchmarkFunction): """The QR3DBD function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - m = 5 - q = x[: m**2].reshape(m, m) - r = np.zeros((m, m), dtype=np.float64) - r[0, :-2] = x[m**2 : -9] - r[1, 1:-1] = x[-9:-6] - r[2, 2:] = x[-6:-3] - r[3, 3:] = x[-3:-1] - r[4, 4] = x[-1] - - a = ( - np.diag((1 - np.arange(2, m + 1)) / m, -1) - + np.diag(2 * np.arange(1, m + 1) / m, 0) - + np.diag((1 - np.arange(1, m)) / m, 1) - ) - a[0, 1] = 0 - a[-1, -2] = (1 - m) / m - a[-1, -1] = 2 * m - - omat = np.zeros((m, m), dtype=np.float64) # triu - fmat = np.zeros((m, m), dtype=np.float64) - - for i in range(m): - for j in range(i, m): - for k in range(m): - omat[i, j] += q[i, k] * q[j, k] - - for i in range(m): - fmat[i, 0] += q[i, 0] * r[0, 0] - fmat[i, 1] += q[i, 0] * r[0, 1] + q[i, 1] * r[1, 1] - for j in range(2, m): - for k in range(j - 2, j + 1): - fmat[i, j] += q[i, k] * r[k, j] - - for i in range(m): - omat[i, i] -= 1 - fmat[0, 0] -= a[0, 0] - fmat[0, 1] -= a[0, 1] - for i in range(1, m - 1): - fmat[i, i - 1] -= a[i, i - 1] - fmat[i, i] -= a[i, i] - fmat[i, i + 1] -= a[i, i + 1] - fmat[-1, -2] -= a[-1, -2] - fmat[-1, -1] -= a[-1, -1] - - return np.concatenate( - (omat[np.triu_indices_from(omat)].flatten(), fmat.flatten()) - ) + return _qr3dbd(x) + + +def _qr3dbd(x: NDArray[np.float64]) -> NDArray[np.float64]: + m = 5 + q = x[: m**2].reshape(m, m) + r = np.zeros((m, m), dtype=np.float64) + r[0, :-2] = x[m**2 : -9] + r[1, 1:-1] = x[-9:-6] + r[2, 2:] = x[-6:-3] + r[3, 3:] = x[-3:-1] + r[4, 4] = x[-1] + + a = ( + np.diag((1 - np.arange(2, m + 1)) / m, -1) + + np.diag(2 * np.arange(1, m + 1) / m, 0) + + np.diag((1 - np.arange(1, m)) / m, 1) + ) + a[0, 1] = 0 + a[-1, -2] = (1 - m) / m + a[-1, -1] = 2 * m + + omat = np.zeros((m, m), dtype=np.float64) # triu + fmat = np.zeros((m, m), dtype=np.float64) + + for i in range(m): + for j in range(i, m): + for k in range(m): + omat[i, j] += q[i, k] * q[j, k] + + for i in range(m): + fmat[i, 0] += q[i, 0] * r[0, 0] + fmat[i, 1] += q[i, 0] * r[0, 1] + q[i, 1] * r[1, 1] + for j in range(2, m): + for k in range(j - 2, j + 1): + fmat[i, j] += q[i, k] * r[k, j] + + for i in range(m): + omat[i, i] -= 1 + fmat[0, 0] -= a[0, 0] + fmat[0, 1] -= a[0, 1] + for i in range(1, m - 1): + fmat[i, i - 1] -= a[i, i - 1] + fmat[i, i] -= a[i, i] + fmat[i, i + 1] -= a[i, i + 1] + fmat[-1, -2] -= a[-1, -2] + fmat[-1, -1] -= a[-1, -1] + + return np.concatenate((omat[np.triu_indices_from(omat)].flatten(), fmat.flatten())) @mark.least_squares @@ -664,12 +718,16 @@ class Eigen(BenchmarkFunction): number of parameters is m * (m + 1).""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = int(np.sqrt(len(x) + 0.25)) - dvec = x[:dim_in] - qmat = x[dim_in:].reshape(dim_in, dim_in) - emat = qmat @ np.diag(dvec) @ qmat - self.matrix - omat = qmat @ qmat - np.eye(dim_in) - return np.concatenate((emat.flatten(), omat.flatten())) + return _eigen(x, matrix=self.matrix) + + +def _eigen(x: NDArray[np.float64], matrix: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = int(np.sqrt(len(x) + 0.25)) + dvec = x[:dim_in] + qmat = x[dim_in:].reshape(dim_in, dim_in) + emat = qmat @ np.diag(dvec) @ qmat - matrix + omat = qmat @ qmat - np.eye(dim_in) + return np.concatenate((emat.flatten(), omat.flatten())) @mark.least_squares @@ -678,22 +736,39 @@ class ExtendedPowellSingular(BenchmarkFunction): """The extended Powell singular function (POWELLSE in the CUTEst collection).""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = np.zeros(dim_in) - fvec[::4] = x[::4] + 10 * x[1::4] - fvec[1::4] = 5 * (x[2::4] - x[3::4]) - fvec[2::4] = (x[1::4] - 2 * x[2::4]) ** 2 - fvec[3::4] = 10 * (x[0::4] - x[3::4]) ** 2 - return fvec + return _extended_powell_singular(x) + + +def _extended_powell_singular(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in) + fvec[::4] = x[::4] + 10 * x[1::4] + fvec[1::4] = 5 * (x[2::4] - x[3::4]) + fvec[2::4] = (x[1::4] - 2 * x[2::4]) ** 2 + fvec[3::4] = 10 * (x[0::4] - x[3::4]) ** 2 + return fvec + + +@mark.least_squares +@dataclass(frozen=True) +class Hydcar(BenchmarkFunction): + """The HYDCAR function from the CUTEst collection.""" + + n: int + """The number of plates.""" + + m: int + """The number of components.""" + + k: int + """The index of the feed plate.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return _hydcar(x, n=self.n, m=self.m, k=self.k) @njit -def hydcar( - x_in, - n, - m, - k, -): +def _hydcar(x_in: NDArray[np.float64], n: int, m: int, k: int) -> NDArray[np.float64]: x = x_in[: (n * m)].reshape((n, m)) t = x_in[(n * m) : 4 * n] v = x_in[4 * n :] @@ -808,418 +883,395 @@ def hydcar( return out -@mark.least_squares -@dataclass(frozen=True) -class Hydcar(BenchmarkFunction): - """The HYDCAR function from the CUTEst collection.""" - - n: int - """The number of plates.""" - - m: int - """The number of components.""" - - k: int - """The index of the feed plate.""" - - def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return hydcar(x, self.n, self.m, self.k) - - @mark.least_squares @dataclass(frozen=True) class Methane(BenchmarkFunction): """Function of the METHANB8 and METHANL8 problems from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - fvec = np.zeros(31, dtype=np.float64) - fvec[0] = 0.01 * ( - 0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - - x[4] * (693.37 + x[24]) - + 693.37 * x[1] - ) - fvec[1] = ( - 0.000869565217391304 * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) * x[19] - - x[22] - ) - fvec[2] = 0.01 * ( - -0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - - x[7] * (693.37 + x[25]) - + x[4] * (693.37 + x[24]) - + 0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - ) - fvec[3] = -4.5125 + 0.01 * ( - -0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - - x[10] * (-442.13 + x[26]) - + x[7] * (693.37 + x[25]) - + 0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - ) - fvec[4] = 0.01 * ( - -0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - - x[13] * (-442.13 + x[27]) - + x[10] * (-442.13 + x[26]) - + 0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - ) - fvec[5] = 0.01 * ( - -0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - - x[16] * (-442.13 + x[28]) - + x[13] * (-442.13 + x[27]) - + 0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - ) - fvec[6] = 0.01 * ( - -0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - - x[19] * (-442.13 + x[29]) - + x[16] * (-442.13 + x[28]) - + 0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - ) - fvec[7] = 0.01 * ( - -0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - - x[22] * (-442.13 + x[30]) - + x[19] * (-442.13 + x[29]) - + 0.000869565217391304 - * x[30] - * x[19] - * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) - ) - fvec[8] = 0.01 * ( - 0.000826446280991736 - * x[24] - * x[2] - * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - - x[5] * (693.37 + x[24]) - + 693.37 * x[2] - ) - fvec[9] = ( - 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] - - x[23] - ) - fvec[10] = 0.01 * ( - -0.000826446280991736 - * x[24] - * x[2] - * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - - x[8] * (693.37 + x[25]) - + x[5] * (693.37 + x[24]) - + 0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - ) - fvec[11] = -6.8425 + 0.01 * ( - -0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - - x[11] * (-442.13 + x[26]) - + x[8] * (693.37 + x[25]) - + 0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - ) - fvec[12] = 0.01 * ( - -0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - - x[14] * (-442.13 + x[27]) - + x[11] * (-442.13 + x[26]) - + 0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - ) - fvec[13] = 0.01 * ( - -0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - - x[17] * (-442.13 + x[28]) - + x[14] * (-442.13 + x[27]) - + 0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - ) - fvec[14] = 0.01 * ( - -0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - - x[20] * (-442.13 + x[29]) - + x[17] * (-442.13 + x[28]) - + 0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - ) - fvec[15] = 0.01 * ( - -0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - - x[23] * (-442.13 + x[30]) - + x[20] * (-442.13 + x[29]) - + 0.000869565217391304 - * x[30] - * x[20] - * np.exp(18.3443 - 3841.2203 / (228 + x[18])) - ) - fvec[16] = ( - -1 - + 0.000826446280991736 * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) * x[1] - + 0.000826446280991736 * np.exp(18.3443 - 3841.2203 / (228 + x[0])) * x[2] - ) - fvec[17] = ( - -1 - + 0.000833333333333333 * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) * x[4] - + 0.000833333333333333 * np.exp(18.3443 - 3841.2203 / (228 + x[3])) * x[5] - ) - fvec[18] = ( - -1 - + 0.000840336134453782 * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) * x[7] - + 0.000840336134453782 * np.exp(18.3443 - 3841.2203 / (228 + x[6])) * x[8] - ) - fvec[19] = ( - -1 - + 0.000847457627118644 * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) * x[10] - + 0.000847457627118644 * np.exp(18.3443 - 3841.2203 / (228 + x[9])) * x[11] - ) - fvec[20] = ( - -1 - + 0.000854700854700855 - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - * x[13] - + 0.000854700854700855 * np.exp(18.3443 - 3841.2203 / (228 + x[12])) * x[14] - ) - fvec[21] = ( - -1 - + 0.000862068965517241 - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - * x[16] - + 0.000862068965517241 * np.exp(18.3443 - 3841.2203 / (228 + x[15])) * x[17] - ) - fvec[22] = ( - -1 - + 0.000869565217391304 - * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) - * x[19] - + 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] - ) - fvec[23] = ( - -1 - + 0.00087719298245614 * np.exp(18.5751 - 3632.649 / (239.2 + x[21])) * x[22] - + 0.00087719298245614 * np.exp(18.3443 - 3841.2203 / (228 + x[21])) * x[23] - ) - fvec[24] = -83.862 + 1e-5 * ( - 0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) - + 693.37 * (0.0422 * x[0] * x[0] + 15.97 * x[0]) * x[1] - - x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) - + 0.000826446280991736 - * x[24] - * x[2] - * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - * (10834.67 + 8.74 * x[0]) - + 12549.997 * x[2] * x[0] - - 18.1 * x[5] * (693.37 + x[24]) * x[3] - ) - fvec[25] = 1e-5 * ( - 0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) - + x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) - - 0.000826446280991736 - * x[24] - * x[1] - * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) - * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) - - x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) - + 0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - * (10834.67 + 8.74 * x[3]) - + 18.1 * x[5] * (693.37 + x[24]) * x[3] - - 0.000826446280991736 - * x[24] - * x[2] - * np.exp(18.3443 - 3841.2203 / (228 + x[0])) - * (10834.67 + 8.74 * x[0]) - - 18.1 * x[8] * (693.37 + x[25]) * x[6] - ) - fvec[26] = -18.9447111025 + 1e-5 * ( - 0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) - + x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) - - 0.000833333333333333 - * x[25] - * x[4] - * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) - * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) - - x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) - + 0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - * (10834.67 + 8.74 * x[6]) - + 18.1 * x[8] * (693.37 + x[25]) * x[6] - - 0.000833333333333333 - * x[25] - * x[5] - * np.exp(18.3443 - 3841.2203 / (228 + x[3])) - * (10834.67 + 8.74 * x[3]) - - 18.1 * x[11] * (-442.13 + x[26]) * x[9] - ) - fvec[27] = 1e-5 * ( - 0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) - + x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) - - 0.000840336134453782 - * x[26] - * x[7] - * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) - * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) - - x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) - + 0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - * (10834.67 + 8.74 * x[9]) - + 18.1 * x[11] * (-442.13 + x[26]) * x[9] - - 0.000840336134453782 - * x[26] - * x[8] - * np.exp(18.3443 - 3841.2203 / (228 + x[6])) - * (10834.67 + 8.74 * x[6]) - - 18.1 * x[14] * (-442.13 + x[27]) * x[12] - ) - fvec[28] = 1e-5 * ( - 0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) - + x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) - - 0.000847457627118644 - * x[27] - * x[10] - * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) - * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) - - x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) - + 0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - * (10834.67 + 8.74 * x[12]) - + 18.1 * x[14] * (-442.13 + x[27]) * x[12] - - 0.000847457627118644 - * x[27] - * x[11] - * np.exp(18.3443 - 3841.2203 / (228 + x[9])) - * (10834.67 + 8.74 * x[9]) - - 18.1 * x[17] * (-442.13 + x[28]) * x[15] - ) - fvec[29] = 1e-5 * ( - 0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) - + x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) - - 0.000854700854700855 - * x[28] - * x[13] - * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) - * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) - - x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) - + 0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - * (10834.67 + 8.74 * x[15]) - + 18.1 * x[17] * (-442.13 + x[28]) * x[15] - - 0.000854700854700855 - * x[28] - * x[14] - * np.exp(18.3443 - 3841.2203 / (228 + x[12])) - * (10834.67 + 8.74 * x[12]) - - 18.1 * x[20] * (-442.13 + x[29]) * x[18] - ) - fvec[30] = 1e-5 * ( - 0.000869565217391304 - * x[30] - * x[19] - * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) - * (9566.67 + 0.0422 * x[18] * x[18] - 1.59 * x[18]) - + x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) - - 0.000862068965517241 - * x[29] - * x[16] - * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) - * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) - - x[22] * (-442.13 + x[30]) * (0.0422 * x[21] * x[21] + 15.97 * x[21]) - + 0.000869565217391304 - * x[30] - * x[20] - * np.exp(18.3443 - 3841.2203 / (228 + x[18])) - * (10834.67 + 8.74 * x[18]) - + 18.1 * x[20] * (-442.13 + x[29]) * x[18] - - 0.000862068965517241 - * x[29] - * x[17] - * np.exp(18.3443 - 3841.2203 / (228 + x[15])) - * (10834.67 + 8.74 * x[15]) - - 18.1 * x[23] * (-442.13 + x[30]) * x[21] - ) - return fvec + return _methane(x) + + +def _methane(x: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = np.zeros(31, dtype=np.float64) + fvec[0] = 0.01 * ( + 0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + - x[4] * (693.37 + x[24]) + + 693.37 * x[1] + ) + fvec[1] = ( + 0.000869565217391304 * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) * x[19] + - x[22] + ) + fvec[2] = 0.01 * ( + -0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + - x[7] * (693.37 + x[25]) + + x[4] * (693.37 + x[24]) + + 0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + ) + fvec[3] = -4.5125 + 0.01 * ( + -0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + - x[10] * (-442.13 + x[26]) + + x[7] * (693.37 + x[25]) + + 0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + ) + fvec[4] = 0.01 * ( + -0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + - x[13] * (-442.13 + x[27]) + + x[10] * (-442.13 + x[26]) + + 0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + ) + fvec[5] = 0.01 * ( + -0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + - x[16] * (-442.13 + x[28]) + + x[13] * (-442.13 + x[27]) + + 0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + ) + fvec[6] = 0.01 * ( + -0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + - x[19] * (-442.13 + x[29]) + + x[16] * (-442.13 + x[28]) + + 0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + ) + fvec[7] = 0.01 * ( + -0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + - x[22] * (-442.13 + x[30]) + + x[19] * (-442.13 + x[29]) + + 0.000869565217391304 + * x[30] + * x[19] + * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) + ) + fvec[8] = 0.01 * ( + 0.000826446280991736 * x[24] * x[2] * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + - x[5] * (693.37 + x[24]) + + 693.37 * x[2] + ) + fvec[9] = ( + 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] + - x[23] + ) + fvec[10] = 0.01 * ( + -0.000826446280991736 + * x[24] + * x[2] + * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + - x[8] * (693.37 + x[25]) + + x[5] * (693.37 + x[24]) + + 0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + ) + fvec[11] = -6.8425 + 0.01 * ( + -0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + - x[11] * (-442.13 + x[26]) + + x[8] * (693.37 + x[25]) + + 0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + ) + fvec[12] = 0.01 * ( + -0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + - x[14] * (-442.13 + x[27]) + + x[11] * (-442.13 + x[26]) + + 0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + ) + fvec[13] = 0.01 * ( + -0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + - x[17] * (-442.13 + x[28]) + + x[14] * (-442.13 + x[27]) + + 0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + ) + fvec[14] = 0.01 * ( + -0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + - x[20] * (-442.13 + x[29]) + + x[17] * (-442.13 + x[28]) + + 0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + ) + fvec[15] = 0.01 * ( + -0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + - x[23] * (-442.13 + x[30]) + + x[20] * (-442.13 + x[29]) + + 0.000869565217391304 + * x[30] + * x[20] + * np.exp(18.3443 - 3841.2203 / (228 + x[18])) + ) + fvec[16] = ( + -1 + + 0.000826446280991736 * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) * x[1] + + 0.000826446280991736 * np.exp(18.3443 - 3841.2203 / (228 + x[0])) * x[2] + ) + fvec[17] = ( + -1 + + 0.000833333333333333 * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) * x[4] + + 0.000833333333333333 * np.exp(18.3443 - 3841.2203 / (228 + x[3])) * x[5] + ) + fvec[18] = ( + -1 + + 0.000840336134453782 * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) * x[7] + + 0.000840336134453782 * np.exp(18.3443 - 3841.2203 / (228 + x[6])) * x[8] + ) + fvec[19] = ( + -1 + + 0.000847457627118644 * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) * x[10] + + 0.000847457627118644 * np.exp(18.3443 - 3841.2203 / (228 + x[9])) * x[11] + ) + fvec[20] = ( + -1 + + 0.000854700854700855 * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) * x[13] + + 0.000854700854700855 * np.exp(18.3443 - 3841.2203 / (228 + x[12])) * x[14] + ) + fvec[21] = ( + -1 + + 0.000862068965517241 * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) * x[16] + + 0.000862068965517241 * np.exp(18.3443 - 3841.2203 / (228 + x[15])) * x[17] + ) + fvec[22] = ( + -1 + + 0.000869565217391304 * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) * x[19] + + 0.000869565217391304 * np.exp(18.3443 - 3841.2203 / (228 + x[18])) * x[20] + ) + fvec[23] = ( + -1 + + 0.00087719298245614 * np.exp(18.5751 - 3632.649 / (239.2 + x[21])) * x[22] + + 0.00087719298245614 * np.exp(18.3443 - 3841.2203 / (228 + x[21])) * x[23] + ) + fvec[24] = -83.862 + 1e-5 * ( + 0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) + + 693.37 * (0.0422 * x[0] * x[0] + 15.97 * x[0]) * x[1] + - x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) + + 0.000826446280991736 + * x[24] + * x[2] + * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + * (10834.67 + 8.74 * x[0]) + + 12549.997 * x[2] * x[0] + - 18.1 * x[5] * (693.37 + x[24]) * x[3] + ) + fvec[25] = 1e-5 * ( + 0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) + + x[4] * (693.37 + x[24]) * (0.0422 * x[3] * x[3] + 15.97 * x[3]) + - 0.000826446280991736 + * x[24] + * x[1] + * np.exp(18.5751 - 3632.649 / (239.2 + x[0])) + * (9566.67 + 0.0422 * x[0] * x[0] - 1.59 * x[0]) + - x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) + + 0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + * (10834.67 + 8.74 * x[3]) + + 18.1 * x[5] * (693.37 + x[24]) * x[3] + - 0.000826446280991736 + * x[24] + * x[2] + * np.exp(18.3443 - 3841.2203 / (228 + x[0])) + * (10834.67 + 8.74 * x[0]) + - 18.1 * x[8] * (693.37 + x[25]) * x[6] + ) + fvec[26] = -18.9447111025 + 1e-5 * ( + 0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) + + x[7] * (693.37 + x[25]) * (0.0422 * x[6] * x[6] + 15.97 * x[6]) + - 0.000833333333333333 + * x[25] + * x[4] + * np.exp(18.5751 - 3632.649 / (239.2 + x[3])) + * (9566.67 + 0.0422 * x[3] * x[3] - 1.59 * x[3]) + - x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) + + 0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + * (10834.67 + 8.74 * x[6]) + + 18.1 * x[8] * (693.37 + x[25]) * x[6] + - 0.000833333333333333 + * x[25] + * x[5] + * np.exp(18.3443 - 3841.2203 / (228 + x[3])) + * (10834.67 + 8.74 * x[3]) + - 18.1 * x[11] * (-442.13 + x[26]) * x[9] + ) + fvec[27] = 1e-5 * ( + 0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) + + x[10] * (-442.13 + x[26]) * (0.0422 * x[9] * x[9] + 15.97 * x[9]) + - 0.000840336134453782 + * x[26] + * x[7] + * np.exp(18.5751 - 3632.649 / (239.2 + x[6])) + * (9566.67 + 0.0422 * x[6] * x[6] - 1.59 * x[6]) + - x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) + + 0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + * (10834.67 + 8.74 * x[9]) + + 18.1 * x[11] * (-442.13 + x[26]) * x[9] + - 0.000840336134453782 + * x[26] + * x[8] + * np.exp(18.3443 - 3841.2203 / (228 + x[6])) + * (10834.67 + 8.74 * x[6]) + - 18.1 * x[14] * (-442.13 + x[27]) * x[12] + ) + fvec[28] = 1e-5 * ( + 0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) + + x[13] * (-442.13 + x[27]) * (0.0422 * x[12] * x[12] + 15.97 * x[12]) + - 0.000847457627118644 + * x[27] + * x[10] + * np.exp(18.5751 - 3632.649 / (239.2 + x[9])) + * (9566.67 + 0.0422 * x[9] * x[9] - 1.59 * x[9]) + - x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) + + 0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + * (10834.67 + 8.74 * x[12]) + + 18.1 * x[14] * (-442.13 + x[27]) * x[12] + - 0.000847457627118644 + * x[27] + * x[11] + * np.exp(18.3443 - 3841.2203 / (228 + x[9])) + * (10834.67 + 8.74 * x[9]) + - 18.1 * x[17] * (-442.13 + x[28]) * x[15] + ) + fvec[29] = 1e-5 * ( + 0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) + + x[16] * (-442.13 + x[28]) * (0.0422 * x[15] * x[15] + 15.97 * x[15]) + - 0.000854700854700855 + * x[28] + * x[13] + * np.exp(18.5751 - 3632.649 / (239.2 + x[12])) + * (9566.67 + 0.0422 * x[12] * x[12] - 1.59 * x[12]) + - x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) + + 0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + * (10834.67 + 8.74 * x[15]) + + 18.1 * x[17] * (-442.13 + x[28]) * x[15] + - 0.000854700854700855 + * x[28] + * x[14] + * np.exp(18.3443 - 3841.2203 / (228 + x[12])) + * (10834.67 + 8.74 * x[12]) + - 18.1 * x[20] * (-442.13 + x[29]) * x[18] + ) + fvec[30] = 1e-5 * ( + 0.000869565217391304 + * x[30] + * x[19] + * np.exp(18.5751 - 3632.649 / (239.2 + x[18])) + * (9566.67 + 0.0422 * x[18] * x[18] - 1.59 * x[18]) + + x[19] * (-442.13 + x[29]) * (0.0422 * x[18] * x[18] + 15.97 * x[18]) + - 0.000862068965517241 + * x[29] + * x[16] + * np.exp(18.5751 - 3632.649 / (239.2 + x[15])) + * (9566.67 + 0.0422 * x[15] * x[15] - 1.59 * x[15]) + - x[22] * (-442.13 + x[30]) * (0.0422 * x[21] * x[21] + 15.97 * x[21]) + + 0.000869565217391304 + * x[30] + * x[20] + * np.exp(18.3443 - 3841.2203 / (228 + x[18])) + * (10834.67 + 8.74 * x[18]) + + 18.1 * x[20] * (-442.13 + x[29]) * x[18] + - 0.000862068965517241 + * x[29] + * x[17] + * np.exp(18.3443 - 3841.2203 / (228 + x[15])) + * (10834.67 + 8.74 * x[15]) + - 18.1 * x[23] * (-442.13 + x[30]) * x[21] + ) + return fvec @mark.least_squares @@ -1228,13 +1280,17 @@ class Argtrig(BenchmarkFunction): """The ARGTRIG function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = ( - dim_in - - np.sum(np.cos(x)) - + np.arange(1, dim_in + 1) * (1 - np.cos(x) - np.sin(x)) - ) - return fvec + return _argtrig(x) + + +def _argtrig(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = ( + dim_in + - np.sum(np.cos(x)) + + np.arange(1, dim_in + 1) * (1 - np.cos(x) - np.sin(x)) + ) + return fvec @mark.least_squares @@ -1243,15 +1299,19 @@ class Artif(BenchmarkFunction): """The ARTIF function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - xvec = np.zeros(dim_in + 2, dtype=np.float64) - xvec[1:-1] = x - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(dim_in): - fvec[i] = -0.05 * (xvec[i + 1] + xvec[i + 2] + xvec[i]) + np.arctan( - np.sin(np.mod(i + 1, 100) * xvec[i + 1]) - ) - return fvec + return _artif(x) + + +def _artif(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + xvec = np.zeros(dim_in + 2, dtype=np.float64) + xvec[1:-1] = x + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(dim_in): + fvec[i] = -0.05 * (xvec[i + 1] + xvec[i + 2] + xvec[i]) + np.arctan( + np.sin(np.mod(i + 1, 100) * xvec[i + 1]) + ) + return fvec @mark.least_squares @@ -1260,15 +1320,28 @@ class Arwhdne(BenchmarkFunction): """The ARWHDNE function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = np.zeros(2 * (dim_in - 1)) - fvec[: dim_in - 1] = x[:-1] ** 2 + x[-1] ** 2 - fvec[dim_in - 1 :] = 4 * x[:-1] - 3 - return fvec + return _arwhdne(x) + + +def _arwhdne(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(2 * (dim_in - 1)) + fvec[: dim_in - 1] = x[:-1] ** 2 + x[-1] ** 2 + fvec[dim_in - 1 :] = 4 * x[:-1] - 3 + return fvec + + +@mark.least_squares +@dataclass(frozen=True) +class Bdvalues(BenchmarkFunction): + """The BDVALUES function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return _bdvalues(x) @njit -def bdvalues(x): +def _bdvalues(x: NDArray[np.float64]) -> NDArray[np.float64]: dim_in = len(x) h = 1 / (dim_in + 1) xvec = np.zeros(dim_in + 2, dtype=np.float64) @@ -1285,15 +1358,6 @@ def bdvalues(x): return fvec -@mark.least_squares -@dataclass(frozen=True) -class Bdvalues(BenchmarkFunction): - """The BDVALUES function from the CUTEst collection.""" - - def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return bdvalues(x) - - @mark.least_squares @dataclass(frozen=True) class Bratu2d(BenchmarkFunction): @@ -1303,24 +1367,28 @@ class Bratu2d(BenchmarkFunction): """The parameter of the Bratu equation.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - x = x.reshape((int(np.sqrt(len(x))), int(np.sqrt(len(x))))) - p = x.shape[0] + 2 - h = 1 / (p - 1) - c = h**2 * self.alpha - xvec = np.zeros((x.shape[0] + 2, x.shape[1] + 2), dtype=np.float64) - xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1] = x - fvec = np.zeros(x.shape) - for i in range(2, p): - for j in range(2, p): - fvec[i - 2, j - 2] = ( - 4 * xvec[i - 1, j - 1] - - xvec[i, j - 1] - - xvec[i - 2, j - 1] - - xvec[i - 1, j] - - xvec[i - 1, j - 2] - - c * np.exp(xvec[i - 1, j - 1]) - ) - return fvec.flatten() + return _bratu_2d(x, alpha=self.alpha) + + +def _bratu_2d(x: NDArray[np.float64], alpha: float) -> NDArray[np.float64]: + x = x.reshape((int(np.sqrt(len(x))), int(np.sqrt(len(x))))) + p = x.shape[0] + 2 + h = 1 / (p - 1) + c = h**2 * alpha + xvec = np.zeros((x.shape[0] + 2, x.shape[1] + 2), dtype=np.float64) + xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1] = x + fvec = np.zeros(x.shape) + for i in range(2, p): + for j in range(2, p): + fvec[i - 2, j - 2] = ( + 4 * xvec[i - 1, j - 1] + - xvec[i, j - 1] + - xvec[i - 2, j - 1] + - xvec[i - 1, j] + - xvec[i - 1, j - 2] + - c * np.exp(xvec[i - 1, j - 1]) + ) + return fvec.flatten() @mark.least_squares @@ -1332,30 +1400,32 @@ class Bratu3d(BenchmarkFunction): """The parameter of the Bratu equation.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - n = int(np.cbrt(len(x))) - x = x.reshape((n, n, n)) - p = x.shape[0] + 2 - h = 1 / (p - 1) - c = h**2 * self.alpha - xvec = np.zeros( - (x.shape[0] + 2, x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64 - ) - xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x - fvec = np.zeros(x.shape, dtype=np.float64) - for i in range(2, p): - for j in range(2, p): - for k in range(2, p): - fvec[i - 2, j - 2, k - 2] = ( - 6 * xvec[i - 1, j - 1, k - 1] - - xvec[i, j - 1, k - 1] - - xvec[i - 2, j - 1, k - 1] - - xvec[i - 1, j, k - 1] - - xvec[i - 1, j - 2, k - 1] - - xvec[i - 1, j - 1, k] - - xvec[i - 1, j - 1, k - 2] - - c * np.exp(xvec[i, j, k]) - ) - return fvec.flatten() + return _bratu_3d(x, alpha=self.alpha) + + +def _bratu_3d(x: NDArray[np.float64], alpha: float) -> NDArray[np.float64]: + n = int(np.cbrt(len(x))) + x = x.reshape((n, n, n)) + p = x.shape[0] + 2 + h = 1 / (p - 1) + c = h**2 * alpha + xvec = np.zeros((x.shape[0] + 2, x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64) + xvec[1 : x.shape[0] + 1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x + fvec = np.zeros(x.shape, dtype=np.float64) + for i in range(2, p): + for j in range(2, p): + for k in range(2, p): + fvec[i - 2, j - 2, k - 2] = ( + 6 * xvec[i - 1, j - 1, k - 1] + - xvec[i, j - 1, k - 1] + - xvec[i - 2, j - 1, k - 1] + - xvec[i - 1, j, k - 1] + - xvec[i - 1, j - 2, k - 1] + - xvec[i - 1, j - 1, k] + - xvec[i - 1, j - 1, k - 2] + - c * np.exp(xvec[i, j, k]) + ) + return fvec.flatten() @mark.least_squares @@ -1364,15 +1434,19 @@ class Broydn3d(BenchmarkFunction): """The BROYDN3D function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - kappa_1 = 2 - kappa_2 = 1 - fvec = np.zeros_like(x) - fvec[0] = -2 * x[1] + kappa_2 + (3 - kappa_1 * x[0]) * x[0] - fvec[1 : len(x) - 1] = ( - -x[:-2] - 2 * x[2:] + kappa_2 + (3 - kappa_1 * x[1:-1]) * x[1:-1] - ) - fvec[-1] = -x[-2] + kappa_2 + (3 - kappa_1 * x[-1]) * x[-1] - return fvec + return _broydn_3d(x) + + +def _broydn_3d(x: NDArray[np.float64]) -> NDArray[np.float64]: + kappa_1 = 2 + kappa_2 = 1 + fvec = np.zeros_like(x) + fvec[0] = -2 * x[1] + kappa_2 + (3 - kappa_1 * x[0]) * x[0] + fvec[1 : len(x) - 1] = ( + -x[:-2] - 2 * x[2:] + kappa_2 + (3 - kappa_1 * x[1:-1]) * x[1:-1] + ) + fvec[-1] = -x[-2] + kappa_2 + (3 - kappa_1 * x[-1]) * x[-1] + return fvec @mark.least_squares @@ -1381,19 +1455,23 @@ class BroydnBd(BenchmarkFunction): """The BROYDNBD function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(1, 1 + dim_in): - ji = [] - lb = max(1, i - 5) - ub = min(dim_in, i + 1) - for j in range(lb, ub + 1): - if j != i: - ji.append(j) - fvec[i - 1] = x[i - 1] * (2 + 5 * x[i - 1] ** 2) - np.sum( - x[np.array(ji) - 1] * (1 + x[np.array(ji) - 1]) - ) - return fvec + return _broydn_bd(x) + + +def _broydn_bd(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(1, 1 + dim_in): + ji = [] + lb = max(1, i - 5) + ub = min(dim_in, i + 1) + for j in range(lb, ub + 1): + if j != i: + ji.append(j) + fvec[i - 1] = x[i - 1] * (2 + 5 * x[i - 1] ** 2) - np.sum( + x[np.array(ji) - 1] * (1 + x[np.array(ji) - 1]) + ) + return fvec @mark.least_squares @@ -1402,35 +1480,39 @@ class Cbratu2d(BenchmarkFunction): """The CBRATU2D function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - n = int(np.sqrt(len(x) / 2)) - x = x.reshape((2, n, n)) - xvec = np.zeros((x.shape[0], x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64) - xvec[0, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[0, :, :] - xvec[1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[1, :, :] - p = x.shape[1] + 2 - h = 1 / (p - 1) - alpha = 5 - c = h**2 * alpha - fvec = np.zeros(x.shape, dtype=np.float64) - for i in range(2, p): - for j in range(2, p): - fvec[0, i - 2, j - 2] = ( - 4 * xvec[0, i - 1, j - 1] - - xvec[0, i, j - 1] - - xvec[0, i - 2, j - 1] - - xvec[0, i - 1, j] - - xvec[0, i - 1, j - 2] - - c * np.exp(xvec[0, i - 1, j - 1]) * np.cos(xvec[0, i - 1, j - 1]) - ) - fvec[1, i - 2, j - 2] = ( - 4 * xvec[1, i - 1, j - 1] - - xvec[1, i, j - 1] - - xvec[1, i - 2, j - 1] - - xvec[1, i - 1, j] - - xvec[1, i - 1, j - 2] - - c * np.exp(xvec[1, i - 1, j - 1]) * np.sin(xvec[1, i - 1, j - 1]) - ) - return fvec.flatten() + return _cbratu_2d(x) + + +def _cbratu_2d(x: NDArray[np.float64]) -> NDArray[np.float64]: + n = int(np.sqrt(len(x) / 2)) + x = x.reshape((2, n, n)) + xvec = np.zeros((x.shape[0], x.shape[1] + 2, x.shape[2] + 2), dtype=np.float64) + xvec[0, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[0, :, :] + xvec[1, 1 : x.shape[1] + 1, 1 : x.shape[2] + 1] = x[1, :, :] + p = x.shape[1] + 2 + h = 1 / (p - 1) + alpha = 5 + c = h**2 * alpha + fvec = np.zeros(x.shape, dtype=np.float64) + for i in range(2, p): + for j in range(2, p): + fvec[0, i - 2, j - 2] = ( + 4 * xvec[0, i - 1, j - 1] + - xvec[0, i, j - 1] + - xvec[0, i - 2, j - 1] + - xvec[0, i - 1, j] + - xvec[0, i - 1, j - 2] + - c * np.exp(xvec[0, i - 1, j - 1]) * np.cos(xvec[0, i - 1, j - 1]) + ) + fvec[1, i - 2, j - 2] = ( + 4 * xvec[1, i - 1, j - 1] + - xvec[1, i, j - 1] + - xvec[1, i - 2, j - 1] + - xvec[1, i - 1, j] + - xvec[1, i - 1, j - 2] + - c * np.exp(xvec[1, i - 1, j - 1]) * np.sin(xvec[1, i - 1, j - 1]) + ) + return fvec.flatten() @mark.least_squares @@ -1439,20 +1521,31 @@ class Chandheq(BenchmarkFunction): """The CHANDHEQ function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - constant = 1 - w = np.ones(dim_in, dtype=np.int64) / dim_in - h = np.ones(dim_in, dtype=np.int64) - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(dim_in): - fvec[i] = ( - -0.5 * constant * w * x[i] / (x[i] + x) * h[i] * h + h[i] - 1 - ).sum() - return fvec + return _chandheq(x) + + +def _chandheq(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + constant = 1 + w = np.ones(dim_in, dtype=np.int64) / dim_in + h = np.ones(dim_in, dtype=np.int64) + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(dim_in): + fvec[i] = (-0.5 * constant * w * x[i] / (x[i] + x) * h[i] * h + h[i] - 1).sum() + return fvec + + +@mark.least_squares +@dataclass(frozen=True) +class Chemrcta(BenchmarkFunction): + """The CHEMRCTA function from the CUTEst collection.""" + + def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: + return _chemrcta(x) @njit -def chemrcta(x): +def _chemrcta(x: NDArray[np.float64]) -> NDArray[np.float64]: dim_in = int(len(x) / 2) x = x.reshape((2, dim_in)) fvec = np.zeros(2 * dim_in, dtype=np.float64) @@ -1495,15 +1588,15 @@ def chemrcta(x): @mark.least_squares @dataclass(frozen=True) -class Chemrcta(BenchmarkFunction): - """The CHEMRCTA function from the CUTEst collection.""" +class Chemrctb(BenchmarkFunction): + """The CHEMRCTB function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return chemrcta(x) + return _chemrctb(x) @njit -def chemrctb(x): +def _chemrctb(x: NDArray[np.float64]) -> NDArray[np.float64]: dim_in = int(len(x)) fvec = np.zeros(dim_in, dtype=np.float64) @@ -1531,82 +1624,89 @@ def chemrctb(x): @mark.least_squares @dataclass(frozen=True) -class Chemrctb(BenchmarkFunction): - """The CHEMRCTB function from the CUTEst collection.""" +class Chnrsbne(BenchmarkFunction): + """The CHNRSBNE function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return chemrctb(x) + return _chnrsbne(x) + + +def _chnrsbne(x: NDArray[np.float64]) -> NDArray[np.float64]: + alfa = np.array( + [ + 1.25, + 1.40, + 2.40, + 1.40, + 1.75, + 1.20, + 2.25, + 1.20, + 1.00, + 1.10, + 1.50, + 1.60, + 1.25, + 1.25, + 1.20, + 1.20, + 1.40, + 0.50, + 0.50, + 1.25, + 1.80, + 0.75, + 1.25, + 1.40, + 1.60, + 2.00, + 1.00, + 1.60, + 1.25, + 2.75, + 1.25, + 1.25, + 1.25, + 3.00, + 1.50, + 2.00, + 1.25, + 1.40, + 1.80, + 1.50, + 2.20, + 1.40, + 1.50, + 1.25, + 2.00, + 1.50, + 1.25, + 1.40, + 0.60, + 1.50, + ] + ) + dim_in = len(x) + fvec = np.zeros(2 * (dim_in - 1)) + fvec[: dim_in - 1] = 4 * alfa[1:] * (x[:-1] - x[1:] ** 2) + fvec[dim_in - 1 :] = x[1:] - 1 + return fvec @mark.least_squares @dataclass(frozen=True) -class Chnrsbne(BenchmarkFunction): - """The CHNRSBNE function from the CUTEst collection.""" +class Drcavty(BenchmarkFunction): + """The DRCAVTY function from the CUTEst collection.""" + + r: float + """The Reynolds number.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - alfa = np.array( - [ - 1.25, - 1.40, - 2.40, - 1.40, - 1.75, - 1.20, - 2.25, - 1.20, - 1.00, - 1.10, - 1.50, - 1.60, - 1.25, - 1.25, - 1.20, - 1.20, - 1.40, - 0.50, - 0.50, - 1.25, - 1.80, - 0.75, - 1.25, - 1.40, - 1.60, - 2.00, - 1.00, - 1.60, - 1.25, - 2.75, - 1.25, - 1.25, - 1.25, - 3.00, - 1.50, - 2.00, - 1.25, - 1.40, - 1.80, - 1.50, - 2.20, - 1.40, - 1.50, - 1.25, - 2.00, - 1.50, - 1.25, - 1.40, - 0.60, - 1.50, - ] - ) - dim_in = len(x) - fvec = np.zeros(2 * (dim_in - 1)) - fvec[: dim_in - 1] = 4 * alfa[1:] * (x[:-1] - x[1:] ** 2) - fvec[dim_in - 1 :] = x[1:] - 1 - return fvec + return _drcavty(x, r=self.r) @njit -def drcavty(x, r): +def _drcavty(x: NDArray[np.float64], r: float) -> NDArray[np.float64]: m = int(np.sqrt(len(x))) x = x.reshape((m, m)) h = 1 / (m + 2) @@ -1660,30 +1760,22 @@ def drcavty(x, r): return fvec.flatten() -@mark.least_squares -@dataclass(frozen=True) -class Drcavty(BenchmarkFunction): - """The DRCAVTY function from the CUTEst collection.""" - - r: float - """The Reynolds number.""" - - def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return drcavty(x, self.r) - - @mark.least_squares @dataclass(frozen=True) class Freurone(BenchmarkFunction): """The FREURONE function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = np.zeros((2, dim_in - 1), dtype=np.float64) - for i in range(dim_in - 1): - fvec[0, i] = (5.0 - x[i + 1]) * x[i + 1] ** 2 + x[i] - 2 * x[i + 1] - 13.0 - fvec[1, i] = (1.0 + x[i + 1]) * x[i + 1] ** 2 + x[i] - 14 * x[i + 1] - 29.0 - return fvec.flatten() + return _freurone(x) + + +def _freurone(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros((2, dim_in - 1), dtype=np.float64) + for i in range(dim_in - 1): + fvec[0, i] = (5.0 - x[i + 1]) * x[i + 1] ** 2 + x[i] - 2 * x[i + 1] - 13.0 + fvec[1, i] = (1.0 + x[i + 1]) * x[i + 1] ** 2 + x[i] - 14 * x[i + 1] - 29.0 + return fvec.flatten() @mark.least_squares @@ -1692,13 +1784,17 @@ class Hatfldg(BenchmarkFunction): """The HATFLDG function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = np.zeros(dim_in, dtype=np.float64) - for i in range(1, dim_in - 1): - fvec[i - 1] = x[i] * (x[i - 1] - x[i + 1]) + x[i] - x[12] + 1 - fvec[-2] = x[0] - x[12] + 1 - x[0] * x[1] - fvec[-1] = x[-1] - x[12] + 1 + x[-2] * x[-1] - return fvec + return _hatfldg(x) + + +def _hatfldg(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in, dtype=np.float64) + for i in range(1, dim_in - 1): + fvec[i - 1] = x[i] * (x[i - 1] - x[i + 1]) + x[i] - x[12] + 1 + fvec[-2] = x[0] - x[12] + 1 - x[0] * x[1] + fvec[-1] = x[-1] - x[12] + 1 + x[-2] * x[-1] + return fvec @mark.least_squares @@ -1707,33 +1803,36 @@ class Integreq(BenchmarkFunction): """The INTEGREQ function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - h = 1 / (dim_in + 1) - t = np.arange(1, dim_in + 1) * h - xvec = np.zeros(dim_in + 2, dtype=np.float64) - xvec[1:-1] = x - fvec = np.zeros_like(x) - for i in range(1, dim_in): - fvec[i - 1] = ( - xvec[i] - + h - * ( - (1 - t[i - 1]) * (t[:i] * (xvec[1 : i + 1] + t[:i] + 1) ** 3).sum() - + t[i - 1] - * ((1 - t[i:]) * (xvec[i + 1 : -1] + t[i:] + 1) ** 3).sum() - ) - / 2 - ) - fvec[-1] = ( - xvec[-2] + return _integreq(x) + + +def _integreq(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + h = 1 / (dim_in + 1) + t = np.arange(1, dim_in + 1) * h + xvec = np.zeros(dim_in + 2, dtype=np.float64) + xvec[1:-1] = x + fvec = np.zeros_like(x) + for i in range(1, dim_in): + fvec[i - 1] = ( + xvec[i] + h * ( - (1 - t[-1]) * (t * (xvec[1:-1] + t + 1) ** 3).sum() - + t[-1] * ((1 - t[-1]) * (xvec[-2] + t[-1] + 1) ** 3) + (1 - t[i - 1]) * (t[:i] * (xvec[1 : i + 1] + t[:i] + 1) ** 3).sum() + + t[i - 1] * ((1 - t[i:]) * (xvec[i + 1 : -1] + t[i:] + 1) ** 3).sum() ) / 2 ) - return fvec + fvec[-1] = ( + xvec[-2] + + h + * ( + (1 - t[-1]) * (t * (xvec[1:-1] + t + 1) ** 3).sum() + + t[-1] * ((1 - t[-1]) * (xvec[-2] + t[-1] + 1) ** 3) + ) + / 2 + ) + return fvec @mark.least_squares @@ -1742,20 +1841,24 @@ class Msqrta(BenchmarkFunction): """The MSQRTA function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = int(np.sqrt(len(x))) - xmat = x.reshape((dim_in, dim_in)) - bmat = 5 * xmat - amat = np.zeros((dim_in, dim_in), dtype=np.float64) - for i in range(1, dim_in + 1): - for j in range(1, dim_in + 1): - amat[i - 1, j - 1] = (bmat[i - 1, :] * bmat[:, j - 1]).sum() - fmat = np.zeros((dim_in, dim_in)) - for i in range(1, dim_in + 1): - for j in range(1, dim_in + 1): - fmat[i - 1, j - 1] = (xmat[i - 1, :] * xmat[:, j - 1]).sum() - amat[ - i - 1, j - 1 - ] - return fmat.flatten() + return _msqrta(x) + + +def _msqrta(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = int(np.sqrt(len(x))) + xmat = x.reshape((dim_in, dim_in)) + bmat = 5 * xmat + amat = np.zeros((dim_in, dim_in), dtype=np.float64) + for i in range(1, dim_in + 1): + for j in range(1, dim_in + 1): + amat[i - 1, j - 1] = (bmat[i - 1, :] * bmat[:, j - 1]).sum() + fmat = np.zeros((dim_in, dim_in)) + for i in range(1, dim_in + 1): + for j in range(1, dim_in + 1): + fmat[i - 1, j - 1] = (xmat[i - 1, :] * xmat[:, j - 1]).sum() - amat[ + i - 1, j - 1 + ] + return fmat.flatten() @mark.least_squares @@ -1768,9 +1871,13 @@ class Penalty1(BenchmarkFunction): root.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - fvec = np.sqrt(self.a) * (x - 2) - fvec = np.concatenate([fvec, [x @ x - 1 / 4]]) - return fvec + return _penalty_1(x, a=self.a) + + +def _penalty_1(x: NDArray[np.float64], a: float) -> NDArray[np.float64]: + fvec = np.sqrt(a) * (x - 2) + fvec = np.concatenate([fvec, [x @ x - 1 / 4]]) + return fvec @mark.least_squares @@ -1783,18 +1890,20 @@ class Penalty2(BenchmarkFunction): its square root.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - y = np.exp(np.arange(1, 2 * dim_in + 1) / 10) + np.exp( - np.arange(2 * dim_in) / 10 - ) - fvec = np.zeros(2 * dim_in) - fvec[0] = x[0] - 0.2 - fvec[1:dim_in] = np.sqrt(self.a) * ( - np.exp(x[1:] / 10) + np.exp(x[:-1] / 10) - y[1:dim_in] - ) - fvec[dim_in:-1] = np.sqrt(self.a) * (np.exp(x[1:] / 10) - np.exp(-1 / 10)) - fvec[-1] = (np.arange(1, dim_in + 1)[::-1] * x**2).sum() - 1 - return fvec + return _penalty_2(x, a=self.a) + + +def _penalty_2(x: NDArray[np.float64], a: float) -> NDArray[np.float64]: + dim_in = len(x) + y = np.exp(np.arange(1, 2 * dim_in + 1) / 10) + np.exp(np.arange(2 * dim_in) / 10) + fvec = np.zeros(2 * dim_in) + fvec[0] = x[0] - 0.2 + fvec[1:dim_in] = np.sqrt(a) * ( + np.exp(x[1:] / 10) + np.exp(x[:-1] / 10) - y[1:dim_in] + ) + fvec[dim_in:-1] = np.sqrt(a) * (np.exp(x[1:] / 10) - np.exp(-1 / 10)) + fvec[-1] = (np.arange(1, dim_in + 1)[::-1] * x**2).sum() - 1 + return fvec @mark.least_squares @@ -1803,12 +1912,16 @@ class Vardimne(BenchmarkFunction): """The VARDIMNE function from the CUTEst collection.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = len(x) - fvec = np.zeros(dim_in + 2) - fvec[:-2] = x - 1 - fvec[-2] = (np.arange(1, dim_in + 1) * (x - 1)).sum() - fvec[-1] = ((np.arange(1, dim_in + 1) * (x - 1)).sum()) ** 2 - return fvec + return _vardimne(x) + + +def _vardimne(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in + 2) + fvec[:-2] = x - 1 + fvec[-2] = (np.arange(1, dim_in + 1) * (x - 1)).sum() + fvec[-1] = ((np.arange(1, dim_in + 1) * (x - 1)).sum()) ** 2 + return fvec @mark.least_squares @@ -1821,26 +1934,29 @@ class Yatpsq1(BenchmarkFunction): parameters is dim_in**2 + 2 * dim_in.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = self.dim_in - xvec = x[: dim_in**2] - xvec = xvec.reshape((dim_in, dim_in)) - yvec = x[dim_in**2 : dim_in**2 + dim_in] - zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] - fvec = np.zeros((dim_in, dim_in), dtype=np.float64) - for i in range(dim_in): - for j in range(dim_in): - fvec[i, j] = ( - xvec[i, j] ** 3 - - 10 * xvec[i, j] ** 2 - - (yvec[i] + zvec[j]) - * (xvec[i, j] * np.cos(xvec[i, j]) - np.sin(xvec[i, j])) - ) - fvec = fvec.flatten() - temp = (np.sin(xvec) / xvec).sum(axis=0) - 1 - fvec = np.concatenate((fvec, temp)) - temp = (np.sin(xvec) / xvec).sum(axis=1) - 1 - fvec = np.concatenate((fvec, temp)) - return fvec + return _yatpsq_1(x, dim_in=self.dim_in) + + +def _yatpsq_1(x: NDArray[np.float64], dim_in: int) -> NDArray[np.float64]: + xvec = x[: dim_in**2] + xvec = xvec.reshape((dim_in, dim_in)) + yvec = x[dim_in**2 : dim_in**2 + dim_in] + zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] + fvec = np.zeros((dim_in, dim_in), dtype=np.float64) + for i in range(dim_in): + for j in range(dim_in): + fvec[i, j] = ( + xvec[i, j] ** 3 + - 10 * xvec[i, j] ** 2 + - (yvec[i] + zvec[j]) + * (xvec[i, j] * np.cos(xvec[i, j]) - np.sin(xvec[i, j])) + ) + fvec = fvec.flatten() + temp = (np.sin(xvec) / xvec).sum(axis=0) - 1 + fvec = np.concatenate((fvec, temp)) + temp = (np.sin(xvec) / xvec).sum(axis=1) - 1 + fvec = np.concatenate((fvec, temp)) + return fvec @mark.least_squares @@ -1853,23 +1969,24 @@ class Yatpsq2(BenchmarkFunction): parameters is dim_in**2 + 2 * dim_in.""" def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - dim_in = self.dim_in - xvec = x[: dim_in**2] - xvec = xvec.reshape((dim_in, dim_in)) - yvec = x[dim_in**2 : dim_in**2 + dim_in] - zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] - fvec = np.zeros((dim_in, dim_in), dtype=np.float64) - for i in range(dim_in): - for j in range(dim_in): - fvec[i, j] = ( - xvec[i, j] - (yvec[i] + zvec[j]) * (1 + np.cos(xvec[i, j])) - 1 - ) - fvec = fvec.flatten() - temp = (np.sin(xvec) + xvec).sum(axis=0) - 1 - fvec = np.concatenate((fvec, temp)) - temp = (np.sin(xvec) + xvec).sum(axis=1) - 1 - fvec = np.concatenate((fvec, temp)) - return fvec + return _yatpsq_2(x, dim_in=self.dim_in) + + +def _yatpsq_2(x: NDArray[np.float64], dim_in: int) -> NDArray[np.float64]: + xvec = x[: dim_in**2] + xvec = xvec.reshape((dim_in, dim_in)) + yvec = x[dim_in**2 : dim_in**2 + dim_in] + zvec = x[dim_in**2 + dim_in : dim_in**2 + 2 * dim_in] + fvec = np.zeros((dim_in, dim_in), dtype=np.float64) + for i in range(dim_in): + for j in range(dim_in): + fvec[i, j] = xvec[i, j] - (yvec[i] + zvec[j]) * (1 + np.cos(xvec[i, j])) - 1 + fvec = fvec.flatten() + temp = (np.sin(xvec) + xvec).sum(axis=0) - 1 + fvec = np.concatenate((fvec, temp)) + temp = (np.sin(xvec) + xvec).sum(axis=1) - 1 + fvec = np.concatenate((fvec, temp)) + return fvec def get_start_points_msqrta(dim_in, flag=1): diff --git a/src/optimagic/benchmarking/more_wild.py b/src/optimagic/benchmarking/more_wild.py index 1c15f1e29..732e13567 100644 --- a/src/optimagic/benchmarking/more_wild.py +++ b/src/optimagic/benchmarking/more_wild.py @@ -34,277 +34,6 @@ ) -@mark.least_squares -def linear_full_rank(x, dim_out): - temp = 2 * x.sum() / dim_out + 1 - out = np.full(dim_out, -temp) - out[: len(x)] += x - return out - - -@mark.least_squares -def linear_rank_one(x, dim_out): - dim_in = len(x) - sm = np.arange(1, dim_in + 1) @ x - fvec = np.arange(1, dim_out + 1) * sm - 1.0 - return fvec - - -@mark.least_squares -def linear_rank_one_zero_columns_rows(x, dim_out): - dim_in = len(x) - sm = (np.arange(2, dim_in) * x[1:-1]).sum() - fvec = np.arange(dim_out) * sm - 1.0 - fvec[-1] = -1.0 - return fvec - - -@mark.least_squares -def rosenbrock(x): - fvec = np.zeros(2) - fvec[0] = 10 * (x[1] - x[0] ** 2) - fvec[1] = 1.0 - x[0] - return fvec - - -@mark.least_squares -def helical_valley(x): - temp = 8 * np.arctan(1.0) - temp1 = np.sign(x[1]) * 0.25 - if x[0] > 0: - temp1 = np.arctan(x[1] / x[0]) / temp - elif x[0] < 0: - temp1 = np.arctan(x[1] / x[0]) / temp + 0.5 - temp2 = np.sqrt(x[0] ** 2 + x[1] ** 2) - fvec = np.zeros(3) - fvec[0] = 10 * (x[2] - 10 * temp1) - fvec[1] = 10 * (temp2 - 1.0) - fvec[2] = x[2] - return fvec - - -@mark.least_squares -def powell_singular(x): - fvec = np.zeros(4) - fvec[0] = x[0] + 10 * x[1] - fvec[1] = np.sqrt(5.0) * (x[2] - x[3]) - fvec[2] = (x[1] - 2 * x[2]) ** 2 - fvec[3] = np.sqrt(10.0) * (x[0] - x[3]) ** 2 - return fvec - - -@mark.least_squares -def freudenstein_roth(x): - fvec = np.zeros(2) - fvec[0] = -13 + x[0] + ((5 - x[1]) * x[1] - 2) * x[1] - fvec[1] = -29 + x[0] + ((1.0 + x[1]) * x[1] - 14) * x[1] - return fvec - - -@mark.least_squares -def bard(x, y): - fvec = np.zeros(len(y)) - for i in range(1, round(len(y) / 2) + 1): - temp = len(y) + 1 - i - fvec[i - 1] = y[i - 1] - (x[0] + i / (x[1] * temp + x[2] * i)) - for i in range(round(len(y) / 2) + 1, len(y) + 1): - temp = len(y) + 1 - i - fvec[i - 1] = y[i - 1] - (x[0] + i / (x[1] * temp + x[2] * temp)) - return fvec - - -@mark.least_squares -def kowalik_osborne(x, y1, y2): - temp1 = y1 * (y1 + x[1]) - temp2 = y1 * (y1 + x[2]) + x[3] - fvec = y2 - x[0] * temp1 / temp2 - return fvec - - -@mark.least_squares -def meyer(x, y): - temp = 5 * np.arange(1, len(y) + 1) + 45 + x[2] - temp1 = x[1] / temp - temp2 = np.exp(temp1) - fvec = x[0] * temp2 - y - return fvec - - -@mark.least_squares -def watson(x): - dim_in = len(x) - fvec = np.zeros(31) - for i in range(1, 30): - temp = i / 29 - sum_1 = (np.arange(1, dim_in) * temp ** np.arange(dim_in - 1) * x[1:]).sum() - sum_2 = (temp ** np.arange(dim_in) * x).sum() - fvec[i - 1] = sum_1 - sum_2**2 - 1.0 - fvec[29] = x[0] - fvec[30] = x[1] - x[0] ** 2 - 1.0 - return fvec - - -@mark.least_squares -def box_3d(x, dim_out): - fvec = np.zeros(dim_out) - for i in range(1, dim_out + 1): - fvec[i - 1] = ( - np.exp(-i / 10 * x[0]) - - np.exp(-i / 10 * x[1]) - + (np.exp(-i) - np.exp(-i / 10)) * x[2] - ) - return fvec - - -@mark.least_squares -def jennrich_sampson(x, dim_out): - fvec = ( - 2 * (1.0 + np.arange(1, dim_out + 1)) - - np.exp(np.arange(1, dim_out + 1) * x[0]) - - np.exp(np.arange(1, dim_out + 1) * x[1]) - ) - return fvec - - -@mark.least_squares -def brown_dennis(x, dim_out): - fvec = np.zeros(dim_out) - for i in range(1, dim_out + 1): - temp = i / 5 - temp_1 = x[0] + temp * x[1] - np.exp(temp) - temp_2 = x[2] + np.sin(temp) * x[3] - np.cos(temp) - fvec[i - 1] = temp_1**2 + temp_2**2 - return fvec - - -@mark.least_squares -def chebyquad(x, dim_out): - fvec = np.zeros(dim_out) - dim_in = len(x) - for i in range(1, dim_in + 1): - temp_1 = 1.0 - temp_2 = 2 * x[i - 1] - 1.0 - temp_3 = 2 * temp_2 - for j in range(dim_out): - fvec[j] = fvec[j] + temp_2 - temp_4 = temp_3 * temp_2 - temp_1 - temp_1 = temp_2 - temp_2 = temp_4 - for i in range(1, dim_out + 1): - fvec[i - 1] = fvec[i - 1] / dim_in - if i % 2 == 0: - fvec[i - 1] = fvec[i - 1] + 1 / (i**2 - 1.0) - return fvec - - -@mark.least_squares -def brown_almost_linear(x): - dim_in = len(x) - sm = -(dim_in + 1) + x.sum() - product = x.prod() - fvec = x + sm - fvec[dim_in - 1] = product - 1.0 - return fvec - - -@mark.least_squares -def osborne_one(x, y): - temp = 10 * np.arange(len(y)) - temp_1 = np.exp(-x[3] * temp) - temp_2 = np.exp(-x[4] * temp) - fvec = y - (x[0] + x[1] * temp_1 + x[2] * temp_2) - return fvec - - -@mark.least_squares -def osborne_two(x, y): - temp_array = np.zeros((4, len(y))) - temp = np.arange(len(y)) / 10 - temp_array[0] = np.exp(-x[4] * temp) - temp_array[1] = np.exp(-x[5] * (temp - x[8]) ** 2) - temp_array[2] = np.exp(-x[6] * (temp - x[9]) ** 2) - temp_array[3] = np.exp(-x[7] * (temp - x[10]) ** 2) - fvec = y - (temp_array.T * x[:4]).T.sum(axis=0) - return fvec - - -@mark.least_squares -def bdqrtic(x): - # the length of array x should be more than 5. - dim_in = len(x) - fvec = np.zeros(2 * (dim_in - 4)) - for i in range(dim_in - 4): - fvec[i] = -4 * x[i] + 3 - fvec[dim_in - 4 + i] = ( - x[i] ** 2 - + 2 * x[i + 1] ** 2 - + 3 * x[i + 2] ** 2 - + 4 * x[i + 3] ** 2 - + 5 * x[dim_in - 1] ** 2 - ) - return fvec - - -@mark.least_squares -def cube(x): - fvec = 10 * (x - np.roll(x, 1) ** 3) - fvec[0] = x[0] - 1.0 - return fvec - - -@mark.least_squares -def mancino(x): - dim_in = len(x) - fvec = np.zeros(dim_in) - for i in range(dim_in): - sm = 0 - for j in range(dim_in): - temp = np.sqrt(x[i] ** 2 + (i + 1) / (j + 1)) - sm += temp * ((np.sin(np.log(temp))) ** 5 + (np.cos(np.log(temp))) ** 5) - fvec[i] = 1400 * x[i] + (i + 1 - 50) ** 3 + sm - return fvec - - -@mark.least_squares -def heart_eight(x, y): - dim_y = len(y) - fvec = np.zeros(dim_y) - fvec[0] = x[0] + x[1] - y[0] - fvec[1] = x[2] + x[3] - y[1] - fvec[2] = x[4] * x[0] + x[5] * x[1] - x[6] * x[2] - x[7] * x[3] - y[2] - fvec[3] = x[6] * x[0] + x[7] * x[1] + x[4] * x[2] + x[5] * x[3] - y[3] - fvec[4] = ( - x[0] * (x[4] ** 2 - x[6] ** 2) - - 2 * x[2] * x[4] * x[6] - + x[1] * (x[5] ** 2 - x[7] ** 2) - - 2 * x[3] * x[5] * x[7] - - y[4] - ) - fvec[5] = ( - x[2] * (x[4] ** 2 - x[6] ** 2) - + 2 * x[0] * x[4] * x[6] - + x[3] * (x[5] ** 2 - x[7] ** 2) - + 2 * x[1] * x[5] * x[7] - - y[5] - ) - fvec[6] = ( - x[0] * x[4] * (x[4] ** 2 - 3 * x[6] ** 2) - + x[2] * x[6] * (x[6] ** 2 - 3 * x[4] ** 2) - + x[1] * x[5] * (x[5] ** 2 - 3 * x[7] ** 2) - + x[3] * x[7] * (x[7] ** 2 - 3 * x[5] ** 2) - - y[6] - ) - fvec[7] = ( - x[2] * x[4] * (x[4] ** 2 - 3 * x[6] ** 2) - - x[0] * x[6] * (x[6] ** 2 - 3 * x[4] ** 2) - + x[3] * x[5] * (x[5] ** 2 - 3 * x[7] ** 2) - - x[1] * x[7] * (x[7] ** 2 - 3 * x[5] ** 2) - - y[7] - ) - return fvec - - -@mark.least_squares def get_start_points_mancino(n, a=1): x = np.zeros(n) for i in range(1, n + 1): @@ -812,12 +541,19 @@ class LinearFullRank(BenchmarkFunction): multimodal = False def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return linear_full_rank(x, dim_out=self.dim_out) + return _linear_full_rank(x, dim_out=self.dim_out) def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +def _linear_full_rank(x: NDArray[np.float64], dim_out: int) -> NDArray[np.float64]: + temp = 2 * x.sum() / dim_out + 1 + out = np.full(dim_out, -temp) + out[: len(x)] += x + return out + + @mark.least_squares @dataclass(frozen=True) class LinearRankOne(BenchmarkFunction): @@ -831,12 +567,19 @@ class LinearRankOne(BenchmarkFunction): multimodal = False def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return linear_rank_one(x, dim_out=self.dim_out) + return _linear_rank_one(x, dim_out=self.dim_out) def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +def _linear_rank_one(x: NDArray[np.float64], dim_out: int) -> NDArray[np.float64]: + dim_in = len(x) + sm = np.arange(1, dim_in + 1) @ x + fvec = np.arange(1, dim_out + 1) * sm - 1.0 + return fvec + + @mark.least_squares @dataclass(frozen=True) class LinearRankOneZeroColumnsRows(BenchmarkFunction): @@ -850,12 +593,22 @@ class LinearRankOneZeroColumnsRows(BenchmarkFunction): multimodal = False def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return linear_rank_one_zero_columns_rows(x, dim_out=self.dim_out) + return _linear_rank_one_zero_columns_rows(x, dim_out=self.dim_out) def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +def _linear_rank_one_zero_columns_rows( + x: NDArray[np.float64], dim_out: int +) -> NDArray[np.float64]: + dim_in = len(x) + sm = (np.arange(2, dim_in) * x[1:-1]).sum() + fvec = np.arange(dim_out) * sm - 1.0 + fvec[-1] = -1.0 + return fvec + + @mark.least_squares @dataclass(frozen=True) class Rosenbrock(BenchmarkFunction): @@ -868,7 +621,14 @@ class Rosenbrock(BenchmarkFunction): max_n_params = 2 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return rosenbrock(x) + return _rosenbrock(x) + + +def _rosenbrock(x: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = np.zeros(2) + fvec[0] = 10 * (x[1] - x[0] ** 2) + fvec[1] = 1.0 - x[0] + return fvec @mark.least_squares @@ -882,7 +642,22 @@ class HelicalValley(BenchmarkFunction): max_n_params = 3 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return helical_valley(x) + return _helical_valley(x) + + +def _helical_valley(x: NDArray[np.float64]) -> NDArray[np.float64]: + temp = 8 * np.arctan(1.0) + temp1 = np.sign(x[1]) * 0.25 + if x[0] > 0: + temp1 = np.arctan(x[1] / x[0]) / temp + elif x[0] < 0: + temp1 = np.arctan(x[1] / x[0]) / temp + 0.5 + temp2 = np.sqrt(x[0] ** 2 + x[1] ** 2) + fvec = np.zeros(3) + fvec[0] = 10 * (x[2] - 10 * temp1) + fvec[1] = 10 * (temp2 - 1.0) + fvec[2] = x[2] + return fvec @mark.least_squares @@ -897,7 +672,16 @@ class PowellSingular(BenchmarkFunction): max_n_params = 4 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return powell_singular(x) + return _powell_singular(x) + + +def _powell_singular(x: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = np.zeros(4) + fvec[0] = x[0] + 10 * x[1] + fvec[1] = np.sqrt(5.0) * (x[2] - x[3]) + fvec[2] = (x[1] - 2 * x[2]) ** 2 + fvec[3] = np.sqrt(10.0) * (x[0] - x[3]) ** 2 + return fvec @mark.least_squares @@ -914,7 +698,14 @@ class FreudensteinRoth(BenchmarkFunction): max_n_params = 2 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return freudenstein_roth(x) + return _freudenstein_roth(x) + + +def _freudenstein_roth(x: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = np.zeros(2) + fvec[0] = -13 + x[0] + ((5 - x[1]) * x[1] - 2) * x[1] + fvec[1] = -29 + x[0] + ((1.0 + x[1]) * x[1] - 14) * x[1] + return fvec @mark.least_squares @@ -927,7 +718,18 @@ class Bard(BenchmarkFunction): max_n_params = 3 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return bard(x, y=y_vec) + return _bard(x, y=y_vec) + + +def _bard(x: NDArray[np.float64], y: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = np.zeros(len(y)) + for i in range(1, round(len(y) / 2) + 1): + temp = len(y) + 1 - i + fvec[i - 1] = y[i - 1] - (x[0] + i / (x[1] * temp + x[2] * i)) + for i in range(round(len(y) / 2) + 1, len(y) + 1): + temp = len(y) + 1 - i + fvec[i - 1] = y[i - 1] - (x[0] + i / (x[1] * temp + x[2] * temp)) + return fvec @mark.least_squares @@ -940,7 +742,16 @@ class KowalikOsborne(BenchmarkFunction): max_n_params = 4 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return kowalik_osborne(x, y1=v_vec, y2=y2_vec) + return _kowalik_osborne(x, y1=v_vec, y2=y2_vec) + + +def _kowalik_osborne( + x: NDArray[np.float64], y1: NDArray[np.float64], y2: NDArray[np.float64] +) -> NDArray[np.float64]: + temp1 = y1 * (y1 + x[1]) + temp2 = y1 * (y1 + x[2]) + x[3] + fvec = y2 - x[0] * temp1 / temp2 + return fvec @mark.least_squares @@ -953,7 +764,15 @@ class Meyer(BenchmarkFunction): max_n_params = 3 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return meyer(x, y=y3_vec) + return _meyer(x, y=y3_vec) + + +def _meyer(x: NDArray[np.float64], y: NDArray[np.float64]) -> NDArray[np.float64]: + temp = 5 * np.arange(1, len(y) + 1) + 45 + x[2] + temp1 = x[1] / temp + temp2 = np.exp(temp1) + fvec = x[0] * temp2 - y + return fvec @mark.least_squares @@ -966,7 +785,20 @@ class Watson(BenchmarkFunction): max_n_params = 31 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return watson(x) + return _watson(x) + + +def _watson(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(31) + for i in range(1, 30): + temp = i / 29 + sum_1 = (np.arange(1, dim_in) * temp ** np.arange(dim_in - 1) * x[1:]).sum() + sum_2 = (temp ** np.arange(dim_in) * x).sum() + fvec[i - 1] = sum_1 - sum_2**2 - 1.0 + fvec[29] = x[0] + fvec[30] = x[1] - x[0] ** 2 - 1.0 + return fvec @mark.least_squares @@ -982,7 +814,18 @@ class Box3D(BenchmarkFunction): max_n_params = 3 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return box_3d(x, dim_out=self.dim_out) + return _box_3d(x, dim_out=self.dim_out) + + +def _box_3d(x: NDArray[np.float64], dim_out: int) -> NDArray[np.float64]: + fvec = np.zeros(dim_out) + for i in range(1, dim_out + 1): + fvec[i - 1] = ( + np.exp(-i / 10 * x[0]) + - np.exp(-i / 10 * x[1]) + + (np.exp(-i) - np.exp(-i / 10)) * x[2] + ) + return fvec @mark.least_squares @@ -998,7 +841,16 @@ class JennrichSampson(BenchmarkFunction): max_n_params = 2 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return jennrich_sampson(x, dim_out=self.dim_out) + return _jennrich_sampson(x, dim_out=self.dim_out) + + +def _jennrich_sampson(x: NDArray[np.float64], dim_out: int) -> NDArray[np.float64]: + fvec = ( + 2 * (1.0 + np.arange(1, dim_out + 1)) + - np.exp(np.arange(1, dim_out + 1) * x[0]) + - np.exp(np.arange(1, dim_out + 1) * x[1]) + ) + return fvec @mark.least_squares @@ -1014,7 +866,17 @@ class BrownDennis(BenchmarkFunction): max_n_params = 4 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return brown_dennis(x, dim_out=self.dim_out) + return _brown_dennis(x, dim_out=self.dim_out) + + +def _brown_dennis(x: NDArray[np.float64], dim_out: int) -> NDArray[np.float64]: + fvec = np.zeros(dim_out) + for i in range(1, dim_out + 1): + temp = i / 5 + temp_1 = x[0] + temp * x[1] - np.exp(temp) + temp_2 = x[2] + np.sin(temp) * x[3] - np.cos(temp) + fvec[i - 1] = temp_1**2 + temp_2**2 + return fvec @mark.least_squares @@ -1028,12 +890,31 @@ class Chebyquad(BenchmarkFunction): differentiable = True def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return chebyquad(x, dim_out=self.dim_out) + return _chebyquad(x, dim_out=self.dim_out) def supports_n_params(self, n_params: int) -> bool: return 1 <= n_params <= self.dim_out +def _chebyquad(x: NDArray[np.float64], dim_out: int) -> NDArray[np.float64]: + fvec = np.zeros(dim_out) + dim_in = len(x) + for i in range(1, dim_in + 1): + temp_1 = 1.0 + temp_2 = 2 * x[i - 1] - 1.0 + temp_3 = 2 * temp_2 + for j in range(dim_out): + fvec[j] = fvec[j] + temp_2 + temp_4 = temp_3 * temp_2 - temp_1 + temp_1 = temp_2 + temp_2 = temp_4 + for i in range(1, dim_out + 1): + fvec[i - 1] = fvec[i - 1] / dim_in + if i % 2 == 0: + fvec[i - 1] = fvec[i - 1] + 1 / (i**2 - 1.0) + return fvec + + @mark.least_squares @dataclass(frozen=True) class BrownAlmostLinear(BenchmarkFunction): @@ -1042,7 +923,16 @@ class BrownAlmostLinear(BenchmarkFunction): differentiable = True def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return brown_almost_linear(x) + return _brown_almost_linear(x) + + +def _brown_almost_linear(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + sm = -(dim_in + 1) + x.sum() + product = x.prod() + fvec = x + sm + fvec[dim_in - 1] = product - 1.0 + return fvec @mark.least_squares @@ -1055,7 +945,15 @@ class OsborneOne(BenchmarkFunction): max_n_params = 5 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return osborne_one(x, y=y4_vec) + return _osborne_one(x, y=y4_vec) + + +def _osborne_one(x: NDArray[np.float64], y: NDArray[np.float64]) -> NDArray[np.float64]: + temp = 10 * np.arange(len(y)) + temp_1 = np.exp(-x[3] * temp) + temp_2 = np.exp(-x[4] * temp) + fvec = y - (x[0] + x[1] * temp_1 + x[2] * temp_2) + return fvec @mark.least_squares @@ -1068,7 +966,18 @@ class OsborneTwo(BenchmarkFunction): max_n_params = 11 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return osborne_two(x, y=y5_vec) + return _osborne_two(x, y=y5_vec) + + +def _osborne_two(x: NDArray[np.float64], y: NDArray[np.float64]) -> NDArray[np.float64]: + temp_array = np.zeros((4, len(y))) + temp = np.arange(len(y)) / 10 + temp_array[0] = np.exp(-x[4] * temp) + temp_array[1] = np.exp(-x[5] * (temp - x[8]) ** 2) + temp_array[2] = np.exp(-x[6] * (temp - x[9]) ** 2) + temp_array[3] = np.exp(-x[7] * (temp - x[10]) ** 2) + fvec = y - (temp_array.T * x[:4]).T.sum(axis=0) + return fvec @mark.least_squares @@ -1080,7 +989,22 @@ class Bdqrtic(BenchmarkFunction): min_n_params = 5 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return bdqrtic(x) + return _bdqrtic(x) + + +def _bdqrtic(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(2 * (dim_in - 4)) + for i in range(dim_in - 4): + fvec[i] = -4 * x[i] + 3 + fvec[dim_in - 4 + i] = ( + x[i] ** 2 + + 2 * x[i + 1] ** 2 + + 3 * x[i + 2] ** 2 + + 4 * x[i + 3] ** 2 + + 5 * x[dim_in - 1] ** 2 + ) + return fvec @mark.least_squares @@ -1092,7 +1016,13 @@ class Cube(BenchmarkFunction): min_n_params = 2 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return cube(x) + return _cube(x) + + +def _cube(x: NDArray[np.float64]) -> NDArray[np.float64]: + fvec = 10 * (x - np.roll(x, 1) ** 3) + fvec[0] = x[0] - 1.0 + return fvec @mark.least_squares @@ -1103,7 +1033,19 @@ class Mancino(BenchmarkFunction): differentiable = True def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return mancino(x) + return _mancino(x) + + +def _mancino(x: NDArray[np.float64]) -> NDArray[np.float64]: + dim_in = len(x) + fvec = np.zeros(dim_in) + for i in range(dim_in): + sm = 0 + for j in range(dim_in): + temp = np.sqrt(x[i] ** 2 + (i + 1) / (j + 1)) + sm += temp * ((np.sin(np.log(temp))) ** 5 + (np.cos(np.log(temp))) ** 5) + fvec[i] = 1400 * x[i] + (i + 1 - 50) ** 3 + sm + return fvec @mark.least_squares @@ -1116,7 +1058,45 @@ class HeartEight(BenchmarkFunction): max_n_params = 8 def fun(self, x: NDArray[np.float64]) -> NDArray[np.float64]: - return heart_eight(x, y=heart_eight_y_vec) + return _heart_eight(x, y=heart_eight_y_vec) + + +def _heart_eight(x: NDArray[np.float64], y: NDArray[np.float64]) -> NDArray[np.float64]: + dim_y = len(y) + fvec = np.zeros(dim_y) + fvec[0] = x[0] + x[1] - y[0] + fvec[1] = x[2] + x[3] - y[1] + fvec[2] = x[4] * x[0] + x[5] * x[1] - x[6] * x[2] - x[7] * x[3] - y[2] + fvec[3] = x[6] * x[0] + x[7] * x[1] + x[4] * x[2] + x[5] * x[3] - y[3] + fvec[4] = ( + x[0] * (x[4] ** 2 - x[6] ** 2) + - 2 * x[2] * x[4] * x[6] + + x[1] * (x[5] ** 2 - x[7] ** 2) + - 2 * x[3] * x[5] * x[7] + - y[4] + ) + fvec[5] = ( + x[2] * (x[4] ** 2 - x[6] ** 2) + + 2 * x[0] * x[4] * x[6] + + x[3] * (x[5] ** 2 - x[7] ** 2) + + 2 * x[1] * x[5] * x[7] + - y[5] + ) + fvec[6] = ( + x[0] * x[4] * (x[4] ** 2 - 3 * x[6] ** 2) + + x[2] * x[6] * (x[6] ** 2 - 3 * x[4] ** 2) + + x[1] * x[5] * (x[5] ** 2 - 3 * x[7] ** 2) + + x[3] * x[7] * (x[7] ** 2 - 3 * x[5] ** 2) + - y[6] + ) + fvec[7] = ( + x[2] * x[4] * (x[4] ** 2 - 3 * x[6] ** 2) + - x[0] * x[6] * (x[6] ** 2 - 3 * x[4] ** 2) + + x[3] * x[5] * (x[5] ** 2 - 3 * x[7] ** 2) + - x[1] * x[7] * (x[7] ** 2 - 3 * x[5] ** 2) + - y[7] + ) + return fvec # ====================================================================================== diff --git a/tests/optimagic/benchmarking/test_benchmark_problem.py b/tests/optimagic/benchmarking/test_benchmark_problem.py index faf2a2203..e13c2e303 100644 --- a/tests/optimagic/benchmarking/test_benchmark_problem.py +++ b/tests/optimagic/benchmarking/test_benchmark_problem.py @@ -1,4 +1,5 @@ from dataclasses import dataclass +from functools import partial import numpy as np import pytest @@ -31,16 +32,18 @@ class Sphere(BenchmarkFunction): multimodal = False def fun(self, x): - return float(x @ x) + return _sphere(x) def jac(self, solver_type): - if solver_type != SCALAR: - return None + return _sphere_gradient if solver_type == SCALAR else None - def gradient(x): - return 2 * x - return gradient +def _sphere(x): + return float(x @ x) + + +def _sphere_gradient(x): + return 2 * x @om.mark.least_squares @@ -52,43 +55,51 @@ class ShiftedResiduals(BenchmarkFunction): max_n_params = 4 def fun(self, x): - return np.append(x - self.shift, x[0] * x[1]) + return _shifted_residuals(x, shift=self.shift) def jac(self, solver_type): - def residual_jac(x): - last_row = np.zeros(len(x)) - last_row[0] = x[1] - last_row[1] = x[0] - return np.vstack([np.eye(len(x)), last_row]) - - def gradient(x): - return 2 * residual_jac(x).T @ self.fun(x) - if solver_type == LEAST_SQUARES: - return residual_jac + return _shifted_residuals_jac if solver_type == SCALAR: - return gradient + return partial(_shifted_residuals_gradient, shift=self.shift) return None +def _shifted_residuals(x, shift): + return np.append(x - shift, x[0] * x[1]) + + +def _shifted_residuals_jac(x): + last_row = np.zeros(len(x)) + last_row[0] = x[1] + last_row[1] = x[0] + return np.vstack([np.eye(len(x)), last_row]) + + +def _shifted_residuals_gradient(x, shift): + return 2 * _shifted_residuals_jac(x).T @ _shifted_residuals(x, shift=shift) + + @om.mark.likelihood class Contributions(BenchmarkFunction): def fun(self, x): - return np.array([x[0] ** 2, x[1] ** 2 + x[0], 3.0]) + return _contributions(x) def jac(self, solver_type): - if solver_type != LIKELIHOOD: - return None + return _contributions_jac if solver_type == LIKELIHOOD else None + + +def _contributions(x): + return np.array([x[0] ** 2, x[1] ** 2 + x[0], 3.0]) - def contribution_jac(x): - return np.array([[2 * x[0], 0.0], [1.0, 2 * x[1]], [0.0, 0.0]]) - return contribution_jac +def _contributions_jac(x): + return np.array([[2 * x[0], 0.0], [1.0, 2 * x[1]], [0.0, 0.0]]) class EvenSphere(BenchmarkFunction): def fun(self, x): - return float(x @ x) + return _sphere(x) def supports_n_params(self, n_params): return n_params % 2 == 0 @@ -96,24 +107,28 @@ def supports_n_params(self, n_params): class LogSum(BenchmarkFunction): def fun(self, x): - return float(np.log(x).sum() + x @ x) + return _log_sum(x) def bounds(self, n_params): return om.Bounds(lower=np.zeros(n_params)) -def _sum_is_one(x): - return x.sum() +def _log_sum(x): + return float(np.log(x).sum() + x @ x) class ConstrainedSphere(BenchmarkFunction): def fun(self, x): - return float(x @ x) + return _sphere(x) def constraints(self, n_params): # noqa: ARG002 return [om.NonlinearConstraint(func=_sum_is_one, value=1.0)] +def _sum_is_one(x): + return x.sum() + + ALL_FUNCTIONS = [Sphere(), ShiftedResiduals(), Contributions()]