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
8 changes: 8 additions & 0 deletions src/optimagic/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,7 @@ class BoundedGradientFreeLocalScalarAlgorithms(AlgoSelection):
nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
scipy_neldermead: Type[ScipyNelderMead] = ScipyNelderMead
scipy_powell: Type[ScipyPowell] = ScipyPowell
Expand Down Expand Up @@ -1397,6 +1398,7 @@ class BoundedGradientFreeLocalAlgorithms(AlgoSelection):
nlopt_cobyla: Type[NloptCOBYLA] = NloptCOBYLA
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
pounders: Type[Pounders] = Pounders
scipy_neldermead: Type[ScipyNelderMead] = ScipyNelderMead
Expand Down Expand Up @@ -1570,6 +1572,7 @@ class BoundedGradientFreeScalarAlgorithms(AlgoSelection):
nlopt_isres: Type[NloptISRES] = NloptISRES
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
pygad: Type[Pygad] = Pygad
pygmo_bee_colony: Type[PygmoBeeColony] = PygmoBeeColony
Expand Down Expand Up @@ -2061,6 +2064,7 @@ class BoundedLocalScalarAlgorithms(AlgoSelection):
nlopt_mma: Type[NloptMMA] = NloptMMA
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_slsqp: Type[NloptSLSQP] = NloptSLSQP
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
nlopt_tnewton: Type[NloptTNewton] = NloptTNewton
Expand Down Expand Up @@ -2672,6 +2676,7 @@ class BoundedGradientFreeAlgorithms(AlgoSelection):
nlopt_isres: Type[NloptISRES] = NloptISRES
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
pounders: Type[Pounders] = Pounders
pygad: Type[Pygad] = Pygad
Expand Down Expand Up @@ -3190,6 +3195,7 @@ class BoundedLocalAlgorithms(AlgoSelection):
nlopt_mma: Type[NloptMMA] = NloptMMA
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_slsqp: Type[NloptSLSQP] = NloptSLSQP
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
nlopt_tnewton: Type[NloptTNewton] = NloptTNewton
Expand Down Expand Up @@ -3457,6 +3463,7 @@ class BoundedScalarAlgorithms(AlgoSelection):
nlopt_mma: Type[NloptMMA] = NloptMMA
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_slsqp: Type[NloptSLSQP] = NloptSLSQP
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
nlopt_tnewton: Type[NloptTNewton] = NloptTNewton
Expand Down Expand Up @@ -4104,6 +4111,7 @@ class BoundedAlgorithms(AlgoSelection):
nlopt_mma: Type[NloptMMA] = NloptMMA
nlopt_newuoa: Type[NloptNEWUOA] = NloptNEWUOA
nlopt_neldermead: Type[NloptNelderMead] = NloptNelderMead
nlopt_praxis: Type[NloptPRAXIS] = NloptPRAXIS
nlopt_slsqp: Type[NloptSLSQP] = NloptSLSQP
nlopt_sbplx: Type[NloptSbplx] = NloptSbplx
nlopt_tnewton: Type[NloptTNewton] = NloptTNewton
Expand Down
41 changes: 16 additions & 25 deletions src/optimagic/optimizers/nlopt_optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,8 @@ def _solve_internal_problem(
needs_hess=False,
needs_bounds=False,
supports_parallelism=False,
supports_bounds=False,
supports_infinite_bounds=False,
supports_bounds=True,
supports_infinite_bounds=True,
supports_linear_constraints=False,
supports_nonlinear_constraints=False,
disable_history=False,
Expand Down Expand Up @@ -287,12 +287,6 @@ class NloptPRAXIS(Algorithm):
algorithms with native bound support such as ``nlopt_bobyqa`` and
``nlopt_cobyla``.

.. warning::
optimagic marks this algorithm as not supporting bounds because the NLopt
implementation failed on a simple benchmark function with finite parameter
bounds. Bounds passed to ``minimize`` are nevertheless forwarded to NLopt,
which enforces them via the variable transformation.

"""

convergence_xtol_rel: NonNegativeFloat = CONVERGENCE_XTOL_REL
Expand Down Expand Up @@ -622,14 +616,9 @@ class NloptNEWUOA(Algorithm):
The version in NLopt :cite:`Johnson2007` has been extended to support bound
constraints via the ``LN_NEWUOA_BOUND`` variant, which solves the trust-region
subproblems with the MMA algorithm and truncates some steps to the bounds; this
may slow down convergence. optimagic uses ``LN_NEWUOA_BOUND`` only if at least
one finite lower bound and at least one finite upper bound are specified;
otherwise, it uses the original ``LN_NEWUOA`` algorithm for unconstrained
optimization, which ignores bounds.

.. warning::
With one-sided bounds (e.g. only lower bounds), the bounds are therefore
ignored and the solution can violate them.
may slow down convergence. optimagic uses ``LN_NEWUOA_BOUND`` if at least one
finite bound is specified; otherwise, it uses the original ``LN_NEWUOA``
algorithm for unconstrained optimization.

.. note::
NEWUOA requires the dimension n of the parameter space to be at least 2,
Expand Down Expand Up @@ -691,14 +680,11 @@ class NloptNEWUOA(Algorithm):
def _solve_internal_problem(
self, problem: InternalOptimizationProblem, x0: NDArray[np.float64]
) -> InternalOptimizeResult:
if problem.bounds.lower is None or problem.bounds.upper is None:
algo = nlopt.LN_NEWUOA
elif np.any(np.isfinite(problem.bounds.lower)) or np.any(
np.isfinite(problem.bounds.upper)
):
algo = nlopt.LN_NEWUOA_BOUND
else:
algo = nlopt.LN_NEWUOA
has_finite_bounds = any(
b is not None and np.isfinite(b).any()
for b in (problem.bounds.lower, problem.bounds.upper)
)
algo = nlopt.LN_NEWUOA_BOUND if has_finite_bounds else nlopt.LN_NEWUOA
res = _minimize_nlopt(
problem=problem,
x0=x0,
Expand Down Expand Up @@ -1487,7 +1473,7 @@ class NloptDirect(Algorithm):
halve next in the case of near-ties. It is only available for the locally
biased version of the algorithm, i.e. this option requires
``locally_biased=True``; setting it to True with ``locally_biased=False`` raises
an error.
a ValueError.

"""

Expand Down Expand Up @@ -1517,6 +1503,11 @@ class NloptDirect(Algorithm):
def _solve_internal_problem(
self, problem: InternalOptimizationProblem, x0: NDArray[np.float64]
) -> InternalOptimizeResult:
if self.random_search and not self.locally_biased:
raise ValueError(
"random_search=True requires locally_biased=True because NLopt only "
"has randomized variants of the locally biased DIRECT algorithm."
)
if (
not self.locally_biased
and not self.random_search
Expand Down
2 changes: 1 addition & 1 deletion tests/estimagic/test_estimate_ml.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def multivariate_normal_example():

# simulate 10.000 random samples
mn = multivariate_normal(mean=true_mean, cov=true_cov)
data = mn.rvs(size=10_000)
data = mn.rvs(size=10_000, random_state=np.random.default_rng(12345))

loglike_kwargs = {"data": data}

Expand Down
39 changes: 39 additions & 0 deletions tests/optimagic/optimizers/test_nlopt_optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pytest
from numpy.testing import assert_allclose

import optimagic as om
from optimagic import mark
from optimagic.config import IS_NLOPT_INSTALLED
from optimagic.exceptions import InvalidAlgoOptionError
Expand Down Expand Up @@ -93,3 +94,41 @@ def test_seed_limits_are_valid(seed):
def test_seed_outside_portable_range_is_rejected(seed):
with pytest.raises(InvalidAlgoOptionError):
NloptESCH(seed=seed)


ONE_SIDED_BOUNDS_CASES = [
# start params, bounds, solution of min (x - 3) @ (x - 3) subject to bounds
(np.zeros(2), Bounds(upper=np.full(2, 1.0)), np.array([1.0, 1.0])),
(np.full(2, 5.0), Bounds(lower=np.full(2, 4.0)), np.array([4.0, 4.0])),
(
np.zeros(2),
Bounds(lower=np.array([-1.0, -np.inf]), upper=np.array([1.0, np.inf])),
np.array([1.0, 3.0]),
),
]


@pytest.mark.parametrize("algorithm", ["nlopt_newuoa", "nlopt_praxis"])
@pytest.mark.parametrize(("params", "bounds", "expected"), ONE_SIDED_BOUNDS_CASES)
def test_one_sided_bounds_are_respected(algorithm, params, bounds, expected):
res = minimize(
fun=lambda x: (x - 3) @ (x - 3),
params=params,
algorithm=algorithm,
bounds=bounds,
)
assert_allclose(res.params, expected, atol=1e-4)


def test_praxis_is_marked_as_supporting_bounds():
assert "nlopt_praxis" in om.algos.Bounded.AllNames


def test_direct_random_search_without_locally_biased_raises():
with pytest.raises(ValueError, match="requires locally_biased=True"):
minimize(
fun=lambda x: x @ x,
params=np.array([0.5, 0.5]),
algorithm=om.algos.nlopt_direct(random_search=True),
bounds=Bounds(lower=np.full(2, -1.0), upper=np.full(2, 1.0)),
)
Loading