Skip to content

Commit

Permalink
raise error if first element returns inf in _minimize_local_discrete
Browse files Browse the repository at this point in the history
  • Loading branch information
veni-vidi-vici-dormivi committed Feb 6, 2025
1 parent 681fa61 commit fa715e8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
10 changes: 8 additions & 2 deletions mesmer/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,13 @@ def _minimize_local_discrete(func: Callable, sequence: Iterable, **kwargs):
Raises
------
ValueError : if `func` returns negative infinity for any input.
ValueError : if `func` returns negative infinity for any input or first element is `inf`.
Notes
-----
- The function determines the local minimum, i.e., the loop is aborted if
`func(sequence[i-1]) >= func(sequence[i])`.
- If func returns `inf` for any input, the function will return the previous element.
"""

current_min = float("inf")
Expand All @@ -73,9 +74,14 @@ def _minimize_local_discrete(func: Callable, sequence: Iterable, **kwargs):
sel = i - 1
if sel == 0:
warnings.warn("First element is local minimum.", OptimizeWarning)
elif sel == -1:
raise ValueError("First element is `inf`, aborting.")

return sequence[sel]

warnings.warn("No local minimum found, returning the last element", OptimizeWarning)
warnings.warn(
"No local minimum found, returning the last element", OptimizeWarning
)

return element

Expand Down
12 changes: 9 additions & 3 deletions tests/unit/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,18 @@ def func(i, data_dict):
assert result == 1


def test_minimize_local_discrete_error():
def func(i):
def test_minimize_local_discrete_errors():
def func_minf(i):
return float("-inf")

with pytest.raises(ValueError, match=r"`fun` returned `\-inf`"):
mesmer.core.utils._minimize_local_discrete(func, [0])
mesmer.core.utils._minimize_local_discrete(func_minf, [0])

def func_inf(i):
return float("inf")

with pytest.raises(ValueError, match=r"First element is `inf`, aborting."):
mesmer.core.utils._minimize_local_discrete(func_inf, [0])


@pytest.mark.parametrize("obj", (None, xr.DataArray()))
Expand Down

0 comments on commit fa715e8

Please sign in to comment.