forked from pyomeca/bioptim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_multinode_objective.py
144 lines (123 loc) · 4.36 KB
/
example_multinode_objective.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
This example shows how to use multinode_objectives.
It replicates the results from getting_started/pendulum.py
"""
import platform
from casadi import MX, sum1
from bioptim import (
OptimalControlProgram,
DynamicsFcn,
Dynamics,
BoundsList,
PhaseDynamics,
OdeSolver,
OdeSolverBase,
Solver,
BiorbdModel,
PenaltyController,
MultinodeObjectiveList,
CostType,
)
def multinode_min_controls(controllers: list[PenaltyController]):
"""
This function mimics the ObjectiveFcn.MINIMIZE_CONTROLS with a multinode objective.
Note that it is better to use ObjectiveFcn.MINIMIZE_CONTROLS, here is juste a toy example.
"""
dt = controllers[0].dt.cx
out = 0
for i, ctrl in enumerate(controllers):
out += sum1(ctrl.controls["tau"].cx_start ** 2) * dt
return out
def prepare_ocp(
biorbd_model_path: str,
final_time: float,
n_shooting: int,
ode_solver: OdeSolverBase = OdeSolver.RK4(),
use_sx: bool = True,
n_threads: int = 1,
phase_dynamics: PhaseDynamics = PhaseDynamics.ONE_PER_NODE,
expand_dynamics: bool = True,
) -> OptimalControlProgram:
"""
The initialization of an ocp
Parameters
----------
biorbd_model_path: str
The path to the biorbd model
final_time: float
The time in second required to perform the task
n_shooting: int
The number of shooting points to define int the direct multiple shooting program
ode_solver: OdeSolverBase = OdeSolver.RK4()
Which type of OdeSolver to use
use_sx: bool
If the SX variable should be used instead of MX (can be extensive on RAM)
n_threads: int
Number of thread to use
phase_dynamics: PhaseDynamics
If the dynamics equation within a phase is unique or changes at each node.
PhaseDynamics.SHARED_DURING_THE_PHASE is much faster, but lacks the capability to have changing dynamics within
a phase. A good example of when PhaseDynamics.ONE_PER_NODE should be used is when different external forces
are applied at each node
expand_dynamics: bool
If the dynamics function should be expanded. Please note, this will solve the problem faster, but will slow down
the declaration of the OCP, so it is a trade-off. Also depending on the solver, it may or may not work
(for instance IRK is not compatible with expanded dynamics)
Returns
-------
The OptimalControlProgram ready to be solved
"""
bio_model = BiorbdModel(biorbd_model_path)
# Add objective functions
multinode_objectives = MultinodeObjectiveList()
multinode_objectives.add(
multinode_min_controls,
nodes_phase=[0 for _ in range(n_shooting)],
nodes=[i for i in range(n_shooting)],
weight=10,
quadratic=False,
expand=False,
)
# Dynamics
dynamics = Dynamics(DynamicsFcn.TORQUE_DRIVEN, expand_dynamics=expand_dynamics, phase_dynamics=phase_dynamics)
# Path constraint
x_bounds = BoundsList()
x_bounds["q"] = bio_model.bounds_from_ranges("q")
x_bounds["q"][:, [0, -1]] = 0
x_bounds["q"][1, -1] = 3.14
x_bounds["qdot"] = bio_model.bounds_from_ranges("qdot")
x_bounds["qdot"][:, [0, -1]] = 0
# Define control path constraint
n_tau = bio_model.nb_tau
tau_min, tau_max = -100, 100
u_bounds = BoundsList()
u_bounds["tau"] = [tau_min] * n_tau, [tau_max] * n_tau
u_bounds["tau"][1, :] = 0 # Prevent the model from actively rotate
return OptimalControlProgram(
bio_model,
dynamics,
n_shooting,
final_time,
x_bounds=x_bounds,
u_bounds=u_bounds,
multinode_objectives=multinode_objectives,
ode_solver=ode_solver,
use_sx=use_sx,
n_threads=n_threads, # This has to be set to 1 by definition.
)
def main():
"""
If pendulum is run as a script, it will perform the optimization and animates it
"""
# --- Prepare the ocp --- #
n_shooting = 30
ocp = prepare_ocp(biorbd_model_path="models/pendulum.bioMod", final_time=1, n_shooting=n_shooting)
ocp.add_plot_penalty(CostType.ALL)
# --- Solve the ocp --- #
sol = ocp.solve(Solver.IPOPT(show_online_optim=platform.system() == "Linux"))
# --- Show the results in a bioviz animation --- #
sol.animate(n_frames=100)
# sol.graphs()
# sol.print_cost()
if __name__ == "__main__":
main()