-
Notifications
You must be signed in to change notification settings - Fork 47
/
solution.py
1577 lines (1355 loc) · 63.9 KB
/
solution.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 Any
from copy import deepcopy
import numpy as np
from scipy import interpolate as sci_interp
from scipy.interpolate import interp1d
from casadi import vertcat, DM, Function
from matplotlib import pyplot as plt
from .solution_data import SolutionData, SolutionMerge, TimeAlignment, TimeResolution
from ..optimization_vector import OptimizationVectorHelper
from ...limits.objective_functions import ObjectiveFcn
from ...limits.path_conditions import InitialGuess, InitialGuessList
from ...limits.penalty_helpers import PenaltyHelpers
from ...misc.enums import (
ControlType,
CostType,
Shooting,
InterpolationType,
SolverType,
SolutionIntegrator,
Node,
PhaseDynamics,
)
from ...dynamics.ode_solver import OdeSolver
from ...interfaces.solve_ivp_interface import solve_ivp_interface
from ...models.protocols.stochastic_biomodel import StochasticBioModel
class Solution:
"""
Data manipulation, graphing and storage
Attributes
----------
vector: np.ndarray
The data in the vector format
_cost: float
The value of the cost function
constraints: list
The values of the constraint
lam_g: list
The Lagrange multiplier of the constraints
lam_p: list
The Lagrange multiplier of the parameters
lam_x: list
The Lagrange multiplier of the states and controls
inf_pr: list
The unscaled constraint violation at each iteration
inf_du: list
The scaled dual infeasibility at each iteration
solver_time_to_optimize: float
The total time to solve the program
iterations: int
The number of iterations that were required to solve the program
status: int
Optimization success status (Ipopt: 0=Succeeded, 1=Failed)
_stepwise_times: list
The time corresponding to _stepwise_states
_decision_states: SolutionData
A SolutionData based solely on the solution
_stepwise_states: SolutionData
A SolutionData based on the integrated solution directly from the bioptim integrator
_stepwise_controls: SolutionData
The data structure that holds the controls
_parameters: SolutionData
The data structure that holds the parameters
_decision_algebraic_states: SolutionData
The data structure that holds the algebraic_states variables
phases_dt: list
The time step for each phases
Methods
-------
copy(self, skip_data: bool = False) -> Any
Create a deepcopy of the Solution
@property
controls(self) -> list | dict
Returns the controls scaled and unscaled in list if more than one phases, otherwise it returns the only dict
integrate(self, shooting_type: Shooting = Shooting.MULTIPLE, keep_intermediate_points: bool = True,
merge_phases: bool = False, continuous: bool = True) -> Solution
Integrate the states unscaled
interpolate(self, n_frames: int | list | tuple) -> Solution
Interpolate the states unscaled
merge_phases(self) -> Solution
Get a data structure where all the phases are merged into one
_merge_phases(self, skip_states: bool = False, skip_controls: bool = False) -> tuple
Actually performing the phase merging
_complete_control(self)
Controls don't necessarily have dimensions that matches the states. This method aligns them
graphs(self, automatically_organize: bool, show_bounds: bool,
show_now: bool, shooting_type: Shooting)
Show the graphs of the simulation
animate(self, n_frames: int = 0, show_now: bool = True, **kwargs: Any) -> None | list
Animate the simulation
print(self, cost_type: CostType = CostType.ALL)
Print the objective functions and/or constraints to the console
"""
def __init__(
self,
ocp,
vector: np.ndarray | DM = None,
cost: np.ndarray | DM = None,
constraints: np.ndarray | DM = None,
lam_g: np.ndarray | DM = None,
lam_p: np.ndarray | DM = None,
lam_x: np.ndarray | DM = None,
inf_pr: np.ndarray | DM = None,
inf_du: np.ndarray | DM = None,
solver_time_to_optimize: float = None,
real_time_to_optimize: float = None,
iterations: int = None,
status: int = None,
):
"""
Parameters
----------
ocp: OptimalControlProgram
A reference to the ocp to strip
vector: np.ndarray | DM
The solution vector, containing all the states, controls, parameters and algebraic_states variables
cost: np.ndarray | DM
The cost value of the objective function
constraints: np.ndarray | DM
The constraints value
lam_g: np.ndarray | DM
The lagrange multipliers for the constraints
lam_p: np.ndarray | DM
The lagrange multipliers for the parameters
lam_x: np.ndarray | DM
The lagrange multipliers for the states
lam_g: np.ndarray | DM
The lagrange multipliers for the constraints
inf_pr: np.ndarray | DM
The primal infeasibility
inf_du: np.ndarray | DM
The dual infeasibility
solver_time_to_optimize: float
The time to optimize
real_time_to_optimize: float
The real time to optimize
iterations: int
The number of iterations
status: int
The status of the solution
"""
self.ocp = ocp
# Penalties
self._cost, self._detailed_cost, self.constraints = cost, None, constraints
# Solver options
self.status, self.iterations = status, iterations
self.lam_g, self.lam_p, self.lam_x, self.inf_pr, self.inf_du = lam_g, lam_p, lam_x, inf_pr, inf_du
self.solver_time_to_optimize, self.real_time_to_optimize = solver_time_to_optimize, real_time_to_optimize
# Extract the data now for further use
self._decision_states = None
self._stepwise_states = None
self._stepwise_controls = None
self._parameters = None
self._decision_algebraic_states = None
self.vector = vector
if self.vector is not None:
self.phases_dt = OptimizationVectorHelper.extract_phase_dt(ocp, vector)
self._stepwise_times = OptimizationVectorHelper.extract_step_times(ocp, vector)
x, u, p, a = OptimizationVectorHelper.to_dictionaries(ocp, vector)
self._decision_states = SolutionData.from_scaled(ocp, x, "x")
self._stepwise_controls = SolutionData.from_scaled(ocp, u, "u")
self._parameters = SolutionData.from_scaled(ocp, p, "p")
self._decision_algebraic_states = SolutionData.from_scaled(ocp, a, "a")
@classmethod
def from_dict(cls, ocp, sol: dict):
"""
Initialize all the attributes from an Ipopt-like dictionary data structure
Parameters
----------
ocp: OptimalControlProgram
A reference to the OptimalControlProgram
sol: dict
The solution in a Ipopt-like dictionary
"""
if not isinstance(sol, dict):
raise ValueError("The _sol entry should be a dictionary")
is_ipopt = sol["solver"] == SolverType.IPOPT.value
return cls(
ocp=ocp,
vector=sol["x"],
cost=sol["f"] if is_ipopt else None,
constraints=sol["g"] if is_ipopt else None,
lam_g=sol["lam_g"] if is_ipopt else None,
lam_p=sol["lam_p"] if is_ipopt else None,
lam_x=sol["lam_x"] if is_ipopt else None,
inf_pr=sol["inf_pr"] if is_ipopt else None,
inf_du=sol["inf_du"] if is_ipopt else None,
solver_time_to_optimize=sol["solver_time_to_optimize"],
real_time_to_optimize=sol["real_time_to_optimize"],
iterations=sol["iter"],
status=sol["status"],
)
@classmethod
def from_initial_guess(cls, ocp, sol: list):
"""
Initialize all the attributes from a list of initial guesses (states, controls)
Parameters
----------
ocp: OptimalControlProgram
A reference to the OptimalControlProgram
sol: list
The list of initial guesses
"""
if not (isinstance(sol, (list, tuple)) and len(sol) == 5):
raise ValueError("_sol should be a list of tuple and the length should be 5")
n_param = len(ocp.parameters)
all_ns = [nlp.ns for nlp in ocp.nlp]
# Sanity checks
for i in range(len(sol)): # Convert to list if necessary and copy for as many phases there are
if isinstance(sol[i], InitialGuess):
tp = InitialGuessList()
for _ in range(len(all_ns)):
tp.add(deepcopy(sol[i].init), interpolation=sol[i].init.type)
sol[i] = tp
if sum([isinstance(s, InitialGuessList) for s in sol]) != 4:
raise ValueError(
"solution must be a solution dict, "
"an InitialGuess[List] of len 4 (states, controls, parameters, algebraic_states), "
"or a None"
)
if len(sol[0]) != len(all_ns):
raise ValueError("The time step dt array len must match the number of phases")
is_right_size = [
len(s) != len(all_ns) if p != 3 and len(sol[p + 1].keys()) != 0 else False for p, s in enumerate(sol[:1])
]
if sum(is_right_size) != 0:
raise ValueError("The InitialGuessList len must match the number of phases")
if n_param != 0:
if len(sol) != 3 and len(sol[3]) != 1 and sol[3][0].shape != (n_param, 1):
raise ValueError(
"The 3rd element is the InitialGuess of the parameter and "
"should be a unique vector of size equal to n_param"
)
dt, sol_states, sol_controls, sol_params, sol_algebraic_states = sol
vector = np.ndarray((0, 1))
# For time
if len(dt.shape) == 1:
dt = dt[:, np.newaxis]
vector = np.concatenate((vector, dt))
# For states
for p, ss in enumerate(sol_states):
repeat = 1
if isinstance(ocp.nlp[p].ode_solver, OdeSolver.COLLOCATION):
repeat = ocp.nlp[p].ode_solver.polynomial_degree + 1
for key in ss.keys():
ns = ocp.nlp[p].ns + 1 if ss[key].init.type != InterpolationType.EACH_FRAME else ocp.nlp[p].ns
ss[key].init.check_and_adjust_dimensions(len(ocp.nlp[p].states[key]), ns, "states")
for i in range(all_ns[p] + 1):
for key in ss.keys():
vector = np.concatenate((vector, ss[key].init.evaluate_at(i, repeat)[:, np.newaxis]))
# For controls
for p, ss in enumerate(sol_controls):
control_type = ocp.nlp[p].control_type
if control_type == ControlType.CONSTANT:
off = 0
elif control_type in (ControlType.LINEAR_CONTINUOUS, ControlType.CONSTANT_WITH_LAST_NODE):
off = 1
else:
raise NotImplementedError(f"control_type {control_type} is not implemented in Solution")
for key in ss.keys():
ss[key].init.check_and_adjust_dimensions(len(ocp.nlp[p].controls[key]), all_ns[p] - 1 + off, "controls")
for i in range(all_ns[p] + off):
for key in ss.keys():
vector = np.concatenate((vector, ss[key].init.evaluate_at(i)[:, np.newaxis]))
# For parameters
if n_param:
for p, ss in enumerate(sol_params):
for key in ss.keys():
vector = np.concatenate((vector, np.repeat(ss[key].init, 1)[:, np.newaxis]))
# For algebraic_states variables
for p, ss in enumerate(sol_algebraic_states):
for key in ss.keys():
ss[key].init.check_and_adjust_dimensions(
len(ocp.nlp[p].algebraic_states[key]), all_ns[p], "algebraic_states"
)
for i in range(all_ns[p] + 1):
for key in ss.keys():
vector = np.concatenate((vector, ss[key].init.evaluate_at(i)[:, np.newaxis]))
return cls(ocp=ocp, vector=vector)
@classmethod
def from_vector(cls, ocp, sol: np.ndarray | DM):
"""
Initialize all the attributes from a vector of solution
Parameters
----------
ocp: OptimalControlProgram
A reference to the OptimalControlProgram
sol: np.ndarray | DM
The solution in vector format
"""
if not isinstance(sol, (np.ndarray, DM)):
raise ValueError("The _sol entry should be a np.ndarray or a DM.")
return cls(ocp=ocp, vector=sol)
@classmethod
def from_ocp(cls, ocp):
"""
Initialize all the attributes from a vector of solution
Parameters
----------
ocp: OptimalControlProgram
A reference to the OptimalControlProgram
"""
return cls(ocp=ocp)
def t_span(
self,
to_merge: SolutionMerge | list[SolutionMerge] = None,
time_alignment: TimeAlignment = TimeAlignment.STATES,
continuous: bool = True,
):
"""
Returns the time span at each node of each phases
"""
return self._process_time_vector(
time_resolution=TimeResolution.NODE_SPAN,
to_merge=to_merge,
time_alignment=time_alignment,
continuous=continuous,
)
def decision_time(
self,
to_merge: SolutionMerge | list[SolutionMerge] = None,
time_alignment: TimeAlignment = TimeAlignment.STATES,
continuous: bool = True,
) -> list | np.ndarray:
"""
Returns the time vector at each node that matches decision_states or decision_controls
Parameters
----------
to_merge: SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed. It is often useful to merge NODES, but
is completely useless to merge KEYS
time_alignment: TimeAlignment
The type of alignment to perform. If TimeAlignment.STATES, then the time vector is aligned with the states
(i.e. all the subnodes and the last node time are present). If TimeAlignment.CONTROLS, then the time vector
is aligned with the controls (i.e. only starting of the node without the last node if CONTROL constant).
continuous: bool
If the time should be continuous throughout the whole ocp. If False, then the time is reset at the
beginning of each phase.
"""
return self._process_time_vector(
time_resolution=TimeResolution.DECISION,
to_merge=to_merge,
time_alignment=time_alignment,
continuous=continuous,
)
def stepwise_time(
self,
to_merge: SolutionMerge | list[SolutionMerge] = None,
time_alignment: TimeAlignment = TimeAlignment.STATES,
continuous: bool = True,
duplicated_times: bool = True,
) -> list | np.ndarray:
"""
Returns the time vector at each node that matches stepwise_states or stepwise_controls
Parameters
----------
to_merge: SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed. It is often useful to merge NODES, but
is completely useless to merge KEYS
time_alignment: TimeAlignment
The type of alignment to perform. If TimeAlignment.STATES, then the time vector is aligned with the states
(i.e. all the subnodes and the last node time are present). If TimeAlignment.CONTROLS, then the time vector
is aligned with the controls (i.e. only starting of the node without the last node if CONTROL constant).
continuous: bool
If the time should be continuous throughout the whole ocp. If False, then the time is reset at the
beginning of each phase.
duplicated_times: bool
If the times should be duplicated for each nodes.
If False, then the returned time vector will not have any duplicated times
Returns
-------
The time vector at each node that matches stepwise_states or stepwise_controls
"""
return self._process_time_vector(
time_resolution=TimeResolution.STEPWISE,
to_merge=to_merge,
time_alignment=time_alignment,
continuous=continuous,
duplicated_times=duplicated_times,
)
def _process_time_vector(
self,
time_resolution: TimeResolution,
to_merge: SolutionMerge | list[SolutionMerge],
time_alignment: TimeAlignment,
continuous: bool,
duplicated_times: bool = True,
):
if to_merge is None or isinstance(to_merge, SolutionMerge):
to_merge = [to_merge]
# Make sure to not return internal structure
times_tp = deepcopy(self._stepwise_times)
# Select the appropriate time matrix
phases_tf = []
times = []
for nlp in self.ocp.nlp:
phases_tf.append(times_tp[nlp.phase_idx][-1])
if time_resolution == TimeResolution.NODE_SPAN:
if time_alignment == TimeAlignment.STATES:
times.append([t if t.shape == (1, 1) else t[[0, -1]] for t in times_tp[nlp.phase_idx]])
elif time_alignment == TimeAlignment.CONTROLS:
times.append([t[[0, -1]] for t in times_tp[nlp.phase_idx][:-1]])
else:
if time_alignment == TimeAlignment.STATES:
if nlp.ode_solver.is_direct_collocation:
if nlp.ode_solver.duplicate_starting_point:
times.append(
[t if t.shape == (1, 1) else vertcat(t[0], t[:-1]) for t in times_tp[nlp.phase_idx]]
)
else:
times.append([t if t.shape == (1, 1) else t[:-1] for t in times_tp[nlp.phase_idx]])
else:
if time_resolution == TimeResolution.STEPWISE:
times.append(times_tp[nlp.phase_idx])
elif time_resolution == TimeResolution.DECISION:
times.append([t[0] for t in times_tp[nlp.phase_idx]])
else:
raise ValueError("Unrecognized time_resolution")
elif time_alignment == TimeAlignment.CONTROLS:
if nlp.control_type == ControlType.LINEAR_CONTINUOUS:
times.append([(t if t.shape == (1, 1) else t[[0, -1]]) for t in times_tp[nlp.phase_idx]])
if len(times) < len(self.ocp.nlp):
# The point is duplicated for internal phases, but not the last one
times[-1][-1] = times[-1][-1][[0, 0]].T
elif nlp.control_type == ControlType.CONSTANT_WITH_LAST_NODE:
times.append([t[0] for t in times_tp[nlp.phase_idx]])
elif nlp.control_type == ControlType.CONSTANT:
times.append([t[0] for t in times_tp[nlp.phase_idx]][:-1])
else:
raise ValueError(f"Unrecognized control type {nlp.control_type}")
else:
raise ValueError("time_alignment should be either TimeAlignment.STATES or TimeAlignment.CONTROLS")
if not duplicated_times:
for i in range(len(times)):
for j in range(len(times[i])):
# Last node of last phase is always kept
keep_condition = times[i][j].shape[0] == 1 and i == len(times) - 1
times[i][j] = times[i][j][:] if keep_condition else times[i][j][:-1]
if j == len(times[i]) - 1 and i != len(times) - 1:
del times[i][j]
if continuous:
for phase_idx, phase_time in enumerate(times):
if phase_idx == 0:
continue
previous_tf = sum(phases_tf[:phase_idx])
times[phase_idx] = [t + previous_tf for t in phase_time]
if SolutionMerge.NODES in to_merge or SolutionMerge.ALL in to_merge:
for phase_idx in range(len(times)):
np.concatenate((np.concatenate(times[phase_idx][:-1]), times[phase_idx][-1]))
times[phase_idx] = np.concatenate((np.concatenate(times[phase_idx][:-1]), times[phase_idx][-1]))
if (
SolutionMerge.PHASES in to_merge and SolutionMerge.NODES not in to_merge
) and SolutionMerge.ALL not in to_merge:
raise ValueError("Cannot merge phases without nodes")
if SolutionMerge.PHASES in to_merge or SolutionMerge.ALL in to_merge:
# NODES is necessarily in to_merge if PHASES is in to_merge
times = np.concatenate(times)
return times if len(times) > 1 else times[0]
def decision_states(self, scaled: bool = False, to_merge: SolutionMerge | list[SolutionMerge] = None):
"""
Returns the decision states
Parameters
----------
scaled: bool
If the decision states should be scaled or not (note that scaled is as Ipopt received them, while unscaled
is as the model needs temps). If you don't know what it means, you probably want the unscaled version.
to_merge: SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed.
Returns
-------
The decision variables
"""
data = self._decision_states.to_dict(to_merge=to_merge, scaled=scaled)
if not isinstance(data, list):
return data
return data if len(data) > 1 else data[0]
def stepwise_states(self, scaled: bool = False, to_merge: SolutionMerge | list[SolutionMerge] = None):
"""
Returns the stepwise integrated states
Parameters
----------
scaled: bool
If the states should be scaled or not (note that scaled is as Ipopt received them, while unscaled is as the
model needs temps). If you don't know what it means, you probably want the unscaled version.
to_merge: SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed.
Returns
-------
The stepwise integrated states
"""
if self._stepwise_states is None:
self._integrate_stepwise()
data = self._stepwise_states.to_dict(to_merge=to_merge, scaled=scaled)
if not isinstance(data, list):
return data
return data if len(data) > 1 else data[0]
def decision_controls(self, scaled: bool = False, to_merge: SolutionMerge | list[SolutionMerge] = None):
"""
Returns the decision controls
Parameters
----------
scaled : bool
If the decision controls should be scaled or not (note that scaled is as Ipopt received them, while unscaled
is as the model needs temps). If you don't know what it means, you probably want the unscaled version.
to_merge : SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed.
"""
return self.stepwise_controls(scaled=scaled, to_merge=to_merge)
def stepwise_controls(self, scaled: bool = False, to_merge: SolutionMerge | list[SolutionMerge] = None):
"""
Returns the controls. Note the final control is always present but set to np.nan if it is not defined
Parameters
----------
scaled: bool
If the controls should be scaled or not (note that scaled is as Ipopt received them, while unscaled is as
the model needs temps). If you don't know what it means, you probably want the unscaled version.
to_merge: SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed.
Returns
-------
The controls
"""
data = self._stepwise_controls.to_dict(to_merge=to_merge, scaled=scaled)
if not isinstance(data, list):
return data
return data if len(data) > 1 else data[0]
@property
def parameters(self):
"""
Returns the parameters
"""
return self.decision_parameters(scaled=False)
def decision_parameters(self, scaled: bool = False, to_merge: SolutionMerge | list[SolutionMerge] = None):
"""
Returns the decision parameters
Parameters
----------
scaled: bool
If the parameters should be scaled or not (note that scaled is as Ipopt received them, while unscaled is as
the model needs temps). If you don't know what it means, you probably want the unscaled version.
Returns
-------
The decision parameters
"""
if to_merge is None:
to_merge = []
if isinstance(to_merge, SolutionMerge):
to_merge = [to_merge]
if SolutionMerge.PHASES in to_merge:
raise ValueError("Cannot merge phases for parameters as it is not bound to phases")
if SolutionMerge.NODES in to_merge:
raise ValueError("Cannot merge nodes for parameters as it is not bound to nodes")
out = self._parameters.to_dict(scaled=scaled, to_merge=to_merge)
# Remove the residual phases and nodes
if to_merge:
out = out[0][0][:, 0]
else:
out = out[0]
out = {key: out[key][0][:, 0] for key in out.keys()}
return out
def decision_algebraic_states(self, scaled: bool = False, to_merge: SolutionMerge | list[SolutionMerge] = None):
"""
Returns the decision algebraic_states
Parameters
----------
scaled: bool
If the decision states should be scaled or not (note that scaled is as Ipopt received them, while unscaled
is as the model needs temps). If you don't know what it means, you probably want the unscaled version.
to_merge: SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed.
Returns
-------
The decision variables
"""
data = self._decision_algebraic_states.to_dict(to_merge=to_merge, scaled=scaled)
if not isinstance(data, list):
return data
return data if len(data) > 1 else data[0]
def copy(self, skip_data: bool = False) -> "Solution":
"""
Create a deepcopy of the Solution
Parameters
----------
skip_data: bool
If data should be ignored in the copy
Returns
-------
Return a Solution data structure
"""
new = Solution.from_ocp(self.ocp)
new.vector = deepcopy(self.vector)
new._cost = deepcopy(self._cost)
new.constraints = deepcopy(self.constraints)
new.lam_g = deepcopy(self.lam_g)
new.lam_p = deepcopy(self.lam_p)
new.lam_x = deepcopy(self.lam_x)
new.inf_pr = deepcopy(self.inf_pr)
new.inf_du = deepcopy(self.inf_du)
new.solver_time_to_optimize = deepcopy(self.solver_time_to_optimize)
new.real_time_to_optimize = deepcopy(self.real_time_to_optimize)
new.iterations = deepcopy(self.iterations)
new.phases_dt = deepcopy(self.phases_dt)
new._stepwise_times = deepcopy(self._stepwise_times)
if not skip_data:
new._decision_states = deepcopy(self._decision_states)
new._stepwise_states = deepcopy(self._stepwise_states)
new._stepwise_controls = deepcopy(self._stepwise_controls)
new._decision_algebraic_states = deepcopy(self._decision_algebraic_states)
new._parameters = deepcopy(self._parameters)
return new
def _prepare_integrate(self, integrator: SolutionIntegrator):
"""
Prepare the variables for the states integration and checks if the integrator is compatible with the ocp.
Parameters
----------
integrator: SolutionIntegrator
The integrator to use for the integration
"""
from ...interfaces.interface_utils import _get_dynamics_constants
has_direct_collocation = sum([nlp.ode_solver.is_direct_collocation for nlp in self.ocp.nlp]) > 0
if has_direct_collocation and integrator == SolutionIntegrator.OCP:
raise ValueError(
"When the ode_solver of the Optimal Control Problem is OdeSolver.COLLOCATION, "
"we cannot use the SolutionIntegrator.OCP.\n"
"We must use one of the SolutionIntegrator provided by scipy with any Shooting Enum such as"
" Shooting.SINGLE, Shooting.MULTIPLE, or Shooting.SINGLE_DISCONTINUOUS_PHASE"
)
has_trapezoidal = sum([isinstance(nlp.ode_solver, OdeSolver.TRAPEZOIDAL) for nlp in self.ocp.nlp]) > 0
if has_trapezoidal and integrator == SolutionIntegrator.OCP:
raise ValueError(
"When the ode_solver of the Optimal Control Problem is OdeSolver.TRAPEZOIDAL, "
"we cannot use the SolutionIntegrator.OCP.\n"
"We must use one of the SolutionIntegrator provided by scipy with any Shooting Enum such as"
" Shooting.SINGLE, Shooting.MULTIPLE, or Shooting.SINGLE_DISCONTINUOUS_PHASE",
)
params = self._parameters.to_dict(to_merge=SolutionMerge.KEYS, scaled=True)[0][0]
t_spans = self.t_span(time_alignment=TimeAlignment.CONTROLS)
if len(self.ocp.nlp) == 1:
t_spans = [t_spans]
x = self._decision_states.to_dict(to_merge=SolutionMerge.KEYS, scaled=False)
u = self._stepwise_controls.to_dict(to_merge=SolutionMerge.KEYS, scaled=False)
a = self._decision_algebraic_states.to_dict(to_merge=SolutionMerge.KEYS, scaled=False)
return t_spans, x, u, params, a
def integrate(
self,
shooting_type: Shooting = Shooting.SINGLE,
integrator: SolutionIntegrator = SolutionIntegrator.OCP,
to_merge: SolutionMerge | list[SolutionMerge] = None,
duplicated_times: bool = True,
return_time: bool = False,
):
"""
Create a deepcopy of the Solution
Parameters
----------
shooting_type: Shooting
The integration shooting type to use
integrator: SolutionIntegrator
The type of integrator to use
to_merge: SolutionMerge | list[SolutionMerge, ...]
The type of merge to perform. If None, then no merge is performed.
duplicated_times: bool
If the times should be duplicated for each node.
If False, then the returned time vector will not have any duplicated times.
Default is True.
return_time: bool
If the time vector should be returned, default is False.
Returns
-------
Return the integrated states
"""
from ...interfaces.interface_utils import _get_dynamics_constants
t_spans, x, u, params, a = self._prepare_integrate(integrator=integrator)
out: list = [None] * len(self.ocp.nlp)
integrated_sol = None
for p, nlp in enumerate(self.ocp.nlp):
first_x = self._states_for_phase_integration(shooting_type, p, integrated_sol, x, u, params, a)
d = []
for n_idx in range(nlp.ns + 1):
d_tp = _get_dynamics_constants(self.ocp, p, n_idx, 0)
if d_tp.shape == (0, 0):
d += [np.array([])]
else:
d += [np.array(d_tp)]
integrated_sol = solve_ivp_interface(
list_of_dynamics=[nlp.dynamics_func] * nlp.ns,
shooting_type=shooting_type,
nlp=nlp,
t=t_spans[p],
x=first_x,
u=u[p],
a=a[p],
d=d,
p=params,
method=integrator,
)
out[p] = {}
for key in nlp.states.keys():
out[p][key] = [None] * nlp.n_states_nodes
for ns, sol_ns in enumerate(integrated_sol):
if duplicated_times:
out[p][key][ns] = sol_ns[nlp.states[key].index, :]
else:
# Last node of last phase is always kept
duplicated_times_condition = p == len(self.ocp.nlp) - 1 and ns == nlp.ns
out[p][key][ns] = (
sol_ns[nlp.states[key].index, :]
if duplicated_times_condition
else sol_ns[nlp.states[key].index, :-1]
)
if to_merge:
out = SolutionData.from_unscaled(self.ocp, out, "x").to_dict(to_merge=to_merge, scaled=False)
if return_time:
time_vector = self._return_time_vector(to_merge=to_merge, duplicated_times=duplicated_times)
return out if len(out) > 1 else out[0], time_vector if len(time_vector) > 1 else time_vector[0]
else:
return out if len(out) > 1 else out[0]
def noisy_integrate(
self,
integrator: SolutionIntegrator = SolutionIntegrator.OCP,
to_merge: SolutionMerge | list[SolutionMerge] = None,
size: int = 100,
):
"""
Integrated the states with different noise values sampled from the covariance matrix.
"""
from ...optimization.stochastic_optimal_control_program import StochasticOptimalControlProgram
from ...interfaces.interface_utils import _get_dynamics_constants
if not isinstance(self.ocp, StochasticOptimalControlProgram):
raise ValueError("This method is only available for StochasticOptimalControlProgram.")
t_spans, x, u, params, a = self._prepare_integrate(integrator=integrator)
cov_index = self.ocp.nlp[0].algebraic_states["cov"].index
n_sub_nodes = x[0][0].shape[1]
motor_noise_index = self.ocp.nlp[0].parameters["motor_noise"].index
sensory_noise_index = (
self.ocp.nlp[0].parameters["sensory_noise"].index
if len(list(self.ocp.nlp[0].parameters["sensory_noise"].index)) > 0
else None
)
# initialize the out dictionary
out = [None] * len(self.ocp.nlp)
for p, nlp in enumerate(self.ocp.nlp):
out[p] = {}
for key in self.ocp.nlp[0].states.keys():
out[p][key] = [None] * nlp.n_states_nodes
for i_node in range(nlp.ns):
out[p][key][i_node] = np.zeros((len(nlp.states[key].index), n_sub_nodes, size))
out[p][key][nlp.ns] = np.zeros((len(nlp.states[key].index), 1, size))
cov_matrix = StochasticBioModel.reshape_to_matrix(a[0][0][cov_index, :], self.ocp.nlp[0].model.matrix_shape_cov)
first_x = np.random.multivariate_normal(x[0][0][:, 0], cov_matrix, size=size).T
for p, nlp in enumerate(self.ocp.nlp):
d = []
for n_idx in range(nlp.ns + 1):
d_tp = _get_dynamics_constants(self.ocp, p, n_idx, 0)
if d_tp.shape == (0, 0):
d += [np.array([])]
else:
d += [np.array(d_tp)]
motor_noise = np.zeros((len(params[motor_noise_index]), nlp.ns, size))
for i in range(len(params[motor_noise_index])):
motor_noise[i, :] = np.random.normal(0, params[motor_noise_index[i]], size=(nlp.ns, size))
sensory_noise = (
np.zeros((len(sensory_noise_index), nlp.ns, size)) if sensory_noise_index is not None else None
)
if sensory_noise_index is not None:
for i in range(len(params[sensory_noise_index])):
sensory_noise[i, :] = np.random.normal(0, params[sensory_noise_index[i]], size=(nlp.ns, size))
without_noise_idx = [
i for i in range(len(params)) if i not in motor_noise_index and i not in sensory_noise_index
]
parameters_cx = nlp.parameters.cx[without_noise_idx]
parameters = params[without_noise_idx]
for i_random in range(size):
params_this_time = []
list_of_dynamics = []
for node in range(nlp.ns):
params_this_time += [nlp.parameters.cx]
params_this_time[node][motor_noise_index, :] = motor_noise[:, node, i_random]
if sensory_noise_index is not None:
params_this_time[node][sensory_noise_index, :] = sensory_noise[:, node, i_random]
if len(nlp.extra_dynamics_func) > 1:
raise NotImplementedError("Noisy integration is not available for multiple extra dynamics.")
cas_func = Function(
"noised_extra_dynamics",
[
nlp.time_cx,
nlp.states.cx,
nlp.controls.cx,
parameters_cx,
nlp.algebraic_states.cx,
nlp.dynamics_constants.cx,
],
[
nlp.extra_dynamics_func[0](
nlp.time_cx,
nlp.states.cx,
nlp.controls.cx,
params_this_time[node],
nlp.algebraic_states.cx,
nlp.dynamics_constants.cx,
)
],
)
list_of_dynamics += [cas_func]
integrated_sol = solve_ivp_interface(
list_of_dynamics=list_of_dynamics,
shooting_type=Shooting.SINGLE,
nlp=nlp,
t=t_spans[p],
x=[np.reshape(first_x[:, i_random], (-1, 1))],
u=u[p], # No need to add noise on the controls, the extra_dynamics should do it for us
a=a[p],
p=parameters,
d=d,
method=integrator,
)
for i_node in range(nlp.ns + 1):
for key in nlp.states.keys():
states_integrated = (
integrated_sol[i_node][nlp.states[key].index, :]
if n_sub_nodes > 1
else integrated_sol[i_node][nlp.states[key].index, 0].reshape(-1, 1)
)
out[p][key][i_node][:, :, i_random] = states_integrated
first_x[:, i_random] = np.reshape(integrated_sol[-1], (-1,))
if to_merge:
out = SolutionData.from_unscaled(self.ocp, out, "x").to_dict(to_merge=to_merge, scaled=False)
return out if len(out) > 1 else out[0]
def _states_for_phase_integration(
self,
shooting_type: Shooting,
phase_idx: int,
integrated_states: np.ndarray,
decision_states,
decision_controls,
params,
decision_algebraic_states,
):
"""
Returns the states to integrate for the phase_idx phase. If there was a phase transition, the last state of the
previous phase is transformed into the first state of the next phase
Parameters
----------
shooting_type
The shooting type to use
phase_idx
The phase index of the next phase to integrate
integrated_states
The states integrated from the previous phase
decision_states
The decision states merged with SolutionMerge.KEYS
decision_controls
The decision controls merged with SolutionMerge.KEYS
params
The parameters merged with SolutionMerge.KEYS
decision_algebraic_states
The algebraic_states merged with SolutionMerge.KEYS
Returns
-------
The states to integrate
"""
from ...interfaces.interface_utils import _get_dynamics_constants
# In the case of multiple shootings, we don't need to do anything special
if shooting_type == Shooting.MULTIPLE: