## 1. Expression tools¶

acos(*args)
acos(float x) -> float
acos(IM x) -> IM
acos(DM x) -> DM
acos(SX x) -> SX
acos(MX x) -> MX

acosh(*args)
acosh(float x) -> float
acosh(IM x) -> IM
acosh(DM x) -> DM
acosh(SX x) -> SX
acosh(MX x) -> MX

adj(*args)
adj(IM A) -> IM

asin(*args)
asin(float x) -> float
asin(IM x) -> IM
asin(DM x) -> DM
asin(SX x) -> SX
asin(MX x) -> MX

asinh(*args)
asinh(float x) -> float
asinh(IM x) -> IM
asinh(DM x) -> DM
asinh(SX x) -> SX
asinh(MX x) -> MX

atan(*args)
atan(float x) -> float
atan(IM x) -> IM
atan(DM x) -> DM
atan(SX x) -> SX
atan(MX x) -> MX

atan2(*args)
atan2(float x, float y) -> float
atan2(IM x, IM y) -> IM
atan2(DM x, DM y) -> DM
atan2(SX x, SX y) -> SX
atan2(MX x, MX y) -> MX

atanh(*args)
atanh(float x) -> float
atanh(IM x) -> IM
atanh(DM x) -> DM
atanh(SX x) -> SX
atanh(MX x) -> MX

bilin(*args)
Calculate bilinear form x^T A y.
bilin(IM A, IM x, IM y) -> IM
bilin(DM A, DM x, DM y) -> DM
bilin(SX A, SX x, SX y) -> SX
bilin(MX A, MX x, MX y) -> MX

blockcat(*args)
blockcat([[IM]] v) -> IM
blockcat([[DM]] v) -> DM
blockcat([[SX]] v) -> SX
blockcat([[MX]] v) -> MX
blockcat(Sparsity A, Sparsity B, Sparsity C, Sparsity D) -> Sparsity
blockcat(IM A, IM B, IM C, IM D) -> IM
blockcat(DM A, DM B, DM C, DM D) -> DM
blockcat(SX A, SX B, SX C, SX D) -> SX
blockcat(MX A, MX B, MX C, MX D) -> MX

ceil(*args)
ceil(float x) -> float
ceil(IM x) -> IM
ceil(DM x) -> DM
ceil(SX x) -> SX
ceil(MX x) -> MX

chol(*args)
Obtain a Cholesky factorisation of a matrix Performs and LDL transformation
chol(IM A) -> IM
chol(DM A) -> DM
chol(SX A) -> SX


[L,D] = ldl(A) and returns diag(sqrt(D))*L’.

cofactor(*args)
Get the (i,j) cofactor matrix.
cofactor(IM x, int i, int j) -> IM
cofactor(DM x, int i, int j) -> DM
cofactor(SX x, int i, int j) -> SX

conditional(*args)
Create a switch.
conditional(IM ind, [IM] x, IM x_default, bool short_circuit) -> IM
conditional(DM ind, [DM] x, DM x_default, bool short_circuit) -> DM
conditional(SX ind, [SX] x, SX x_default, bool short_circuit) -> SX
conditional(MX ind, [MX] x, MX x_default, bool short_circuit) -> MX


If the condition

ind: evaluates to the integer k, where 0<=k<f.size(), then x[k] will be returned, otherwise

x_default: will be returned.

constpow(*args)
constpow(float x, float y) -> float
constpow(IM x, IM y) -> IM
constpow(DM x, DM y) -> DM
constpow(SX x, SX y) -> SX
constpow(MX x, MX y) -> MX

copysign(*args)
copysign(float x, float y) -> float
copysign(IM x, IM y) -> IM
copysign(DM x, DM y) -> DM
copysign(SX x, SX y) -> SX
copysign(MX x, MX y) -> MX

cos(*args)
cos(float x) -> float
cos(IM x) -> IM
cos(DM x) -> DM
cos(SX x) -> SX
cos(MX x) -> MX

cosh(*args)
cosh(float x) -> float
cosh(IM x) -> IM
cosh(DM x) -> DM
cosh(SX x) -> SX
cosh(MX x) -> MX

cross(*args)
Matlab’s cross command.
cross(IM a, IM b, int dim) -> IM
cross(DM a, DM b, int dim) -> DM
cross(SX a, SX b, int dim) -> SX
cross(MX a, MX b, int dim) -> MX

cumsum(*args)
Returns cumulative sum along given axis (MATLAB convention)
cumsum(IM A, int axis) -> IM
cumsum(DM A, int axis) -> DM
cumsum(SX A, int axis) -> SX
cumsum(MX A, int axis) -> MX

densify(*args)
Make the matrix dense and assign nonzeros to a value.
densify(IM x) -> IM
densify(DM x) -> DM
densify(SX x) -> SX
densify(MX x) -> MX

depends_on(*args)
Check if expression depends on the argument The argument must be symbolic.
depends_on(IM f, IM arg) -> bool
depends_on(DM f, DM arg) -> bool
depends_on(SX f, SX arg) -> bool
depends_on(MX f, MX arg) -> bool

det(*args)
Matrix determinant (experimental)
det(IM A) -> IM
det(DM A) -> DM
det(SX A) -> SX
det(MX A) -> MX

diag(*args)
Create diagonal sparsity pattern.
diag(IM A) -> IM
diag(DM A) -> DM
diag(SX A) -> SX
diag(MX A) -> MX

diagsplit(*args)
diagsplit(Sparsity x, int incr) -> [Sparsity]
diagsplit(DM x, int incr) -> [DM]
diagsplit(SX x, int incr) -> [SX]
diagsplit(MX x, int incr) -> [MX]
diagsplit(Sparsity x, [int] output_offset) -> [Sparsity]
diagsplit(DM x, [int] output_offset) -> [DM]
diagsplit(SX x, [int] output_offset) -> [SX]
diagsplit(MX x, [int] output_offset) -> [MX]
diagsplit(Sparsity x, int incr1, int incr2) -> [Sparsity]
diagsplit(Sparsity x, [int] output_offset1, [int] output_offset2) -> [Sparsity]
diagsplit(DM x, int incr1, int incr2) -> [DM]
diagsplit(DM x, [int] output_offset1, [int] output_offset2) -> [DM]
diagsplit(SX x, int incr1, int incr2) -> [SX]
diagsplit(SX x, [int] output_offset1, [int] output_offset2) -> [SX]
diagsplit(MX x, int incr1, int incr2) -> [MX]
diagsplit(MX x, [int] output_offset1, [int] output_offset2) -> [MX]

diff(*args)
Returns difference (n-th order) along given axis (MATLAB convention)
diff(IM A, int n, int axis) -> IM
diff(DM A, int n, int axis) -> DM
diff(SX A, int n, int axis) -> SX
diff(MX A, int n, int axis) -> MX

dot(*args)
Inner product of two matrices with x and y matrices of the same dimension.
dot(IM x, IM y) -> IM
dot(DM x, DM y) -> DM
dot(SX x, SX y) -> SX
dot(MX x, MX y) -> MX

eig_symbolic(*args)
Attempts to find the eigenvalues of a symbolic matrix This will only work
eig_symbolic(IM m) -> IM
eig_symbolic(DM m) -> DM
eig_symbolic(SX m) -> SX


for up to 3x3 matrices.

einstein(*args)
Computes an einstein dense tensor contraction.
einstein(IM A, IM B, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> IM
einstein(DM A, DM B, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> DM
einstein(SX A, SX B, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> SX
einstein(MX A, MX B, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> MX
einstein(IM A, IM B, IM C, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> IM
einstein(DM A, DM B, DM C, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> DM
einstein(SX A, SX B, SX C, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> SX
einstein(MX A, MX B, MX C, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> MX


Computes the product: C_c = A_a + B_b where a b c are index/einstein notation in an encoded form

For example, an matrix-matrix product may be written as: C_ij = A_ik B_kj

The encoded form uses strictly negative numbers to indicate labels. For the above example, we would have: a {-1, -3} b {-3, -2} c {-1 -2}

eq(*args)
eq(float x, float y) -> float
eq(IM x, IM y) -> IM
eq(DM x, DM y) -> DM
eq(SX x, SX y) -> SX
eq(MX x, MX y) -> MX

erf(*args)
erf(float x) -> float
erf(IM x) -> IM
erf(DM x) -> DM
erf(SX x) -> SX
erf(MX x) -> MX

erfinv(*args)
erfinv(float x) -> float
erfinv(IM x) -> IM
erfinv(DM x) -> DM
erfinv(SX x) -> SX
erfinv(MX x) -> MX

evalf(*args)
Evaluates the expression numerically.
evalf(IM x) -> DM
evalf(DM x) -> DM
evalf(SX x) -> DM
evalf(MX x) -> DM


An error is raised when the expression contains symbols

exp(*args)
exp(float x) -> float
exp(IM x) -> IM
exp(DM x) -> DM
exp(SX x) -> SX
exp(MX x) -> MX

expand(*args)
Expand the expression as a weighted sum (with constant weights)
expand(IM ex) -> (IM OUTPUT1, IM OUTPUT2)
expand(DM ex) -> (DM OUTPUT1, DM OUTPUT2)
expand(SX ex) -> (SX OUTPUT1, SX OUTPUT2)

expm(*args)
expm(IM A) -> IM
expm(DM A) -> DM
expm(SX A) -> SX
expm(MX A) -> MX

expm_const(*args)
expm_const(IM A, IM t) -> IM
expm_const(DM A, DM t) -> DM
expm_const(SX A, SX t) -> SX
expm_const(MX A, MX t) -> MX

find(*args)
Get the location of all non-zero elements as they would appear in a Dense
find(MX x) -> MX


matrix A : DenseMatrix 4 x 3 B : SparseMatrix 4 x 3 , 5 structural non- zeros.

k = A.find() A[k] will contain the elements of A that are non-zero in B

Inverse of nonzeros.

floor(*args)
floor(float x) -> float
floor(IM x) -> IM
floor(DM x) -> DM
floor(SX x) -> SX
floor(MX x) -> MX

fmax(*args)
fmax(float x, float y) -> float
fmax(IM x, IM y) -> IM
fmax(DM x, DM y) -> DM
fmax(SX x, SX y) -> SX
fmax(MX x, MX y) -> MX

fmin(*args)
fmin(float x, float y) -> float
fmin(IM x, IM y) -> IM
fmin(DM x, DM y) -> DM
fmin(SX x, SX y) -> SX
fmin(MX x, MX y) -> MX

gauss_quadrature(*args)
gauss_quadrature(IM f, IM x, IM a, IM b, int order) -> IM
gauss_quadrature(DM f, DM x, DM a, DM b, int order) -> DM
gauss_quadrature(SX f, SX x, SX a, SX b, int order) -> SX
gauss_quadrature(IM f, IM x, IM a, IM b, int order, IM w) -> IM
gauss_quadrature(DM f, DM x, DM a, DM b, int order, DM w) -> DM
gauss_quadrature(SX f, SX x, SX a, SX b, int order, SX w) -> SX

ge(*args)
ge(float x, float y) -> float
ge(IM x, IM y) -> IM
ge(DM x, DM y) -> DM
ge(SX x, SX y) -> SX
ge(MX x, MX y) -> MX

gradient(*args)
Calculate Jacobian.
gradient(IM ex, IM arg) -> IM
gradient(DM ex, DM arg) -> DM
gradient(SX ex, SX arg) -> SX
gradient(MX ex, MX arg) -> MX

graph_substitute(*args)
Substitute multiple expressions in graph Substitute variable var with
graph_substitute(MX ex, [MX] v, [MX] vdef) -> MX
graph_substitute([MX] ex, [MX] v, [MX] vdef) -> [MX]


expression expr in multiple expressions, preserving nodes.

gt(*args)
gt(float x, float y) -> float
gt(IM x, IM y) -> IM
gt(DM x, DM y) -> DM
gt(SX x, SX y) -> SX
gt(MX x, MX y) -> MX

heaviside(*args)
Heaviside function.
heaviside(IM x) -> IM
heaviside(DM x) -> DM
heaviside(SX x) -> SX


[ begin {cases} H(x) = 0 & x<0 \ H(x) = 1/2 & x=0 \ H(x) = 1 & x>0 \ end {cases} ]

hessian(*args)
hessian(IM ex, IM arg) -> (IM , IM OUTPUT1)
hessian(DM ex, DM arg) -> (DM , DM OUTPUT1)
hessian(SX ex, SX arg) -> (SX , SX OUTPUT1)
hessian(MX ex, MX arg) -> (MX , MX OUTPUT1)

horzsplit(*args)
horzsplit(Sparsity v, int incr) -> [Sparsity]
horzsplit(DM v, int incr) -> [DM]
horzsplit(SX v, int incr) -> [SX]
horzsplit(MX v, int incr) -> [MX]
horzsplit(Sparsity v, [int] offset) -> [Sparsity]
horzsplit(DM v, [int] offset) -> [DM]
horzsplit(SX v, [int] offset) -> [SX]
horzsplit(MX v, [int] offset) -> [MX]

if_else(*args)
Branching on MX nodes Ternary operator, “cond ? if_true : if_false”.
if_else(IM cond, IM if_true, IM if_false, bool short_circuit) -> IM
if_else(DM cond, DM if_true, DM if_false, bool short_circuit) -> DM
if_else(SX cond, SX if_true, SX if_false, bool short_circuit) -> SX
if_else(MX cond, MX if_true, MX if_false, bool short_circuit) -> MX

interp1d(*args)
Performs 1d linear interpolation.
interp1d([float] x, IM v, [float] xq, str mode, bool equidistant) -> IM
interp1d([float] x, DM v, [float] xq, str mode, bool equidistant) -> DM
interp1d([float] x, SX v, [float] xq, str mode, bool equidistant) -> SX
interp1d([float] x, MX v, [float] xq, str mode, bool equidistant) -> MX


The data-points to be interpolated are given as (x[i], v[i]). xq[j] is used as interplating value

inv(*args)
Matrix inverse.
inv(IM A) -> IM
inv(DM A) -> DM
inv(SX A) -> SX
inv(MX A) -> MX
inv(IM A, str lsolver, dict opts) -> IM
inv(DM A, str lsolver, dict opts) -> DM
inv(SX A, str lsolver, dict opts) -> SX
inv(MX A, str lsolver, dict opts) -> MX

inv_minor(*args)
Matrix inverse (experimental)
inv_minor(IM A) -> IM
inv_minor(DM A) -> DM
inv_minor(SX A) -> SX
inv_minor(MX A) -> MX

inv_node(*args)
Inverse node.
inv_node(MX x) -> MX

inv_skew(*args)
Generate the 3-vector progenitor of a skew symmetric matrix.
inv_skew(IM a) -> IM
inv_skew(DM a) -> DM
inv_skew(SX a) -> SX
inv_skew(MX a) -> MX

is_equal(*args)
is_equal(float x, float y, int depth) -> bool
is_equal(IM x, IM y, int depth) -> bool
is_equal(DM x, DM y, int depth) -> bool
is_equal(SX x, SX y, int depth) -> bool
is_equal(MX x, MX y, int depth) -> bool

is_linear(*args)
Is expr linear in var?
is_linear(IM expr, IM var) -> bool
is_linear(DM expr, DM var) -> bool
is_linear(SX expr, SX var) -> bool
is_linear(MX expr, MX var) -> bool


False negatives are possible (an expression may not be recognised as linear while it really is), false positives not.

is_quadratic(*args)
is_quadratic(IM expr, IM var) -> bool
is_quadratic(DM expr, DM var) -> bool
is_quadratic(SX expr, SX var) -> bool
is_quadratic(MX expr, MX var) -> bool


False negatives are possible (an expression may not be recognised as quadratic while it really is), false positives not.

jacobian(*args)
Calculate Jacobian.
jacobian(IM ex, IM arg, dict opts) -> IM
jacobian(DM ex, DM arg, dict opts) -> DM
jacobian(SX ex, SX arg, dict opts) -> SX
jacobian(MX ex, MX arg, dict opts) -> MX

jtimes(*args)
Calculate the Jacobian and multiply by a vector from the right This is
jtimes(IM ex, IM arg, IM v, bool tr) -> IM
jtimes(DM ex, DM arg, DM v, bool tr) -> DM
jtimes(SX ex, SX arg, SX v, bool tr) -> SX
jtimes(MX ex, MX arg, MX v, bool tr) -> MX


equivalent to mul(jacobian(ex, arg), v) or mul(jacobian(ex, arg).T, v) for tr set to false and true respectively. If contrast to these expressions, it will use directional derivatives which is typically (but not necessarily) more efficient if the complete Jacobian is not needed and v has few rows.

kron(*args)
kron(Sparsity a, Sparsity b) -> Sparsity
kron(IM a, IM b) -> IM
kron(DM a, DM b) -> DM
kron(SX a, SX b) -> SX
kron(MX a, MX b) -> MX

ldivide(*args)
ldivide(float x, float y) -> float
ldivide(IM x, IM y) -> IM
ldivide(DM x, DM y) -> DM
ldivide(SX x, SX y) -> SX
ldivide(MX x, MX y) -> MX

ldl(*args)
Symbolic LDL factorization Returns the sparsity pattern of L^T.
ldl(IM A, bool amd) -> (IM OUTPUT1, IM OUTPUT2, [int] OUTPUT3)
ldl(DM A, bool amd) -> (DM OUTPUT1, DM OUTPUT2, [int] OUTPUT3)
ldl(SX A, bool amd) -> (SX OUTPUT1, SX OUTPUT2, [int] OUTPUT3)


The implementation is a modified version of LDL Copyright(c) Timothy A. Davis, 2005-2013 Licensed as a derivative work under the GNU LGPL

ldl_solve(*args)
Solve using a sparse LDL^T factorization.
ldl_solve(IM b, IM D, IM LT, [int] p) -> IM
ldl_solve(DM b, DM D, DM LT, [int] p) -> DM
ldl_solve(SX b, SX D, SX LT, [int] p) -> SX

le(*args)
le(float x, float y) -> float
le(IM x, IM y) -> IM
le(DM x, DM y) -> DM
le(SX x, SX y) -> SX
le(MX x, MX y) -> MX

linear_coeff(*args)
Recognizes linear form in vector expression.
linear_coeff(IM ex, IM arg) -> (IM OUTPUT1, IM OUTPUT2)
linear_coeff(DM ex, DM arg) -> (DM OUTPUT1, DM OUTPUT2)
linear_coeff(SX ex, SX arg) -> (SX OUTPUT1, SX OUTPUT2)
linear_coeff(MX ex, MX arg) -> (MX OUTPUT1, MX OUTPUT2)


A x + b

linearize(*args)
Linearize an expression.
linearize(IM f, IM x, IM x0) -> IM
linearize(DM f, DM x, DM x0) -> DM
linearize(SX f, SX x, SX x0) -> SX
linearize(MX f, MX x, MX x0) -> MX

linspace(*args)
Matlab’s linspace command.
linspace(IM a, IM b, int nsteps) -> IM
linspace(DM a, DM b, int nsteps) -> DM
linspace(SX a, SX b, int nsteps) -> SX
linspace(MX a, MX b, int nsteps) -> MX

log(*args)
log(float x) -> float
log(IM x) -> IM
log(DM x) -> DM
log(SX x) -> SX
log(MX x) -> MX

log10(*args)
log10(float x) -> float
log10(IM x) -> IM
log10(DM x) -> DM
log10(SX x) -> SX
log10(MX x) -> MX

lt(*args)
lt(float x, float y) -> float
lt(IM x, IM y) -> IM
lt(DM x, DM y) -> DM
lt(SX x, SX y) -> SX
lt(MX x, MX y) -> MX

mac(*args)
mac(Sparsity X, Sparsity Y, Sparsity Z) -> Sparsity
mac(IM X, IM Y, IM Z) -> IM
mac(DM X, DM Y, DM Z) -> DM
mac(SX X, SX Y, SX Z) -> SX
mac(MX X, MX Y, MX Z) -> MX

matrix_expand(*args)
Expand MX graph to SXFunction call.
matrix_expand(MX e, [MX] boundary, dict options) -> MX
matrix_expand([MX] e, [MX] boundary, dict options) -> [MX]


Expand the given expression e, optionally supplying expressions contained in it at which expansion should stop.

minor(*args)
Get the (i,j) minor matrix.
minor(IM x, int i, int j) -> IM
minor(DM x, int i, int j) -> DM
minor(SX x, int i, int j) -> SX

minus(*args)
minus(float x, float y) -> float
minus(IM x, IM y) -> IM
minus(DM x, DM y) -> DM
minus(SX x, SX y) -> SX
minus(MX x, MX y) -> MX

mldivide(*args)
Matrix divide (cf. backslash ‘’ in MATLAB)
mldivide(IM x, IM y) -> IM
mldivide(DM x, DM y) -> DM
mldivide(SX x, SX y) -> SX
mldivide(MX x, MX y) -> MX

mmax(*args)
Largest element in a matrix.
mmax(IM x) -> IM
mmax(DM x) -> DM
mmax(SX x) -> SX
mmax(MX x) -> MX

mmin(*args)
Smallest element in a matrix.
mmin(IM x) -> IM
mmin(DM x) -> DM
mmin(SX x) -> SX
mmin(MX x) -> MX

mod(*args)
mod(float x, float y) -> float
mod(IM x, IM y) -> IM
mod(DM x, DM y) -> DM
mod(SX x, SX y) -> SX
mod(MX x, MX y) -> MX

mpower(*args)
Matrix power x^n.
mpower(IM x, IM n) -> IM
mpower(DM x, DM n) -> DM
mpower(SX x, SX n) -> SX
mpower(MX x, MX n) -> MX

mrdivide(*args)
Matrix divide (cf. slash ‘/’ in MATLAB)
mrdivide(IM x, IM y) -> IM
mrdivide(DM x, DM y) -> DM
mrdivide(SX x, SX y) -> SX
mrdivide(MX x, MX y) -> MX

mtaylor(*args)
multivariate Taylor series expansion
mtaylor(IM ex, IM x, IM a, int order) -> IM
mtaylor(DM ex, DM x, DM a, int order) -> DM
mtaylor(SX ex, SX x, SX a, int order) -> SX
mtaylor(IM ex, IM x, IM a, int order, [int] order_contributions) -> IM
mtaylor(DM ex, DM x, DM a, int order, [int] order_contributions) -> DM
mtaylor(SX ex, SX x, SX a, int order, [int] order_contributions) -> SX


Do Taylor expansions until the aggregated order of a term is equal to ‘order’. The aggregated order of $x^n y^m$ equals $n+m$.

The argument order_contributions can denote how match each variable contributes to the aggregated order. If x=[x, y] and order_contributions=[1, 2], then the aggregated order of $x^n y^m$ equals $1n+2m$.

Example usage

$sin(b+a)+cos(b+a)(x-a)+cos(b+a)(y-b)$ $y+x-(x^3+3y x^2+3 y^2 x+y^3)/6$ $(-3 x^2 y-x^3)/6+y+x$

mtimes(*args)
mtimes([Sparsity] args) -> Sparsity
mtimes([IM] args) -> IM
mtimes([DM] args) -> DM
mtimes([SX] args) -> SX
mtimes([MX] args) -> MX
mtimes(Sparsity x, Sparsity y) -> Sparsity
mtimes(IM x, IM y) -> IM
mtimes(DM x, DM y) -> DM
mtimes(SX x, SX y) -> SX
mtimes(MX x, MX y) -> MX

ne(*args)
ne(float x, float y) -> float
ne(IM x, IM y) -> IM
ne(DM x, DM y) -> DM
ne(SX x, SX y) -> SX
ne(MX x, MX y) -> MX

n_nodes(*args)
n_nodes(IM A) -> int
n_nodes(DM A) -> int
n_nodes(SX A) -> int
n_nodes(MX A) -> int

norm_0_mul(*args)
norm_0_mul(Sparsity x, Sparsity y) -> int
norm_0_mul(IM x, IM y) -> int
norm_0_mul(DM x, DM y) -> int
norm_0_mul(SX x, SX y) -> int
norm_0_mul(MX x, MX y) -> int

norm_1(*args)
1-norm
norm_1(IM x) -> IM
norm_1(DM x) -> DM
norm_1(SX x) -> SX
norm_1(MX x) -> MX

norm_2(*args)
2-norm
norm_2(IM x) -> IM
norm_2(DM x) -> DM
norm_2(SX x) -> SX
norm_2(MX x) -> MX

norm_fro(*args)
Frobenius norm.
norm_fro(IM x) -> IM
norm_fro(DM x) -> DM
norm_fro(SX x) -> SX
norm_fro(MX x) -> MX

norm_inf(*args)
Infinity-norm.
norm_inf(IM x) -> IM
norm_inf(DM x) -> DM
norm_inf(SX x) -> SX
norm_inf(MX x) -> MX

norm_inf_mul(*args)
Inf-norm of a Matrix-Matrix product.
norm_inf_mul(IM x, IM y) -> IM
norm_inf_mul(DM x, DM y) -> DM
norm_inf_mul(SX x, SX y) -> SX

nullspace(*args)
Computes the nullspace of a matrix A.
nullspace(IM A) -> IM
nullspace(DM A) -> DM
nullspace(SX A) -> SX
nullspace(MX A) -> MX


Finds Z m-by-(m-n) such that AZ = 0 with A n-by-m with m > n

Assumes A is full rank

Inspired by Numerical Methods in Scientific Computing by Ake Bjorck

pinv(*args)
Computes the Moore-Penrose pseudo-inverse.
pinv(IM A) -> IM
pinv(DM A) -> DM
pinv(SX A) -> SX
pinv(MX A) -> MX
pinv(IM A, str lsolver, dict opts) -> IM
pinv(DM A, str lsolver, dict opts) -> DM
pinv(SX A, str lsolver, dict opts) -> SX
pinv(MX A, str lsolver, dict opts) -> MX


If the matrix A is fat (size1>size2), mul(A, pinv(A)) is unity. If the matrix A is slender (size2<size1), mul(pinv(A), A) is unity.

plus(*args)
plus(float x, float y) -> float
plus(IM x, IM y) -> IM
plus(DM x, DM y) -> DM
plus(SX x, SX y) -> SX
plus(MX x, MX y) -> MX

poly_coeff(*args)
extracts polynomial coefficients from an expression
poly_coeff(IM ex, IM x) -> IM
poly_coeff(DM ex, DM x) -> DM
poly_coeff(SX ex, SX x) -> SX


ex: Scalar expression that represents a polynomial

x: Scalar symbol that the polynomial is build up with

poly_roots(*args)
Attempts to find the roots of a polynomial.
poly_roots(IM p) -> IM
poly_roots(DM p) -> DM
poly_roots(SX p) -> SX


This will only work for polynomials up to order 3 It is assumed that the roots are real.

polyval(*args)
Evaluate a polynomial with coefficients p in x.
polyval(IM p, IM x) -> IM
polyval(DM p, DM x) -> DM
polyval(SX p, SX x) -> SX
polyval(MX p, MX x) -> MX

power(*args)
power(float x, float n) -> float
power(IM x, IM n) -> IM
power(DM x, DM n) -> DM
power(SX x, SX n) -> SX
power(MX x, MX n) -> MX

print_operator(*args)
Get a string representation for a binary MatType, using custom arguments.
print_operator(IM xb, [str] args) -> str
print_operator(DM xb, [str] args) -> str
print_operator(SX xb, [str] args) -> str
print_operator(MX xb, [str] args) -> str

project(*args)
Create a new matrix with a given sparsity pattern but with the nonzeros
project(IM A, Sparsity sp, bool intersect) -> IM
project(DM A, Sparsity sp, bool intersect) -> DM
project(SX A, Sparsity sp, bool intersect) -> SX
project(MX A, Sparsity sp, bool intersect) -> MX


taken from an existing matrix.

pw_const(*args)
Create a piecewise constant function Create a piecewise constant function
pw_const(IM t, IM tval, IM val) -> IM
pw_const(DM t, DM tval, DM val) -> DM
pw_const(SX t, SX tval, SX val) -> SX


with n=val.size() intervals.

Inputs:

t: a scalar variable (e.g. time)

tval: vector with the discrete values of t at the interval transitions (length n-1)

val: vector with the value of the function for each interval (length n)

pw_lin(*args)
t a scalar variable (e.g. time)
pw_lin(IM t, IM tval, IM val) -> IM
pw_lin(DM t, DM tval, DM val) -> DM
pw_lin(SX t, SX tval, SX val) -> SX


Create a piecewise linear function Create a piecewise linear function:

Inputs: tval vector with the the discrete values of t (monotonically increasing) val vector with the corresponding function values (same length as tval)

qr(*args)
QR factorization using the modified Gram-Schmidt algorithm More stable than
qr(IM A) -> (IM OUTPUT1, IM OUTPUT2)
qr(DM A) -> (DM OUTPUT1, DM OUTPUT2)
qr(SX A) -> (SX OUTPUT1, SX OUTPUT2)


the classical Gram-Schmidt, but may break down if the rows of A are nearly linearly dependent See J. Demmel: Applied Numerical Linear Algebra (algorithm 3.1.). Note that in SWIG, Q and R are returned by value.

qr_solve(*args)
Solve using a sparse QR factorization.
qr_solve(IM b, IM v, IM r, IM beta, [int] prinv, [int] pc, bool tr) -> IM
qr_solve(DM b, DM v, DM r, DM beta, [int] prinv, [int] pc, bool tr) -> DM
qr_solve(SX b, SX v, SX r, SX beta, [int] prinv, [int] pc, bool tr) -> SX

qr_sparse(*args)
Symbolic QR factorization Returns the sparsity pattern of V (compact
qr_sparse(IM A, bool amd) -> (IM OUTPUT1, IM OUTPUT2, IM OUTPUT3, [int] OUTPUT4, [int] OUTPUT5)
qr_sparse(DM A, bool amd) -> (DM OUTPUT1, DM OUTPUT2, DM OUTPUT3, [int] OUTPUT4, [int] OUTPUT5)
qr_sparse(SX A, bool amd) -> (SX OUTPUT1, SX OUTPUT2, SX OUTPUT3, [int] OUTPUT4, [int] OUTPUT5)


representation of Q) and R as well as vectors needed for the numerical factorization and solution. The implementation is a modified version of CSparse Copyright(c) Timothy A. Davis, 2006-2009 Licensed as a derivative work under the GNU LGPL.

quadratic_coeff(*args)
Recognizes quadratic form in scalar expression.
quadratic_coeff(IM ex, IM arg) -> (IM OUTPUT1, IM OUTPUT2, IM OUTPUT3)
quadratic_coeff(DM ex, DM arg) -> (DM OUTPUT1, DM OUTPUT2, DM OUTPUT3)
quadratic_coeff(SX ex, SX arg) -> (SX OUTPUT1, SX OUTPUT2, SX OUTPUT3)
quadratic_coeff(MX ex, MX arg) -> (MX OUTPUT1, MX OUTPUT2, MX OUTPUT3)


1/2*x’ A x + b’ x + c

e = 0.5*bilin(A,x,x)+dot(b,x)+c

ramp(*args)
ramp function
ramp(IM x) -> IM
ramp(DM x) -> DM
ramp(SX x) -> SX


[ begin {cases} R(x) = 0 & x <= 1 \ R(x) = x & x > 1 \ end {cases} ]

Also called: slope function

rank1(*args)
Make a rank-1 update to a matrix A Calculates A + 1/2 * alpha * x*y’.
rank1(IM A, IM alpha, IM x, IM y) -> IM
rank1(DM A, DM alpha, DM x, DM y) -> DM
rank1(SX A, SX alpha, SX x, SX y) -> SX
rank1(MX A, MX alpha, MX x, MX y) -> MX

rdivide(*args)
rdivide(float x, float y) -> float
rdivide(IM x, IM y) -> IM
rdivide(DM x, DM y) -> DM
rdivide(SX x, SX y) -> SX
rdivide(MX x, MX y) -> MX

rectangle(*args)
rectangle function
rectangle(IM x) -> IM
rectangle(DM x) -> DM
rectangle(SX x) -> SX


[ begin {cases} Pi(x) = 1 & |x| < 1/2 \ Pi(x) = 1/2 & |x| = 1/2 \ Pi(x) = 0 & |x| > 1/2 \ end {cases} ]

Also called: gate function, block function, band function, pulse function, window function

repmat(*args)
repmat(Sparsity A, int n, int m) -> Sparsity
repmat(Sparsity A, (int,int) rc) -> Sparsity
repmat(IM A, int n, int m) -> IM
repmat(IM A, (int,int) rc) -> IM
repmat(DM A, int n, int m) -> DM
repmat(DM A, (int,int) rc) -> DM
repmat(SX A, int n, int m) -> SX
repmat(SX A, (int,int) rc) -> SX
repmat(MX A, int n, int m) -> MX
repmat(MX A, (int,int) rc) -> MX

repsum(*args)
Given a repeated matrix, computes the sum of repeated parts.
repsum(IM A, int n, int m) -> IM
repsum(DM A, int n, int m) -> DM
repsum(SX A, int n, int m) -> SX
repsum(MX A, int n, int m) -> MX

reshape(*args)
reshape(Sparsity a, (int,int) rc) -> Sparsity
reshape(Sparsity a, Sparsity sp) -> Sparsity
reshape(IM a, (int,int) rc) -> IM
reshape(IM a, Sparsity sp) -> IM
reshape(DM a, (int,int) rc) -> DM
reshape(DM a, Sparsity sp) -> DM
reshape(SX a, (int,int) rc) -> SX
reshape(SX a, Sparsity sp) -> SX
reshape(MX a, (int,int) rc) -> MX
reshape(MX a, Sparsity sp) -> MX
reshape(Sparsity a, int nrow, int ncol) -> Sparsity
reshape(IM a, int nrow, int ncol) -> IM
reshape(DM a, int nrow, int ncol) -> DM
reshape(SX a, int nrow, int ncol) -> SX
reshape(MX a, int nrow, int ncol) -> MX

shared(*args)
Get a shared (owning) reference.
shared([IM] ex, str v_prefix, str v_suffix) -> ([IM] OUTPUT1, [IM] OUTPUT2, [IM] OUTPUT3)
shared([DM] ex, str v_prefix, str v_suffix) -> ([DM] OUTPUT1, [DM] OUTPUT2, [DM] OUTPUT3)
shared([SX] ex, str v_prefix, str v_suffix) -> ([SX] OUTPUT1, [SX] OUTPUT2, [SX] OUTPUT3)
shared([MX] ex, str v_prefix, str v_suffix) -> ([MX] OUTPUT1, [MX] OUTPUT2, [MX] OUTPUT3)

sign(*args)
sign(float x) -> float
sign(IM x) -> IM
sign(DM x) -> DM
sign(SX x) -> SX
sign(MX x) -> MX

simplify(*args)
Simplify an expression.
simplify(float x) -> float
simplify(IM x) -> IM
simplify(DM x) -> DM
simplify(SX x) -> SX
simplify(MX x) -> MX

sin(*args)
sin(float x) -> float
sin(IM x) -> IM
sin(DM x) -> DM
sin(SX x) -> SX
sin(MX x) -> MX

sinh(*args)
sinh(float x) -> float
sinh(IM x) -> IM
sinh(DM x) -> DM
sinh(SX x) -> SX
sinh(MX x) -> MX

skew(*args)
Generate a skew symmetric matrix from a 3-vector.
skew(IM a) -> IM
skew(DM a) -> DM
skew(SX a) -> SX
skew(MX a) -> MX

soc(*args)
Construct second-order-convex.
soc(IM x, IM y) -> IM
soc(DM x, DM y) -> DM
soc(SX x, SX y) -> SX
soc(MX x, MX y) -> MX


x: vector expression of size n

y: scalar expression

soc(x,y) computes [y*eye(n) x; x’ y]

soc(x,y) positive semi definite <=> || x ||_2 <= y

solve(*args)
Crunch the numbers; solve the problem.
solve(IM A, IM b) -> IM
solve(DM A, DM b) -> DM
solve(SX A, SX b) -> SX
solve(MX A, MX b) -> MX
solve(IM A, IM b, str lsolver, dict opts) -> IM
solve(DM A, DM b, str lsolver, dict opts) -> DM
solve(SX A, SX b, str lsolver, dict opts) -> SX
solve(MX A, MX b, str lsolver, dict opts) -> MX

sparsify(*args)
Make a matrix sparse by removing numerical zeros.
sparsify(IM A, float tol) -> IM
sparsify(DM A, float tol) -> DM
sparsify(SX A, float tol) -> SX

sprank(*args)
sprank(Sparsity A) -> int
sprank(IM A) -> int
sprank(DM A) -> int
sprank(SX A) -> int
sprank(MX A) -> int

sqrt(*args)
sqrt(float x) -> float
sqrt(IM x) -> IM
sqrt(DM x) -> DM
sqrt(SX x) -> SX
sqrt(MX x) -> MX

substitute(*args)
Substitute variable var with expression expr in multiple expressions.
substitute(IM ex, IM v, IM vdef) -> IM
substitute(DM ex, DM v, DM vdef) -> DM
substitute([DM] ex, [DM] v, [DM] vdef) -> [DM]
substitute(SX ex, SX v, SX vdef) -> SX
substitute([SX] ex, [SX] v, [SX] vdef) -> [SX]
substitute(MX ex, MX v, MX vdef) -> MX
substitute([MX] ex, [MX] v, [MX] vdef) -> [MX]

substitute_inplace(*args)
Inplace substitution with piggyback expressions Substitute variables v out
substitute_inplace([IM] v, bool reverse) -> ([IM] INOUT1, [IM] INOUT2)
substitute_inplace([DM] v, bool reverse) -> ([DM] INOUT1, [DM] INOUT2)
substitute_inplace([SX] v, bool reverse) -> ([SX] INOUT1, [SX] INOUT2)
substitute_inplace([MX] v, bool reverse) -> ([MX] INOUT1, [MX] INOUT2)


of the expressions vdef sequentially, as well as out of a number of other expressions piggyback.

sum1(*args)
sum1(Sparsity x) -> Sparsity
sum1(IM x) -> IM
sum1(DM x) -> DM
sum1(SX x) -> SX
sum1(MX x) -> MX

sum2(*args)
sum2(Sparsity x) -> Sparsity
sum2(IM x) -> IM
sum2(DM x) -> DM
sum2(SX x) -> SX
sum2(MX x) -> MX

sumsqr(*args)
Calculate sum of squares: sum_ij X_ij^2.
sumsqr(IM X) -> IM
sumsqr(DM X) -> DM
sumsqr(SX X) -> SX
sumsqr(MX X) -> MX

symvar(*args)
Get symbols present in expression.
symvar(IM x) -> std::vector< casadi::Matrix< casadi_int >,std::allocator< casadi::Matrix< casadi_int > > >
symvar(DM x) -> [DM]
symvar(SX x) -> [SX]
symvar(MX x) -> [MX]


Returned vector is ordered according to the order of variable()/parameter() calls used to create the variables

tan(*args)
tan(float x) -> float
tan(IM x) -> IM
tan(DM x) -> DM
tan(SX x) -> SX
tan(MX x) -> MX

tangent(*args)
Calculate Jacobian.
tangent(IM ex, IM arg) -> IM
tangent(DM ex, DM arg) -> DM
tangent(SX ex, SX arg) -> SX
tangent(MX ex, MX arg) -> MX

tanh(*args)
tanh(float x) -> float
tanh(IM x) -> IM
tanh(DM x) -> DM
tanh(SX x) -> SX
tanh(MX x) -> MX

taylor(*args)
univariate Taylor series expansion
taylor(IM ex, IM x, IM a, int order) -> IM
taylor(DM ex, DM x, DM a, int order) -> DM
taylor(SX ex, SX x, SX a, int order) -> SX


Calculate the Taylor expansion of expression ‘ex’ up to order ‘order’ with respect to variable ‘x’ around the point ‘a’

$(x)=f(a)+f’(a)(x-a)+f’‘(a)frac {(x-a)^2}{2!}+f’‘’(a)frac{(x-a)^3}{3!}+ldots$

Example usage:

>>   x

times(*args)
times(float x, float y) -> float
times(IM x, IM y) -> IM
times(DM x, DM y) -> DM
times(SX x, SX y) -> SX
times(MX x, MX y) -> MX

trace(*args)
Matrix trace.
trace(IM a) -> IM
trace(DM a) -> DM
trace(SX a) -> SX
trace(MX a) -> MX

transpose(*args)
Transpose the matrix and get the reordering of the non-zero entries.
transpose(Sparsity X) -> Sparsity
transpose(IM X) -> IM
transpose(DM X) -> DM
transpose(SX X) -> SX
transpose(MX X) -> MX


mapping: the non-zeros of the original matrix for each non-zero of the new matrix

triangle(*args)
triangle function
triangle(IM x) -> IM
triangle(DM x) -> DM
triangle(SX x) -> SX


[ begin {cases} Lambda(x) = 0 & |x| >= 1 \ Lambda(x) = 1-|x| & |x| < 1 end {cases} ]

tril(*args)
tril(Sparsity a, bool includeDiagonal) -> Sparsity
tril(IM a, bool includeDiagonal) -> IM
tril(DM a, bool includeDiagonal) -> DM
tril(SX a, bool includeDiagonal) -> SX
tril(MX a, bool includeDiagonal) -> MX

tril2symm(*args)
Convert a lower triangular matrix to a symmetric one.
tril2symm(IM a) -> IM
tril2symm(DM a) -> DM
tril2symm(SX a) -> SX
tril2symm(MX a) -> MX

triu(*args)
triu(Sparsity a, bool includeDiagonal) -> Sparsity
triu(IM a, bool includeDiagonal) -> IM
triu(DM a, bool includeDiagonal) -> DM
triu(SX a, bool includeDiagonal) -> SX
triu(MX a, bool includeDiagonal) -> MX

triu2symm(*args)
Convert a upper triangular matrix to a symmetric one.
triu2symm(IM a) -> IM
triu2symm(DM a) -> DM
triu2symm(SX a) -> SX
triu2symm(MX a) -> MX

unite(*args)
Union of two sparsity patterns.
unite(IM A, IM B) -> IM
unite(DM A, DM B) -> DM
unite(SX A, SX B) -> SX
unite(MX A, MX B) -> MX

vec(*args)
vec(Sparsity a) -> Sparsity
vec(IM a) -> IM
vec(DM a) -> DM
vec(SX a) -> SX
vec(MX a) -> MX

which_depends(*args)
Find out which variables enter with some order.
which_depends(IM expr, IM var, int order, bool tr) -> [bool]
which_depends(DM expr, DM var, int order, bool tr) -> [bool]
which_depends(SX expr, SX var, int order, bool tr) -> [bool]
which_depends(MX expr, MX var, int order, bool tr) -> [bool]


## 2. Classes¶

### 2.1. DM¶

class DM(*args)
assign(*args)
assign(self, DM rhs)

static binary(*args)
binary(int op, DM x, DM y) -> DM

clear(*args)
clear(self)

dep(*args)
dep(self, int ch) -> DM

static deserialize(*args)
deserialize(std::istream & istream) -> DM
deserialize(str s) -> DM

disp(*args)
Print a representation of the object.
disp(self, bool more)

element_hash(*args)
element_hash(self) -> int

elements(*args)
Get all elements.
elements(self) -> [float]

enlarge(*args)
Enlarge matrix Make the matrix larger by inserting empty rows and columns,
enlarge(self, int nrow, int ncol, [int] rr, [int] cc, bool ind1)


keeping the existing non-zeros.

erase(*args)
Erase a submatrix (leaving structural zeros in its place) Erase elements of
erase(self, [int] rr, bool ind1)
erase(self, [int] rr, [int] cc, bool ind1)


a matrix.

erase(self, [int] rr, bool ind1)


Erase a submatrix (leaving structural zeros in its place) Erase elements of a matrix.

erase(self, [int] rr, [int] cc, bool ind1)


Erase a submatrix (leaving structural zeros in its place) Erase rows and/or columns of a matrix.

export_code(*args)
Export matrix in specific language.
export_code(self, str lang, dict options)


lang: only ‘matlab’ supported for now

* options:
*   inline: Indicates if you want everything on a single line (default: False)
*   name: Name of exported variable (default: 'm')
*   indent_level: Level of indentation (default: 0)
*   spoof_zero: Replace numerical zero by a 1e-200 (default: false)
*               might be needed for matlab sparse construct,
*               which doesn't allow numerical zero
*

static eye(*args)
eye(int ncol) -> DM

full(*args)
full(self) -> PyObject *

get(*args)
get(self, bool ind1, Sparsity sp) -> DM
get(self, bool ind1, Slice rr) -> DM
get(self, bool ind1, IM rr) -> DM
get(self, bool ind1, Slice rr, Slice cc) -> DM
get(self, bool ind1, Slice rr, IM cc) -> DM
get(self, bool ind1, IM rr, Slice cc) -> DM
get(self, bool ind1, IM rr, IM cc) -> DM

static get_free(*args)
get_free(Function f) -> [DM]

static get_input(*args)
get_input(Function f) -> [DM]

static get_max_depth(*args)
get_max_depth() -> int

get_nz(*args)
get_nz(self, bool ind1, Slice k) -> DM
get_nz(self, bool ind1, IM k) -> DM

has_duplicates(*args)
has_duplicates(self) -> bool

has_nz(*args)
Returns true if the matrix has a non-zero at location rr, cc.
has_nz(self, int rr, int cc) -> bool

has_zeros(*args)
Check if the matrix has any zero entries which are not structural zeros.
has_zeros(self) -> bool

static inf(*args)
create a matrix with all inf
inf(int nrow, int ncol) -> DM
inf((int,int) rc) -> DM
inf(Sparsity sp) -> DM

info(*args)
info(self) -> dict

is_commutative(*args)
is_commutative(self) -> bool

is_constant(*args)
Check if the matrix is constant (note that false negative answers are
is_constant(self) -> bool


possible)

is_eye(*args)
check if the matrix is an identity matrix (note that false negative answers
is_eye(self) -> bool


are possible)

is_integer(*args)
Check if the matrix is integer-valued (note that false negative answers are
is_integer(self) -> bool


possible)

is_leaf(*args)
is_leaf(self) -> bool

is_minus_one(*args)
check if the matrix is -1 (note that false negative answers are possible)
is_minus_one(self) -> bool

is_one(*args)
check if the matrix is 1 (note that false negative answers are possible)
is_one(self) -> bool

is_op(*args)
is_op(self, int op) -> bool

is_regular(*args)
is_regular(self) -> bool

is_smooth(*args)
is_smooth(self) -> bool

is_symbolic(*args)
is_symbolic(self) -> bool

is_valid_input(*args)
is_valid_input(self) -> bool

is_zero(*args)
check if the matrix is 0 (note that false negative answers are possible)
is_zero(self) -> bool

static matrix_matrix(*args)
matrix_matrix(int op, DM x, DM y) -> DM

static matrix_scalar(*args)
matrix_scalar(int op, DM x, DM y) -> DM

n_dep(*args)
n_dep(self) -> int

name(*args)
name(self) -> str

static nan(*args)
create a matrix with all nan
nan(int nrow, int ncol) -> DM
nan((int,int) rc) -> DM
nan(Sparsity sp) -> DM

nonzeros(*args)
Get all nonzeros.
nonzeros(self) -> [float]


Implementation of Matrix::get_nonzeros (in public API)

op(*args)
op(self) -> int

print_dense(*args)
Print dense matrix-stype.
print_dense(self, bool truncate)

print_scalar(*args)
Print scalar.
print_scalar(self)

print_sparse(*args)
Print sparse matrix style.
print_sparse(self, bool truncate)

print_split(*args)
print_split(self) -> ([str] OUTPUT, [str] OUTPUT)

print_vector(*args)
Print vector-style.
print_vector(self, bool truncate)

printme(*args)
printme(self, DM y) -> DM

static rand(*args)
Create a matrix with uniformly distributed random numbers.
rand(int nrow, int ncol) -> DM
rand((int,int) rc) -> DM
rand(Sparsity sp) -> DM

remove(*args)
Remove columns and rows Remove/delete rows and/or columns of a matrix.
remove(self, [int] rr, [int] cc)

reserve(*args)
reserve(self, int nnz)
reserve(self, int nnz, int ncol)

reset_input(*args)
reset_input(self)

resize(*args)
resize(self, int nrow, int ncol)

static rng(*args)
rng(int seed)

sanity_check(*args)
[DEPRECATED] Correctness is checked during construction
sanity_check(self, bool complete)

static scalar_matrix(*args)
scalar_matrix(int op, DM x, DM y) -> DM

serialize(*args)
serialize(self) -> str

set(*args)
set(self, DM m, bool ind1, Sparsity sp)
set(self, DM m, bool ind1, Slice rr)
set(self, DM m, bool ind1, IM rr)
set(self, DM m, bool ind1, Slice rr, Slice cc)
set(self, DM m, bool ind1, Slice rr, IM cc)
set(self, DM m, bool ind1, IM rr, Slice cc)
set(self, DM m, bool ind1, IM rr, IM cc)

static set_max_depth(*args)
set_max_depth(int eq_depth)

set_nz(*args)
set_nz(self, DM m, bool ind1, Slice k)
set_nz(self, DM m, bool ind1, IM k)

static set_precision(*args)
Set the ‘precision, width & scientific’ used in printing and serializing to
set_precision(int precision)


streams.

static set_scientific(*args)
Set the ‘precision, width & scientific’ used in printing and serializing to
set_scientific(bool scientific)


streams.

static set_width(*args)
Set the ‘precision, width & scientific’ used in printing and serializing to
set_width(int width)


streams.

sparse(*args)
sparse(self) -> PyObject *

sparsity(*args)
Get an owning reference to the sparsity pattern.
sparsity(self) -> Sparsity

str(*args)
Get string representation.
str(self, bool more) -> str

to_file(*args)
Export numerical matrix to file
to_file(self, str filename, str format)


Supported formats: .mtx Matrix Market

static triplet(*args)
triplet([int] row, [int] col, DM d) -> DM
triplet([int] row, [int] col, DM d, (int,int) rc) -> DM
triplet([int] row, [int] col, DM d, int nrow, int ncol) -> DM

static type_name(*args)
type_name() -> str

static unary(*args)
unary(int op, DM x) -> DM


### 2.2. SX¶

class SX(*args)
static binary(*args)
binary(int op, SX x, SX y) -> SX

clear(*args)
clear(self)

dep(*args)
dep(self, int ch) -> SX

static deserialize(*args)
deserialize(std::istream & istream) -> SX
deserialize(str s) -> SX

disp(*args)
Print a representation of the object.
disp(self, bool more)

element_hash(*args)
element_hash(self) -> int

elements(*args)
Get all elements.
elements(self) -> [SXElem]

enlarge(*args)
Enlarge matrix Make the matrix larger by inserting empty rows and columns,
enlarge(self, int nrow, int ncol, [int] rr, [int] cc, bool ind1)


keeping the existing non-zeros.

erase(*args)
Erase a submatrix (leaving structural zeros in its place) Erase elements of
erase(self, [int] rr, bool ind1)
erase(self, [int] rr, [int] cc, bool ind1)


a matrix.

erase(self, [int] rr, bool ind1)


Erase a submatrix (leaving structural zeros in its place) Erase elements of a matrix.

erase(self, [int] rr, [int] cc, bool ind1)


Erase a submatrix (leaving structural zeros in its place) Erase rows and/or columns of a matrix.

export_code(*args)
Export matrix in specific language.
export_code(self, str lang, dict options)


lang: only ‘matlab’ supported for now

* options:
*   inline: Indicates if you want everything on a single line (default: False)
*   name: Name of exported variable (default: 'm')
*   indent_level: Level of indentation (default: 0)
*   spoof_zero: Replace numerical zero by a 1e-200 (default: false)
*               might be needed for matlab sparse construct,
*               which doesn't allow numerical zero
*

static eye(*args)
eye(int ncol) -> SX

get(*args)
get(self, bool ind1, Sparsity sp) -> SX
get(self, bool ind1, Slice rr) -> SX
get(self, bool ind1, IM rr) -> SX
get(self, bool ind1, Slice rr, Slice cc) -> SX
get(self, bool ind1, Slice rr, IM cc) -> SX
get(self, bool ind1, IM rr, Slice cc) -> SX
get(self, bool ind1, IM rr, IM cc) -> SX

static get_free(*args)
get_free(Function f) -> [SX]

static get_input(*args)
get_input(Function f) -> [SX]

static get_max_depth(*args)
get_max_depth() -> int

get_nz(*args)
get_nz(self, bool ind1, Slice k) -> SX
get_nz(self, bool ind1, IM k) -> SX

has_duplicates(*args)
has_duplicates(self) -> bool

has_nz(*args)
Returns true if the matrix has a non-zero at location rr, cc.
has_nz(self, int rr, int cc) -> bool

has_zeros(*args)
Check if the matrix has any zero entries which are not structural zeros.
has_zeros(self) -> bool

static inf(*args)
create a matrix with all inf
inf(int nrow, int ncol) -> SX
inf((int,int) rc) -> SX
inf(Sparsity sp) -> SX

info(*args)
info(self) -> dict

is_commutative(*args)
is_commutative(self) -> bool

is_constant(*args)
Check if the matrix is constant (note that false negative answers are
is_constant(self) -> bool


possible)

is_eye(*args)
check if the matrix is an identity matrix (note that false negative answers
is_eye(self) -> bool


are possible)

is_integer(*args)
Check if the matrix is integer-valued (note that false negative answers are
is_integer(self) -> bool


possible)

is_leaf(*args)
is_leaf(self) -> bool

is_minus_one(*args)
check if the matrix is -1 (note that false negative answers are possible)
is_minus_one(self) -> bool

is_one(*args)
check if the matrix is 1 (note that false negative answers are possible)
is_one(self) -> bool

is_op(*args)
is_op(self, int op) -> bool

is_regular(*args)
is_regular(self) -> bool

is_smooth(*args)
is_smooth(self) -> bool

is_symbolic(*args)
is_symbolic(self) -> bool

is_valid_input(*args)
is_valid_input(self) -> bool

is_zero(*args)
check if the matrix is 0 (note that false negative answers are possible)
is_zero(self) -> bool

static matrix_matrix(*args)
matrix_matrix(int op, SX x, SX y) -> SX

static matrix_scalar(*args)
matrix_scalar(int op, SX x, SX y) -> SX

n_dep(*args)
n_dep(self) -> int

name(*args)
name(self) -> str

static nan(*args)
create a matrix with all nan
nan(int nrow, int ncol) -> SX
nan((int,int) rc) -> SX
nan(Sparsity sp) -> SX

nonzeros(*args)
Get all nonzeros.
nonzeros(self) -> [SXElem]


Implementation of Matrix::get_nonzeros (in public API)

op(*args)
op(self) -> int

print_dense(*args)
Print dense matrix-stype.
print_dense(self, bool truncate)

print_scalar(*args)
Print scalar.
print_scalar(self)

print_sparse(*args)
Print sparse matrix style.
print_sparse(self, bool truncate)

print_split(*args)
print_split(self) -> ([str] OUTPUT, [str] OUTPUT)

print_vector(*args)
Print vector-style.
print_vector(self, bool truncate)

printme(*args)
printme(self, SX y) -> SX

static rand(*args)
Create a matrix with uniformly distributed random numbers.
rand(int nrow, int ncol) -> SX
rand((int,int) rc) -> SX
rand(Sparsity sp) -> SX

remove(*args)
Remove columns and rows Remove/delete rows and/or columns of a matrix.
remove(self, [int] rr, [int] cc)

reserve(*args)
reserve(self, int nnz)
reserve(self, int nnz, int ncol)

reset_input(*args)
reset_input(self)

resize(*args)
resize(self, int nrow, int ncol)

static rng(*args)
rng(int seed)

sanity_check(*args)
[DEPRECATED] Correctness is checked during construction
sanity_check(self, bool complete)

static scalar_matrix(*args)
scalar_matrix(int op, SX x, SX y) -> SX

serialize(*args)
serialize(self) -> str

set(*args)
set(self, SX m, bool ind1, Sparsity sp)
set(self, SX m, bool ind1, Slice rr)
set(self, SX m, bool ind1, IM rr)
set(self, SX m, bool ind1, Slice rr, Slice cc)
set(self, SX m, bool ind1, Slice rr, IM cc)
set(self, SX m, bool ind1, IM rr, Slice cc)
set(self, SX m, bool ind1, IM rr, IM cc)

static set_max_depth(*args)
set_max_depth(int eq_depth)

set_nz(*args)
set_nz(self, SX m, bool ind1, Slice k)
set_nz(self, SX m, bool ind1, IM k)

static set_precision(*args)
Set the ‘precision, width & scientific’ used in printing and serializing to
set_precision(int precision)


streams.

static set_scientific(*args)
Set the ‘precision, width & scientific’ used in printing and serializing to
set_scientific(bool scientific)


streams.

static set_width(*args)
Set the ‘precision, width & scientific’ used in printing and serializing to
set_width(int width)


streams.

sparsity(*args)
Get an owning reference to the sparsity pattern.
sparsity(self) -> Sparsity

str(*args)
Get string representation.
str(self, bool more) -> str

to_file(*args)
Export numerical matrix to file
to_file(self, str filename, str format)


Supported formats: .mtx Matrix Market

static triplet(*args)
triplet([int] row, [int] col, SX d) -> SX
triplet([int] row, [int] col, SX d, (int,int) rc) -> SX
triplet([int] row, [int] col, SX d, int nrow, int ncol) -> SX

static type_name(*args)
type_name() -> str

static unary(*args)
unary(int op, SX x) -> SX


### 2.3. MX¶

class MX(*args)
MX - Matrix expression.

The MX class is used to build up trees made up from MXNodes. It is a more general graph representation than the scalar expression, SX, and much less efficient for small objects. On the other hand, the class allows much more general operations than does SX, in particular matrix valued operations and calls to arbitrary differentiable functions.

The MX class is designed to have identical syntax with the Matrix<> template class, and uses DM (i.e. Matrix<double>) as its internal representation of the values at a node. By keeping the syntaxes identical, it is possible to switch from one class to the other, as well as inlining MX functions to SXElem functions.

Note that an operation is always “lazy”, making a matrix multiplication will create a matrix multiplication node, not perform the actual multiplication.

C++ includes: mx.hpp

attachAssert(*args)
returns itself, but with an assertion attached
attachAssert(self, MX y, str fail_message) -> MX


If y does not evaluate to 1, a runtime error is raised

static binary(*args)
Create nodes by their ID.
binary(int op, MX x, MX y) -> MX

dep(*args)
Get the nth dependency as MX.
dep(self, int ch) -> MX

static deserialize(*args)
deserialize(casadi::DeSerializer & s) -> MX

static einstein(*args)
Computes an einstein dense tensor contraction.
einstein(MX A, MX B, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> MX
einstein(MX A, MX B, MX C, [int] dim_a, [int] dim_b, [int] dim_c, [int] a, [int] b, [int] c) -> MX


Computes the product: C_c = A_a + B_b where a b c are index/einstein notation in an encoded form

For example, an matrix-matrix product may be written as: C_ij = A_ik B_kj

The encoded form uses strictly negative numbers to indicate labels. For the above example, we would have: a {-1, -3} b {-3, -2} c {-1 -2}

enlarge(*args)
Enlarge matrix Make the matrix larger by inserting empty rows and columns,
enlarge(self, int nrow, int ncol, [int] rr, [int] cc, bool ind1)


keeping the existing non-zeros.

erase(*args)
Erase a submatrix (leaving structural zeros in its place) Erase elements of
erase(self, [int] rr, bool ind1)
erase(self, [int] rr, [int] cc, bool ind1)


a matrix.

erase(self, [int] rr, bool ind1)


Erase a submatrix (leaving structural zeros in its place) Erase elements of a matrix.

erase(self, [int] rr, [int] cc, bool ind1)


Erase a submatrix (leaving structural zeros in its place) Erase rows and/or columns of a matrix.

static eye(*args)
eye(int ncol) -> MX

get(*args)
get(self, bool ind1, Sparsity sp) -> MX
get(self, bool ind1, Slice rr) -> MX
get(self, bool ind1, IM rr) -> MX
get(self, bool ind1, Slice rr, Slice cc) -> MX
get(self, bool ind1, Slice rr, IM cc) -> MX
get(self, bool ind1, IM rr, Slice cc) -> MX
get(self, bool ind1, IM rr, IM cc) -> MX

get(self, bool ind1, Sparsity sp)
get(self, bool ind1, Slice rr)


Get a submatrix, single argument

get(self, bool ind1, Slice rr, Slice cc)


Get a submatrix, two arguments

static get_free(*args)
get_free(Function f) -> [MX]

static get_input(*args)
get_input(Function f) -> [MX]

static get_max_depth(*args)
get_max_depth() -> int

get_nz(*args)
get_nz(self, bool ind1, Slice kk) -> MX
get_nz(self, bool ind1, IM kk) -> MX

get_nz(self, bool ind1, Slice kk)


Get a set of nonzeros

get_output(*args)
Get an output.
get_output(self, int oind) -> MX

get_temp(*args)
[INTERNAL] Get the temporary variable
get_temp(self) -> int

has_duplicates(*args)
[INTERNAL] Detect duplicate symbolic expressions If there are symbolic
has_duplicates(self) -> bool


primitives appearing more than once, the function will return true and the names of the duplicate expressions will be passed to casadi_warning. Note: Will mark the node using MX::set_temp. Make sure to call reset_input() after usage.

static inf(*args)
create a matrix with all inf
inf(int nrow, int ncol) -> MX
inf((int,int) rc) -> MX
inf(Sparsity sp) -> MX

info(*args)
info(self) -> dict

is_binary(*args)
Is binary operation.
is_binary(self) -> bool

is_call(*args)
Check if evaluation.
is_call(self) -> bool

is_commutative(*args)
Check if commutative operation.
is_commutative(self) -> bool

is_constant(*args)
Check if constant.
is_constant(self) -> bool

is_eye(*args)
check if identity
is_eye(self) -> bool

is_minus_one(*args)
check if zero (note that false negative answers are possible)
is_minus_one(self) -> bool

is_multiplication(*args)
Check if multiplication.
is_multiplication(self) -> bool

is_norm(*args)
Check if norm.
is_norm(self) -> bool

is_one(*args)
check if zero (note that false negative answers are possible)
is_one(self) -> bool

is_op(*args)
Is it a certain operation.
is_op(self, int op) -> bool

is_output(*args)
Check if evaluation output.
is_output(self) -> bool

is_regular(*args)
Checks if expression does not contain NaN or Inf.
is_regular(self) -> bool

is_symbolic(*args)
Check if symbolic.
is_symbolic(self) -> bool

is_transpose(*args)
Is the expression a transpose?
is_transpose(self) -> bool

is_unary(*args)
Is unary operation.
is_unary(self) -> bool

is_valid_input(*args)
Check if matrix can be used to define function inputs. Valid inputs for
is_valid_input(self) -> bool


MXFunctions are combinations of Reshape, concatenations and SymbolicMX.

is_zero(*args)
check if zero (note that false negative answers are possible)
is_zero(self) -> bool

join_primitives(*args)
Join an expression along symbolic primitives.
join_primitives(self, [MX] v) -> MX

mapping(*args)
Get an IM representation of a GetNonzeros or SetNonzeros node.
mapping(self) -> IM

monitor(*args)
Monitor an expression Returns itself, but with the side effect of printing
monitor(self, str comment) -> MX


the nonzeros along with a comment.

n_dep(*args)
Get the number of dependencies of a binary SXElem.
n_dep(self) -> int

n_out(*args)
Number of outputs.
n_out(self) -> int

n_primitives(*args)
Get the number of primitives for MXFunction inputs/outputs.
n_primitives(self) -> int

name(*args)
Get the name.
name(self) -> str

static nan(*args)
create a matrix with all nan
nan(int nrow, int ncol) -> MX
nan((int,int) rc) -> MX
nan(Sparsity sp) -> MX

op(*args)
Get operation type.
op(self) -> int

primitives(*args)
Get primitives.
primitives(self) -> [MX]

printme(*args)
printme(self, MX y) -> MX

reset_input(*args)
[INTERNAL] Reset the marker for an input expression.
reset_input(self)

serialize(*args)
serialize(self, casadi::Serializer & s)

set(*args)
set(self, MX m, bool ind1, Sparsity sp)
set(self, MX m, bool ind1, Slice rr)
set(self, MX m, bool ind1, IM rr)
set(self, MX m, bool ind1, Slice rr, Slice cc)
set(self, MX m, bool ind1, Slice rr, IM cc)
set(self, MX m, bool ind1, IM rr, Slice cc)
set(self, MX m, bool ind1, IM rr, IM cc)

set(self, MX m, bool ind1, Sparsity sp)
set(self, MX m, bool ind1, Slice rr)


Set a submatrix, single argument

static set_max_depth(*args)
set_max_depth(int eq_depth)

set_nz(*args)
set_nz(self, MX m, bool ind1, Slice kk)
set_nz(self, MX m, bool ind1, IM kk)

set_nz(self, MX m, bool ind1, Slice kk)


Set a set of nonzeros

set_temp(*args)
[INTERNAL] Set the temporary variable.
set_temp(self, int t)

sparsity(*args)
Get an owning reference to the sparsity pattern.
sparsity(self) -> Sparsity

split_primitives(*args)
Split up an expression along symbolic primitives.
split_primitives(self, MX x) -> [MX]

static test_cast(*args)
test_cast(casadi::SharedObjectInternal const * ptr) -> bool

to_DM(*args)
to_DM(self) -> DM

static type_name(*args)
type_name() -> str

static unary(*args)
Create nodes by their ID.
unary(int op, MX x) -> MX

which_function(*args)
Get function - only valid when is_call() is true.
which_function(self) -> Function

which_output(*args)
Get the index of evaluation output - only valid when is_output() is true.
which_output(self) -> int


### 2.4. Sparsity¶

class Sparsity(*args)
General sparsity class.

The storage format is a compressed column storage (CCS) format. In this format, the structural non-zero elements are stored in column-major order, starting from the upper left corner of the matrix and ending in the lower right corner.

In addition to the dimension ( size1(), size2()), (i.e. the number of rows and the number of columns respectively), there are also two vectors of integers:

“colind” [length size2()+1], which contains the index to the first non- zero element on or after the corresponding column. All the non-zero elements of a particular i are thus the elements with index el that fulfills: colind[i] <= el < colind[i+1].

“row” [same length as the number of non-zero elements, nnz()] The rows for each of the structural non-zeros.

Note that with this format, it is cheap to loop over all the non-zero elements of a particular column, at constant time per element, but expensive to jump to access a location (i, j).

If the matrix is dense, i.e. length(row) == size1()*size2(), the format reduces to standard dense column major format, which allows access to an arbitrary element in constant time.

Since the object is reference counted (it inherits from SharedObject), several matrices are allowed to share the same sparsity pattern.

The implementations of methods marked as such in this class has been taken from the CSparse package and modified to fit CasADi data structures and separation of sparsity pattern calculation and numerical evaluation. These functions are Copyright(c) Timothy A. Davis, 2006-2009 and licensed as a derivative work under the GNU LGPL

See: Matrix

C++ includes: sparsity.hpp

add_nz(*args)
Get the index of a non-zero element Add the element if it does not exist and
add_nz(self, int rr, int cc) -> int


copy object if it’s not unique.

amd(*args)
Approximate minimal degree preordering Fill-reducing ordering applied to the
amd(self) -> [int]


sparsity pattern of a linear system prior to factorization. The system must be symmetric, for an unsymmetric matrix A, first form the square of the pattern, A’*A.

The implementation is a modified version of cs_amd in CSparse Copyright(c) Timothy A. Davis, 2006-2009 Licensed as a derivative work under the GNU LGPL

append(*args)
Append another sparsity patten vertically (NOTE: only efficient if vector)
append(self, Sparsity sp)

appendColumns(*args)
Append another sparsity patten horizontally.
appendColumns(self, Sparsity sp)

static band(*args)
band(int n, int p) -> Sparsity

static banded(*args)
banded(int n, int p) -> Sparsity

btf(*args)
Calculate the block triangular form (BTF) See Direct Methods for Sparse
btf(self) -> (int , [int] OUTPUT, [int] OUTPUT, [int] OUTPUT, [int] OUTPUT, [int] OUTPUT, [int] OUTPUT)


Linear Systems by Davis (2006).

The function computes the Dulmage-Mendelsohn decomposition, which allows you to reorder the rows and columns of a matrix to bring it into block triangular form (BTF).

It will not consider the distance of off-diagonal elements to the diagonal: there is no guarantee you will get a block-diagonal matrix if you supply a randomly permuted block-diagonal matrix.

If your matrix is symmetrical, this method is of limited use; permutation can make it non-symmetric.

See: scc The implementation is a modified version of cs_dmperm in CSparse Copyright(c) Timothy A. Davis, 2006-2009 Licensed as a derivative work under the GNU LGPL

bw_lower(*args)
Lower half-bandwidth.
bw_lower(self) -> int

bw_upper(*args)
Upper half-bandwidth.
bw_upper(self) -> int

colind(*args)
Get a reference to the colindex of column cc (see class description)
colind(self) -> [int]
colind(self, int cc) -> int

colind(self)


Get the column index for each column Together with the row-vector, one obtains the sparsity pattern in the column compressed format.

colind(self, int cc)


Get a reference to the colindex of column cc (see class description)

columns(*args)
Get the number of columns, Octave-style syntax.
columns(self) -> int

combine(*args)
Combine two sparsity patterns Returns the new sparsity pattern as well as a
combine(self, Sparsity y, bool f0x_is_zero, bool fx0_is_zero) -> Sparsity


mapping with the same length as the number of non-zero elements The mapping matrix contains the arguments for each nonzero, the first bit indicates if the first argument is nonzero, the second bit indicates if the second argument is nonzero (note that none of, one of or both of the arguments can be nonzero)

compress(*args)
Compress a sparsity pattern.
compress(self) -> [int]

static compressed(*args)
Create from a single vector containing the pattern in compressed column
compressed([int] v, bool order_rows) -> Sparsity


storage format: The format: The first two entries are the number of rows (nrow) and columns (ncol) The next ncol+1 entries are the column offsets (colind). Note that the last element, colind[ncol], gives the number of nonzeros The last colind[ncol] entries are the row indices

static dense(*args)
Create a dense rectangular sparsity pattern.
dense(int nrow, int ncol) -> Sparsity
dense((int,int) rc) -> Sparsity

density(*args)
The percentage of nonzero Equivalent to (100.0 * nnz())/numel(), but avoids
density(self) -> float


overflow.

static deserialize(*args)
deserialize(std::istream & istream) -> Sparsity
deserialize(str s) -> Sparsity

dfs(*args)
Depth-first search on the adjacency graph of the sparsity See Direct Methods
dfs(self, int j, int top, [int] pinv) -> (int , [int] INOUT, [int] INOUT, [bool] INOUT)


for Sparse Linear Systems by Davis (2006).

static diag(*args)
Create diagonal sparsity pattern.
diag(int nrow) -> Sparsity
diag((int,int) rc) -> Sparsity
diag(int nrow, int ncol) -> Sparsity

dim(*args)
Get the dimension as a string.
dim(self, bool with_nz) -> str

enlarge(*args)
Enlarge matrix Make the matrix larger by inserting empty rows and columns,
enlarge(self, int nrow, int ncol, [int] rr, [int] cc, bool ind1)


keeping the existing non-zeros.

For the matrices A to B A(m, n) length(jj)=m , length(ii)=n B(nrow, ncol)

A=enlarge(m, n, ii, jj) makes sure that

B[jj, ii] == A

enlargeColumns(*args)
Enlarge the matrix along the second dimension (i.e. insert columns)
enlargeColumns(self, int ncol, [int] cc, bool ind1)

enlargeRows(*args)
Enlarge the matrix along the first dimension (i.e. insert rows)
enlargeRows(self, int nrow, [int] rr, bool ind1)

erase(*args)
Erase elements of a matrix.
erase(self, [int] rr, bool ind1) -> [int]
erase(self, [int] rr, [int] cc, bool ind1) -> [int]

erase(self, [int] rr, bool ind1)


Erase elements of a matrix.

erase(self, [int] rr, [int] cc, bool ind1)


Erase rows and/or columns of a matrix.

etree(*args)
Calculate the elimination tree See Direct Methods for Sparse Linear Systems
etree(self, bool ata) -> [int]


by Davis (2006). If the parameter ata is false, the algorithm is equivalent to MATLAB’s etree(A), except that the indices are zero- based. If ata is true, the algorithm is equivalent to MATLAB’s etree(A, ‘col’).

The implementation is a modified version of cs_etree in CSparse Copyright(c) Timothy A. Davis, 2006-2009 Licensed as a derivative work under the GNU LGPL

export_code(*args)
Export matrix in specific language.
export_code(self, str lang, dict options)


lang: only ‘matlab’ supported for now

 * options:
*   inline: Indicates if you want everything on a single line (default: False)
*   name: Name of exported variable (default: 'sp')
*   as_matrix: Matlab does not have a sparsity object. (default: false)
*               With this option true, a numeric matrix will be constructed
*

find(*args)
Get the location of all non-zero elements as they would appear in a Dense
find(self, bool ind1) -> [int]


matrix A : DenseMatrix 4 x 3 B : SparseMatrix 4 x 3 , 5 structural non- zeros.

k = A.find() A[k] will contain the elements of A that are non-zero in B

Inverse of nonzeros.

static from_file(*args)
from_file(str filename, str format_hint) -> Sparsity

get_ccs(*args)
Get the sparsity in compressed column storage (CCS) format.
get_ccs(self) -> ([int] OUTPUT, [int] OUTPUT)

get_col(*args)
Get the column for each non-zero entry Together with the row-vector, this
get_col(self) -> [int]


vector gives the sparsity of the matrix in sparse triplet format, i.e. the column and row for each non-zero elements.

get_crs(*args)
Get the sparsity in compressed row storage (CRS) format.
get_crs(self) -> ([int] OUTPUT, [int] OUTPUT)

get_diag(*args)
Get the diagonal of the matrix/create a diagonal matrix (mapping will
get_diag(self) -> (Sparsity , [int] OUTPUT)


contain the nonzero mapping) When the input is square, the diagonal elements are returned. If the input is vector-like, a diagonal matrix is constructed with it.

get_lower(*args)
Get nonzeros in lower triangular part.
get_lower(self) -> [int]

get_nz(*args)
Get the nonzero index for a set of elements The index vector is used both
get_nz(self) -> [int]
get_nz(self, int rr, int cc) -> int
get_nz(self, [int] rr, [int] cc) -> [int]


for input and outputs and must be sorted by increasing nonzero index, i.e. column-wise. Elements not found in the sparsity pattern are set to -1.

get_nz(self, int rr, int cc)


Get the index of an existing non-zero element return -1 if the element does not exist.

get_nz(self)


Get the nonzero index for a set of elements The index vector is used both for input and outputs and must be sorted by increasing nonzero index, i.e. column-wise. Elements not found in the sparsity pattern are set to -1.

get_nz(self, [int] rr, [int] cc)


Get a set of non-zero element return -1 if the element does not exist.

get_triplet(*args)
Get the sparsity in sparse triplet format.
get_triplet(self) -> ([int] OUTPUT, [int] OUTPUT)

get_upper(*args)
Get nonzeros in upper triangular part.
get_upper(self) -> [int]

has_nz(*args)
Returns true if the pattern has a non-zero at location rr, cc.
has_nz(self, int rr, int cc) -> bool

hash(*args)
hash(self) -> std::size_t

info(*args)
info(self) -> dict

intersect(*args)
Intersection of two sparsity patterns Returns the new sparsity pattern as
intersect(self, Sparsity y) -> Sparsity


well as a mapping with the same length as the number of non-zero elements The value is 1 if the non-zero comes from the first (i.e. this) object, 2 if it is from the second and 3 (i.e. 1 | 2) if from both.

is_column(*args)
Check if the pattern is a column vector (i.e. size2()==1)
is_column(self) -> bool

is_dense(*args)
Is dense?
is_dense(self) -> bool

is_diag(*args)
Is diagonal?
is_diag(self) -> bool

is_empty(*args)
Check if the sparsity is empty.
is_empty(self, bool both) -> bool


A sparsity is considered empty if one of the dimensions is zero (or optionally both dimensions)

is_equal(*args)
is_equal(self, Sparsity y) -> bool
is_equal(self, int nrow, int ncol, [int] colind, [int] row) -> bool

is_reshape(*args)
Check if the sparsity is a reshape of another.
is_reshape(self, Sparsity y) -> bool

is_row(*args)
Check if the pattern is a row vector (i.e. size1()==1)
is_row(self) -> bool

is_scalar(*args)
Is scalar?
is_scalar(self, bool scalar_and_dense) -> bool

is_singular(*args)
Check whether the sparsity-pattern indicates structural singularity.
is_singular(self) -> bool

is_square(*args)
Is square?
is_square(self) -> bool

is_stacked(*args)
Check if pattern is horizontal repeat of another.
is_stacked(self, Sparsity y, int n) -> bool

is_symmetric(*args)
Is symmetric?
is_symmetric(self) -> bool

is_transpose(*args)
Check if the sparsity is the transpose of another.
is_transpose(self, Sparsity y) -> bool

is_tril(*args)
Is lower triangular?
is_tril(self) -> bool

is_triu(*args)
Is upper triangular?
is_triu(self) -> bool

is_vector(*args)
Check if the pattern is a row or column vector.
is_vector(self) -> bool

static kkt(*args)
kkt(Sparsity H, Sparsity J, bool with_x_diag, bool with_lam_g_diag) -> Sparsity

largest_first(*args)
Order the columns by decreasing degree.
largest_first(self) -> [int]

ldl(*args)
Symbolic LDL factorization Returns the sparsity pattern of L^T.
ldl(self, bool amd) -> (Sparsity , [int] OUTPUT)


The implementation is a modified version of LDL Copyright(c) Timothy A. Davis, 2005-2013 Licensed as a derivative work under the GNU LGPL

static lower(*args)
lower(int n) -> Sparsity

makeDense(*args)
Make a patten dense.
makeDense(self) -> (Sparsity , [int] OUTPUT)

nnz(*args)
Get the number of (structural) non-zeros.
nnz(self) -> int


See: numel()

nnz_diag(*args)
Number of non-zeros on the diagonal, i.e. the number of elements (i, j) with
nnz_diag(self) -> int


j==i.

nnz_lower(*args)
Number of non-zeros in the lower triangular half, i.e. the number of
nnz_lower(self, bool strictly) -> int


elements (i, j) with j<=i.

nnz_upper(*args)
Number of non-zeros in the upper triangular half, i.e. the number of
nnz_upper(self, bool strictly) -> int


elements (i, j) with j>=i.

static nonzeros(*args)
nonzeros(int nrow, int ncol, [int] nz, bool ind1) -> Sparsity

numel(*args)
The total number of elements, including structural zeros, i.e.
numel(self) -> int


size2()*size1() Beware of overflow.

See: nnz()

pattern_inverse(*args)
Take the inverse of a sparsity pattern; flip zeros and non-zeros.
pattern_inverse(self) -> Sparsity

pmult(*args)
Permute rows and/or columns Multiply the sparsity with a permutation matrix
pmult(self, [int] p, bool permute_rows, bool permute_columns, bool invert_permutation) -> Sparsity


from the left and/or from the right P * A * trans(P), A * trans(P) or A * trans(P) with P defined by an index vector containing the row for each col. As an alternative, P can be transposed (inverted).

postfix_dim(*args)
Dimension string as a postfix to a name Rules:
postfix_dim(self) -> str


Dense and scalar: “”

0-by-0: “[]”

Dense column vector: “[5]”

Dense matrix: “[5x10]”

Otherwise: “[5x10,3nz]”

qr_sparse(*args)
Symbolic QR factorization Returns the sparsity pattern of V (compact
qr_sparse(self, bool amd) -> (Sparsity OUTPUT, Sparsity OUTPUT, [int] OUTPUT, [int] OUTPUT)


representation of Q) and R as well as vectors needed for the numerical factorization and solution. The implementation is a modified version of CSparse Copyright(c) Timothy A. Davis, 2006-2009 Licensed as a derivative work under the GNU LGPL.

removeDuplicates(*args)
Remove duplicate entries.
removeDuplicates(self) -> [int]


The same indices will be removed from the mapping vector, which must have the same length as the number of nonzeros

repr_el(*args)
Describe the nonzero location k as a string.
repr_el(self, int k) -> str

resize(*args)
Resize.
resize(self, int nrow, int ncol)

row(*args)
Get the row of a non-zero element.
row(self) -> [int]
row(self, int el) -> int

row(self, int el)


Get the row of a non-zero element.

row(self)


Get the row for each non-zero entry Together with the column-vector, this vector gives the sparsity of the matrix in sparse triplet format, and together with the colind vector, one obtains the sparsity in column compressed format.

static rowcol(*args)
rowcol([int] row, [int] col, int nrow, int ncol) -> Sparsity

rows(*args)
Get the number of rows, Octave-style syntax.
rows(self) -> int

rowsSequential(*args)
Do the rows appear sequentially on each column.
rowsSequential(self, bool strictly) -> bool


strictly: if true, then do not allow multiple entries

sanity_check(*args)
[DEPRECATED] Correctness of sparsity patterns are checked during
sanity_check(self, bool complete)


construction

static scalar(*args)
Create a scalar sparsity pattern.
scalar(bool dense_scalar) -> Sparsity

scc(*args)
Find the strongly connected components of the bigraph defined by the
scc(self) -> (int , [int] OUTPUT, [int] OUTPUT)


sparsity pattern of a square matrix.

See Direct Methods for Sparse Linear Systems by Davis (2006). Returns: Number of components

Offset for each components (length: 1 + number of components)

Indices for each components, component i has indices index[offset[i]], …, index[offset[i+1]]

In the case that the matrix is symmetric, the result has a particular interpretation: Given a symmetric matrix A and n = A.scc(p, r)

=> A[p, p] will appear block-diagonal with n blocks and with the indices of the block boundaries to be found in r.

The implementation is a modified version of cs_scc in CSparse Copyright(c) Timothy A. Davis, 2006-2009 Licensed as a derivative work under the GNU LGPL

serialize(*args)
serialize(self) -> str

serialize(self)


Serialize.

size(*args)
Get the size along a particular dimensions.
size(self) -> (int,int)
size(self, int axis) -> int

size(self)


Get the shape.

size(self, int axis)


Get the size along a particular dimensions.

size1(*args)
Get the number of rows.
size1(self) -> int

size2(*args)
Get the number of columns.
size2(self) -> int

spy(*args)
Print a textual representation of sparsity.
spy(self)

spy_matlab(*args)
Generate a script for Matlab or Octave which visualizes the sparsity using
spy_matlab(self, str mfile)


the spy command.

star_coloring(*args)
Perform a star coloring of a symmetric matrix: A greedy distance-2 coloring
star_coloring(self, int ordering, int cutoff) -> Sparsity


algorithm Algorithm 4.1 in What Color Is Your Jacobian? Graph Coloring for Computing Derivatives A. H. GEBREMEDHIN, F. MANNE, A. POTHEN SIAM Rev., 47(4), 629705 (2006)

Ordering options: None (0), largest first (1)

star_coloring2(*args)
Perform a star coloring of a symmetric matrix: A new greedy distance-2
star_coloring2(self, int ordering, int cutoff) -> Sparsity


coloring algorithm Algorithm 4.1 in NEW ACYCLIC AND STAR COLORING ALGORITHMS WITH APPLICATION TO COMPUTING HESSIANS A. H. GEBREMEDHIN, A. TARAFDAR, F. MANNE, A. POTHEN SIAM J. SCI. COMPUT. Vol. 29, No. 3, pp. 10421072 (2007)

Ordering options: None (0), largest first (1)

sub(*args)
Get a set of elements.
sub(self, [int] rr, Sparsity sp, bool ind1) -> (Sparsity , [int] OUTPUT)
sub(self, [int] rr, [int] cc, bool ind1) -> (Sparsity , [int] OUTPUT)


Returns the sparsity of the corresponding elements, with a mapping such that submatrix[k] = originalmatrix[mapping[k]]

sub(self, [int] rr, Sparsity sp, bool ind1)


Get a set of elements.

Returns the sparsity of the corresponding elements, with a mapping such that submatrix[k] = originalmatrix[mapping[k]]

sub(self, [int] rr, [int] cc, bool ind1)


Get a submatrix.

Returns the sparsity of the submatrix, with a mapping such that submatrix[k] = originalmatrix[mapping[k]]

static test_cast(*args)
test_cast(casadi::SharedObjectInternal const * ptr) -> bool

to_file(*args)
Export sparsity pattern to file
to_file(self, str filename, str format_hint)


Supported formats: .mtx Matrix Market

transpose(*args)
Transpose the matrix and get the reordering of the non-zero entries.
transpose(self, bool invert_mapping) -> (Sparsity , [int] OUTPUT)


mapping: the non-zeros of the original matrix for each non-zero of the new matrix

static triplet(*args)
triplet(int nrow, int ncol, [int] row, [int] col) -> Sparsity
triplet(int nrow, int ncol, [int] row, [int] col, bool invert_mapping) -> (Sparsity , [int] OUTPUT)

static type_name(*args)
type_name() -> str

uni_coloring(*args)
Perform a unidirectional coloring: A greedy distance-2 coloring algorithm
uni_coloring(self, Sparsity AT, int cutoff) -> Sparsity


(Algorithm 3.1 in A. H. GEBREMEDHIN, F. MANNE, A. POTHEN)

static unit(*args)
Create the sparsity pattern for a unit vector of length n and a nonzero on
unit(int n, int el) -> Sparsity


position el.

unite(*args)
Union of two sparsity patterns.
unite(self, Sparsity y) -> Sparsity

static upper(*args)
upper(int n) -> Sparsity


### 2.5. Function¶

class Function(*args)
Function object A Function instance is a general multiple-input, multiple-

output function where each input and output can be a sparse matrix. .

For an introduction to this class, see the CasADi user guide. Function is a reference counted and immutable class; copying a class instance is very cheap and its behavior (with some exceptions) is not affected by calling its member functions. Joel Andersson >List of available options

Id Type Description Used in
ad_weight OT_DOUBLE Weighting factor for derivative calculation.When there is an option of either using forward or reverse mode directional derivatives, the condition ad_wei ght*nf<=(1-ad_we ight)*na is used where nf and na are estimates of the number of forward/reverse mode directional derivatives needed. By default, ad_weight is calculated automatically, but this can be overridden by setting this option. In particular, 0 means forcing forward mode and 1 forcing reverse mode. Leave unset for (class specific) heuristics. casadi::Function Internal
ad_weight_sp OT_DOUBLE Weighting factor for sparsity pattern calculation calc ulation.Override s default behavior. Set to 0 and 1 to force forward and reverse mode respectively. Cf. option “ad_weight”. casadi::Function Internal
compiler OT_STRING Just-in-time compiler plugin to be used. casadi::Function Internal
derivative_of OT_FUNCTION The function is a derivative of another function. The type of derivative (directional derivative, Jacobian) is inferred from the function name. casadi::Function Internal
enable_fd OT_BOOL Enable derivative calculation by finite differencing. [default: false]] casadi::Function Internal
enable_forward OT_BOOL Enable derivative calculation using generated functions for Jacobian-times- vector products - typically using forward mode AD - if available. [default: true] casadi::Function Internal
enable_jacobian OT_BOOL Enable derivative calculation using generated functions for Jacobians of all differentiable outputs with respect to all differentiable inputs - if available. [default: true] casadi::Function Internal
enable_reverse OT_BOOL Enable derivative calculation using generated functions for transposed Jacobian-times- vector products - typically using reverse mode AD - if available. [default: true] casadi::Function Internal
fd_method OT_STRING Method for finite differencing [default ‘central’] casadi::Function Internal
fd_options OT_DICT Options to be passed to the finite difference instance casadi::Function Internal
gather_stats OT_BOOL Deprecated option (ignored): Statistics are now always collected. casadi::Function Internal
input_scheme OT_STRINGVECTOR Deprecated option (ignored) casadi::Function Internal
inputs_check OT_BOOL Throw exceptions when the numerical values of the inputs don’t make sense casadi::Function Internal
jac_penalty OT_DOUBLE When requested for a number of forward/reverse directions, it may be cheaper to compute first the full jacobian and then multiply with seeds, rather than obtain the requested directions in a straightforward manner. Casadi uses a heuristic to decide which is cheaper. A high value of ‘jac_penalty’ makes it less likely for the heurstic to chose the full Jacobian strategy. The special value -1 indicates never to use the full Jacobian strategy casadi::Function Internal
jit OT_BOOL Use just-in-time compiler to speed up the evaluation casadi::Function Internal
jit_options OT_DICT Options to be passed to the jit compiler. casadi::Function Internal
max_num_dir OT_INT Specify the maximum number of directions for derivative functions. Overrules the builtin optimize d_num_dir. casadi::Function Internal
output_scheme OT_STRINGVECTOR Deprecated option (ignored) casadi::Function Internal
regularity_check OT_BOOL Throw exceptions when NaN or Inf appears during evaluation casadi::Function Internal
user_data OT_VOIDPTR A user-defined field that can be used to identify the function or pass additional information casadi::Function Internal
verbose OT_BOOL Verbose evaluation for debugging casadi::Function Internal

C++ includes: function.hpp

assert_size_in(*args)
Assert that an input dimension is equal so some given value.
assert_size_in(self, int i, int nrow, int ncol)

assert_size_out(*args)
Assert that an output dimension is equal so some given value.
assert_size_out(self, int i, int nrow, int ncol)

static bspline(*args)
bspline(str name, [[float]] knots, [float] coeffs, [int] degree, int m, dict opts) -> Function

static bspline_dual(*args)
bspline_dual(str name, [[float]] knots, [float] x, [int] degree, int m, bool reverse, dict opts) -> Function

call(*args)
Generate a Jacobian function of output oind with respect to input iind.
call(self, dict:DM arg, bool always_inline, bool never_inline) -> dict:DM
call(self, [DM] arg, bool always_inline, bool never_inline) -> [DM]
call(self, [SX] arg, bool always_inline, bool never_inline) -> [SX]
call(self, dict:SX arg, bool always_inline, bool never_inline) -> dict:SX
call(self, dict:MX arg, bool always_inline, bool never_inline) -> dict:MX
call(self, [MX] arg, bool always_inline, bool never_inline) -> [MX]


iind: The index of the input

oind: The index of the output Legacy function: To be deprecated in a future version of CasADi. Exists only for compatibility with Function::jacobian pre-CasADi 3.2

call(self, [DM] arg, bool always_inline, bool never_inline)


Evaluate the function symbolically or numerically.

call(self, dict:DM arg, bool always_inline, bool never_inline)
call(self, [SX] arg, bool always_inline, bool never_inline)
call(self, dict:SX arg, bool always_inline, bool never_inline)
call(self, dict:MX arg, bool always_inline, bool never_inline)
call(self, [MX] arg, bool always_inline, bool never_inline)


Generate a Jacobian function of output oind with respect to input iind.

iind: The index of the input

oind: The index of the output Legacy function: To be deprecated in a future version of CasADi. Exists only for compatibility with Function::jacobian pre-CasADi 3.2

static check_name(*args)
check_name(str name) -> bool

checkout(*args)
Checkout a memory object.
checkout(self) -> int

static conditional(*args)
conditional(str name, [Function] f, Function f_def, dict opts) -> Function

default_in(*args)
Get default input value.
default_in(self, int ind) -> float

static deserialize(*args)
deserialize(std::istream & istream) -> Function
deserialize(str s) -> Function

expand(*args)
Expand a function to SX.
expand(self) -> Function
expand(self, str name, dict opts) -> Function

export_code(*args)
Export function in specific language.
export_code(self, str lang, dict options) -> str
export_code(self, str lang, str fname, dict options)


Only allowed for (a subset of) SX/MX Functions

factory(*args)
factory(self, str name, [str] s_in, [str] s_out, dict:[str] aux, dict opts) -> Function

static fix_name(*args)
fix_name(str name) -> str

fold(*args)
Create a mapaccumulated version of this function.
fold(self, int n, dict opts) -> Function


Suppose the function has a signature of:

f: (x, u) -> (x_next , y )


The the mapaccumulated version has the signature:

F: (x0, U) -> (X , Y )

with
U: horzcat([u0, u1, ..., u_(N-1)])
X: horzcat([x1, x2, ..., x_N])
Y: horzcat([y0, y1, ..., y_(N-1)])

and
x1, y0 <- f(x0, u0)
x2, y1 <- f(x1, u1)
...
x_N, y_(N-1) <- f(x_(N-1), u_(N-1))


Mapaccum has the following benefits over writing an equivalent for- loop: much faster at construction time

potentially much faster compilation times (for codegen)

offers a trade-off between memory and evaluation time

The base (settable through the options dictionary, default 10), is used to create a tower of function calls, containing unrolled for- loops of length maximum base.

This technique is much more scalable in terms of memory-usage, but slightly slower at evaluation, than a plain for-loop. The effect is similar to that of a for-loop with a check-pointing instruction after each chunk of iterations with size base.

Set base to -1 to unroll all the way; no gains in memory efficiency here.

forward(*args)
Get a function that calculates nfwd forward derivatives.
forward(self, int nfwd) -> Function


Returns a function with n_in + n_out + n_in inputs and nfwd outputs. The first n_in inputs correspond to nondifferentiated inputs. The next n_out inputs correspond to nondifferentiated outputs. and the last n_in inputs correspond to forward seeds, stacked horizontally The n_out outputs correspond to forward sensitivities, stacked horizontally. * (n_in = n_in(), n_out = n_out())

The functions returned are cached, meaning that if called multiple timed with the same value, then multiple references to the same function will be returned.

free_mx(*args)
Get all the free variables of the function.
free_mx(self) -> [MX]

free_sx(*args)
Get all the free variables of the function.
free_sx(self) -> [SX]

generate(*args)
Export / Generate C code for the function.
generate(self, dict opts) -> str
generate(self, str fname, dict opts) -> str

generate_dependencies(*args)
Export / Generate C code for the dependency function.
generate_dependencies(self, str fname, dict opts) -> str

generate_lifted(*args)
Extract the functions needed for the Lifted Newton method.
generate_lifted(self) -> (Function OUTPUT, Function OUTPUT)

get_free(*args)
Get free variables as a string.
get_free(self) -> [str]

get_function(*args)
get_function(self) -> [str]
get_function(self, str name) -> Function

has_free(*args)
Does the function have free variables.
has_free(self) -> bool

has_function(*args)
has_function(self, str fname) -> bool

has_spfwd(*args)
Is the class able to propagate seeds through the algorithm?
has_spfwd(self) -> bool

has_sprev(*args)
Is the class able to propagate seeds through the algorithm?
has_sprev(self) -> bool

hessian_old(*args)
Generate a Hessian function of output oind with respect to input iind.
hessian_old(self, int iind, int oind) -> Function


iind: The index of the input

oind: The index of the output Legacy function: To be deprecated in a future version of CasADi. Exists only for compatibility with Function::hessian pre- CasADi 3.2

static if_else(*args)
if_else(str name, Function f_true, Function f_false, dict opts) -> Function

index_in(*args)
Find the index for a string describing a particular entry of an input
index_in(self, str name) -> int


scheme.

example: schemeEntry(“x_opt”) -> returns NLPSOL_X if FunctionInternal adheres to SCHEME_NLPINput

index_out(*args)
Find the index for a string describing a particular entry of an output
index_out(self, str name) -> int


scheme.

example: schemeEntry(“x_opt”) -> returns NLPSOL_X if FunctionInternal adheres to SCHEME_NLPINput

info(*args)
info(self) -> dict

instruction_MX(*args)
Get the MX node corresponding to an instruction ( MXFunction)
instruction_MX(self, int k) -> MX

instruction_constant(*args)
Get the floating point output argument of an instruction ( SXFunction)
instruction_constant(self, int k) -> float

instruction_id(*args)
Identifier index of the instruction (SXFunction/MXFunction)
instruction_id(self, int k) -> int

instruction_input(*args)
Locations in the work vector for the inputs of the instruction
instruction_input(self, int k) -> [int]


(SXFunction/MXFunction)

instruction_output(*args)
Location in the work vector for the output of the instruction
instruction_output(self, int k) -> [int]


(SXFunction/MXFunction)

is_a(*args)
Check if the function is of a particular type Optionally check if name
is_a(self, str type, bool recursive) -> bool


matches one of the base classes (default true)

jac(*args)
Calculate all Jacobian blocks Generates a function that takes all non-
jac(self) -> Function


differentiated inputs and outputs and calculates all Jacobian blocks. Inputs that are not needed by the routine are all-zero sparse matrices with the correct dimensions. Output blocks that are not calculated, e.g. if the corresponding input or output is marked non-differentiated are also all-zero sparse. The Jacobian blocks are sorted starting by all the blocks for the first output, then all the blocks for the second output and so on. E.g. f:(x,y)->(r,s) results in the function jac_f:(x,y,r,s)->(dr_dx, dr_dy, ds_dx, ds_dy) This function is cached.

jacobian(*args)
Generate a Jacobian function of all the inputs elements with respect to all
jacobian(self) -> Function


the output elements).

jacobian_old(*args)
Generate a Jacobian function of output oind with respect to input iind.
jacobian_old(self, int iind, int oind) -> Function


iind: The index of the input

oind: The index of the output Legacy function: To be deprecated in a future version of CasADi. Exists only for compatibility with Function::jacobian pre-CasADi 3.2

static jit(*args)
To resolve ambiguity on some compilers.
jit(str name, str body, [str] name_in, [str] name_out, dict opts) -> Function
jit(str name, str body, [str] name_in, [str] name_out, [Sparsity] sparsity_in, [Sparsity] sparsity_out, dict opts) -> Function


Create a just-in-time compiled function from a C language string The names and sparsity patterns of all the inputs and outputs must be provided. If sparsities are not provided, all inputs and outputs are assumed to be scalar. Only specify the function body, assuming that input and output nonzeros are stored in arrays with the specified naming convension. The data type used is ‘casadi_real’, which is typically equal to ‘double or another data type with the same API as ‘double’.

Inputs may be null pointers. This means that the all entries are zero. Outputs may be null points. This means that the corresponding result can be ignored.

If an error occurs in the evaluation, issue “return 1;”;

The final generated function will have a structure similar to:

map(*args)
Map with reduction A subset of the inputs are non-repeated and a subset of
map(self, int n, str parallelization) -> Function
map(self, int n, str parallelization, int max_num_threads) -> Function
map(self, str name, str parallelization, int n, [int] reduce_in, [int] reduce_out, dict opts) -> Function
map(self, str name, str parallelization, int n, [str] reduce_in, [str] reduce_out, dict opts) -> Function


the outputs summed up.

map(self, int n, str parallelization)


Create a mapped version of this function.

Suppose the function has a signature of:

f: (a, p) -> ( s )


The the mapped version has the signature:

F: (A, P) -> (S )

with
A: horzcat([a0, a1, ..., a_(N-1)])
P: horzcat([p0, p1, ..., p_(N-1)])
S: horzcat([s0, s1, ..., s_(N-1)])
and
s0 <- f(a0, p0)
s1 <- f(a1, p1)
...
s_(N-1) <- f(a_(N-1), p_(N-1))


parallelization: Type of parallelization used: unroll|serial|openmp

map(self, str name, str parallelization, int n, [int] reduce_in, [int] reduce_out, dict opts)
map(self, str name, str parallelization, int n, [str] reduce_in, [str] reduce_out, dict opts)


Map with reduction A subset of the inputs are non-repeated and a subset of the outputs summed up.

mapaccum(*args)
Create a mapaccumulated version of this function.
mapaccum(self, int n, dict opts) -> Function
mapaccum(self, str name, int n, dict opts) -> Function
mapaccum(self, str name, int n, int n_accum, dict opts) -> Function
mapaccum(self, str name, int n, [str] accum_in, [str] accum_out, dict opts) -> Function
mapaccum(self, str name, int n, [int] accum_in, [int] accum_out, dict opts) -> Function


Suppose the function has a signature of:

f: (x, u) -> (x_next , y )


The the mapaccumulated version has the signature:

F: (x0, U) -> (X , Y )

with
U: horzcat([u0, u1, ..., u_(N-1)])
X: horzcat([x1, x2, ..., x_N])
Y: horzcat([y0, y1, ..., y_(N-1)])

and
x1, y0 <- f(x0, u0)
x2, y1 <- f(x1, u1)
...
x_N, y_(N-1) <- f(x_(N-1), u_(N-1))


Mapaccum has the following benefits over writing an equivalent for- loop: much faster at construction time

potentially much faster compilation times (for codegen)

offers a trade-off between memory and evaluation time

The base (settable through the options dictionary, default 10), is used to create a tower of function calls, containing unrolled for- loops of length maximum base.

This technique is much more scalable in terms of memory-usage, but slightly slower at evaluation, than a plain for-loop. The effect is similar to that of a for-loop with a check-pointing instruction after each chunk of iterations with size base.

Set base to -1 to unroll all the way; no gains in memory efficiency here.

mapsum(*args)
Evaluate symbolically in parallel and sum (matrix graph)
mapsum(self, [MX] arg, str parallelization) -> [MX]


parallelization: Type of parallelization used: unroll|serial|openmp

max_in(*args)
Get largest input value.
max_in(self, int ind) -> float

min_in(*args)
Get smallest input value.
min_in(self, int ind) -> float

mx_in(*args)
Get symbolic primitives equivalent to the input expressions There is no
mx_in(self) -> [MX]
mx_in(self, int ind) -> MX
mx_in(self, str iname) -> MX


guarantee that subsequent calls return unique answers.

mx_out(*args)
Get symbolic primitives equivalent to the output expressions There is no
mx_out(self) -> [MX]
mx_out(self, int ind) -> MX
mx_out(self, str oname) -> MX


guarantee that subsequent calls return unique answers.

n_in(*args)
Get the number of function inputs.
n_in(self) -> int

n_instructions(*args)
Number of instruction in the algorithm (SXFunction/MXFunction)
n_instructions(self) -> int

n_nodes(*args)
Number of nodes in the algorithm.
n_nodes(self) -> int

n_out(*args)
Get the number of function outputs.
n_out(self) -> int

name(*args)
Name of the function.
name(self) -> str

name_in(*args)
Get input scheme name by index.
name_in(self) -> [str]
name_in(self, int ind) -> str

name_in(self, int ind)


Get input scheme name by index.

name_in(self)


Get input scheme.

name_out(*args)
Get output scheme name by index.
name_out(self) -> [str]
name_out(self, int ind) -> str

name_out(self, int ind)


Get output scheme name by index.

name_out(self)


Get output scheme.

nnz_in(*args)
Get number of input nonzeros.
nnz_in(self) -> int
nnz_in(self, int ind) -> int
nnz_in(self, str iname) -> int


For a particular input or for all of the inputs

nnz_out(*args)
Get number of output nonzeros.
nnz_out(self) -> int
nnz_out(self, int ind) -> int
nnz_out(self, str oname) -> int


For a particular output or for all of the outputs

numel_in(*args)
Get number of input elements.
numel_in(self) -> int
numel_in(self, int ind) -> int
numel_in(self, str iname) -> int


For a particular input or for all of the inputs

numel_out(*args)
Get number of output elements.
numel_out(self) -> int
numel_out(self, int ind) -> int
numel_out(self, str oname) -> int


For a particular output or for all of the outputs

oracle(*args)
Get oracle.
oracle(self) -> Function

print_dimensions(*args)
Print dimensions of inputs and outputs.
print_dimensions(self)

print_option(*args)
Print all information there is to know about a certain option.
print_option(self, str name)

print_options(*args)
Print options to a stream.
print_options(self)

release(*args)
Release a memory object.
release(self, int mem)

reverse(*args)
reverse(self, int nadj) -> Function


Returns a function with n_in + n_out + n_out inputs and n_in outputs. The first n_in inputs correspond to nondifferentiated inputs. The next n_out inputs correspond to nondifferentiated outputs. and the last n_out inputs correspond to adjoint seeds, stacked horizontally The n_in outputs correspond to adjoint sensitivities, stacked horizontally. * (n_in = n_in(), n_out = n_out())

(n_in = n_in(), n_out = n_out())

The functions returned are cached, meaning that if called multiple timed with the same value, then multiple references to the same function will be returned.

serialize(*args)
Serialize.
serialize(self) -> str

size1_in(*args)
Get input dimension.
size1_in(self, int ind) -> int
size1_in(self, str iname) -> int

size1_out(*args)
Get output dimension.
size1_out(self, int ind) -> int
size1_out(self, str oname) -> int

size2_in(*args)
Get input dimension.
size2_in(self, int ind) -> int
size2_in(self, str iname) -> int

size2_out(*args)
Get output dimension.
size2_out(self, int ind) -> int
size2_out(self, str oname) -> int

size_in(*args)
Get input dimension.
size_in(self, int ind) -> (int,int)
size_in(self, str iname) -> (int,int)

size_out(*args)
Get output dimension.
size_out(self, int ind) -> (int,int)
size_out(self, str oname) -> (int,int)

slice(*args)
returns a new function with a selection of inputs/outputs of the original
slice(self, str name, [int] order_in, [int] order_out, dict opts) -> Function

sparsity_in(*args)
Get sparsity of a given input.
sparsity_in(self, int ind) -> Sparsity
sparsity_in(self, str iname) -> Sparsity

sparsity_jac(*args)
Get, if necessary generate, the sparsity of a Jacobian block
sparsity_jac(self, str iind, int oind, bool compact, bool symmetric) -> Sparsity
sparsity_jac(self, int iind, int oind, bool compact, bool symmetric) -> Sparsity
sparsity_jac(self, int iind, str oind, bool compact, bool symmetric) -> Sparsity
sparsity_jac(self, str iind, str oind, bool compact, bool symmetric) -> Sparsity

sparsity_out(*args)
Get sparsity of a given output.
sparsity_out(self, int ind) -> Sparsity
sparsity_out(self, str iname) -> Sparsity

stats(*args)
Get all statistics obtained at the end of the last evaluate call.
stats(self, int mem) -> dict

sx_in(*args)
Get symbolic primitives equivalent to the input expressions There is no
sx_in(self) -> [SX]
sx_in(self, int iind) -> SX
sx_in(self, str iname) -> SX


guarantee that subsequent calls return unique answers.

sx_out(*args)
Get symbolic primitives equivalent to the output expressions There is no
sx_out(self) -> [SX]
sx_out(self, int oind) -> SX
sx_out(self, str oname) -> SX


guarantee that subsequent calls return unique answers.

sz_arg(*args)
Get required length of arg field.
sz_arg(self) -> size_t

sz_iw(*args)
Get required length of iw field.
sz_iw(self) -> size_t

sz_res(*args)
Get required length of res field.
sz_res(self) -> size_t

sz_w(*args)
Get required length of w field.
sz_w(self) -> size_t

static type_name(*args)
type_name() -> str

uses_output(*args)
Do the derivative functions need nondifferentiated outputs?
uses_output(self) -> bool

which_depends(*args)
Which variables enter with some order.
which_depends(self, str s_in, [str] s_out, int order, bool tr) -> [bool]


order: Only 1 (linear) and 2 (nonlinear) allowed

tr: Flip the relationship. Return which expressions contain the variables

wrap(*args)
Wrap in an Function instance consisting of only one MX call.
wrap(self) -> Function


## 3. Solvers¶

### 3.1. NLP¶

nlpsol(*args)
nlpsol(str name, str solver, Importer compiler, dict opts) -> Function
nlpsol(str name, str solver, NlpBuilder nl, dict opts) -> Function
nlpsol(str name, str solver, dict:SX nlp, dict opts) -> Function
nlpsol(str name, str solver, dict:MX nlp, dict opts) -> Function
nlpsol(str name, str solver, str fname, dict opts) -> Function

nlpsol(str name, str solver, dict:SX nlp, dict opts)


Create an NLP solver Creates a solver for the following parametric nonlinear program (NLP):

min          F(x, p)
x

subject to
LBX <=   x    <= UBX
LBG <= G(x, p) <= UBG
p  == P

nx: number of decision variables
ng: number of constraints
np: number of parameters


>List of available options

Id Type Description Used in
bound_consistenc y OT_BOOL Ensure that primal-dual solution is consistent with the bounds casadi::Nlpsol
calc_f OT_BOOL Calculate ‘f’ in the Nlpsol base class casadi::Nlpsol
calc_g OT_BOOL Calculate ‘g’ in the Nlpsol base class casadi::Nlpsol
calc_lam_p OT_BOOL Calculate ‘lam_p’ in the Nlpsol base class casadi::Nlpsol
calc_lam_x OT_BOOL Calculate ‘lam_x’ in the Nlpsol base class casadi::Nlpsol
calc_multipliers OT_BOOL Calculate Lagrange multipliers in the Nlpsol base class casadi::Nlpsol
common_options OT_DICT Options for auto-generated functions casadi::OracleFu nction
discrete OT_BOOLVECTOR Indicates which of the variables are discrete, i.e. integer- valued casadi::Nlpsol
error_on_fail OT_BOOL When the numerical process returns unsuccessfully, raise an error (default false). casadi::Nlpsol
eval_errors_fata l OT_BOOL When errors occur during evaluation of f,g,…,stop the iterations casadi::Nlpsol
expand OT_BOOL Replace MX with SX expressions in problem formulation [false] casadi::Nlpsol
ignore_check_vec OT_BOOL If set to true, the input shape of F will not be checked. casadi::Nlpsol
iteration_callba ck OT_FUNCTION A function that will be called at each iteration with the solver as input. Check documentation of Callback . casadi::Nlpsol
iteration_callba ck_ignore_errors OT_BOOL If set to true, errors thrown by iteration_callba ck will be ignored. casadi::Nlpsol
iteration_callba ck_step OT_INT Only call the callback function every few iterations. casadi::Nlpsol
monitor OT_STRINGVECTOR Set of user problem functions to be monitored casadi::OracleFu nction
oracle_options OT_DICT Options to be passed to the oracle function casadi::Nlpsol
specific_options OT_DICT Options for specific auto- generated functions, overwriting the defaults from common_options. Nested dictionary. casadi::OracleFu nction
verbose_init OT_BOOL Print out timing information about the different stages of initialization casadi::Nlpsol
warn_initial_bou nds OT_BOOL Warn if the initial guess does not satisfy LBX and UBX casadi::Nlpsol

>Input scheme: casadi::NlpsolInput (NLPSOL_NUM_IN = 8)

Full name Short Description
NLPSOL_X0 x0 Decision variables, initial guess (nx x 1)
NLPSOL_P p Value of fixed parameters (np x 1)
NLPSOL_LBX lbx Decision variables lower bound (nx x 1), default -inf.
NLPSOL_UBX ubx Decision variables upper bound (nx x 1), default +inf.
NLPSOL_LBG lbg Constraints lower bound (ng x 1), default -inf.
NLPSOL_UBG ubg Constraints upper bound (ng x 1), default +inf.
NLPSOL_LAM_X0 lam_x0 Lagrange multipliers for bounds on X, initial guess (nx x 1)
NLPSOL_LAM_G0 lam_g0 Lagrange multipliers for bounds on G, initial guess (ng x 1)

>Output scheme: casadi::NlpsolOutput (NLPSOL_NUM_OUT = 6)

Full name Short Description
NLPSOL_X x Decision variables at the optimal solution (nx x 1)
NLPSOL_F f Cost function value at the optimal solution (1 x 1)
NLPSOL_G g Constraints function at the optimal solution (ng x 1)
NLPSOL_LAM_X lam_x Lagrange multipliers for bounds on X at the solution (nx x 1)
NLPSOL_LAM_G lam_g Lagrange multipliers for bounds on G at the solution (ng x 1)
NLPSOL_LAM_P lam_p Lagrange multipliers for bounds on P at the solution (np x 1)
• AmplInterface
• blocksqp
• bonmin
• ipopt
• knitro
• snopt
• worhp
• qrsqp
• scpgen
• sqpmethod

Note: some of the plugins in this list might not be available on your system. Also, there might be extra plugins available to you that are not listed here. You can obtain their documentation with Nlpsol.doc(“myextraplugin”)

>List of available options

Id Type Description
solver OT_STRING AMPL solver binary

This is a modified version of blockSQP by Janka et al.

>List of available options

Id Type Description
block_hess OT_INT Blockwise Hessian approximation?
col_eps OT_DOUBLE Epsilon for COL scaling strategy
col_tau1 OT_DOUBLE tau1 for COL scaling strategy
col_tau2 OT_DOUBLE tau2 for COL scaling strategy
conv_strategy OT_INT Convexification strategy
delta OT_DOUBLE Filter line search parameter, cf. IPOPT paper
delta_h0 OT_DOUBLE Filter line search parameter, cf. IPOPT paper
eps OT_DOUBLE Values smaller than this are regarded as numerically zero
eta OT_DOUBLE Filter line search parameter, cf. IPOPT paper
fallback_scaling OT_INT If indefinite update is used, the type of fallback strategy
fallback_update OT_INT If indefinite update is used, the type of fallback strategy
gamma_f OT_DOUBLE Filter line search parameter, cf. IPOPT paper
gamma_theta OT_DOUBLE Filter line search parameter, cf. IPOPT paper
globalization OT_BOOL Enable globalization
hess_damp OT_INT Activate Powell damping for BFGS
hess_damp_fac OT_DOUBLE Damping factor for BFGS Powell modification
hess_lim_mem OT_INT Full or limited memory
hess_memsize OT_INT Memory size for L-BFGS updates
hess_scaling OT_INT Scaling strategy for Hessian approximation
hess_update OT_INT Type of Hessian approximation
ini_hess_diag OT_DOUBLE Initial Hessian guess: diagonal matrix diag(iniHessDiag)
kappa_f OT_DOUBLE Filter line search parameter, cf. IPOPT paper
kappa_minus OT_DOUBLE Filter line search parameter, cf. IPOPT paper
kappa_plus OT_DOUBLE Filter line search parameter, cf. IPOPT paper
kappa_plus_max OT_DOUBLE Filter line search parameter, cf. IPOPT paper
kappa_soc OT_DOUBLE Filter line search parameter, cf. IPOPT paper
linsol OT_STRING The linear solver to be used by the QP method
max_consec_reduced_steps OT_INT Maximum number of consecutive reduced steps
max_conv_qp OT_INT How many additional QPs may be solved for convexification per iteration?
max_it_qp OT_INT Maximum number of QP iterations per SQP iteration
max_iter OT_INT Maximum number of SQP iterations
max_line_search OT_INT Maximum number of steps in line search
max_soc_iter OT_INT Maximum number of SOC line search iterations
max_time_qp OT_DOUBLE Maximum number of time in seconds per QP solve per SQP iteration
nlinfeastol OT_DOUBLE Nonlinear feasibility tolerance
obj_lo OT_DOUBLE Lower bound on objective function [-inf]
obj_up OT_DOUBLE Upper bound on objective function [inf]
opttol OT_DOUBLE Optimality tolerance
print_iteration OT_BOOL Print SQP iterations
qpsol OT_STRING The QP solver to be used by the SQP method
qpsol_options OT_DICT Options to be passed to the QP solver
restore_feas OT_BOOL Use feasibility restoration phase
s_f OT_DOUBLE Filter line search parameter, cf. IPOPT paper
s_theta OT_DOUBLE Filter line search parameter, cf. IPOPT paper
schur OT_BOOL Use qpOASES Schur compliment approach
skip_first_globalization OT_BOOL No globalization strategy in first iteration
theta_max OT_DOUBLE Filter line search parameter, cf. IPOPT paper
theta_min OT_DOUBLE Filter line search parameter, cf. IPOPT paper
warmstart OT_BOOL Use warmstarting
which_second_derv OT_INT For which block should second derivatives be provided by the user

When in warmstart mode, output NLPSOL_LAM_X may be used as input

NOTE: Even when max_iter == 0, it is not guaranteed that input(NLPSOL_X0) == output(NLPSOL_X). Indeed if bounds on X or constraints are unmet, they will differ.

For a good tutorial on BONMIN, seehttp://drops.dagstuhl.de/volltexte/2009/2089/pdf/09061.WaechterAndreas.Paper.2089.pdf

A good resource about the algorithms in BONMIN is: Wachter and L. T. Biegler, On the Implementation of an Interior-Point Filter Line-Search Algorithm for Large-Scale Nonlinear Programming, Mathematical Programming 106(1), pp. 25-57, 2006 (As Research Report RC 23149, IBM T. J. Watson Research Center, Yorktown, USA

Caveats: with default options, multipliers for the decision variables are wrong for equality constraints. Change the ‘fixed_variable_treatment’ to ‘make_constraint’ or ‘relax_bounds’ to obtain correct results.

>List of available options

Id Type Description
bonmin OT_DICT Options to be passed to BONMIN
con_integer_md OT_DICT Integer metadata (a dictionary with lists of integers) about constraints to be passed to BONMIN
con_numeric_md OT_DICT Numeric metadata (a dictionary with lists of reals) about constraints to be passed to BONMIN
con_string_md OT_DICT String metadata (a dictionary with lists of strings) about constraints to be passed to BONMIN
grad_f OT_FUNCTION Function for calculating the gradient of the objective (column, autogenerated by default)
hess_lag OT_FUNCTION Function for calculating the Hessian of the Lagrangian (autogenerated by default)
hess_lag_options OT_DICT Options for the autogenerated Hessian of the Lagrangian.
jac_g OT_FUNCTION Function for calculating the Jacobian of the constraints (autogenerated by default)
jac_g_options OT_DICT Options for the autogenerated Jacobian of the constraints.
pass_nonlinear_constrai nts OT_BOOL Pass list of constraints entering nonlinearly to BONMIN
pass_nonlinear_variable s OT_BOOL Pass list of variables entering nonlinearly to BONMIN
sos1_groups OT_INTVECTORVECTOR Options for the autogenerated gradient of the objective.
sos1_priorities OT_INTVECTOR Options for the autogenerated gradient of the objective.
sos1_weights OT_DOUBLEVECTORVECTOR Options for the autogenerated gradient of the objective.
var_integer_md OT_DICT Integer metadata (a dictionary with lists of integers) about variables to be passed to BONMIN
var_numeric_md OT_DICT Numeric metadata (a dictionary with lists of reals) about variables to be passed to BONMIN
var_string_md OT_DICT String metadata (a dictionary with lists of strings) about variables to be passed to BONMIN

When in warmstart mode, output NLPSOL_LAM_X may be used as input

NOTE: Even when max_iter == 0, it is not guaranteed that input(NLPSOL_X0) == output(NLPSOL_X). Indeed if bounds on X or constraints are unmet, they will differ.

For a good tutorial on IPOPT, seehttp://drops.dagstuhl.de/volltexte/2009/2089/pdf/09061.WaechterAndreas.Paper.2089.pdf

A good resource about the algorithms in IPOPT is: Wachter and L. T. Biegler, On the Implementation of an Interior-Point Filter Line-Search Algorithm for Large-Scale Nonlinear Programming, Mathematical Programming 106(1), pp. 25-57, 2006 (As Research Report RC 23149, IBM T. J. Watson Research Center, Yorktown, USA

Caveats: with default options, multipliers for the decision variables are wrong for equality constraints. Change the ‘fixed_variable_treatment’ to ‘make_constraint’ or ‘relax_bounds’ to obtain correct results.

>List of available options

Id Type Description
con_integer_md OT_DICT Integer metadata (a dictionary with lists of integers) about constraints to be passed to IPOPT
con_numeric_md OT_DICT Numeric metadata (a dictionary with lists of reals) about constraints to be passed to IPOPT
con_string_md OT_DICT String metadata (a dictionary with lists of strings) about constraints to be passed to IPOPT
grad_f OT_FUNCTION Function for calculating the gradient of the objective (column, autogenerated by default)
hess_lag OT_FUNCTION Function for calculating the Hessian of the Lagrangian (autogenerated by default)
ipopt OT_DICT Options to be passed to IPOPT
jac_g OT_FUNCTION Function for calculating the Jacobian of the constraints (autogenerated by default)
pass_nonlinear_variables OT_BOOL Pass list of variables entering nonlinearly to IPOPT
var_integer_md OT_DICT Integer metadata (a dictionary with lists of integers) about variables to be passed to IPOPT
var_numeric_md OT_DICT Numeric metadata (a dictionary with lists of reals) about variables to be passed to IPOPT
var_string_md OT_DICT String metadata (a dictionary with lists of strings) about variables to be passed to IPOPT

KNITRO interface

>List of available options

Id Type Description
contype OT_INTVECTOR Type of constraint
detect_linear_constraints OT_BOOL Detect type of constraints
knitro OT_DICT Options to be passed to KNITRO

SNOPT interface

>List of available options

Id Type Description
snopt OT_DICT Options to be passed to SNOPT
start OT_STRING Warm-start options for Worhp: cold|warm|hot

WORHP interface

Designed for Worhp 1.12

>List of available options

Id Type Description
worhp OT_DICT Options to be passed to WORHP

A textbook SQPMethod

A structure-exploiting sequential quadratic programming (to be come sequential convex programming) method for nonlinear programming.

>List of available options

Id Type Description
beta OT_DOUBLE Line-search parameter, restoration factor of stepsize
c1 OT_DOUBLE Armijo condition, coefficient of decrease in merit
codegen OT_BOOL C-code generation
hessian_approximation OT_STRING gauss-newton|exact
lbfgs_memory OT_INT Size of L-BFGS memory.
max_iter OT_INT Maximum number of SQP iterations
max_iter_ls OT_INT Maximum number of linesearch iterations
merit_memsize OT_INT Size of memory to store history of merit function values
merit_start OT_DOUBLE Lower bound for the merit function parameter
name_x OT_STRINGVECTOR Names of the variables.
print_x OT_INTVECTOR Which variables to print.
qpsol OT_STRING The QP solver to be used by the SQP method
qpsol_options OT_DICT Options to be passed to the QP solver
reg_threshold OT_DOUBLE Threshold for the regularization.
regularize OT_BOOL Automatic regularization of Lagrange Hessian.
tol_du OT_DOUBLE Stopping criterion for dual infeasability
tol_pr OT_DOUBLE Stopping criterion for primal infeasibility
tol_pr_step OT_DOUBLE Stopping criterion for the step size
tol_reg OT_DOUBLE Stopping criterion for regularization

A textbook SQPMethod

>List of available options

Id Type Description
beta OT_DOUBLE Line-search parameter, restoration factor of stepsize
c1 OT_DOUBLE Armijo condition, coefficient of decrease in merit
hessian_approximation OT_STRING limited-memory|exact
lbfgs_memory OT_INT Size of L-BFGS memory.
max_iter OT_INT Maximum number of SQP iterations
max_iter_ls OT_INT Maximum number of linesearch iterations
merit_memory OT_INT Size of memory to store history of merit function values
min_iter OT_INT Minimum number of SQP iterations
min_step_size OT_DOUBLE The size (inf-norm) of the step size should not become smaller than this.
print_iteration OT_BOOL Print the iterations
print_status OT_BOOL Print a status message after solving
qpsol OT_STRING The QP solver to be used by the SQP method [qpoases]
qpsol_options OT_DICT Options to be passed to the QP solver
regularize OT_BOOL Automatic regularization of Lagrange Hessian.
tol_du OT_DOUBLE Stopping criterion for dual infeasability
tol_pr OT_DOUBLE Stopping criterion for primal infeasibility

### 3.2. QP¶

#### 3.2.1. High-level¶

qpsol(*args)
qpsol(str name, str solver, dict:SX qp, dict opts) -> Function
qpsol(str name, str solver, dict:MX qp, dict opts) -> Function


#### 3.2.2. Low-level¶

conic(*args)
Create a QP solver Solves the following strictly convex problem:
conic(str name, str solver, dict:Sparsity qp, dict opts) -> Function

min          1/2 x' H x + g' x
x

subject to
LBA <= A x <= UBA
LBX <= x   <= UBX

resize(Q x, np, np) + P >= 0 (psd)

with :
H sparse (n x n) positive definite
g dense  (n x 1)
A sparse (nc x n)
Q sparse symmetric (np^2 x n)
P sparse symmetric (np x nq)

n: number of decision variables (x)
nc: number of constraints (A)
nq: shape of psd constraint matrix


If H is not positive-definite, the solver should throw an error.

Second-order cone constraints can be added as psd constraints through a helper function ‘soc’:

x in R^n y in R

|| x ||_2 <= y

<=>

soc(x, y) psd

This can be proven with soc(x, y)=[y*I x; x’ y] using the Shur complement.

>List of available options

Id Type Description Used in
ad_weight OT_DOUBLE Weighting factor for derivative calculation.When there is an option of either using forward or reverse mode directional derivatives, the condition ad_wei ght*nf<=(1-ad_we ight)*na is used where nf and na are estimates of the number of forward/reverse mode directional derivatives needed. By default, ad_weight is calculated automatically, but this can be overridden by setting this option. In particular, 0 means forcing forward mode and 1 forcing reverse mode. Leave unset for (class specific) heuristics. casadi::Function Internal
ad_weight_sp OT_DOUBLE Weighting factor for sparsity pattern calculation calc ulation.Override s default behavior. Set to 0 and 1 to force forward and reverse mode respectively. Cf. option “ad_weight”. casadi::Function Internal
compiler OT_STRING Just-in-time compiler plugin to be used. casadi::Function Internal
derivative_of OT_FUNCTION The function is a derivative of another function. The type of derivative (directional derivative, Jacobian) is inferred from the function name. casadi::Function Internal
discrete OT_BOOLVECTOR Indicates which of the variables are discrete, i.e. integer- valued casadi::Conic
enable_fd OT_BOOL Enable derivative calculation by finite differencing. [default: false]] casadi::Function Internal
enable_forward OT_BOOL Enable derivative calculation using generated functions for Jacobian-times- vector products - typically using forward mode AD - if available. [default: true] casadi::Function Internal
enable_jacobian OT_BOOL Enable derivative calculation using generated functions for Jacobians of all differentiable outputs with respect to all differentiable inputs - if available. [default: true] casadi::Function Internal
enable_reverse OT_BOOL Enable derivative calculation using generated functions for transposed Jacobian-times- vector products - typically using reverse mode AD - if available. [default: true] casadi::Function Internal
fd_method OT_STRING Method for finite differencing [default ‘central’] casadi::Function Internal
fd_options OT_DICT Options to be passed to the finite difference instance casadi::Function Internal
gather_stats OT_BOOL Deprecated option (ignored): Statistics are now always collected. casadi::Function Internal
input_scheme OT_STRINGVECTOR Deprecated option (ignored) casadi::Function Internal
inputs_check OT_BOOL Throw exceptions when the numerical values of the inputs don’t make sense casadi::Function Internal
jac_penalty OT_DOUBLE When requested for a number of forward/reverse directions, it may be cheaper to compute first the full jacobian and then multiply with seeds, rather than obtain the requested directions in a straightforward manner. Casadi uses a heuristic to decide which is cheaper. A high value of ‘jac_penalty’ makes it less likely for the heurstic to chose the full Jacobian strategy. The special value -1 indicates never to use the full Jacobian strategy casadi::Function Internal
jit OT_BOOL Use just-in-time compiler to speed up the evaluation casadi::Function Internal
jit_options OT_DICT Options to be passed to the jit compiler. casadi::Function Internal
max_num_dir OT_INT Specify the maximum number of directions for derivative functions. Overrules the builtin optimize d_num_dir. casadi::Function Internal
output_scheme OT_STRINGVECTOR Deprecated option (ignored) casadi::Function Internal
regularity_check OT_BOOL Throw exceptions when NaN or Inf appears during evaluation casadi::Function Internal
user_data OT_VOIDPTR A user-defined field that can be used to identify the function or pass additional information casadi::Function Internal
verbose OT_BOOL Verbose evaluation for debugging casadi::Function Internal

>Input scheme: casadi::ConicInput (CONIC_NUM_IN = 12)

Full name Short Description
CONIC_H h The square matrix H: sparse, (n x n). Only the lower triangular part is actually used. The matrix is assumed to be symmetrical.
CONIC_G g The vector g: dense, (n x 1)
CONIC_A a The matrix A: sparse, (nc x n) - product with x must be dense.
CONIC_LBA lba dense, (nc x 1)
CONIC_UBA uba dense, (nc x 1)
CONIC_LBX lbx dense, (n x 1)
CONIC_UBX ubx dense, (n x 1)
CONIC_X0 x0 dense, (n x 1)
CONIC_LAM_X0 lam_x0 dense
CONIC_LAM_A0 lam_a0 dense
CONIC_Q q The matrix Q: sparse symmetric, (np^2 x n)
CONIC_P p The matrix P: sparse symmetric, (np x np)

>Output scheme: casadi::ConicOutput (CONIC_NUM_OUT = 4)

Full name Short Description
CONIC_X x The primal solution.
CONIC_COST cost The optimal cost.
CONIC_LAM_A lam_a The dual solution corresponding to linear bounds.
CONIC_LAM_X lam_x The dual solution corresponding to simple bounds.
• clp
• cplex
• gurobi
• hpmpc
• ooqp
• qpoases
• sqic
• nlpsol
• qrqp

Note: some of the plugins in this list might not be available on your system. Also, there might be extra plugins available to you that are not listed here. You can obtain their documentation with Conic.doc(“myextraplugin”)

Interface to Clp solver for sparse Quadratic Programs

Interface to Cplex solver for sparse Quadratic Programs

>List of available options

Id Type Description
cplex OT_DICT Options to be passed to CPLEX
dep_check OT_INT Detect redundant constraints.
dump_filename OT_STRING The filename to dump to.
dump_to_file OT_BOOL Dumps QP to file in CPLEX format.
qp_method OT_INT Determines which CPLEX algorithm to use.
tol OT_DOUBLE Tolerance of solver
warm_start OT_BOOL Use warm start with simplex methods (affects only the simplex methods).

Interface to the GUROBI Solver for quadratic programming

>List of available options

Id Type Description
gurobi OT_DICT Options to be passed to gurobi.
vtype OT_STRINGVECTOR Type of variables: [CONTINUOUS|binary|integer|semicont|semiint]

Interface to HMPC Solver

In order to use this interface, you must:

Decision variables must only by state and control, and the variable ordering must be [x0 u0 x1 u1 …]

The constraints must be in order: [ gap0 lincon0 gap1 lincon1 ]

gap: Ak+1 = Ak xk + Bk uk lincon: yk= Ck xk + Dk uk

A0 B0 -I
C0 D0
A1 B1 -I
C1 D1


where I must be a diagonal sparse matrix Either supply all of N, nx, ng, nu options or rely on automatic detection

>List of available options

Id Type Description
N OT_INT OCP horizon
blasfeo_target OT_STRING hpmpc target
inf OT_DOUBLE HPMPC cannot handle infinities. Infinities will be replaced by this option’s value.
max_iter OT_INT Max number of iterations
mu0 OT_DOUBLE Max element in cost function as estimate of max multiplier
ng OT_INTVECTOR Number of non-dynamic constraints, length N+1
nu OT_INTVECTOR Number of controls, length N
nx OT_INTVECTOR Number of states, length N+1
target OT_STRING hpmpc target
tol OT_DOUBLE Tolerance in the duality measure
warm_start OT_BOOL Use warm-starting

Interface to the OOQP Solver for quadratic programming The current implementation assumes that OOQP is configured with the MA27 sparse linear solver.

NOTE: when doing multiple calls to evaluate(), check if you need to reInit();

>List of available options

Id Type Description
artol OT_DOUBLE tolerance as provided with setArTol to OOQP
mutol OT_DOUBLE tolerance as provided with setMuTol to OOQP
print_level OT_INT Print level. OOQP listens to print_level 0, 10 and 100

Interface to QPOases Solver for quadratic programming

>List of available options

Id Type Description
CPUtime OT_DOUBLE The maximum allowed CPU time in seconds for the whole initialisation (and the actually required one on output). Disabled if unset.
boundRelaxation OT_DOUBLE Initial relaxation of bounds to start homotopy and initial value for far bounds.
boundTolerance OT_DOUBLE If upper and lower bounds differ less than this tolerance, they are regarded equal, i.e. as equality constraint.
enableCholeskyRefactorisation OT_INT Specifies the frequency of a full re-factorisation of projected Hessian matrix: 0: turns them off, 1: uses them at each iteration etc.
enableDriftCorrection OT_INT Specifies the frequency of drift corrections: 0: turns them off.
enableEqualities OT_BOOL Specifies whether equalities should be treated as always active (True) or not (False)
enableFarBounds OT_BOOL Enables the use of far bounds.
enableFlippingBounds OT_BOOL Enables the use of flipping bounds.
enableFullLITests OT_BOOL Enables condition-hardened (but more expensive) LI test.
enableInertiaCorrection OT_BOOL Should working set be repaired when negative curvature is discovered during hotstart.
enableNZCTests OT_BOOL Enables nonzero curvature tests.
enableRamping OT_BOOL Enables ramping.
enableRegularisation OT_BOOL Enables automatic Hessian regularisation.
epsDen OT_DOUBLE Denominator tolerance for ratio tests.
epsFlipping OT_DOUBLE Tolerance of squared Cholesky diagonal factor which triggers flipping bound.
epsIterRef OT_DOUBLE Early termination tolerance for iterative refinement.
epsLITests OT_DOUBLE Tolerance for linear independence tests.
epsNZCTests OT_DOUBLE Tolerance for nonzero curvature tests.
epsNum OT_DOUBLE Numerator tolerance for ratio tests.
epsRegularisation OT_DOUBLE Scaling factor of identity matrix used for Hessian regularisation.
finalRamping OT_DOUBLE Final value for ramping strategy.
growFarBounds OT_DOUBLE Factor to grow far bounds.
hessian_type OT_STRING Type of Hessian - see qpOASES documentation [UNKNO WN|posdef|semidef|indef|zero |identity]]
initialFarBounds OT_DOUBLE Initial size for far bounds.
initialRamping OT_DOUBLE Start value for ramping strategy.
initialStatusBounds OT_STRING Initial status of bounds at first iteration.
linsol_plugin OT_STRING Linear solver plugin
maxDualJump OT_DOUBLE Maximum allowed jump in dual variables in linear independence tests.
maxPrimalJump OT_DOUBLE Maximum allowed jump in primal variables in nonzero curvature tests.
max_schur OT_INT Maximal number of Schur updates [75]
nWSR OT_INT The maximum number of working set recalculations to be performed during the initial homotopy. Default is 5(nx + nc)
numRefinementSteps OT_INT Maximum number of iterative refinement steps.
numRegularisationSteps OT_INT Maximum number of successive regularisation steps.
printLevel OT_STRING Defines the amount of text output during QP solution, see Section 5.7
schur OT_BOOL Use Schur Complement Approach [false]
sparse OT_BOOL Formulate the QP using sparse matrices. [false]
terminationTolerance OT_DOUBLE Relative termination tolerance to stop homotopy.

Interface to the SQIC solver for quadratic programming

Solve QPs using an Nlpsol Use the ‘nlpsol’ option to specify the NLP solver to use.

>List of available options

Id Type Description
nlpsol OT_STRING Name of solver.
nlpsol_options OT_DICT Options to be passed to solver.

Solve QPs using an active-set method

>List of available options

Id Type Description
du_to_pr OT_DOUBLE How much larger dual than primal error is acceptable [1000]
max_iter OT_INT Maximum number of iterations [1000].
print_iter OT_BOOL Print iterations [true].
tol OT_DOUBLE Tolerance [1e-8].

### 3.3. Integrator¶

integrator(*args)
integrator(str name, str solver, dict:SX dae, dict opts) -> Function
integrator(str name, str solver, dict:MX dae, dict opts) -> Function

integrator(str name, str solver, dict:SX dae, dict opts)


Create an ODE/DAE integrator Solves an initial value problem (IVP) coupled to a terminal value problem with differential equation given as an implicit ODE coupled to an algebraic equation and a set of quadratures:

Initial conditions at t=t0
x(t0)  = x0
q(t0)  = 0

Forward integration from t=t0 to t=tf
der(x) = function(x, z, p, t)                  Forward ODE
0 = fz(x, z, p, t)                  Forward algebraic equations
der(q) = fq(x, z, p, t)                  Forward quadratures

Terminal conditions at t=tf
rx(tf)  = rx0
rq(tf)  = 0

Backward integration from t=tf to t=t0
der(rx) = gx(rx, rz, rp, x, z, p, t)        Backward ODE
0 = gz(rx, rz, rp, x, z, p, t)        Backward algebraic equations
der(rq) = gq(rx, rz, rp, x, z, p, t)        Backward quadratures

where we assume that both the forward and backwards integrations are index-1
(i.e. dfz/dz, dgz/drz are invertible) and furthermore that
gx, gz and gq have a linear dependency on rx, rz and rp.


>List of available options

Id Type Description Used in
augmented_option s OT_DICT Options to be passed down to the augmented integrator, if one is constructed. casadi::Integrat or
common_options OT_DICT Options for auto-generated functions casadi::OracleFu nction
expand OT_BOOL Replace MX with SX expressions in problem formulation [false] casadi::Integrat or
grid OT_DOUBLEVECTOR Time grid casadi::Integrat or
monitor OT_STRINGVECTOR Set of user problem functions to be monitored casadi::OracleFu nction
number_of_finite _elements OT_INT Number of finite elements casadi::Integrat or
output_t0 OT_BOOL Output the state at the initial time casadi::Integrat or
print_stats OT_BOOL Print out statistics after integration casadi::Integrat or
rootfinder OT_STRING An implicit function solver casadi::Integrat or
rootfinder_optio ns OT_DICT Options to be passed to the NLP Solver casadi::Integrat or
specific_options OT_DICT Options for specific auto- generated functions, overwriting the defaults from common_options. Nested dictionary. casadi::OracleFu nction
t0 OT_DOUBLE Beginning of the time horizon casadi::Integrat or
tf OT_DOUBLE End of the time horizon casadi::Integrat or

>Input scheme: casadi::IntegratorInput (INTEGRATOR_NUM_IN = 6)

Full name Short Description
INTEGRATOR_X0 x0 Differential state at the initial time.
INTEGRATOR_P p Parameters.
INTEGRATOR_Z0 z0 Initial guess for the algebraic variable.
INTEGRATOR_RX0 rx0 Backward differential state at the final time.
INTEGRATOR_RP rp Backward parameter vector.
INTEGRATOR_RZ0 rz0 Initial guess for the backwards algebraic variable.

>Output scheme: casadi::IntegratorOutput (INTEGRATOR_NUM_OUT = 6)

Full name Short Description
INTEGRATOR_XF xf Differential state at the final time.
INTEGRATOR_QF qf Quadrature state at the final time.
INTEGRATOR_ZF zf Algebraic variable at the final time.
INTEGRATOR_RXF rxf Backward differential state at the initial time.
INTEGRATOR_RQF rqf Backward quadrature state at the initial time.
INTEGRATOR_RZF rzf Backward algebraic variable at the initial time.
• cvodes
• idas
• collocation
• rk

Note: some of the plugins in this list might not be available on your system. Also, there might be extra plugins available to you that are not listed here. You can obtain their documentation with Integrator.doc(“myextraplugin”)

Interface to CVodes from the Sundials suite.

A call to evaluate will integrate to the end.

You can retrieve the entire state trajectory as follows, after the evaluate call: Call reset. Then call integrate(t_i) and getOuput for a series of times t_i.

>List of available options

Id Type Description
abstol OT_DOUBLE Absolute tolerence for the IVP solution
disable_internal_warnings OT_BOOL Disable SUNDIALS internal warning messages
fsens_all_at_once OT_BOOL Calculate all right hand sides of the sensitivity equations at once
fsens_err_con OT_BOOL include the forward sensitivities in all error controls
interpolation_type OT_STRING Type of interpolation for the adjoint sensitivities
linear_solver OT_STRING A custom linear solver creator function [default: qr]
linear_solver_options OT_DICT Options to be passed to the linear solver
max_krylov OT_INT Maximum Krylov subspace size
max_multistep_order OT_INT Maximum order for the (variable-order) multistep method
max_num_steps OT_INT Maximum number of integrator steps
max_order OT_DOUBLE Maximum order
newton_scheme OT_STRING Linear solver scheme in the Newton method: DIRECT|gmres|bcgstab|tfqmr
nonlin_conv_coeff OT_DOUBLE Coefficient in the nonlinear convergence test
nonlinear_solver_iteration OT_STRING Nonlinear solver type: NEWTON|functional
reltol OT_DOUBLE Relative tolerence for the IVP solution
second_order_correction OT_BOOL Second order correction in the augmented system Jacobian [true]
sensitivity_method OT_STRING Sensitivity method: SIMULTANEOUS|staggered
step0 OT_DOUBLE initial step size [default: 0/estimated]
steps_per_checkpoint OT_INT Number of steps between two consecutive checkpoints
stop_at_end OT_BOOL Stop the integrator at the end of the interval
use_preconditioner OT_BOOL Precondition the iterative solver [default: true]

Interface to IDAS from the Sundials suite.

>List of available options

Id Type Description
abstol OT_DOUBLE Absolute tolerence for the IVP solution
abstolv OT_DOUBLEVECTOR Absolute tolerarance for each component
calc_ic OT_BOOL Use IDACalcIC to get consistent initial conditions.
calc_icB OT_BOOL Use IDACalcIC to get consistent initial conditions for backwards system [default: equal to calc_ic].
cj_scaling OT_BOOL IDAS scaling on cj for the user-defined linear solver module
disable_internal_warnings OT_BOOL Disable SUNDIALS internal warning messages
first_time OT_DOUBLE First requested time as a fraction of the time interval
fsens_err_con OT_BOOL include the forward sensitivities in all error controls
init_xdot OT_DOUBLEVECTOR Initial values for the state derivatives
interpolation_type OT_STRING Type of interpolation for the adjoint sensitivities
linear_solver OT_STRING A custom linear solver creator function [default: qr]
linear_solver_options OT_DICT Options to be passed to the linear solver
max_krylov OT_INT Maximum Krylov subspace size
max_multistep_order OT_INT Maximum order for the (variable-order) multistep method
max_num_steps OT_INT Maximum number of integrator steps
max_order OT_DOUBLE Maximum order
max_step_size OT_DOUBLE Maximim step size
newton_scheme OT_STRING Linear solver scheme in the Newton method: DIRECT|gmres|bcgstab|tfqmr
nonlin_conv_coeff OT_DOUBLE Coefficient in the nonlinear convergence test
reltol OT_DOUBLE Relative tolerence for the IVP solution
second_order_correction OT_BOOL Second order correction in the augmented system Jacobian [true]
sensitivity_method OT_STRING Sensitivity method: SIMULTANEOUS|staggered
step0 OT_DOUBLE initial step size [default: 0/estimated]
steps_per_checkpoint OT_INT Number of steps between two consecutive checkpoints
stop_at_end OT_BOOL Stop the integrator at the end of the interval
suppress_algebraic OT_BOOL Suppress algebraic variables in the error testing
use_preconditioner OT_BOOL Precondition the iterative solver [default: true]

Fixed-step implicit Runge-Kutta integrator ODE/DAE integrator based on collocation schemes

The method is still under development

>List of available options

Id Type Description
augmented_options OT_DICT Options to be passed down to the augmented integrator, if one is constructed.
expand OT_BOOL Replace MX with SX expressions in problem formulation [false]
grid OT_DOUBLEVECTOR Time grid
interpolation_order OT_INT Order of the interpolating polynomials
number_of_finite_elements OT_INT Number of finite elements
output_t0 OT_BOOL Output the state at the initial time
print_stats OT_BOOL Print out statistics after integration
rootfinder OT_STRING An implicit function solver
rootfinder_options OT_DICT Options to be passed to the NLP Solver
t0 OT_DOUBLE Beginning of the time horizon
tf OT_DOUBLE End of the time horizon

rk –

Fixed-step explicit Runge-Kutta integrator for ODEs Currently implements RK4.

The method is still under development

### 3.4. Rootfinding¶

rootfinder(*args)
rootfinder(str name, str solver, dict:SX rfp, dict opts) -> Function
rootfinder(str name, str solver, dict:MX rfp, dict opts) -> Function
rootfinder(str name, str solver, Function f, dict opts) -> Function

rootfinder(str name, str solver, dict:SX rfp, dict opts)


Create a solver for rootfinding problems Takes a function where one of the inputs is unknown and one of the outputs is a residual function that is always zero, defines a new function where the the unknown input has been replaced by a guess for the unknown and the residual output has been replaced by the calculated value for the input.

For a function [y0, y1, …,yi, .., yn] = F(x0, x1, …, xj, …, xm), where xj is unknown and yi=0, defines a new function [y0, y1, …,xj, .., yn] = G(x0, x1, …, xj_guess, …, xm),

xj and yi must have the same dimension and d(yi)/d(xj) must be invertable.

By default, the first input is unknown and the first output is the residual.

>List of available options

Id Type Description Used in
common_options OT_DICT Options for auto-generated functions casadi::OracleFu nction
constraints OT_INTVECTOR Constrain the unknowns. 0 (default): no constraint on ui, 1: ui >= 0.0, -1: ui <= 0.0, 2: ui > 0.0, -2: ui < 0.0. casadi::Rootfind er
error_on_fail OT_BOOL When the numerical process returns unsuccessfully, raise an error (default false). casadi::Rootfind er
implicit_input OT_INT Index of the input that corresponds to the actual root- finding casadi::Rootfind er
implicit_output OT_INT Index of the output that corresponds to the actual root- finding casadi::Rootfind er
jacobian_functio n OT_FUNCTION Function object for calculating the Jacobian (autogenerated by default) casadi::Rootfind er
linear_solver OT_STRING User-defined linear solver class. Needed for sensitivities. casadi::Rootfind er
linear_solver_op tions OT_DICT Options to be passed to the linear solver. casadi::Rootfind er
monitor OT_STRINGVECTOR Set of user problem functions to be monitored casadi::OracleFu nction
specific_options OT_DICT Options for specific auto- generated functions, overwriting the defaults from common_options. Nested dictionary. casadi::OracleFu nction

>Input scheme: casadi::RootfinderInput (ROOTFINDER_NUM_IN = 2)

Full name Short Description
ROOTFINDER_X0 x0 Initial guess for the solution.
ROOTFINDER_P p Parameters.

>Output scheme: casadi::RootfinderOutput (ROOTFINDER_NUM_OUT = 1)

Full name Short Description
ROOTFINDER_X x Solution to the system of equations.
• kinsol
• fast_newton
• nlpsol
• newton

Note: some of the plugins in this list might not be available on your system. Also, there might be extra plugins available to you that are not listed here. You can obtain their documentation with Rootfinder.doc(“myextraplugin”)

KINSOL interface from the Sundials suite

>List of available options

Id Type Description
abstol OT_DOUBLE Stopping criterion tolerance
disable_internal_warnings OT_BOOL Disable KINSOL internal warning messages
exact_jacobian OT_BOOL Use exact Jacobian information
f_scale OT_DOUBLEVECTOR Equation scaling factors
iterative_solver OT_STRING gmres|bcgstab|tfqmr
linear_solver_type OT_STRING dense|banded|iterative|use r_defined
lower_bandwidth OT_INT Lower bandwidth for banded linear solvers
max_iter OT_INT Maximum number of Newton iterations. Putting 0 sets the default value of KinSol.
max_krylov OT_INT Maximum Krylov space dimension
pretype OT_STRING Type of preconditioner
strategy OT_STRING Globalization strategy
u_scale OT_DOUBLEVECTOR Variable scaling factors
upper_bandwidth OT_INT Upper bandwidth for banded linear solvers
use_preconditioner OT_BOOL Precondition an iterative solver

Implements simple newton iterations to solve an implicit function.

>List of available options

Id Type Description
abstol OT_DOUBLE Stopping criterion tolerance on ||g||__inf)
abstolStep OT_DOUBLE Stopping criterion tolerance on step size
max_iter OT_INT Maximum number of Newton iterations to perform before returning.

Implements simple newton iterations to solve an implicit function.

>List of available options

Id Type Description
abstol OT_DOUBLE Stopping criterion tolerance on max(|F|)
abstolStep OT_DOUBLE Stopping criterion tolerance on step size
max_iter OT_INT Maximum number of Newton iterations to perform before returning.
print_iteration OT_BOOL Print information about each iteration

### 3.5. Linear systems¶

class Linsol(*args)
Linear solver Create a solver for linear systems of equations Solves the

linear system A*X = B or A^T*X = B for X with A square and non- singular.

If A is structurally singular, an error will be thrown during init. If A is numerically singular, the prepare step will fail.

• csparsecholesky
• csparse
• ma27
• lapacklu
• lapackqr
• ldl
• qr
• symbolicqr

Note: some of the plugins in this list might not be available on your system. Also, there might be extra plugins available to you that are not listed here. You can obtain their documentation with Linsol.doc(“myextraplugin”)

Linsol with CSparseCholesky Interface

Linsol with CSparse Interface

Interface to the sparse direct linear solver MA27 Works for symmetric indefinite systems Partly adopted from qpOASES 3.2 Joel Andersson

This class solves the linear system A.x=b by making an LU factorization of A: A = L.U, with L lower and U upper triangular

>List of available options

Id Type Description
allow_equilibration_failure OT_BOOL Non-fatal error when equilibration fails
equilibration OT_BOOL Equilibrate the matrix

This class solves the linear system A.x=b by making an QR factorization of A: A = Q.R, with Q orthogonal and R upper triangular

>List of available options

Id Type Description
max_nrhs OT_INT Maximum number of right-hand-sides that get processed in a single pass [default:10].

Linear solver using sparse direct LDL factorization

qr –

Linear solver using sparse direct QR factorization

Linear solver for sparse least-squares problems Inspired fromhttps://github.com/scipy/scipy/blob/v0.14.0/scipy/sparse/linalg/isolve/lsqr.py#L96

Linsol based on QR factorization with sparsity pattern based reordering without partial pivoting

>List of available options

Id Type Description
fopts OT_DICT Options to be passed to generated function objects

C++ includes: linsol.hpp

static doc(*args)
doc(str name) -> str

static has_plugin(*args)
has_plugin(str name) -> bool

static load_plugin(*args)
load_plugin(str name)

neig(*args)
Number of negative eigenvalues Not available for all solvers.
neig(self, DM A) -> int

nfact(*args)
Numeric factorization of the linear system.
nfact(self, DM A)

plugin_name(*args)
Query plugin name.
plugin_name(self) -> str

rank(*args)
Matrix rank Not available for all solvers.
rank(self, DM A) -> int

sfact(*args)
Symbolic factorization of the linear system, e.g. selecting pivots.
sfact(self, DM A)

solve(*args)
Solve linear system of equations
solve(self, DM A, DM B, bool tr) -> DM
solve(self, MX A, MX B, bool tr) -> MX

sparsity(*args)
Get linear system sparsity.
sparsity(self) -> Sparsity

static type_name(*args)
type_name() -> str
`