Skip to content
Open
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
33 changes: 12 additions & 21 deletions bioptim/interfaces/acados_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from ..limits.objective_functions import ObjectiveFunction, ObjectiveFcn
from ..limits.path_conditions import Bounds
from ..misc.enums import InterpolationType
from ..optimization.bound_vector import _dispatch_control_bounds


from ..misc.parameters_types import (
Expand Down Expand Up @@ -368,16 +369,11 @@ def __set_constraints(self, ocp) -> None:
self.x_bound_min[index, i] = x_tp.min[:, i]

# setup control constraints
u_bounds_max = np.ndarray((self.acados_ocp.dims.nu, 1))
u_bounds_min = np.ndarray((self.acados_ocp.dims.nu, 1))
for key in ocp.nlp[0].controls.keys():
u_tp = ocp.nlp[0].u_bounds[key].scale(ocp.nlp[0].u_scaling[key].scaling)
index = ocp.nlp[0].controls[key].index
u_bounds_max[index, 0] = np.array(u_tp.max[:, 0])
u_bounds_min[index, 0] = np.array(u_tp.min[:, 0])

self.acados_ocp.constraints.lbu = u_bounds_max
self.acados_ocp.constraints.ubu = u_bounds_min
u_bounds_min, u_bounds_max = _dispatch_control_bounds(
ocp.nlp[0], ocp.nlp[0].controls, ocp.nlp[0].u_bounds, ocp.nlp[0].u_scaling
)
self.acados_ocp.constraints.lbu = u_bounds_min[0]
self.acados_ocp.constraints.ubu = u_bounds_max[0]
self.acados_ocp.constraints.idxbu = np.array(range(self.acados_ocp.dims.nu))
self.acados_ocp.dims.nbu = self.acados_ocp.dims.nu

Expand Down Expand Up @@ -761,6 +757,10 @@ def __update_solver(self):
scale_init = self.ocp.parameter_init[key].scale(self.ocp.parameters[key].scaling.scaling)
param_init = np.concatenate((param_init, scale_init.init[:, 0]))

u_bounds_min, u_bounds_max = _dispatch_control_bounds(
self.ocp.nlp[0], self.ocp.nlp[0].controls, self.ocp.nlp[0].u_bounds, self.ocp.nlp[0].u_scaling
)

for n in range(self.acados_ocp.solver_options.N_horizon):
if n == 0:
# Initial node
Expand Down Expand Up @@ -807,17 +807,8 @@ def __update_solver(self):

self.ocp_solver.set(n, "u", u_init)

# The u_bounds need to be ordered by index that's why we use a for loop
u_bounds_max = np.ndarray(self.acados_ocp.dims.nu)
u_bounds_min = np.ndarray(self.acados_ocp.dims.nu)
for key in self.ocp.nlp[0].controls.keys():
u_tp = self.ocp.nlp[0].u_bounds[key]
index = self.ocp.nlp[0].controls[key].index
u_bounds_max[index] = np.array(u_tp.max[:, 0])
u_bounds_min[index] = np.array(u_tp.min[:, 0])

self.ocp_solver.constraints_set(n, "lbu", u_bounds_min)
self.ocp_solver.constraints_set(n, "ubu", u_bounds_max)
self.ocp_solver.constraints_set(n, "lbu", u_bounds_min[n][:, 0])
self.ocp_solver.constraints_set(n, "ubu", u_bounds_max[n][:, 0])
self.ocp_solver.constraints_set(n, "uh", self.all_g_bounds.max[:, 0])
self.ocp_solver.constraints_set(n, "lh", self.all_g_bounds.min[:, 0])

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
40 changes: 39 additions & 1 deletion tests/shard6/test_bounds_accessor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import numpy as np
import numpy.testing as npt
from bioptim import BoundsList, InterpolationType
from bioptim import BoundsList, InterpolationType, VariableScalingList
from bioptim.examples.toy_examples.torque_driven_ocp import torque_activation_driven
from bioptim.optimization.bound_vector import _dispatch_control_bounds
from tests.utils import TestUtils


def test_accessors_on_bounds_option():
Expand Down Expand Up @@ -40,3 +43,38 @@ def test_accessors_on_bounds_option_multidimensional():
x_bounds["my_key"].max[:],
np.array([[0, 150, 200], [0, 10, 10], [0, 10, 10], [100, 10, 10], [100, 10, 10], [100, 150, 200]]),
)


def test_dispatch_control_bounds_keeps_scaled_bounds_in_solver_order():
ocp = torque_activation_driven.prepare_ocp(
biorbd_model_path=TestUtils.bioptim_folder() + "/examples/models/2segments_2dof_2contacts.bioMod",
n_shooting=2,
final_time=1,
expand_dynamics=False,
)
nlp = ocp.nlp[0]

u_bounds = BoundsList()
u_bounds.add(
"residual_tau",
min_bound=[20.0, -60.0],
max_bound=[60.0, 100.0],
interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,
)
u_bounds.add(
"tau",
min_bound=[-10.0, -30.0],
max_bound=[10.0, 50.0],
interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT,
)
u_scaling = VariableScalingList()
u_scaling.add("residual_tau", scaling=[10.0, 20.0])
u_scaling.add("tau", scaling=[2.0, 10.0])

lower, upper = _dispatch_control_bounds(nlp, nlp.controls, u_bounds, u_scaling)

assert len(lower) == nlp.n_controls_nodes
assert len(upper) == nlp.n_controls_nodes
for node_lower, node_upper in zip(lower, upper):
npt.assert_allclose(node_lower[:, 0], [-5.0, -3.0, 2.0, -3.0])
npt.assert_allclose(node_upper[:, 0], [5.0, 5.0, 6.0, 5.0])
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
Loading