Skip to content
Open
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 @@ -29,6 +29,10 @@ This release adds experimental support for **SciPy-style callbacks**, replaces p
validators of algorithm options are built when an algorithm is instantiated for the
first time and the classes behind `om.algos` are no longer dataclasses. The minimum
supported version of pydantic is now 2.10 ({ghuser}`janosg`).
- {gh}`742` Ignores derivatives with respect to parameters that do not depend on
internal parameters, e.g. fixed parameters. Infinite or NaN entries of a user
provided derivative for such parameters no longer make the optimization fail
({ghuser}`janosg`).
- {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
Expand Down
77 changes: 76 additions & 1 deletion src/optimagic/parameters/space_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,20 @@ def get_space_converter(
post_replacements=constr_info["post_replacements"]
)

_depends_on_internal = get_mask_of_params_that_depend_on_internal(
transformations=transformations,
pre_replace_jac=_pre_replace_jac,
post_replace_jac=_post_replace_jac,
)

_derivative_to_internal = partial(
convert_external_derivative_to_internal,
fixed_values=constr_info["internal_fixed_values"],
pre_replacements=constr_info["pre_replacements"],
transformations=transformations,
pre_replace_jac=_pre_replace_jac,
post_replace_jac=_post_replace_jac,
depends_on_internal=_depends_on_internal,
)

_has_transforming_constraints = bool(transformations)
Expand Down Expand Up @@ -242,6 +249,7 @@ def convert_external_derivative_to_internal(
post_replacements=None,
pre_replace_jac=None,
post_replace_jac=None,
depends_on_internal=None,
):
r"""Compute the derivative of the criterion utilizing an external derivative.

Expand All @@ -262,6 +270,10 @@ def convert_external_derivative_to_internal(
second part denotes the derivative of the parameter transform from inner
to external.

Entries of the external derivative that belong to external parameters that do not
depend on any internal parameter (e.g. fixed parameters) are ignored. They do not
influence the result, even if they are infinite or NaN.

Args:
external_derivative (numpy.ndarray): The external derivative evaluated at
external values mapped from ``internal_values``.
Expand All @@ -279,7 +291,9 @@ def convert_external_derivative_to_internal(
vector that has to be copied to duplicated and copied to the i_th position
of the external parameter vector.
pre_replace_jac (np.ndarray): 2d Array with the jacobian of pre_replace
post_replacment_jacobian (np.ndarray): 2d Array with the jacobian post_replace
post_replace_jac (np.ndarray): 2d Array with the jacobian post_replace
depends_on_internal (np.ndarray): 1d boolean array of length n_external. True
for external parameters that depend on at least one internal parameter.

Returns:
deriv (numpy.ndarray): The gradient or Jacobian.
Expand All @@ -300,9 +314,23 @@ def convert_external_derivative_to_internal(
if post_replace_jac is None:
post_replace_jac = post_replace_jacobian(post_replacements)

if depends_on_internal is None:
depends_on_internal = get_mask_of_params_that_depend_on_internal(
transformations=transformations,
pre_replace_jac=pre_replace_jac,
post_replace_jac=post_replace_jac,
)

transform_jac = transformation_jacobian(transformations, pre_replaced)

external_derivative = np.atleast_2d(external_derivative)

# The rows of the transformation Jacobians that belong to parameters that do not
# depend on internal parameters are zero. Multiplying them with infinite or NaN
# entries of the external derivative would spread NaNs to the whole result.
if not depends_on_internal.all():
external_derivative = np.where(depends_on_internal, external_derivative, 0)

tall_external = external_derivative.shape[0] > external_derivative.shape[1]

mat_list = [
Expand All @@ -323,6 +351,53 @@ def convert_external_derivative_to_internal(
return deriv


def get_mask_of_params_that_depend_on_internal(
transformations, pre_replace_jac, post_replace_jac
):
"""Determine which external parameters depend on at least one internal parameter.

External parameters that do not depend on any internal parameter are constant
during the optimization. Examples are fixed parameters and parameters that are
equal to a fixed parameter.

The dependence is determined from the structure of the reparametrization and not
from the values of a Jacobian. All parameters of a transforming constraint are
treated as dependent if at least one of them depends on an internal parameter.

Args:
transformations (list): Processed transforming constraints.
pre_replace_jac (np.ndarray): 2d Array of shape (n_external, n_internal) with
the jacobian of pre_replace.
post_replace_jac (np.ndarray): 2d Array of shape (n_external, n_external) with
the jacobian of post_replace.

Returns:
np.ndarray: 1d boolean array of length n_external.

Examples:
>>> # Note: The Jacobians are the ones from the doctests of
>>> # pre_replace_jacobian and post_replace_jacobian
>>> pre_replace_jac = np.array([[0., 1.], [0., 0.], [1., 0.]])
>>> post_replace_jac = np.array([[1., 0., 0.], [0., 1., 0.], [0., 1., 0.]])
>>> get_mask_of_params_that_depend_on_internal(
... transformations=[],
... pre_replace_jac=pre_replace_jac,
... post_replace_jac=post_replace_jac,
... )
array([ True, False, False])

"""
# dependence after the pre-replacement step
depends = pre_replace_jac.any(axis=1)

# dependence after the transformation step
for constr in transformations:
depends[constr["index"]] = depends[constr["index"]].any()

# dependence after the post-replacement step
return post_replace_jac.astype(bool) @ depends


def _multiply_from_left(mat_list):
"""Multiply all matrices in the list, starting from the left.

Expand Down
91 changes: 90 additions & 1 deletion tests/optimagic/optimization/test_invalid_jacobian_value.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal as aaae

from optimagic.exceptions import UserFunctionRuntimeError
import optimagic as om
from optimagic.exceptions import InvalidFunctionError, UserFunctionRuntimeError
from optimagic.optimization.optimize import minimize

# ======================================================================================
Expand Down Expand Up @@ -131,3 +133,90 @@ def fun(params):
),
):
minimize(fun=fun, params=params, algorithm="scipy_lbfgsb")


# ======================================================================================
# Test that invalid derivatives with respect to fixed parameters are ignored
# ======================================================================================


def _fix_a():
return om.FixedConstraint(selector=lambda params: params["a"])


@pytest.mark.parametrize("invalid_value", [np.nan, np.inf, -np.inf])
def test_minimize_ignores_invalid_jac_of_fixed_params(invalid_value, params):
def jac(params):
return {"a": invalid_value, "b": 2 * params["b"]}

res = minimize(
fun=sphere,
params=params,
algorithm="scipy_lbfgsb",
jac=jac,
constraints=_fix_a(),
)

assert res.params["a"] == 1
aaae(res.params["b"], np.zeros(2))


@pytest.mark.parametrize("invalid_value", [np.nan, np.inf, -np.inf])
def test_minimize_ignores_invalid_fun_and_jac_of_fixed_params(invalid_value, params):
def fun_and_jac(params):
return sphere(params), {"a": invalid_value, "b": 2 * params["b"]}

res = minimize(
params=params,
algorithm="scipy_lbfgsb",
fun_and_jac=fun_and_jac,
constraints=_fix_a(),
)

assert res.params["a"] == 1
aaae(res.params["b"], np.zeros(2))


@pytest.mark.parametrize("invalid_value", [np.nan, np.inf, -np.inf])
def test_minimize_ignores_invalid_least_squares_jac_of_fixed_params(invalid_value):
@om.mark.least_squares
def fun(x):
return x

@om.mark.least_squares
def jac(x):
out = np.eye(len(x))
out[:, 0] = invalid_value
return out

res = minimize(
fun=fun,
params=np.array([1.0, 2.0, 3.0]),
algorithm="scipy_ls_lm",
jac=jac,
constraints=om.FixedConstraint(selector=lambda x: x[0]),
)

aaae(res.params, np.array([1.0, 0.0, 0.0]))


@pytest.mark.parametrize("invalid_value", [np.nan, np.inf, -np.inf])
def test_minimize_with_invalid_jac_of_free_params_and_fixed_params(
invalid_value, params
):
def jac(params):
return {
"a": 2 * params["a"],
"b": np.array([invalid_value, 2 * params["b"][1]]),
}

# The derivative is already invalid at the start params, so the check of the start
# params raises.
with pytest.raises(InvalidFunctionError, match="via jac is not finite"):
minimize(
fun=sphere,
params=params,
algorithm="scipy_lbfgsb",
jac=jac,
constraints=_fix_a(),
)
96 changes: 96 additions & 0 deletions tests/optimagic/parameters/test_space_conversion.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal as aaae
from numpy.testing import assert_array_equal

from optimagic import first_derivative
from optimagic.parameters.space_conversion import (
Expand Down Expand Up @@ -310,3 +311,98 @@ def test_multiply_from_left_and_right(seed):

aaae(calc_from_left, expected)
aaae(calc_from_right, expected)


# ======================================================================================
# Derivatives with respect to external parameters that do not depend on the internal
# parameters (e.g. fixed parameters) must not influence the internal derivative.
# ======================================================================================

# name: (constraints, external values, positions that do not depend on internal params)
INDEPENDENT_PARAMS_CASES = {
"fixed": (
[{"index": [0, 2], "type": "fixed"}],
np.array([1.0, 2.0, 3.0, 4.0]),
[0, 2],
),
"fixed_and_increasing": (
[{"index": [0], "type": "fixed"}, {"index": [1, 2, 3], "type": "increasing"}],
np.array([5.0, 1.0, 2.0, 3.0]),
[0],
),
"fixed_and_probability": (
[
{"index": [4], "type": "fixed"},
{"index": [0, 1, 2, 3], "type": "probability"},
],
np.array([0.1, 0.2, 0.2, 0.5, 10.0]),
[4],
),
"fixed_and_equality": (
[{"index": [1], "type": "fixed"}, {"index": [1, 2], "type": "equality"}],
np.array([0.0, 1.5, 1.5, 3.0]),
[1, 2],
),
}


def _get_converter_and_internal_values(constraints, values):
params = InternalParams(
values=values,
lower_bounds=np.full(len(values), -np.inf),
upper_bounds=np.full(len(values), np.inf),
names=[str(i) for i in range(len(values))],
)
converter, internal = get_space_converter(
internal_params=params, internal_constraints=constraints
)
return converter, internal.values


@pytest.mark.parametrize("invalid", [np.nan, np.inf, -np.inf])
@pytest.mark.parametrize("n_rows", [None, 2, 8], ids=["gradient", "wide", "tall"])
@pytest.mark.parametrize(
"constraints, values, independent",
list(INDEPENDENT_PARAMS_CASES.values()),
ids=list(INDEPENDENT_PARAMS_CASES),
)
def test_derivative_to_internal_ignores_params_that_do_not_depend_on_internal(
constraints, values, independent, n_rows, invalid
):
converter, internal_values = _get_converter_and_internal_values(constraints, values)

shape = (len(values),) if n_rows is None else (n_rows, len(values))
valid_derivative = get_rng(0).uniform(size=shape)
invalid_derivative = valid_derivative.copy()
invalid_derivative[..., independent] = invalid
passed_derivative = invalid_derivative.copy()

expected = converter.derivative_to_internal(valid_derivative, internal_values)
got = converter.derivative_to_internal(passed_derivative, internal_values)

assert np.isfinite(got).all()
aaae(got, expected)
# the derivative that was passed in is not modified
assert_array_equal(passed_derivative, invalid_derivative)


@pytest.mark.parametrize("invalid", [np.nan, np.inf, -np.inf])
@pytest.mark.parametrize("n_rows", [None, 2, 8], ids=["gradient", "wide", "tall"])
@pytest.mark.parametrize(
"constraints, values, independent",
list(INDEPENDENT_PARAMS_CASES.values()),
ids=list(INDEPENDENT_PARAMS_CASES),
)
def test_derivative_to_internal_keeps_invalid_values_of_other_params(
constraints, values, independent, n_rows, invalid
):
converter, internal_values = _get_converter_and_internal_values(constraints, values)

shape = (len(values),) if n_rows is None else (n_rows, len(values))
for position in set(range(len(values))) - set(independent):
derivative = get_rng(0).uniform(size=shape)
derivative[..., position] = invalid

got = converter.derivative_to_internal(derivative, internal_values)

assert not np.isfinite(got).all()
Loading