From 0b643394f25f4113eec1360784d7ab825233c4d0 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Sun, 25 Oct 2026 12:42:03 +0100 Subject: [PATCH 1/9] Raise if the objective is not finite at the start params optimagic only caught exceptions in the first evaluation of the objective. With an inf start value, scipy_lbfgsb reported success at a wrong point. Co-Authored-By: Claude Opus 5.5 --- src/optimagic/optimization/optimize.py | 38 ++++++++++++++++++- tests/optimagic/optimization/test_optimize.py | 32 ++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/src/optimagic/optimization/optimize.py b/src/optimagic/optimization/optimize.py index b8a571126..8c8fccdb2 100644 --- a/src/optimagic/optimization/optimize.py +++ b/src/optimagic/optimization/optimize.py @@ -35,7 +35,12 @@ 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, + LeastSquaresFunctionValue, + LikelihoodFunctionValue, + SpecificFunctionValue, +) from optimagic.optimization.internal_optimization_problem import ( InternalBounds, InternalOptimizationProblem, @@ -532,6 +537,7 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: # Do first evaluation of user provided functions # ================================================================================== first_crit_eval = problem.fun_eval + _check_fun_is_finite_at_start(first_crit_eval) # do first derivative evaluation (if given) if problem.jac is not None: @@ -761,3 +767,33 @@ 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 isinstance(fun_eval, LeastSquaresFunctionValue): + level = AggregationLevel.LEAST_SQUARES + elif isinstance(fun_eval, LikelihoodFunctionValue): + level = AggregationLevel.LIKELIHOOD + else: + level = AggregationLevel.SCALAR + value = np.atleast_1d(fun_eval.internal_value(level)) + invalid = np.flatnonzero(~np.isfinite(value)) + if invalid.size > 0: + msg = ( + "The objective function is not finite (inf or nan) at the start params. " + "Choose start params at which the objective function is finite." + ) + if value.size > 1: + shown = invalid[:10].tolist() + more = " (first 10 shown)" if invalid.size > 10 else "" + msg += ( + f" {invalid.size} of {value.size} entries of the flattened objective " + f"value are not finite; their positions are {shown}{more}." + ) + raise InvalidFunctionError(msg) diff --git a/tests/optimagic/optimization/test_optimize.py b/tests/optimagic/optimization/test_optimize.py index f74c307df..926ee14c0 100644 --- a/tests/optimagic/optimization/test_optimize.py +++ b/tests/optimagic/optimization/test_optimize.py @@ -5,6 +5,7 @@ import pytest from numpy.testing import assert_array_almost_equal as aaae +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 @@ -66,3 +67,34 @@ def test_fun_and_jac_sequence_without_fun(container): params=np.arange(5), algorithm="scipy_lbfgsb", ) + + +@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"): + minimize(fun, params=np.array([5.0, 2.0]), algorithm="scipy_lbfgsb") + + +def test_non_finite_likelihood_contributions_at_start_raise_with_positions(): + @mark.likelihood + def fun(x): + out = np.ones(20) * (x @ x) + out[[3, 7]] = np.nan + return out + + with pytest.raises( + InvalidFunctionError, match=r"2 of 20 .* positions are \[3, 7\]" + ): + minimize(fun, params=np.ones(2), algorithm="scipy_lbfgsb") + + +def test_non_finite_residuals_at_start_raise_for_derivative_free_algorithm(): + @mark.least_squares + def fun(x): + return np.array([x[0], np.inf if x[1] == 2 else x[1]]) + + with pytest.raises(InvalidFunctionError, match="not finite"): + minimize(fun, params=np.array([1.0, 2.0]), algorithm="scipy_neldermead") From f55c36db38442fa641121e4030b0beaa33b2459c Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Fri, 30 Oct 2026 07:50:57 +0100 Subject: [PATCH 2/9] Show the full output and check derivatives at the start params The message for a non-finite objective now contains the complete output of the objective function instead of positions in the flattened value, which are not meaningful for pytrees. User provided derivatives (jac and fun_and_jac) are now also checked for finiteness at the start params. Co-Authored-By: Claude Opus 5.5 --- src/optimagic/optimization/optimize.py | 62 +++++++++++++++---- tests/optimagic/optimization/test_optimize.py | 45 ++++++++++++-- 2 files changed, 90 insertions(+), 17 deletions(-) diff --git a/src/optimagic/optimization/optimize.py b/src/optimagic/optimization/optimize.py index 8c8fccdb2..7f32ec41d 100644 --- a/src/optimagic/optimization/optimize.py +++ b/src/optimagic/optimization/optimize.py @@ -14,10 +14,13 @@ from __future__ import annotations +import sys from pathlib import Path 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 @@ -62,6 +65,7 @@ ) from optimagic.parameters.bounds import Bounds from optimagic.parameters.conversion import ( + Converter, get_converter, ) from optimagic.parameters.nonlinear_constraints import process_nonlinear_constraints @@ -579,6 +583,15 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: add_soft_bounds=problem.multistart is not None, ) + derivative_evals = {} + if problem.jac is not None: + derivative_evals["jac"] = first_deriv_eval + if problem.fun_and_jac is not None: + derivative_evals["fun_and_jac"] = first_crit_and_deriv_eval[1] + _check_derivatives_are_finite_at_start( + derivative_evals, converter=converter, x=internal_params.values + ) + # ================================================================================== # initialize the log database # ================================================================================== @@ -782,18 +795,45 @@ def _check_fun_is_finite_at_start(fun_eval: SpecificFunctionValue) -> None: level = AggregationLevel.LIKELIHOOD else: level = AggregationLevel.SCALAR - value = np.atleast_1d(fun_eval.internal_value(level)) - invalid = np.flatnonzero(~np.isfinite(value)) - if invalid.size > 0: + if not np.all(np.isfinite(fun_eval.internal_value(level))): msg = ( "The objective function is not finite (inf or nan) at the start params. " - "Choose start params at which the objective function is finite." + "Choose start params at which the objective function is finite. The " + f"objective function returned:\n\n{_format_in_full(fun_eval.value)}" ) - if value.size > 1: - shown = invalid[:10].tolist() - more = " (first 10 shown)" if invalid.size > 10 else "" - msg += ( - f" {invalid.size} of {value.size} entries of the flattened objective " - f"value are not finite; their positions are {shown}{more}." - ) 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. + + 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. + + """ + for name, derivative_eval in derivative_evals.items(): + internal = converter.derivative_to_internal(derivative_eval, x) + if not np.all(np.isfinite(internal)): + 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. {name} returned the following derivative:" + f"\n\n{_format_in_full(derivative_eval)}" + ) + raise InvalidFunctionError(msg) + + +def _format_in_full(value: PyTree) -> str: + """Represent a pytree without truncating numpy arrays or pandas objects.""" + with ( + np.printoptions(threshold=sys.maxsize), + pd.option_context("display.max_rows", None, "display.max_columns", None), + ): + return repr(value) diff --git a/tests/optimagic/optimization/test_optimize.py b/tests/optimagic/optimization/test_optimize.py index 926ee14c0..f951bc087 100644 --- a/tests/optimagic/optimization/test_optimize.py +++ b/tests/optimagic/optimization/test_optimize.py @@ -78,17 +78,28 @@ def fun(x): minimize(fun, params=np.array([5.0, 2.0]), algorithm="scipy_lbfgsb") -def test_non_finite_likelihood_contributions_at_start_raise_with_positions(): +def test_non_finite_likelihood_contributions_at_start_raise_with_full_output(): @mark.likelihood def fun(x): - out = np.ones(20) * (x @ x) - out[[3, 7]] = np.nan + out = np.ones(2_000) * (x @ x) + out[1_500] = np.nan return out - with pytest.raises( - InvalidFunctionError, match=r"2 of 20 .* positions are \[3, 7\]" - ): + with pytest.raises(InvalidFunctionError, match="not finite") as e: minimize(fun, params=np.ones(2), algorithm="scipy_lbfgsb") + assert "nan" in str(e.value) + assert "..." not in str(e.value) + + +def test_non_finite_pytree_residuals_at_start_raise_with_full_output(): + @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") + assert "'b':" in str(e.value) + assert "c inf" in str(e.value) def test_non_finite_residuals_at_start_raise_for_derivative_free_algorithm(): @@ -98,3 +109,25 @@ def fun(x): with pytest.raises(InvalidFunctionError, match="not finite"): minimize(fun, params=np.array([1.0, 2.0]), algorithm="scipy_neldermead") + + +@pytest.mark.parametrize("value", [np.inf, np.nan]) +def test_non_finite_jac_at_start_raises(value): + def jac(x): + return np.array([value, 2 * x[1]]) + + with pytest.raises(InvalidFunctionError, match="provided via jac is not finite"): + minimize(lambda x: x @ x, params=np.ones(2), algorithm="scipy_lbfgsb", jac=jac) + + +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", + ) + assert "'b': nan" in str(e.value) From ba1b962e98ca1826f84645847ba25045b10d4dfc Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Fri, 30 Oct 2026 09:14:22 +0100 Subject: [PATCH 3/9] Add changelog entry for #727 Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 4b1484e25..67989c460 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,9 @@ 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}`727` Raises an error if the objective function or a user provided derivative is + not finite at the start params. The message shows the complete output of the function + ({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`). From f1f85cb2792865590c852c943ad7d1b74686a7b8 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Sun, 1 Nov 2026 10:38:14 +0100 Subject: [PATCH 4/9] Simplify the start value check and only check derivatives that are used Check finiteness of the objective on its scalar aggregate instead of selecting the aggregation level by function type. Check user provided derivatives only for algorithms that need them, since others never use the derivative. Co-Authored-By: Claude Opus 5.5 --- src/optimagic/optimization/optimize.py | 32 +++++++------------ tests/optimagic/optimization/test_optimize.py | 19 +++++------ 2 files changed, 21 insertions(+), 30 deletions(-) diff --git a/src/optimagic/optimization/optimize.py b/src/optimagic/optimization/optimize.py index 7f32ec41d..7263561ea 100644 --- a/src/optimagic/optimization/optimize.py +++ b/src/optimagic/optimization/optimize.py @@ -38,12 +38,7 @@ create_optimization_problem, ) from optimagic.optimization.error_penalty import get_error_penalty_function -from optimagic.optimization.fun_value import ( - FunctionValue, - LeastSquaresFunctionValue, - LikelihoodFunctionValue, - SpecificFunctionValue, -) +from optimagic.optimization.fun_value import FunctionValue, SpecificFunctionValue from optimagic.optimization.internal_optimization_problem import ( InternalBounds, InternalOptimizationProblem, @@ -583,14 +578,15 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: add_soft_bounds=problem.multistart is not None, ) - derivative_evals = {} - if problem.jac is not None: - derivative_evals["jac"] = first_deriv_eval - if problem.fun_and_jac is not None: - derivative_evals["fun_and_jac"] = first_crit_and_deriv_eval[1] - _check_derivatives_are_finite_at_start( - derivative_evals, converter=converter, x=internal_params.values - ) + if problem.algorithm.algo_info.needs_jac: + derivative_evals = {} + if problem.jac is not None: + derivative_evals["jac"] = first_deriv_eval + if problem.fun_and_jac is not None: + derivative_evals["fun_and_jac"] = first_crit_and_deriv_eval[1] + _check_derivatives_are_finite_at_start( + derivative_evals, converter=converter, x=internal_params.values + ) # ================================================================================== # initialize the log database @@ -789,13 +785,7 @@ def _check_fun_is_finite_at_start(fun_eval: SpecificFunctionValue) -> None: ``error_handling="continue"`` is derived from the start value. """ - if isinstance(fun_eval, LeastSquaresFunctionValue): - level = AggregationLevel.LEAST_SQUARES - elif isinstance(fun_eval, LikelihoodFunctionValue): - level = AggregationLevel.LIKELIHOOD - else: - level = AggregationLevel.SCALAR - if not np.all(np.isfinite(fun_eval.internal_value(level))): + if not np.isfinite(fun_eval.internal_value(AggregationLevel.SCALAR)): msg = ( "The objective function is not finite (inf or nan) at the start params. " "Choose start params at which the objective function is finite. The " diff --git a/tests/optimagic/optimization/test_optimize.py b/tests/optimagic/optimization/test_optimize.py index f951bc087..90bc80d6a 100644 --- a/tests/optimagic/optimization/test_optimize.py +++ b/tests/optimagic/optimization/test_optimize.py @@ -102,15 +102,6 @@ def fun(x): assert "c inf" in str(e.value) -def test_non_finite_residuals_at_start_raise_for_derivative_free_algorithm(): - @mark.least_squares - def fun(x): - return np.array([x[0], np.inf if x[1] == 2 else x[1]]) - - with pytest.raises(InvalidFunctionError, match="not finite"): - minimize(fun, params=np.array([1.0, 2.0]), algorithm="scipy_neldermead") - - @pytest.mark.parametrize("value", [np.inf, np.nan]) def test_non_finite_jac_at_start_raises(value): def jac(x): @@ -120,6 +111,16 @@ def jac(x): 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_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} From 5452e2120f11cf13f816a9c5176bb10c1d5f6799 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Sun, 1 Nov 2026 10:53:38 +0100 Subject: [PATCH 5/9] Only evaluate user provided derivatives at the start params if they are used Algorithms that do not need derivatives never call jac or fun_and_jac, so the evaluation at the start params was wasted. Collect the derivative evaluations in one dict that feeds both the converter and the finiteness check. Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 5 +- src/optimagic/optimization/optimize.py | 59 ++++++++----------- tests/optimagic/optimization/test_optimize.py | 14 +++++ 3 files changed, 42 insertions(+), 36 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 67989c460..52ec4330e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -11,8 +11,9 @@ This release adds experimental support for **SciPy-style callbacks**, replaces p **optree** for pytree handling and uses **pydantic** to validate algorithm options. - {gh}`727` Raises an error if the objective function or a user provided derivative is - not finite at the start params. The message shows the complete output of the function - ({ghuser}`janosg`). + not finite at the start params. The message shows the complete output of the function. + User provided derivatives are only evaluated at the start params if the algorithm uses + them ({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/src/optimagic/optimization/optimize.py b/src/optimagic/optimization/optimize.py index 72c0ad20a..24f47ebfe 100644 --- a/src/optimagic/optimization/optimize.py +++ b/src/optimagic/optimization/optimize.py @@ -538,31 +538,28 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: first_crit_eval = problem.fun_eval _check_fun_is_finite_at_start(first_crit_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 + # 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: + 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) @@ -578,15 +575,9 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: add_soft_bounds=problem.multistart is not None, ) - if problem.algorithm.algo_info.needs_jac: - derivative_evals = {} - if problem.jac is not None: - derivative_evals["jac"] = first_deriv_eval - if problem.fun_and_jac is not None: - derivative_evals["fun_and_jac"] = first_crit_and_deriv_eval[1] - _check_derivatives_are_finite_at_start( - derivative_evals, converter=converter, x=internal_params.values - ) + _check_derivatives_are_finite_at_start( + derivative_evals, converter=converter, x=internal_params.values + ) # ================================================================================== # initialize the log database diff --git a/tests/optimagic/optimization/test_optimize.py b/tests/optimagic/optimization/test_optimize.py index 90bc80d6a..2c7c363bd 100644 --- a/tests/optimagic/optimization/test_optimize.py +++ b/tests/optimagic/optimization/test_optimize.py @@ -121,6 +121,20 @@ def jac(x): 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} From c843a18db24466841121d7cdb5388a7c3350f580 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Sun, 1 Nov 2026 11:05:05 +0100 Subject: [PATCH 6/9] Show the correct error message for non-finite numerical derivatives The condition `origin == "jac" or "fun_and_jac"` was always true, so a non-finite numerical derivative was reported as "the derivative provided via numerical". Co-Authored-By: Claude Opus 5.5 --- .../internal_optimization_problem.py | 2 +- .../test_invalid_jacobian_value.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/optimagic/optimization/internal_optimization_problem.py b/src/optimagic/optimization/internal_optimization_problem.py index f6d628739..be15b9860 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/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") From 57f7d9b6401f7e6fd16b9a63f7bb96adf047c142 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Sun, 15 Nov 2026 17:01:51 +0100 Subject: [PATCH 7/9] Update src/optimagic/optimization/internal_optimization_problem.py Co-authored-by: Hans-Martin von Gaudecker --- src/optimagic/optimization/internal_optimization_problem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/optimagic/optimization/internal_optimization_problem.py b/src/optimagic/optimization/internal_optimization_problem.py index be15b9860..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 in ("jac", "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." From 6c46fc4059b18dfb2c3b5ff117bd2581fc9a15a7 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Sun, 15 Nov 2026 17:50:49 +0100 Subject: [PATCH 8/9] Address review comments on the start params checks - List the paths of non-finite entries in the error messages and abbreviate large outputs instead of printing them in full. - Say in the error message and the docs that the start params have to be valid for global optimizers and multistart, too. - Evaluate fun_and_jac only once at the start params if fun is derived from it. - Add tests for maximize and for the changed exception type. Co-Authored-By: Claude Fable 5.2 --- CHANGES.md | 10 +- .../how_to_errors_during_optimization.ipynb | 38 ++- docs/source/how_to/how_to_multistart.ipynb | 6 +- .../create_optimization_problem.py | 37 ++- src/optimagic/optimization/optimize.py | 136 ++++++++-- src/optimagic/optimization/scipy_aliases.py | 38 ++- tests/optimagic/optimization/test_optimize.py | 254 +++++++++++++++++- 7 files changed, 461 insertions(+), 58 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index d9d4ef899..6c290c451 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -14,10 +14,12 @@ 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 error if the objective function or a user provided derivative is - not finite at the start params. The message shows the complete output of the function. - User provided derivatives are only evaluated at the start params if the algorithm uses - them ({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}`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..da5c92665 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,7 @@ 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 # ================================================================================== # Handle scipy arguments that are not yet implemented @@ -368,7 +380,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 +494,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 +594,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/optimize.py b/src/optimagic/optimization/optimize.py index 24f47ebfe..1e82b6fe6 100644 --- a/src/optimagic/optimization/optimize.py +++ b/src/optimagic/optimization/optimize.py @@ -14,7 +14,6 @@ from __future__ import annotations -import sys from pathlib import Path from typing import Any, Callable, Literal, Sequence, Type, cast @@ -65,6 +64,7 @@ ) 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, @@ -72,6 +72,7 @@ ErrorHandlingLiteral, NonNegativeFloat, PyTree, + PyTreeNamespace, ) FunType = Callable[..., float | PyTree | FunctionValue] @@ -85,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 @@ -151,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 @@ -362,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 @@ -551,13 +560,22 @@ def _optimize(problem: OptimizationProblem) -> OptimizeResult: raise InvalidFunctionError(msg) from e if problem.fun_and_jac is not None: - 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 + 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")) @@ -777,10 +795,19 @@ def _check_fun_is_finite_at_start(fun_eval: SpecificFunctionValue) -> None: """ 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. The " - f"objective function returned:\n\n{_format_in_full(fun_eval.value)}" + "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) @@ -792,29 +819,100 @@ def _check_derivatives_are_finite_at_start( ) -> 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. + 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. {name} returned the following derivative:" - f"\n\n{_format_in_full(derivative_eval)}" + 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 _format_in_full(value: PyTree) -> str: - """Represent a pytree without truncating numpy arrays or pandas objects.""" +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=sys.maxsize), - pd.option_context("display.max_rows", None, "display.max_columns", None), + 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_optimize.py b/tests/optimagic/optimization/test_optimize.py index 2c7c363bd..476035802 100644 --- a/tests/optimagic/optimization/test_optimize.py +++ b/tests/optimagic/optimization/test_optimize.py @@ -5,10 +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(): @@ -69,45 +78,158 @@ def test_fun_and_jac_sequence_without_fun(container): ) +# ====================================================================================== +# 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"): + 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) -def test_non_finite_likelihood_contributions_at_start_raise_with_full_output(): +@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(2_000) * (x @ x) - out[1_500] = np.nan + 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") - assert "nan" in str(e.value) - assert "..." not in str(e.value) + 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_full_output(): +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") - assert "'b':" in str(e.value) - assert "c inf" in str(e.value) + 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([value, 2 * x[1]]) + 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(InvalidFunctionError, match="provided via jac is not finite"): + with pytest.raises(UserFunctionRuntimeError, match="infinite or NaN values"): minimize(lambda x: x @ x, params=np.ones(2), algorithm="scipy_lbfgsb", jac=jac) @@ -145,4 +267,108 @@ def fun_and_jac(x): params={"a": 1.0, "b": 2.0}, algorithm="scipy_lbfgsb", ) - assert "'b': nan" in str(e.value) + 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 does not get them. + def fun_and_jac(x, factor=np.nan): + return x @ x, 2 * x * factor + + res = minimize( + fun_and_jac=fun_and_jac, + fun_and_jac_kwargs={"factor": 1.0}, + params=np.ones(2), + algorithm="scipy_lbfgsb", + ) + aaae(res.params, np.zeros(2)) + + +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)) From f9f0aa1e4e2869dff892225b1c16fc1083b309bb Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Sun, 15 Nov 2026 18:06:50 +0100 Subject: [PATCH 9/9] Share kwargs between fun and fun_and_jac if fun is derived from fun_and_jac If only fun_and_jac was provided or jac=True, keyword arguments had to be passed via fun_kwargs and fun_and_jac_kwargs. Providing just one of them failed, or silently used default values for the other function. Co-Authored-By: Claude Fable 5.2 --- CHANGES.md | 4 + .../create_optimization_problem.py | 8 ++ tests/optimagic/optimization/test_optimize.py | 74 ++++++++++++++++++- 3 files changed, 84 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 6c290c451..83738e88b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -20,6 +20,10 @@ This release adds experimental support for **SciPy-style callbacks**, replaces p - {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/src/optimagic/optimization/create_optimization_problem.py b/src/optimagic/optimization/create_optimization_problem.py index da5c92665..708a357fe 100644 --- a/src/optimagic/optimization/create_optimization_problem.py +++ b/src/optimagic/optimization/create_optimization_problem.py @@ -297,6 +297,14 @@ def create_optimization_problem( 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 # ================================================================================== diff --git a/tests/optimagic/optimization/test_optimize.py b/tests/optimagic/optimization/test_optimize.py index 476035802..d028245b5 100644 --- a/tests/optimagic/optimization/test_optimize.py +++ b/tests/optimagic/optimization/test_optimize.py @@ -349,12 +349,13 @@ def test_fun_and_jac_is_evaluated_once_at_start_if_fun_is_provided(): 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 does not get them. - def fun_and_jac(x, factor=np.nan): + # 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", @@ -362,6 +363,75 @@ def fun_and_jac(x, factor=np.nan): 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):