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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
38 changes: 29 additions & 9 deletions docs/source/how_to/how_to_errors_during_optimization.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -42,7 +62,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "2",
"id": "3",
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -62,7 +82,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "3",
"id": "4",
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -84,7 +104,7 @@
},
{
"cell_type": "markdown",
"id": "4",
"id": "5",
"metadata": {},
"source": [
"### What would scipy do?"
Expand All @@ -93,7 +113,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "5",
"id": "6",
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -103,7 +123,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "6",
"id": "7",
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -113,7 +133,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "7",
"id": "8",
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -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",
Expand All @@ -133,7 +153,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "9",
"id": "10",
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -149,7 +169,7 @@
},
{
"cell_type": "markdown",
"id": "10",
"id": "11",
"metadata": {},
"source": [
"### How does the magic work\n",
Expand Down
6 changes: 5 additions & 1 deletion docs/source/how_to/how_to_multistart.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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`)."
]
},
{
Expand Down
45 changes: 44 additions & 1 deletion src/optimagic/optimization/create_optimization_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
# ==================================================================================
Expand Down Expand Up @@ -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,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
Loading
Loading