Skip to content
Draft
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
4 changes: 2 additions & 2 deletions bioptim/gui/check_conditioning.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def create_conditioning_plots(ocp):
objectives_hess_func = hessian_objective(variables_vector, all_objectives)

# PLOT CONSTRAINTS
fig_constraints, axis_constraints = plt.subplots(1, 2, num="Check conditioning for constraints")
fig_constraints, axis_constraints = plt.subplots(1, 2, num="Check conditioning for constraints", clear=True)

# Jacobian plot
fake_jacobian = np.zeros((nb_constraints, nb_variables))
Expand Down Expand Up @@ -161,7 +161,7 @@ def create_conditioning_plots(ocp):
pass

# PLOT OBJECTIVES
fig_obj, axis_obj = plt.subplots(1, 1, num="Check conditioning for objectives")
fig_obj, axis_obj = plt.subplots(1, 1, num="Check conditioning for objectives", clear=True)

# Hessian objective plot
fake_hessian_obj = np.zeros((nb_variables, nb_variables))
Expand Down
2 changes: 1 addition & 1 deletion bioptim/gui/ipopt_output_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def create_ipopt_output_plot(ocp, interface):
"""
This function creates the plots for the ipopt output: f, g, inf_pr, inf_du.
"""
ipopt_fig, axs = plt.subplots(3, 1, num="IPOPT output")
ipopt_fig, axs = plt.subplots(3, 1, num="IPOPT output", clear=True)
axs[0].set_ylabel("f", fontweight="bold")
axs[1].set_ylabel("inf_pr", fontweight="bold")
axs[2].set_ylabel("inf_du", fontweight="bold")
Expand Down
26 changes: 12 additions & 14 deletions bioptim/optimization/receding_horizon_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,21 +699,20 @@ def advance_window_initial_guess_states(self, sol: Solution, **advance_options)
self.nlp[0].x_init[key].check_and_adjust_dimensions(
self.nlp[0].states[key].shape, self.nlp[0].ns * self.nb_intermediate_frames
)
else:
initial_guess_frames = []
for _ in range(self.n_cycles):
initial_guess_frames.extend(
list(
range(
self.n_cycles_to_advance * self.cycle_len * self.nb_intermediate_frames,
(self.n_cycles_to_advance + 1) * self.cycle_len * self.nb_intermediate_frames,
)
initial_guess_frames = []
for _ in range(self.n_cycles):
initial_guess_frames.extend(
list(
range(
self.n_cycles_to_advance * self.cycle_len * self.nb_intermediate_frames,
(self.n_cycles_to_advance + 1) * self.cycle_len * self.nb_intermediate_frames,
)
)
initial_guess_frames.append(
(self.n_cycles_to_advance + 1) * self.cycle_len * self.nb_intermediate_frames
)
self.nlp[0].x_init[key].init[:, :] = states[key][:, initial_guess_frames]
initial_guess_frames.append(
(self.n_cycles_to_advance + 1) * self.cycle_len * self.nb_intermediate_frames
)
self.nlp[0].x_init[key].init[:, :] = states[key][:, initial_guess_frames]
else:
if self.nlp[0].x_init[key].type != InterpolationType.EACH_FRAME:
self.nlp[0].x_init.add(
Expand All @@ -723,8 +722,7 @@ def advance_window_initial_guess_states(self, sol: Solution, **advance_options)
phase=0,
)
self.nlp[0].x_init[key].check_and_adjust_dimensions(self.nlp[0].states[key].shape, self.nlp[0].ns)
else:
self.nlp[0].x_init[key].init[:, :] = states[key][:, self.initial_guess_frames]
self.nlp[0].x_init[key].init[:, :] = states[key][:, self.initial_guess_frames]

def advance_window_initial_guess_controls(self, sol: Solution, **advance_options) -> None:
controls = sol.decision_controls(to_merge=SolutionMerge.NODES)
Expand Down
71 changes: 69 additions & 2 deletions tests/shard1/test_global_nmpc_final.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,82 @@
"""

import platform

from bioptim import Solver, MultiCyclicCycleSolutions, PhaseDynamics, SolutionMerge, OdeSolver
from types import SimpleNamespace

from bioptim import (
Solver,
MultiCyclicCycleSolutions,
PhaseDynamics,
SolutionMerge,
OdeSolver,
InitialGuessList,
InterpolationType,
)
import bioptim.optimization.receding_horizon_optimization as rho_module
from bioptim.optimization.receding_horizon_optimization import MultiCyclicRecedingHorizonOptimization
import numpy as np
import numpy.testing as npt
import pytest

from ..utils import TestUtils


@pytest.mark.parametrize("already_converted", [False, True])
@pytest.mark.parametrize(
"ode_solver",
[OdeSolver.RK4(), OdeSolver.COLLOCATION(polynomial_degree=3, method="radau")],
)
def test_multi_cyclic_state_guess_first_and_following_windows(ode_solver, already_converted, monkeypatch):
is_collocation = isinstance(ode_solver, OdeSolver.COLLOCATION)
intermediate_frames = ode_solver.polynomial_degree + 1 if is_collocation else 1
interpolation = InterpolationType.ALL_POINTS if is_collocation else InterpolationType.EACH_FRAME
n_frames = 6 * intermediate_frames + 1
x_init = InitialGuessList()
dimensions = {"q": 2, "qdot": 1}
for key, size in dimensions.items():
x_init.add(
key,
np.zeros((size, n_frames if already_converted else 1)),
interpolation=interpolation if already_converted else InterpolationType.CONSTANT,
phase=0,
)

nmpc = MultiCyclicRecedingHorizonOptimization.__new__(MultiCyclicRecedingHorizonOptimization)
nmpc.nlp = [
SimpleNamespace(
x_init=x_init,
dynamics_type=SimpleNamespace(ode_solver=ode_solver),
ns=6,
states={key: SimpleNamespace(shape=size) for key, size in dimensions.items()},
)
]
nmpc.cycle_len = 3
nmpc.n_cycles = 2
nmpc.n_cycles_to_advance = 1
nmpc.nb_intermediate_frames = intermediate_frames
nmpc.initial_guess_frames = [3, 4, 5, 3, 4, 5, 6]

# An unwritten allocation must fail independently of the allocator's previous contents.
monkeypatch.setattr(rho_module, "np", SimpleNamespace(ndarray=lambda shape: np.full(shape, np.nan)))
expected_frames = np.concatenate(
(np.tile(np.arange(3 * intermediate_frames, 6 * intermediate_frames), 2), [6 * intermediate_frames])
)
for window in range(2):
states = {
key: np.arange(size * n_frames).reshape(size, n_frames) + 1000 * (window + 1)
for key, size in dimensions.items()
}

def decision_states(to_merge):
assert to_merge == SolutionMerge.NODES
return states

nmpc.advance_window_initial_guess_states(SimpleNamespace(decision_states=decision_states))
for key in dimensions:
assert x_init[key].type == interpolation
npt.assert_array_equal(x_init[key].init, states[key][:, expected_frames])


@pytest.mark.parametrize("phase_dynamics", [PhaseDynamics.SHARED_DURING_THE_PHASE, PhaseDynamics.ONE_PER_NODE])
@pytest.mark.parametrize(
"ode_solver",
Expand Down
13 changes: 13 additions & 0 deletions tests/shard2/test_global_getting_started.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,19 @@ def test_parameter_optimization(ode_solver, phase_dynamics):
# gravity parameter
npt.assert_almost_equal(gravity, np.array([0, 5.19787253e-03, -9.84722491e00]))

elif isinstance(ode_solver, OdeSolver.COLLOCATION) and phase_dynamics == PhaseDynamics.SHARED_DURING_THE_PHASE:
npt.assert_equal(g.shape, (400, 1))
npt.assert_almost_equal(g, np.zeros((400, 1)), decimal=6)

TestUtils.assert_objective_value(sol=sol, expected_value=99.67117614751174, decimal=6)

# initial and final controls
npt.assert_almost_equal(tau[:, 0], np.array((9.5552488, 0.0)))
npt.assert_almost_equal(tau[:, -1], np.array((-24.212346, 0.0)))

# gravity parameter
npt.assert_almost_equal(gravity, np.array([0, 7.0281362e-03, -1.0000000e01]))

else:
npt.assert_equal(g.shape, (400, 1))
npt.assert_almost_equal(g, np.zeros((400, 1)), decimal=6)
Expand Down
2 changes: 2 additions & 0 deletions tests/shard4/test_variational_integrator_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def test_variational_pendulum(use_sx):

# --- Solve the ocp --- #
sol = ocp.solve(Solver.IPOPT())
TestUtils.assert_solver_success(sol, max_iterations=100)
states = sol.decision_states(to_merge=SolutionMerge.NODES)
controls = sol.decision_controls(to_merge=SolutionMerge.NODES)

Expand Down Expand Up @@ -64,6 +65,7 @@ def test_variational_pendulum_with_holonomic_constraints(use_sx):

# --- Solve the ocp --- #
sol = ocp.solve(Solver.IPOPT())
TestUtils.assert_solver_success(sol, max_iterations=100)
states = sol.decision_states(to_merge=SolutionMerge.NODES)
controls = sol.decision_controls(to_merge=SolutionMerge.NODES)

Expand Down
7 changes: 6 additions & 1 deletion tests/shard6/test_global_optimal_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
PhaseDynamics,
SolutionMerge,
DynamicsOptions,
Solver,
)
import numpy as np
import numpy.testing as npt
Expand Down Expand Up @@ -55,7 +56,11 @@ def test_pendulum_max_time_mayer_constrained(ode_solver, phase_dynamics):
expand_dynamics=ode_solver != OdeSolver.IRK,
control_type=control_type,
)
sol = ocp.solve()
solver = Solver.IPOPT()
if ode_solver == OdeSolver.COLLOCATION:
# Match IPOPT's convergence criterion to the unscaled defects checked below.
solver.set_nlp_scaling_method("none")
sol = ocp.solve(solver)

# Check constraints
g = np.array(sol.constraints)
Expand Down
12 changes: 12 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@


class TestUtils:
@staticmethod
def assert_solver_success(solution: Solution, max_iterations: int | None = None):
"""Assert convergence and optionally guard against a large iteration-count regression."""
assert (
solution.status == 0
), f"Solver did not converge (status={solution.status}, iterations={solution.iterations})"
assert isinstance(solution.iterations, int) and solution.iterations >= 0
if max_iterations is not None:
assert (
solution.iterations <= max_iterations
), f"Solver iteration regression: {solution.iterations} iterations, expected at most {max_iterations}"

@staticmethod
def bioptim_folder() -> str:
return TestUtils._capitalize_folder_drive(str(Path(__file__).parent / "../bioptim"))
Expand Down
Loading