-
Notifications
You must be signed in to change notification settings - Fork 46
/
optimal_control_program.py
2070 lines (1810 loc) · 83.1 KB
/
optimal_control_program.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Callable, Any
import os
import sys
import pickle
from copy import deepcopy
from math import inf
import numpy as np
import biorbd_casadi as biorbd
import casadi
from casadi import MX, SX, Function, sum1, horzcat, vertcat
from matplotlib import pyplot as plt
from .optimization_vector import OptimizationVectorHelper
from .non_linear_program import NonLinearProgram as NLP
from ..dynamics.configure_problem import DynamicsList, Dynamics, ConfigureProblem
from ..dynamics.ode_solver import OdeSolver, OdeSolverBase
from ..gui.plot import CustomPlot, PlotOcp
from ..gui.graph import OcpToConsole, OcpToGraph
from ..interfaces.biomodel import BioModel
from ..interfaces.variational_biorbd_model import VariationalBiorbdModel
from ..interfaces.solver_options import Solver
from ..limits.constraints import (
ConstraintFunction,
ConstraintFcn,
ConstraintList,
Constraint,
ParameterConstraintList,
ParameterConstraint,
)
from ..limits.phase_transition import PhaseTransitionList, PhaseTransitionFcn
from ..limits.multinode_constraint import MultinodeConstraintList
from ..limits.multinode_objective import MultinodeObjectiveList
from ..limits.objective_functions import (
ObjectiveFcn,
ObjectiveList,
Objective,
ParameterObjectiveList,
ParameterObjective,
)
from ..limits.path_conditions import BoundsList, Bounds
from ..limits.path_conditions import InitialGuess, InitialGuessList
from ..limits.penalty import PenaltyOption
from ..limits.objective_functions import ObjectiveFunction
from ..misc.__version__ import __version__
from ..misc.enums import (
ControlType,
SolverType,
Shooting,
PlotType,
CostType,
SolutionIntegrator,
QuadratureRule,
InterpolationType,
PenaltyType,
Node,
PhaseDynamics,
)
from ..misc.mapping import BiMappingList, Mapping, BiMapping, NodeMappingList
from ..misc.options import OptionDict
from ..misc.utils import check_version
from ..optimization.parameters import ParameterList, Parameter
from ..optimization.solution import Solution
from ..optimization.variable_scaling import VariableScalingList
from ..gui.check_conditioning import check_conditioning
class OptimalControlProgram:
"""
The main class to define an ocp. This class prepares the full program and gives all
the needed interface to modify and solve the program
Attributes
----------
cx: [MX, SX]
The base type for the symbolic casadi variables
g: list
Constraints that are not phase dependent (mostly parameters and continuity constraints)
g_internal: list[list[Constraint]]
All the constraints internally defined by the OCP at each of the node of the phase
g_implicit: list[list[Constraint]]
All the implicit constraints defined by the OCP at each of the node of the phase
J: list
Objective values that are not phase dependent (mostly parameters)
nlp: NLP
All the phases of the ocp
n_phases: int | list | tuple
The number of phases of the ocp
n_threads: int
The number of thread to use if using multithreading
original_phase_time: list[float]
The time vector as sent by the user
original_values: dict
A copy of the ocp as it is after defining everything
phase_transitions: list[PhaseTransition]
The list of transition constraint between phases
ocp_solver: SolverInterface
A reference to the ocp solver
version: dict
The version of all the underlying software. This is important when loading a previous ocp
Methods
-------
update_objectives(self, new_objective_function: Objective | ObjectiveList)
The main user interface to add or modify objective functions in the ocp
update_objectives_target(self, target, phase=None, list_index=None)
Fast accessor to update the target of a specific objective function. To update target of global objective
(usually defined by parameters), one can pass 'phase=-1
update_constraints(self, new_constraint: Constraint | ConstraintList)
The main user interface to add or modify constraint in the ocp
update_parameters(self, new_parameters: Parameter | ParameterList)
The main user interface to add or modify parameters in the ocp
update_bounds(self, x_bounds: Bounds | BoundsList, u_bounds: Bounds | BoundsList)
The main user interface to add bounds in the ocp
update_initial_guess(
self,
x_init: InitialGuess | InitialGuessList,
u_init: InitialGuess | InitialGuessList,
param_init: InitialGuess | InitialGuessList,
)
The main user interface to add initial guesses in the ocp
add_plot(self, fig_name: str, update_function: Callable, phase: int = -1, **parameters: Any)
The main user interface to add a new plot to the ocp
prepare_plots(self, automatically_organize: bool, show_bounds: bool,
shooting_type: Shooting) -> PlotOCP
Create all the plots associated with the OCP
solve(self, solver: Solver, show_online_optim: bool, solver_options: dict) -> Solution
Call the solver to actually solve the ocp
save(self, sol: Solution, file_path: str, stand_alone: bool = False)
Save the ocp and solution structure to the hard drive. It automatically create the required
folder if it does not exists. Please note that biorbd is required to load back this structure.
@staticmethod
load(file_path: str) -> list
Reload a previous optimization (*.bo) saved using save
_define_time(self, phase_time: float | tuple, objective_functions: ObjectiveList, constraints: ConstraintList)
Declare the phase_time vector in v. If objective_functions or constraints defined a time optimization,
a sanity check is perform and the values of initial guess and bounds for these particular phases
__modify_penalty(self, new_penalty: PenaltyOption | Parameter)
The internal function to modify a penalty. It is also stored in the original_values, meaning that if one
overrides an objective only the latter is preserved when saved
__set_nlp_is_stochastic(self)
Set the nlp as stochastic if any of the phases is stochastic
__set_stochastic_internal_stochastic_variables(self)
Set the internal stochastic variables (s_init, s_bounds, s_scaling) if any of the phases is stochastic
_set_stochastic_variables_to_original_values(self, s_init, s_bounds, s_scaling)
Set the original_values with the stochastic variables (s_init, s_bounds, s_scaling) if any of the phases is
stochastic
_check_quaternions_hasattr(self, bio_model)
Check if the bio_model has quaternions and set the flag accordingly
_check_and_prepare_dynamics(self, dynamics)
Check if the dynamics is a Dynamics or a DynamicsList and set the flag accordingly
_set_original_values(
"""
def __init__(
self,
bio_model: list | tuple | BioModel,
dynamics: Dynamics | DynamicsList,
n_shooting: int | list | tuple,
phase_time: int | float | list | tuple,
x_bounds: BoundsList = None,
u_bounds: BoundsList = None,
x_init: InitialGuessList | None = None,
u_init: InitialGuessList | None = None,
objective_functions: Objective | ObjectiveList = None,
constraints: Constraint | ConstraintList = None,
parameters: ParameterList = None,
parameter_bounds: BoundsList = None,
parameter_init: InitialGuessList = None,
parameter_objectives: ParameterObjectiveList = None,
parameter_constraints: ParameterConstraintList = None,
ode_solver: list | OdeSolverBase | OdeSolver = None,
control_type: ControlType | list = ControlType.CONSTANT,
variable_mappings: BiMappingList = None,
time_phase_mapping: BiMapping = None,
node_mappings: NodeMappingList = None,
plot_mappings: Mapping = None,
phase_transitions: PhaseTransitionList = None,
multinode_constraints: MultinodeConstraintList = None,
multinode_objectives: MultinodeObjectiveList = None,
x_scaling: VariableScalingList = None,
xdot_scaling: VariableScalingList = None,
u_scaling: VariableScalingList = None,
n_threads: int = 1,
use_sx: bool = False,
integrated_value_functions: dict[str, Callable] = None,
):
"""
Parameters
----------
bio_model: list | tuple | BioModel
The bio_model to use for the optimization
dynamics: Dynamics | DynamicsList
The dynamics of the phases
n_shooting: int | list[int]
The number of shooting point of the phases
phase_time: int | float | list | tuple
The phase time of the phases
x_init: InitialGuess | InitialGuessList
The initial guesses for the states
u_init: InitialGuess | InitialGuessList
The initial guesses for the controls
x_bounds: Bounds | BoundsList
The bounds for the states
u_bounds: Bounds | BoundsList
The bounds for the controls
x_scaling: VariableScalingList
The scaling for the states at each phase, if only one is sent, then the scaling is copied over the phases
xdot_scaling: VariableScalingList
The scaling for the states derivative, if only one is sent, then the scaling is copied over the phases
u_scaling: VariableScalingList
The scaling for the controls, if only one is sent, then the scaling is copied over the phases
objective_functions: Objective | ObjectiveList
All the objective function of the program
constraints: Constraint | ConstraintList
All the constraints of the program
parameters: ParameterList
All the parameters to optimize of the program
parameter_bounds: BoundsList
The bounds for the parameters, default values are -inf to inf
parameter_init: InitialGuessList
The initial guess for the parameters, default value is 0
parameter_objectives: ParameterObjectiveList
All the parameter objectives to optimize of the program
parameter_constraints: ParameterConstraintList
All the parameter constraints of the program
ode_solver: OdeSolverBase
The solver for the ordinary differential equations
control_type: ControlType
The type of controls for each phase
variable_mappings: BiMappingList
The mapping to apply on variables
time_phase_mapping: BiMapping
The mapping of the time of the phases, so some phase share the same time variable (when optimized, that is
a constraint or an objective on the time is declared)
node_mappings: NodeMappingList
The mapping to apply between the variables associated with the nodes
plot_mappings: Mapping
The mapping to apply on the plots
phase_transitions: PhaseTransitionList
The transition types between the phases
n_threads: int
The number of thread to use while solving (multi-threading if > 1)
use_sx: bool
The nature of the casadi variables. MX are used if False.
"""
self._check_bioptim_version()
bio_model = self._initialize_model(bio_model)
# Placed here because of MHE
self._check_and_prepare_dynamics(dynamics)
self._set_original_values(
bio_model,
n_shooting,
phase_time,
x_init,
u_init,
x_bounds,
u_bounds,
x_scaling,
xdot_scaling,
u_scaling,
ode_solver,
control_type,
variable_mappings,
time_phase_mapping,
node_mappings,
plot_mappings,
phase_transitions,
multinode_constraints,
multinode_objectives,
parameter_bounds,
parameter_init,
parameter_constraints,
parameter_objectives,
n_threads,
use_sx,
integrated_value_functions,
)
s_init, s_bounds, s_scaling = self._set_stochastic_internal_stochastic_variables()
self._set_stochastic_variables_to_original_values(s_init, s_bounds, s_scaling)
self._check_and_set_threads(n_threads)
self._check_and_set_shooting_points(n_shooting)
self._check_and_set_phase_time(phase_time)
(
x_bounds,
x_init,
x_scaling,
u_bounds,
u_init,
u_scaling,
s_bounds,
s_init,
s_scaling,
xdot_scaling,
) = self._prepare_all_decision_variables(
x_bounds,
x_init,
x_scaling,
u_bounds,
u_init,
u_scaling,
xdot_scaling,
s_bounds,
s_init,
s_scaling,
)
(
constraints,
objective_functions,
parameter_constraints,
parameter_objectives,
multinode_constraints,
multinode_objectives,
phase_transitions,
parameter_bounds,
parameter_init,
) = self._check_arguments_and_build_nlp(
dynamics,
objective_functions,
constraints,
parameters,
phase_transitions,
multinode_constraints,
multinode_objectives,
parameter_bounds,
parameter_init,
parameter_constraints,
parameter_objectives,
ode_solver,
use_sx,
bio_model,
plot_mappings,
time_phase_mapping,
control_type,
variable_mappings,
integrated_value_functions,
)
# Do not copy singleton since x_scaling was already dealt with before
NLP.add(self, "x_scaling", x_scaling, True)
NLP.add(self, "xdot_scaling", xdot_scaling, True)
NLP.add(self, "u_scaling", u_scaling, True)
NLP.add(self, "s_scaling", s_scaling, True)
self._set_nlp_is_stochastic()
self._prepare_node_mapping(node_mappings)
self._prepare_dynamics()
self._prepare_bounds_and_init(
x_bounds, u_bounds, parameter_bounds, s_bounds, x_init, u_init, parameter_init, s_init
)
self._declare_multi_node_penalties(multinode_constraints, multinode_objectives, constraints, phase_transitions)
self._finalize_penalties(
constraints,
parameter_constraints,
objective_functions,
parameter_objectives,
phase_transitions,
)
def _check_bioptim_version(self):
self.version = {"casadi": casadi.__version__, "biorbd": biorbd.__version__, "bioptim": __version__}
return
def _initialize_model(self, bio_model):
"""
Initialize the bioptim model and check if the quaternions are used, if yes then setting them.
Setting the number of phases.
"""
if not isinstance(bio_model, (list, tuple)):
bio_model = [bio_model]
bio_model = self._check_quaternions_hasattr(bio_model)
self.n_phases = len(bio_model)
return bio_model
def _check_and_prepare_dynamics(self, dynamics):
if isinstance(dynamics, Dynamics):
dynamics_type_tp = DynamicsList()
dynamics_type_tp.add(dynamics)
self.dynamics = dynamics_type_tp
elif isinstance(dynamics, DynamicsList):
self.dynamics = dynamics
elif not isinstance(dynamics, DynamicsList):
raise RuntimeError("dynamics should be a Dynamics or a DynamicsList")
def _set_original_values(
self,
bio_model,
n_shooting,
phase_time,
x_init,
u_init,
x_bounds,
u_bounds,
x_scaling,
xdot_scaling,
u_scaling,
ode_solver,
control_type,
variable_mappings,
time_phase_mapping,
node_mappings,
plot_mappings,
phase_transitions,
multinode_constraints,
multinode_objectives,
parameter_bounds,
parameter_init,
parameter_constraints,
parameter_objectives,
n_threads,
use_sx,
integrated_value_functions,
):
self.original_values = {
"bio_model": [m.serialize() for m in bio_model],
"dynamics": self.dynamics,
"n_shooting": n_shooting,
"phase_time": phase_time,
"x_init": x_init,
"u_init": u_init,
"x_bounds": x_bounds,
"u_bounds": u_bounds,
"x_scaling": x_scaling,
"xdot_scaling": xdot_scaling,
"u_scaling": u_scaling,
"objective_functions": ObjectiveList(),
"constraints": ConstraintList(),
"parameters": ParameterList(),
"ode_solver": ode_solver,
"control_type": control_type,
"variable_mappings": variable_mappings,
"time_phase_mapping": time_phase_mapping,
"node_mappings": node_mappings,
"plot_mappings": plot_mappings,
"phase_transitions": phase_transitions,
"multinode_constraints": multinode_constraints,
"multinode_objectives": multinode_objectives,
"parameter_bounds": parameter_bounds,
"parameter_init": parameter_init,
"parameter_objectives": parameter_objectives,
"parameter_constraints": parameter_constraints,
"n_threads": n_threads,
"use_sx": use_sx,
"integrated_value_functions": integrated_value_functions,
}
return
def _check_and_set_threads(self, n_threads):
if not isinstance(n_threads, int) or isinstance(n_threads, bool) or n_threads < 1:
raise RuntimeError("n_threads should be a positive integer greater or equal than 1")
self.n_threads = n_threads
def _check_and_set_shooting_points(self, n_shooting):
if not isinstance(n_shooting, int) or n_shooting < 2:
if isinstance(n_shooting, (tuple, list)):
if sum([True for i in n_shooting if not isinstance(i, int) and not isinstance(i, bool)]) != 0:
raise RuntimeError("n_shooting should be a positive integer (or a list of) greater or equal than 2")
else:
raise RuntimeError("n_shooting should be a positive integer (or a list of) greater or equal than 2")
self.n_shooting = n_shooting
def _check_and_set_phase_time(self, phase_time):
if not isinstance(phase_time, (int, float)):
if isinstance(phase_time, (tuple, list)):
if sum([True for i in phase_time if not isinstance(i, (int, float))]) != 0:
raise RuntimeError("phase_time should be a number or a list of number")
else:
raise RuntimeError("phase_time should be a number or a list of number")
self.phase_time = phase_time
def _check_and_prepare_decision_variables(
self,
var_name: str,
bounds: BoundsList,
init: InitialGuessList,
scaling: VariableScalingList,
):
"""
This function checks if the decision variables are of the right type for initial guess and bounds.
It also prepares the scaling for the decision variables.
And set them in a dictionary for the phase.
"""
if bounds is None:
bounds = BoundsList()
elif not isinstance(bounds, BoundsList):
raise RuntimeError(f"{var_name}_bounds should be built from a BoundsList")
if init is None:
init = InitialGuessList()
elif not isinstance(init, InitialGuessList):
raise RuntimeError(f"{var_name}_init should be built from a InitialGuessList")
bounds = self._prepare_option_dict_for_phase(f"{var_name}_bounds", bounds, BoundsList)
init = self._prepare_option_dict_for_phase(f"{var_name}_init", init, InitialGuessList)
scaling = self._prepare_option_dict_for_phase(f"{var_name}_scaling", scaling, VariableScalingList)
return bounds, init, scaling
def _prepare_all_decision_variables(
self,
x_bounds,
x_init,
x_scaling,
u_bounds,
u_init,
u_scaling,
xdot_scaling,
s_bounds,
s_init,
s_scaling,
):
"""
This function checks if the decision variables are of the right type for initial guess and bounds.
It also prepares the scaling for the decision variables.
Note
----
s decision variables are not relevant for traditional OCPs, only relevant for StochasticOptimalControlProgram
"""
x_bounds, x_init, x_scaling = self._check_and_prepare_decision_variables("x", x_bounds, x_init, x_scaling)
u_bounds, u_init, u_scaling = self._check_and_prepare_decision_variables("u", u_bounds, u_init, u_scaling)
s_bounds, s_init, s_scaling = self._check_and_prepare_decision_variables("s", s_bounds, s_init, s_scaling)
xdot_scaling = self._prepare_option_dict_for_phase("xdot_scaling", xdot_scaling, VariableScalingList)
return x_bounds, x_init, x_scaling, u_bounds, u_init, u_scaling, s_bounds, s_init, s_scaling, xdot_scaling
def _check_arguments_and_build_nlp(
self,
dynamics,
objective_functions,
constraints,
parameters,
phase_transitions,
multinode_constraints,
multinode_objectives,
parameter_bounds,
parameter_init,
parameter_constraints,
parameter_objectives,
ode_solver,
use_sx,
bio_model,
plot_mappings,
time_phase_mapping,
control_type,
variable_mappings,
integrated_value_functions,
):
if objective_functions is None:
objective_functions = ObjectiveList()
elif isinstance(objective_functions, Objective):
objective_functions_tp = ObjectiveList()
objective_functions_tp.add(objective_functions)
objective_functions = objective_functions_tp
elif not isinstance(objective_functions, ObjectiveList):
raise RuntimeError("objective_functions should be built from an Objective or ObjectiveList")
self.implicit_constraints = ConstraintList()
if constraints is None:
constraints = ConstraintList()
elif isinstance(constraints, Constraint):
constraints_tp = ConstraintList()
constraints_tp.add(constraints)
constraints = constraints_tp
elif not isinstance(constraints, ConstraintList):
raise RuntimeError("constraints should be built from an Constraint or ConstraintList")
if parameters is None:
parameters = ParameterList()
elif not isinstance(parameters, ParameterList):
raise RuntimeError("parameters should be built from an ParameterList")
if phase_transitions is None:
phase_transitions = PhaseTransitionList()
elif not isinstance(phase_transitions, PhaseTransitionList):
raise RuntimeError("phase_transitions should be built from an PhaseTransitionList")
if multinode_constraints is None:
multinode_constraints = MultinodeConstraintList()
elif not isinstance(multinode_constraints, MultinodeConstraintList):
raise RuntimeError("multinode_constraints should be built from an MultinodeConstraintList")
if multinode_objectives is None:
multinode_objectives = MultinodeObjectiveList()
elif not isinstance(multinode_objectives, MultinodeObjectiveList):
raise RuntimeError("multinode_objectives should be built from an MultinodeObjectiveList")
if parameter_bounds is None:
parameter_bounds = BoundsList()
elif not isinstance(parameter_bounds, BoundsList):
raise ValueError("parameter_bounds must be of type BoundsList")
if parameter_init is None:
parameter_init = InitialGuessList()
elif not isinstance(parameter_init, InitialGuessList):
raise ValueError("parameter_init must be of type InitialGuessList")
if parameter_objectives is None:
parameter_objectives = ParameterObjectiveList()
elif isinstance(parameter_objectives, ParameterObjective):
parameter_objectives_tp = ParameterObjectiveList()
parameter_objectives_tp.add(parameter_objectives)
parameter_objectives = parameter_objectives_tp
elif not isinstance(parameter_objectives, ParameterObjectiveList):
raise RuntimeError("objective_functions should be built from an Objective or ObjectiveList")
if parameter_constraints is None:
parameter_constraints = ParameterConstraintList()
elif isinstance(constraints, ParameterConstraint):
parameter_constraints_tp = ParameterConstraintList()
parameter_constraints_tp.add(parameter_constraints)
parameter_constraints = parameter_constraints_tp
elif not isinstance(parameter_constraints, ParameterConstraintList):
raise RuntimeError("constraints should be built from an Constraint or ConstraintList")
if ode_solver is None:
ode_solver = self._set_default_ode_solver()
elif not isinstance(ode_solver, OdeSolverBase):
raise RuntimeError("ode_solver should be built an instance of OdeSolver")
if not isinstance(use_sx, bool):
raise RuntimeError("use_sx should be a bool")
if isinstance(dynamics, Dynamics):
tp = dynamics
dynamics = DynamicsList()
dynamics.add(tp)
if not isinstance(dynamics, DynamicsList):
raise ValueError("dynamics must be of type DynamicsList or Dynamics")
# Type of CasADi graph
self.cx = SX if use_sx else MX
# Declare optimization variables
self.program_changed = True
self.J = []
self.J_internal = []
self.g = []
self.g_internal = []
self.g_implicit = []
# nlp is the core of a phase
self.nlp = [NLP(dynamics[i].phase_dynamics) for i in range(self.n_phases)]
NLP.add(self, "model", bio_model, False)
NLP.add(self, "phase_idx", [i for i in range(self.n_phases)], False)
# Define some aliases
NLP.add(self, "ns", self.n_shooting, False)
for nlp in self.nlp:
if nlp.ns < 1:
raise RuntimeError("Number of shooting points must be at least 1")
NLP.add(self, "n_threads", self.n_threads, True)
self.ocp_solver = None
self.is_warm_starting = False
plot_mappings = plot_mappings if plot_mappings is not None else {}
reshaped_plot_mappings = []
for i in range(self.n_phases):
reshaped_plot_mappings.append({})
for key in plot_mappings:
reshaped_plot_mappings[i][key] = plot_mappings[key][i]
NLP.add(self, "plot_mapping", reshaped_plot_mappings, False, name="plot_mapping")
phase_mapping, dof_names = self._set_kinematic_phase_mapping()
NLP.add(self, "phase_mapping", phase_mapping, True)
NLP.add(self, "dof_names", dof_names, True)
# Prepare the parameter mappings
if time_phase_mapping is None:
time_phase_mapping = BiMapping(
to_second=[i for i in range(self.n_phases)], to_first=[i for i in range(self.n_phases)]
)
self.time_phase_mapping = time_phase_mapping
# Add any time related parameters to the parameters list before declaring it
self._define_time(
self.phase_time, objective_functions, constraints, parameters, parameter_init, parameter_bounds
)
# Declare and fill the parameters
self.parameters = ParameterList()
self._declare_parameters(parameters)
# Prepare path constraints and dynamics of the program
NLP.add(self, "dynamics_type", dynamics, False)
NLP.add(self, "ode_solver", ode_solver, True)
NLP.add(self, "control_type", control_type, True)
# Prepare the variable mappings
if variable_mappings is None:
variable_mappings = BiMappingList()
variable_mappings = variable_mappings.variable_mapping_fill_phases(self.n_phases)
NLP.add(self, "variable_mappings", variable_mappings, True)
NLP.add(self, "integrated_value_functions", integrated_value_functions, True)
return (
constraints,
objective_functions,
parameter_constraints,
parameter_objectives,
multinode_constraints,
multinode_objectives,
phase_transitions,
parameter_bounds,
parameter_init,
)
def _prepare_node_mapping(self, node_mappings):
# Prepare the node mappings
if node_mappings is None:
node_mappings = NodeMappingList()
(
use_states_from_phase_idx,
use_states_dot_from_phase_idx,
use_controls_from_phase_idx,
) = node_mappings.get_variable_from_phase_idx(self)
self._check_variable_mapping_consistency_with_node_mapping(
use_states_from_phase_idx, use_controls_from_phase_idx
)
def _prepare_dynamics(self):
# Prepare the dynamics
for i in range(self.n_phases):
self.nlp[i].initialize(self.cx)
ConfigureProblem.initialize(self, self.nlp[i])
self.nlp[i].ode_solver.prepare_dynamic_integrator(self, self.nlp[i])
if (isinstance(self.nlp[i].model, VariationalBiorbdModel)) and self.nlp[i].stochastic_variables.shape > 0:
raise NotImplementedError(
"Stochastic variables were not tested with variational integrators. If you come across this error, "
"please notify the developers by opening open an issue on GitHub pinging Ipuch and EveCharbie"
)
def _prepare_bounds_and_init(
self, x_bounds, u_bounds, parameter_bounds, s_bounds, x_init, u_init, parameter_init, s_init
):
self.parameter_bounds = BoundsList()
self.parameter_init = InitialGuessList()
self.update_bounds(x_bounds, u_bounds, parameter_bounds, s_bounds)
self.update_initial_guess(x_init, u_init, parameter_init, s_init)
# Define the actual NLP problem
OptimizationVectorHelper.declare_ocp_shooting_points(self)
def _declare_multi_node_penalties(
self,
multinode_constraints: ConstraintList,
multinode_objectives: ObjectiveList,
constraints: ConstraintList,
phase_transition: PhaseTransitionList,
):
"""
This function declares the multi node penalties (constraints and objectives) to the penalty pool.
Note
----
This function is overriden in StochasticOptimalControlProgram
"""
multinode_constraints.add_or_replace_to_penalty_pool(self)
multinode_objectives.add_or_replace_to_penalty_pool(self)
def _finalize_penalties(
self,
constraints,
parameter_constraints,
objective_functions,
parameter_objectives,
phase_transitions,
):
# Define continuity constraints
# Prepare phase transitions (Reminder, it is important that parameters are declared before,
# otherwise they will erase the phase_transitions)
self.phase_transitions = phase_transitions.prepare_phase_transitions(self)
# Skipping creates an OCP without built-in continuity constraints, make sure you declared constraints elsewhere
self._declare_continuity()
# Prepare constraints
self.update_constraints(self.implicit_constraints)
self.update_constraints(constraints)
self.update_parameter_constraints(parameter_constraints)
# Prepare objectives
self.update_objectives(objective_functions)
self.update_parameter_objectives(parameter_objectives)
return
@property
def variables_vector(self):
return OptimizationVectorHelper.vector(self)
@property
def bounds_vectors(self):
return OptimizationVectorHelper.bounds_vectors(self)
@property
def init_vector(self):
return OptimizationVectorHelper.init_vector(self)
@classmethod
def from_loaded_data(cls, data):
"""
Loads an OCP from a dictionary ("ocp_initializer")
Parameters
----------
data: dict
A dictionary containing the data to load
Returns
-------
OptimalControlProgram
"""
for i, model in enumerate(data["bio_model"]):
model_class = model[0]
model_initializer = model[1]
data["bio_model"][i] = model_class(**model_initializer)
return cls(**data)
def _check_variable_mapping_consistency_with_node_mapping(
self, use_states_from_phase_idx, use_controls_from_phase_idx
):
# TODO this feature is broken since the merge with bi_node, fix it
if (
list(set(use_states_from_phase_idx)) != use_states_from_phase_idx
or list(set(use_controls_from_phase_idx)) != use_controls_from_phase_idx
):
raise NotImplementedError("Mapping over phases is broken")
for i in range(self.n_phases):
for j in [idx for idx, x in enumerate(use_states_from_phase_idx) if x == i]:
for key in self.nlp[i].variable_mappings.keys():
if key in self.nlp[j].variable_mappings.keys():
if (
self.nlp[i].variable_mappings[key].to_first.map_idx
!= self.nlp[j].variable_mappings[key].to_first.map_idx
or self.nlp[i].variable_mappings[key].to_second.map_idx
!= self.nlp[j].variable_mappings[key].to_second.map_idx
):
raise RuntimeError(
f"The variable mappings must be the same for the mapped phases."
f"Mapping on {key} is different between phases {i} and {j}."
)
for i in range(self.n_phases):
for j in [idx for idx, x in enumerate(use_controls_from_phase_idx) if x == i]:
for key in self.nlp[i].variable_mappings.keys():
if key in self.nlp[j].variable_mappings.keys():
if (
self.nlp[i].variable_mappings[key].to_first.map_idx
!= self.nlp[j].variable_mappings[key].to_first.map_idx
or self.nlp[i].variable_mappings[key].to_second.map_idx
!= self.nlp[j].variable_mappings[key].to_second.map_idx
):
raise RuntimeError(
f"The variable mappings must be the same for the mapped phases."
f"Mapping on {key} is different between phases {i} and {j}."
)
return
def _set_kinematic_phase_mapping(self):
"""
To add phase_mapping for different kinematic number of states in the ocp. It maps the degrees of freedom
across phases, so they appear on the same graph.
"""
dof_names_all_phases = []
phase_mappings = [] # [[] for _ in range(len(self.nlp))]
dof_names = [] # [[] for _ in range(len(self.nlp))]
for i, nlp in enumerate(self.nlp):
current_dof_mapping = []
for legend in nlp.model.name_dof:
if legend in dof_names_all_phases:
current_dof_mapping += [dof_names_all_phases.index(legend)]
else:
dof_names_all_phases += [legend]
current_dof_mapping += [len(dof_names_all_phases) - 1]
phase_mappings.append(
BiMapping(to_first=current_dof_mapping, to_second=list(range(len(current_dof_mapping))))
)
dof_names.append([dof_names_all_phases[i] for i in phase_mappings[i].to_first.map_idx])
return phase_mappings, dof_names
@staticmethod
def _check_quaternions_hasattr(biomodels: list[BioModel]) -> list[BioModel]:
"""
This functions checks if the biomodels have quaternions and if not we set an attribute to nb_quaternion to 0
Note: this need to be checked as this information is of importance for ODE solvers
Parameters
----------
biomodels: list[BioModel]
The list of biomodels to check
Returns
-------
biomodels: list[BioModel]
The list of biomodels with the attribute nb_quaternion set to 0 if no quaternion is present
"""
for i, model in enumerate(biomodels):
if not hasattr(model, "nb_quaternions"):
setattr(model, "nb_quaternions", 0)
return biomodels
def _prepare_option_dict_for_phase(self, name: str, option_dict: OptionDict, option_dict_type: type) -> Any:
if option_dict is None:
option_dict = option_dict_type()
if not isinstance(option_dict, option_dict_type):
raise RuntimeError(f"{name} should be built from a {option_dict_type.__name__} or a tuple of which")
option_dict: Any
if len(option_dict) == 1 and self.n_phases > 1:
scaling_phase_0 = option_dict[0]
for i in range(1, self.n_phases):
option_dict.add("None", [], phase=i) # Force the creation of the structure internally
for key in scaling_phase_0.keys():
option_dict.add(key, scaling_phase_0[key], phase=i)
return option_dict
def _declare_continuity(self) -> None:
"""
Declare the continuity function for the state variables. By default, the continuity function
is a constraint, but it declared as an objective if dynamics_type.state_continuity_weight is not None
"""
for nlp in self.nlp: # Inner-phase
if nlp.dynamics_type.skip_continuity:
continue
if nlp.dynamics_type.state_continuity_weight is None:
# Continuity as constraints
if nlp.phase_dynamics == PhaseDynamics.SHARED_DURING_THE_PHASE:
penalty = Constraint(
ConstraintFcn.STATE_CONTINUITY, node=Node.ALL_SHOOTING, penalty_type=PenaltyType.INTERNAL
)
penalty.add_or_replace_to_penalty_pool(self, nlp)
if nlp.ode_solver.is_direct_collocation and nlp.ode_solver.include_starting_collocation_point:
penalty = Constraint(
ConstraintFcn.FIRST_COLLOCATION_HELPER_EQUALS_STATE,
node=Node.ALL_SHOOTING,
penalty_type=PenaltyType.INTERNAL,
)
penalty.add_or_replace_to_penalty_pool(self, nlp)
else:
for shooting_node in range(nlp.ns):
penalty = Constraint(
ConstraintFcn.STATE_CONTINUITY, node=shooting_node, penalty_type=PenaltyType.INTERNAL
)
penalty.add_or_replace_to_penalty_pool(self, nlp)
if nlp.ode_solver.is_direct_collocation and nlp.ode_solver.include_starting_collocation_point:
penalty = Constraint(
ConstraintFcn.FIRST_COLLOCATION_HELPER_EQUALS_STATE,
node=shooting_node,
penalty_type=PenaltyType.INTERNAL,
)
penalty.add_or_replace_to_penalty_pool(self, nlp)
else:
# Continuity as objectives
if nlp.phase_dynamics == PhaseDynamics.SHARED_DURING_THE_PHASE:
penalty = Objective(
ObjectiveFcn.Mayer.STATE_CONTINUITY,
weight=nlp.dynamics_type.state_continuity_weight,
quadratic=True,
node=Node.ALL_SHOOTING,
penalty_type=PenaltyType.INTERNAL,
)
penalty.add_or_replace_to_penalty_pool(self, nlp)
else:
for shooting_point in range(nlp.ns):
penalty = Objective(
ObjectiveFcn.Mayer.STATE_CONTINUITY,
weight=nlp.dynamics_type.state_continuity_weight,
quadratic=True,
node=shooting_point,
penalty_type=PenaltyType.INTERNAL,
)
penalty.add_or_replace_to_penalty_pool(self, nlp)
for pt in self.phase_transitions:
# Phase transition as constraints