pytrajopt 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pytrajopt/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ from pytrajopt.guess import CusGuess, LinGuess
2
+ from pytrajopt.model import Expression, Syms
3
+ from pytrajopt.ocp import DisOcp, Ocp
4
+ from pytrajopt.ocp2nlp import generate_NLP
5
+ from pytrajopt.plots import (
6
+ check_feasibility,
7
+ cubic_spline_interp,
8
+ pc_interp,
9
+ plot_solution,
10
+ plot_solution_all_phase,
11
+ plot_sparsity,
12
+ )
13
+ from pytrajopt.transcription import DynamicMesh, Integrator, Transcription
@@ -0,0 +1,61 @@
1
+ import casadi as cs
2
+
3
+ from .ocp import Ocp
4
+
5
+
6
+ # @validate_call(config=ConfigDict(arbitrary_types_allowed=True))
7
+ def kkt_ub_lb(kkt: cs.DM):
8
+ """
9
+ lb<=g<=ub
10
+
11
+ Multiplier
12
+
13
+ lb-g<=0
14
+
15
+ g-ub<=0
16
+
17
+ There will be 2 multipliers for 2 constraints. But for the
18
+ bounded constraint can be merged into 1.
19
+
20
+ lam_ub-lam_lb
21
+ """
22
+ if kkt.shape != (1, 1):
23
+ pieces = kkt.shape[1] // 2
24
+ lbub = cs.horzsplit(kkt, pieces)
25
+ else:
26
+ pass
27
+ return lbub[1] - lbub[0]
28
+
29
+
30
+ # @validate_call(config=ConfigDict(arbitrary_types_allowed=True))
31
+ def get_costate(ocp: Ocp, nlp: cs.Opti, constraints: dict, t: cs.DM | cs.MX):
32
+ """
33
+ extracts the kkt multipliers for all the
34
+ constraints
35
+
36
+ for certain constraints the costates are also
37
+ estimated from the kkt multipliers
38
+
39
+ kkt multipliers of the defect constraints are
40
+ costates for states (only for explicit rk method or
41
+ multiple shooting constraints of the form x(k+1)=phi(x(k),u(k))).
42
+
43
+ rk4, fw_euler, exp_mid, casadi integrators (implicit and explicit)
44
+ all provide costate estimates
45
+ """
46
+
47
+ dual = {}
48
+
49
+ for name, constraint in constraints.items():
50
+ dual[f"kkt_{name}"] = kkt_ub_lb(nlp.dual(constraint[0]))
51
+ if name == "e":
52
+ dual[f"lam_{name}"] = dual[f"kkt_{name}"]
53
+ if name == "f":
54
+ dual[f"lam_{name}"] = -dual[f"kkt_{name}"]
55
+ if name == "h":
56
+ dt = t[:, 1:] - t[:, 0:-1]
57
+ dual[f"lam_{name}"] = dual[f"kkt_{name}"][:, 0:-1] / cs.repmat(
58
+ dt, dual[f"kkt_{name}"].shape[0], 1
59
+ )
60
+
61
+ return dual
pytrajopt/guess.py ADDED
@@ -0,0 +1,175 @@
1
+ import casadi as cs
2
+ from pydantic import (
3
+ BaseModel,
4
+ ConfigDict,
5
+ Field,
6
+ PositiveInt,
7
+ PrivateAttr,
8
+ model_validator,
9
+ )
10
+
11
+
12
+ class LinGuess(BaseModel):
13
+ """
14
+ Given lower and upper value for
15
+ state or control, LinGuess creates a linear
16
+ interpolation between these values
17
+
18
+ equal values of upper and lower values lead to
19
+ constant guess
20
+
21
+ guess for time enforced to be positive
22
+ """
23
+
24
+ model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
25
+ n: PositiveInt
26
+ xl: list[float | int]
27
+ xr: list[float | int]
28
+ ul: list[float | int]
29
+ ur: list[float | int]
30
+ tl: float | int = Field(ge=0, default=0)
31
+ tr: float | int = Field(gt=0, default=1)
32
+ _Xg: cs.DM | None = PrivateAttr(default=None)
33
+ _Ug: cs.DM | None = PrivateAttr(default=None)
34
+ _tg: cs.DM | None = PrivateAttr(default=None)
35
+ _t0g: cs.DM | None = PrivateAttr(default=None)
36
+ _tfg: cs.DM | None = PrivateAttr(default=None)
37
+
38
+ @model_validator(mode="after")
39
+ def check(self) -> "LinGuess":
40
+
41
+ for name, limits in zip(
42
+ ["state", "control"], [(self.xl, self.xr), (self.ul, self.ur)]
43
+ ):
44
+ if len(limits[0]) != len(limits[1]):
45
+ raise ValueError(
46
+ f"Number of elements mismatch for {name} end points. Received l={len(limits[0])} r={len(limits[1])}"
47
+ )
48
+
49
+ if self.tl < 0 or self.tr <= 0:
50
+ raise ValueError(
51
+ f"Guess for time cannot be negative (t0={self.tl},tf={self.tr}) "
52
+ )
53
+ if self.tr - self.tl <= 0:
54
+ raise ValueError(
55
+ f"Final time guess must be greater than initial time but received tr={self.tr}<= tl={self.tl}"
56
+ )
57
+
58
+ self._Xg = cs.vcat(
59
+ [cs.linspace(l, r, self.n + 1).T for l, r in zip(self.xl, self.xr)]
60
+ )
61
+ self._Ug = cs.vcat(
62
+ [cs.linspace(l, r, self.n).T for l, r in zip(self.ul, self.ur)]
63
+ )
64
+ self._t0g = cs.DM(self.tl)
65
+ self._tfg = cs.DM(self.tr)
66
+ self._tg = cs.linspace(self.tl, self.tr, self.n + 1).T
67
+ return self
68
+
69
+ def set_guess(self, dis_ocp: DisOcp, nlp: cs.Opti) -> None:
70
+ """
71
+ set guess to NLP
72
+
73
+ Parameters
74
+ ----------
75
+ dis_ocp : DisOcp
76
+ discrete OCP
77
+ nlp : cs.Opti
78
+ Opti
79
+ """
80
+
81
+ for name, att in zip(["state", "control"], ["X", "U"]):
82
+ if getattr(dis_ocp, att).shape != getattr(self, f"_{att}g").shape:
83
+ raise ValueError(
84
+ f"Guess for the {name} matrix has incorrect dimension, expected {getattr(dis_ocp, att).shape} but received {getattr(self, f'_{att}g').shape}"
85
+ )
86
+
87
+ nlp.set_initial(dis_ocp.X, self._Xg)
88
+ nlp.set_initial(dis_ocp.U, self._Ug)
89
+
90
+ if not isinstance(dis_ocp.t, cs.DM) or not dis_ocp.t.is_constant():
91
+ for i in cs.symvar(dis_ocp.t):
92
+ if i.shape == (1, self.n + 1):
93
+ nlp.set_initial(dis_ocp.t, self._tg)
94
+ break
95
+ if i.shape == (1, 1):
96
+ if cs.is_equal(dis_ocp.t0, i):
97
+ nlp.set_initial(dis_ocp.t0, self._t0g)
98
+ elif cs.is_equal(dis_ocp.tf, i):
99
+ nlp.set_initial(dis_ocp.tf, self._tfg)
100
+
101
+
102
+ class CusGuess(BaseModel):
103
+ """
104
+ a class to supply user defined guess
105
+
106
+ the transcription intervals must be passed to
107
+ check shape of the matrices
108
+
109
+ positivity of time guess enforced
110
+ """
111
+
112
+ model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
113
+ n: PositiveInt
114
+ Xg: cs.DM | None = None
115
+ Ug: cs.DM | None = None
116
+ tg: cs.DM | None = None
117
+ t0g: float | None = Field(ge=0, default=0)
118
+ tfg: float | None = Field(gt=0, default=1)
119
+
120
+ @model_validator(mode="after")
121
+ def check(self) -> "CusGuess":
122
+
123
+ if self.Xg.shape[1] != self.n + 1:
124
+ raise ValueError(
125
+ f"State guess matrix colums dont match. Expected {self.n + 1} but received {self.Xg.shape[1]}"
126
+ )
127
+
128
+ if self.Ug.shape[1] != self.n:
129
+ raise ValueError(
130
+ f"Control guess matrix colums dont match. Expected {self.n} but received {self.Ug.shape[1]}"
131
+ )
132
+
133
+ if self.tg.shape != (1, self.n + 1):
134
+ raise ValueError(
135
+ f'Time guess vector shape don"t match. Expected {(1, self.n + 1)} but received {self.tg.shape[1]}'
136
+ )
137
+
138
+ if self.tfg <= self.t0g:
139
+ raise ValueError(
140
+ f"Final time guess must be greater than initial time guess but received t0g ({self.t0g}) > tfg ({self.tfg}) "
141
+ )
142
+
143
+ return self
144
+
145
+ def set_guess(self, dis_ocp: DisOcp, nlp: cs.Opti) -> None:
146
+ """
147
+ set guess to NLP
148
+
149
+ Parameters
150
+ ----------
151
+ dis_ocp : DisOcp
152
+ discrete OCP
153
+ nlp : cs.Opti
154
+ Opti
155
+ """
156
+
157
+ for name, att in zip(["state", "control"], ["X", "U"]):
158
+ if getattr(dis_ocp, att).shape != getattr(self, f"{att}g").shape:
159
+ raise ValueError(
160
+ f"Guess for the {name} matrix has incorrect row dimension, expected {getattr(dis_ocp, att).shape} but received {getattr(self, f'{att}g').shape}"
161
+ )
162
+
163
+ nlp.set_initial(dis_ocp.X, self.Xg)
164
+ nlp.set_initial(dis_ocp.U, self.Ug)
165
+
166
+ if not isinstance(dis_ocp.t, cs.DM) or not dis_ocp.t.is_constant():
167
+ for i in cs.symvar(dis_ocp.t):
168
+ if i.shape == (1, self.n + 1):
169
+ nlp.set_initial(dis_ocp.t, self.tg)
170
+ break
171
+ if i.shape == (1, 1):
172
+ if cs.is_equal(dis_ocp.t0, i):
173
+ nlp.set_initial(dis_ocp.t0, self.t0g)
174
+ elif cs.is_equal(dis_ocp.tf, i):
175
+ nlp.set_initial(dis_ocp.tf, self.tfg)
pytrajopt/model.py ADDED
@@ -0,0 +1,173 @@
1
+ from typing import Literal
2
+
3
+ import casadi as cs
4
+ from pydantic import (
5
+ BaseModel,
6
+ ConfigDict,
7
+ PositiveInt,
8
+ PrivateAttr,
9
+ ValidationInfo,
10
+ field_validator,
11
+ model_validator,
12
+ )
13
+
14
+
15
+ class Expression(BaseModel):
16
+ """
17
+ A class which holds the expressions
18
+ related to the optimal control problem
19
+ like the lagrange and mayer objective
20
+ (L,E), dynamics (xd=f), event constraints
21
+ (<=e(t0,tf,x0,xf)<=) and path (<=h(t,x,u)<=)
22
+ constraints.
23
+
24
+ This class checks type and if the objective is
25
+ a scalar.
26
+ """
27
+
28
+ model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
29
+ L: cs.SX | None = None
30
+ E: cs.SX | None = None
31
+ f: cs.SX | None = None
32
+ e: cs.SX | None = None
33
+ h: cs.SX | None = None
34
+
35
+ @field_validator("L", "E")
36
+ @classmethod
37
+ def check_scalar(cls, obj: cs.SX | None, info: ValidationInfo) -> cs.SX | None:
38
+ """
39
+ Objective function related terms must be scalar.
40
+ """
41
+ if obj is not None and obj.numel() != 1:
42
+ raise ValueError(
43
+ f"{info.field_name} must be scalar but received matrix of shape {obj.shape}"
44
+ )
45
+ return obj
46
+
47
+
48
+ class Syms(BaseModel):
49
+ """
50
+ Symbolic variables for the defining the optimal
51
+ control problem problem.
52
+
53
+ Generate symbolics for the OCP and convert the
54
+ expressions to functions.
55
+ """
56
+
57
+ model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
58
+ nx: PositiveInt
59
+ nu: PositiveInt
60
+ _event: list[cs.SX] = PrivateAttr(default_factory=list)
61
+ _path: list[cs.SX] = PrivateAttr(default_factory=list)
62
+ _exps: Expression | None = PrivateAttr(default=None)
63
+
64
+ @model_validator(mode="after")
65
+ def create_syms(self) -> "Syms":
66
+ """
67
+ generates symbolics for
68
+ t0,tf,x0,xf and t,x,u
69
+ which will be used to create
70
+ casadi functions
71
+
72
+ Returns
73
+ -------
74
+ Syms
75
+ Syms
76
+ """
77
+ ts = cs.SX.sym("ts", 1, 1)
78
+ xs = cs.SX.sym("xs", self.nx, 1)
79
+ us = cs.SX.sym("us", self.nu, 1)
80
+ t0s = cs.SX.sym("t0s", 1, 1)
81
+ tfs = cs.SX.sym("tfs", 1, 1)
82
+ x0s = cs.SX.sym("x0s", self.nx, 1)
83
+ xfs = cs.SX.sym("xfs", self.nx, 1)
84
+ self._path = [ts, xs, us]
85
+ self._event = [t0s, tfs, x0s, xfs]
86
+ return self
87
+
88
+ def get_path(self) -> list[cs.SX]:
89
+ """
90
+ t,x,u
91
+
92
+ Returns
93
+ -------
94
+ list[cs.SX]
95
+ [t,x,u]
96
+ """
97
+ return self._path
98
+
99
+ def get_event(self) -> list[cs.SX]:
100
+ """
101
+ t0,tf,x0,xf
102
+
103
+ Returns
104
+ -------
105
+ list[cs.SX]
106
+ [t0,tf,x0,xf]
107
+ """
108
+ return self._event
109
+
110
+ def get_function(
111
+ self, name: str, expression: cs.SX, nature: Literal["event", "path"]
112
+ ) -> cs.Function:
113
+ """
114
+ generates a casadi function for Lagrange, Mayer,
115
+ event, dynamics and path constraints
116
+
117
+ Parameters
118
+ ----------
119
+ name : str
120
+ name passed to casadi.Function
121
+ expression : cs.SX
122
+ expression of symbolics
123
+ nature : Literal[&#39;event&#39;,&#39;path&#39;]
124
+ path or event variables
125
+
126
+ Returns
127
+ -------
128
+ cs.Function
129
+ a casadi function of the expression
130
+
131
+ Raises
132
+ ------
133
+ ValueError
134
+ path constraints have event variables and vice versa
135
+ """
136
+ input_vars = self.get_path() if nature == "path" else self.get_event()
137
+ try:
138
+ return cs.Function(name, input_vars, [expression])
139
+ except RuntimeError:
140
+ raise ValueError(
141
+ f"Cannot mix path (t,x,u) and event (t0,tf,x0,xf) variables in {name}"
142
+ )
143
+
144
+ def collect_expression(self, data) -> None:
145
+ """
146
+ store the expressions provided by the user
147
+ """
148
+ if self._exps is not None:
149
+ print("Overwriting previous expressions")
150
+ self._exps = Expression(**data)
151
+
152
+ def generate_funcs(self) -> dict[str, cs.Function]:
153
+ """
154
+ create a dict of functions based the OCP
155
+ expressions created
156
+ """
157
+ path = ["L", "f", "h"]
158
+ event = ["E", "e"]
159
+ func_dict = {}
160
+
161
+ for name, nature in zip(path, ["path"] * 3):
162
+ if getattr(self._exps, name) is not None:
163
+ func_dict[name] = self.get_function(
164
+ name, getattr(self._exps, name), nature
165
+ )
166
+
167
+ for name, nature in zip(event, ["event"] * 2):
168
+ if getattr(self._exps, name) is not None:
169
+ func_dict[name] = self.get_function(
170
+ name, getattr(self._exps, name), nature
171
+ )
172
+
173
+ return func_dict