diff --git a/CHANGES.md b/CHANGES.md index d3f830ef6..83738e88b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -14,6 +14,16 @@ This release adds experimental support for **SciPy-style callbacks**, replaces p `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}`727` Raises an `InvalidFunctionError` if the objective function or a user + provided derivative is not finite at the start params. The error message lists the + paths of the non-finite entries ({ghuser}`janosg`). +- {gh}`727` Derivative-free algorithms no longer evaluate `jac` and `fun_and_jac` at the + start params. `fun_and_jac` is only evaluated once at the start params if `fun` is + derived from it ({ghuser}`janosg`). +- {gh}`727` Fixes keyword arguments that were not passed to both the objective and the + derivative if `fun` is derived from `fun_and_jac`, i.e. if only `fun_and_jac` is + provided or `jac=True`. It is now enough to provide either `fun_kwargs` or + `fun_and_jac_kwargs` ({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`). diff --git a/docs/source/how_to/how_to_errors_during_optimization.ipynb b/docs/source/how_to/how_to_errors_during_optimization.ipynb index e3efdee80..6aae5258f 100644 --- a/docs/source/how_to/how_to_errors_during_optimization.ipynb +++ b/docs/source/how_to/how_to_errors_during_optimization.ipynb @@ -29,6 +29,26 @@ "cell_type": "markdown", "id": "1", "metadata": {}, + "source": [ + "## Make sure the start parameters are valid\n", + "\n", + "Before the optimization starts, optimagic evaluates the objective function at the start\n", + "parameters. If the algorithm uses derivatives, it also evaluates the derivatives you\n", + "provided via `jac` or `fun_and_jac`. If one of these evaluations raises an error or\n", + "returns infinite or NaN values, `minimize` and `maximize` raise an\n", + "`InvalidFunctionError`, independent of `error_handling`. The error message tells you\n", + "which entries are not finite.\n", + "\n", + "This also holds for global optimizers and multistart optimizations, even though the\n", + "start parameters are just one of many parameter vectors that are tried there. If you\n", + "cannot find a single valid parameter vector yourself, for example by random sampling,\n", + "it is unlikely that an optimizer finds one in its initial sample." + ] + }, + { + "cell_type": "markdown", + "id": "2", + "metadata": {}, "source": [ "## Let optimagic do its magic\n", "\n", @@ -42,7 +62,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2", + "id": "3", "metadata": {}, "outputs": [], "source": [ @@ -62,7 +82,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3", + "id": "4", "metadata": {}, "outputs": [], "source": [ @@ -84,7 +104,7 @@ }, { "cell_type": "markdown", - "id": "4", + "id": "5", "metadata": {}, "source": [ "### What would scipy do?" @@ -93,7 +113,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5", + "id": "6", "metadata": {}, "outputs": [], "source": [ @@ -103,7 +123,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6", + "id": "7", "metadata": {}, "outputs": [], "source": [ @@ -113,7 +133,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7", + "id": "8", "metadata": {}, "outputs": [], "source": [ @@ -122,7 +142,7 @@ }, { "cell_type": "markdown", - "id": "8", + "id": "9", "metadata": {}, "source": [ "So, scipy thinks it solved the problem successfully but the result is far off. (Note that scipy would have given us a warning, but we disabled warnings in order to not clutter the output).\n", @@ -133,7 +153,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9", + "id": "10", "metadata": {}, "outputs": [], "source": [ @@ -149,7 +169,7 @@ }, { "cell_type": "markdown", - "id": "10", + "id": "11", "metadata": {}, "source": [ "### How does the magic work\n", diff --git a/docs/source/how_to/how_to_multistart.ipynb b/docs/source/how_to/how_to_multistart.ipynb index 203ef063c..630da3a5a 100644 --- a/docs/source/how_to/how_to_multistart.ipynb +++ b/docs/source/how_to/how_to_multistart.ipynb @@ -25,7 +25,11 @@ "\n", "To activate multistart at the default options, pass `multistart=True` to the `minimize`\n", "or `maximize` function, as well as finite bounds on the parameters (which are used to\n", - "sample the initial points). The default options are discussed below." + "sample the initial points). The default options are discussed below.\n", + "\n", + "The start parameters you provide are part of the exploration sample. As in any other\n", + "optimization, the objective function has to be finite at the start parameters (see\n", + "{ref}`how-to-errors`)." ] }, { diff --git a/src/optimagic/optimization/create_optimization_problem.py b/src/optimagic/optimization/create_optimization_problem.py index a74ee918d..708a357fe 100644 --- a/src/optimagic/optimization/create_optimization_problem.py +++ b/src/optimagic/optimization/create_optimization_problem.py @@ -36,6 +36,7 @@ pre_process_multistart, ) from optimagic.optimization.scipy_aliases import ( + get_entry_of_fun_and_jac_output, map_method_to_algorithm, split_fun_and_jac, ) @@ -87,6 +88,13 @@ class OptimizationProblem: skip_checks: bool direction: Direction fun_eval: SpecificFunctionValue + fun_and_jac_eval: PyTree | None + """Derivative at the start params, as returned by ``fun_and_jac``. + + Only available if ``fun`` was derived from ``fun_and_jac``, such that the derivative + is a byproduct of the first evaluation of ``fun``. None otherwise. + + """ callback: Callable[[PyTree], None] | None @@ -170,6 +178,9 @@ def create_optimization_problem( "If `fun_and_jac` is a sequence of callables, `fun` is not optional. " ) fun = split_fun_and_jac(fun_and_jac, target="fun") + split_fun_and_jac_candidate = fun_and_jac + else: + split_fun_and_jac_candidate = None # ================================================================================== # deprecations @@ -284,6 +295,15 @@ def create_optimization_problem( if fun_and_jac is None: fun_and_jac = fun fun = split_fun_and_jac(fun_and_jac, target="fun") + split_fun_and_jac_candidate = fun_and_jac + + # If fun is derived from fun_and_jac, both are the same user function and need the + # same keyword arguments. Users only have to provide them once. + if split_fun_and_jac_candidate is not None: + if fun_kwargs is None: + fun_kwargs = fun_and_jac_kwargs + elif fun_and_jac_kwargs is None: + fun_and_jac_kwargs = fun_kwargs # ================================================================================== # Handle scipy arguments that are not yet implemented @@ -368,7 +388,21 @@ def create_optimization_problem( # problem type until the decorator approach becomes mandatory. # TODO: Move this into `_optimize` as soon as we reach 0.6.0 try: - fun_eval = fun(params) + if split_fun_and_jac_candidate is None: + fun_eval = fun(params) + fun_and_jac_eval = None + else: + # fun is the first output of fun_and_jac. Evaluate fun_and_jac instead of + # fun to keep the derivative. This saves an evaluation of fun_and_jac at + # the start params. + raw_eval = partial_func_of_params( + func=split_fun_and_jac_candidate, + kwargs=fun_kwargs, + name="criterion", + skip_checks=skip_checks, + )(params) + fun_eval = get_entry_of_fun_and_jac_output(raw_eval, 0) + fun_and_jac_eval = get_entry_of_fun_and_jac_output(raw_eval, 1) except (KeyboardInterrupt, SystemExit): raise except Exception as e: @@ -468,6 +502,14 @@ def create_optimization_problem( fun_and_jac ) + # The derivative from the first evaluation can only be used if fun_and_jac is used + # for the optimization and gets the same keyword arguments as fun. + same_kwargs = fun_kwargs is fun_and_jac_kwargs or ( + not fun_kwargs and not fun_and_jac_kwargs + ) + if fun_and_jac is None or not same_kwargs: + fun_and_jac_eval = None + # ================================================================================== # Check types of arguments # ================================================================================== @@ -560,6 +602,7 @@ def create_optimization_problem( skip_checks=skip_checks, direction=direction, fun_eval=fun_eval, + fun_and_jac_eval=fun_and_jac_eval, callback=callback, ) diff --git a/src/optimagic/optimization/internal_optimization_problem.py b/src/optimagic/optimization/internal_optimization_problem.py index f6d628739..6a2581f0b 100644 --- a/src/optimagic/optimization/internal_optimization_problem.py +++ b/src/optimagic/optimization/internal_optimization_problem.py @@ -834,7 +834,7 @@ def _assert_finite_jac( """ if not np.all(np.isfinite(out_jac)): - if origin == "jac" or "fun_and_jac": + if origin in {"jac", "fun_and_jac"}: msg = ( "The optimization failed because the derivative provided via " f"{origin} contains infinite or NaN values." diff --git a/src/optimagic/optimization/optimize.py b/src/optimagic/optimization/optimize.py index ffb96c0b2..1e82b6fe6 100644 --- a/src/optimagic/optimization/optimize.py +++ b/src/optimagic/optimization/optimize.py @@ -18,6 +18,8 @@ from typing import Any, Callable, Literal, Sequence, Type, cast import numpy as np +import pandas as pd +from numpy.typing import NDArray from scipy.optimize import Bounds as ScipyBounds from optimagic.batch_evaluators import process_batch_evaluator @@ -35,7 +37,7 @@ create_optimization_problem, ) from optimagic.optimization.error_penalty import get_error_penalty_function -from optimagic.optimization.fun_value import FunctionValue +from optimagic.optimization.fun_value import FunctionValue, SpecificFunctionValue from optimagic.optimization.internal_optimization_problem import ( InternalBounds, InternalOptimizationProblem, @@ -57,10 +59,12 @@ ) from optimagic.parameters.bounds import Bounds from optimagic.parameters.conversion import ( + Converter, get_converter, ) from optimagic.parameters.nonlinear_constraints import process_nonlinear_constraints from optimagic.parameters.scaling import ScalingOptions, ScalingOptionsDict +from optimagic.pytree import leaf_names, tree_leaves from optimagic.typing import ( AggregationLevel, Direction, @@ -68,6 +72,7 @@ ErrorHandlingLiteral, NonNegativeFloat, PyTree, + PyTreeNamespace, ) FunType = Callable[..., float | PyTree | FunctionValue] @@ -81,6 +86,12 @@ CriterionType = Callable[..., float | dict[str, Any]] CriterionAndDerivativeType = Callable[..., tuple[float | dict[str, Any], PyTree]] +MAX_PATHS_IN_ERROR_MESSAGE = 20 +"""Maximal number of paths of non-finite entries that are listed in an error.""" + +MAX_ENTRIES_SHOWN_IN_FULL = 50 +"""Numpy arrays and pandas objects with more entries are abbreviated in errors.""" + from optimagic.logging.logger import LogOptions @@ -147,7 +158,8 @@ def maximize( params: The start parameters for the optimization. Params can be numpy arrays, dictionaries, pandas.Series, pandas.DataFrames, NamedTuples, floats, lists, and any nested combination thereof. See :ref:`params` for details and - examples. + examples. The objective function has to be finite at the start parameters. + This also holds for global optimizers and multistart optimizations. algorithm: The optimization algorithm to use. Can be a string, subclass of :class:`optimagic.Algorithm` or an instance of a subclass of :class:`optimagic.Algorithm`. For guidelines on how to choose an algorithm @@ -358,7 +370,8 @@ def minimize( params: The start parameters for the optimization. Params can be numpy arrays, dictionaries, pandas.Series, pandas.DataFrames, NamedTuples, floats, lists, and any nested combination thereof. See :ref:`params` for details and - examples. + examples. The objective function has to be finite at the start parameters. + This also holds for global optimizers and multistart optimizations. algorithm: The optimization algorithm to use. Can be a string, subclass of :class:`optimagic.Algorithm` or an instance of a subclass of :class:`optimagic.Algorithm`. For guidelines on how to choose an algorithm @@ -532,32 +545,39 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: # Do first evaluation of user provided functions # ================================================================================== first_crit_eval = problem.fun_eval - - # do first derivative evaluation (if given) - if problem.jac is not None: - try: - first_deriv_eval = problem.jac(problem.params) - except (KeyboardInterrupt, SystemExit): - raise - except Exception as e: - msg = "Error while evaluating derivative at start params." - raise InvalidFunctionError(msg) from e - - if problem.fun_and_jac is not None: - try: - first_crit_and_deriv_eval = problem.fun_and_jac(problem.params) - except (KeyboardInterrupt, SystemExit): - raise - except Exception as e: - msg = "Error while evaluating criterion_and_derivative at start params." - raise InvalidFunctionError(msg) from e - - if problem.jac is not None: - used_deriv = first_deriv_eval - elif problem.fun_and_jac is not None: - used_deriv = first_crit_and_deriv_eval[1] - else: - used_deriv = None + _check_fun_is_finite_at_start(first_crit_eval) + + # do first derivative evaluation (if given and used by the algorithm) + derivative_evals = {} + if problem.algorithm.algo_info.needs_jac: + if problem.jac is not None: + try: + derivative_evals["jac"] = problem.jac(problem.params) + except (KeyboardInterrupt, SystemExit): + raise + except Exception as e: + msg = "Error while evaluating derivative at start params." + raise InvalidFunctionError(msg) from e + + if problem.fun_and_jac is not None: + if problem.fun_and_jac_eval is not None: + # fun_and_jac was already evaluated to get the first objective value + derivative_evals["fun_and_jac"] = problem.fun_and_jac_eval + else: + try: + derivative_evals["fun_and_jac"] = problem.fun_and_jac( + problem.params + )[1] + except (KeyboardInterrupt, SystemExit): + raise + except Exception as e: + msg = ( + "Error while evaluating criterion_and_derivative at start " + "params." + ) + raise InvalidFunctionError(msg) from e + + used_deriv = derivative_evals.get("jac", derivative_evals.get("fun_and_jac")) # ================================================================================== # Get the converter (for tree flattening, constraints and scaling) @@ -573,6 +593,10 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: add_soft_bounds=problem.multistart is not None, ) + _check_derivatives_are_finite_at_start( + derivative_evals, converter=converter, x=internal_params.values + ) + # ================================================================================== # initialize the log database # ================================================================================== @@ -761,3 +785,134 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: res.logger = log_reader return res + + +def _check_fun_is_finite_at_start(fun_eval: SpecificFunctionValue) -> None: + """Raise an error if the objective is not finite at the start parameters. + + No optimizer can make progress from such a point, and the penalty used with + ``error_handling="continue"`` is derived from the start value. + + """ + if not np.isfinite(fun_eval.internal_value(AggregationLevel.SCALAR)): + details = _describe_non_finite_entries( + fun_eval.value, + label="returned by the objective function", + reason_if_all_finite=( + "the sum of the contributions or squared residuals is not" + ), + ) + msg = ( + "The objective function is not finite (inf or nan) at the start params. " + "Choose start params at which the objective function is finite. This is " + "required for all algorithms, including global optimizers and multistart " + f"optimizations.{details}\n\nThe objective function returned:" + f"\n\n{_format_abbreviated(fun_eval.value)}" + ) + raise InvalidFunctionError(msg) + + +def _check_derivatives_are_finite_at_start( + derivative_evals: dict[str, PyTree], + converter: Converter, + x: NDArray[np.float64], +) -> None: + """Raise an error if a user provided derivative is not finite at the start params. + + The check is done on the derivative with respect to the internal parameters, + because this is what the optimizer sees. + + Args: + derivative_evals: Derivatives at the start params by the name of the argument + through which they were provided. + converter: Converter between external and internal parameters. + x: Internal start parameters. Has shape (n_internal,). + + """ + for name, derivative_eval in derivative_evals.items(): + internal = converter.derivative_to_internal(derivative_eval, x) + if not np.all(np.isfinite(internal)): + details = _describe_non_finite_entries( + derivative_eval, + label="of the derivative", + reason_if_all_finite=( + "the derivative is not finite after the constraints and the " + "scaling are applied" + ), + ) + msg = ( + f"The derivative provided via {name} is not finite (inf or nan) at the " + "start params. Check the derivative function or choose start params " + f"at which it is finite.{details}\n\n{name} returned the following " + f"derivative:\n\n{_format_abbreviated(derivative_eval)}" + ) + raise InvalidFunctionError(msg) + + +def _describe_non_finite_entries( + tree: PyTree, label: str, reason_if_all_finite: str +) -> str: + """Describe which entries of a pytree are not finite. + + The entries are identified by their paths, i.e. the names that optimagic uses for + the entries of a pytree. For a one-dimensional numpy array, the paths are the + positions of the entries. + + Args: + tree: A pytree with numbers, e.g. the output of the objective function. + label: Describes where the entries come from. It is placed after + "entries" in the description. + reason_if_all_finite: Describes what is not finite if all entries of the + pytree are finite. + + Returns: + A paragraph for an error message that starts with two line breaks. Empty if + the pytree has just one entry. + + """ + names = leaf_names(tree, namespace=PyTreeNamespace.VALUE) + leaves = np.array( + tree_leaves(tree, namespace=PyTreeNamespace.VALUE), dtype=np.float64 + ) + paths = [ + name + for name, is_finite in zip(names, np.isfinite(leaves), strict=True) + if not is_finite + ] + n_entries = len(names) + + if n_entries == 1: + return "" + + if not paths: + out = f"All {n_entries} entries {label} are finite, but {reason_if_all_finite}." + elif len(paths) == 1: + out = ( + f"1 of the {n_entries} entries {label} is not finite. Its path is: " + f"{paths[0]}" + ) + else: + shown = ", ".join(paths[:MAX_PATHS_IN_ERROR_MESSAGE]) + n_omitted = len(paths) - MAX_PATHS_IN_ERROR_MESSAGE + if n_omitted > 0: + shown += f" (and {n_omitted} more)" + out = ( + f"{len(paths)} of the {n_entries} entries {label} are not finite. Their " + f"paths are: {shown}" + ) + + return f"\n\n{out}" + + +def _format_abbreviated(value: PyTree) -> str: + """Represent a pytree and abbreviate large numpy arrays and pandas objects.""" + with ( + np.printoptions(threshold=MAX_ENTRIES_SHOWN_IN_FULL), + pd.option_context( + "display.max_rows", + MAX_ENTRIES_SHOWN_IN_FULL, + "display.min_rows", + 10, + ), + ): + return repr(value) diff --git a/src/optimagic/optimization/scipy_aliases.py b/src/optimagic/optimization/scipy_aliases.py index fd9d1d107..112788c2b 100644 --- a/src/optimagic/optimization/scipy_aliases.py +++ b/src/optimagic/optimization/scipy_aliases.py @@ -52,15 +52,33 @@ def split_fun_and_jac(fun_and_jac, target="fun"): @functools.wraps(fun_and_jac) def fun(*args, **kwargs): raw = fun_and_jac(*args, **kwargs) - try: - out = raw[index] - except TypeError as e: - msg = ( - "If you set `jac=True`, `fun` needs to return a tuple where the first " - "entry is the value of your objective function and the second entry " - "is its derivative." - ) - raise InvalidFunctionError(msg) from e - return out + return get_entry_of_fun_and_jac_output(raw, index) return fun + + +def get_entry_of_fun_and_jac_output(raw, index): + """Get the objective value or the derivative from the output of fun_and_jac. + + Args: + raw: The output of a function that returns the objective value and its + derivative. + index: 0 for the objective value and 1 for the derivative. + + Returns: + The selected entry of the output. + + Raises: + InvalidFunctionError: If the output cannot be indexed. + + """ + try: + out = raw[index] + except TypeError as e: + msg = ( + "If you set `jac=True`, `fun` needs to return a tuple where the first " + "entry is the value of your objective function and the second entry " + "is its derivative." + ) + raise InvalidFunctionError(msg) from e + return out diff --git a/tests/optimagic/optimization/test_invalid_jacobian_value.py b/tests/optimagic/optimization/test_invalid_jacobian_value.py index 19e186591..33a361d45 100644 --- a/tests/optimagic/optimization/test_invalid_jacobian_value.py +++ b/tests/optimagic/optimization/test_invalid_jacobian_value.py @@ -112,3 +112,22 @@ def test_minimize_with_invalid_fun_and_jac(invalid_jac_value, params): algorithm="scipy_lbfgsb", fun_and_jac=get_invalid_fun_and_jac(invalid_jac_value), ) + + +# ====================================================================================== +# Test Invalid Jacobian raises proper error with numerical derivatives +# ====================================================================================== + + +def test_minimize_with_invalid_numerical_derivative(params): + def fun(params): + return sphere(params) if params["a"] == 1 else np.inf + + with pytest.raises( + UserFunctionRuntimeError, + match=( + "The optimization failed because the numerical derivative " + r"\(computed using fun\) contains infinite or NaN values." + ), + ): + minimize(fun=fun, params=params, algorithm="scipy_lbfgsb") diff --git a/tests/optimagic/optimization/test_optimize.py b/tests/optimagic/optimization/test_optimize.py index f74c307df..d028245b5 100644 --- a/tests/optimagic/optimization/test_optimize.py +++ b/tests/optimagic/optimization/test_optimize.py @@ -5,9 +5,19 @@ import pytest from numpy.testing import assert_array_almost_equal as aaae +import optimagic as om +from optimagic import mark from optimagic.examples.criterion_functions import sos_scalar -from optimagic.exceptions import InvalidFunctionError, InvalidNumdiffOptionsError -from optimagic.optimization.optimize import maximize, minimize +from optimagic.exceptions import ( + InvalidFunctionError, + InvalidNumdiffOptionsError, + UserFunctionRuntimeError, +) +from optimagic.optimization.optimize import ( + MAX_PATHS_IN_ERROR_MESSAGE, + maximize, + minimize, +) def test_sign_is_switched_back_after_maximization(): @@ -66,3 +76,369 @@ def test_fun_and_jac_sequence_without_fun(container): params=np.arange(5), algorithm="scipy_lbfgsb", ) + + +# ====================================================================================== +# The objective function has to be finite at the start params +# ====================================================================================== + + +@pytest.mark.parametrize("value", [np.inf, -np.inf, np.nan]) +def test_non_finite_scalar_fun_at_start_raises(value): + def fun(x): + return value if x[0] == 5 else x @ x + + with pytest.raises(InvalidFunctionError, match="not finite") as e: + minimize(fun, params=np.array([5.0, 2.0]), algorithm="scipy_lbfgsb") + # a scalar has no path + assert "path" not in str(e.value) + assert "multistart" in str(e.value) + + +@pytest.mark.parametrize("value", [np.inf, -np.inf, np.nan]) +def test_non_finite_scalar_fun_at_start_raises_with_maximize(value): + def fun(x): + return value if x[0] == 5 else -x @ x + + with pytest.raises(InvalidFunctionError, match="not finite"): + maximize(fun, params=np.array([5.0, 2.0]), algorithm="scipy_lbfgsb") + + +def test_finite_fun_at_start_does_not_raise_with_maximize(): + res = maximize(lambda x: -x @ x, params=np.ones(2), algorithm="scipy_lbfgsb") + aaae(res.params, np.zeros(2)) + + +def test_non_finite_fun_at_start_raises_with_error_handling_continue(): + def fun(x): + return np.nan if x[0] == 5 else x @ x + + with pytest.raises(InvalidFunctionError, match="not finite"): + minimize( + fun, + params=np.array([5.0, 2.0]), + algorithm="scipy_lbfgsb", + error_handling="continue", + ) + + +@pytest.mark.parametrize("algorithm", ["scipy_lbfgsb", "scipy_neldermead"]) +def test_non_finite_fun_at_start_raises_with_multistart(algorithm): + def fun(x): + return np.nan if x[0] == 5 else x @ x + + with pytest.raises(InvalidFunctionError, match="not finite"): + minimize( + fun, + params=np.array([5.0, 2.0]), + algorithm=algorithm, + bounds=om.Bounds(lower=np.full(2, -10.0), upper=np.full(2, 10.0)), + multistart=True, + ) + + +def test_non_finite_likelihood_contributions_at_start_raise_with_short_message(): + @mark.likelihood + def fun(x): + out = np.ones(20_000) * (x @ x) + out[[1_500, 15_000]] = np.nan + return out + + with pytest.raises(InvalidFunctionError, match="not finite") as e: + minimize(fun, params=np.ones(2), algorithm="scipy_lbfgsb") + msg = str(e.value) + assert "2 of the 20000 entries" in msg + assert "Their paths are: 1500, 15000" in msg + # the output of the function is abbreviated + assert "..." in msg + assert len(msg) < 1_000 + + +def test_non_finite_fun_at_start_raises_with_limited_number_of_paths(): + @mark.likelihood + def fun(x): + return np.full(1_000, np.nan) + + with pytest.raises(InvalidFunctionError, match="not finite") as e: + minimize(fun, params=np.ones(2), algorithm="scipy_lbfgsb") + msg = str(e.value) + assert "1000 of the 1000 entries" in msg + last_path = MAX_PATHS_IN_ERROR_MESSAGE - 1 + n_omitted = 1_000 - MAX_PATHS_IN_ERROR_MESSAGE + assert f", {last_path} (and {n_omitted} more)" in msg + + +def test_non_finite_pytree_residuals_at_start_raise_with_paths(): + @mark.least_squares + def fun(x): + return {"a": x, "b": pd.Series([np.inf, 1.0], index=["c", "d"])} + + with pytest.raises(InvalidFunctionError, match="not finite") as e: + minimize(fun, params=np.ones(2), algorithm="scipy_ls_lm") + msg = str(e.value) + assert "1 of the 4 entries" in msg + assert "Its path is: b_c" in msg + # small outputs are shown in full + assert "'b':" in msg + assert "c inf" in msg + + +def test_overflow_in_aggregation_of_residuals_at_start_raises(): + @mark.least_squares + def fun(x): + return np.full(3, 1e200) * x[0] + + with pytest.raises(InvalidFunctionError, match="not finite") as e: + minimize(fun, params=np.ones(2), algorithm="scipy_lbfgsb") + assert "All 3 entries returned by the objective function are finite" in str(e.value) + + +# ====================================================================================== +# User provided derivatives have to be finite at the start params if they are used +# ====================================================================================== + + +@pytest.mark.parametrize("value", [np.inf, np.nan]) +def test_non_finite_jac_at_start_raises(value): + def jac(x): + return np.array([2 * x[0], value, 2 * x[2]]) + + with pytest.raises( + InvalidFunctionError, match="provided via jac is not finite" + ) as e: + minimize(lambda x: x @ x, params=np.ones(3), algorithm="scipy_lbfgsb", jac=jac) + msg = str(e.value) + assert "1 of the 3 entries" in msg + # for flat arrays, the paths are positions + assert "Its path is: 1\n" in msg + + +def test_non_finite_jac_at_start_is_not_a_user_function_runtime_error(): + # Before, this was a UserFunctionRuntimeError that was raised by the algorithm's + # first derivative evaluation. Code that catches this error does not catch the + # error at the start params. + def jac(x): + return np.array([np.nan, 2 * x[1]]) + + with pytest.raises(InvalidFunctionError) as e: + minimize(lambda x: x @ x, params=np.ones(2), algorithm="scipy_lbfgsb", jac=jac) + assert not isinstance(e.value, UserFunctionRuntimeError) + + +def test_non_finite_jac_after_start_is_a_user_function_runtime_error(): + def jac(x): + return 2 * x if np.allclose(x, 1) else np.array([np.nan, 2 * x[1]]) + + with pytest.raises(UserFunctionRuntimeError, match="infinite or NaN values"): + minimize(lambda x: x @ x, params=np.ones(2), algorithm="scipy_lbfgsb", jac=jac) + + +def test_non_finite_jac_at_start_does_not_raise_for_derivative_free_algorithm(): + def jac(x): + return np.array([np.inf, 2 * x[1]]) + + res = minimize( + lambda x: x @ x, params=np.ones(2), algorithm="scipy_neldermead", jac=jac + ) + aaae(res.params, np.zeros(2), decimal=4) + + +def test_derivatives_are_not_evaluated_for_derivative_free_algorithm(): + def raise_error(x): + raise ValueError("Derivatives should not be evaluated.") + + res = minimize( + lambda x: x @ x, + params=np.ones(2), + algorithm="scipy_neldermead", + jac=raise_error, + fun_and_jac=raise_error, + ) + aaae(res.params, np.zeros(2), decimal=4) + + +def test_non_finite_fun_and_jac_at_start_raises(): + def fun_and_jac(x): + return x["a"] ** 2 + x["b"] ** 2, {"a": 2 * x["a"], "b": np.nan} + + with pytest.raises(InvalidFunctionError, match="fun_and_jac is not finite") as e: + minimize( + fun_and_jac=fun_and_jac, + params={"a": 1.0, "b": 2.0}, + algorithm="scipy_lbfgsb", + ) + msg = str(e.value) + assert "Its path is: b\n" in msg + assert "'b': nan" in msg + + +@pytest.mark.filterwarnings("ignore:overflow encountered") +def test_jac_that_is_only_non_finite_after_scaling_at_start_raises(): + def jac(x): + return np.array([1e300, 2 * x[1]]) + + with pytest.raises(InvalidFunctionError, match="jac is not finite") as e: + minimize( + lambda x: x @ x, + params=np.array([1e10, 1.0]), + algorithm="scipy_lbfgsb", + jac=jac, + scaling=True, + ) + assert "All 2 entries of the derivative are finite" in str(e.value) + + +def test_non_finite_jac_of_single_param_at_start_raises_without_path(): + with pytest.raises(InvalidFunctionError, match="jac is not finite") as e: + minimize( + lambda x: x**2, + params=1.0, + algorithm="scipy_lbfgsb", + jac=lambda x: np.nan, + ) + assert "path" not in str(e.value) + + +# ====================================================================================== +# fun_and_jac is not evaluated more often than necessary at the start params +# ====================================================================================== + + +def _get_counting_fun_and_jac(): + calls = [] + + def fun_and_jac(x): + calls.append(x) + return x @ x, 2 * x + + return fun_and_jac, calls + + +def test_fun_and_jac_without_fun_is_evaluated_once_at_start(): + fun_and_jac, calls = _get_counting_fun_and_jac() + + res = minimize(fun_and_jac=fun_and_jac, params=np.ones(2), algorithm="scipy_lbfgsb") + + aaae(res.params, np.zeros(2)) + # one evaluation at the start params and the evaluations done by the algorithm + assert len(calls) - 1 == res.n_fun_evals + + +def test_fun_with_jac_equal_to_true_is_evaluated_once_at_start(): + fun_and_jac, calls = _get_counting_fun_and_jac() + + res = minimize(fun_and_jac, params=np.ones(2), algorithm="scipy_lbfgsb", jac=True) + + aaae(res.params, np.zeros(2)) + assert len(calls) - 1 == res.n_fun_evals + + +def test_fun_and_jac_is_evaluated_once_at_start_if_fun_is_provided(): + fun_and_jac, calls = _get_counting_fun_and_jac() + + res = minimize( + lambda x: x @ x, + fun_and_jac=fun_and_jac, + params=np.ones(2), + algorithm="scipy_lbfgsb", + ) + + aaae(res.params, np.zeros(2)) + assert len(calls) - 1 == res.n_fun_evals + + +def test_start_derivative_is_evaluated_with_fun_and_jac_kwargs(): + # The derivative at the start params is only finite with the fun_and_jac_kwargs. + # It must not be taken from the first evaluation of fun, which gets fun_kwargs. + def fun_and_jac(x, factor): + return x @ x, 2 * x * factor + + res = minimize( + fun_and_jac=fun_and_jac, + fun_kwargs={"factor": np.nan}, + fun_and_jac_kwargs={"factor": 1.0}, + params=np.ones(2), + algorithm="scipy_lbfgsb", + ) + aaae(res.params, np.zeros(2)) + + +# ====================================================================================== +# A fun that is derived from fun_and_jac gets the same kwargs as fun_and_jac +# ====================================================================================== + + +def _get_counting_fun_and_jac_with_target(): + calls = [] + + def fun_and_jac(x, target): + calls.append(x) + diff = x - target + return diff @ diff, 2 * diff + + return fun_and_jac, calls + + +@pytest.mark.parametrize("use_fun_kwargs", [True, False]) +def test_fun_and_jac_without_fun_shares_kwargs(use_fun_kwargs): + fun_and_jac, calls = _get_counting_fun_and_jac_with_target() + target = np.array([1.0, 2.0]) + kwargs = {"target": target} + + res = minimize( + fun_and_jac=fun_and_jac, + params=np.zeros(2), + algorithm="scipy_lbfgsb", + fun_kwargs=kwargs if use_fun_kwargs else None, + fun_and_jac_kwargs=None if use_fun_kwargs else kwargs, + ) + + aaae(res.params, target) + assert len(calls) - 1 == res.n_fun_evals + + +@pytest.mark.parametrize("use_fun_kwargs", [True, False]) +def test_fun_with_jac_equal_to_true_shares_kwargs(use_fun_kwargs): + fun_and_jac, calls = _get_counting_fun_and_jac_with_target() + target = np.array([1.0, 2.0]) + kwargs = {"target": target} + + res = minimize( + fun_and_jac, + params=np.zeros(2), + algorithm="scipy_lbfgsb", + jac=True, + fun_kwargs=kwargs if use_fun_kwargs else None, + fun_and_jac_kwargs=None if use_fun_kwargs else kwargs, + ) + + aaae(res.params, target) + assert len(calls) - 1 == res.n_fun_evals + + +def test_fun_with_jac_equal_to_true_and_args(): + fun_and_jac, calls = _get_counting_fun_and_jac_with_target() + target = np.array([1.0, 2.0]) + + res = minimize( + fun_and_jac, + params=np.zeros(2), + algorithm="scipy_lbfgsb", + jac=True, + args=(target,), + ) + + aaae(res.params, target) + assert len(calls) - 1 == res.n_fun_evals + + +def test_start_derivative_of_unused_fun_and_jac_is_ignored(): + @mark.least_squares + def fun_and_jac(x): + return x, np.full((2, 2), np.nan) + + with pytest.warns(UserWarning, match="Falling back to numerical derivatives"): + res = minimize( + fun_and_jac=fun_and_jac, params=np.ones(2), algorithm="scipy_lbfgsb" + ) + aaae(res.params, np.zeros(2))