Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ 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}`739` Fixes `tao_pounders` ignoring `convergence_gtol_abs`,
`convergence_gtol_rel` and `convergence_gtol_scaled`. Reaching `stopping_maxiter` is
now reported as unsuccessful with the message "maxits reached" instead of as
successful with "user defined" ({ghuser}`janosg`).
- {gh}`697` Adds experimental support for SciPy-style `callback(xk)` in `minimize` and
`maximize`. The callback is called after each objective evaluation; its behavior might
change in upcoming releases ({ghuser}`Pragati5-DEBUG`).
Expand Down
88 changes: 7 additions & 81 deletions src/optimagic/optimizers/tao_optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from __future__ import annotations

import functools
from dataclasses import dataclass

import numpy as np
Expand Down Expand Up @@ -97,11 +96,6 @@ class TAOPounders(Algorithm):
trust-region radius. Setting this option to zero restores TAO's default
(1e-8) instead of disabling the criterion.

.. note::
This criterion has no effect, because optimagic always installs
a custom convergence test for ``stopping_maxiter`` that replaces TAO's
default convergence test.

"""

convergence_gtol_rel: NonNegativeFloat = CONVERGENCE_GTOL_REL
Expand All @@ -116,11 +110,6 @@ class TAOPounders(Algorithm):
Setting this option to zero restores TAO's default (1e-8) instead of disabling
the criterion.

.. note::
This criterion has no effect, because optimagic always installs
a custom convergence test for ``stopping_maxiter`` that replaces TAO's
default convergence test.

"""

convergence_gtol_scaled: NonNegativeFloat = CONVERGENCE_GTOL_SCALED
Expand All @@ -136,11 +125,6 @@ class TAOPounders(Algorithm):
Setting this option to zero restores TAO's default (0), which disables the
criterion.

.. note::
This criterion has no effect, because optimagic always installs
a custom convergence test for ``stopping_maxiter`` that replaces TAO's
default convergence test.

"""

trustregion_initial_radius: NonNegativeFloat | None = None
Expand All @@ -155,12 +139,10 @@ class TAOPounders(Algorithm):
stopping_maxiter: PositiveInt = STOPPING_MAXITER
"""Maximum number of iterations.

This limit is always enforced via a custom convergence test that replaces TAO's
default convergence test, so the ``convergence_gtol_*`` criteria are ignored.
Reaching the limit is reported as a successful convergence with the message
"user defined". POUNDERS can still stop earlier on its own if the same
interpolation model is used in two successive iterations without a change of
the trust-region radius (message "step size small").
If reached, the optimization stops, but this is not counted as successful
convergence. POUNDERS can also stop on its own if the same interpolation model
is used in two successive iterations without a change of the trust-region radius
(message "step size small").

"""

Expand Down Expand Up @@ -291,22 +273,9 @@ def func_tao(tao, x, resid_out): # noqa: ARG001
gttol=default_gttol,
)

# Set user defined convergence tests. Beware that specifying multiple tests could
# overwrite others or lead to unclear behavior.
if stopping_maxiter is not None:
tao.setConvergenceTest(functools.partial(_max_iters, stopping_maxiter))
elif convergence_gtol_scaled is False and convergence_gtol_abs is False:
tao.setConvergenceTest(functools.partial(_grtol_conv, convergence_gtol_rel))
elif convergence_gtol_rel is False and convergence_gtol_scaled is False:
tao.setConvergenceTest(functools.partial(_gatol_conv, convergence_gtol_abs))
elif convergence_gtol_scaled is False:
tao.setConvergenceTest(
functools.partial(
_grtol_gatol_conv,
convergence_gtol_rel,
convergence_gtol_abs,
)
)
# Use TAO's default convergence test, which checks the gradient tolerances and the
# maximum number of iterations.
tao.setMaximumIterations(stopping_maxiter)

# Run the problem.
tao.solve()
Expand Down Expand Up @@ -344,49 +313,6 @@ def _initialise_petsc_array(len_or_array):
return array


def _max_iters(max_iterations, tao):
if tao.getSolutionStatus()[0] < max_iterations:
return 0
elif tao.getSolutionStatus()[0] >= max_iterations:
tao.setConvergedReason(8)


def _gatol_conv(absolute_gradient_tolerance, tao):
if tao.getSolutionStatus()[2] >= absolute_gradient_tolerance:
return 0
elif tao.getSolutionStatus()[2] < absolute_gradient_tolerance:
tao.setConvergedReason(3)


def _grtol_conv(relative_gradient_tolerance, tao):
if (
tao.getSolutionStatus()[2] / tao.getSolutionStatus()[1]
>= relative_gradient_tolerance
):
return 0
elif (
tao.getSolutionStatus()[2] / tao.getSolutionStatus()[1]
< relative_gradient_tolerance
):
tao.setConvergedReason(4)


def _grtol_gatol_conv(relative_gradient_tolerance, absolute_gradient_tolerance, tao):
if (
tao.getSolutionStatus()[2] / tao.getSolutionStatus()[1]
>= relative_gradient_tolerance
):
return 0
elif (
tao.getSolutionStatus()[2] / tao.getSolutionStatus()[1]
< relative_gradient_tolerance
):
tao.setConvergedReason(4)

elif tao.getSolutionStatus()[2] < absolute_gradient_tolerance:
tao.setConvergedReason(3)


def _translate_tao_convergence_reason(tao_resaon):
mapping = {
3: "absolute_gradient_tolerance below critical value",
Expand Down
121 changes: 28 additions & 93 deletions tests/optimagic/optimizers/test_tao_optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,102 +75,37 @@ def test_box_constr():
assert 0 <= result.params["value"].to_numpy()[1] <= 0.3


def test_max_iters():
rng = get_rng(5473)
true_params = get_random_params(2, rng, 0.3, 0.4, 0, 0.3)
start_params = true_params.copy()
start_params["value"] = get_random_params(2, rng, 0.1, 0.2)["value"]

exog, endog = _simulate_ols_sample(NUM_AGENTS, true_params)
criterion_func = mark.least_squares(
functools.partial(_ols_criterion, endog=endog, exog=exog)
)
result = minimize(
criterion_func,
start_params,
"tao_pounders",
algo_options={"stopping.maxiter": 25},
)

assert result.message in ("user defined", "step size small")


def test_grtol():
rng = get_rng(5474)
true_params = get_random_params(2, rng, 0.3, 0.4, 0, 0.3)
start_params = true_params.copy()
start_params["value"] = get_random_params(2, rng, 0.1, 0.2)["value"]

exog, endog = _simulate_ols_sample(NUM_AGENTS, true_params)
criterion_func = mark.least_squares(
functools.partial(_ols_criterion, endog=endog, exog=exog)
)
result = minimize(
criterion_func,
start_params,
"tao_pounders",
algo_options={
"convergence.gtol_abs": False,
"convergence.gtol_scaled": False,
},
)

assert result.message in (
"relative_gradient_tolerance below critical value",
"step size small",
)


def test_gatol():
rng = get_rng(5475)
true_params = get_random_params(2, rng, 0.3, 0.4, 0, 0.3)
start_params = true_params.copy()
start_params["value"] = get_random_params(2, rng, 0.1, 0.2)["value"]

exog, endog = _simulate_ols_sample(NUM_AGENTS, true_params)
criterion_func = mark.least_squares(
functools.partial(_ols_criterion, endog=endog, exog=exog)
)
result = minimize(
criterion_func,
start_params,
"tao_pounders",
algo_options={
"convergence.gtol_rel": False,
"convergence.gtol_scaled": False,
},
)

assert result.message in (
"absolute_gradient_tolerance below critical value",
"step size small",
)


def test_gttol():
rng = get_rng(5476)
true_params = get_random_params(2, rng, 0.3, 0.4, 0, 0.3)
start_params = true_params.copy()
start_params["value"] = get_random_params(2, rng, 0.1, 0.2)["value"]

exog, endog = _simulate_ols_sample(NUM_AGENTS, true_params)
criterion_func = mark.least_squares(
functools.partial(_ols_criterion, endog=endog, exog=exog)
)
@mark.least_squares
def _rosenbrock_residuals(x):
return np.array([x[0] - 1, 10 * (x[1] - x[0] ** 2), x[2] + 2])


@pytest.mark.parametrize(
("algo_options", "expected_message"),
[
({"stopping_maxiter": 3}, "maxits reached"),
(
{"convergence_gtol_abs": 1e-2},
"absolute_gradient_tolerance below critical value",
),
(
{"convergence_gtol_rel": 1e-2},
"relative_gradient_tolerance below critical value",
),
(
{"convergence_gtol_scaled": 1e-2},
"scaled_gradient_tolerance below critical value",
),
],
)
def test_stopping_criteria(algo_options, expected_message):
result = minimize(
criterion_func,
start_params,
_rosenbrock_residuals,
np.array([3.0, 2.0, 1.0]),
"tao_pounders",
algo_options={
"convergence.gtol_rel": False,
"convergence.gtol_abs": False,
},
)

assert result.message in (
"gradient_total_tolerance below critical value",
"step size small",
algo_options=algo_options,
)
assert result.message == expected_message


def test_tol():
Expand Down
Loading