List of all members | Public Types | Public Member Functions | Static Public Member Functions | Protected Member Functions | Friends
casadi::MX Class Reference

MX - Matrix expression. More...

#include <mx.hpp>

Detailed Description

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.

Each node is a matrix-valued operation (symbolic primitive, constant, binary operation, concatenation, matrix product, call to a Function, ...), so an expression such as A+1 is a small number of nodes regardless of the matrix sizes. The graph is immutable: every operation creates new nodes. Symbolic primitives are created with MX.sym; MX(...) creates constants.

>>> x = MX.sym("x", 2)
>>> A = MX.sym("A", 2, 2)
>>> e = A @ x + 1
>>> e
MX((ones(2x1)+mac(A,x,zeros(2x1))))
>>> e.shape, e.n_dep(), e.is_symbolic()
((2, 1), 2, False)
>>> f = Function("f", [A, x], [e])
>>> f(DM([[1, 2], [3, 4]]), DM([1, 1]))
DM([4, 8])

>> x = MX.sym('x', 2); A = MX.sym('A', 2, 2);
>> e = A*x + 1;
>> e
(ones(2x1)+mac(A,x,zeros(2x1)))
>> size(e), e.n_dep(), e.is_symbolic()
2 1
2
0
>> f = Function('f', {A, x}, {e});
>> f(DM([1 2; 3 4]), DM([1; 1]))
[4, 8]

julia> x = ca.MX.sym("x", 2); A = ca.MX.sym("A", 2, 2);
julia> e = A * x + 1;
julia> e
MX((ones(2x1)+mac(A,x,zeros(2x1))))
julia> size(e), ca.n_dep(e), ca.is_symbolic(e)
((2, 1), 2, false)
julia> f = ca.Function("f", [A, x], [e]);
julia> f([1 2; 3 4], [1, 1])
DM([4, 8])

See also
SX, DM, Function
Author
Joel Andersson
Date
2010-2011

Extra doc: https://github.com/casadi/casadi/wiki/L_py

Definition at line 141 of file mx.hpp.

Inheritance diagram for casadi::MX:
Inheritance graph
[legend]
Collaboration diagram for casadi::MX:
Collaboration graph
[legend]

Public Types

typedef MX ScalarType
 
typedef GenericMatrix< MX > B
 Base class. More...
 
typedef std::map< std::string, MX > MXDict
 Readability typedef. More...
 
using internal_base_type = SharedObjectInternal
 
using base_type = SharedObject
 

Public Member Functions

 MX ()
 Default constructor: a 0-by-0 constant. More...
 
 MX (casadi_int nrow, casadi_int ncol)
 Create a sparse matrix with all structural zeros. More...
 
 MX (const std::pair< casadi_int, casadi_int > &rc)
 Create a sparse matrix with all structural zeros. More...
 
 MX (const Sparsity &sp)
 Create a constant with a given sparsity pattern and all nonzeros equal to one. More...
 
 MX (const Sparsity &sp, const MX &val)
 Construct a matrix with a given sparsity pattern and given nonzeros. More...
 
 MX (const Sparsity &sp, const std::string &fname)
 Construct a constant whose nonzeros are read from a text file. More...
 
 MX (const Matrix< double > &val, const std::string &name)
 Construct a named constant that generated code exposes as a modifiable pool. More...
 
 MX (double x)
 Create a 1-by-1 constant (also used for implicit conversion from a number) More...
 
 MX (const std::vector< double > &x)
 Create vector constant (also implicit type conversion) More...
 
 MX (const Matrix< double > &x)
 Create a constant from a DM (also used for implicit conversion) More...
 
 ~MX ()
 Destructor. More...
 
const Sparsity & sparsity () const
 Get the sparsity pattern. More...
 
bool __nonzero__ () const
 Truth value of a 1-by-1 constant. More...
 
Sparsity get_sparsity () const
 Get an owning reference to the sparsity pattern. More...
 
std::vector< MX > get_nonzeros () const
 Get the nonzeros as a list of 1-by-1 expressions. More...
 
void erase (const std::vector< casadi_int > &rr, const std::vector< casadi_int > &cc, bool ind1=false)
 Erase a submatrix (leaving structural zeros in its place) More...
 
void erase (const std::vector< casadi_int > &rr, bool ind1=false)
 Erase elements (leaving structural zeros in their place) More...
 
void enlarge (casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &rr, const std::vector< casadi_int > &cc, bool ind1=false)
 Enlarge matrix. More...
 
MX operator- () const
 Unary minus. More...
 
MX operator+ () const
 Unary plus: returns the expression itself. More...
 
MX inv () const
 Element-wise inverse, 1/x. More...
 
MX dep (casadi_int ch=0) const
 Get the ch-th dependency (child node) of this node. More...
 
casadi_int n_out () const
 Number of outputs of this node. More...
 
MX get_output (casadi_int oind) const
 Get an output of a multiple-output node. More...
 
casadi_int n_dep () const
 Get the number of dependencies (child nodes) of this node. More...
 
std::string name () const
 Get the name of a symbolic primitive. More...
 
 operator double () const
 Get the value of a 1-by-1 constant node (float conversion) More...
 
 operator Matrix< double > () const
 Get the value of a constant node as a DM. More...
 
bool is_symbolic () const
 Check if the node is a symbolic primitive (created by MX.sym) More...
 
bool is_constant () const
 Check if the node is a constant. More...
 
bool is_integer () const
 Check if the node is a constant with integer-valued nonzeros. More...
 
bool is_doubled () const
 Check if the node is the sum of two equal expressions, or 2*x. More...
 
bool is_call () const
 Check if the node is a call to a Function. More...
 
Function which_function () const
 Get the Function of a call node. More...
 
bool is_output () const
 Check if the node selects one output of a multiple-output node. More...
 
bool has_output () const
 Check if this is a multiple-output node. More...
 
casadi_int which_output () const
 Get the output index of an OutputNode. More...
 
bool is_op (casadi_int op) const
 Check if the node is a certain operation. More...
 
bool is_multiplication () const
 Check if the node is a matrix product (mtimes) More...
 
bool is_commutative () const
 Check if a binary operation is commutative. More...
 
bool is_norm () const
 Check if the node is a norm (norm_1, norm_2, norm_inf or norm_fro) More...
 
bool is_valid_input () const
 Check if the expression can be used as a Function input. More...
 
casadi_int n_primitives () const
 Get the number of symbolic primitives in a valid Function input. More...
 
std::vector< MX > primitives () const
 Get the symbolic primitives of a valid Function input. More...
 
bool has_duplicates () const
 Detect duplicate symbolic primitives in a Function input. More...
 
void reset_input () const
 Reset the marker set by has_duplicates on an input expression. More...
 
bool is_eye () const
 Check if the node is a constant identity matrix. More...
 
bool is_zero () const
 Check if the node is a constant zero (false negatives are possible) More...
 
bool is_one () const
 Check if the node is a constant with all nonzeros one (false negatives possible) More...
 
bool is_minus_one () const
 Check if the node is a constant with all nonzeros -1 (false negatives possible) More...
 
bool is_half () const
 Check if the node is a constant with all nonzeros 0.5 (false negatives possible) More...
 
bool is_value (double val) const
 Check if the node is a constant with all nonzeros equal to val. More...
 
bool is_inf () const
 Check if the node is a constant with all nonzeros +inf (false negatives possible) More...
 
bool is_minus_inf () const
 Check if the node is a constant with all nonzeros -inf (false negatives possible) More...
 
bool is_transpose () const
 Check if the node is a transpose operation. More...
 
bool is_regular () const
 Check that a constant node contains neither NaN nor Inf. More...
 
bool is_binary () const
 Check if the node is an elementwise binary operation. More...
 
bool is_nonnegative () const
 Check if a value is always nonnegative (false negatives are allowed) More...
 
bool is_unary () const
 Check if the node is an elementwise unary operation. More...
 
casadi_int op () const
 Get the operation type of the node. More...
 
Dict info () const
 Obtain information about the node as a dictionary. More...
 
void serialize (SerializingStream &s) const
 Serialize the expression to a stream. More...
 
casadi_int get_temp () const
 
void set_temp (casadi_int t) const
 Set the temporary variable. More...
 
MXNode * get () const
 Get a const pointer to the node. More...
 
MX nzref (const Sparsity &sp, const std::vector< casadi_int > &nz) const
 Low-level access to get_nzref. More...
 
MX printme (const MX &b) const
 Return the expression with the side effect of printing its value with a tag. More...
 
MX attachAssert (const MX &y, const std::string &fail_message="") const
 Return the expression with a run-time assertion attached. More...
 
MX monitor (const std::string &comment) const
 Return the expression with the side effect of printing its value. More...
 
MX dump (const std::string &base_filename, const Dict &opts=Dict()) const
 Return the expression with the side effect of writing its value to a file. More...
 
void reset_dump_count ()
 Reset the file counter of a dump node; raises an error on any other node. More...
 
MX T () const
 Transpose the matrix. More...
 
Matrix< casadi_int > mapping () const
 Get the nonzero mapping of a GetNonzeros or SetNonzeros node. More...
 
void eval_mx (const std::vector< MX > &arg, std::vector< MX > &res, const std::vector< bool > &unique=std::vector< bool >()) const
 Re-apply the operation of this node to new dependencies. More...
 
 MX (const Sparsity &sp, double val, bool dummy)
 Construct constant matrix with a given sparsity and values. More...
 
casadi_int nnz () const
 Get the number of structural nonzeros. More...
 
casadi_int nnz_lower () const
 Get the number of structural nonzeros on or below the diagonal. More...
 
casadi_int nnz_upper () const
 Get the number of structural nonzeros on or above the diagonal. More...
 
casadi_int nnz_diag () const
 Get the number of structural nonzeros on the diagonal. More...
 
casadi_int numel () const
 Get the number of elements, size1()*size2() More...
 
casadi_int size1 () const
 Get the first dimension (i.e. number of rows) More...
 
casadi_int rows () const
 Get the number of rows, Octave-style syntax (same as size1()) More...
 
casadi_int size2 () const
 Get the second dimension (i.e. number of columns) More...
 
casadi_int columns () const
 Get the number of columns, Octave-style syntax (same as size2()) More...
 
std::string dim (bool with_nz=false) const
 Get string representation of dimensions. More...
 
std::pair< casadi_int, casadi_int > size () const
 Get the shape as a pair (number of rows, number of columns) More...
 
casadi_int size (casadi_int axis) const
 Get the size along a particular dimension. More...
 
bool is_empty (bool both=false) const
 Check if the matrix is empty, i.e. if one of the dimensions is zero. More...
 
bool is_dense () const
 Check if the matrix is dense, i.e. nnz() equals numel() More...
 
bool is_scalar (bool scalar_and_dense=false) const
 Check if the matrix is scalar, i.e. 1-by-1. More...
 
bool is_square () const
 Check if the matrix is square, i.e. size1() equals size2() More...
 
bool is_vector () const
 Check if the matrix is a row or column vector. More...
 
bool is_row () const
 Check if the matrix is a row vector (i.e. size1()==1) More...
 
bool is_column () const
 Check if the matrix is a column vector (i.e. size2()==1) More...
 
bool is_triu () const
 Check if the matrix is upper triangular. More...
 
bool is_tril () const
 Check if the matrix is lower triangular. More...
 
const MX nz (const K &k) const
 Get vector nonzero or slice of nonzeros. More...
 
NonZeros< MX, K > nz (const K &k)
 Access vector nonzero or slice of nonzeros. More...
 
const MX operator() (const RR &rr) const
 Get vector element or slice. More...
 
const MX operator() (const RR &rr, const CC &cc) const
 Get Matrix element or slice. More...
 
SubIndex< MX, RR > operator() (const RR &rr)
 Access Matrix elements (one argument) More...
 
SubMatrix< MX, RR, CC > operator() (const RR &rr, const CC &cc)
 Access Matrix elements (two arguments) More...
 
std::string class_name () const
 Get class name. More...
 
void disp (std::ostream &stream, bool more=false) const
 Print a description of the object. More...
 
std::string get_str (bool more=false) const
 Get string representation. More...
 
void print_ptr (std::ostream &stream=casadi::uout()) const
 
void own (SharedObjectInternal *node)
 
void assign (SharedObjectInternal *node)
 Assign the node to a node class pointer without reference counting. More...
 
casadi_int getCount () const
 Get the reference count. More...
 
void swap (GenericShared &other)
 Swap content with another instance. More...
 
std::string debug_repr () const
 
bool is_null () const
 Is a null pointer? More...
 
casadi_int __hash__ () const
 Returns a number that is unique for a given Node. More...
 
GenericWeakRef< SharedObject, SharedObjectInternal > * weak ()
 Get a weak reference to the object. More...
 
MXNode * operator-> ()
 Access a member of the node. More...
 
const MXNode * operator-> () const
 Const access a member of the node. More...
 
std::vector< MX > split_primitives (const MX &x) const
 Split a value along the symbolic primitives of this expression. More...
 
std::vector< SX > split_primitives (const SX &x) const
 Split a value along the symbolic primitives of this expression. More...
 
std::vector< DM > split_primitives (const DM &x) const
 Split a value along the symbolic primitives of this expression. More...
 
MX join_primitives (const std::vector< MX > &v) const
 Join values along the symbolic primitives of this expression. More...
 
SX join_primitives (const std::vector< SX > &v) const
 Join values along the symbolic primitives of this expression. More...
 
DM join_primitives (const std::vector< DM > &v) const
 Join values along the symbolic primitives of this expression. More...
 
void get (MX &m, bool ind1, const Slice &rr) const
 Get a submatrix by linear index (what x[k] does) More...
 
void get (MX &m, bool ind1, const Matrix< casadi_int > &rr) const
 Get a submatrix by linear index (what x[k] does) More...
 
void get (MX &m, bool ind1, const Sparsity &sp) const
 Get a submatrix by linear index (what x[k] does) More...
 
void get (MX &m, bool ind1, const MX &rr) const
 Get a submatrix by linear index (what x[k] does) More...
 
void get (MX &m, bool ind1, const casadi_int rr) const
 Get a submatrix by linear index (what x[k] does) More...
 
void get (MX &m, bool ind1, const Slice &rr, const Slice &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, const Slice &rr, const Matrix< casadi_int > &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, const Slice &rr, casadi_int cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, const Matrix< casadi_int > &rr, const Slice &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, casadi_int rr, const Slice &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, const Matrix< casadi_int > &rr, const Matrix< casadi_int > &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, casadi_int rr, casadi_int cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, const MX &rr, const Slice &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, const Slice &rr, const MX &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void get (MX &m, bool ind1, const MX &rr, const MX &cc) const
 Get a submatrix by row and column index (what x[i, j] does) More...
 
void set (const MX &m, bool ind1, const Slice &rr)
 Assign to a submatrix by linear index (what x[k] = m does) More...
 
void set (const MX &m, bool ind1, const Matrix< casadi_int > &rr)
 Assign to a submatrix by linear index (what x[k] = m does) More...
 
void set (const MX &m, bool ind1, const Sparsity &sp)
 Assign to a submatrix by linear index (what x[k] = m does) More...
 
void set (const MX &m, bool ind1, const Slice &rr, const Slice &cc)
 Assign to a submatrix by row and column index (what x[i, j] = m does) More...
 
void set (const MX &m, bool ind1, const Slice &rr, const Matrix< casadi_int > &cc)
 Assign to a submatrix by row and column index (what x[i, j] = m does) More...
 
void set (const MX &m, bool ind1, const Matrix< casadi_int > &rr, const Slice &cc)
 Assign to a submatrix by row and column index (what x[i, j] = m does) More...
 
void set (const MX &m, bool ind1, const Matrix< casadi_int > &rr, const Matrix< casadi_int > &cc)
 Assign to a submatrix by row and column index (what x[i, j] = m does) More...
 
void get_nz (MX &m, bool ind1, const Slice &kk) const
 Get a set of nonzeros (what x.nz[k] does) More...
 
void get_nz (MX &m, bool ind1, const Matrix< casadi_int > &kk) const
 Get a set of nonzeros (what x.nz[k] does) More...
 
void get_nz (MX &m, bool ind1, const MX &kk) const
 Get a set of nonzeros (what x.nz[k] does) More...
 
void get_nz (MX &m, bool ind1, casadi_int kk) const
 Get a set of nonzeros (what x.nz[k] does) More...
 
void get_nz (MX &m, bool ind1, const MX &inner, const Slice &outer) const
 Get a set of nonzeros (what x.nz[k] does) More...
 
void get_nz (MX &m, bool ind1, const Slice &inner, const MX &outer) const
 Get a set of nonzeros (what x.nz[k] does) More...
 
void get_nz (MX &m, bool ind1, const MX &inner, const MX &outer) const
 Get a set of nonzeros (what x.nz[k] does) More...
 
void set_nz (const MX &m, bool ind1, const Slice &kk)
 Assign to a set of nonzeros (what x.nz[k] = m does) More...
 
void set_nz (const MX &m, bool ind1, const Matrix< casadi_int > &kk)
 Assign to a set of nonzeros (what x.nz[k] = m does) More...
 
void set_nz (const MX &m, bool ind1, const MX &kk)
 Assign to a set of nonzeros (what x.nz[k] = m does) More...
 
void set_nz (const MX &m, bool ind1, casadi_int kk)
 Assign to a set of nonzeros (what x.nz[k] = m does) More...
 
void ad_forward (const std::vector< std::vector< MX > > &fseed, std::vector< std::vector< MX > > &fsens) const
 Called from MXFunction. More...
 
void ad_reverse (const std::vector< std::vector< MX > > &aseed, std::vector< std::vector< MX > > &asens) const
 Called from MXFunction. More...
 
std::vector< casadi_int > get_row () const
 Get the sparsity pattern. See the Sparsity class for details. More...
 
std::vector< casadi_int > get_colind () const
 Get the sparsity pattern. See the Sparsity class for details. More...
 
const casadi_int * row () const
 Get the sparsity pattern. See the Sparsity class for details. More...
 
casadi_int row (casadi_int el) const
 Get the sparsity pattern. See the Sparsity class for details. More...
 
const casadi_int * colind () const
 Get the sparsity pattern. See the Sparsity class for details. More...
 
casadi_int colind (casadi_int col) const
 Get the sparsity pattern. See the Sparsity class for details. More...
 

Static Public Member Functions

static std::string type_name ()
 Get type name. More...
 
static MX create (MXNode *node)
 Create from node. More...
 
static std::vector< MX > createMultipleOutput (MXNode *node)
 Create from node (multiple-outputs) More...
 
static MX deserialize (DeserializingStream &s)
 Deserialize an expression from a stream, with type disambiguation. More...
 
static MX eye (casadi_int n)
 Identity matrix constant of size n-by-n, with a diagonal sparsity pattern. More...
 
static bool simplify_ref_count (std::vector< MX > &arg, std::vector< MX > &res, const Dict &opts=Dict())
 
static bool simplify_const_folding (std::vector< MX > &arg, std::vector< MX > &res, const Dict &opts=Dict())
 
static bool simplify_combine_terms (std::vector< MX > &arg, std::vector< MX > &res, const Dict &opts=Dict())
 
static DM bspline_dual (const std::vector< double > &x, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, const Dict &opts=Dict())
 Evaluate the B-spline basis functions at given points. More...
 
static MX interpn_linear (const std::vector< MX > &x, const MX &v, const std::vector< MX > &xq, const Dict &opts=Dict())
 Low-level inlined multilinear interpolation. More...
 
static void set_max_depth (casadi_int eq_depth=1)
 Set the depth to which equalities are checked for simplifications. More...
 
static casadi_int get_max_depth ()
 Get the depth to which equalities are checked for simplifications. More...
 
static bool test_cast (const SharedObjectInternal *ptr)
 Check if a SharedObjectInternal pointer refers to an MX node (C++ only) More...
 
static std::vector< MX > get_input (const Function &f)
 Get the symbolic inputs of a Function, as MX. More...
 
static std::vector< MX > get_free (const Function &f)
 Get the free variables of a Function. More...
 
static MX _sym (const std::string &name, const Sparsity &sp)
 
static MX logsumexp (const MX &x)
 
static MX binary (casadi_int op, const MX &x, const MX &y, bool unique_x=false, bool unique_y=false)
 Create an elementwise binary or unary node from an operation code. More...
 
static MX unary (casadi_int op, const MX &x, bool unique=false)
 Create an elementwise binary or unary node from an operation code. More...
 
static MX inf (const Sparsity &sp)
 Create a constant with all nonzeros +inf. More...
 
static MX inf (casadi_int nrow=1, casadi_int ncol=1)
 Create a constant with all nonzeros +inf. More...
 
static MX inf (const std::pair< casadi_int, casadi_int > &rc)
 Create a constant with all nonzeros +inf. More...
 
static MX nan (const Sparsity &sp)
 Create a constant with all nonzeros NaN. More...
 
static MX nan (casadi_int nrow=1, casadi_int ncol=1)
 Create a constant with all nonzeros NaN. More...
 
static MX nan (const std::pair< casadi_int, casadi_int > &rc)
 Create a constant with all nonzeros NaN. More...
 
static MX einstein (const MX &A, const MX &B, const MX &C, const std::vector< casadi_int > &dim_a, const std::vector< casadi_int > &dim_b, const std::vector< casadi_int > &dim_c, const std::vector< casadi_int > &a, const std::vector< casadi_int > &b, const std::vector< casadi_int > &c)
 Compute a dense tensor contraction in Einstein notation. More...
 
static MX einstein (const MX &A, const MX &B, const std::vector< casadi_int > &dim_a, const std::vector< casadi_int > &dim_b, const std::vector< casadi_int > &dim_c, const std::vector< casadi_int > &a, const std::vector< casadi_int > &b, const std::vector< casadi_int > &c)
 Compute a dense tensor contraction in Einstein notation. More...
 
static bool is_equal (const MX &x, const MX &y, casadi_int depth=0)
 
static MX mmin (const MX &x)
 
static MX mmax (const MX &x)
 
static MX horzcat (const std::vector< MX > &x)
 
static MX diagcat (const std::vector< MX > &x)
 
static MX vertcat (const std::vector< MX > &x)
 
static std::vector< MX > horzsplit (const MX &x, const std::vector< casadi_int > &offset)
 
static std::vector< MX > diagsplit (const MX &x, const std::vector< casadi_int > &offset1, const std::vector< casadi_int > &offset2)
 
static std::vector< MX > vertsplit (const MX &x, const std::vector< casadi_int > &offset)
 
static MX blockcat (const std::vector< std::vector< MX > > &v)
 
static MX mtimes (const MX &x, const MX &y, const std::string &blas="reference")
 
static MX mac (const MX &x, const MX &y, const MX &z, const std::string &blas="reference")
 
static MX reshape (const MX &x, casadi_int nrow, casadi_int ncol)
 
static MX reshape (const MX &x, const Sparsity &sp)
 
static MX sparsity_cast (const MX &x, const Sparsity &sp)
 
static MX kron (const MX &x, const MX &b)
 
static MX kron_contract (const MX &m, const MX &x, bool inner)
 
static MX repmat (const MX &x, casadi_int n, casadi_int m=1)
 
static MX linspace (const MX &a, const MX &b, casadi_int nsteps)
 
static MX jacobian (const MX &f, const MX &x, const Dict &opts=Dict())
 
static MX hessian (const MX &f, const MX &x, const Dict &opts=Dict())
 
static MX hessian (const MX &f, const MX &x, MX &g, const Dict &opts=Dict())
 
static std::vector< std::vector< MX > > forward (const std::vector< MX > &ex, const std::vector< MX > &arg, const std::vector< std::vector< MX > > &v, const Dict &opts=Dict())
 
static std::vector< std::vector< MX > > reverse (const std::vector< MX > &ex, const std::vector< MX > &arg, const std::vector< std::vector< MX > > &v, const Dict &opts=Dict())
 
static std::vector< bool > which_depends (const MX &expr, const MX &var, casadi_int order=1, bool tr=false)
 
static Sparsity jacobian_sparsity (const MX &f, const MX &x)
 
static MX substitute (const MX &ex, const MX &v, const MX &vdef)
 
static std::vector< MX > substitute (const std::vector< MX > &ex, const std::vector< MX > &v, const std::vector< MX > &vdef)
 
static void substitute_inplace (const std::vector< MX > &v, std::vector< MX > &vdef, std::vector< MX > &ex, bool reverse)
 
static MX solve (const MX &a, const MX &b)
 
static MX solve (const MX &a, const MX &b, const std::string &lsolver, const Dict &dict=Dict())
 
static MX inv_minor (const MX &A)
 
static MX inv_node (const MX &A)
 
static MX inv (const MX &A, const std::string &lsolver="qr", const Dict &dict=Dict())
 
static MX pinv (const MX &A, const std::string &lsolver="qr", const Dict &dict=Dict())
 
static MX expm_const (const MX &A, const MX &t)
 
static MX expm (const MX &A)
 
static casadi_int n_nodes (const MX &x)
 
static std::string print_operator (const MX &x, const std::vector< std::string > &args)
 
static void extract (std::vector< MX > &ex, std::vector< MX > &v, std::vector< MX > &vdef, const Dict &opts=Dict())
 
static void shared (std::vector< MX > &ex, std::vector< MX > &v, std::vector< MX > &vdef, const std::string &v_prefix, const std::string &v_suffix)
 
static MX if_else (const MX &cond, const MX &if_true, const MX &if_false, bool short_circuit=false)
 
static MX conditional (const MX &ind, const std::vector< MX > &x, const MX &x_default, bool short_circuit=false)
 
static bool depends_on (const MX &x, const MX &arg)
 
static bool contains_all (const std::vector< MX > &v, const std::vector< MX > &n)
 
static bool contains_any (const std::vector< MX > &v, const std::vector< MX > &n)
 
static MX simplify (const MX &x)
 
static MX transform (const MX &x, const Dict &opts=Dict())
 
static MX transform (const MX &x, const std::vector< std::vector< GenericType > > &passes, const Dict &opts=Dict())
 
static std::vector< MX > transform (const std::vector< MX > &x, const Dict &opts=Dict())
 
static std::vector< MX > transform (const std::vector< MX > &x, const std::vector< std::vector< GenericType > > &passes, const Dict &opts=Dict())
 
static MX dot (const MX &x, const MX &y)
 
static MX mrdivide (const MX &a, const MX &b)
 
static MX mldivide (const MX &a, const MX &b)
 
static MX norm_2 (const MX &x)
 
static MX norm_fro (const MX &x)
 
static MX norm_1 (const MX &x)
 
static MX norm_inf (const MX &x)
 
static MX unite (const MX &A, const MX &B)
 
static MX trace (const MX &x)
 
static MX diag (const MX &x)
 
static MX sum2 (const MX &x)
 
static MX sum1 (const MX &x)
 
static MX polyval (const MX &p, const MX &x)
 
static MX det (const MX &x)
 
static MX det (const MX &x, const std::string &lsolver, const Dict &opts=Dict())
 
static std::vector< MX > symvar (const MX &x)
 
static MX nullspace (const MX &A)
 
static MX repsum (const MX &x, casadi_int n, casadi_int m=1)
 
static MX densify (const MX &x, const MX &val=0)
 
static MX _bilin (const MX &A, const MX &x, const MX &y)
 
static MX _rank1 (const MX &A, const MX &alpha, const MX &x, const MX &y)
 
static MX project (const MX &x, const Sparsity &sp, bool intersect=false)
 
static MX cumsum (const MX &x, casadi_int axis=-1)
 
static MX _logsumexp (const MX &x)
 
static std::vector< MX > cse (const std::vector< MX > &e)
 
static void extract_parametric (const MX &expr, const MX &par, MX &expr_ret, std::vector< MX > &symbols, std::vector< MX > &parametric, const Dict &opts)
 
static void separate_linear (const MX &expr, const MX &sym_lin, const MX &sym_const, MX &expr_const, MX &expr_lin, MX &expr_nonlin)
 
static MX find (const MX &x)
 
static MX low (const MX &v, const MX &p, const Dict &options=Dict())
 
static MX graph_substitute (const MX &x, const std::vector< MX > &v, const std::vector< MX > &vdef)
 
static MX graph_substitute (const MX &x, const std::vector< MX > &v, const std::vector< MX > &vdef, bool &updated)
 
static std::vector< MX > graph_substitute (const std::vector< MX > &ex, const std::vector< MX > &v, const std::vector< MX > &vdef)
 
static std::vector< MX > graph_substitute (const std::vector< MX > &ex, const std::vector< MX > &v, const std::vector< MX > &vdef, bool &updated)
 
static MX matrix_expand (const MX &e, const std::vector< MX > &boundary, const Dict &options)
 
static std::vector< MX > matrix_expand (const std::vector< MX > &e, const std::vector< MX > &boundary, const Dict &options)
 
static MX lift (const MX &x, const MX &x_guess)
 
static DM evalf (const MX &m)
 
static MX bspline (const MX &x, const DM &coeffs, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts=Dict())
 
static MX bspline (const MX &x, const MX &coeffs, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts=Dict())
 
static MX bspline (const MX &x, const MX &coeffs, const std::vector< MX > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts=Dict())
 
static MX convexify (const MX &H, const Dict &opts=Dict())
 
static MX stop_diff (const MX &expr, casadi_int order)
 
static MX stop_diff (const MX &expr, const MX &var, casadi_int order)
 
static std::vector< MX > difference (const std::vector< MX > &a, const std::vector< MX > &b)
 
static MX interp1d (const std::vector< double > &x, const MX &v, const std::vector< double > &xq, const std::string &mode, bool equidistant)
 Functions called by friend functions defined here. More...
 
static casadi_int sprank (const MX &x)
 Functions called by friend functions defined here. More...
 
static casadi_int norm_0_mul (const MX &x, const MX &y)
 Functions called by friend functions defined here. More...
 
static MX tril (const MX &x, bool includeDiagonal=true)
 Functions called by friend functions defined here. More...
 
static MX triu (const MX &x, bool includeDiagonal=true)
 Functions called by friend functions defined here. More...
 
static MX sumsqr (const MX &x)
 Functions called by friend functions defined here. More...
 
static MX linspace (const MX &a, const MX &b, casadi_int nsteps)
 Functions called by friend functions defined here. More...
 
static MX cross (const MX &a, const MX &b, casadi_int dim=-1)
 Functions called by friend functions defined here. More...
 
static MX skew (const MX &a)
 Functions called by friend functions defined here. More...
 
static MX inv_skew (const MX &a)
 Functions called by friend functions defined here. More...
 
static MX tril2symm (const MX &x)
 Functions called by friend functions defined here. More...
 
static MX triu2symm (const MX &x)
 Functions called by friend functions defined here. More...
 
static MX repsum (const MX &x, casadi_int n, casadi_int m=1)
 Functions called by friend functions defined here. More...
 
static MX diff (const MX &x, casadi_int n=1, casadi_int axis=-1)
 Functions called by friend functions defined here. More...
 
static bool is_linear (const MX &expr, const MX &var)
 Functions called by friend functions defined here. More...
 
static bool is_quadratic (const MX &expr, const MX &var)
 Functions called by friend functions defined here. More...
 
static void quadratic_coeff (const MX &expr, const MX &var, MX &A, MX &b, MX &c, bool check)
 Functions called by friend functions defined here. More...
 
static void linear_coeff (const MX &expr, const MX &var, MX &A, MX &b, bool check)
 Functions called by friend functions defined here. More...
 
static MX mpower (const MX &x, const MX &y)
 
static MX soc (const MX &x, const MX &y)
 
static MX linearize (const MX &f, const MX &x, const MX &x0, const Dict &opts=Dict())
 
static MX gradient (const MX &ex, const MX &arg, const Dict &opts=Dict())
 
static MX tangent (const MX &ex, const MX &arg, const Dict &opts=Dict())
 
static MX jtimes (const MX &ex, const MX &arg, const MX &v, bool tr=false, const Dict &opts=Dict())
 
static MX bilin (const MX &A, const MX &x, const MX &y)
 Calculate bilinear/quadratic form x^T A y. More...
 
static MX rank1 (const MX &A, const MX &alpha, const MX &x, const MX &y)
 Make a rank-1 update to a matrix A. More...
 
Construct symbolic primitives

The "sym" function is intended to work in a similar way as "sym" used in the Symbolic Toolbox for Matlab but instead creating a CasADi symbolic primitive.

static MX sym (const std::string &name, casadi_int nrow=1, casadi_int ncol=1)
 Create an nrow-by-ncol symbolic primitive. More...
 
static MX sym (const std::string &name, const std::pair< casadi_int, casadi_int > &rc)
 Construct a symbolic primitive with given dimensions, as a pair (nrow, ncol) More...
 
static MX sym (const std::string &name, const Sparsity &sp)
 Create symbolic primitive with a given sparsity pattern. More...
 
static std::vector< MX > sym (const std::string &name, const Sparsity &sp, casadi_int p)
 Create a list of length p of symbolic primitives with a given sparsity. More...
 
static std::vector< MX > sym (const std::string &name, casadi_int nrow, casadi_int ncol, casadi_int p)
 Create a list of length p of nrow-by-ncol symbolic primitives. More...
 
static std::vector< std::vector< MX > > sym (const std::string &name, const Sparsity &sp, casadi_int p, casadi_int r)
 Create a list of length r of lists of length p of symbolic primitives. More...
 
static std::vector< std::vector< MX > > sym (const std::string &name, casadi_int nrow, casadi_int ncol, casadi_int p, casadi_int r)
 Create a list of length r of lists of length p of nrow-by-ncol symbolic primitives. More...
 
static MX zeros (casadi_int nrow=1, casadi_int ncol=1)
 Create a dense matrix or a matrix with specified sparsity with all entries zero. More...
 
static MX zeros (const Sparsity &sp)
 Create a dense matrix or a matrix with specified sparsity with all entries zero. More...
 
static MX zeros (const std::pair< casadi_int, casadi_int > &rc)
 Create a dense matrix or a matrix with specified sparsity with all entries zero. More...
 
static MX ones (casadi_int nrow=1, casadi_int ncol=1)
 Create a dense matrix or a matrix with specified sparsity with all entries one. More...
 
static MX ones (const Sparsity &sp)
 Create a dense matrix or a matrix with specified sparsity with all entries one. More...
 
static MX ones (const std::pair< casadi_int, casadi_int > &rc)
 Create a dense matrix or a matrix with specified sparsity with all entries one. More...
 

Protected Member Functions

void count_up ()
 
void count_down ()
 

Static Private Member Functions

static MX printme (const MX &x, const MX &y)
 Debug printing: (x,y) -> x, printing x when evaluated. More...
 

Friends

MX find (const MX &x)
 Find the index of the first nonzero entry of a vector. More...
 
MX low (const MX &v, const MX &p, const Dict &options=Dict())
 Find the interval of a sorted grid that contains each query value. More...
 
MX graph_substitute (const MX &ex, const std::vector< MX > &v, const std::vector< MX > &vdef)
 Substitute nodes in the expression graph, by node identity. More...
 
MX graph_substitute (const MX &ex, const std::vector< MX > &v, const std::vector< MX > &vdef, bool &updated)
 
std::vector< MX > graph_substitute (const std::vector< MX > &ex, const std::vector< MX > &v, const std::vector< MX > &vdef)
 Substitute nodes in several expressions at once, by node identity. More...
 
std::vector< MX > graph_substitute (const std::vector< MX > &ex, const std::vector< MX > &v, const std::vector< MX > &vdef, bool &updated)
 
MX matrix_expand (const MX &e, const std::vector< MX > &boundary=std::vector< MX >(), const Dict &options=Dict())
 Expand an MX expression into a call to an SX Function. More...
 
std::vector< MX > matrix_expand (const std::vector< MX > &e, const std::vector< MX > &boundary=std::vector< MX >(), const Dict &options=Dict())
 Expand several MX expressions into one call to an SX Function. More...
 
MX bspline (const MX &x, const DM &coeffs, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts=Dict())
 Evaluate a tensor-product B-spline with fixed coefficients. More...
 
MX bspline (const MX &x, const MX &coeffs, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts=Dict())
 Evaluate a B-spline whose coefficients are an expression. More...
 
MX bspline (const MX &x, const MX &coeffs, const std::vector< MX > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts=Dict())
 Evaluate a B-spline whose knots and coefficients are expressions. More...
 
DM bspline_dual (const std::vector< double > &x, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, const Dict &opts=Dict())
 Evaluate the B-spline basis functions at given points, see MX::bspline_dual. More...
 
MX convexify (const MX &H, const Dict &opts=Dict())
 Make a symmetric matrix positive definite at evaluation time. More...
 
MX lift (const MX &x, const MX &x_guess)
 Lift the expression. More...
 
MX inv_node (const MX &x)
 Symbolic matrix inverse node. More...
 
DM evalf (const MX &expr)
 Evaluate an expression without free symbols numerically. More...
 
MX stop_diff (const MX &expr, casadi_int order)
 Stop derivatives of an expression with respect to all its symbolic variables. More...
 
MX no_grad (const MX &expr)
 Treat an expression as constant for differentiation (stop first derivatives) More...
 
MX no_hess (const MX &expr)
 Stop second derivatives of an expression wrt all its symbolic variables. More...
 
MX stop_diff (const MX &expr, const MX &var, casadi_int order)
 Stop derivatives of an expression wrt a selected set of symbolic variables. More...
 
std::vector< MX > difference (const std::vector< MX > &a, const std::vector< MX > &b)
 Return all elements of a that do not occur in b, preserving order. More...
 

Member Typedef Documentation

◆ B

Definition at line 577 of file mx.hpp.

◆ base_type

Definition at line 103 of file shared_object.hpp.

◆ internal_base_type

Definition at line 102 of file shared_object.hpp.

◆ MXDict

typedef std::map<std::string, MX> casadi::MX::MXDict

Definition at line 5053 of file mx.hpp.

◆ ScalarType

Scalar type

Definition at line 573 of file mx.hpp.

Constructor & Destructor Documentation

◆ MX() [1/11]

casadi::MX::MX ( )

The result is an empty constant, not a symbolic primitive (use MX.sym for that).

>>> MX(), MX().shape, MX().is_constant()
(MX(0x0), (0, 0), True)

>> MX(), size(MX()), MX().is_constant()
0x0
0 0
1

julia> ca.MX(), size(ca.MX()), ca.is_constant(ca.MX())
(0x0, (0, 0), true)

Extra doc: https://github.com/casadi/casadi/wiki/L_q0

Definition at line 61 of file mx.cpp.

61  {
63  }
static ZeroByZero * getInstance()
Get a pointer to the singleton.

References casadi::ZeroByZero::getInstance(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

Referenced by binary(), blockcat(), create(), createMultipleOutput(), cse(), diagcat(), extract(), extract_parametric(), eye(), graph_substitute(), horzcat(), repmat(), separate_linear(), set(), set_nz(), simplify_const_folding(), simplify_ref_count(), solve(), and vertcat().

◆ MX() [2/11]

casadi::MX::MX ( casadi_int  nrow,
casadi_int  ncol 
)

The result is a constant of shape nrow-by-ncol without any nonzeros. It is the usual starting point for building a matrix by assignment: assigning to an element grows the sparsity pattern.

>>> Z = MX(2, 3)
>>> Z, Z.nnz(), Z.is_zero()
(MX(zeros(2x3,0nz)), 0, True)
>>> Z[1, 2] = MX.sym("x")
>>> Z.sparsity()
Sparsity(2x3,1nz)

>> Z = MX(2, 3);
>> Z, Z.nnz(), Z.is_zero()
zeros(2x3,0nz)
0
1
>> Z(2, 3) = MX.sym('x');
>> Z.sparsity()
2x3,1nz

julia> Z = ca.MX(2, 3);
julia> Z, ca.nnz(Z), ca.is_zero(Z)
(zeros(2x3,0nz), 0, true)
julia> Z[2, 3] = ca.MX.sym("x");
julia> ca.sparsity(Z)
Sparsity(2x3,1nz)

See also
MX.zeros, MX.sym

Extra doc: https://github.com/casadi/casadi/wiki/L_q1

Definition at line 111 of file mx.cpp.

111  {
112  own(ConstantMX::create(Sparsity(nrow, ncol), 0));
113  }
static ConstantMX * create(const Sparsity &sp, casadi_int val)

References casadi::ConstantMX::create(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

◆ MX() [3/11]

casadi::MX::MX ( const std::pair< casadi_int, casadi_int > &  rc)
explicit

◆ MX() [4/11]

casadi::MX::MX ( const Sparsity &  sp)
explicit

Same as MX::ones(sp).

>>> MX(Sparsity.lower(2))
MX(ones(2x2,3nz))
>>> evalf(MX(Sparsity.lower(2)))
DM(
[[1, 00],
 [1, 1]])

>> MX(Sparsity.lower(2))
ones(2x2,3nz)
>> evalf(MX(Sparsity.lower(2)))
[[1, 00],
 [1, 1]]

julia> ca.MX(ca.Sparsity.lower(2))
MX(ones(2x2,3nz))
julia> ca.evalf(ca.MX(ca.Sparsity.lower(2)))
DM(
[[1, 00],
 [1, 1]])

See also
MX.ones

Extra doc: https://github.com/casadi/casadi/wiki/L_q3

Definition at line 107 of file mx.cpp.

107  {
108  own(ConstantMX::create(sp, 1));
109  }

References casadi::ConstantMX::create(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

◆ MX() [5/11]

casadi::MX::MX ( const Sparsity &  sp,
const MX &  val 
)
Parameters
spSparsity pattern of the result
valEither a scalar, which is repeated over all nonzeros of sp, or a column vector with exactly sp.nnz() entries, which become the nonzeros of the result in column-major order. A matrix whose shape is a reshape of sp is reshaped. Anything else is an error.

val may be symbolic; the result is then an expression, not a constant.

>>> v = MX.sym("v", 3)
>>> L = MX(Sparsity.lower(2), v)
>>> L.sparsity(), L.is_constant()
(Sparsity(2x2,3nz), False)
>>> Function("f", [v], [L])(DM([1, 2, 3]))
DM(
[[1, 00],
 [2, 3]])
>>> evalf(MX(Sparsity.lower(2), MX(7)))
DM(
[[7, 00],
 [7, 7]])

>> v = MX.sym('v', 3);
>> L = MX(Sparsity.lower(2), v);
>> L.sparsity(), L.is_constant()
2x2,3nz
0
>> f = Function('f', {v}, {L});
>> f(DM([1; 2; 3]))
[[1, 00],
 [2, 3]]
>> evalf(MX(Sparsity.lower(2), MX(7)))
[[7, 00],
 [7, 7]]

julia> v = ca.MX.sym("v", 3);
julia> L = ca.MX(ca.Sparsity.lower(2), v);
julia> ca.sparsity(L), ca.is_constant(L)
(2x2,3nz, false)
julia> ca.Function("f", [v], [L])([1, 2, 3])
DM(
[[1, 00],
 [2, 3]])
julia> ca.evalf(ca.MX(ca.Sparsity.lower(2), ca.MX(7)))
DM(
[[7, 00],
 [7, 7]])

See also
MX.sym, sparsity_cast

Extra doc: https://github.com/casadi/casadi/wiki/L_q4

Definition at line 85 of file mx.cpp.

85  {
86  if (sp.is_reshape(val.sparsity())) {
87  *this = reshape(val, sp);
88  } else if (val.is_scalar()) {
89  // Dense matrix if val dense
90  if (val.is_dense()) {
91  if (val.is_constant()) {
92  own(ConstantMX::create(sp, static_cast<double>(val)));
93  } else {
94  *this = val->get_nzref(sp, std::vector<casadi_int>(sp.nnz(), 0));
95  }
96  } else {
97  // Empty matrix
98  own(ConstantMX::create(Sparsity(sp.size()), 0));
99  }
100  } else {
101  casadi_assert(val.is_column() && sp.nnz()==val.size1(),
102  "Expected a column vector with " + str(sp.nnz()) + " nonzeros, but got " + val.dim() + ".");
103  *this = densify(val)->get_nzref(sp, range(sp.nnz()));
104  }
105  }
virtual MX get_nzref(const Sparsity &sp, const std::vector< casadi_int > &nz, bool unique=false) const
Get the nonzeros of matrix.
Definition: mx_node.cpp:661
static MX reshape(const MX &x, casadi_int nrow, casadi_int ncol)
Definition: mx.cpp:1334
static MX densify(const MX &x, const MX &val=0)
Definition: mx.cpp:926
std::vector< casadi_int > range(casadi_int start, casadi_int stop, casadi_int step, casadi_int len)
Range function.
std::string str(const T &v)
String representation, any type.

References casadi::ConstantMX::create(), densify(), casadi::GenericMatrix< MatType >::dim(), casadi::MXNode::get_nzref(), casadi::GenericMatrix< MatType >::is_column(), is_constant(), casadi::GenericMatrix< MatType >::is_dense(), casadi::Sparsity::is_reshape(), casadi::GenericMatrix< MatType >::is_scalar(), casadi::Sparsity::nnz(), casadi::GenericShared< SharedObject, SharedObjectInternal >::own(), casadi::range(), reshape(), casadi::Sparsity::size(), casadi::GenericMatrix< MatType >::size1(), sparsity(), and casadi::str().

◆ MX() [6/11]

casadi::MX::MX ( const Sparsity &  sp,
const std::string &  fname 
)

The file must contain exactly sp.nnz() whitespace-separated numbers, giving the nonzeros in column-major order; otherwise an error is raised. In generated C code the file is read at initialization time rather than embedded in the source. The node cannot be converted with to_DM.

Parameters
fnamePath of the file, read when the constructor runs

>>> try:
...   MX(Sparsity.lower(2), "no_such_file.txt")
... except Exception as e:
...   print("Cannot open file" in str(e))
True

>> try, MX(Sparsity.lower(2), 'no_such_file.txt'); catch e, disp('cannot open file'); end
cannot open file

julia> try
           ca.MX(ca.Sparsity.lower(2), "no_such_file.txt")
       catch e
           println(occursin("Cannot open file", sprint(showerror, e)))
       end
true

Extra doc: https://github.com/casadi/casadi/wiki/L_q5

Definition at line 123 of file mx.cpp.

123  {
124  own(ConstantMX::create(sp, fname));
125  }

References casadi::ConstantMX::create(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

◆ MX() [7/11]

casadi::MX::MX ( const Matrix< double > &  val,
const std::string &  name 
)

Behaves like the constant val during evaluation. In generated C code the nonzeros are placed in a named double pool so that they can be changed after compilation. The node cannot be converted with to_DM.

>>> p = MX(DM([1, 2]), "p")
>>> p, p.is_constant()
(MX(constant_pool('p'): [1, 2]), True)
>>> evalf(2*p)
DM([2, 4])

>> p = MX(DM([1; 2]), 'p');
>> p, p.is_constant()
constant_pool('p'): [1, 2]
1
>> evalf(2*p)
[2, 4]

julia> p = ca.MX(ca.DM([1, 2]), "p");
julia> p, ca.is_constant(p)
(constant_pool('p'): [1, 2], true)
julia> ca.evalf(2 * p)
DM([2, 4])

See also
CodeGenerator

Extra doc: https://github.com/casadi/casadi/wiki/L_2aa

Definition at line 127 of file mx.cpp.

127  {
128  own(ConstantMX::create(val, name));
129  }
std::string name() const
Get the name of a symbolic primitive.
Definition: mx.cpp:794

References casadi::ConstantMX::create(), name(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

◆ MX() [8/11]

casadi::MX::MX ( double  x)

>>> c = MX(3.5)
>>> c, c.is_constant(), c.shape, float(c)
(MX(3.5), True, (1, 1), 3.5)

>> c = MX(3.5);
>> c, c.is_constant(), size(c), c.to_double()
3.5
1
1 1
3.5000

julia> c = ca.MX(3.5);
julia> c, ca.is_constant(c), size(c), Float64(c)
(3.5, true, (1, 1), 3.5)

Extra doc: https://github.com/casadi/casadi/wiki/L_q6

Definition at line 73 of file mx.cpp.

73  {
75  }
static Sparsity dense(casadi_int nrow, casadi_int ncol=1)
Create a dense rectangular sparsity pattern.
Definition: sparsity.cpp:1041

References casadi::ConstantMX::create(), casadi::Sparsity::dense(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

◆ MX() [9/11]

casadi::MX::MX ( const std::vector< double > &  x)

◆ MX() [10/11]

casadi::MX::MX ( const Matrix< double > &  x)

The sparsity pattern of x is kept. Numbers and numeric arrays are accepted through the DM conversion. SX cannot be converted to MX this way.

>>> c = MX(DM(Sparsity.diag(2), [1, 2]))
>>> c.sparsity(), c.is_constant()
(Sparsity(2x2,2nz), True)
>>> MX([1, 2, 3]).shape
(3, 1)
>>> MX(np.array([[1, 2], [3, 4]]))
MX(
[[1, 2],
 [3, 4]])

>> c = MX(DM(Sparsity.diag(2), [1; 2]));
>> c.sparsity(), c.is_constant()
2x2,2nz
1
>> size(MX([1; 2; 3]))
3 1
>> MX([1 2; 3 4])
[[1, 2],
 [3, 4]]

julia> c = ca.MX(ca.DM(ca.Sparsity.diag(2), [1, 2]));
julia> ca.sparsity(c), ca.is_constant(c)
(2x2,2nz, true)
julia> size(ca.MX([1, 2, 3]))
(3, 1)
julia> ca.MX([1 2; 3 4])
MX(
[[1, 2],
 [3, 4]])

See also
to_DM, evalf

Extra doc: https://github.com/casadi/casadi/wiki/L_q8

Definition at line 77 of file mx.cpp.

77  {
79  }

References casadi::ConstantMX::create(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

◆ ~MX()

casadi::MX::~MX ( )

Extra doc: https://github.com/casadi/casadi/wiki/L_q9

Definition at line 58 of file mx.cpp.

58  {
59  }

◆ MX() [11/11]

casadi::MX::MX ( const Sparsity &  sp,
double  val,
bool  dummy 
)

Definition at line 119 of file mx.cpp.

119  {
120  own(ConstantMX::create(sp, val));
121  }

References casadi::ConstantMX::create(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

Member Function Documentation

◆ __hash__()

casadi_int casadi::GenericShared< SharedObject , SharedObjectInternal >::__hash__
inherited

If the Object does not point to any node, "0" is returned.

Extra doc: https://github.com/casadi/casadi/wiki/L_av

Definition at line 123 of file generic_shared_impl.hpp.

148  {
149  return reinterpret_cast<casadi_int>(get());
150  }

◆ __nonzero__()

bool casadi::MX::__nonzero__ ( ) const

Nonzero constants are true, zero is false. Symbolic expressions and non-scalar constants raise an error: use a Function or evalf to evaluate first.

>>> bool(MX(2)), bool(MX(0))
(True, False)
>>> try:
...   bool(MX.sym("x"))
... except Exception as e:
...   print("Can only determine truth value of a numeric MX" in str(e))
True

julia> Bool(ca.MX(1)), Bool(ca.MX(0))
(true, false)
julia> try
           Bool(ca.MX.sym("x"))
       catch e
           println(occursin("constant scalar", sprint(showerror, e)))
       end
true

Extra doc: https://github.com/casadi/casadi/wiki/L_2pp

Definition at line 146 of file mx.cpp.

146  {
147  return (*this)->__nonzero__();
148  }

◆ _bilin()

MX casadi::MX::_bilin ( const MX &  A,
const MX &  x,
const MX &  y 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 3203 of file mx.cpp.

3203  {
3204  return A->get_bilin(x, y);
3205  }

References casadi::MXNode::get_bilin().

◆ _logsumexp()

MX casadi::MX::_logsumexp ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 3211 of file mx.cpp.

3211  {
3212  return x->get_logsumexp();
3213  }

References casadi::MXNode::get_logsumexp().

◆ _rank1()

MX casadi::MX::_rank1 ( const MX &  A,
const MX &  alpha,
const MX &  x,
const MX &  y 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 3207 of file mx.cpp.

3207  {
3208  return A->get_rank1(alpha, x, y);
3209  }

References casadi::MXNode::get_rank1().

◆ _sym()

MX casadi::MX::_sym ( const std::string &  name,
const Sparsity &  sp 
)
static

Definition at line 949 of file mx.cpp.

949  {
950  if (sp.nnz()==0) {
951  return MX::zeros(sp);
952  } else {
953  return MX::create(new SymbolicMX(name, sp));
954  }
955  }
static MX zeros(casadi_int nrow=1, casadi_int ncol=1)
Create a dense matrix or a matrix with specified sparsity with all entries zero.
static MX create(MXNode *node)
Create from node.
Definition: mx.cpp:69

References create(), name(), casadi::Sparsity::nnz(), and casadi::GenericMatrix< MX >::zeros().

◆ ad_forward()

void casadi::MX::ad_forward ( const std::vector< std::vector< MX > > &  fseed,
std::vector< std::vector< MX > > &  fsens 
) const

Extra doc: https://github.com/casadi/casadi/wiki/L_ro

Definition at line 3228 of file mx.cpp.

3229  {
3230  try {
3231  (*this)->ad_forward(fseed, fsens);
3232  } catch (std::exception& e) {
3233  CASADI_THROW_ERROR_OBJ("ad_forward", e.what());
3234  }
3235  }

◆ ad_reverse()

void casadi::MX::ad_reverse ( const std::vector< std::vector< MX > > &  aseed,
std::vector< std::vector< MX > > &  asens 
) const

Extra doc: https://github.com/casadi/casadi/wiki/L_ro

Definition at line 3237 of file mx.cpp.

3238  {
3239  try {
3240  (*this)->ad_reverse(aseed, asens);
3241  } catch (std::exception& e) {
3242  CASADI_THROW_ERROR_OBJ("ad_reverse", e.what());
3243  }
3244  }

◆ assign()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::assign ( Internal *  node)
inherited

improper use will cause memory leaks!

Extra doc: https://github.com/casadi/casadi/wiki/L_at

Definition at line 96 of file generic_shared_impl.hpp.

86  {
87  node = node_;
88  }

◆ attachAssert()

MX casadi::MX::attachAssert ( const MX &  y,
const std::string &  fail_message = "" 
) const

The result is equal to this expression, but when it is evaluated the scalar expression y is evaluated too and a runtime error with fail_message is raised unless y equals 1. Useful to check preconditions inside a Function. A non-scalar y raises an error at construction.

>>> x = MX.sym("x")
>>> e = x.attachAssert(x > 0, "x must be positive")
>>> e
MX(assertion(x, (0<x)))
>>> f = Function("f", [x], [e])
>>> f(1)
DM(1)
>>> try:
...   f(-1)
... except Exception as e:
...   print("Assertion error: x must be positive" in str(e))
True

>> x = MX.sym('x');
>> e = x.attachAssert(x > 0, 'x must be positive');
>> e
assertion(x, (0<x))
>> f = Function('f', {x}, {e});
>> f(1)
1
>> try, f(-1); catch err, disp('assertion error'); end
assertion error

julia> x = ca.MX.sym("x");
julia> e = ca.attachAssert(x, x > 0, "x must be positive");
julia> e
MX(assertion(x, (0<x)))
julia> f = ca.Function("f", [x], [e]);
julia> f(1)
DM(1)
julia> try
           f(-1)
       catch err
           println(occursin("Assertion error: x must be positive", sprint(showerror, err)))
       end
true

See also
monitor, printme

Extra doc: https://github.com/casadi/casadi/wiki/L_rg

Examples
misc/assertion.py.

Definition at line 746 of file mx.cpp.

746  {
747  casadi_assert(y.is_scalar(),
748  "Error in attachAssert: assertion expression y must be scalar, "
749  "but got " + y.dim());
750  return(*this)->get_assert(y, fail_message);
751  }

References casadi::GenericMatrix< MatType >::dim(), and casadi::GenericMatrix< MatType >::is_scalar().

◆ bilin()

static MX casadi::GenericMatrix< MX >::bilin ( const MX &  A,
const MX &  x,
const MX &  y 
)
staticinherited

x and y must be vectors (row vectors are transposed, sparse vectors densified) with x.numel() == A.size1() and y.numel() == A.size2(); otherwise an error is raised. The result is scalar. When y is omitted, the quadratic form x^T A x is calculated.

>>> A = DM([[1, 2], [3, 4]])
>>> bilin(A, DM([1, 1]), DM([1, 2]))
DM(16)
>>> bilin(A, DM([1, 1]))
DM(10)
>>> bilin(MX.sym("A", 2, 2), MX.sym("x", 2), MX.sym("y", 2))
MX(bilin(A, x, y))

>> A = DM([1 2; 3 4]);
>> bilin(A, DM([1; 1]), DM([1; 2]))
16
>> bilin(A, DM([1; 1]))
10
>> bilin(MX.sym('A', 2, 2), MX.sym('x', 2), MX.sym('y', 2))
bilin(A, x, y)

julia> A = ca.DM([1 2; 3 4]);
julia> ca.bilin(A, ca.DM([1, 1]), ca.DM([1, 2]))
DM(16)
julia> ca.bilin(A, ca.DM([1, 1]))
DM(10)
julia> ca.bilin(ca.MX.sym("A", 2, 2), ca.MX.sym("x", 2), ca.MX.sym("y", 2))
MX(bilin(A, x, y))

See also
rank1, dot, mtimes

Extra doc: https://github.com/casadi/casadi/wiki/L_1bo

◆ binary()

MX casadi::MX::binary ( casadi_int  op,
const MX &  x,
const MX &  y,
bool  unique_x = false,
bool  unique_y = false 
)
static

Low-level constructors behind the operators: MX.binary(OP_ADD, x, y) is x + y. Operands must have the same shape, or one of them is a scalar, or one is a horizontal repetition of the other (which is repmat-ed). The usual simplifications are applied. An invalid operation code is not checked.

Parameters
opOne of the OP_* constants
unique_x,unique_yInternal hints for in-place simplification; leave false

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> MX.binary(OP_ADD, x, y), MX.unary(OP_SIN, x)
(MX((x+y)), MX(sin(x)))
>>> MX.binary(OP_ADD, MX.sym("V", 2, 4), MX.sym("W", 2, 2))
MX((V+repmat(W, 2)))
>>> try:
...   MX.binary(OP_ADD, MX.sym("v", 2), MX.sym("w", 3))
... except Exception as e:
...   print("Dimension mismatch" in str(e))
True

>> x = MX.sym('x'); y = MX.sym('y');
>> MX.binary(OP_ADD, x, y), MX.unary(OP_SIN, x)
(x+y)
sin(x)
>> MX.binary(OP_ADD, MX.sym('V', 2, 4), MX.sym('W', 2, 2))
(V+repmat(W, 2))
>> v = MX.sym('v', 2); w = MX.sym('w', 3);
>> try, MX.binary(OP_ADD, v, w); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> ca.MX.binary(ca.OP_ADD, x, y), ca.MX.unary(ca.OP_SIN, x)
((x+y), sin(x))
julia> ca.MX.binary(ca.OP_ADD, ca.MX.sym("V", 2, 4), ca.MX.sym("W", 2, 2))
MX((V+repmat(W, 2)))
julia> try
           ca.MX.binary(ca.OP_ADD, ca.MX.sym("v", 2), ca.MX.sym("w", 3))
       catch e
           println(occursin("Dimension mismatch", sprint(showerror, e)))
       end
true

See also
op

Extra doc: https://github.com/casadi/casadi/wiki/L_r1

Definition at line 534 of file mx.cpp.

534  {
535  casadi_assert(casadi_math<double>::is_binary(op), "Not a binary operation: " + str(op));
536  // Check, correct dimensions
537  if (x.size()!=y.size() && !x.is_scalar() && !y.is_scalar()) {
538  // x and y are horizontal multiples of each other?
539  if (!x.is_empty() && !y.is_empty()) {
540  if (x.size1() == y.size1() && x.size2() % y.size2() == 0) {
541  return binary(op, x, repmat(y, 1, x.size2() / y.size2()), unique_x, false);
542  } else if (y.size1() == x.size1() && y.size2() % x.size2() == 0) {
543  return binary(op, repmat(x, 1, y.size2() / x.size2()), y, false, unique_y);
544  }
545  }
546  // x and y are empty horizontal multiples of each other?
547  if (x.size1()==0 && y.size1()==0 && x.size2()>0 && y.size2()>0) {
548  if (x.size2() % y.size2() == 0) {
549  return MX(0, x.size2());
550  } else if (y.size2() % x.size2() == 0) {
551  return MX(0, y.size2());
552  }
553  }
554  // Dimension mismatch
555  casadi_error("Dimension mismatch for " + casadi_math<double>::print(op, "x", "y") +
556  ", x is " + x.dim() + ", while y is " + y.dim());
557  }
558  // Call internal class
559  return x->get_binary(op, y, unique_x, unique_y);
560  }
static MX repmat(const MX &x, casadi_int n, casadi_int m=1)
Definition: mx.cpp:2078
MX()
Default constructor: a 0-by-0 constant.
Definition: mx.cpp:61
static MX binary(casadi_int op, const MX &x, const MX &y, bool unique_x=false, bool unique_y=false)
Create an elementwise binary or unary node from an operation code.
Definition: mx.cpp:534
casadi_int op() const
Get the operation type of the node.
Definition: mx.cpp:854
static bool is_binary(unsigned char op)
Is binary operation?
Definition: calculus.hpp:1626
static std::string print(unsigned char op, const std::string &x, const std::string &y)
Print.
Definition: calculus.hpp:1665

References casadi::GenericMatrix< MatType >::dim(), casadi::MXNode::get_binary(), casadi::GenericMatrix< MatType >::is_empty(), casadi::GenericMatrix< MatType >::is_scalar(), MX(), op(), repmat(), casadi::GenericMatrix< MatType >::size(), casadi::GenericMatrix< MatType >::size1(), casadi::GenericMatrix< MatType >::size2(), and casadi::str().

Referenced by casadi::BinaryMX< ScX, ScY >::eval_mx(), and printme().

◆ blockcat()

MX casadi::MX::blockcat ( const std::vector< std::vector< MX > > &  v)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1254 of file mx.cpp.

1254  {
1255  // Quick return if no block rows
1256  if (v.empty()) return MX(0, 0);
1257 
1258  // Make sure same number of block columns
1259  casadi_int ncols = v.front().size();
1260  for (auto&& e : v) {
1261  casadi_assert(e.size()==ncols, "blockcat: Inconsistent number of block columns");
1262  }
1263 
1264  // Quick return if no block columns
1265  if (v.front().empty()) return MX(0, 0);
1266 
1267  // Horizontally concatenate all columns for each row, then vertically concatenate rows
1268  std::vector<MX> rows;
1269  for (auto&& e : v) {
1270  rows.push_back(horzcat(e));
1271  }
1272  return vertcat(rows);
1273  }
casadi_int rows() const
Get the number of rows, Octave-style syntax (same as size1())
static MX horzcat(const std::vector< MX > &x)
Definition: mx.cpp:1122
static MX vertcat(const std::vector< MX > &x)
Definition: mx.cpp:1168

References horzcat(), MX(), casadi::GenericMatrix< MX >::rows(), and vertcat().

Referenced by casadi::Expm::get_forward(), casadi::Expm::get_reverse(), and casadi::Conic::sens_kkt().

◆ bspline() [1/3]

MX casadi::MX::bspline ( const MX &  x,
const DM &  coeffs,
const std::vector< std::vector< double > > &  knots,
const std::vector< casadi_int > &  degree,
casadi_int  m,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for this class

Definition at line 2217 of file mx.cpp.

2222  {
2223  return BSpline::create(x, knots, coeffs.nonzeros(), degree, m, opts);
2224  }
static MX create(const MX &x, const std::vector< std::vector< double > > &knots, const std::vector< double > &coeffs, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts)
Definition: bspline.cpp:280

References casadi::BSpline::create(), and casadi::Matrix< Scalar >::nonzeros().

Referenced by casadi::Function::bspline(), casadi::BSplineInterpolant::construct_graph(), and casadi::BSplineCommon::jac().

◆ bspline() [2/3]

MX casadi::MX::bspline ( const MX &  x,
const MX &  coeffs,
const std::vector< MX > &  knots,
const std::vector< casadi_int > &  degree,
casadi_int  m,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for this class

Definition at line 2234 of file mx.cpp.

2238  {
2239  return BSplineParametric::create(x, coeffs, knots, degree, m, opts);
2240  }
static MX create(const MX &x, const MX &coeffs, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts)
Definition: bspline.cpp:320

References casadi::BSplineParametric::create().

◆ bspline() [3/3]

MX casadi::MX::bspline ( const MX &  x,
const MX &  coeffs,
const std::vector< std::vector< double > > &  knots,
const std::vector< casadi_int > &  degree,
casadi_int  m,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for this class

Definition at line 2226 of file mx.cpp.

2230  {
2231  return BSplineParametric::create(x, coeffs, knots, degree, m, opts);
2232  }

References casadi::BSplineParametric::create().

◆ bspline_dual()

DM casadi::MX::bspline_dual ( const std::vector< double > &  x,
const std::vector< std::vector< double > > &  knots,
const std::vector< casadi_int > &  degree,
const Dict &  opts = Dict() 
)
static

Returns the sparse matrix of basis function values such that bspline_dual(x, knots, degree) @ coeffs equals bspline(x, coeffs, knots, degree, 1) at the same points. Each row corresponds to one evaluation point and each row sums to one inside the knot range. Used to fit coefficients to data.

Parameters
xEvaluation points, flattened: n_points * n_dims numbers, point by point
knotsOne knot vector per dimension
degreeDegree per dimension
opts"lookup_mode": list with one of "linear", "exact", "binary" per dimension
Returns
n_points-by-n_coeffs DM

>>> knots = [[0, 0, 0, 0, 1, 2, 3, 3, 3, 3]]
>>> B = MX.bspline_dual([0.5, 1.5], knots, [3])
>>> B.shape, sum2(B)
((2, 6), DM([1, 1]))
>>> B @ DM(range(6))
DM([1.17708, 2.5])

>> knots = {[0 0 0 0 1 2 3 3 3 3]};
>> B = MX.bspline_dual([0.5, 1.5], knots, 3);
>> size(B), sum2(B)
2 6
[1, 1]
>> B * DM((0:5)')
[1.17708, 2.5]

julia> knots = [[0, 0, 0, 0, 1, 2, 3, 3, 3, 3]];
julia> B = ca.MX.bspline_dual([0.5, 1.5], knots, [3]);
julia> size(B), sum(B, dims=2)
((2, 6), [1, 1])
julia> B * ca.DM(0:5)
DM([1.17708, 2.5])

See also
bspline

Extra doc: https://github.com/casadi/casadi/wiki/L_2qg

Definition at line 2242 of file mx.cpp.

2245  {
2246  return BSpline::dual(x, knots, degree, opts);
2247  }
static DM dual(const std::vector< double > &x, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, const Dict &opts)
Definition: bspline.cpp:503

References casadi::BSpline::dual().

Referenced by casadi::BSplineInterpolant::construct_graph().

◆ class_name()

std::string casadi::SharedObject::class_name ( ) const
inherited

◆ colind() [1/2]

const casadi_int* casadi::GenericMatrix< MX >::colind ( ) const
inlineinherited

The pattern is stored in compressed column format: colind has size2()+1 entries, the nonzeros of column j are the entries colind(j) up to colind(j+1) (exclusive), and row(el) is the row index of nonzero el. Without argument, the full vectors are returned. Out-of-range indices raise an error.

>>> x = DM(Sparsity.diag(2), [5, 6])
>>> x.row(), x.colind()
([0, 1], [0, 1, 2])
>>> x.row(1), x.colind(2)
(1, 2)

>> x = DM(Sparsity.diag(2), [5; 6]);
>> x.row(), x.colind()
0 1
0 1 2
>> fprintf('%d %d\n', x.row(1), x.colind(2))
1 2

julia> x = ca.DM(ca.Sparsity.diag(2), [5, 6]);
julia> ca.row(x), ca.colind(x)
([0, 1], [0, 1, 2])
julia> ca.row(x, 1), ca.colind(x, 2)
(1, 2)

Extra doc: https://github.com/casadi/casadi/wiki/L_1b8

Definition at line 606 of file generic_matrix.hpp.

606 { return sparsity().colind(); }
Sparsity sparsity() const
Get the sparsity pattern.
const casadi_int * colind() const
Get a reference to the colindex of all column element (see class description)
Definition: sparsity.cpp:170

◆ colind() [2/2]

casadi_int casadi::GenericMatrix< MX >::colind ( casadi_int  col) const
inlineinherited

The pattern is stored in compressed column format: colind has size2()+1 entries, the nonzeros of column j are the entries colind(j) up to colind(j+1) (exclusive), and row(el) is the row index of nonzero el. Without argument, the full vectors are returned. Out-of-range indices raise an error.

>>> x = DM(Sparsity.diag(2), [5, 6])
>>> x.row(), x.colind()
([0, 1], [0, 1, 2])
>>> x.row(1), x.colind(2)
(1, 2)

>> x = DM(Sparsity.diag(2), [5; 6]);
>> x.row(), x.colind()
0 1
0 1 2
>> fprintf('%d %d\n', x.row(1), x.colind(2))
1 2

julia> x = ca.DM(ca.Sparsity.diag(2), [5, 6]);
julia> ca.row(x), ca.colind(x)
([0, 1], [0, 1, 2])
julia> ca.row(x, 1), ca.colind(x, 2)
(1, 2)

Extra doc: https://github.com/casadi/casadi/wiki/L_1b8

Definition at line 609 of file generic_matrix.hpp.

609 { return sparsity().colind(col); }

◆ columns()

casadi_int casadi::GenericMatrix< MX >::columns ( ) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1av

Definition at line 295 of file generic_matrix.hpp.

295 {return size2();}
casadi_int size2() const
Get the second dimension (i.e. number of columns)

◆ conditional()

MX casadi::MX::conditional ( const MX &  ind,
const std::vector< MX > &  x,
const MX &  x_default,
bool  short_circuit = false 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1386 of file mx.cpp.

1387  {
1388  if (short_circuit) {
1389  // Get symbolic primitives
1390  std::vector<MX> arg = x;
1391  arg.push_back(x_default);
1392  arg = symvar(veccat(arg));
1393 
1394  // Form functions for cases
1395  std::vector<Function> f(x.size());
1396  for (casadi_int k=0; k<x.size(); ++k) {
1397  std::stringstream ss;
1398  ss << "f_case" << k;
1399  f[k] = Function(ss.str(), arg, {x[k]});
1400  }
1401  Function f_default("f_default", arg, {x_default});
1402 
1403  // Form Switch
1404  Function sw = Function::conditional("switch", f, f_default);
1405 
1406  // Call the Switch
1407  std::vector<MX> sw_arg;
1408  sw_arg.push_back(ind);
1409  sw_arg.insert(sw_arg.end(), arg.begin(), arg.end());
1410  return sw(sw_arg).at(0);
1411  } else {
1412  MX ret = x_default;
1413  for (casadi_int k=0; k<x.size(); ++k) {
1414  ret = if_else(ind==static_cast<double>(k), x[k], ret);
1415  }
1416  return ret;
1417  }
1418  }
static Function conditional(const std::string &name, const std::vector< Function > &f, const Function &f_def, const Dict &opts=Dict())
Create a function that selects one of several functions by an index input.
Definition: function.cpp:917
static std::vector< MX > symvar(const MX &x)
Definition: mx.cpp:2034
static MX if_else(const MX &cond, const MX &if_true, const MX &if_false, bool short_circuit=false)
Definition: mx.cpp:1364
static MatType veccat(const std::vector< MatType > &x)

References casadi::Function::conditional(), if_else(), symvar(), and casadi::SparsityInterface< MatType >::veccat().

◆ contains_all()

bool casadi::MX::contains_all ( const std::vector< MX > &  v,
const std::vector< MX > &  n 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2177 of file mx.cpp.

2177  {
2178  if (n.empty()) return true;
2179 
2180  // Set to contain all nodes
2181  std::set<MXNode*> l;
2182  for (const MX& e : v) l.insert(e.get());
2183 
2184  size_t l_unique = l.size();
2185 
2186  for (const MX& e : n) l.insert(e.get());
2187 
2188  return l.size()==l_unique;
2189  }

◆ contains_any()

bool casadi::MX::contains_any ( const std::vector< MX > &  v,
const std::vector< MX > &  n 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2191 of file mx.cpp.

2191  {
2192  if (n.empty()) return true;
2193 
2194  // Set to contain all nodes
2195  std::set<MXNode*> l;
2196  for (const MX& e : v) l.insert(e.get());
2197 
2198  size_t l_unique = l.size();
2199 
2200  std::set<MXNode*> r;
2201  for (const MX& e : n) r.insert(e.get());
2202 
2203  size_t r_unique = r.size();
2204  for (const MX& e : n) l.insert(e.get());
2205 
2206  return l.size()<l_unique+r_unique;
2207  }

◆ convexify()

MX casadi::MX::convexify ( const MX &  H,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for this class

Definition at line 2249 of file mx.cpp.

2250  {
2251  return H->get_convexify(opts);
2252  }

References casadi::MXNode::get_convexify().

◆ count_down()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::count_down
protectedinherited

Definition at line 133 of file generic_shared_impl.hpp.

46  {
47 #ifdef WITH_EXTRA_CHECKS
48  casadi_assert_dev(Function::call_depth_==0);
49 #endif // WITH_EXTRA_CHECKS
50  if (!node) return;
51 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
52  GenericWeakRef<Shared, Internal>* weak_ref =
53  node->weak_ref_.load(std::memory_order_acquire);
54 #else
55  GenericWeakRef<Shared, Internal>* weak_ref = node->weak_ref_;
56 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
57  if (weak_ref) {
58 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
59  // get_mutex() returns a shared_ptr copy, so the mutex outlives this lock
60  // even if delete node (below) destroys the WeakRefInternal holding it
61  auto mutex = weak_ref->get_mutex();
62  // Avoid triggering a delete while a weak_ref.shared_if_alive is being called
63  std::lock_guard<std::mutex> lock(*mutex);
64 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
65 
66  if (--static_cast<Internal*>(node)->count == 0) {
67  delete node;
68  node = nullptr;
69  }
70  } else {
71  if (--static_cast<Internal*>(node)->count == 0) {
72  delete node;
73  node = nullptr;
74  }
75  }
76  }

◆ count_up()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::count_up
protectedinherited

Definition at line 132 of file generic_shared_impl.hpp.

36  {
37 #ifdef WITH_EXTRA_CHECKS
38  casadi_assert_dev(Function::call_depth_==0);
39 #endif // WITH_EXTRA_CHECKS
40 
41  if (node) static_cast<Internal*>(node)->count++;
42 
43  }

◆ create()

MX casadi::MX::create ( MXNode *  node)
static

Extra doc: https://github.com/casadi/casadi/wiki/L_qa

Definition at line 69 of file mx.cpp.

69  {
70  return MX(node, false, false, false, false);
71  }

References MX().

Referenced by casadi::MXNode::_get_binary(), _sym(), casadi::Kron::create(), casadi::KronContract::create(), casadi::GetNonzerosParam::create(), casadi::SetNonzerosParam< Add >::create(), casadi::SetNonzeros< Add >::create(), casadi::Multiplication::create(), casadi::GetNonzeros::create(), casadi::Call::create_call(), createMultipleOutput(), deserialize(), casadi::MXNode::get_assert(), casadi::MXNode::get_bilin(), casadi::MXNode::get_bspline(), casadi::MXNode::get_convexify(), casadi::MXNode::get_det(), casadi::MXNode::get_diagcat(), casadi::MXNode::get_dot(), casadi::MXNode::get_dump(), casadi::MXNode::get_einstein(), casadi::MXNode::get_find(), casadi::MXNode::get_horzcat(), casadi::MXNode::get_inv(), casadi::MXNode::get_logsumexp(), casadi::MXNode::get_low(), casadi::MXNode::get_mmax(), casadi::MXNode::get_mmin(), casadi::MXNode::get_monitor(), casadi::MXNode::get_norm_1(), casadi::MXNode::get_norm_2(), casadi::MXNode::get_norm_fro(), casadi::MXNode::get_norm_inf(), casadi::Constant< Value >::get_nzref(), casadi::Call::get_output(), casadi::MultipleOutput::get_output(), casadi::MXNode::get_project(), casadi::Constant< Value >::get_project(), casadi::MXNode::get_rank1(), casadi::MXNode::get_repmat(), casadi::MXNode::get_repsum(), casadi::MXNode::get_reshape(), casadi::Constant< Value >::get_reshape(), casadi::MXNode::get_solve(), casadi::MXNode::get_solve_tril(), casadi::MXNode::get_solve_tril_unity(), casadi::MXNode::get_solve_triu(), casadi::MXNode::get_solve_triu_unity(), casadi::MXNode::get_sparsity_cast(), casadi::MXNode::get_subassign(), casadi::MXNode::get_subref(), casadi::MXNode::get_transpose(), casadi::Constant< Value >::get_transpose(), casadi::MXNode::get_unary(), casadi::MXNode::get_vertcat(), inf(), casadi::MXFunction::init(), and nan().

◆ createMultipleOutput()

std::vector< MX > casadi::MX::createMultipleOutput ( MXNode *  node)
static

Extra doc: https://github.com/casadi/casadi/wiki/L_qb

Definition at line 131 of file mx.cpp.

131  {
132  casadi_assert_dev(dynamic_cast<MultipleOutput*>(node) != nullptr);
133  MX x = MX::create(node);
134  std::vector<MX> ret(x->nout());
135  for (casadi_int i=0; i<ret.size(); ++i) {
136  ret[i] = x.get_output(i);
137  if (ret[i].is_empty(true)) {
138  ret[i] = MX(0, 0);
139  } else if (ret[i].nnz()==0) {
140  ret[i] = MX(ret[i].size());
141  }
142  }
143  return ret;
144  }
bool is_empty(bool both=false) const
Check if the matrix is empty, i.e. if one of the dimensions is zero.
std::pair< casadi_int, casadi_int > size() const
Get the shape as a pair (number of rows, number of columns)
casadi_int nnz() const
Get the number of structural nonzeros.

References create(), get_output(), casadi::GenericMatrix< MX >::is_empty(), MX(), casadi::GenericMatrix< MX >::nnz(), casadi::MXNode::nout(), and casadi::GenericMatrix< MX >::size().

Referenced by casadi::Call::create(), casadi::MXNode::get_diagsplit(), casadi::MXNode::get_horzsplit(), and casadi::MXNode::get_vertsplit().

◆ cross()

MX casadi::GenericMatrix< MX >::cross ( const MX &  a,
const MX &  b,
casadi_int  dim = -1 
)
staticinherited

Definition at line 662 of file generic_matrix.hpp.

5326  {
5327  casadi_assert(a.size1()==b.size1() && a.size2()==b.size2(),
5328  "cross(a, b): Inconsistent dimensions. Dimension of a ("
5329  + a.dim() + " ) must equal that of b (" + b.dim() + ").");
5330 
5331  casadi_assert(a.size1()==3 || a.size2()==3,
5332  "cross(a, b): One of the dimensions of a should have length 3, but got "
5333  + a.dim() + ".");
5334  casadi_assert(dim==-1 || dim==1 || dim==2,
5335  "cross(a, b, dim): Dim must be 1, 2 or -1 (automatic).");
5336 
5337  std::vector<MatType> ret(3);
5338 
5339  bool t = a.size1()==3;
5340 
5341  if (dim==1) t = true;
5342  if (dim==2) t = false;
5343 
5344  MatType a1 = t ? a(0, Slice()) : a(Slice(), 0);
5345  MatType a2 = t ? a(1, Slice()) : a(Slice(), 1);
5346  MatType a3 = t ? a(2, Slice()) : a(Slice(), 2);
5347 
5348  MatType b1 = t ? b(0, Slice()) : b(Slice(), 0);
5349  MatType b2 = t ? b(1, Slice()) : b(Slice(), 1);
5350  MatType b3 = t ? b(2, Slice()) : b(Slice(), 2);
5351 
5352  ret[0] = a2*b3-a3*b2;
5353  ret[1] = a3*b1-a1*b3;
5354  ret[2] = a1*b2-a2*b1;
5355 
5356  return t ? vertcat(ret) : horzcat(ret);
5357  }
std::string dim(bool with_nz=false) const
Get string representation of dimensions.
friend MatType vertcat(const std::vector< MatType > &v)
Concatenate a list of matrices vertically.
friend MatType horzcat(const std::vector< MatType > &v)
Concatenate a list of matrices horizontally.

◆ cse()

std::vector< MX > casadi::MX::cse ( const std::vector< MX > &  e)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2635 of file mx.cpp.

2635  {
2636  std::vector<MX> orig = e;
2637  bool updated = true;
2638  while (updated) {
2639  Function f("f", std::vector<MX>{}, orig,
2640  {{"live_variables", false}, {"max_io", 0}, {"cse", false}, {"allow_free", true}});
2641  MXFunction *ff = f.get<MXFunction>();
2642 
2643  // Symbolic work, non-differentiated
2644  std::vector<MX> swork(ff->workloc_.size()-1);
2645 
2646  // Allocate storage for split outputs
2647  std::vector<std::vector<MX> > res_split(orig.size());
2648  for (casadi_int i=0; i<orig.size(); ++i) res_split[i].resize(orig[i].n_primitives());
2649 
2650  std::vector<MX> arg1, res1;
2651  std::vector<MX> res(orig.size());
2652 
2653  std::unordered_map<std::string, MX > cache;
2654  IncrementalSerializerMX s;
2655 
2656  SimpleCache<FunctionInternal*, std::string> function_serialize_cache;
2657  SimpleCache<std::string, Function> function_cache;
2658 
2659  // Pre-cache the original nodes
2660  // This makes sure we recycle old nodes when possible
2661  for (auto it=ff->algorithm_.begin(); it!=ff->algorithm_.end(); ++it) {
2662  if (it->op == OP_INPUT || it->op==OP_OUTPUT || it->op==OP_PARAMETER) continue;
2663 
2664  std::string key = s.pack(it->data);
2665 
2666  auto itk = cache.find(key);
2667  if (itk==cache.end()) {
2668  cache[key] = it->data;
2669  }
2670  }
2671 
2672  // Loop over computational nodes in forward order
2673  casadi_int alg_counter = 0;
2674  for (auto it=ff->algorithm_.begin(); it!=ff->algorithm_.end(); ++it, ++alg_counter) {
2675  if (it->op == OP_INPUT) {
2676  // pass
2677  } else if (it->op==OP_OUTPUT) {
2678  // Collect the results
2679  res_split.at(it->data->ind()).at(it->data->segment()) = swork[it->arg.front()];
2680  } else if (it->op==OP_PARAMETER) {
2681  // Fetch parameter
2682  MX& target = swork[it->res.front()];
2683  target = it->data;
2684  cache[s.pack(target)] = target;
2685  } else {
2686 
2687  // Arguments of the operation
2688  arg1.resize(it->arg.size());
2689  for (casadi_int i=0; i<arg1.size(); ++i) {
2690  casadi_int el = it->arg[i]; // index of the argument
2691  arg1[i] = el<0 ? MX(it->data->dep(i).size()) : swork[el];
2692  }
2693 
2694  // Perform the operation
2695  res1.resize(it->res.size());
2696  it->data->eval_mx(arg1, res1);
2697 
2698  // Get the result
2699  for (casadi_int i=0; i<res1.size(); ++i) {
2700  casadi_int el = it->res[i]; // index of the output
2701 
2702  MX& out_i = res1[i];
2703 
2704  // Default assumption is that out_i is not an output node
2705  casadi_int output_node = -1;
2706 
2707  if (out_i.is_output()) {
2708  output_node = out_i.which_output();
2709  // First pack/cache the parent (MultipleOutput node e.g. Call, Horzsplit)
2710  out_i = out_i.dep(0);
2711 
2712  // If we are a call node,
2713  if (out_i.op()==OP_CALL) {
2714  FunctionInternal* fptr = out_i.which_function().get();
2715 
2716  // Get or compute serialization (cached)
2717  std::string key_s;
2718  if (!function_serialize_cache.incache(fptr, key_s)) {
2719  key_s = out_i.which_function().serialize();
2720  function_serialize_cache.tocache(fptr, key_s);
2721  }
2722 
2723  // Get or store canonical function (cached)
2724  Function canonical;
2725  if (!function_cache.incache(key_s, canonical)) {
2726  function_cache.tocache(key_s, out_i.which_function());
2727  } else {
2728  out_i = Call::create_call(canonical, out_i->dep_);
2729  }
2730  }
2731  }
2732 
2733  while (true) {
2734  // Replace out_i by a cached variant if possible
2735  std::string key = s.pack(out_i);
2736 
2737  auto itk = cache.find(key);
2738  if (itk==cache.end()) {
2739  cache[key] = out_i;
2740  } else {
2741  out_i = itk->second;
2742  }
2743 
2744  if (output_node==-1) {
2745  break; // Job is done
2746  } else {
2747  // Recreate the output node on top of the parent
2748  out_i = out_i.get_output(output_node);
2749  output_node = -1;
2750  // Loop once more
2751  }
2752  }
2753 
2754  if (el>=0) swork[el] = out_i;
2755  }
2756  }
2757  }
2758 
2759  // Join split outputs
2760  for (casadi_int i=0; i<res.size(); ++i) res[i] = orig[i].join_primitives(res_split[i]);
2761 
2762  std::vector<MX> subs_from;
2763  std::vector<MX> subs_to;
2764  for (const auto& e : function_cache.cache_map()) {
2765  e.second->merge(res, subs_from, subs_to);
2766  }
2767  orig = graph_substitute(res, subs_from, subs_to, updated);
2768  }
2769 
2770  return orig;
2771  }
static MX create_call(const Function &fcn, const std::vector< MX > &arg)
Create function call node.
casadi_int n_primitives() const
Get the number of symbolic primitives in a valid Function input.
Definition: mx.cpp:961
static MX graph_substitute(const MX &x, const std::vector< MX > &v, const std::vector< MX > &vdef)
Definition: mx.cpp:1544
MX join_primitives(const std::vector< MX > &v) const
Join values along the symbolic primitives of this expression.
Definition: mx.cpp:997
@ OP_OUTPUT
Definition: calculus.hpp:82
@ OP_INPUT
Definition: calculus.hpp:82
@ OP_PARAMETER
Definition: calculus.hpp:85
@ OP_CALL
Definition: calculus.hpp:88

References casadi::SimpleCache< K, T >::cache_map(), casadi::Call::create_call(), dep(), casadi::MXNode::dep_, casadi::Function::get(), get_output(), graph_substitute(), casadi::SimpleCache< K, T >::incache(), is_output(), join_primitives(), MX(), n_primitives(), op(), casadi::OP_CALL, casadi::OP_INPUT, casadi::OP_OUTPUT, casadi::OP_PARAMETER, casadi::Function::serialize(), casadi::SimpleCache< K, T >::tocache(), which_function(), and which_output().

◆ cumsum()

MX casadi::MX::cumsum ( const MX &  x,
casadi_int  axis = -1 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 701 of file mx.cpp.

701  {
702  if (axis==-1) axis = x.is_row();
703  MX r = axis==0 ? x.T() : x;
704  Sparsity sl = r(Slice(), 0).sparsity();
705  MX acc = MX::sym("acc", sl);
706  MX u = MX::sym("u", sl);
707 
708  Function f("f", {acc, u}, {acc+u});
709  f = f.mapaccum(r.size2());
710  MX ret = f(std::vector<MX>{0, r})[0];
711 
712  return axis==0 ? ret.T() : ret;
713  }
static MX sym(const std::string &name, casadi_int nrow=1, casadi_int ncol=1)
Create an nrow-by-ncol symbolic primitive.

References casadi::GenericMatrix< MatType >::is_row(), casadi::Function::mapaccum(), casadi::GenericMatrix< MatType >::size2(), sparsity(), casadi::GenericMatrix< MX >::sym(), and T().

◆ debug_repr()

std::string casadi::GenericShared< SharedObject , SharedObjectInternal >::debug_repr
inherited

Definition at line 112 of file generic_shared_impl.hpp.

91  {
92  if (node) {
93  return node->debug_repr(node);
94  } else {
95  return "NULL";
96  }
97  }
std::string debug_repr(const Internal *) const

◆ densify()

MX casadi::MX::densify ( const MX &  x,
const MX &  val = 0 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 926 of file mx.cpp.

926  {
927  casadi_assert_dev(val.is_scalar());
928  if (x.is_dense()) {
929  return x; // Already ok
930  } else if (val->is_zero()) {
931  return project(x, Sparsity::dense(x.size()));
932  } else {
933  MX ret = MX::repmat(val, x.size());
934  ret(x.sparsity()) = x;
935  return ret;
936  }
937  }
static MX project(const MX &x, const Sparsity &sp, bool intersect=false)
Definition: mx.cpp:909

References casadi::Sparsity::dense(), casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_scalar(), casadi::MXNode::is_zero(), project(), repmat(), casadi::GenericMatrix< MatType >::size(), and sparsity().

Referenced by MX(), and set().

◆ dep()

MX casadi::MX::dep ( casadi_int  ch = 0) const

Together with n_dep, op and is_op this allows walking the expression graph. Symbolic primitives and constants have no dependencies.

Parameters
chIndex in [0, n_dep()); out of range raises an error

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> e = x*y + 1
>>> e.n_dep(), e.dep(0), e.dep(1)
(2, MX(1), MX((x*y)))
>>> e.dep(1).dep(0), x.n_dep()
(MX(x), 0)

>> x = MX.sym('x'); y = MX.sym('y');
>> e = x*y + 1;
>> e.n_dep(), e.dep(0), e.dep(1)
2
1
(x*y)
>> e.dep(1).dep(0), x.n_dep()
x
0

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> e = x * y + 1;
julia> ca.n_dep(e), ca.dep(e, 0), ca.dep(e, 1)
(2, 1, (x*y))
julia> ca.dep(ca.dep(e, 1), 0), ca.n_dep(x)
(x, 0)

See also
n_dep, op, is_op

Extra doc: https://github.com/casadi/casadi/wiki/L_qj

Definition at line 786 of file mx.cpp.

786  {
787  return (*this)->dep(ch);
788  }

References casadi::MXNode::dep().

Referenced by casadi::OptiNode::canon_expr(), casadi::Call::common_cond(), casadi::DaeBuilderInternal::create(), cse(), casadi::MXFunction::export_code_body(), casadi::MXNode::get_binary(), casadi::BinaryMX< ScX, ScY >::get_solve_tril(), casadi::BinaryMX< ScX, ScY >::get_solve_triu(), inv(), is_doubled(), casadi::DaeBuilderInternal::jac_vdef_v_from_calls(), casadi::Onnx::load(), casadi::DaeBuilderInternal::load_fmi_description(), and casadi::DaeBuilderInternal::when().

◆ depends_on()

bool casadi::MX::depends_on ( const MX &  x,
const MX &  arg 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2158 of file mx.cpp.

2158  {
2159  if (x.nnz()==0) return false;
2160 
2161  // Construct a temporary algorithm
2162  Function temp("tmp_depends_on", {arg}, {x}, Dict{{"max_io", 0}, {"allow_free", true}});
2163 
2164  // Perform a single dependency sweep
2165  std::vector<bvec_t> t_in(arg.nnz(), 1), t_out(x.nnz());
2166  temp({get_ptr(t_in)}, {get_ptr(t_out)});
2167 
2168  // Loop over results
2169  for (casadi_int i=0; i<t_out.size(); ++i) {
2170  if (t_out[i]) return true;
2171  }
2172 
2173  return false;
2174  }
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.
T * get_ptr(std::vector< T > &v)
Get a pointer to the data contained in the vector.

References casadi::get_ptr(), and casadi::GenericMatrix< MatType >::nnz().

◆ deserialize()

MX casadi::MX::deserialize ( DeserializingStream &  s)
static

Counterpart of serialize; use StringDeserializer.unpack from Python.

Extra doc: https://github.com/casadi/casadi/wiki/L_r0

Definition at line 866 of file mx.cpp.

866  {
867  return MX::create(MXNode::deserialize(s));
868  }
static MXNode * deserialize(DeserializingStream &s)
Deserialize with type disambiguation.
Definition: mx_node.cpp:548

References create(), and casadi::MXNode::deserialize().

◆ det() [1/2]

MX casadi::MX::det ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2013 of file mx.cpp.

2013  {
2014  return det(x, "qr");
2015  }
static MX det(const MX &x)
Definition: mx.cpp:2013

◆ det() [2/2]

MX casadi::MX::det ( const MX &  x,
const std::string &  lsolver,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2017 of file mx.cpp.

2017  {
2018  Linsol mysolver("det", lsolver, x.sparsity(), opts);
2019  return mysolver.det(x);
2020  }

References casadi::Linsol::det(), and sparsity().

◆ diag()

MX casadi::MX::diag ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1455 of file mx.cpp.

1455  {
1456  // Nonzero mapping
1457  std::vector<casadi_int> mapping;
1458 
1459  // Get the sparsity
1460  Sparsity sp = x.sparsity().get_diag(mapping);
1461 
1462  // Create a reference to the nonzeros
1463  return x->get_nzref(sp, mapping);
1464  }
Matrix< casadi_int > mapping() const
Get the nonzero mapping of a GetNonzeros or SetNonzeros node.
Definition: mx.cpp:889
const Sparsity & sparsity() const
Const access the sparsity - reference to data member.
Sparsity get_diag(std::vector< casadi_int > &mapping) const
Pattern of the diagonal of a matrix, or of the diagonal matrix built from a vector.
Definition: sparsity.cpp:621

References casadi::Sparsity::get_diag(), casadi::MXNode::get_nzref(), mapping(), and sparsity().

◆ diagcat()

MX casadi::MX::diagcat ( const std::vector< MX > &  x)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1158 of file mx.cpp.

1158  {
1159  // Quick return if empty or single element
1160  if (x.empty()) return MX();
1161  if (x.size()==1) return x.front();
1162  // Call recursively if any 0-by-0 matrices
1163  if (has_empty(x, true)) return diagcat(trim_empty(x, true));
1164  // Create diagcat node
1165  return x.front()->get_diagcat(x);
1166  }
static MX diagcat(const std::vector< MX > &x)
Definition: mx.cpp:1158
std::vector< MX > trim_empty(const std::vector< MX > &x, bool both=false)
Definition: mx.cpp:1114
bool has_empty(const std::vector< MX > &x, bool both=false)
Definition: mx.cpp:1107

References casadi::has_empty(), MX(), and casadi::trim_empty().

◆ diagsplit()

std::vector< MX > casadi::MX::diagsplit ( const MX &  x,
const std::vector< casadi_int > &  offset1,
const std::vector< casadi_int > &  offset2 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1223 of file mx.cpp.

1224  {
1225  // Consistency check
1226  check_offset(offset1, x.size1(), "diagsplit");
1227  check_offset(offset2, x.size2(), "diagsplit");
1228  casadi_assert(offset1.size()==offset2.size(),
1229  "diagsplit: offset1 and offset2 must have the same length");
1230 
1231  return x->get_diagsplit(offset1, offset2);
1232  }
void check_offset(const std::vector< casadi_int > &offset, casadi_int n, const std::string &fname)
Assert that offset starts at 0, is nondecreasing and ends at n.

References casadi::check_offset(), casadi::MXNode::get_diagsplit(), casadi::GenericMatrix< MatType >::size1(), and casadi::GenericMatrix< MatType >::size2().

◆ diff()

MX casadi::GenericMatrix< MX >::diff ( const MX &  x,
casadi_int  n = 1,
casadi_int  axis = -1 
)
staticinherited

Definition at line 668 of file generic_matrix.hpp.

5709  {
5710  casadi_assert(axis==-1 || axis==0 || axis==1, "Axis argument invalid");
5711  casadi_assert(n>=1, "n argument invalid");
5712 
5713  MatType ret = x;
5714  for (casadi_int i=0;i<n;++i) {
5715  // Matlab's special case
5716  if (axis==-1 && ret.is_scalar()) return MatType();
5717 
5718  casadi_int local_axis = (axis==-1) ? ret.is_row() : axis;
5719  if (local_axis==0) {
5720  if (ret.size1()<=1) {
5721  ret = MatType::zeros(0, ret.size2());
5722  } else {
5723  ret = ret(Slice(1, ret.size1()), Slice())-ret(Slice(0, ret.size1()-1), Slice());
5724  }
5725  } else {
5726  if (ret.size2()<=1) {
5727  ret = MatType::zeros(ret.size1(), 0);
5728  } else {
5729  ret = ret(Slice(), Slice(1, ret.size2()))-ret(Slice(), Slice(0, ret.size2()-1));
5730  }
5731  }
5732  }
5733  return ret;
5734  }

◆ difference()

std::vector< MX > casadi::MX::difference ( const std::vector< MX > &  a,
const std::vector< MX > &  b 
)
static

Functions called by friend functions defined for this class

Definition at line 3092 of file mx.cpp.

3092  {
3093  // Create a set of MXNodes from b
3094  std::set<MXNode*> bs;
3095  for (const auto& e : b) {
3096  if (!e.is_null()) bs.insert(e.get());
3097  }
3098  std::vector<MX> ret;
3099  for (auto&& e : a) {
3100  // If the element is not in the set, add it to the return vector
3101  if (bs.find(e.get())==bs.end()) {
3102  ret.push_back(e);
3103  }
3104  }
3105  return ret;
3106  }

Referenced by stop_diff().

◆ dim()

std::string casadi::GenericMatrix< MX >::dim ( bool  with_nz = false) const
inherited

The representation is e.g. "4x5" or, with with_nz true, "4x5,10nz".

>>> DM.eye(3).dim(), DM.eye(3).dim(True), DM.ones(3, 3).dim(True)
('3x3', '3x3,3nz', '3x3,9nz')

>> fprintf('%s %s %s\n', DM.eye(3).dim(), DM.eye(3).dim(true), DM.ones(3, 3).dim(true))
3x3 3x3,3nz 3x3,9nz

julia> ca.dim(ca.DM.eye(3)), ca.dim(ca.DM.eye(3), true), ca.dim(ca.DM.ones(3, 3), true)
("3x3", "3x3,3nz", "3x3,9nz")

See also
size, nnz

Extra doc: https://github.com/casadi/casadi/wiki/L_1aw

Definition at line 325 of file generic_matrix.hpp.

5274  {
5275  return sparsity().dim(with_nz);
5276  }
std::string dim(bool with_nz=false) const
Dimensions as a string "nrow x ncol", optionally with the number of nonzeros.
Definition: sparsity.cpp:595

◆ disp()

void casadi::SharedObject::disp ( std::ostream &  stream,
bool  more = false 
) const
inherited

Definition at line 35 of file shared_object.cpp.

35  {
36  if (is_null()) {
37  stream << "NULL";
38  } else {
39  (*this)->disp(stream, more);
40  }
41  }

References casadi::GenericShared< SharedObject, SharedObjectInternal >::is_null().

Referenced by casadi::WeakRefInternal::disp(), casadi::Nlpsol::disp_more(), and casadi::CsparseInterface::nfact().

◆ dot()

MX casadi::MX::dot ( const MX &  x,
const MX &  y 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 738 of file mx.cpp.

738  {
739  return x->get_dot(y);
740  }

References casadi::MXNode::get_dot().

Referenced by casadi::RuntimeIntegrator::jump_function().

◆ dump()

MX casadi::MX::dump ( const std::string &  base_filename,
const Dict &  opts = Dict() 
) const

Each evaluation writes the value to a new file named after base_filename and a running counter. The value is unchanged. A matrix without nonzeros is returned as is.

Parameters
base_filenamePrefix of the file names
opts"dir" (directory, default "."), "format" (file format, default "mtx", Matrix Market), "verbose" (print the file name on each dump, default false). Unknown keys raise an error.
See also
monitor, reset_dump_count

Extra doc: https://github.com/casadi/casadi/wiki/L_2f9

Definition at line 757 of file mx.cpp.

757  {
758  return(*this)->get_dump(base_filename, opts);
759  }

References casadi::MXNode::get_dump().

◆ einstein() [1/2]

MX casadi::MX::einstein ( const MX &  A,
const MX &  B,
const MX &  C,
const std::vector< casadi_int > &  dim_a,
const std::vector< casadi_int > &  dim_b,
const std::vector< casadi_int > &  dim_c,
const std::vector< casadi_int > &  a,
const std::vector< casadi_int > &  b,
const std::vector< casadi_int > &  c 
)
static

Computes C_c += A_a * B_b, where a, b and c are index labels in Einstein notation: a label appearing in both a and b is summed over, the remaining labels index the result. Tensors are passed as flat column vectors in column-major (Fortran) order together with their dimensions. Labels are encoded as strictly negative integers. For the matrix product C_ij = A_ik B_kj one writes a = [-1, -3], b = [-3, -2], c = [-1, -2].

Parameters
A,BDense column vectors with product(dim_a), product(dim_b) entries
COptional accumulator with product(dim_c) entries, added to the result; when omitted the result starts from zero
dim_a,dim_b,dim_cTensor dimensions
a,b,cNegative labels, one per dimension
Returns
Column vector with product(dim_c) entries

Inconsistent dimensions or labels are not validated with a user-facing message. Also available for SX and DM.

>>> A = MX.sym("A", 6)
>>> B = MX.sym("B", 6)
>>> C = einstein(A, B, [2, 3], [3, 2], [2, 2], [-1, -3], [-3, -2], [-1, -2])
>>> C.shape
(4, 1)
>>> f = Function("f", [A, B], [C])
>>> f(DM(range(1, 7)), DM(range(1, 7)))
DM([22, 28, 49, 64])
>>> reshape(DM(range(1, 7)), 2, 3) @ reshape(DM(range(1, 7)), 3, 2)
DM(
[[22, 49],
 [28, 64]])

>> A = MX.sym('A', 6); B = MX.sym('B', 6);
>> C = einstein(A, B, [2 3], [3 2], [2 2], [-1 -3], [-3 -2], [-1 -2]);
>> size(C)
4 1
>> f = Function('f', {A, B}, {C});
>> f(DM((1:6)'), DM((1:6)'))
[22, 28, 49, 64]
>> reshape(DM((1:6)'), 2, 3) * reshape(DM((1:6)'), 3, 2)
[[22, 49],
 [28, 64]]

julia> A = ca.MX.sym("A", 6); B = ca.MX.sym("B", 6);
julia> C = ca.einstein(A, B, [2, 3], [3, 2], [2, 2], [-1, -3], [-3, -2], [-1, -2]);
julia> size(C)
(4, 1)
julia> f = ca.Function("f", [A, B], [C]);
julia> f(1:6, 1:6)
DM([22, 28, 49, 64])
julia> reshape(ca.DM(1:6), 2, 3) * reshape(ca.DM(1:6), 3, 2)
DM(
[[22, 49],
 [28, 64]])

Extra doc: https://github.com/casadi/casadi/wiki/L_r5

Definition at line 685 of file mx.cpp.

689  {
690  return C->get_einstein(A, B, dim_c, dim_a, dim_b, c, a, b);
691  }
GenericMatrix< MX > B
Base class.
Definition: mx.hpp:577

References casadi::C.

Referenced by casadi::Einstein::ad_forward(), casadi::Einstein::ad_reverse(), and casadi::derivative_coeff_mx().

◆ einstein() [2/2]

MX casadi::MX::einstein ( const MX &  A,
const MX &  B,
const std::vector< casadi_int > &  dim_a,
const std::vector< casadi_int > &  dim_b,
const std::vector< casadi_int > &  dim_c,
const std::vector< casadi_int > &  a,
const std::vector< casadi_int > &  b,
const std::vector< casadi_int > &  c 
)
static

Computes C_c += A_a * B_b, where a, b and c are index labels in Einstein notation: a label appearing in both a and b is summed over, the remaining labels index the result. Tensors are passed as flat column vectors in column-major (Fortran) order together with their dimensions. Labels are encoded as strictly negative integers. For the matrix product C_ij = A_ik B_kj one writes a = [-1, -3], b = [-3, -2], c = [-1, -2].

Parameters
A,BDense column vectors with product(dim_a), product(dim_b) entries
COptional accumulator with product(dim_c) entries, added to the result; when omitted the result starts from zero
dim_a,dim_b,dim_cTensor dimensions
a,b,cNegative labels, one per dimension
Returns
Column vector with product(dim_c) entries

Inconsistent dimensions or labels are not validated with a user-facing message. Also available for SX and DM.

>>> A = MX.sym("A", 6)
>>> B = MX.sym("B", 6)
>>> C = einstein(A, B, [2, 3], [3, 2], [2, 2], [-1, -3], [-3, -2], [-1, -2])
>>> C.shape
(4, 1)
>>> f = Function("f", [A, B], [C])
>>> f(DM(range(1, 7)), DM(range(1, 7)))
DM([22, 28, 49, 64])
>>> reshape(DM(range(1, 7)), 2, 3) @ reshape(DM(range(1, 7)), 3, 2)
DM(
[[22, 49],
 [28, 64]])

>> A = MX.sym('A', 6); B = MX.sym('B', 6);
>> C = einstein(A, B, [2 3], [3 2], [2 2], [-1 -3], [-3 -2], [-1 -2]);
>> size(C)
4 1
>> f = Function('f', {A, B}, {C});
>> f(DM((1:6)'), DM((1:6)'))
[22, 28, 49, 64]
>> reshape(DM((1:6)'), 2, 3) * reshape(DM((1:6)'), 3, 2)
[[22, 49],
 [28, 64]]

julia> A = ca.MX.sym("A", 6); B = ca.MX.sym("B", 6);
julia> C = ca.einstein(A, B, [2, 3], [3, 2], [2, 2], [-1, -3], [-3, -2], [-1, -2]);
julia> size(C)
(4, 1)
julia> f = ca.Function("f", [A, B], [C]);
julia> f(1:6, 1:6)
DM([22, 28, 49, 64])
julia> reshape(ca.DM(1:6), 2, 3) * reshape(ca.DM(1:6), 3, 2)
DM(
[[22, 49],
 [28, 64]])

Extra doc: https://github.com/casadi/casadi/wiki/L_r5

Definition at line 693 of file mx.cpp.

697  {
698  return MX::zeros(product(dim_c), 1)->get_einstein(A, B, dim_c, dim_a, dim_b, c, a, b);
699  }
virtual MX get_einstein(const MX &A, const MX &B, const std::vector< casadi_int > &dim_c, const std::vector< casadi_int > &dim_a, const std::vector< casadi_int > &dim_b, const std::vector< casadi_int > &c, const std::vector< casadi_int > &a, const std::vector< casadi_int > &b) const
Einstein product and addition.
Definition: mx_node.cpp:586
T product(const std::vector< T > &values)
product

References casadi::MXNode::get_einstein(), casadi::product(), and casadi::GenericMatrix< MX >::zeros().

◆ enlarge()

void casadi::MX::enlarge ( casadi_int  nrow,
casadi_int  ncol,
const std::vector< casadi_int > &  rr,
const std::vector< casadi_int > &  cc,
bool  ind1 = false 
)

Makes the matrix nrow-by-ncol by inserting empty rows and columns, keeping the existing nonzeros. Modifies the expression in place.

Parameters
nrowNew number of rows
ncolNew number of columns
rrRows of the new matrix that receive the existing rows; one entry per existing row
ccColumns of the new matrix that receive the existing columns; one entry per existing column
ind1True for 1-based indices (MATLAB), default 0-based

>>> B = MX.sym("B", 2, 2)
>>> B.enlarge(3, 3, [0, 2], [0, 2])
>>> B.shape, B.nnz(), B.sparsity().row()
((3, 3), 4, [0, 2, 0, 2])

>> B = MX.sym('B', 2, 2);
>> B.enlarge(3, 3, [1, 3], [1, 3], true);
>> size(B), B.nnz(), B.sparsity().row()
3 3
4
0 2 0 2

julia> B = ca.MX.sym("B", 2, 2);
julia> ca.enlarge(B, 3, 3, [0, 2], [0, 2]);
julia> size(B), ca.nnz(B), ca.row(ca.sparsity(B))
((3, 3), 4, [0, 2, 0, 2])

See also
erase, Sparsity.enlarge

Extra doc: https://github.com/casadi/casadi/wiki/L_qg

Definition at line 665 of file mx.cpp.

667  {
668  Sparsity sp = sparsity();
669  sp.enlarge(nrow, ncol, rr, cc, ind1);
670 
671  MX ret = (*this)->get_nzref(sp, range(nnz())); // FIXME?
672  *this = ret;
673  }
const Sparsity & sparsity() const
Get the sparsity pattern.
Definition: mx.cpp:615

References casadi::Sparsity::enlarge(), casadi::MXNode::get_nzref(), casadi::GenericMatrix< MX >::nnz(), casadi::range(), and sparsity().

◆ erase() [1/2]

void casadi::MX::erase ( const std::vector< casadi_int > &  rr,
bool  ind1 = false 
)

Same as the two-index overload, but rr holds linear (column-major) element indices.

>>> B = MX.sym("B", 3, 3)
>>> B.erase([0, 4])
>>> B.sparsity()
Sparsity(3x3,7nz)

>> B = MX.sym('B', 3, 3);
>> B.erase([1, 5], true);
>> B.sparsity()
3x3,7nz

julia> B = ca.MX.sym("B", 3, 3);
julia> ca.erase(B, [0, 4]);
julia> ca.sparsity(B)
Sparsity(3x3,7nz)

Extra doc: https://github.com/casadi/casadi/wiki/L_qf

Definition at line 651 of file mx.cpp.

651  {
652  // Get sparsity of the new matrix
653  Sparsity sp = sparsity();
654 
655  // Erase from sparsity pattern
656  std::vector<casadi_int> mapping = sp.erase(rr, ind1);
657 
658  // Create new matrix
659  if (mapping.size()!=nnz()) {
660  MX ret = (*this)->get_nzref(sp, mapping);
661  *this = ret;
662  }
663  }
void erase(const std::vector< casadi_int > &rr, const std::vector< casadi_int > &cc, bool ind1=false)
Erase the block at the given rows and columns, leaving structural zeros.

References casadi::Sparsity::erase(), casadi::MXNode::get_nzref(), mapping(), casadi::GenericMatrix< MX >::nnz(), casadi::GenericMatrix< MatType >::size(), and sparsity().

◆ erase() [2/2]

void casadi::MX::erase ( const std::vector< casadi_int > &  rr,
const std::vector< casadi_int > &  cc,
bool  ind1 = false 
)

Removes the nonzeros at the intersection of rows rr and columns cc from the sparsity pattern. The shape is unchanged. Modifies the expression in place by replacing it with a new node that references the remaining nonzeros.

Parameters
rrRow indices to erase; out-of-range values raise an error
ccColumn indices to erase
ind1True for 1-based indices (MATLAB), default 0-based

>>> B = MX.sym("B", 3, 3)
>>> B.erase([0], [1])
>>> B.sparsity(), B.shape
(Sparsity(3x3,8nz), (3, 3))

>> B = MX.sym('B', 3, 3);
>> B.erase(1, 2, true);
>> B.sparsity(), size(B)
3x3,8nz
3 3

julia> B = ca.MX.sym("B", 3, 3);
julia> ca.erase(B, [0], [1]);
julia> ca.sparsity(B), size(B)
(3x3,8nz, (3, 3))

See also
enlarge, Sparsity.erase

Extra doc: https://github.com/casadi/casadi/wiki/L_qe

Definition at line 619 of file mx.cpp.

619  {
620  // Get sparsity of the new matrix
621  Sparsity sp = sparsity();
622 
623  // Erase from sparsity pattern
624  std::vector<casadi_int> mapping = sp.erase(rr, cc, ind1);
625 
626  // Create new matrix
627  if (mapping.size()!=nnz()) {
628  MX ret = (*this)->get_nzref(sp, mapping);
629  *this = ret;
630  }
631  }

References casadi::Sparsity::erase(), casadi::MXNode::get_nzref(), mapping(), casadi::GenericMatrix< MX >::nnz(), casadi::GenericMatrix< MatType >::size(), and sparsity().

Referenced by set().

◆ eval_mx()

void casadi::MX::eval_mx ( const std::vector< MX > &  arg,
std::vector< MX > &  res,
const std::vector< bool > &  unique = std::vector<bool>() 
) const

Creates the same operation as this node, applied to arg instead of the node's own dependencies, with the usual simplifications. arg must have exactly n_dep() entries of matching shapes; a mismatch is a developer error. Symbolic primitives and constants return the node itself. Call nodes are re-called with the new arguments; OutputNodes cannot be evaluated this way. Mainly useful for writing graph transformations.

Parameters
argNew dependencies
uniqueInternal hints that the arguments are not referenced elsewhere; leave empty
Returns
List with n_out() results

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> (x * y).eval_mx([MX(2), MX(3)]), (x + y).eval_mx([y, x])
([MX(6)], [MX((y+x))])
>>> MX.sym("v", 3)[1].eval_mx([MX([4, 5, 6])])
[MX([4, 5, 6][1])]

>> x = MX.sym('x'); y = MX.sym('y');
>> e = x * y; r = e.eval_mx({MX(2), MX(3)});
>> numel(r), r{1}
1
6
>> e = x + y; r = e.eval_mx({y, x});
>> r{1}
(y+x)
>> v = MX.sym('v', 3); e = v(2); r = e.eval_mx({MX([4; 5; 6])});
>> r{1}
[4, 5, 6][1]

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> ca.eval_mx(x * y, [ca.MX(2), ca.MX(3)]), ca.eval_mx(x + y, [y, x])
(MX[6], MX[(y+x)])
julia> ca.eval_mx(ca.MX.sym("v", 3)[2], [ca.MX([4, 5, 6])])
1-element Vector{MX}:
 MX([4, 5, 6][1])

See also
dep, n_dep, graph_substitute

Extra doc: https://github.com/casadi/casadi/wiki/L_rn

Definition at line 3216 of file mx.cpp.

3217  {
3218  try {
3219  casadi_assert(arg.size()==n_dep(),
3220  "Expected " + str(n_dep()) + " arguments, but got " + str(arg.size()) + ".");
3221  res.resize((*this)->nout());
3222  (*this)->eval_mx(arg, res, unique);
3223  } catch (std::exception& e) {
3224  CASADI_THROW_ERROR_OBJ("eval_mx", e.what());
3225  }
3226  }
casadi_int n_dep() const
Get the number of dependencies (child nodes) of this node.
Definition: mx.cpp:790

References n_dep(), and casadi::str().

◆ evalf()

DM casadi::MX::evalf ( const MX &  m)
static

Functions called by friend functions defined for this class

Definition at line 771 of file mx.cpp.

771  {
772  Function f("f", std::vector<MX>{}, {m}, {{"allow_free", true}});
773  return f(std::vector<DM>{})[0];
774  }

◆ expm()

MX casadi::MX::expm ( const MX &  A)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2147 of file mx.cpp.

2147  {
2148  Function ret = expmsol("mysolver", "slicot", A.sparsity());
2149  return ret(std::vector<MX>{A, 1})[0];
2150  }
Function expmsol(const std::string &name, const std::string &solver, const Sparsity &A, const Dict &opts)
Definition: expm.cpp:44

References casadi::expmsol(), and sparsity().

◆ expm_const()

MX casadi::MX::expm_const ( const MX &  A,
const MX &  t 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2140 of file mx.cpp.

2140  {
2141  Dict opts;
2142  opts["const_A"] = true;
2143  Function ret = expmsol("mysolver", "slicot", A.sparsity(), opts);
2144  return ret(std::vector<MX>{A, t})[0];
2145  }

References casadi::expmsol(), and sparsity().

◆ extract()

void casadi::MX::extract ( std::vector< MX > &  ex,
std::vector< MX > &  v,
std::vector< MX > &  vdef,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1733 of file mx.cpp.

1734  {
1735  try {
1736  // Read options
1737  std::string v_prefix = "v_", v_suffix = "";
1738  bool lift_shared = true, lift_calls = false;
1739  casadi_int v_ind = 0;
1740  for (auto&& op : opts) {
1741  if (op.first == "prefix") {
1742  v_prefix = std::string(op.second);
1743  } else if (op.first == "suffix") {
1744  v_suffix = std::string(op.second);
1745  } else if (op.first == "lift_shared") {
1746  lift_shared = op.second;
1747  } else if (op.first == "lift_calls") {
1748  lift_calls = op.second;
1749  } else if (op.first == "offset") {
1750  v_ind = op.second;
1751  } else {
1752  casadi_error("No such option: " + std::string(op.first));
1753  }
1754  }
1755  // Sort the expression
1756  Function f("tmp_extract", std::vector<MX>{}, ex, Dict{{"max_io", 0}, {"allow_free", true}});
1757  auto *ff = f.get<MXFunction>();
1758  // Get references to the internal data structures
1759  const std::vector<MXAlgEl>& algorithm = ff->algorithm_;
1760  std::vector<MX> work(ff->workloc_.size()-1);
1761  // Count how many times an expression has been used
1762  std::vector<casadi_int> usecount(work.size(), 0);
1763  // Remember the origin of every calculation
1764  std::vector<std::pair<casadi_int, casadi_int> > origin(work.size(), std::make_pair(-1, -1));
1765  // Which evaluations to replace
1766  std::vector<std::pair<casadi_int, casadi_int> > replace;
1767  // Evaluate the algorithm to identify which evaluations to replace
1768  casadi_int k=0;
1769  for (auto it=algorithm.begin(); it<algorithm.end(); ++it, ++k) {
1770  // Increase usage counters
1771  switch (it->op) {
1772  case OP_CONST:
1773  case OP_PARAMETER:
1774  break;
1775  default: // Unary operation, binary operation or output
1776  for (casadi_int c=0; c<it->arg.size(); ++c) {
1777  // Identify nodes used more than once
1778  if (lift_calls && it->op == OP_CALL) {
1779  // If not already marked for replacing
1780  if (usecount.at(it->arg[c]) >= 0) {
1781  replace.push_back(origin.at(it->arg[c]));
1782  usecount.at(it->arg[c]) = -1; // Do not replace again
1783  }
1784  } else if (lift_shared && work[it->arg[c]].op() != OP_PARAMETER
1785  && work[it->arg[c]].op() != OP_CONST) {
1786  if (usecount.at(it->arg[c]) == 0) {
1787  // First time node is used
1788  usecount.at(it->arg[c]) = 1;
1789  } else if (usecount.at(it->arg[c]) == 1) {
1790  // Second time node is used
1791  replace.push_back(origin.at(it->arg[c]));
1792  usecount.at(it->arg[c]) = -1; // Do not replace again
1793  }
1794  }
1795  }
1796  }
1797  // Perform the operation
1798  switch (it->op) {
1799  case OP_OUTPUT:
1800  break;
1801  case OP_CONST:
1802  usecount[it->res.front()] = -1; // Never extract constants
1803  break;
1804  default:
1805  for (casadi_int c=0; c<it->res.size(); ++c) {
1806  if (it->res[c]>=0) {
1807  work[it->res[c]] = it->data.get_output(c);
1808  origin[it->res[c]] = std::make_pair(k, c);
1809  if (lift_calls && it->op == OP_CALL) {
1810  // If function call, replace right away
1811  replace.push_back(origin.at(it->res[c]));
1812  usecount.at(it->res[c]) = -1; // Do not replace again
1813  } else {
1814  usecount.at(it->res[c]) = 0; // Not (yet) extracted
1815  }
1816  }
1817  }
1818  break;
1819  }
1820  }
1821  // New variables and definitions
1822  v.clear();
1823  v.reserve(replace.size());
1824  vdef.clear();
1825  vdef.reserve(replace.size());
1826  // Quick return
1827  if (replace.empty()) return;
1828  // Sort the elements to be replaced in the order of appearence in the algorithm
1829  sort(replace.begin(), replace.end());
1830  std::vector<std::pair<casadi_int, casadi_int> >::const_iterator replace_it=replace.begin();
1831  // Arguments for calling the atomic operations
1832  std::vector<MX> oarg, ores;
1833  // Evaluate the algorithm
1834  k = 0;
1835  for (auto it=algorithm.begin(); it<algorithm.end(); ++it, ++k) {
1836  switch (it->op) {
1837  case OP_OUTPUT:
1838  casadi_assert(it->data->segment()==0, "Not implemented");
1839  ex[it->data->ind()] = work[it->arg.front()];
1840  break;
1841  case OP_CONST:
1842  work[it->res.front()] = it->data;
1843  break;
1844  default:
1845  {
1846  if (it->op == OP_PARAMETER) {
1847  // Free parameter
1848  work[it->res.front()] = it->data;
1849  } else {
1850  // Arguments of the operation
1851  oarg.resize(it->arg.size());
1852  for (casadi_int i=0; i<oarg.size(); ++i) {
1853  casadi_int el = it->arg[i];
1854  oarg[i] = el<0 ? MX(it->data->dep(i).size()) : work.at(el);
1855  }
1856  // Perform the operation
1857  ores.resize(it->res.size());
1858  it->data->eval_mx(oarg, ores);
1859  // Get the result
1860  for (casadi_int i=0; i<ores.size(); ++i) {
1861  casadi_int el = it->res[i];
1862  if (el>=0) work.at(el) = ores[i];
1863  }
1864  }
1865  // Possibly replace results with new variables
1866  for (casadi_int c=0; c<it->res.size(); ++c) {
1867  // Output index
1868  casadi_int ind = it->res[c];
1869  // In the list of nodes for replacing?
1870  bool replace_node = replace_it != replace.end()
1871  && replace_it->first==k && replace_it->second==c;
1872  // Call node (introduce variable for outputs, even if unused)
1873  bool output_node = lift_calls && it->op == OP_CALL;
1874  // Skip if no reason to replace
1875  if (!replace_node && !output_node) continue;
1876  // Create a new variable
1877  Sparsity v_sp = it->op == OP_PARAMETER ? it->data.sparsity() : ores.at(c).sparsity();
1878  v.push_back(MX::sym(v_prefix + std::to_string(v_ind++) + v_suffix, v_sp));
1879  // Add definition of new variable
1880  if (ind >= 0) {
1881  // Replace existing call
1882  casadi_assert(replace_node, "Consistency check");
1883  // Store the result
1884  vdef.push_back(work[ind]);
1885  // Use in calculations
1886  work[ind] = v.back();
1887  // Go to the next element to be replaced
1888  replace_it++;
1889  } else {
1890  // New node corresponding to an output
1891  casadi_assert(output_node, "Consistency check");
1892  // Store the result
1893  vdef.push_back(ores.at(c));
1894  }
1895  }
1896  }
1897  }
1898  }
1899  // Ensure all nodes have been replaced
1900  casadi_assert(replace_it == replace.end(), "Consistency check failed");
1901  } catch (std::exception& e) {
1902  CASADI_THROW_ERROR("extract", e.what());
1903  }
1904  }
CASADI_EXPORT std::string replace(const std::string &s, const std::string &p, const std::string &r)
Replace all occurences of p with r in s.
void sort(const std::vector< T > &values, std::vector< T > &sorted_values, std::vector< casadi_int > &indices, bool invert_indices=false)
Sort the data in a vector.
@ OP_CONST
Definition: calculus.hpp:79

References casadi::MXFunction::algorithm_, casadi::Function::get(), MX(), op(), casadi::OP_CALL, casadi::OP_CONST, casadi::OP_OUTPUT, casadi::OP_PARAMETER, casadi::replace(), casadi::sort(), and casadi::GenericMatrix< MX >::sym().

Referenced by shared().

◆ extract_parametric()

void casadi::MX::extract_parametric ( const MX &  expr,
const MX &  par,
MX &  expr_ret,
std::vector< MX > &  symbols,
std::vector< MX > &  parametric,
const Dict &  opts 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2803 of file mx.cpp.

2805  {
2806  std::string v_prefix = "e_";
2807  std::string v_suffix = "";
2808  bool extract_trivial = false;
2809  casadi_int v_offset = 0;
2810  for (auto&& op : opts) {
2811  if (op.first == "prefix") {
2812  v_prefix = std::string(op.second);
2813  } else if (op.first == "suffix") {
2814  v_suffix = std::string(op.second);
2815  } else if (op.first == "offset") {
2816  v_offset = op.second;
2817  } else if (op.first == "extract_trivial") {
2818  extract_trivial = op.second;
2819  } else {
2820  casadi_error("No such option: " + std::string(op.first));
2821  }
2822  }
2823  Function f("f", {par}, {expr}, {{"live_variables", false},
2824  {"max_io", 0}, {"allow_free", true}});
2825  MXFunction *ff = f.get<MXFunction>();
2826 
2827  // Work vector
2828  std::vector< MX > w(ff->workloc_.size()-1);
2829 
2830  // Status of the expression:
2831  // 0: dependant on constants only
2832  // 1: dependant on parameters/constants only
2833  // 2: dependant on non-parameters
2834  std::vector< char > expr_status(ff->workloc_.size()-1, 0);
2835 
2836  // Split up inputs analogous to symbolic primitives
2837  std::vector<MX> arg_split = par.split_primitives(par);
2838 
2839  // Allocate storage for split outputs
2840  std::vector<MX> res_split;
2841  res_split.resize(expr.n_primitives());
2842 
2843  // Scratch space for node inputs/outputs
2844  std::vector<MX > arg1, res1;
2845 
2846  // Map of registered symbols
2847  std::map<MXNode*, MX> symbol_map;
2848 
2849  // Flat list of registerd symbols and parametric expressions
2850  std::vector<MX> symbol_v, parametric_v;
2851 
2852  // Loop over computational nodes in forward order
2853  casadi_int alg_counter = 0;
2854  for (auto it=ff->algorithm_.begin(); it!=ff->algorithm_.end(); ++it, ++alg_counter) {
2855  if (it->op == OP_INPUT) {
2856  w[it->res.front()] = arg_split.at(it->data->segment());
2857  expr_status[it->res.front()] = 1;
2858  } else if (it->op==OP_OUTPUT) {
2859  MX arg = w[it->arg.front()];
2860  if (expr_status[it->arg.front()]==1) {
2861  arg = register_symbol(arg, symbol_map, symbol_v, parametric_v,
2862  extract_trivial, v_offset, v_prefix, v_suffix);
2863  }
2864  // Collect the results
2865  res_split.at(it->data->segment()) = arg;
2866  } else if (it->op==OP_CONST) {
2867  // Fetch constant
2868  w[it->res.front()] = it->data;
2869  expr_status[it->res.front()] = 0;
2870  } else if (it->op==OP_PARAMETER) {
2871  // Free variables
2872  w[it->res.front()] = it->data;
2873  expr_status[it->res.front()] = 2;
2874  } else {
2875  // Arguments of the operation
2876  arg1.resize(it->arg.size());
2877  for (casadi_int i=0; i<arg1.size(); ++i) {
2878  casadi_int el = it->arg[i]; // index of the argument
2879  arg1[i] = el<0 ? MX(it->data->dep(i).size()) : w[el];
2880  }
2881 
2882  // Check worst case status of inputs
2883  char max_status = 0;
2884  for (casadi_int i=0; i<arg1.size(); ++i) {
2885  casadi_int el = it->arg[i]; // index of the argument
2886  if (el>=0) {
2887  max_status = std::max(max_status, expr_status[it->arg[i]]);
2888  }
2889  }
2890  bool any_tainted = max_status==2;
2891 
2892  if (any_tainted) {
2893  // Loop over all inputs
2894  for (casadi_int i=0; i<arg1.size(); ++i) {
2895  casadi_int el = it->arg[i]; // index of the argument
2896 
2897  // For each parametric input being mixed into a non-parametric expression
2898  if (el>=0 && expr_status[el]==1) {
2899 
2900  arg1[i] = register_symbol(w[el], symbol_map, symbol_v, parametric_v,
2901  extract_trivial, v_offset, v_prefix, v_suffix);
2902  }
2903  }
2904  }
2905 
2906  // Perform the operation
2907  res1.resize(it->res.size());
2908  it->data->eval_mx(arg1, res1);
2909 
2910  // Get the result
2911  for (casadi_int i=0; i<res1.size(); ++i) {
2912  casadi_int el = it->res[i]; // index of the output
2913  if (el>=0) {
2914  w[el] = res1[i];
2915  // Update expression status
2916  expr_status[el] = max_status;
2917  }
2918  }
2919  }
2920  }
2921 
2922  // Join split outputs
2923  expr_ret = expr.join_primitives(res_split);
2924 
2925  symbols = symbol_v;
2926  parametric = parametric_v;
2927  }
MX register_symbol(const MX &node, std::map< MXNode *, MX > &symbol_map, std::vector< MX > &symbol_v, std::vector< MX > &parametric_v, bool extract_trivial, casadi_int v_offset, const std::string &v_prefix, const std::string &v_suffix)
Definition: mx.cpp:2773

References join_primitives(), MX(), n_primitives(), op(), casadi::OP_CONST, casadi::OP_INPUT, casadi::OP_OUTPUT, casadi::OP_PARAMETER, casadi::register_symbol(), and split_primitives().

◆ eye()

MX casadi::MX::eye ( casadi_int  n)
static

>>> MX.eye(2), MX.eye(2).is_eye()
(MX(ones(2x2,2nz)), True)

>> MX.eye(2), MX.eye(2).is_eye()
ones(2x2,2nz)
1

julia> ca.MX.eye(2), ca.is_eye(ca.MX.eye(2))
(ones(2x2,2nz), true)

Extra doc: https://github.com/casadi/casadi/wiki/L_r4

Definition at line 603 of file mx.cpp.

603  {
604  return MX(DM::eye(n));
605  }
static Matrix< double > eye(casadi_int n)
Create an n-by-n identity matrix.

References casadi::Matrix< double >::eye(), and MX().

Referenced by casadi::OptiNode::canon_expr(), and inv().

◆ find()

MX casadi::MX::find ( const MX &  x)
static

Functions called by friend functions defined for this class

Definition at line 2209 of file mx.cpp.

2209  {
2210  return x->get_find();
2211  }

References casadi::MXNode::get_find().

Referenced by casadi::DaeBuilderInternal::create(), graph_substitute(), casadi::DaeBuilderInternal::hess_v_v_from_calls(), casadi::DaeBuilderInternal::jac_vdef_v_from_calls(), and casadi::register_symbol().

◆ forward()

std::vector< std::vector< MX > > casadi::MX::forward ( const std::vector< MX > &  ex,
const std::vector< MX > &  arg,
const std::vector< std::vector< MX > > &  v,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1942 of file mx.cpp.

1944  {
1945  try {
1946  // Read options
1947  bool always_inline = true;
1948  bool never_inline = false;
1949 
1950  Dict h_opts;
1951  Dict opts_remainder = extract_from_dict(opts, "helper_options", h_opts);
1952  h_opts["allow_free"] = true;
1953  for (auto&& op : opts_remainder) {
1954  if (op.first=="always_inline") {
1955  always_inline = op.second;
1956  } else if (op.first=="never_inline") {
1957  never_inline = op.second;
1958  } else {
1959  casadi_error("No such option: " + std::string(op.first));
1960  }
1961  }
1962  // Call internal function on a temporary object
1963  Function temp("forward_temp", arg, ex, h_opts);
1964  std::vector<std::vector<MX> > ret;
1965  temp->call_forward(arg, ex, v, ret, always_inline, never_inline);
1966  return ret;
1967  } catch (std::exception& e) {
1968  CASADI_THROW_ERROR("forward", e.what());
1969  }
1970  }
Dict extract_from_dict(const Dict &d, const std::string &key, T &value)

References casadi::FunctionInternal::call_forward(), casadi::extract_from_dict(), and op().

◆ get() [1/16]

MXNode * casadi::MX::get ( ) const

◆ get() [2/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
casadi_int  rr,
casadi_int  cc 
) const
inline

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 2962 of file mx.hpp.

2963  {
2964  get(m, ind1, Matrix<casadi_int>(rr), Matrix<casadi_int>(cc));
2965  }
MXNode * get() const
Get a const pointer to the node.
Definition: mx.cpp:567
template class CASADI_EXPORT Matrix< casadi_int >

◆ get() [3/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
casadi_int  rr,
const Slice &  cc 
) const
inline

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 2957 of file mx.hpp.

2957  {
2958  get(m, ind1, Matrix<casadi_int>(rr), cc);
2959  }

◆ get() [4/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const casadi_int  rr 
) const
inline

Backs single-index subscripting. Elements are addressed in column-major order over all numel() entries, including structural zeros. Indices may be negative (counted from the end); out-of-range indices raise an error. The result is a new GetNonzeros node referencing the selected nonzeros of this expression; a structural zero is returned as an empty-sparsity constant. Accepted index types: integer, slice, list of integers, list of booleans (mask), integer DM, Sparsity pattern of the same shape (returns the projection on that pattern) and MX (a symbolic index into the nonzeros of a dense expression, evaluated at run time with truncation and NaN for out-of-range values).

Parameters
ind1True for 1-based indices (MATLAB), false for 0-based
rrElement indices

>>> X = MX.sym("X", 3, 3)
>>> X[4], X[-1], X[[0, 4]], X[1:3].shape
(MX(X[4]), MX(X[8]), MX(X[:8:4]), (2, 1))
>>> try:
...   X[9]
... except Exception as e:
...   print("Out of bounds" in str(e))
True
>>> S = MX.sym("S", Sparsity.lower(2))
>>> S[2], S[2].nnz()
(MX(00), 0)
>>> X[Sparsity.lower(3)]
MX(project(X))
>>> k = MX.sym("k")
>>> v = MX.sym("v", 4)
>>> v[k], Function("f", [v, k], [v[k]])(DM([10, 20, 30, 40]), 1.7)
(MX(v[k]), DM(20))

>> X = MX.sym('X', 3, 3);
>> a = X(5); b = X(end); c = X([1, 5]); d = X([2; 3]);
>> a, b, c, size(d)
X[4]
X[8]
X[:8:4]
2 1
>> try, X(10); catch e, disp('out of bounds'); end
out of bounds
>> S = MX.sym('S', Sparsity.lower(2));
>> e = S(3);
>> e, e.nnz()
00
0
>> X(Sparsity.lower(3))
project(X)
>> k = MX.sym('k'); v = MX.sym('v', 4);
>> f = Function('f', {v, k}, {v(k)});
>> v(k), f(DM([10; 20; 30; 40]), 2.7)
v[(k-1)]
20

julia> X = ca.MX.sym("X", 3, 3);
julia> X[5], X[end], X[[1, 5]], size(X[2:3])
(X[4], X[8], X[[0, 4]], (2, 1))
julia> try
           X[10]
       catch e
           println(e isa BoundsError)
       end
true
julia> S = ca.MX.sym("S", ca.Sparsity.lower(2));
julia> S[3], ca.nnz(S[3])
(00, 0)
julia> X[ca.Sparsity.lower(3)]
MX(project(X))
julia> k = ca.MX.sym("k"); v = ca.MX.sym("v", 4);
julia> v[k]
MX(v[(k-1)])
julia> ca.Function("f", [v, k], [v[k]])([10, 20, 30, 40], 2.7)
DM(20)

See also
set, get_nz, nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qa

Definition at line 2891 of file mx.hpp.

2891  {
2892  get(m, ind1, Matrix<casadi_int>(rr));
2893  }

◆ get() [5/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Matrix< casadi_int > &  rr 
) const

Backs single-index subscripting. Elements are addressed in column-major order over all numel() entries, including structural zeros. Indices may be negative (counted from the end); out-of-range indices raise an error. The result is a new GetNonzeros node referencing the selected nonzeros of this expression; a structural zero is returned as an empty-sparsity constant. Accepted index types: integer, slice, list of integers, list of booleans (mask), integer DM, Sparsity pattern of the same shape (returns the projection on that pattern) and MX (a symbolic index into the nonzeros of a dense expression, evaluated at run time with truncation and NaN for out-of-range values).

Parameters
ind1True for 1-based indices (MATLAB), false for 0-based
rrElement indices

>>> X = MX.sym("X", 3, 3)
>>> X[4], X[-1], X[[0, 4]], X[1:3].shape
(MX(X[4]), MX(X[8]), MX(X[:8:4]), (2, 1))
>>> try:
...   X[9]
... except Exception as e:
...   print("Out of bounds" in str(e))
True
>>> S = MX.sym("S", Sparsity.lower(2))
>>> S[2], S[2].nnz()
(MX(00), 0)
>>> X[Sparsity.lower(3)]
MX(project(X))
>>> k = MX.sym("k")
>>> v = MX.sym("v", 4)
>>> v[k], Function("f", [v, k], [v[k]])(DM([10, 20, 30, 40]), 1.7)
(MX(v[k]), DM(20))

>> X = MX.sym('X', 3, 3);
>> a = X(5); b = X(end); c = X([1, 5]); d = X([2; 3]);
>> a, b, c, size(d)
X[4]
X[8]
X[:8:4]
2 1
>> try, X(10); catch e, disp('out of bounds'); end
out of bounds
>> S = MX.sym('S', Sparsity.lower(2));
>> e = S(3);
>> e, e.nnz()
00
0
>> X(Sparsity.lower(3))
project(X)
>> k = MX.sym('k'); v = MX.sym('v', 4);
>> f = Function('f', {v, k}, {v(k)});
>> v(k), f(DM([10; 20; 30; 40]), 2.7)
v[(k-1)]
20

julia> X = ca.MX.sym("X", 3, 3);
julia> X[5], X[end], X[[1, 5]], size(X[2:3])
(X[4], X[8], X[[0, 4]], (2, 1))
julia> try
           X[10]
       catch e
           println(e isa BoundsError)
       end
true
julia> S = ca.MX.sym("S", ca.Sparsity.lower(2));
julia> S[3], ca.nnz(S[3])
(00, 0)
julia> X[ca.Sparsity.lower(3)]
MX(project(X))
julia> k = ca.MX.sym("k"); v = ca.MX.sym("v", 4);
julia> v[k]
MX(v[(k-1)])
julia> ca.Function("f", [v, k], [v[k]])([10, 20, 30, 40], 2.7)
DM(20)

See also
set, get_nz, nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qa

Definition at line 189 of file mx.cpp.

189  {
190  // If the indexed matrix is dense, use nonzero indexing
191  if (is_dense()) {
192  get_nz(m, ind1, rr);
193  return;
194  }
195 
196  // If indexed matrix was a row/column vector, make sure that the result is too
197  bool tr = (is_column() && rr.is_row()) || (is_row() && rr.is_column());
198 
199  // Get the sparsity pattern - does bounds checking
200  std::vector<casadi_int> mapping;
201  Sparsity sp = sparsity().sub(rr.nonzeros(), tr ? rr.sparsity().T() : rr.sparsity(),
202  mapping, ind1);
203 
204  // Create return MX
205  m = (*this)->get_nzref(sp, mapping);
206  }
bool is_dense() const
Check if the matrix is dense, i.e. nnz() equals numel()
bool is_column() const
Check if the matrix is a column vector (i.e. size2()==1)
bool is_row() const
Check if the matrix is a row vector (i.e. size1()==1)
void get_nz(MX &m, bool ind1, const Slice &kk) const
Get a set of nonzeros (what x.nz[k] does)
Definition: mx.cpp:406
std::vector< Scalar > & nonzeros()
Sparsity sub(const std::vector< casadi_int > &rr, const std::vector< casadi_int > &cc, std::vector< casadi_int > &mapping, bool ind1=false) const
Pattern of the submatrix with rows rr and columns cc.
Definition: sparsity.cpp:336
Sparsity T() const
Transposed pattern.
Definition: sparsity.cpp:396

References get_nz(), casadi::MXNode::get_nzref(), casadi::GenericMatrix< MatType >::is_column(), casadi::GenericMatrix< MX >::is_column(), casadi::GenericMatrix< MX >::is_dense(), casadi::GenericMatrix< MX >::is_row(), casadi::GenericMatrix< MatType >::is_row(), mapping(), casadi::Matrix< Scalar >::nonzeros(), casadi::Matrix< Scalar >::sparsity(), sparsity(), casadi::Sparsity::sub(), and casadi::Sparsity::T().

◆ get() [6/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Matrix< casadi_int > &  rr,
const Matrix< casadi_int > &  cc 
) const

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 169 of file mx.cpp.

169  {
170  // Make sure dense vectors
171  casadi_assert(rr.is_dense() && rr.is_vector(),
172  "Marix::get: First index must be a dense vector");
173  casadi_assert(cc.is_dense() && cc.is_vector(),
174  "Marix::get: Second index must be a dense vector");
175 
176  // Get the sparsity pattern - does bounds checking
177  std::vector<casadi_int> mapping;
178  Sparsity sp = sparsity().sub(rr.nonzeros(), cc.nonzeros(), mapping, ind1);
179 
180  // Create return MX
181  m = (*this)->get_nzref(sp, mapping);
182  }
bool is_vector() const
Check if the matrix is a row or column vector.

References casadi::MXNode::get_nzref(), casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_vector(), mapping(), casadi::Matrix< Scalar >::nonzeros(), sparsity(), and casadi::Sparsity::sub().

◆ get() [7/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Matrix< casadi_int > &  rr,
const Slice &  cc 
) const

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 164 of file mx.cpp.

164  {
165  // Fall back on (IM, IM)
166  get(m, ind1, rr, cc.all(size2(), ind1));
167  }

References casadi::Slice::all(), get(), and casadi::GenericMatrix< MX >::size2().

◆ get() [8/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const MX &  rr 
) const

Backs single-index subscripting. Elements are addressed in column-major order over all numel() entries, including structural zeros. Indices may be negative (counted from the end); out-of-range indices raise an error. The result is a new GetNonzeros node referencing the selected nonzeros of this expression; a structural zero is returned as an empty-sparsity constant. Accepted index types: integer, slice, list of integers, list of booleans (mask), integer DM, Sparsity pattern of the same shape (returns the projection on that pattern) and MX (a symbolic index into the nonzeros of a dense expression, evaluated at run time with truncation and NaN for out-of-range values).

Parameters
ind1True for 1-based indices (MATLAB), false for 0-based
rrElement indices

>>> X = MX.sym("X", 3, 3)
>>> X[4], X[-1], X[[0, 4]], X[1:3].shape
(MX(X[4]), MX(X[8]), MX(X[:8:4]), (2, 1))
>>> try:
...   X[9]
... except Exception as e:
...   print("Out of bounds" in str(e))
True
>>> S = MX.sym("S", Sparsity.lower(2))
>>> S[2], S[2].nnz()
(MX(00), 0)
>>> X[Sparsity.lower(3)]
MX(project(X))
>>> k = MX.sym("k")
>>> v = MX.sym("v", 4)
>>> v[k], Function("f", [v, k], [v[k]])(DM([10, 20, 30, 40]), 1.7)
(MX(v[k]), DM(20))

>> X = MX.sym('X', 3, 3);
>> a = X(5); b = X(end); c = X([1, 5]); d = X([2; 3]);
>> a, b, c, size(d)
X[4]
X[8]
X[:8:4]
2 1
>> try, X(10); catch e, disp('out of bounds'); end
out of bounds
>> S = MX.sym('S', Sparsity.lower(2));
>> e = S(3);
>> e, e.nnz()
00
0
>> X(Sparsity.lower(3))
project(X)
>> k = MX.sym('k'); v = MX.sym('v', 4);
>> f = Function('f', {v, k}, {v(k)});
>> v(k), f(DM([10; 20; 30; 40]), 2.7)
v[(k-1)]
20

julia> X = ca.MX.sym("X", 3, 3);
julia> X[5], X[end], X[[1, 5]], size(X[2:3])
(X[4], X[8], X[[0, 4]], (2, 1))
julia> try
           X[10]
       catch e
           println(e isa BoundsError)
       end
true
julia> S = ca.MX.sym("S", ca.Sparsity.lower(2));
julia> S[3], ca.nnz(S[3])
(00, 0)
julia> X[ca.Sparsity.lower(3)]
MX(project(X))
julia> k = ca.MX.sym("k"); v = ca.MX.sym("v", 4);
julia> v[k]
MX(v[(k-1)])
julia> ca.Function("f", [v, k], [v[k]])([10, 20, 30, 40], 2.7)
DM(20)

See also
set, get_nz, nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qa

Definition at line 216 of file mx.cpp.

216  {
217  casadi_assert(is_dense(), "Parametric slicing only supported for dense matrices."
218  "Got " + dim(true) + " instead.");
219  get_nz(m, ind1, rr);
220  }

References casadi::GenericMatrix< MX >::dim(), get_nz(), and casadi::GenericMatrix< MX >::is_dense().

◆ get() [9/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const MX &  rr,
const MX &  cc 
) const

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 232 of file mx.cpp.

232  {
233  casadi_assert(is_dense(), "Parametric slicing only supported for dense matrices.");
234  m = (*this)->get_nz_ref(ind1 ? rr-1 : rr, floor(ind1 ? cc-1 : cc)*size1());
235  }
casadi_int size1() const
Get the first dimension (i.e. number of rows)
static MX floor(const MX &x)
Round down to nearest integer: x -> floor(x)

References casadi::GenericExpression< MX >::floor(), casadi::MXNode::get_nz_ref(), casadi::GenericMatrix< MX >::is_dense(), and casadi::GenericMatrix< MX >::size1().

◆ get() [10/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const MX &  rr,
const Slice &  cc 
) const

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 227 of file mx.cpp.

227  {
228  casadi_assert(is_dense(), "Parametric slicing only supported for dense matrices.");
229  m = (*this)->get_nz_ref(ind1 ? rr-1 : rr, cc.apply(size2())*size1());
230  }

References casadi::Slice::apply(), casadi::MXNode::get_nz_ref(), casadi::GenericMatrix< MX >::is_dense(), casadi::GenericMatrix< MX >::size1(), and casadi::GenericMatrix< MX >::size2().

◆ get() [11/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Slice &  rr 
) const

Backs single-index subscripting. Elements are addressed in column-major order over all numel() entries, including structural zeros. Indices may be negative (counted from the end); out-of-range indices raise an error. The result is a new GetNonzeros node referencing the selected nonzeros of this expression; a structural zero is returned as an empty-sparsity constant. Accepted index types: integer, slice, list of integers, list of booleans (mask), integer DM, Sparsity pattern of the same shape (returns the projection on that pattern) and MX (a symbolic index into the nonzeros of a dense expression, evaluated at run time with truncation and NaN for out-of-range values).

Parameters
ind1True for 1-based indices (MATLAB), false for 0-based
rrElement indices

>>> X = MX.sym("X", 3, 3)
>>> X[4], X[-1], X[[0, 4]], X[1:3].shape
(MX(X[4]), MX(X[8]), MX(X[:8:4]), (2, 1))
>>> try:
...   X[9]
... except Exception as e:
...   print("Out of bounds" in str(e))
True
>>> S = MX.sym("S", Sparsity.lower(2))
>>> S[2], S[2].nnz()
(MX(00), 0)
>>> X[Sparsity.lower(3)]
MX(project(X))
>>> k = MX.sym("k")
>>> v = MX.sym("v", 4)
>>> v[k], Function("f", [v, k], [v[k]])(DM([10, 20, 30, 40]), 1.7)
(MX(v[k]), DM(20))

>> X = MX.sym('X', 3, 3);
>> a = X(5); b = X(end); c = X([1, 5]); d = X([2; 3]);
>> a, b, c, size(d)
X[4]
X[8]
X[:8:4]
2 1
>> try, X(10); catch e, disp('out of bounds'); end
out of bounds
>> S = MX.sym('S', Sparsity.lower(2));
>> e = S(3);
>> e, e.nnz()
00
0
>> X(Sparsity.lower(3))
project(X)
>> k = MX.sym('k'); v = MX.sym('v', 4);
>> f = Function('f', {v, k}, {v(k)});
>> v(k), f(DM([10; 20; 30; 40]), 2.7)
v[(k-1)]
20

julia> X = ca.MX.sym("X", 3, 3);
julia> X[5], X[end], X[[1, 5]], size(X[2:3])
(X[4], X[8], X[[0, 4]], (2, 1))
julia> try
           X[10]
       catch e
           println(e isa BoundsError)
       end
true
julia> S = ca.MX.sym("S", ca.Sparsity.lower(2));
julia> S[3], ca.nnz(S[3])
(00, 0)
julia> X[ca.Sparsity.lower(3)]
MX(project(X))
julia> k = ca.MX.sym("k"); v = ca.MX.sym("v", 4);
julia> v[k]
MX(v[(k-1)])
julia> ca.Function("f", [v, k], [v[k]])([10, 20, 30, 40], 2.7)
DM(20)

See also
set, get_nz, nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qa

Definition at line 184 of file mx.cpp.

184  {
185  // Fall back on IM
186  get(m, ind1, rr.all(numel(), ind1));
187  }
casadi_int numel() const
Get the number of elements, size1()*size2()

References casadi::Slice::all(), get(), and casadi::GenericMatrix< MX >::numel().

◆ get() [12/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Slice &  rr,
casadi_int  cc 
) const
inline

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 2953 of file mx.hpp.

2953  {
2954  get(m, ind1, rr, Matrix<casadi_int>(cc));
2955  }

◆ get() [13/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Slice &  rr,
const Matrix< casadi_int > &  cc 
) const

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 159 of file mx.cpp.

159  {
160  // Fall back on (IM, IM)
161  get(m, ind1, rr.all(size1(), ind1), cc);
162  }

References casadi::Slice::all(), get(), and casadi::GenericMatrix< MX >::size1().

◆ get() [14/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Slice &  rr,
const MX &  cc 
) const

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 222 of file mx.cpp.

222  {
223  casadi_assert(is_dense(), "Parametric slicing only supported for dense matrices. ");
224  m = (*this)->get_nz_ref(rr.apply(size1()), floor(ind1 ? cc-1 : cc)*size1());
225  }

References casadi::Slice::apply(), casadi::GenericExpression< MX >::floor(), casadi::MXNode::get_nz_ref(), casadi::GenericMatrix< MX >::is_dense(), and casadi::GenericMatrix< MX >::size1().

◆ get() [15/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Slice &  rr,
const Slice &  cc 
) const

Backs two-index subscripting. rr and cc select rows and columns (integer, slice, list, integer DM); the result has shape len(rr)-by-len(cc) and the corresponding part of the sparsity pattern. Out-of-range indices raise an error. An MX index is only allowed for dense expressions and selects at run time.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1], X[1, :].shape, X[[0, 2], [0, 2]].shape
(MX(X[3]), (1, 3), (2, 2))
>>> S = MX.sym("S", Sparsity.lower(3))
>>> S[:, 0].sparsity(), S[0, 2].nnz()
(Sparsity(3x1), 0)
>>> k = MX.sym("k")
>>> X[k, 1]
MX(X[(k;3:6:3)])

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(2, :); c = X([1 3], [1 3]);
>> a, size(b), size(c)
X[3]
1 3
2 2
>> S = MX.sym('S', Sparsity.lower(3));
>> a = S(:, 1); b = S(1, 3);
>> a.sparsity(), b.nnz()
3x1
0
>> k = MX.sym('k');
>> X(k, 2)
X[((k-1);3)]

julia> X = ca.MX.sym("X", 3, 3);
julia> X[1, 2], size(X[2, :]), size(X[[1, 3], [1, 3]])
(X[3], (1, 3), (2, 2))
julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> ca.sparsity(S[:, 1]), ca.nnz(S[1, 3])
(3x1, 0)

See also
set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qb

Definition at line 154 of file mx.cpp.

154  {
155  // Fall back on (IM, IM)
156  get(m, ind1, rr.all(size1(), ind1), cc.all(size2(), ind1));
157  }

References casadi::Slice::all(), get(), casadi::GenericMatrix< MX >::size1(), and casadi::GenericMatrix< MX >::size2().

◆ get() [16/16]

void casadi::MX::get ( MX &  m,
bool  ind1,
const Sparsity &  sp 
) const

Backs single-index subscripting. Elements are addressed in column-major order over all numel() entries, including structural zeros. Indices may be negative (counted from the end); out-of-range indices raise an error. The result is a new GetNonzeros node referencing the selected nonzeros of this expression; a structural zero is returned as an empty-sparsity constant. Accepted index types: integer, slice, list of integers, list of booleans (mask), integer DM, Sparsity pattern of the same shape (returns the projection on that pattern) and MX (a symbolic index into the nonzeros of a dense expression, evaluated at run time with truncation and NaN for out-of-range values).

Parameters
ind1True for 1-based indices (MATLAB), false for 0-based
rrElement indices

>>> X = MX.sym("X", 3, 3)
>>> X[4], X[-1], X[[0, 4]], X[1:3].shape
(MX(X[4]), MX(X[8]), MX(X[:8:4]), (2, 1))
>>> try:
...   X[9]
... except Exception as e:
...   print("Out of bounds" in str(e))
True
>>> S = MX.sym("S", Sparsity.lower(2))
>>> S[2], S[2].nnz()
(MX(00), 0)
>>> X[Sparsity.lower(3)]
MX(project(X))
>>> k = MX.sym("k")
>>> v = MX.sym("v", 4)
>>> v[k], Function("f", [v, k], [v[k]])(DM([10, 20, 30, 40]), 1.7)
(MX(v[k]), DM(20))

>> X = MX.sym('X', 3, 3);
>> a = X(5); b = X(end); c = X([1, 5]); d = X([2; 3]);
>> a, b, c, size(d)
X[4]
X[8]
X[:8:4]
2 1
>> try, X(10); catch e, disp('out of bounds'); end
out of bounds
>> S = MX.sym('S', Sparsity.lower(2));
>> e = S(3);
>> e, e.nnz()
00
0
>> X(Sparsity.lower(3))
project(X)
>> k = MX.sym('k'); v = MX.sym('v', 4);
>> f = Function('f', {v, k}, {v(k)});
>> v(k), f(DM([10; 20; 30; 40]), 2.7)
v[(k-1)]
20

julia> X = ca.MX.sym("X", 3, 3);
julia> X[5], X[end], X[[1, 5]], size(X[2:3])
(X[4], X[8], X[[0, 4]], (2, 1))
julia> try
           X[10]
       catch e
           println(e isa BoundsError)
       end
true
julia> S = ca.MX.sym("S", ca.Sparsity.lower(2));
julia> S[3], ca.nnz(S[3])
(00, 0)
julia> X[ca.Sparsity.lower(3)]
MX(project(X))
julia> k = ca.MX.sym("k"); v = ca.MX.sym("v", 4);
julia> v[k]
MX(v[(k-1)])
julia> ca.Function("f", [v, k], [v[k]])([10, 20, 30, 40], 2.7)
DM(20)

See also
set, get_nz, nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qa

Definition at line 208 of file mx.cpp.

208  {
209  casadi_assert(size()==sp.size(),
210  "get(Sparsity sp): shape mismatch. This matrix has shape "
211  + str(size()) + ", but supplied sparsity index has shape "
212  + str(sp.size()) + ".");
213  m = project(*this, sp);
214  }

References project(), casadi::GenericMatrix< MX >::size(), casadi::Sparsity::size(), and casadi::str().

◆ get_colind()

std::vector<casadi_int> casadi::GenericMatrix< MX >::get_colind ( ) const
inlineinherited

The pattern is stored in compressed column format: colind has size2()+1 entries, the nonzeros of column j are the entries colind(j) up to colind(j+1) (exclusive), and row(el) is the row index of nonzero el. Without argument, the full vectors are returned. Out-of-range indices raise an error.

>>> x = DM(Sparsity.diag(2), [5, 6])
>>> x.row(), x.colind()
([0, 1], [0, 1, 2])
>>> x.row(1), x.colind(2)
(1, 2)

>> x = DM(Sparsity.diag(2), [5; 6]);
>> x.row(), x.colind()
0 1
0 1 2
>> fprintf('%d %d\n', x.row(1), x.colind(2))
1 2

julia> x = ca.DM(ca.Sparsity.diag(2), [5, 6]);
julia> ca.row(x), ca.colind(x)
([0, 1], [0, 1, 2])
julia> ca.row(x, 1), ca.colind(x, 2)
(1, 2)

Extra doc: https://github.com/casadi/casadi/wiki/L_1b8

Definition at line 603 of file generic_matrix.hpp.

603 { return sparsity().get_colind(); }
std::vector< casadi_int > get_colind() const
Column offsets of the compressed column storage.
Definition: sparsity.cpp:366

◆ get_free()

std::vector< MX > casadi::MX::get_free ( const Function &  f)
static

Same as f.free_mx(): the symbolic primitives that occur in the outputs of an MX Function without being an input. Such a Function can only be created with the option "allow_free" and cannot be evaluated until the free variables are bound.

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> f = Function("f", [x], [x + y], {"allow_free": True})
>>> MX.get_free(f), MX.get_free(Function("g", [x], [x]))
([MX(y)], [])
>>> try:
...   Function("f", [x], [x + y])
... except Exception as e:
...   print("variables [y] are free" in str(e))
True

>> x = MX.sym('x'); y = MX.sym('y');
>> f = Function('f', {x}, {x + y}, struct('allow_free', true));
>> v = MX.get_free(f);
>> numel(v), v{1}
1
y
>> numel(MX.get_free(Function('g', {x}, {x})))
0
>> try, Function('f', {x}, {x + y}); catch e, disp('free variables'); end
free variables

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> f = ca.Function("f", [x], [x + y], Dict("allow_free" => true));
julia> ca.MX.get_free(f), ca.MX.get_free(ca.Function("g", [x], [x]))
(MX[y], MX[])
julia> try
           ca.Function("f", [x], [x + y])
       catch e
           println(occursin("variables [y] are free", sprint(showerror, e)))
       end
true

See also
Function.free_mx, symvar

Extra doc: https://github.com/casadi/casadi/wiki/L_rm

Definition at line 3199 of file mx.cpp.

3199  {
3200  return f.free_mx();
3201  }

References casadi::Function::free_mx().

◆ get_input()

std::vector< MX > casadi::MX::get_input ( const Function &  f)
static

Same as f.mx_in(). For an MX Function these are the original input expressions; for other Functions fresh symbols with the input names and sparsities.

>>> x = MX.sym("x")
>>> f = Function("f", [x], [2*x])
>>> MX.get_input(f), is_equal(MX.get_input(f)[0], x)
([MX(x)], True)

>> x = MX.sym('x');
>> f = Function('f', {x}, {2*x});
>> v = MX.get_input(f);
>> numel(v), v{1}, is_equal(v{1}, x)
1
x
1

julia> x = ca.MX.sym("x");
julia> f = ca.Function("f", [x], [2 * x]);
julia> ca.MX.get_input(f), ca.is_equal(ca.MX.get_input(f)[1], x)
(MX[x], true)

See also
Function.mx_in, get_free

Extra doc: https://github.com/casadi/casadi/wiki/L_rl

Definition at line 3195 of file mx.cpp.

3195  {
3196  return f.mx_in();
3197  }

References casadi::Function::mx_in().

◆ get_max_depth()

casadi_int casadi::MX::get_max_depth ( )
static
See also
set_max_depth

Extra doc: https://github.com/casadi/casadi/wiki/L_rk

Definition at line 945 of file mx.cpp.

945  {
946  return eq_depth_;
947  }

Referenced by is_doubled(), and casadi::MXNode::maxDepth().

◆ get_nonzeros()

std::vector< MX > casadi::MX::get_nonzeros ( ) const

Since an MX is not a container, each entry is an expression that selects one nonzero of this expression. When the expression satisfies is_valid_input, the entries are the scalar primitives themselves: for vertcat(x, y) with scalar symbols x and y the result is [x, y]. The list has nnz() entries, in column-major order.

See also
x.nz[:], primitives

Extra doc: https://github.com/casadi/casadi/wiki/L_2bh

Definition at line 633 of file mx.cpp.

633  {
634  std::vector<MX> ret;
635  std::vector<MX> p = primitives();
636  for (const MX& e : p) {
637  if (e.is_scalar()) {
638  ret.push_back(e);
639  } else {
640  // Get nonzeros sparsity cast
641  MX nz;
642  e.get_nz(nz, false, Slice());
643  for (casadi_int i=0; i<nz.nnz(); ++i) {
644  ret.push_back(nz(i));
645  }
646  }
647  }
648  return ret;
649  }
const MX nz(const K &k) const
Get vector nonzero or slice of nonzeros.
std::vector< MX > primitives() const
Get the symbolic primitives of a valid Function input.
Definition: mx.cpp:965

References get_nz(), casadi::GenericMatrix< MatType >::nnz(), casadi::GenericMatrix< MX >::nz(), and primitives().

◆ get_nz() [1/7]

void casadi::MX::get_nz ( MX &  m,
bool  ind1,
casadi_int  kk 
) const
inline

Indexes the nnz() nonzeros directly, skipping structural zeros, in column-major order. Negative indices count from the end; out-of-range indices raise an error. An MX index (or an inner/outer pair of indices) creates a parametric lookup that is resolved at evaluation time; such a node has no derivative with respect to the index. For dense expressions x[k] and x.nz[k] coincide.

>>> S = MX.sym("S", Sparsity.lower(3))
>>> S.nz[1], S.nz[:].shape, len(S.nz)
(MX(S[1]), (6, 1), 6)
>>> k = MX.sym("k")
>>> S.nz[k]
MX(S[k])
>>> MX.sym("x", 2, 2).nz[[]].shape
(0, 1)

>> S = MX.sym('S', Sparsity.lower(3));
>> a = S.get_nz(true, 2); b = S.get_nz(true, Slice());
>> a, size(b), S.nnz()
S[1]
6 1
6
>> k = MX.sym('k');
>> S.get_nz(true, k)
S[(k-1)]
>> size(MX.sym('x', 2, 2).get_nz(true, []))
0 0

julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> S.nz[2], size(S.nz[:]), length(S.nz)
(S[1], (6, 1), 6)
julia> k = ca.MX.sym("k");
julia> S.nz[k]
MX(S[(k-1)])
julia> size(ca.MX.sym("x", 2, 2).nz[Int[]])
(0, 1)

See also
set_nz, get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qe

Definition at line 3175 of file mx.hpp.

3175  {
3176  get_nz(m, ind1, Matrix<casadi_int>(kk));
3177  }

◆ get_nz() [2/7]

void casadi::MX::get_nz ( MX &  m,
bool  ind1,
const Matrix< casadi_int > &  kk 
) const

Indexes the nnz() nonzeros directly, skipping structural zeros, in column-major order. Negative indices count from the end; out-of-range indices raise an error. An MX index (or an inner/outer pair of indices) creates a parametric lookup that is resolved at evaluation time; such a node has no derivative with respect to the index. For dense expressions x[k] and x.nz[k] coincide.

>>> S = MX.sym("S", Sparsity.lower(3))
>>> S.nz[1], S.nz[:].shape, len(S.nz)
(MX(S[1]), (6, 1), 6)
>>> k = MX.sym("k")
>>> S.nz[k]
MX(S[k])
>>> MX.sym("x", 2, 2).nz[[]].shape
(0, 1)

>> S = MX.sym('S', Sparsity.lower(3));
>> a = S.get_nz(true, 2); b = S.get_nz(true, Slice());
>> a, size(b), S.nnz()
S[1]
6 1
6
>> k = MX.sym('k');
>> S.get_nz(true, k)
S[(k-1)]
>> size(MX.sym('x', 2, 2).get_nz(true, []))
0 0

julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> S.nz[2], size(S.nz[:]), length(S.nz)
(S[1], (6, 1), 6)
julia> k = ca.MX.sym("k");
julia> S.nz[k]
MX(S[(k-1)])
julia> size(ca.MX.sym("x", 2, 2).nz[Int[]])
(0, 1)

See also
set_nz, get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qe

Definition at line 411 of file mx.cpp.

411  {
412  // If indexed matrix was a row/column vector, make sure that the result is too
413  bool tr = (is_column() && kk.is_row()) || (is_row() && kk.is_column());
414 
415  // Quick return if no entries
416  if (kk.nnz()==0) {
417  m = MX::zeros(tr ? kk.sparsity().T() : kk.sparsity());
418  return;
419  }
420 
421  // Check bounds
422  casadi_int sz = nnz();
423  casadi_assert_in_range(kk.nonzeros(), -sz+ind1, sz+ind1);
424 
425  // Handle index-1, negative indices
426  if (ind1 || *std::min_element(kk->begin(), kk->end())<0) {
427  Matrix<casadi_int> kk_mod = kk;
428  for (auto&& i : kk_mod.nonzeros()) {
429  casadi_assert(!(ind1 && i<=0),
430  "Matlab is 1-based, but requested index " + str(i) + ". "
431  "Note that negative slices are disabled in the Matlab interface. "
432  "Possibly you may want to use 'end'.");
433  if (ind1) i--;
434  if (i<0) i += sz;
435  }
436  get_nz(m, false, kk_mod); // Call recursively
437  return;
438  }
439 
440  // Return reference to the nonzeros
441  m = (*this)->get_nzref(tr ? kk.sparsity().T() : kk.sparsity(), kk.nonzeros());
442  }

References get_nz(), casadi::MXNode::get_nzref(), casadi::GenericMatrix< MatType >::is_column(), casadi::GenericMatrix< MX >::is_column(), casadi::GenericMatrix< MX >::is_row(), casadi::GenericMatrix< MatType >::is_row(), casadi::GenericMatrix< MX >::nnz(), casadi::GenericMatrix< MatType >::nnz(), casadi::Matrix< Scalar >::nonzeros(), casadi::Matrix< Scalar >::sparsity(), casadi::str(), casadi::Sparsity::T(), and casadi::GenericMatrix< MX >::zeros().

◆ get_nz() [3/7]

void casadi::MX::get_nz ( MX &  m,
bool  ind1,
const MX &  inner,
const MX &  outer 
) const

Indexes the nnz() nonzeros directly, skipping structural zeros, in column-major order. Negative indices count from the end; out-of-range indices raise an error. An MX index (or an inner/outer pair of indices) creates a parametric lookup that is resolved at evaluation time; such a node has no derivative with respect to the index. For dense expressions x[k] and x.nz[k] coincide.

>>> S = MX.sym("S", Sparsity.lower(3))
>>> S.nz[1], S.nz[:].shape, len(S.nz)
(MX(S[1]), (6, 1), 6)
>>> k = MX.sym("k")
>>> S.nz[k]
MX(S[k])
>>> MX.sym("x", 2, 2).nz[[]].shape
(0, 1)

>> S = MX.sym('S', Sparsity.lower(3));
>> a = S.get_nz(true, 2); b = S.get_nz(true, Slice());
>> a, size(b), S.nnz()
S[1]
6 1
6
>> k = MX.sym('k');
>> S.get_nz(true, k)
S[(k-1)]
>> size(MX.sym('x', 2, 2).get_nz(true, []))
0 0

julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> S.nz[2], size(S.nz[:]), length(S.nz)
(S[1], (6, 1), 6)
julia> k = ca.MX.sym("k");
julia> S.nz[k]
MX(S[(k-1)])
julia> size(ca.MX.sym("x", 2, 2).nz[Int[]])
(0, 1)

See also
set_nz, get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qe

Definition at line 449 of file mx.cpp.

449  {
450  // Create return MX
451  m = (*this)->get_nz_ref(ind1 ? inner-1.0: inner, ind1 ? outer-1.0: outer);
452  }

References casadi::MXNode::get_nz_ref().

◆ get_nz() [4/7]

void casadi::MX::get_nz ( MX &  m,
bool  ind1,
const MX &  inner,
const Slice &  outer 
) const

Indexes the nnz() nonzeros directly, skipping structural zeros, in column-major order. Negative indices count from the end; out-of-range indices raise an error. An MX index (or an inner/outer pair of indices) creates a parametric lookup that is resolved at evaluation time; such a node has no derivative with respect to the index. For dense expressions x[k] and x.nz[k] coincide.

>>> S = MX.sym("S", Sparsity.lower(3))
>>> S.nz[1], S.nz[:].shape, len(S.nz)
(MX(S[1]), (6, 1), 6)
>>> k = MX.sym("k")
>>> S.nz[k]
MX(S[k])
>>> MX.sym("x", 2, 2).nz[[]].shape
(0, 1)

>> S = MX.sym('S', Sparsity.lower(3));
>> a = S.get_nz(true, 2); b = S.get_nz(true, Slice());
>> a, size(b), S.nnz()
S[1]
6 1
6
>> k = MX.sym('k');
>> S.get_nz(true, k)
S[(k-1)]
>> size(MX.sym('x', 2, 2).get_nz(true, []))
0 0

julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> S.nz[2], size(S.nz[:]), length(S.nz)
(S[1], (6, 1), 6)
julia> k = ca.MX.sym("k");
julia> S.nz[k]
MX(S[(k-1)])
julia> size(ca.MX.sym("x", 2, 2).nz[Int[]])
(0, 1)

See also
set_nz, get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qe

Definition at line 459 of file mx.cpp.

459  {
460  // Create return MX
461  m = (*this)->get_nz_ref(ind1 ? inner-1.0: inner, ind1 ? outer-1: outer);
462  }

References casadi::MXNode::get_nz_ref().

◆ get_nz() [5/7]

void casadi::MX::get_nz ( MX &  m,
bool  ind1,
const MX &  kk 
) const

Indexes the nnz() nonzeros directly, skipping structural zeros, in column-major order. Negative indices count from the end; out-of-range indices raise an error. An MX index (or an inner/outer pair of indices) creates a parametric lookup that is resolved at evaluation time; such a node has no derivative with respect to the index. For dense expressions x[k] and x.nz[k] coincide.

>>> S = MX.sym("S", Sparsity.lower(3))
>>> S.nz[1], S.nz[:].shape, len(S.nz)
(MX(S[1]), (6, 1), 6)
>>> k = MX.sym("k")
>>> S.nz[k]
MX(S[k])
>>> MX.sym("x", 2, 2).nz[[]].shape
(0, 1)

>> S = MX.sym('S', Sparsity.lower(3));
>> a = S.get_nz(true, 2); b = S.get_nz(true, Slice());
>> a, size(b), S.nnz()
S[1]
6 1
6
>> k = MX.sym('k');
>> S.get_nz(true, k)
S[(k-1)]
>> size(MX.sym('x', 2, 2).get_nz(true, []))
0 0

julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> S.nz[2], size(S.nz[:]), length(S.nz)
(S[1], (6, 1), 6)
julia> k = ca.MX.sym("k");
julia> S.nz[k]
MX(S[(k-1)])
julia> size(ca.MX.sym("x", 2, 2).nz[Int[]])
(0, 1)

See also
set_nz, get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qe

Definition at line 444 of file mx.cpp.

444  {
445  // Create return MX
446  m = (*this)->get_nz_ref(ind1 ? kk-1.0 : kk);
447  }

References casadi::MXNode::get_nz_ref().

◆ get_nz() [6/7]

void casadi::MX::get_nz ( MX &  m,
bool  ind1,
const Slice &  inner,
const MX &  outer 
) const

Indexes the nnz() nonzeros directly, skipping structural zeros, in column-major order. Negative indices count from the end; out-of-range indices raise an error. An MX index (or an inner/outer pair of indices) creates a parametric lookup that is resolved at evaluation time; such a node has no derivative with respect to the index. For dense expressions x[k] and x.nz[k] coincide.

>>> S = MX.sym("S", Sparsity.lower(3))
>>> S.nz[1], S.nz[:].shape, len(S.nz)
(MX(S[1]), (6, 1), 6)
>>> k = MX.sym("k")
>>> S.nz[k]
MX(S[k])
>>> MX.sym("x", 2, 2).nz[[]].shape
(0, 1)

>> S = MX.sym('S', Sparsity.lower(3));
>> a = S.get_nz(true, 2); b = S.get_nz(true, Slice());
>> a, size(b), S.nnz()
S[1]
6 1
6
>> k = MX.sym('k');
>> S.get_nz(true, k)
S[(k-1)]
>> size(MX.sym('x', 2, 2).get_nz(true, []))
0 0

julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> S.nz[2], size(S.nz[:]), length(S.nz)
(S[1], (6, 1), 6)
julia> k = ca.MX.sym("k");
julia> S.nz[k]
MX(S[(k-1)])
julia> size(ca.MX.sym("x", 2, 2).nz[Int[]])
(0, 1)

See also
set_nz, get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qe

Definition at line 454 of file mx.cpp.

454  {
455  // Create return MX
456  m = (*this)->get_nz_ref(ind1 ? inner-1: inner, ind1 ? outer-1.0: outer);
457  }

References casadi::MXNode::get_nz_ref().

◆ get_nz() [7/7]

void casadi::MX::get_nz ( MX &  m,
bool  ind1,
const Slice &  kk 
) const

Indexes the nnz() nonzeros directly, skipping structural zeros, in column-major order. Negative indices count from the end; out-of-range indices raise an error. An MX index (or an inner/outer pair of indices) creates a parametric lookup that is resolved at evaluation time; such a node has no derivative with respect to the index. For dense expressions x[k] and x.nz[k] coincide.

>>> S = MX.sym("S", Sparsity.lower(3))
>>> S.nz[1], S.nz[:].shape, len(S.nz)
(MX(S[1]), (6, 1), 6)
>>> k = MX.sym("k")
>>> S.nz[k]
MX(S[k])
>>> MX.sym("x", 2, 2).nz[[]].shape
(0, 1)

>> S = MX.sym('S', Sparsity.lower(3));
>> a = S.get_nz(true, 2); b = S.get_nz(true, Slice());
>> a, size(b), S.nnz()
S[1]
6 1
6
>> k = MX.sym('k');
>> S.get_nz(true, k)
S[(k-1)]
>> size(MX.sym('x', 2, 2).get_nz(true, []))
0 0

julia> S = ca.MX.sym("S", ca.Sparsity.lower(3));
julia> S.nz[2], size(S.nz[:]), length(S.nz)
(S[1], (6, 1), 6)
julia> k = ca.MX.sym("k");
julia> S.nz[k]
MX(S[(k-1)])
julia> size(ca.MX.sym("x", 2, 2).nz[Int[]])
(0, 1)

See also
set_nz, get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qe

Definition at line 406 of file mx.cpp.

406  {
407  // Fallback on IM
408  get_nz(m, ind1, kk.all(nnz(), ind1));
409  }

References casadi::Slice::all(), and casadi::GenericMatrix< MX >::nnz().

Referenced by get(), casadi::get_boor(), get_nonzeros(), get_nz(), casadi::interpn_G(), and interpn_linear().

◆ get_output()

MX casadi::MX::get_output ( casadi_int  oind) const

For a multiple-output node (a Function call), returns the OutputNode selecting output oind. For any other node only oind == 0 is valid and the node itself is returned.

>>> a = SX.sym("a")
>>> f = Function("f", [a], [a + 1, 2*a])
>>> x = MX.sym("x")
>>> r0, r1 = f(x, )
>>> call = r0.dep(0)
>>> call.get_output(1), is_equal(call.get_output(0), r0)
(MX(f(x){1}), True)
>>> x.get_output(0)
MX(x)

>> a = SX.sym('a');
>> f = Function('f', {a}, {a + 1, 2*a});
>> x = MX.sym('x');
>> [r0, r1] = f(x);
>> call = r0.dep(0);
>> call.get_output(1), is_equal(call.get_output(0), r0)
f(x){1}
1
>> x.get_output(0)
x

julia> a = ca.SX.sym("a");
julia> f = ca.Function("f", [a], [a + 1, 2 * a]);
julia> x = ca.MX.sym("x");
julia> r0, r1 = f(x);
julia> call = ca.dep(r0, 0);
julia> ca.get_output(call, 1), ca.is_equal(ca.get_output(call, 0), r0)
(f(x){1}, true)
julia> ca.get_output(x, 0)
MX(x)

See also
n_out, which_output

Extra doc: https://github.com/casadi/casadi/wiki/L_ql

Definition at line 905 of file mx.cpp.

905  {
906  return (*this)->get_output(oind);
907  }

References casadi::MXNode::get_output().

Referenced by createMultipleOutput(), cse(), and graph_substitute().

◆ get_row()

std::vector<casadi_int> casadi::GenericMatrix< MX >::get_row ( ) const
inlineinherited

The pattern is stored in compressed column format: colind has size2()+1 entries, the nonzeros of column j are the entries colind(j) up to colind(j+1) (exclusive), and row(el) is the row index of nonzero el. Without argument, the full vectors are returned. Out-of-range indices raise an error.

>>> x = DM(Sparsity.diag(2), [5, 6])
>>> x.row(), x.colind()
([0, 1], [0, 1, 2])
>>> x.row(1), x.colind(2)
(1, 2)

>> x = DM(Sparsity.diag(2), [5; 6]);
>> x.row(), x.colind()
0 1
0 1 2
>> fprintf('%d %d\n', x.row(1), x.colind(2))
1 2

julia> x = ca.DM(ca.Sparsity.diag(2), [5, 6]);
julia> ca.row(x), ca.colind(x)
([0, 1], [0, 1, 2])
julia> ca.row(x, 1), ca.colind(x, 2)
(1, 2)

Extra doc: https://github.com/casadi/casadi/wiki/L_1b8

Definition at line 602 of file generic_matrix.hpp.

602 { return sparsity().get_row(); }
std::vector< casadi_int > get_row() const
Row index of every nonzero, in nonzero (column-major) order.
Definition: sparsity.cpp:374

◆ get_sparsity()

Sparsity casadi::MX::get_sparsity ( ) const
inline

Extra doc: https://github.com/casadi/casadi/wiki/L_qd

Definition at line 623 of file mx.hpp.

623 { return sparsity();}

◆ get_str()

std::string casadi::SharedObject::get_str ( bool  more = false) const
inlineinherited

Definition at line 91 of file shared_object.hpp.

91  {
92  std::stringstream ss;
93  disp(ss, more);
94  return ss.str();
95  }
void disp(std::ostream &stream, bool more=false) const
Print a description of the object.

◆ get_temp()

casadi_int casadi::MX::get_temp ( ) const

Get the temporary variable

Definition at line 893 of file mx.cpp.

893  {
894  return (*this)->temp;
895  }

◆ getCount()

casadi_int casadi::GenericShared< SharedObject , SharedObjectInternal >::getCount
inherited

Definition at line 102 of file generic_shared_impl.hpp.

138  {
139  return (*this)->getCount();
140  }

◆ gradient()

static MX casadi::GenericMatrix< MX >::gradient ( const MX &  ex,
const MX &  arg,
const Dict &  opts = Dict() 
)
staticinherited

Functions called by friend functions defined here

◆ graph_substitute() [1/4]

MX casadi::MX::graph_substitute ( const MX &  x,
const std::vector< MX > &  v,
const std::vector< MX > &  vdef 
)
static

Functions called by friend functions defined for this class

Definition at line 1544 of file mx.cpp.

1545  {
1546  return graph_substitute(std::vector<MX>{x}, v, vdef).at(0);
1547  }

Referenced by cse(), graph_substitute(), and matrix_expand().

◆ graph_substitute() [2/4]

MX casadi::MX::graph_substitute ( const MX &  x,
const std::vector< MX > &  v,
const std::vector< MX > &  vdef,
bool &  updated 
)
static

Functions called by friend functions defined for this class

Definition at line 1549 of file mx.cpp.

1550  {
1551  return graph_substitute(std::vector<MX>{x}, v, vdef, updated).at(0);
1552  }

References graph_substitute().

◆ graph_substitute() [3/4]

std::vector< MX > casadi::MX::graph_substitute ( const std::vector< MX > &  ex,
const std::vector< MX > &  v,
const std::vector< MX > &  vdef 
)
static

Functions called by friend functions defined for this class

Definition at line 1554 of file mx.cpp.

1556  {
1557  bool updated;
1558  return graph_substitute(ex, v, vdef, updated);
1559  }

References graph_substitute().

◆ graph_substitute() [4/4]

std::vector< MX > casadi::MX::graph_substitute ( const std::vector< MX > &  ex,
const std::vector< MX > &  v,
const std::vector< MX > &  vdef,
bool &  updated 
)
static

Functions called by friend functions defined for this class

Definition at line 1560 of file mx.cpp.

1563  {
1564  casadi_assert(v.size()==vdef.size(),
1565  "Mismatch in the number of expression to substitute: "
1566  + str(v.size()) + " <-> " + str(vdef.size()) + ".");
1567 
1568  updated = false;
1569 
1570  // Quick return if all equal
1571  bool all_equal = true;
1572  for (casadi_int k=0; k<v.size(); ++k) {
1573  if (v[k].size()!=vdef[k].size() || !is_equal(v[k], vdef[k])) {
1574  all_equal = false;
1575  break;
1576  }
1577  }
1578  if (all_equal) return ex;
1579 
1580  // Validate dimensions
1581  for (casadi_int i=0;i<v.size();++i) {
1582  casadi_assert(v[i].size()==vdef[i].size(),
1583  "Inconsistent shapes for i = " + str(i) + ": v[i] " + v[i].dim() +
1584  " <-> vdef[i] " + vdef[i].dim());
1585  }
1586 
1587  // Sort the expression
1588  Dict opts({{"max_io", 0}, {"allow_free", true}});
1589  Function f("tmp_graph_substitute", std::vector<MX>{}, ex, opts);
1590  MXFunction *ff = f.get<MXFunction>();
1591 
1592  // Get references to the internal data structures
1593  const std::vector<MXAlgEl>& algorithm = ff->algorithm_;
1594  std::vector<MX> swork(ff->workloc_.size()-1);
1595 
1596  // A boolean vector indicated whoch nodes are tainted by substitutions
1597  std::vector<bool> tainted(swork.size());
1598 
1599  // Construct lookup table for expressions,
1600  // giving priority to first occurances
1601  std::map<const MXNode*, casadi_int> expr_lookup;
1602  for (casadi_int i=0;i<v.size();++i) {
1603  auto it = expr_lookup.find(v[i].operator->());
1604  if (it==expr_lookup.end()) expr_lookup[v[i].operator->()] = i;
1605  }
1606 
1607  // Construct found map
1608  std::vector<bool> expr_found(v.size(), false);
1609 
1610  // Allocate output vector
1611  std::vector<MX> f_out(f.n_out());
1612  std::vector<MX> oarg, ores;
1613 
1614  // expr_lookup iterator
1615  std::map<const MXNode*, casadi_int>::const_iterator it_lookup;
1616 
1617  // Allocate storage for split outputs
1618  std::vector<std::vector<MX>> out_split(ex.size());
1619  for (casadi_int i = 0; i < out_split.size(); ++i) out_split[i].resize(ex[i].n_primitives());
1620 
1621  for (auto it=algorithm.begin(); it!=algorithm.end(); ++it) {
1622 
1623  if (it->op != OP_OUTPUT) {
1624  // Check if it->data points to a supplied expr
1625  it_lookup = expr_lookup.find((it->data).operator->());
1626 
1627  if (it_lookup!=expr_lookup.end()) {
1628  // Fill in that expression in-place
1629  MX e = vdef[it_lookup->second];
1630 
1631  // If node is of a MultipleOutput type
1632  if (e->has_output()) {
1633  for (casadi_int i=0;i<it->res.size();++i) {
1634  casadi_int k = it->res[i];
1635  if (k!=-1) {
1636  swork[k] = e.get_output(i);
1637  tainted[k] = true;
1638  }
1639  }
1640  } else {
1641  swork[it->res.front()] = e;
1642  tainted[it->res.front()] = true;
1643  }
1644  expr_found[it_lookup->second] = true;
1645  continue;
1646  } else if (it->data->has_output()) {
1647  bool any_tainted = false;
1648  // Loop over all oputputs of MultiOutput
1649  for (casadi_int i=0;i<it->res.size();++i) {
1650  // Create Output node (cached)
1651  casadi_int k = it->res[i];
1652  if (k!=-1) {
1653  MX out = it->data.get_output(i);
1654  // Check if out points to a supplied expr
1655  it_lookup = expr_lookup.find(out.operator->());
1656  if (it_lookup!=expr_lookup.end()) {
1657  // Fill in that expression in-place
1658  MX e = vdef[it_lookup->second];
1659  swork[k] = e;
1660  tainted[k] = true;
1661  any_tainted = true;
1662  expr_found[it_lookup->second] = true;
1663  }
1664  }
1665  }
1666  if (any_tainted) continue;
1667  }
1668  }
1669 
1670  switch (it->op) {
1671  case OP_INPUT:
1672  tainted[it->res.front()] = false;
1673  break;
1674  case OP_PARAMETER:
1675  swork[it->res.front()] = it->data;
1676  tainted[it->res.front()] = false;
1677  break;
1678  case OP_OUTPUT:
1679  out_split.at(it->data->ind()).at(it->data->segment()) = swork[it->arg.front()];
1680  break;
1681  default:
1682  {
1683  bool node_tainted = false;
1684 
1685  // Arguments of the operation
1686  oarg.resize(it->arg.size());
1687  for (casadi_int i=0; i<oarg.size(); ++i) {
1688  casadi_int el = it->arg[i];
1689  if (el>=0) node_tainted = node_tainted || tainted[el];
1690  oarg[i] = el<0 ? MX(it->data->dep(i).size()) : swork.at(el);
1691  }
1692 
1693  // Perform the operation
1694  ores.resize(it->res.size());
1695  if (!node_tainted) {
1696  if (it->data.has_output()) {
1697  for (casadi_int i=0;i<it->res.size();++i) {
1698  ores.at(i) = it->data.get_output(i);
1699  }
1700  } else {
1701  ores.at(0) = it->data;
1702  }
1703  } else {
1704  it->data->eval_mx(oarg, ores);
1705  }
1706 
1707  // Get the result
1708  for (casadi_int i=0; i<ores.size(); ++i) {
1709  casadi_int el = it->res[i];
1710  if (el>=0) swork.at(el) = ores[i];
1711  if (el>=0) tainted[el] = node_tainted;
1712  }
1713  }
1714  }
1715  }
1716 
1717  // Join primitives
1718  for (size_t k = 0; k < out_split.size(); ++k) {
1719  f_out[k] = ex[k].join_primitives(out_split.at(k));
1720  }
1721 
1722  bool all_found=true;
1723  for (casadi_int i=0;i<v.size();++i) {
1724  all_found = all_found && expr_found[i];
1725  }
1726 
1727  updated = any(expr_found);
1728 
1729  return f_out;
1730 
1731  }
static bool is_equal(const MX &x, const MX &y, casadi_int depth=0)
Definition: mx.cpp:870
bool any(const std::vector< bool > &v)
Check if any arguments are true.
Definition: casadi_misc.cpp:88

References casadi::MXFunction::algorithm_, casadi::any(), casadi::GenericMatrix< MX >::dim(), find(), get_output(), casadi::MXNode::get_output(), casadi::MXNode::has_output(), is_equal(), MX(), n_primitives(), casadi::OP_INPUT, casadi::OP_OUTPUT, casadi::OP_PARAMETER, casadi::GenericMatrix< MX >::size(), and casadi::str().

◆ has_duplicates()

bool casadi::MX::has_duplicates ( ) const

If a symbolic primitive appears more than once in this expression (a valid Function input), returns true and warns with the name of the duplicate. Only defined for valid inputs; other nodes raise an error. Note: marks the visited primitives using MX::set_temp; call reset_input() afterwards.

>>> x = MX.sym("x", 2)
>>> vertcat(x, x).has_duplicates()
True
>>> vertcat(x, x).reset_input()
>>> vertcat(x, MX.sym("y")).has_duplicates()
False

>> x = MX.sym('x', 2);
>> vertcat(x, x).has_duplicates()
...
1
>> vertcat(x, x).reset_input();
>> vertcat(x, MX.sym('y')).has_duplicates()
0

julia> x = ca.MX.sym("x", 2);
julia> ca.has_duplicates([x; x])
true
julia> ca.reset_input([x; x])
julia> ca.has_duplicates([x; ca.MX.sym("y")])
false

See also
reset_input, is_valid_input

Extra doc: https://github.com/casadi/casadi/wiki/L_qs

Definition at line 1021 of file mx.cpp.

1021  {
1022  return (*this)->has_duplicates();
1023  }

◆ has_output()

bool casadi::MX::has_output ( ) const

True for the call node of a Function with several outputs. Such a node cannot be used directly in expressions; select an output with get_output.

>>> a = SX.sym("a")
>>> f = Function("f", [a], [a + 1, 2*a])
>>> x = MX.sym("x")
>>> r0, r1 = f(x, )
>>> r0.dep(0).has_output(), r0.has_output(), x.has_output()
(True, False, False)

>> a = SX.sym('a');
>> f = Function('f', {a}, {a + 1, 2*a});
>> x = MX.sym('x');
>> [r0, r1] = f(x);
>> call = r0.dep(0);
>> call.has_output(), r0.has_output(), x.has_output()
1
0
0

julia> a = ca.SX.sym("a");
julia> f = ca.Function("f", [a], [a + 1, 2 * a]);
julia> x = ca.MX.sym("x");
julia> r0, r1 = f(x);
julia> ca.has_output(ca.dep(r0, 0)), ca.has_output(r0), ca.has_output(x)
(true, false, false)

See also
n_out, get_output, is_output

Extra doc: https://github.com/casadi/casadi/wiki/L_284

Definition at line 818 of file mx.cpp.

818  {
819  return (*this)->has_output();
820  }

◆ hessian() [1/2]

MX casadi::MX::hessian ( const MX &  f,
const MX &  x,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1925 of file mx.cpp.

1925  {
1926  MX g;
1927  return hessian(f, x, g, opts);
1928  }
static MX hessian(const MX &f, const MX &x, const Dict &opts=Dict())
Definition: mx.cpp:1925

◆ hessian() [2/2]

MX casadi::MX::hessian ( const MX &  f,
const MX &  x,
MX &  g,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1930 of file mx.cpp.

1930  {
1931  try {
1932  Dict all_opts = opts;
1933  g = gradient(f, x, opts);
1934  if (!opts.count("symmetric")) all_opts["symmetric"] = true;
1935  return jacobian(g, x, all_opts);
1936  } catch (std::exception& e) {
1937  CASADI_THROW_ERROR("hessian", e.what());
1938  }
1939  }
static MX jacobian(const MX &f, const MX &x, const Dict &opts=Dict())
Definition: mx.cpp:1913
friend MX gradient(const MX &ex, const MX &arg, const Dict &opts=Dict())
Calculate the gradient of an expression.

References casadi::GenericMatrix< MX >::gradient, and jacobian().

◆ horzcat()

MX casadi::MX::horzcat ( const std::vector< MX > &  x)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1122 of file mx.cpp.

1122  {
1123  // Check dimensions
1124  if (x.size()>1) {
1125  std::vector<MX> ne = trim_empty(x, true);
1126  for (casadi_int i=0;i<ne.size();i++) {
1127  casadi_assert(ne[i].size1()==ne[0].size1(),
1128  "horzcat dimension mismatch x[" + str(i) + "]:" + ne[i].dim() +
1129  " and x[0]: " + ne[0].dim() + ".");
1130  }
1131  }
1132 
1133  if (x.empty()) {
1134  return MX(1, 0);
1135  } else if (x.size()==1) {
1136  return x.front();
1137  } else if (has_empty(x)) {
1138  std::vector<MX> ret = trim_empty(x);
1139  if (ret.empty()) {
1140  // We still want horzcat(zeros(0,5),zeros(0,5)) -> zeros(0,10)
1141  ret = trim_empty(x, true);
1142  casadi_int s = 0;
1143  casadi_int nrow = 0;
1144  for (casadi_int i=0;i<ret.size();++i) {
1145  s+= ret[i].size2();
1146  casadi_assert_dev(nrow==0 || nrow==ret[i].size1());
1147  nrow = ret[i].size1();
1148  }
1149  return MX::zeros(nrow, s);
1150  } else {
1151  return horzcat(ret);
1152  }
1153  } else {
1154  return x.front()->get_horzcat(x);
1155  }
1156  }
static MX ne(const MX &x, const MX &y)
Logical not equal to: (x,y) -> x != y.

References casadi::GenericMatrix< MX >::dim(), casadi::has_empty(), MX(), casadi::GenericExpression< MX >::ne(), casadi::GenericMatrix< MatType >::size(), casadi::GenericMatrix< MX >::size1(), casadi::str(), casadi::trim_empty(), and casadi::GenericMatrix< MX >::zeros().

Referenced by blockcat(), and vertcat().

◆ horzsplit()

std::vector< MX > casadi::MX::horzsplit ( const MX &  x,
const std::vector< casadi_int > &  offset 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1209 of file mx.cpp.

1209  {
1210  // Consistency check
1211  check_offset(offset, x.size2(), "horzsplit");
1212 
1213  // Trivial return if possible
1214  if (offset.size()==1) {
1215  return std::vector<MX>(0);
1216  } else if (offset.size()==2) {
1217  return std::vector<MX>(1, x);
1218  } else {
1219  return x->get_horzsplit(offset);
1220  }
1221  }
static std::vector< casadi_int > offset(const std::vector< MatType > &v, bool vert=true)

References casadi::check_offset(), casadi::MXNode::get_horzsplit(), casadi::SparsityInterface< MatType >::offset(), and casadi::GenericMatrix< MatType >::size2().

Referenced by vertsplit().

◆ if_else()

MX casadi::MX::if_else ( const MX &  cond,
const MX &  if_true,
const MX &  if_false,
bool  short_circuit = false 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1364 of file mx.cpp.

1364  {
1365  if (short_circuit) {
1366  // Get symbolic primitives
1367  std::vector<MX> arg = symvar(veccat(std::vector<MX>{x_true, x_false}));
1368 
1369  // Form functions for cases
1370  Function f_true("f_true", arg, {x_true});
1371  Function f_false("f_false", arg, {x_false});
1372 
1373  // Form Switch
1374  Function sw = Function::if_else("switch", f_true, f_false);
1375 
1376  // Call the Switch
1377  std::vector<MX> sw_arg;
1378  sw_arg.push_back(cond);
1379  sw_arg.insert(sw_arg.end(), arg.begin(), arg.end());
1380  return sw(sw_arg).at(0);
1381  } else {
1382  return if_else_zero(cond, x_true) + if_else_zero(!cond, x_false);
1383  }
1384  }
static Function if_else(const std::string &name, const Function &f_true, const Function &f_false, const Dict &opts=Dict())
Create a function that evaluates f_true or f_false depending on.
Definition: function.cpp:962
static MX if_else_zero(const MX &x, const MX &y)
Conditional assignment: (x,y) -> x ? y : 0.

References casadi::Function::if_else(), casadi::GenericExpression< MX >::if_else_zero(), symvar(), and casadi::SparsityInterface< MatType >::veccat().

Referenced by conditional().

◆ inf() [1/3]

MX casadi::MX::inf ( casadi_int  nrow = 1,
casadi_int  ncol = 1 
)
static

Dense nrow-by-ncol (default 1-by-1), or with the given sparsity pattern.

>>> MX.inf(), MX.inf(2, 1), MX.inf(Sparsity.lower(2))
(MX(inf), MX(inf(2x1)), MX(inf(2x2,3nz)))

>> MX.inf(), MX.inf(2, 1), MX.inf(Sparsity.lower(2))
inf
inf(2x1)
inf(2x2,3nz)

julia> ca.MX.inf(), ca.MX.inf(2, 1), ca.MX.inf(ca.Sparsity.lower(2))
(inf, inf(2x1), inf(2x2,3nz))

See also
is_inf, nan

Extra doc: https://github.com/casadi/casadi/wiki/L_r2

Definition at line 579 of file mx.cpp.

579  {
580  return inf(Sparsity::dense(nrow, ncol));
581  }
static MX inf(const Sparsity &sp)
Create a constant with all nonzeros +inf.
Definition: mx.cpp:587

References casadi::Sparsity::dense(), and inf().

◆ inf() [2/3]

MX casadi::MX::inf ( const Sparsity &  sp)
static

Dense nrow-by-ncol (default 1-by-1), or with the given sparsity pattern.

>>> MX.inf(), MX.inf(2, 1), MX.inf(Sparsity.lower(2))
(MX(inf), MX(inf(2x1)), MX(inf(2x2,3nz)))

>> MX.inf(), MX.inf(2, 1), MX.inf(Sparsity.lower(2))
inf
inf(2x1)
inf(2x2,3nz)

julia> ca.MX.inf(), ca.MX.inf(2, 1), ca.MX.inf(ca.Sparsity.lower(2))
(inf, inf(2x1), inf(2x2,3nz))

See also
is_inf, nan

Extra doc: https://github.com/casadi/casadi/wiki/L_r2

Definition at line 587 of file mx.cpp.

587  {
588  return create(ConstantMX::create(sp, std::numeric_limits<double>::infinity()));
589  }

References casadi::ConstantMX::create(), and create().

Referenced by inf(), and casadi::init_gen().

◆ inf() [3/3]

MX casadi::MX::inf ( const std::pair< casadi_int, casadi_int > &  rc)
static

Dense nrow-by-ncol (default 1-by-1), or with the given sparsity pattern.

>>> MX.inf(), MX.inf(2, 1), MX.inf(Sparsity.lower(2))
(MX(inf), MX(inf(2x1)), MX(inf(2x2,3nz)))

>> MX.inf(), MX.inf(2, 1), MX.inf(Sparsity.lower(2))
inf
inf(2x1)
inf(2x2,3nz)

julia> ca.MX.inf(), ca.MX.inf(2, 1), ca.MX.inf(ca.Sparsity.lower(2))
(inf, inf(2x1), inf(2x2,3nz))

See also
is_inf, nan

Extra doc: https://github.com/casadi/casadi/wiki/L_r2

Definition at line 583 of file mx.cpp.

583  {
584  return inf(rc.first, rc.second);
585  }

References inf().

◆ info()

Dict casadi::MX::info ( ) const

The contents depend on the node type; most nodes return an empty dictionary. For example, a slicing node reports the slice it takes.

>>> X = MX.sym("X", 2, 2)
>>> X[0, 1].info()
{'slice': {'start': 2, 'step': 1, 'stop': 3}}
>>> X.info()
{}

>> X = MX.sym('X', 2, 2);
>> e = X(1, 2); s = e.info();
>> s.slice
start: 2
step: 1
stop: 3
>> isempty(fieldnames(X.info()))
1

julia> X = ca.MX.sym("X", 3, 3);
julia> ca.info(X[1, 2])
Dict{String, Any} with 1 entry:
  "slice" => Dict{String, Any}("step"=>1, "stop"=>4, "start"=>3)
julia> ca.info(X)
Dict{String, Any}()

Extra doc: https://github.com/casadi/casadi/wiki/L_2q9

Definition at line 858 of file mx.cpp.

858  {
859  return (*this)->info();
860  }

Referenced by casadi::MXFunction::export_code_body(), and casadi::Onnx::load().

◆ interp1d()

MX casadi::GenericMatrix< MX >::interp1d ( const std::vector< double > &  x,
const MX &  v,
const std::vector< double > &  xq,
const std::string &  mode,
bool  equidistant 
)
staticinherited

Definition at line 648 of file generic_matrix.hpp.

5364  {
5365 
5366  bool mode_floor = false;
5367  bool mode_ceil = false;
5368  if (mode=="floor") {
5369  mode_floor = true;
5370  } else if (mode=="ceil") {
5371  mode_ceil = true;
5372  } else if (mode=="linear") {
5373  //
5374  } else {
5375  casadi_error("interp1d(x, v, xq, mode): "
5376  "Mode must be 'floor', 'ceil' or 'linear'. Got '" + mode + "' instead.");
5377  }
5378 
5379  casadi_assert(is_increasing(x), "interp1d(x, v, xq): x must be increasing.");
5380 
5381  casadi_assert(x.size()==v.size1(),
5382  "interp1d(x, v, xq): dimensions mismatch. v expected to have " + str(x.size()) + " rows,"
5383  " but got " + str(v.size1()) + " instead.");
5384 
5385  // Need at least two elements
5386  casadi_assert(x.size()>=2, "interp1d(x, v, xq): x must be at least length 2.");
5387 
5388  // Vectors to compose a sparse matrix
5389  std::vector<double> val;
5390  std::vector<casadi_int> colind(1, 0);
5391  std::vector<casadi_int> row;
5392 
5393  // Number of nonzeros in to-be composed matrix
5394  casadi_int nnz = 0;
5395  for (casadi_int i=0;i<xq.size();++i) {
5396  // Obtain index corresponding to xq[i]
5397  double ind = index_interp1d(x, xq[i], equidistant);
5398 
5399  if (mode_floor) ind = floor(ind);
5400  if (mode_ceil) ind = ceil(ind);
5401 
5402  // Split into integer and fractional part
5403  double int_partd;
5404  double frac_part = modf(ind, &int_partd);
5405  casadi_int int_part = static_cast<casadi_int>(int_partd);
5406 
5407  if (frac_part==0) {
5408  // Create a single entry
5409  val.push_back(1);
5410  row.push_back(int_part);
5411  nnz+=1;
5412  colind.push_back(nnz);
5413  } else {
5414  // Create a double entry
5415  val.push_back(1-frac_part);
5416  val.push_back(frac_part);
5417  row.push_back(int_part);
5418  row.push_back(int_part+1);
5419  nnz+=2;
5420  colind.push_back(nnz);
5421  }
5422  }
5423 
5424  // Construct sparsity for composed matrix
5425  Sparsity sp(x.size(), xq.size() , colind, row);
5426 
5427  return MatType::mtimes(MatType(sp, val).T(), v);
5428 
5429  }
const casadi_int * colind() const
const casadi_int * row() const
double index_interp1d(const std::vector< double > &x, double xq, bool equidistant)
bool is_increasing(const std::vector< T > &v)
Check if the vector is strictly increasing.

◆ interpn_linear()

MX casadi::MX::interpn_linear ( const std::vector< MX > &  x,
const MX &  v,
const std::vector< MX > &  xq,
const Dict &  opts = Dict() 
)
static

Builds the interpolation as explicit MX operations (low, nonzero lookups and arithmetic) instead of an interpolant Function, so that the grid and values can be symbolic. Usually you want interpolant('name', 'linear', ...) instead. Extrapolates linearly outside the grid.

Parameters
xGrid points, one vector per dimension
vValues on the grid, flattened in column-major order over the grid; its length must be an integer multiple m of the number of grid points, giving m outputs per query point
xqQuery coordinates, one vector per dimension, all of the same length nq
opts"lookup_mode": list with one of "linear", "exact", "binary", "auto" (default) per dimension, see low
Returns
nq-by-m matrix

>>> g = MX.sym("g", 3)
>>> v = MX.sym("v", 3)
>>> xq = MX.sym("xq", 2)
>>> e = MX.interpn_linear([g], v, [xq])
>>> f = Function("f", [g, v, xq], [e])
>>> f(DM([0, 1, 2]), DM([0, 10, 40]), DM([0.5, 3]))
DM([5, 70])
>>> try:
...   MX.interpn_linear([g], MX.sym("w", 4), [xq])
... except Exception as e:
...   print("Dimension mismatch" in str(e))
True

>> g = MX.sym('g', 3); v = MX.sym('v', 3); xq = MX.sym('xq', 2);
>> e = MX.interpn_linear({g}, v, {xq});
>> f = Function('f', {g, v, xq}, {e});
>> f(DM([0; 1; 2]), DM([0; 10; 40]), DM([0.5; 3]))
[5, 70]
>> w = MX.sym('w', 4);
>> try, MX.interpn_linear({g}, w, {xq}); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> g = ca.MX.sym("g", 3); v = ca.MX.sym("v", 3); xq = ca.MX.sym("xq", 2);
julia> ex = ca.MX.interpn_linear([g], v, [xq]);
julia> f = ca.Function("f", [g, v, xq], [ex]);
julia> f([0, 1, 2], [0, 10, 40], [0.5, 3])
DM([5, 70])
julia> try
           ca.MX.interpn_linear([g], ca.MX.sym("w", 4), [xq])
       catch e
           println(occursin("Dimension mismatch", sprint(showerror, e)))
       end
true

See also
interpolant, low

Extra doc: https://github.com/casadi/casadi/wiki/L_r6

Definition at line 3138 of file mx.cpp.

3139  {
3140 
3141  casadi_int n_dim = x.size();
3142  std::vector<std::string> lookup_mode(n_dim, "auto");
3143  for (auto&& op : opts) {
3144  if (op.first=="lookup_mode") {
3145  lookup_mode = op.second;
3146  } else {
3147  casadi_error("Unknown option '" + op.first + "'.");
3148  }
3149  }
3150 
3151  casadi_assert(xq.size()==n_dim,
3152  "Expected " + str(n_dim) + " query vectors, but got " + str(xq.size()) + ".");
3153  casadi_assert(v.is_vector(), "Expected a vector of values, but got " + v.dim() + ".");
3154 
3155  // Extract grid dimensions
3156  std::vector<casadi_int> x_dims;
3157  for (auto e : x) x_dims.push_back(e.numel());
3158 
3159  // Determine multipicity of output
3160  casadi_int n_out = v.numel()/product(x_dims);
3161  casadi_assert(n_out*product(x_dims)==v.numel(),
3162  "Dimension mismatch: coefficients (" + str(v.numel()) + ") should be "
3163  "an integer multiple of product-of-dimensions (" + str(product(x_dims)) + ").");
3164 
3165  // Dimension check xq
3166  casadi_int nq = xq[0].numel();
3167  for (auto e : xq) {
3168  casadi_assert_dev(e.is_vector() && e.numel()==nq);
3169  }
3170 
3171  // Compute stride vector
3172  std::vector<casadi_int> strides;
3173  strides.push_back(n_out);
3174  for (auto d : x_dims) strides.push_back(strides.back()*d);
3175 
3176  // Pre-compute lower index and normalized coordinate
3177  // (Allows for more sub-expression sharing)
3178  std::vector<MX> xis, Ls, Lps;
3179  for (casadi_int i=0;i<n_dim;++i) {
3180  MX L = low(x[i], xq[i], {{"lookup_mode", lookup_mode[i]}});
3181  MX Lp = L+1;
3182  MX xl, xu;
3183  x[i].get_nz(xl, false, L);
3184  x[i].get_nz(xu, false, Lp);
3185  xis.push_back((xq[i]-xl)/(xu-xl));
3186  Ls.push_back(L);
3187  Lps.push_back(Lp);
3188  }
3189 
3190  Slice I(0, n_out);
3191 
3192  return interpn_G(n_dim, v, xis, Ls, Lps, strides, I);
3193  }
casadi_int n_out() const
Number of outputs of this node.
Definition: mx.cpp:901
static MX low(const MX &v, const MX &p, const Dict &options=Dict())
Definition: mx.cpp:2213
MX interpn_G(casadi_int i, const MX &v, const std::vector< MX > &xis, const std::vector< MX > &L, const std::vector< MX > &Lp, const std::vector< casadi_int > &strides, const Slice &I, const MX &offset=0)
Definition: mx.cpp:3108

References casadi::GenericMatrix< MatType >::dim(), get_nz(), casadi::interpn_G(), casadi::GenericMatrix< MatType >::is_vector(), low(), n_out(), casadi::GenericMatrix< MatType >::numel(), op(), casadi::product(), casadi::GenericMatrix< MatType >::size(), and casadi::str().

Referenced by casadi::LinearInterpolant::do_inline().

◆ inv() [1/2]

MX casadi::MX::inv ( ) const

Not the matrix inverse: use inv or inv_node for that. Applied twice it returns the original node. Not available in MATLAB and Julia, where inv is the matrix inverse; use 1./x there.

>>> A = MX.sym("A", 2, 2)
>>> A.inv(), A.inv().inv()
(MX((1./A)), MX(A))
>>> evalf(MX(4).inv())
DM(0.25)

See also
inv, inv_node

Extra doc: https://github.com/casadi/casadi/wiki/L_2dz

Definition at line 1090 of file mx.cpp.

1090  {
1091  if (is_op(OP_INV)) {
1092  return dep(0);
1093  } else {
1094  return (*this)->get_unary(OP_INV);
1095  }
1096  }
bool is_op(casadi_int op) const
Check if the node is a certain operation.
Definition: mx.cpp:826
MX dep(casadi_int ch=0) const
Get the ch-th dependency (child node) of this node.
Definition: mx.cpp:786
@ OP_INV
Definition: calculus.hpp:73

References dep(), is_op(), and casadi::OP_INV.

◆ inv() [2/2]

MX casadi::MX::inv ( const MX &  A,
const std::string &  lsolver = "qr",
const Dict &  dict = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2030 of file mx.cpp.

2030  {
2031  return solve(x, MX::eye(x.size1()), lsolver, dict);
2032  }
static MX eye(casadi_int n)
Identity matrix constant of size n-by-n, with a diagonal sparsity pattern.
Definition: mx.cpp:603
static MX solve(const MX &a, const MX &b)
Definition: mx.cpp:2108

References eye(), casadi::GenericMatrix< MatType >::size1(), and solve().

◆ inv_minor()

MX casadi::MX::inv_minor ( const MX &  A)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2026 of file mx.cpp.

2026  {
2027  casadi_error("Not implemented");
2028  }

◆ inv_node()

MX casadi::MX::inv_node ( const MX &  A)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2022 of file mx.cpp.

2022  {
2023  return x->get_inv();
2024  }

References casadi::MXNode::get_inv().

◆ inv_skew()

MX casadi::GenericMatrix< MX >::inv_skew ( const MX &  a)
staticinherited

Definition at line 664 of file generic_matrix.hpp.

5443  {
5444  casadi_assert(a.size1()==3 && a.size2()==3,
5445  "inv_skew(a): Expecting 3-by-3 matrix, got " + a.dim() + ".");
5446 
5447  return 0.5*vertcat(std::vector<MatType>({a(2, 1)-a(1, 2), a(0, 2)-a(2, 0), a(1, 0)-a(0, 1)}));
5448  }

◆ is_binary()

bool casadi::MX::is_binary ( ) const

Elementwise operations with two operands (OP_ADD, OP_MUL, OP_POW, comparisons, ...). Matrix products, concatenations and calls are not binary nodes. Note that x + x and x*x are stored as unary nodes (doubling, square).

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> A = MX.sym("A", 2, 2)
>>> (x + y).is_binary(), (x**y).is_binary(), (A @ A).is_binary(), (x + x).is_binary()
(True, True, False, False)

>> x = MX.sym('x'); y = MX.sym('y'); A = MX.sym('A', 2, 2);
>> a = x + y; b = x^y; c = A*A; d = x + x;
>> a.is_binary(), b.is_binary(), c.is_binary(), d.is_binary()
1
1
0
0

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y"); A = ca.MX.sym("A", 2, 2);
julia> ca.is_binary(x + y), ca.is_binary(x^y), ca.is_binary(A * A), ca.is_binary(x + x)
(true, true, false, false)

See also
is_unary, op

Extra doc: https://github.com/casadi/casadi/wiki/L_2q6

Definition at line 846 of file mx.cpp.

846  {
847  return (*this)->is_binary();
848  }

Referenced by casadi::MXFunction::export_code_body(), and is_commutative().

◆ is_call()

bool casadi::MX::is_call ( ) const

A call to a Function with several outputs is a single call node; the values you get back from calling the Function are OutputNodes that reference it (see is_output). MX Functions are inlined when called with MX arguments unless never_inline is set, so no call node appears in that case.

>>> a = SX.sym("a")
>>> f = Function("f", [a], [a + 1, 2*a])
>>> x = MX.sym("x")
>>> r0, r1 = f(x, )
>>> r0.is_call(), r0.is_output(), r0.dep(0).is_call()
(False, True, True)
>>> r0.dep(0).which_function().name()
'f'

>> a = SX.sym('a');
>> f = Function('f', {a}, {a + 1, 2*a});
>> x = MX.sym('x');
>> [r0, r1] = f(x);
>> call = r0.dep(0);
>> r0.is_call(), r0.is_output(), call.is_call()
0
1
1
>> call.which_function().name()
f

julia> a = ca.SX.sym("a");
julia> f = ca.Function("f", [a], [a + 1, 2 * a]);
julia> x = ca.MX.sym("x");
julia> r0, r1 = f(x);
julia> ca.is_call(r0), ca.is_output(r0), ca.is_call(ca.dep(r0, 0))
(false, true, true)
julia> ca.name(ca.which_function(ca.dep(r0, 0)))
"f"

See also
which_function, is_output, which_output, n_out

Extra doc: https://github.com/casadi/casadi/wiki/L_2px

Definition at line 806 of file mx.cpp.

806  {
807  return (*this)->op()==OP_CALL;
808  }

References casadi::OP_CALL.

Referenced by casadi::BlazingSplineFunction::merge().

◆ is_column()

bool casadi::GenericMatrix< MX >::is_column ( ) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1b5

Definition at line 517 of file generic_matrix.hpp.

517 { return sparsity().is_column();}
bool is_column() const
Check whether the pattern is a column vector, i.e. size2() == 1.
Definition: sparsity.cpp:287

◆ is_commutative()

bool casadi::MX::is_commutative ( ) const

Unary operations count as commutative. Any other node raises an error.

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> (x + y).is_commutative(), (x - y).is_commutative()
(True, False)

>> x = MX.sym('x'); y = MX.sym('y');
>> a = x + y; b = x - y;
>> a.is_commutative(), b.is_commutative()
1
0

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> ca.is_commutative(x + y), ca.is_commutative(x - y)
(true, false)

See also
is_binary, is_unary

Extra doc: https://github.com/casadi/casadi/wiki/L_2q3

Definition at line 882 of file mx.cpp.

882  {
883  if (is_unary()) return true;
884  casadi_assert(is_binary() || is_unary(),
885  "MX::is_commutative: must be binary or unary operation");
886  return operation_checker<CommChecker>(op());
887  }
bool is_binary() const
Check if the node is an elementwise binary operation.
Definition: mx.cpp:846
bool is_unary() const
Check if the node is an elementwise unary operation.
Definition: mx.cpp:850

References is_binary(), is_unary(), and op().

◆ is_constant()

bool casadi::MX::is_constant ( ) const

True only for constant nodes. Operations between constants are folded into a new constant where possible, but an expression without symbols is not constant in general (e.g. a Function call with constant arguments); use evalf to evaluate it.

>>> MX(1).is_constant(), MX(2, 2).is_constant(), MX.sym("x").is_constant()
(True, True, False)
>>> (MX(1) + MX(2)).is_constant()
True

>> MX(1).is_constant(), MX(2, 2).is_constant(), MX.sym('x').is_constant()
1
1
0
>> e = MX(1) + MX(2);
>> e.is_constant()
1

julia> ca.is_constant(ca.MX(1)), ca.is_constant(ca.MX(2, 2)), ca.is_constant(ca.MX.sym("x"))
(true, true, false)
julia> ca.is_constant(ca.MX(1) + ca.MX(2))
true

See also
is_symbolic, to_DM, evalf

Extra doc: https://github.com/casadi/casadi/wiki/L_2pv

Definition at line 802 of file mx.cpp.

802  {
803  return (*this)->op()==OP_CONST;
804  }

References casadi::OP_CONST.

Referenced by casadi::MXNode::_get_binary(), casadi::constant_ints(), casadi::DaeBuilderInternal::create(), casadi::ConstantMX::get_dot(), casadi::MXNode::get_einstein(), casadi::Constant< Value >::get_nzassign(), is_regular(), casadi::DaeBuilderInternal::load_fmi_description(), MX(), casadi::OptiNode::subject_to(), and casadi::MXNode::~MXNode().

◆ is_dense()

bool casadi::GenericMatrix< MX >::is_dense ( ) const
inlineinherited

Based on the sparsity pattern only: stored numerical zeros still count as nonzeros. Empty matrices are dense.

>>> DM.zeros(2, 2).is_dense(), DM(2, 2).is_dense(), DM(0, 3).is_dense()
(True, False, True)

>> Z = DM.zeros(2, 2);
>> fprintf('%d %d %d\n', Z.is_dense(), DM(2, 2).is_dense(), DM(0, 3).is_dense())
1 0 1

julia> ca.is_dense(ca.DM.zeros(2, 2)), ca.is_dense(ca.DM(2, 2)), ca.is_dense(ca.DM(0, 3))
(true, false, true)

See also
nnz, numel, densify

Extra doc: https://github.com/casadi/casadi/wiki/L_1b0

Definition at line 434 of file generic_matrix.hpp.

434 { return sparsity().is_dense();}
bool is_dense() const
Check whether every entry is a structural nonzero, i.e. nnz() == numel()
Definition: sparsity.cpp:275

◆ is_doubled()

bool casadi::MX::is_doubled ( ) const

True for x + x (which is stored as a doubling node) and for 2*x, and for a sum whose two operands compare equal up to get_max_depth.

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> (x + x).is_doubled(), (2*x).is_doubled(), (x + y).is_doubled()
(True, True, False)

>> x = MX.sym('x'); y = MX.sym('y');
>> a = x + x; b = 2*x; c = x + y;
>> a.is_doubled(), b.is_doubled(), c.is_doubled()
1
1
0

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> ca.is_doubled(x + x), ca.is_doubled(2 * x), ca.is_doubled(x + y)
(true, true, false)

Extra doc: https://github.com/casadi/casadi/wiki/L_2e0

Definition at line 1085 of file mx.cpp.

1085  {
1086  return (op()==OP_ADD && is_equal(dep(0), dep(1), get_max_depth())) ||
1087  (op()==OP_TWICE);
1088  }
static casadi_int get_max_depth()
Get the depth to which equalities are checked for simplifications.
Definition: mx.cpp:945
@ OP_TWICE
Definition: calculus.hpp:67
@ OP_ADD
Definition: calculus.hpp:65

References dep(), get_max_depth(), is_equal(), op(), casadi::OP_ADD, and casadi::OP_TWICE.

◆ is_empty()

bool casadi::GenericMatrix< MX >::is_empty ( bool  both = false) const
inlineinherited

With both true, only a 0-by-0 matrix counts as empty.

>>> DM(0, 3).is_empty(), DM(0, 3).is_empty(True), DM(0, 0).is_empty(True)
(True, False, True)
>>> DM(1, 1).is_empty()
False

>> E = DM(0, 3);
>> fprintf('%d %d %d\n', E.is_empty(), E.is_empty(true), DM(0, 0).is_empty(true))
1 0 1
>> DM(1, 1).is_empty()
0

julia> E = ca.DM(0, 3);
julia> ca.is_empty(E), ca.is_empty(E, true), ca.is_empty(ca.DM(0, 0), true)
(true, false, true)
julia> ca.is_empty(ca.DM(1, 1))
false

Extra doc: https://github.com/casadi/casadi/wiki/L_1az

Definition at line 402 of file generic_matrix.hpp.

402 { return sparsity().is_empty(both);}
bool is_empty(bool both=false) const
Check whether the pattern has a zero dimension.
Definition: sparsity.cpp:146

◆ is_equal()

bool casadi::MX::is_equal ( const MX &  x,
const MX &  y,
casadi_int  depth = 0 
)
static

Functions called by friend functions defined for GenericExpression

Definition at line 870 of file mx.cpp.

870  {
871  return MXNode::is_equal(x.get(), y.get(), depth);
872  }
static bool is_equal(const MXNode *x, const MXNode *y, casadi_int depth)
Check if two nodes are equivalent up to a given depth.
Definition: mx_node.cpp:1318

References get(), and casadi::MXNode::is_equal().

Referenced by casadi::BinaryMX< ScX, ScY >::_get_binary(), casadi::UnaryMX::_get_binary(), casadi::Call::common_cond(), casadi::MXNode::get_binary(), graph_substitute(), is_doubled(), casadi::BinaryMX< ScX, ScY >::is_equal(), casadi::MXNode::sameOpAndDeps(), and substitute().

◆ is_eye()

bool casadi::MX::is_eye ( ) const

Only recognizes constants created as an identity (MX.eye, DM.eye); a dense constant that happens to equal the identity is not detected. A 1-by-1 constant one counts.

>>> MX.eye(2).is_eye(), MX(DM([[1, 0], [0, 1]])).is_eye(), MX(1).is_eye()
(True, False, True)

>> MX.eye(2).is_eye(), MX(DM([1 0; 0 1])).is_eye(), MX(1).is_eye()
1
0
1

julia> ca.is_eye(ca.MX.eye(2)), ca.is_eye(ca.MX([1 0; 0 1])), ca.is_eye(ca.MX(1))
(true, false, true)

Extra doc: https://github.com/casadi/casadi/wiki/L_qu

Definition at line 1029 of file mx.cpp.

1029  {
1030  return (*this)->is_eye();
1031  }

Referenced by mac().

◆ is_half()

bool casadi::MX::is_half ( ) const

Extra doc: https://github.com/casadi/casadi/wiki/L_2ep

Definition at line 1049 of file mx.cpp.

1049  {
1050  return (*this)->is_half();
1051  }

◆ is_inf()

bool casadi::MX::is_inf ( ) const

>>> MX.inf().is_inf(), MX.inf(2, 2).is_inf(), MX(1).is_inf()
(True, True, False)

>> MX.inf().is_inf(), MX.inf(2, 2).is_inf(), MX(1).is_inf()
1
1
0

julia> ca.is_inf(ca.MX.inf()), ca.is_inf(ca.MX.inf(2, 2)), ca.is_inf(ca.MX(1))
(true, true, false)

See also
is_minus_inf, MX.inf

Extra doc: https://github.com/casadi/casadi/wiki/L_2e1

Definition at line 1073 of file mx.cpp.

1073  {
1074  return (*this)->is_inf();
1075  }

◆ is_integer()

bool casadi::MX::is_integer ( ) const

False for non-constant nodes.

>>> MX(3).is_integer(), MX(3.5).is_integer(), MX.sym("x").is_integer()
(True, False, False)

>> MX(3).is_integer(), MX(3.5).is_integer(), MX.sym('x').is_integer()
1
0
0

julia> ca.is_integer(ca.MX(3)), ca.is_integer(ca.MX(3.5)), ca.is_integer(ca.MX.sym("x"))
(true, false, false)

Extra doc: https://github.com/casadi/casadi/wiki/L_2pw

Definition at line 1081 of file mx.cpp.

1081  {
1082  return (*this)->is_integer();
1083  }

◆ is_linear()

bool casadi::GenericMatrix< MX >::is_linear ( const MX &  expr,
const MX &  var 
)
staticinherited

Definition at line 670 of file generic_matrix.hpp.

5678  {
5679  return !any(MatType::which_depends(expr, var, 2, true));
5680  }

◆ is_minus_inf()

bool casadi::MX::is_minus_inf ( ) const

>>> (-MX.inf()).is_minus_inf(), MX.inf().is_minus_inf()
(True, False)

>> m = -MX.inf();
>> m.is_minus_inf(), MX.inf().is_minus_inf()
1
0

julia> ca.is_minus_inf(-ca.MX.inf()), ca.is_minus_inf(ca.MX.inf())
(true, false)

Extra doc: https://github.com/casadi/casadi/wiki/L_2e2

Definition at line 1077 of file mx.cpp.

1077  {
1078  return (*this)->is_minus_inf();
1079  }

◆ is_minus_one()

bool casadi::MX::is_minus_one ( ) const

>>> MX(-1).is_minus_one(), (-MX(1)).is_minus_one(), MX(1).is_minus_one()
(True, True, False)

>> m = -MX(1);
>> MX(-1).is_minus_one(), m.is_minus_one(), MX(1).is_minus_one()
1
1
0

julia> ca.is_minus_one(ca.MX(-1)), ca.is_minus_one(-ca.MX(1)), ca.is_minus_one(ca.MX(1))
(true, true, false)

Extra doc: https://github.com/casadi/casadi/wiki/L_qx

Definition at line 1045 of file mx.cpp.

1045  {
1046  return (*this)->is_value(-1);
1047  }

◆ is_multiplication()

bool casadi::MX::is_multiplication ( ) const

Elementwise multiplication does not count.

>>> A = MX.sym("A", 2, 2)
>>> (A @ A).is_multiplication(), (A * A).is_multiplication()
(True, False)

>> A = MX.sym('A', 2, 2);
>> a = A*A; b = A.*A;
>> a.is_multiplication(), b.is_multiplication()
1
0

julia> A = ca.MX.sym("A", 2, 2);
julia> ca.is_multiplication(A * A), ca.is_multiplication(A .* A)
(true, false)

Extra doc: https://github.com/casadi/casadi/wiki/L_2q2

Definition at line 830 of file mx.cpp.

830  {
831  return (*this)->op()==OP_MTIMES;
832  }
@ OP_MTIMES
Definition: calculus.hpp:100

References casadi::OP_MTIMES.

◆ is_nonnegative()

bool casadi::MX::is_nonnegative ( ) const

Recognizes nonnegative constants and operations with a nonnegative range such as squares, absolute values, exponentials and square roots.

>>> x = MX.sym("x")
>>> (x**2).is_nonnegative(), fabs(x).is_nonnegative(), exp(x).is_nonnegative()
(True, True, True)
>>> x.is_nonnegative(), MX(-3).is_nonnegative(), MX(0).is_nonnegative()
(False, False, True)

>> x = MX.sym('x');
>> a = x^2; b = abs(x); c = exp(x);
>> a.is_nonnegative(), b.is_nonnegative(), c.is_nonnegative()
1
1
1
>> x.is_nonnegative(), MX(-3).is_nonnegative(), MX(0).is_nonnegative()
0
0
1

julia> x = ca.MX.sym("x");
julia> ca.is_nonnegative(x^2), ca.is_nonnegative(abs(x)), ca.is_nonnegative(exp(x))
(true, true, true)
julia> ca.is_nonnegative(x), ca.is_nonnegative(ca.MX(-3)), ca.is_nonnegative(ca.MX(0))
(false, false, true)

Extra doc: https://github.com/casadi/casadi/wiki/L_2e3

Definition at line 1057 of file mx.cpp.

1057  {
1058  return (*this)->is_nonnegative();
1059  }

◆ is_norm()

bool casadi::MX::is_norm ( ) const

>>> A = MX.sym("A", 2, 2)
>>> norm_2(A).is_norm(), norm_fro(A).is_norm(), sqrt(dot(A, A)).is_norm()
(True, True, False)

>> A = MX.sym('A', 2, 2);
>> a = norm_2(A); b = norm_fro(A); c = sqrt(dot(A, A));
>> a.is_norm(), b.is_norm(), c.is_norm()
1
1
0

julia> A = ca.MX.sym("A", 2, 2);
julia> ca.is_norm(ca.norm_2(A)), ca.is_norm(ca.norm_fro(A)), ca.is_norm(sqrt(ca.dot(A, A)))
(true, true, false)

Extra doc: https://github.com/casadi/casadi/wiki/L_2q4

Definition at line 834 of file mx.cpp.

834  {
835  return dynamic_cast<const Norm*>(get())!=nullptr;
836  }

References get().

◆ is_null()

Definition at line 116 of file generic_shared_impl.hpp.

120  {
121  return node==nullptr;
122  }

◆ is_one()

bool casadi::MX::is_one ( ) const

Structural zeros are ignored: MX(Sparsity.lower(2)) is not "one" because it has structural zeros that would be zero when densified.

>>> MX(1).is_one(), MX.ones(2, 2).is_one(), MX(Sparsity.lower(2)).is_one()
(True, True, False)

>> MX(1).is_one(), MX.ones(2, 2).is_one(), MX(Sparsity.lower(2)).is_one()
1
1
0

julia> ca.is_one(ca.MX(1)), ca.is_one(ca.MX.ones(2, 2)),
       ca.is_one(ca.MX(ca.Sparsity.lower(2)))
(true, true, false)

Extra doc: https://github.com/casadi/casadi/wiki/L_qw

Definition at line 1041 of file mx.cpp.

1041  {
1042  return (*this)->is_one();
1043  }

◆ is_op()

bool casadi::MX::is_op ( casadi_int  op) const
Parameters
opOne of the OP_* constants (OP_ADD, OP_SIN, OP_CALL, OP_GETNONZEROS, ...)

>>> x = MX.sym("x", 2)
>>> (x + 1).is_op(OP_ADD), sin(x).is_op(OP_SIN), x.is_op(OP_PARAMETER)
(True, True, True)
>>> x[0].is_op(OP_GETNONZEROS), MX(1).is_op(OP_CONST)
(True, True)

>> x = MX.sym('x', 2);
>> a = x + 1; b = sin(x);
>> a.is_op(OP_ADD), b.is_op(OP_SIN), x.is_op(OP_PARAMETER)
1
1
1
>> c = x(1);
>> c.is_op(OP_GETNONZEROS), MX(1).is_op(OP_CONST)
1
1

julia> x = ca.MX.sym("x", 2);
julia> ca.is_op(x + 1, ca.OP_ADD), ca.is_op(sin.(x), ca.OP_SIN),
       ca.is_op(x, ca.OP_PARAMETER)
(true, true, true)
julia> ca.is_op(x[1], ca.OP_GETNONZEROS), ca.is_op(ca.MX(1), ca.OP_CONST)
(true, true)

See also
op

Extra doc: https://github.com/casadi/casadi/wiki/L_2q1

Definition at line 826 of file mx.cpp.

826  {
827  return (*this)->op()==op;
828  }

References op().

Referenced by casadi::OptiNode::canon_expr(), inv(), and casadi::DaeBuilderInternal::when().

◆ is_output()

bool casadi::MX::is_output ( ) const

The expressions obtained by calling a Function with several outputs are OutputNodes: they have one dependency, the call node, and which_output gives the index.

>>> a = SX.sym("a")
>>> f = Function("f", [a], [a + 1, 2*a])
>>> x = MX.sym("x")
>>> r0, r1 = f(x, )
>>> r1, r1.is_output(), r1.which_output(), r1.dep(0)
(MX(f(x){1}), True, 1, MX(f(x)))
>>> x.is_output(), (x + 1).is_output()
(False, False)

>> a = SX.sym('a');
>> f = Function('f', {a}, {a + 1, 2*a});
>> x = MX.sym('x');
>> [r0, r1] = f(x);
>> r1, r1.is_output(), r1.which_output(), r1.dep(0)
f(x){1}
1
1
f(x)
>> e = x + 1;
>> x.is_output(), e.is_output()
0
0

julia> a = ca.SX.sym("a");
julia> f = ca.Function("f", [a], [a + 1, 2 * a]);
julia> x = ca.MX.sym("x");
julia> r0, r1 = f(x);
julia> r1, ca.is_output(r1), ca.which_output(r1), ca.dep(r1, 0)
(f(x){1}, true, 1, f(x))
julia> ca.is_output(x), ca.is_output(x + 1)
(false, false)

See also
which_output, is_call, has_output

Extra doc: https://github.com/casadi/casadi/wiki/L_2pz

Definition at line 814 of file mx.cpp.

814  {
815  return (*this)->is_output();
816  }

Referenced by casadi::DaeBuilderInternal::create(), cse(), and casadi::DaeBuilderInternal::jac_vdef_v_from_calls().

◆ is_quadratic()

bool casadi::GenericMatrix< MX >::is_quadratic ( const MX &  expr,
const MX &  var 
)
staticinherited

Definition at line 671 of file generic_matrix.hpp.

5683  {
5684  return is_linear(gradient(expr, var), var);
5685  }
static bool is_linear(const MX &expr, const MX &var)

◆ is_regular()

bool casadi::MX::is_regular ( ) const

Only defined for constant nodes; a symbolic expression raises an error.

>>> MX(1).is_regular(), MX.inf().is_regular(), MX(DM([1, float("nan")])).is_regular()
(True, False, False)
>>> try:
...   MX.sym("x").is_regular()
... except Exception as e:
...   print("Cannot check regularity for symbolic MX" in str(e))
True

>> MX(1).is_regular(), MX.inf().is_regular()
1
0
>> MX(DM([1; nan])).is_regular()
0
>> try, MX.sym('x').is_regular(); catch e, disp('error'); end
error

julia> ca.is_regular(ca.MX(1)), ca.is_regular(ca.MX.inf()), ca.is_regular(ca.MX([1, NaN]))
(true, false, false)
julia> try
           ca.is_regular(ca.MX.sym("x"))
       catch e
           println(occursin("Cannot check regularity", sprint(showerror, e)))
       end
true

Extra doc: https://github.com/casadi/casadi/wiki/L_2q5

Definition at line 1065 of file mx.cpp.

1065  {
1066  if (is_constant()) {
1067  return static_cast<DM>(*this).is_regular();
1068  } else {
1069  casadi_error("Cannot check regularity for symbolic MX");
1070  }
1071  }
bool is_constant() const
Check if the node is a constant.
Definition: mx.cpp:802
bool is_regular() const
Check that no entry is nan, inf or -inf.

References is_constant(), and casadi::Matrix< Scalar >::is_regular().

◆ is_row()

bool casadi::GenericMatrix< MX >::is_row ( ) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1b4

Definition at line 512 of file generic_matrix.hpp.

512 { return sparsity().is_row();}
bool is_row() const
Check whether the pattern is a row vector, i.e. size1() == 1.
Definition: sparsity.cpp:283

◆ is_scalar()

bool casadi::GenericMatrix< MX >::is_scalar ( bool  scalar_and_dense = false) const
inherited
Parameters
scalar_and_denseWhen true, a 1-by-1 matrix with a structural zero does not count

>>> x = SX.sym("x", Sparsity(1, 1))
>>> x.is_scalar(), x.is_scalar(True), SX.sym("y").is_scalar(True)
(True, False, True)

>> x = SX.sym('x', Sparsity(1, 1));
>> fprintf('%d %d %d\n', x.is_scalar(), x.is_scalar(true), SX.sym('y').is_scalar(true))
1 0 1

julia> x = ca.SX.sym("x", ca.Sparsity(1, 1));
julia> ca.is_scalar(x), ca.is_scalar(x, true), ca.is_scalar(ca.SX.sym("y"), true)
(true, false, true)

Extra doc: https://github.com/casadi/casadi/wiki/L_1b1

Definition at line 465 of file generic_matrix.hpp.

5279  {
5280  return sparsity().is_scalar(scalar_and_dense);
5281  }
bool is_scalar(bool scalar_and_dense=false) const
Check whether the pattern is 1-by-1.
Definition: sparsity.cpp:271

◆ is_square()

bool casadi::GenericMatrix< MX >::is_square ( ) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1b2

Definition at line 470 of file generic_matrix.hpp.

470 { return sparsity().is_square();}
bool is_square() const
Check whether the number of rows equals the number of columns.
Definition: sparsity.cpp:295

◆ is_symbolic()

bool casadi::MX::is_symbolic ( ) const

False for any expression built from primitives, including concatenations of primitives (use is_valid_input for those). A symbol without nonzeros, e.g. MX.sym("x", 2, 0), is stored as an empty constant and is not symbolic.

>>> x = MX.sym("x")
>>> x.is_symbolic(), (x + 1).is_symbolic(), vertcat(x, x).is_symbolic()
(True, False, False)
>>> MX.sym("e", 2, 0).is_symbolic()
False

>> x = MX.sym('x'); e = x + 1; v = vertcat(x, x);
>> x.is_symbolic(), e.is_symbolic(), v.is_symbolic()
1
0
0
>> MX.sym('e', 2, 0).is_symbolic()
0

julia> x = ca.MX.sym("x");
julia> ca.is_symbolic(x), ca.is_symbolic(x + 1), ca.is_symbolic([x; x])
(true, false, false)
julia> ca.is_symbolic(ca.MX.sym("e", 2, 0))
false

See also
is_constant, is_valid_input, name

Extra doc: https://github.com/casadi/casadi/wiki/L_2pu

Definition at line 798 of file mx.cpp.

798  {
799  return (*this)->op()==OP_PARAMETER;
800  }

References casadi::OP_PARAMETER.

Referenced by casadi::DaeBuilder::add(), casadi::DaeBuilderInternal::der(), casadi::OptiNode::describe(), casadi::DaeBuilderInternal::find(), casadi::DaeBuilderInternal::load_fmi_description(), casadi::register_symbol(), and substitute_inplace().

◆ is_transpose()

bool casadi::MX::is_transpose ( ) const

The transpose of a scalar is the scalar itself and that of a vector is a reshape, so only transposes of genuine matrices create a transpose node.

>>> A = MX.sym("A", 2, 2)
>>> A.T.is_transpose(), A.is_transpose(), MX.sym("v", 2).T.is_transpose()
(True, False, False)

>> A = MX.sym('A', 2, 2); At = A'; vt = MX.sym('v', 2)';
>> At.is_transpose(), A.is_transpose(), vt.is_transpose()
1
0
0

julia> A = ca.MX.sym("A", 2, 2);
julia> ca.is_transpose(A'), ca.is_transpose(A), ca.is_transpose(ca.MX.sym("v", 2)')
(true, false, false)

See also
T

Extra doc: https://github.com/casadi/casadi/wiki/L_qy

Definition at line 1061 of file mx.cpp.

1061  {
1062  return op()==OP_TRANSPOSE;
1063  }
@ OP_TRANSPOSE
Definition: calculus.hpp:106

References op(), and casadi::OP_TRANSPOSE.

◆ is_tril()

bool casadi::GenericMatrix< MX >::is_tril ( ) const
inlineinherited

Decided on the sparsity pattern alone, see is_triu.

See also
is_triu, tril, tril2symm

Extra doc: https://github.com/casadi/casadi/wiki/L_1b7

Definition at line 560 of file generic_matrix.hpp.

560 { return sparsity().is_tril();}
bool is_tril(bool strictly=false) const
Check whether all nonzeros are on or below the diagonal (row >= col)
Definition: sparsity.cpp:323

◆ is_triu()

bool casadi::GenericMatrix< MX >::is_triu ( ) const
inlineinherited

Decided on the sparsity pattern alone: all structural nonzeros must lie on or above the diagonal. A dense matrix with numerical zeros below the diagonal is not upper triangular. Also defined for non-square matrices.

>>> DM(Sparsity.upper(3), 1).is_triu(), DM.zeros(2, 2).is_triu(), DM(2, 2).is_triu()
(True, False, True)

>> U = DM(Sparsity.upper(3), 1);
>> fprintf('%d %d %d\n', U.is_triu(), DM.zeros(2, 2).is_triu(), DM(2, 2).is_triu())
1 0 1

julia> U = ca.DM(ca.Sparsity.upper(3), 1);
julia> ca.is_triu(U), ca.is_triu(ca.DM.zeros(2, 2)), ca.is_triu(ca.DM(2, 2))
(true, false, true)

See also
is_tril, triu, triu2symm

Extra doc: https://github.com/casadi/casadi/wiki/L_1b6

Definition at line 551 of file generic_matrix.hpp.

551 { return sparsity().is_triu();}
bool is_triu(bool strictly=false) const
Check whether all nonzeros are on or above the diagonal (row <= col)
Definition: sparsity.cpp:327

◆ is_unary()

bool casadi::MX::is_unary ( ) const

OP_SIN, OP_NEG, OP_SQ, ... Transposes, reshapes and projections are not unary nodes even though they have one dependency.

>>> x = MX.sym("x")
>>> A = MX.sym("A", 2, 2)
>>> sin(x).is_unary(), (-x).is_unary(), x.is_unary(), A.T.is_unary()
(True, True, False, False)

>> x = MX.sym('x'); A = MX.sym('A', 2, 2);
>> a = sin(x); b = -x; c = A';
>> a.is_unary(), b.is_unary(), x.is_unary(), c.is_unary()
1
1
0
0

julia> x = ca.MX.sym("x"); A = ca.MX.sym("A", 2, 2);
julia> ca.is_unary(sin(x)), ca.is_unary(-x), ca.is_unary(x), ca.is_unary(A')
(true, true, false, false)

See also
is_binary, op

Extra doc: https://github.com/casadi/casadi/wiki/L_2q7

Definition at line 850 of file mx.cpp.

850  {
851  return (*this)->is_unary();
852  }

Referenced by casadi::MXFunction::export_code_body(), and is_commutative().

◆ is_valid_input()

bool casadi::MX::is_valid_input ( ) const

Valid inputs are symbolic primitives, reshapes and transposes of them, and (nested) concatenations of valid inputs. Constants without nonzeros are also accepted. An expression that is not a valid input raises an error when passed as a Function input.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> vertcat(x, y).is_valid_input(), vertcat(x, y).T.is_valid_input()
(True, True)
>>> (x + 1).is_valid_input(), MX(1).is_valid_input(), MX(2, 2).is_valid_input()
(False, False, True)

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> v = [x; y]; vt = v';
>> v.is_valid_input(), vt.is_valid_input()
1
1
>> e = x + 1;
>> e.is_valid_input(), MX(1).is_valid_input(), MX(2, 2).is_valid_input()
0
0
1

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> ca.is_valid_input([x; y]), ca.is_valid_input([x; y]')
(true, true)
julia> ca.is_valid_input(x + 1), ca.is_valid_input(ca.MX(1)), ca.is_valid_input(ca.MX(2, 2))
(false, false, true)

See also
primitives, n_primitives, is_symbolic

Extra doc: https://github.com/casadi/casadi/wiki/L_qn

Definition at line 957 of file mx.cpp.

957  {
958  return (*this)->is_valid_input();
959  }

Referenced by casadi::DaeBuilderInternal::der(), casadi::OptiNode::set_domain(), and casadi::OptiNode::to_function().

◆ is_value()

bool casadi::MX::is_value ( double  val) const

False negatives are possible: only constant nodes are inspected; symbolic expressions always give false.

>>> MX(3).is_value(3), MX(DM([3, 3])).is_value(3), MX(DM([3, 4])).is_value(3)
(True, True, False)
>>> MX.sym("x").is_value(3)
False

>> MX(3).is_value(3), MX(DM([3; 3])).is_value(3)
1
1
>> MX(DM([3; 4])).is_value(3)
0
>> MX.sym('x').is_value(3)
0

julia> ca.is_value(ca.MX(3), 3), ca.is_value(ca.MX([3, 3]), 3),
       ca.is_value(ca.MX([3, 4]), 3)
(true, true, false)
julia> ca.is_value(ca.MX.sym("x"), 3)
false

Extra doc: https://github.com/casadi/casadi/wiki/L_2eq

Definition at line 1053 of file mx.cpp.

1053  {
1054  return (*this)->is_value(val);
1055  }

◆ is_vector()

bool casadi::GenericMatrix< MX >::is_vector ( ) const
inlineinherited

True when size1() or size2() is one, so scalars and n-by-1 or 1-by-n empties count. A 0-by-0 matrix does not.

>>> DM(3, 1).is_vector(), DM(1, 3).is_vector(), DM(1, 1).is_vector()
(True, True, True)
>>> DM(3, 3).is_vector(), DM(0, 1).is_vector(), DM(0, 0).is_vector()
(False, True, False)

>> fprintf('%d %d %d\n', DM(3, 1).is_vector(), DM(1, 3).is_vector(), DM(1, 1).is_vector())
1 1 1
>> fprintf('%d %d %d\n', DM(3, 3).is_vector(), DM(0, 1).is_vector(), DM(0, 0).is_vector())
0 1 0

julia> ca.is_vector(ca.DM(3, 1)), ca.is_vector(ca.DM(1, 3)), ca.is_vector(ca.DM(1, 1))
(true, true, true)
julia> ca.is_vector(ca.DM(3, 3)), ca.is_vector(ca.DM(0, 1)), ca.is_vector(ca.DM(0, 0))
(false, true, false)

See also
is_row, is_column

Extra doc: https://github.com/casadi/casadi/wiki/L_1b3

Definition at line 507 of file generic_matrix.hpp.

507 { return sparsity().is_vector();}
bool is_vector() const
Check whether the pattern is a row or a column vector.
Definition: sparsity.cpp:291

◆ is_zero()

bool casadi::MX::is_zero ( ) const

True for constants with all nonzeros zero and for any matrix without nonzeros, whether symbolic or not. Expressions that simplify to zero (x - x, 0*x) are folded to a constant at construction and therefore report true.

>>> x = MX.sym("x")
>>> MX(0).is_zero(), MX(2, 2).is_zero(), (x - x).is_zero(), x.is_zero()
(True, True, True, False)
>>> MX.sym("e", 2, 0).is_zero()
True

>> x = MX.sym('x'); e = x - x;
>> MX(0).is_zero(), MX(2, 2).is_zero(), e.is_zero(), x.is_zero()
1
1
1
0
>> MX.sym('e', 2, 0).is_zero()
1

julia> x = ca.MX.sym("x");
julia> ca.is_zero(ca.MX(0)), ca.is_zero(ca.MX(2, 2)), ca.is_zero(x - x), ca.is_zero(x)
(true, true, true, false)
julia> ca.is_zero(ca.MX.sym("e", 2, 0))
true

Extra doc: https://github.com/casadi/casadi/wiki/L_qv

Definition at line 1033 of file mx.cpp.

1033  {
1034  if (nnz()==0) {
1035  return true;
1036  } else {
1037  return (*this)->is_zero();
1038  }
1039  }

References casadi::GenericMatrix< MX >::nnz().

Referenced by casadi::MXNode::_get_binary(), casadi::MXNode::get_dot(), casadi::MXNode::get_einstein(), casadi::MXNode::get_mac(), and mac().

◆ jacobian()

MX casadi::MX::jacobian ( const MX &  f,
const MX &  x,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1913 of file mx.cpp.

1913  {
1914  try {
1915  Dict h_opts;
1916  Dict opts_remainder = extract_from_dict(opts, "helper_options", h_opts);
1917  h_opts["allow_free"] = true;
1918  Function h("helper_jacobian_MX", {x}, {f}, h_opts);
1919  return h.get<MXFunction>()->jac(opts_remainder).at(0);
1920  } catch (std::exception& e) {
1921  CASADI_THROW_ERROR("jacobian", e.what());
1922  }
1923  }

References casadi::extract_from_dict(), and casadi::Function::get().

Referenced by hessian(), casadi::Scpgen::init(), and casadi::RuntimeIntegrator::jump_function().

◆ jacobian_sparsity()

Sparsity casadi::MX::jacobian_sparsity ( const MX &  f,
const MX &  x 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2009 of file mx.cpp.

2009  {
2010  return _jacobian_sparsity(f, x);
2011  }
Sparsity _jacobian_sparsity(const MatType &expr, const MatType &var)

References casadi::_jacobian_sparsity().

◆ join_primitives() [1/3]

DM casadi::MX::join_primitives ( const std::vector< DM > &  v) const

Inverse of split_primitives: v holds one value per primitive, with the shape of that primitive, and the result has the shape of this expression. A wrong number of pieces raises an error.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> X = vertcat(x, y)
>>> X.join_primitives([DM([1, 2]), DM([3, 4, 5])])
DM([1, 2, 3, 4, 5])
>>> try:
...   X.join_primitives([DM([1, 2])])
... except Exception as e:
...   print("Wrong number of primitives" in str(e))
True

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> X = [x; y];
>> X.join_primitives({DM([1; 2]), DM([3; 4; 5])})
[1, 2, 3, 4, 5]
>> try, X.join_primitives({DM([1; 2])}); catch e, disp('wrong number of primitives'); end
wrong number of primitives

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> X = [x; y];
julia> ca.join_primitives(X, [ca.DM([1, 2]), ca.DM([3, 4, 5])])
DM([1, 2, 3, 4, 5])
julia> try
           ca.join_primitives(X, [ca.DM([1, 2])])
       catch e
           println(occursin("Wrong number of primitives", sprint(showerror, e)))
       end
true

See also
split_primitives, primitives

Extra doc: https://github.com/casadi/casadi/wiki/L_qr

Definition at line 1013 of file mx.cpp.

1013  {
1014  casadi_assert(v.size()==n_primitives(), "Wrong number of primitives supplied");
1015  std::vector<DM>::const_iterator it=v.begin();
1016  DM ret = (*this)->join_primitives(it);
1017  casadi_assert_dev(it==v.end());
1018  return ret;
1019  }

References n_primitives().

◆ join_primitives() [2/3]

MX casadi::MX::join_primitives ( const std::vector< MX > &  v) const

Inverse of split_primitives: v holds one value per primitive, with the shape of that primitive, and the result has the shape of this expression. A wrong number of pieces raises an error.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> X = vertcat(x, y)
>>> X.join_primitives([DM([1, 2]), DM([3, 4, 5])])
DM([1, 2, 3, 4, 5])
>>> try:
...   X.join_primitives([DM([1, 2])])
... except Exception as e:
...   print("Wrong number of primitives" in str(e))
True

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> X = [x; y];
>> X.join_primitives({DM([1; 2]), DM([3; 4; 5])})
[1, 2, 3, 4, 5]
>> try, X.join_primitives({DM([1; 2])}); catch e, disp('wrong number of primitives'); end
wrong number of primitives

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> X = [x; y];
julia> ca.join_primitives(X, [ca.DM([1, 2]), ca.DM([3, 4, 5])])
DM([1, 2, 3, 4, 5])
julia> try
           ca.join_primitives(X, [ca.DM([1, 2])])
       catch e
           println(occursin("Wrong number of primitives", sprint(showerror, e)))
       end
true

See also
split_primitives, primitives

Extra doc: https://github.com/casadi/casadi/wiki/L_qr

Definition at line 997 of file mx.cpp.

997  {
998  casadi_assert(v.size()==n_primitives(), "Wrong number of primitives supplied");
999  std::vector<MX>::const_iterator it=v.begin();
1000  MX ret = (*this)->join_primitives(it);
1001  casadi_assert_dev(it==v.end());
1002  return ret;
1003  }

References casadi::MXNode::join_primitives(), and n_primitives().

Referenced by cse(), casadi::DaeBuilderInternal::der(), extract_parametric(), separate_linear(), simplify_const_folding(), and simplify_ref_count().

◆ join_primitives() [3/3]

SX casadi::MX::join_primitives ( const std::vector< SX > &  v) const

Inverse of split_primitives: v holds one value per primitive, with the shape of that primitive, and the result has the shape of this expression. A wrong number of pieces raises an error.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> X = vertcat(x, y)
>>> X.join_primitives([DM([1, 2]), DM([3, 4, 5])])
DM([1, 2, 3, 4, 5])
>>> try:
...   X.join_primitives([DM([1, 2])])
... except Exception as e:
...   print("Wrong number of primitives" in str(e))
True

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> X = [x; y];
>> X.join_primitives({DM([1; 2]), DM([3; 4; 5])})
[1, 2, 3, 4, 5]
>> try, X.join_primitives({DM([1; 2])}); catch e, disp('wrong number of primitives'); end
wrong number of primitives

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> X = [x; y];
julia> ca.join_primitives(X, [ca.DM([1, 2]), ca.DM([3, 4, 5])])
DM([1, 2, 3, 4, 5])
julia> try
           ca.join_primitives(X, [ca.DM([1, 2])])
       catch e
           println(occursin("Wrong number of primitives", sprint(showerror, e)))
       end
true

See also
split_primitives, primitives

Extra doc: https://github.com/casadi/casadi/wiki/L_qr

Definition at line 1005 of file mx.cpp.

1005  {
1006  casadi_assert(v.size()==n_primitives(), "Wrong number of primitives supplied");
1007  std::vector<SX>::const_iterator it=v.begin();
1008  SX ret = (*this)->join_primitives(it);
1009  casadi_assert_dev(it==v.end());
1010  return ret;
1011  }
Matrix< SXElem > SX
Definition: sx_fwd.hpp:32

References n_primitives().

◆ jtimes()

static MX casadi::GenericMatrix< MX >::jtimes ( const MX &  ex,
const MX &  arg,
const MX &  v,
bool  tr = false,
const Dict &  opts = Dict() 
)
staticinherited

Functions called by friend functions defined here

◆ kron()

MX casadi::MX::kron ( const MX &  x,
const MX &  b 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 2070 of file mx.cpp.

2070  {
2071  return a->get_kron(b);
2072  }

References casadi::MXNode::get_kron().

◆ kron_contract()

MX casadi::MX::kron_contract ( const MX &  m,
const MX &  x,
bool  inner 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 2074 of file mx.cpp.

2074  {
2075  return m->get_kron_contract(x, inner);
2076  }

References casadi::MXNode::get_kron_contract().

Referenced by casadi::kron_contract().

◆ lift()

MX casadi::MX::lift ( const MX &  x,
const MX &  x_guess 
)
static

Functions called by friend functions defined for this class

Definition at line 766 of file mx.cpp.

766  {
767  casadi_assert_dev(x.sparsity()==x_guess.sparsity());
768  return x->_get_binary(OP_LIFT, x_guess, false, false);
769  }
@ OP_LIFT
Definition: calculus.hpp:191

References casadi::MXNode::_get_binary(), casadi::OP_LIFT, and sparsity().

◆ linear_coeff()

void casadi::GenericMatrix< MX >::linear_coeff ( const MX &  expr,
const MX &  var,
MX &  A,
MX &  b,
bool  check 
)
staticinherited

Definition at line 674 of file generic_matrix.hpp.

5700  {
5701  casadi_assert(expr.is_vector(), "'linear_coeff' only defined for vector expressions.");
5702  if (check)
5703  casadi_assert(is_linear(expr, var), "'linear_coeff' called on non-linear expression.");
5704  A = substitute(jacobian(expr, var), var, 0);
5705  b = vec(substitute(expr, var, 0));
5706  }
static MatType vec(const MatType &x)
friend MX substitute(const MX &ex, const MX &v, const MX &vdef)
Substitute variable v with expression vdef in an expression ex.
friend MX jacobian(const MX &ex, const MX &arg, const Dict &opts=Dict())
Calculate Jacobian.

◆ linearize()

static MX casadi::GenericMatrix< MX >::linearize ( const MX &  f,
const MX &  x,
const MX &  x0,
const Dict &  opts = Dict() 
)
staticinherited

Functions called by friend functions defined here

◆ linspace() [1/2]

MX casadi::GenericMatrix< MX >::linspace ( const MX &  a,
const MX &  b,
casadi_int  nsteps 
)
staticinherited

Definition at line 661 of file generic_matrix.hpp.

5312  {
5313  casadi_assert(nsteps>=1, "linspace: nsteps (" + str(nsteps) + ") must be at least 1");
5314  std::vector<MatType> ret(nsteps);
5315  ret[0] = a;
5316  MatType step = (b-a)/static_cast<MatType>(nsteps-1);
5317 
5318  for (casadi_int i=1; i<nsteps-1; ++i)
5319  ret[i] = a + i * step;
5320 
5321  ret[nsteps-1] = b;
5322  return vertcat(ret);
5323  }

◆ linspace() [2/2]

MX casadi::MX::linspace ( const MX &  a,
const MX &  b,
casadi_int  nsteps 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2096 of file mx.cpp.

2096  {
2097  // Specialized over GenericMatrix<MX>::linspace to keep the MX graph
2098  // O(1) in nsteps. The FP recipe (a + i*step interior, literal b at
2099  // the endpoint) matches the generic implementation and numpy.linspace
2100  // bit-for-bit; see test_linspace in test/python/matrix.py.
2101  if (nsteps < 2) return b;
2102  MX step = (b - a) / static_cast<double>(nsteps - 1);
2103  std::vector<double> idx(nsteps - 1);
2104  for (casadi_int i = 0; i < nsteps - 1; ++i) idx[i] = static_cast<double>(i);
2105  return vertcat(std::vector<MX>{a + DM(idx) * step, b});
2106  }

References vertcat().

◆ logsumexp()

static MX casadi::GenericMatrix< MX >::logsumexp ( const MX &  x)
staticinherited

◆ low()

MX casadi::MX::low ( const MX &  v,
const MX &  p,
const Dict &  options = Dict() 
)
static

Functions called by friend functions defined for this class

Definition at line 2213 of file mx.cpp.

2213  {
2214  return p->get_low(v, options);
2215  }

References casadi::MXNode::get_low().

Referenced by interpn_linear().

◆ mac()

MX casadi::MX::mac ( const MX &  x,
const MX &  y,
const MX &  z,
const std::string &  blas = "reference" 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 715 of file mx.cpp.

715  {
716  if (x.is_scalar() || y.is_scalar()) {
717  // Use element-wise multiplication if at least one factor scalar
718  return z + x*y;
719  }
720 
721  // Check matching dimensions
722  casadi_assert(x.size2()==y.size1(),
723  "Matrix product with incompatible dimensions. Lhs is "
724  + x.dim() + " and rhs is " + y.dim() + ".");
725 
726  // Check if we can simplify the product
727  if (x.is_eye()) {
728  return y + z;
729  } else if (y.is_eye()) {
730  return x + z;
731  } else if (x.is_zero() || y.is_zero()) {
732  return z;
733  } else {
734  return x->get_mac(y, z, blas);
735  }
736  }

References casadi::GenericMatrix< MatType >::dim(), casadi::MXNode::get_mac(), is_eye(), casadi::GenericMatrix< MatType >::is_scalar(), is_zero(), casadi::GenericMatrix< MatType >::size1(), and casadi::GenericMatrix< MatType >::size2().

Referenced by mtimes().

◆ mapping()

Matrix< casadi_int > casadi::MX::mapping ( ) const

For a slicing node (x[...], x.nz[...]) returns the indices of the nonzeros of the dependency that make up the result; for an assignment node, the target indices. Any other node raises an error.

>>> X = MX.sym("X", 3, 3)
>>> X[0, 1].mapping(), X[:, 1].mapping()
(DM(3), DM([3, 4, 5]))
>>> try:
...   X.mapping()
... except Exception as e:
...   print("'mapping' not defined" in str(e))
True

>> X = MX.sym('X', 3, 3);
>> a = X(1, 2); b = X(:, 2);
>> a.mapping(), b.mapping()
3
[3, 4, 5]
>> try, X.mapping(); catch e, disp('error'); end
error

julia> X = ca.MX.sym("X", 3, 3);
julia> ca.mapping(X[1, 2]), ca.mapping(X[:, 2])
([3;;], [3; 4; 5;;])
julia> try
           ca.mapping(X)
       catch e
           println(occursin("'mapping' not defined", sprint(showerror, e)))
       end
true

See also
info

Extra doc: https://github.com/casadi/casadi/wiki/L_ri

Definition at line 889 of file mx.cpp.

889  {
890  return (*this)->mapping();
891  }

Referenced by diag(), erase(), get(), and unite().

◆ matrix_expand() [1/2]

MX casadi::MX::matrix_expand ( const MX &  e,
const std::vector< MX > &  boundary,
const Dict &  options 
)
static

Functions called by friend functions defined for this class

Definition at line 2039 of file mx.cpp.

2039  {
2040  return matrix_expand(std::vector<MX>{e}, boundary, options).at(0);
2041  }
static MX matrix_expand(const MX &e, const std::vector< MX > &boundary, const Dict &options)
Definition: mx.cpp:2039

◆ matrix_expand() [2/2]

std::vector< MX > casadi::MX::matrix_expand ( const std::vector< MX > &  e,
const std::vector< MX > &  boundary,
const Dict &  options 
)
static

Functions called by friend functions defined for this class

Definition at line 2043 of file mx.cpp.

2045  {
2046 
2047  // Create symbols for boundary nodes
2048  std::vector<MX> syms(boundary.size());
2049 
2050  for (casadi_int i=0;i<syms.size();++i) {
2051  syms[i] = MX::sym("x", boundary[i].sparsity());
2052  }
2053 
2054  // Substitute symbols for boundary nodes
2055  std::vector<MX> ret = graph_substitute(e, boundary, syms);
2056 
2057  // Obtain list of dependents
2058  std::vector<MX> v = symvar(veccat(ret));
2059 
2060  // Construct an MXFunction with it
2061  Function f("tmp_matrix_expand", v, ret, Dict{{"max_io", 0}, {"allow_free", true}});
2062 
2063  // Expand to SXFunction
2064  Function s = f.expand("expand_" + f.name(), options);
2065  std::vector<MX> r;
2066  s.call(graph_substitute(v, syms, boundary), r);
2067  return r;
2068  }

References casadi::Function::call(), casadi::Function::expand(), graph_substitute(), sparsity(), casadi::GenericMatrix< MX >::sym(), symvar(), and casadi::SparsityInterface< MatType >::veccat().

◆ mldivide()

MX casadi::MX::mldivide ( const MX &  a,
const MX &  b 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 781 of file mx.cpp.

781  {
782  if (a.is_scalar() || b.is_scalar()) return b/a;
783  return solve(a, b);
784  }

References casadi::GenericMatrix< MatType >::is_scalar(), and solve().

◆ mmax()

MX casadi::MX::mmax ( const MX &  x)
static

Functions called by friend functions defined for GenericExpression

Definition at line 878 of file mx.cpp.

878  {
879  return x->get_mmax();
880  }

References casadi::MXNode::get_mmax().

◆ mmin()

MX casadi::MX::mmin ( const MX &  x)
static

Functions called by friend functions defined for GenericExpression

Definition at line 874 of file mx.cpp.

874  {
875  return x->get_mmin();
876  }

References casadi::MXNode::get_mmin().

◆ monitor()

MX casadi::MX::monitor ( const std::string &  comment) const

When the returned expression is evaluated, comment followed by the nonzeros is printed to standard output. The value is unchanged. A matrix without nonzeros is returned as is.

>>> x = MX.sym("x")
>>> e = x.monitor("value of x")
>>> e, e.is_op(OP_MONITOR)
(MX(monitor(x, value of x)), True)

>> x = MX.sym('x');
>> e = x.monitor('value of x');
>> e, e.is_op(OP_MONITOR)
monitor(x, value of x)
1

julia> x = ca.MX.sym("x");
julia> e = ca.monitor(x, "value of x");
julia> e, ca.is_op(e, ca.OP_MONITOR)
(monitor(x, value of x), true)

See also
printme, dump, attachAssert

Extra doc: https://github.com/casadi/casadi/wiki/L_rh

Definition at line 753 of file mx.cpp.

753  {
754  return(*this)->get_monitor(comment);
755  }

References casadi::MXNode::get_monitor().

◆ mpower()

static MX casadi::GenericMatrix< MX >::mpower ( const MX &  x,
const MX &  y 
)
staticinherited

Functions called by friend functions defined here

◆ mrdivide()

MX casadi::MX::mrdivide ( const MX &  a,
const MX &  b 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 776 of file mx.cpp.

776  {
777  if (a.is_scalar() || b.is_scalar()) return b/a;
778  return solve(a.T(), b.T()).T();
779  }
MX T() const
Transpose the matrix.
Definition: mx.cpp:1098

References casadi::GenericMatrix< MatType >::is_scalar(), solve(), and T().

◆ mtimes()

MX casadi::MX::mtimes ( const MX &  x,
const MX &  y,
const std::string &  blas = "reference" 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 675 of file mx.cpp.

675  {
676  if (x.is_scalar() || y.is_scalar()) {
677  // Use element-wise multiplication if at least one factor scalar
678  return x*y;
679  } else {
680  MX z = MX::zeros(Sparsity::mtimes(x.sparsity(), y.sparsity()));
681  return mac(x, y, z, blas);
682  }
683  }
static MX mac(const MX &x, const MX &y, const MX &z, const std::string &blas="reference")
Definition: mx.cpp:715
static Sparsity mtimes(const Sparsity &x, const Sparsity &y, const std::string &blas="reference")
Accessed by SparsityInterface.
Definition: sparsity.cpp:432

References casadi::GenericMatrix< MatType >::is_scalar(), mac(), casadi::Sparsity::mtimes(), sparsity(), and casadi::GenericMatrix< MX >::zeros().

Referenced by pinv(), solve(), sum1(), and sum2().

◆ n_dep()

casadi_int casadi::MX::n_dep ( ) const

Zero for symbolic primitives and constants, one for unary operations and projections, two for binary operations, the number of arguments for concatenations and Function calls.

>>> x = MX.sym("x")
>>> A = MX.sym("A", 2, 2)
>>> x.n_dep(), sin(x).n_dep(), (x + 1).n_dep(), vertcat(x, x, x).n_dep()
(0, 1, 2, 3)
>>> (A @ A).n_dep(), A[0, 0].n_dep(), MX(1).n_dep()
(3, 1, 0)

>> x = MX.sym('x'); A = MX.sym('A', 2, 2);
>> e = x + 1; v = vertcat(x, x, x);
>> x.n_dep(), sin(x).n_dep(), e.n_dep(), v.n_dep()
0
1
2
3
>> P = A*A; a = A(1, 1);
>> P.n_dep(), a.n_dep(), MX(1).n_dep()
3
1
0

julia> x = ca.MX.sym("x"); A = ca.MX.sym("A", 2, 2);
julia> ca.n_dep(x), ca.n_dep(sin(x)), ca.n_dep(x + 1), ca.n_dep([x; x; x])
(0, 1, 2, 3)
julia> ca.n_dep(A * A), ca.n_dep(A[1, 1]), ca.n_dep(ca.MX(1))
(3, 1, 0)

See also
dep

Extra doc: https://github.com/casadi/casadi/wiki/L_qm

Definition at line 790 of file mx.cpp.

790  {
791  return (*this)->n_dep();
792  }

Referenced by casadi::DaeBuilderInternal::create(), eval_mx(), casadi::DaeBuilderInternal::load_fmi_description(), and print_operator().

◆ n_nodes()

casadi_int casadi::MX::n_nodes ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1466 of file mx.cpp.

1466  {
1467  Dict opts{{"max_io", 0}, {"cse", false}, {"allow_free", true}};
1468  Function f("tmp_n_nodes", std::vector<MX>{}, {x}, opts);
1469  return f.n_nodes();
1470  }

References casadi::Function::n_nodes().

◆ n_out()

casadi_int casadi::MX::n_out ( ) const

Greater than one only for multiple-output nodes, i.e. a call to a Function with several outputs. Every other node, including the OutputNode that selects one output of such a call, reports 1.

>>> a = SX.sym("a")
>>> f = Function("f", [a], [a + 1, 2*a])
>>> x = MX.sym("x")
>>> r0, r1 = f(x, )
>>> call = r0.dep(0)
>>> call, call.n_out(), r0.n_out()
(MX(f(x)), 2, 1)

>> a = SX.sym('a');
>> f = Function('f', {a}, {a + 1, 2*a});
>> x = MX.sym('x');
>> [r0, r1] = f(x);
>> call = r0.dep(0);
>> call, call.n_out(), r0.n_out()
f(x)
2
1

julia> a = ca.SX.sym("a");
julia> f = ca.Function("f", [a], [a + 1, 2 * a]);
julia> x = ca.MX.sym("x");
julia> r0, r1 = f(x);
julia> call = ca.dep(r0, 0);
julia> call, ca.n_out(call), ca.n_out(r0)
(f(x), 2, 1)

See also
get_output, has_output, is_output

Extra doc: https://github.com/casadi/casadi/wiki/L_qk

Definition at line 901 of file mx.cpp.

901  {
902  return (*this)->nout();
903  }

Referenced by casadi::DaeBuilderInternal::create(), and interpn_linear().

◆ n_primitives()

casadi_int casadi::MX::n_primitives ( ) const

For an expression that is not a valid input the count is 1 (the expression itself); check is_valid_input first.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> vertcat(x, y).n_primitives(), x.n_primitives()
(2, 1)

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> v = [x; y];
>> v.n_primitives(), x.n_primitives()
2
1

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> ca.n_primitives([x; y]), ca.n_primitives(x)
(2, 1)

See also
primitives, is_valid_input

Extra doc: https://github.com/casadi/casadi/wiki/L_qo

Definition at line 961 of file mx.cpp.

961  {
962  return (*this)->n_primitives();
963  }

Referenced by cse(), extract_parametric(), graph_substitute(), join_primitives(), primitives(), separate_linear(), simplify_const_folding(), simplify_ref_count(), and split_primitives().

◆ name()

std::string casadi::MX::name ( ) const

Only defined for nodes created by MX.sym; any other node raises an error. Check with is_symbolic first.

>>> x = MX.sym("x", 2)
>>> x.name()
'x'
>>> try:
...   (x + 1).name()
... except Exception as e:
...   print("'name' not defined" in str(e))
True

>> x = MX.sym('x', 2);
>> x.name()
x
>> e = x + 1;
>> try, e.name(); catch err, disp('error'); end
error

julia> x = ca.MX.sym("x", 2);
julia> ca.name(x)
"x"
julia> try
           ca.name(x + 1)
       catch e
           println(occursin("'name' not defined", sprint(showerror, e)))
       end
true

See also
is_symbolic, symvar

Extra doc: https://github.com/casadi/casadi/wiki/L_2pr

Definition at line 794 of file mx.cpp.

794  {
795  return (*this)->name();
796  }

Referenced by _sym(), casadi::DaeBuilder::add(), casadi::OptiNode::describe(), casadi::DaeBuilderInternal::find(), casadi::DaeBuilderInternal::import_binding_equations(), casadi::DaeBuilderInternal::import_dynamic_equations(), casadi::DaeBuilderInternal::import_model_variables(), casadi::DaeBuilderInternal::load_fmi_description(), and MX().

◆ nan() [1/3]

MX casadi::MX::nan ( casadi_int  nrow = 1,
casadi_int  ncol = 1 
)
static

Dense nrow-by-ncol (default 1-by-1), or with the given sparsity pattern.

>>> MX.nan(), MX.nan(Sparsity.lower(2))
(MX(nan), MX(nan(2x2,3nz)))

>> MX.nan(), MX.nan(Sparsity.lower(2))
nan
nan(2x2,3nz)

julia> ca.MX.nan(), ca.MX.nan(ca.Sparsity.lower(2))
(nan, nan(2x2,3nz))

See also
inf

Extra doc: https://github.com/casadi/casadi/wiki/L_r3

Definition at line 591 of file mx.cpp.

591  {
592  return nan(Sparsity::dense(nrow, ncol));
593  }
static MX nan(const Sparsity &sp)
Create a constant with all nonzeros NaN.
Definition: mx.cpp:599

References casadi::Sparsity::dense(), and nan().

◆ nan() [2/3]

MX casadi::MX::nan ( const Sparsity &  sp)
static

Dense nrow-by-ncol (default 1-by-1), or with the given sparsity pattern.

>>> MX.nan(), MX.nan(Sparsity.lower(2))
(MX(nan), MX(nan(2x2,3nz)))

>> MX.nan(), MX.nan(Sparsity.lower(2))
nan
nan(2x2,3nz)

julia> ca.MX.nan(), ca.MX.nan(ca.Sparsity.lower(2))
(nan, nan(2x2,3nz))

See also
inf

Extra doc: https://github.com/casadi/casadi/wiki/L_r3

Definition at line 599 of file mx.cpp.

599  {
600  return create(ConstantMX::create(sp, std::numeric_limits<double>::quiet_NaN()));
601  }

References casadi::ConstantMX::create(), and create().

Referenced by casadi::MXNode::_get_binary(), nan(), and casadi::qpsol_nlp().

◆ nan() [3/3]

MX casadi::MX::nan ( const std::pair< casadi_int, casadi_int > &  rc)
static

Dense nrow-by-ncol (default 1-by-1), or with the given sparsity pattern.

>>> MX.nan(), MX.nan(Sparsity.lower(2))
(MX(nan), MX(nan(2x2,3nz)))

>> MX.nan(), MX.nan(Sparsity.lower(2))
nan
nan(2x2,3nz)

julia> ca.MX.nan(), ca.MX.nan(ca.Sparsity.lower(2))
(nan, nan(2x2,3nz))

See also
inf

Extra doc: https://github.com/casadi/casadi/wiki/L_r3

Definition at line 595 of file mx.cpp.

595  {
596  return nan(rc.first, rc.second);
597  }

References nan().

◆ nnz()

casadi_int casadi::GenericMatrix< MX >::nnz
inherited

Counts the entries present in the sparsity pattern. Entries that are stored but numerically zero still count; structural zeros (not stored) do not. For a dense matrix this equals numel().

>>> DM.eye(3).nnz(), DM.ones(3, 3).nnz(), DM(3, 3).nnz()
(3, 9, 0)
>>> DM([[1, 0], [0, 2]]).nnz()
4
>>> MX.sym("x", 2, 0).nnz()
0

>> fprintf('%d %d %d\n', DM.eye(3).nnz(), DM.ones(3, 3).nnz(), DM(3, 3).nnz())
3 9 0
>> DM([1 0; 0 2]).nnz()
4
>> MX.sym('x', 2, 0).nnz()
0

julia> ca.nnz(ca.DM.eye(3)), ca.nnz(ca.DM.ones(3, 3)), ca.nnz(ca.DM(3, 3))
(3, 9, 0)
julia> ca.nnz(ca.DM([1 0; 0 2]))
4
julia> ca.nnz(ca.MX.sym("x", 2, 0))
0

See also
numel, nnz_lower, nnz_upper, nnz_diag, sparsity

Extra doc: https://github.com/casadi/casadi/wiki/L_1an

Definition at line 123 of file generic_matrix.hpp.

5229  {
5230  return sparsity().nnz();
5231  }
casadi_int nnz() const
Number of structural nonzeros.
Definition: sparsity.cpp:150

◆ nnz_diag()

casadi_int casadi::GenericMatrix< MX >::nnz_diag
inherited

Also defined for non-square matrices.

>>> DM.ones(3, 3).nnz_diag(), DM.eye(3).nnz_diag(), DM.ones(2, 3).nnz_diag()
(3, 3, 2)

>> A = DM.ones(3, 3); I = DM.eye(3); B = DM.ones(2, 3);
>> fprintf('%d %d %d\n', A.nnz_diag(), I.nnz_diag(), B.nnz_diag())
3 3 2

julia> A = ca.DM.ones(3, 3); I = ca.DM.eye(3); B = ca.DM.ones(2, 3);
julia> ca.nnz_diag(A), ca.nnz_diag(I), ca.nnz_diag(B)
(3, 3, 2)

See also
nnz, nnz_lower, nnz_upper

Extra doc: https://github.com/casadi/casadi/wiki/L_1aq

Definition at line 215 of file generic_matrix.hpp.

5244  {
5245  return sparsity().nnz_diag();
5246  }
casadi_int nnz_diag() const
Number of nonzeros on the main diagonal, i.e. entries (i, i)
Definition: sparsity.cpp:362

◆ nnz_lower()

casadi_int casadi::GenericMatrix< MX >::nnz_lower
inherited

>>> DM.ones(3, 3).nnz_lower(), DM.eye(3).nnz_lower(), DM.ones(2, 3).nnz_lower()
(6, 3, 3)

>> A = DM.ones(3, 3); I = DM.eye(3); B = DM.ones(2, 3);
>> fprintf('%d %d %d\n', A.nnz_lower(), I.nnz_lower(), B.nnz_lower())
6 3 3

julia> A = ca.DM.ones(3, 3); I = ca.DM.eye(3); B = ca.DM.ones(2, 3);
julia> ca.nnz_lower(A), ca.nnz_lower(I), ca.nnz_lower(B)
(6, 3, 3)

See also
nnz, nnz_upper, nnz_diag

Extra doc: https://github.com/casadi/casadi/wiki/L_1ao

Definition at line 153 of file generic_matrix.hpp.

5234  {
5235  return sparsity().nnz_lower();
5236  }
casadi_int nnz_lower(bool strictly=false) const
Number of nonzeros in the lower triangular part, i.e. entries (i, j) with i >= j.
Definition: sparsity.cpp:354

◆ nnz_upper()

casadi_int casadi::GenericMatrix< MX >::nnz_upper
inherited

>>> DM.ones(3, 3).nnz_upper(), DM.eye(3).nnz_upper(), DM.ones(2, 3).nnz_upper()
(6, 3, 5)

>> A = DM.ones(3, 3); I = DM.eye(3); B = DM.ones(2, 3);
>> fprintf('%d %d %d\n', A.nnz_upper(), I.nnz_upper(), B.nnz_upper())
6 3 5

julia> A = ca.DM.ones(3, 3); I = ca.DM.eye(3); B = ca.DM.ones(2, 3);
julia> ca.nnz_upper(A), ca.nnz_upper(I), ca.nnz_upper(B)
(6, 3, 5)

See also
nnz, nnz_lower, nnz_diag

Extra doc: https://github.com/casadi/casadi/wiki/L_1ap

Definition at line 183 of file generic_matrix.hpp.

5239  {
5240  return sparsity().nnz_upper();
5241  }
casadi_int nnz_upper(bool strictly=false) const
Number of nonzeros in the upper triangular part, i.e. entries (i, j) with i <= j.
Definition: sparsity.cpp:358

◆ norm_0_mul()

static casadi_int casadi::GenericMatrix< MX >::norm_0_mul ( const MX &  x,
const MX &  y 
)
inlinestaticinherited

Definition at line 651 of file generic_matrix.hpp.

651  {
652  return Sparsity::norm_0_mul(x.sparsity(), y.sparsity());
653  }

◆ norm_1()

MX casadi::MX::norm_1 ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1287 of file mx.cpp.

1287  {
1288  return x->get_norm_1();
1289  }

References casadi::MXNode::get_norm_1().

◆ norm_2()

MX casadi::MX::norm_2 ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1275 of file mx.cpp.

1275  {
1276  if (x.is_vector()) {
1277  return norm_fro(x);
1278  } else {
1279  return x->get_norm_2();
1280  }
1281  }
static MX norm_fro(const MX &x)
Definition: mx.cpp:1283

References casadi::MXNode::get_norm_2(), casadi::GenericMatrix< MatType >::is_vector(), and norm_fro().

◆ norm_fro()

MX casadi::MX::norm_fro ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1283 of file mx.cpp.

1283  {
1284  return x->get_norm_fro();
1285  }

References casadi::MXNode::get_norm_fro().

Referenced by norm_2().

◆ norm_inf()

MX casadi::MX::norm_inf ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1291 of file mx.cpp.

1291  {
1292  return x->get_norm_inf();
1293  }

References casadi::MXNode::get_norm_inf().

◆ nullspace()

MX casadi::MX::nullspace ( const MX &  A)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2152 of file mx.cpp.

2152  {
2153  SX A_sx = SX::sym("A", A.sparsity());
2154  Function f("nullspace", {A_sx}, {SX::nullspace(A_sx)});
2155  return f(A).at(0);
2156  }
static Matrix< Scalar > nullspace(const Matrix< Scalar > &x)

References casadi::Matrix< Scalar >::nullspace(), sparsity(), and casadi::GenericMatrix< Matrix< Scalar > >::sym().

◆ numel()

casadi_int casadi::GenericMatrix< MX >::numel
inherited

Counts all entries, structural zeros included.

>>> DM.eye(3).numel(), MX.sym("x", 2, 0).numel(), SX.sym("x").numel()
(9, 0, 1)

>> fprintf('%d %d %d\n', DM.eye(3).numel(), MX.sym('x', 2, 0).numel(), SX.sym('x').numel())
9 0 1

julia> ca.numel(ca.DM.eye(3)), ca.numel(ca.MX.sym("x", 2, 0)), ca.numel(ca.SX.sym("x"))
(9, 0, 1)
julia> length(ca.DM.eye(3))
9

See also
nnz, size

Extra doc: https://github.com/casadi/casadi/wiki/L_1ar

Definition at line 247 of file generic_matrix.hpp.

5249  {
5250  return sparsity().numel();
5251  }
casadi_int numel() const
Total number of entries, structural zeros included, i.e. size1()*size2()
Definition: sparsity.cpp:132

◆ nz() [1/2]

NonZeros<MX , K> casadi::GenericMatrix< MX >::nz ( const K &  k)
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1bc

Definition at line 693 of file generic_matrix.hpp.

693  {
694  return NonZeros<MatType, K>(self(), k);
695  }

◆ nz() [2/2]

const MX casadi::GenericMatrix< MX >::nz ( const K &  k) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1bb

Definition at line 683 of file generic_matrix.hpp.

683  {
684  MatType ret;
685  self().get_nz(ret, false, k);
686  return ret;
687  }

◆ nzref()

MX casadi::MX::nzref ( const Sparsity &  sp,
const std::vector< casadi_int > &  nz 
) const

Intended for writing unittests

Extra doc: https://github.com/casadi/casadi/wiki/L_2er

Definition at line 150 of file mx.cpp.

150  {
151  return (*this)->get_nzref(sp, nz);
152  }

References casadi::MXNode::get_nzref(), and casadi::GenericMatrix< MX >::nz().

◆ ones() [1/3]

static MX casadi::GenericMatrix< MX >::ones ( casadi_int  nrow = 1,
casadi_int  ncol = 1 
)
inlinestaticinherited

ones(sp) sets every structural nonzero of sp to one; other entries stay structurally zero.

>>> DM.ones(2, 3)
DM(
[[1, 1, 1],
 [1, 1, 1]])
>>> DM.ones(Sparsity.diag(2))
DM(
[[1, 00],
 [00, 1]])

>> DM.ones(2, 3)
[[1, 1, 1],
 [1, 1, 1]]
>> DM.ones(Sparsity.diag(2))
[[1, 00],
 [00, 1]]

julia> ca.DM.ones(2, 3)
DM(
[[1, 1, 1],
 [1, 1, 1]])
julia> ca.DM.ones(ca.Sparsity.diag(2))
DM(
[[1, 00],
 [00, 1]])

See also
zeros, Sparsity

Extra doc: https://github.com/casadi/casadi/wiki/L_1di

Definition at line 5206 of file generic_matrix.hpp.

5206  {
5207  return ones(Sparsity::dense(nrow, ncol));
5208  }
static MX ones(casadi_int nrow=1, casadi_int ncol=1)
Create a dense matrix or a matrix with specified sparsity with all entries one.

◆ ones() [2/3]

static MX casadi::GenericMatrix< MX >::ones ( const Sparsity &  sp)
inlinestaticinherited

ones(sp) sets every structural nonzero of sp to one; other entries stay structurally zero.

>>> DM.ones(2, 3)
DM(
[[1, 1, 1],
 [1, 1, 1]])
>>> DM.ones(Sparsity.diag(2))
DM(
[[1, 00],
 [00, 1]])

>> DM.ones(2, 3)
[[1, 1, 1],
 [1, 1, 1]]
>> DM.ones(Sparsity.diag(2))
[[1, 00],
 [00, 1]]

julia> ca.DM.ones(2, 3)
DM(
[[1, 1, 1],
 [1, 1, 1]])
julia> ca.DM.ones(ca.Sparsity.diag(2))
DM(
[[1, 00],
 [00, 1]])

See also
zeros, Sparsity

Extra doc: https://github.com/casadi/casadi/wiki/L_1di

Definition at line 5209 of file generic_matrix.hpp.

5209 { return MatType(sp, 1, false);}

◆ ones() [3/3]

static MX casadi::GenericMatrix< MX >::ones ( const std::pair< casadi_int, casadi_int > &  rc)
inlinestaticinherited

ones(sp) sets every structural nonzero of sp to one; other entries stay structurally zero.

>>> DM.ones(2, 3)
DM(
[[1, 1, 1],
 [1, 1, 1]])
>>> DM.ones(Sparsity.diag(2))
DM(
[[1, 00],
 [00, 1]])

>> DM.ones(2, 3)
[[1, 1, 1],
 [1, 1, 1]]
>> DM.ones(Sparsity.diag(2))
[[1, 00],
 [00, 1]]

julia> ca.DM.ones(2, 3)
DM(
[[1, 1, 1],
 [1, 1, 1]])
julia> ca.DM.ones(ca.Sparsity.diag(2))
DM(
[[1, 00],
 [00, 1]])

See also
zeros, Sparsity

Extra doc: https://github.com/casadi/casadi/wiki/L_1di

Definition at line 5210 of file generic_matrix.hpp.

5210  {
5211  return ones(rc.first, rc.second);
5212  }

◆ op()

casadi_int casadi::MX::op ( ) const

Returns one of the OP_* constants. Every node, not only elementwise operations, has an operation code (OP_PARAMETER, OP_CONST, OP_CALL, OP_MTIMES, OP_GETNONZEROS, ...). Function print_operator shows the symbol of an operation.

>>> x = MX.sym("x")
>>> x.op() == OP_PARAMETER, (x + 1).op() == OP_ADD, MX(1).op() == OP_CONST
(True, True, True)
>>> print_operator(x + 1, ["a", "b"])
'(a+b)'

>> x = MX.sym('x'); e = x + 1;
>> x.op() == OP_PARAMETER, e.op() == OP_ADD, MX(1).op() == OP_CONST
1
1
1
>> print_operator(x + 1, {'a', 'b'})
(a+b)

julia> x = ca.MX.sym("x");
julia> ca.op(x) == ca.OP_PARAMETER, ca.op(x + 1) == ca.OP_ADD,
       ca.op(ca.MX(1)) == ca.OP_CONST
(true, true, true)
julia> ca.print_operator(x + 1, ["a", "b"])
"(a+b)"

See also
is_op, print_operator

Extra doc: https://github.com/casadi/casadi/wiki/L_2q8

Definition at line 854 of file mx.cpp.

854  {
855  return (*this)->op();
856  }

Referenced by casadi::UnaryMX::_get_binary(), binary(), cse(), extract(), extract_parametric(), forward(), casadi::MXNode::get_binary(), interpn_linear(), is_commutative(), is_doubled(), is_op(), is_transpose(), casadi::MXFunction::MXFunction(), reset_dump_count(), reverse(), and unary().

◆ operator double()

casadi::MX::operator double ( ) const
explicit

Raises an error for symbolic nodes and for constants that are not 1-by-1.

>>> float(MX(2))
2.0
>>> try:
...   float(MX.sym("x"))
... except Exception as e:
...   print("'to_double' not defined" in str(e))
True

>> MX(2).to_double()
2
>> try, MX.sym('x').to_double(); catch e, disp('error'); end
error

julia> Float64(ca.MX(2))
2.0
julia> try
           Float64(ca.MX.sym("x"))
       catch e
           println(occursin("requires a constant scalar", sprint(showerror, e)))
       end
true

See also
to_DM, evalf

Extra doc: https://github.com/casadi/casadi/wiki/L_2ps

Definition at line 838 of file mx.cpp.

838  {
839  return (*this)->to_double();
840  }

References casadi::MXNode::to_double().

◆ operator Matrix< double >()

casadi::MX::operator Matrix< double > ( ) const
explicit

Only defined for constant nodes (is_constant). For a general expression without free symbols use evalf instead. Not defined for constants created from a file or with a pool name.

>>> MX(DM([[1, 2], [3, 4]])).to_DM()
DM(
[[1, 2],
 [3, 4]])
>>> try:
...   (MX.sym("x") + 1).to_DM()
... except Exception as e:
...   print("'get_DM' not defined" in str(e))
True

>> MX(DM([1 2; 3 4])).to_DM()
[[1, 2],
 [3, 4]]
>> e = MX.sym('x') + 1;
>> try, e.to_DM(); catch err, disp('error'); end
error

julia> ca.to_DM(ca.MX(ca.DM([1 2; 3 4])))
DM(
[[1, 2],
 [3, 4]])
julia> try
           ca.to_DM(ca.MX.sym("x") + 1)
       catch e
           println(occursin("'get_DM' not defined", sprint(showerror, e)))
       end
true

See also
evalf, is_constant

Extra doc: https://github.com/casadi/casadi/wiki/L_2pt

◆ operator()() [1/4]

SubIndex<MX , RR> casadi::GenericMatrix< MX >::operator() ( const RR &  rr)
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1bf

Definition at line 721 of file generic_matrix.hpp.

721  {
722  return SubIndex<MatType, RR>(self(), rr);
723  }

◆ operator()() [2/4]

const MX casadi::GenericMatrix< MX >::operator() ( const RR &  rr) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1bd

Definition at line 701 of file generic_matrix.hpp.

701  {
702  MatType ret;
703  self().get(ret, false, rr);
704  return ret;
705  }

◆ operator()() [3/4]

SubMatrix<MX , RR, CC> casadi::GenericMatrix< MX >::operator() ( const RR &  rr,
const CC &  cc 
)
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1bg

Definition at line 729 of file generic_matrix.hpp.

729  {
730  return SubMatrix<MatType, RR, CC>(self(), rr, cc);
731  }

◆ operator()() [4/4]

const MX casadi::GenericMatrix< MX >::operator() ( const RR &  rr,
const CC &  cc 
) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1be

Definition at line 711 of file generic_matrix.hpp.

711  {
712  MatType ret;
713  self().get(ret, false, rr, cc);
714  return ret;
715  }

◆ operator+()

MX casadi::MX::operator+ ( ) const
inline

Definition at line 798 of file mx.hpp.

798 { return *this; }

◆ operator-()

MX casadi::MX::operator- ( ) const

Negating a negation returns the original node.

>>> x = MX.sym("x")
>>> -x, -(-x)
(MX((-x)), MX(x))

>> x = MX.sym('x');
>> -x, -(-x)
(-x)
x

julia> x = ca.MX.sym("x");
julia> -x, -(-x)
((-x), x)

Extra doc: https://github.com/casadi/casadi/wiki/L_2pq

Definition at line 607 of file mx.cpp.

607  {
608  if ((*this)->op()==OP_NEG) {
609  return (*this)->dep(0);
610  } else {
611  return (*this)->get_unary(OP_NEG);
612  }
613  }
@ OP_NEG
Definition: calculus.hpp:66

References casadi::MXNode::dep(), casadi::MXNode::get_unary(), and casadi::OP_NEG.

◆ operator->() [1/2]

MXNode * casadi::MX::operator-> ( )

Extra doc: https://github.com/casadi/casadi/wiki/L_qh

Definition at line 571 of file mx.cpp.

571  {
572  return static_cast<MXNode*>(SharedObject::operator->());
573  }
SharedObjectInternal * operator->() const
Access a member function or object.

References casadi::GenericShared< SharedObject, SharedObjectInternal >::operator->().

◆ operator->() [2/2]

const MXNode * casadi::MX::operator-> ( ) const

Extra doc: https://github.com/casadi/casadi/wiki/L_qi

Definition at line 575 of file mx.cpp.

575  {
576  return static_cast<const MXNode*>(SharedObject::operator->());
577  }

References casadi::GenericShared< SharedObject, SharedObjectInternal >::operator->().

◆ own()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::own ( Internal *  node)
inherited

Assign the node to a node class pointer (or null)

Definition at line 89 of file generic_shared_impl.hpp.

◆ pinv()

MX casadi::MX::pinv ( const MX &  A,
const std::string &  lsolver = "qr",
const Dict &  dict = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2132 of file mx.cpp.

2132  {
2133  if (A.size1()>=A.size2()) {
2134  return solve(mtimes(A.T(), A), A.T(), lsolver, dict);
2135  } else {
2136  return solve(mtimes(A, A.T()), A, lsolver, dict).T();
2137  }
2138  }
static MX mtimes(const MX &x, const MX &y, const std::string &blas="reference")
Definition: mx.cpp:675

References mtimes(), casadi::GenericMatrix< MatType >::size1(), casadi::GenericMatrix< MatType >::size2(), solve(), and T().

◆ polyval()

MX casadi::MX::polyval ( const MX &  p,
const MX &  x 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1480 of file mx.cpp.

1480  {
1481  casadi_assert(p.is_dense(), "polynomial coefficients vector must be dense");
1482  casadi_assert(p.is_vector() && p.nnz()>0, "polynomial coefficients must be a vector");
1483  MX ret = p.nz(0);
1484  for (casadi_int i=1; i<p.nnz(); ++i) {
1485  ret = ret*x + p.nz(i);
1486  }
1487  return ret;
1488  }

References casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_vector(), casadi::GenericMatrix< MatType >::nnz(), and casadi::GenericMatrix< MatType >::nz().

◆ primitives()

std::vector< MX > casadi::MX::primitives ( ) const

Returns the symbolic primitives in the order in which they appear in the concatenation. For an expression that is not a valid input, the expression itself is returned.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> vertcat(x, y).primitives()
[MX(x), MX(y)]
>>> reshape(x, 1, 2).primitives()
[MX(x)]

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> v = [x; y];
>> p = v.primitives();
>> numel(p), p{1}, p{2}
2
x
y
>> p = reshape(x, 1, 2).primitives();
>> numel(p), p{1}
1
x

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> ca.primitives([x; y])
2-element Vector{MX}:
 MX(x)
 MX(y)
julia> ca.primitives(reshape(x, 1, 2))
1-element Vector{MX}:
 MX(x)

See also
n_primitives, split_primitives, join_primitives, is_valid_input

Extra doc: https://github.com/casadi/casadi/wiki/L_qp

Definition at line 965 of file mx.cpp.

965  {
966  std::vector<MX> ret(n_primitives());
967  std::vector<MX>::iterator it=ret.begin();
968  (*this)->primitives(it);
969  casadi_assert_dev(it==ret.end());
970  return ret;
971  }

References n_primitives().

Referenced by casadi::DaeBuilderInternal::der(), get_nonzeros(), casadi::DaeBuilderInternal::load_fmi_description(), casadi::OptiNode::set_domain(), and casadi::OptiNode::to_function().

◆ print_operator()

std::string casadi::MX::print_operator ( const MX &  x,
const std::vector< std::string > &  args 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1490 of file mx.cpp.

1490  {
1491  casadi_assert(args.size()>=x.n_dep(),
1492  "Expected " + str(x.n_dep()) + " argument names, but got " + str(args.size()) + ".");
1493  return x->disp(args);
1494  }

References casadi::MXNode::disp(), n_dep(), and casadi::str().

◆ print_ptr()

void casadi::SharedObject::print_ptr ( std::ostream &  stream = casadi::uout()) const
inherited

Print the pointer to the internal class

Definition at line 43 of file shared_object.cpp.

43  {
44  stream << get();
45  }

References casadi::GenericShared< SharedObject, SharedObjectInternal >::get().

◆ printme()

MX casadi::MX::printme ( const MX &  b) const

Returns an expression equal to this one; when it is evaluated, every nonzero is printed to standard output as "|> b : value", where b is a scalar expression evaluated alongside it (an identifier for the print). Useful to trace values inside a Function. The printing is not part of the returned value and not seen by the doctest runner's output capture.

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> e = x.printme(y)
>>> e, e.is_op(OP_PRINTME)
(MX(printme(x,y)), True)

>> x = MX.sym('x'); y = MX.sym('y');
>> e = x.printme(y);
>> e, e.is_op(OP_PRINTME)
printme(x,y)
1

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> e = ca.printme(x, y);
julia> e, ca.is_op(e, ca.OP_PRINTME)
(printme(x,y), true)

See also
monitor, attachAssert

Extra doc: https://github.com/casadi/casadi/wiki/L_2qh

Definition at line 742 of file mx.cpp.

742  {
743  return binary(OP_PRINTME, *this, b);
744  }
@ OP_PRINTME
Definition: calculus.hpp:190

References binary(), and casadi::OP_PRINTME.

◆ project()

MX casadi::MX::project ( const MX &  x,
const Sparsity &  sp,
bool  intersect = false 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 909 of file mx.cpp.

909  {
910  try {
911  if (x.is_empty() || (sp==x.sparsity())) {
912  return x;
913  } else {
914  casadi_assert(sp.size()==x.size(), "Cannot project " + x.dim() + " to " + sp.dim());
915  if (intersect) {
916  return x->get_project(sp.intersect(x.sparsity()));
917  } else {
918  return x->get_project(sp);
919  }
920  }
921  } catch (std::exception& e) {
922  CASADI_THROW_ERROR("project", e.what());
923  }
924  }

References casadi::GenericMatrix< MatType >::dim(), casadi::Sparsity::dim(), casadi::MXNode::get_project(), casadi::Sparsity::intersect(), casadi::GenericMatrix< MatType >::is_empty(), casadi::GenericMatrix< MatType >::size(), casadi::Sparsity::size(), and sparsity().

Referenced by densify(), get(), set(), set_nz(), simplify_const_folding(), and simplify_ref_count().

◆ quadratic_coeff()

void casadi::GenericMatrix< MX >::quadratic_coeff ( const MX &  expr,
const MX &  var,
MX &  A,
MX &  b,
MX &  c,
bool  check 
)
staticinherited

Definition at line 672 of file generic_matrix.hpp.

5689  {
5690  casadi_assert(expr.is_scalar(), "'quadratic_coeff' only defined for scalar expressions.");
5691  A = hessian(expr, var);
5692  b = substitute(jacobian(expr, var), var, 0).T();
5693  if (check)
5694  casadi_assert(!depends_on(A, var), "'quadratic_coeff' called on non-quadratic expression.");
5695  c = substitute(expr, var, 0);
5696  }
friend bool depends_on(const MX &f, const MX &arg)
Check if expression depends on the argument.
friend MX hessian(const MX &ex, const MX &arg, const Dict &opts=Dict())
Hessian and (optionally) gradient.

◆ rank1()

static MX casadi::GenericMatrix< MX >::rank1 ( const MX &  A,
const MX &  alpha,
const MX &  x,
const MX &  y 
)
staticinherited

Calculates A + alpha * x*y'

Parameters
alphaScalar; if it is a structural zero, A is returned unchanged
xVector with x.numel() == A.size1() (row vectors are transposed)
yVector with y.numel() == A.size2()

>>> A = DM([[1, 2], [3, 4]])
>>> rank1(A, 2, DM([1, 0]), DM([0, 1]))
DM(
[[1, 4],
 [3, 4]])
>>> rank1(MX.sym("A", 2, 2), MX.sym("a"), MX.sym("x", 2), MX.sym("y", 2))
MX(rank1(A, a, x, y))

>> A = DM([1 2; 3 4]);
>> rank1(A, 2, DM([1; 0]), DM([0; 1]))
[[1, 4],
 [3, 4]]
>> rank1(MX.sym('A', 2, 2), MX.sym('a'), MX.sym('x', 2), MX.sym('y', 2))
rank1(A, a, x, y)

julia> A = ca.DM([1 2; 3 4]);
julia> ca.rank1(A, 2, ca.DM([1, 0]), ca.DM([0, 1]))
DM(
[[1, 4],
 [3, 4]])
julia> ca.rank1(ca.MX.sym("A", 2, 2), ca.MX.sym("a"), ca.MX.sym("x", 2), ca.MX.sym("y", 2))
MX(rank1(A, a, x, y))

See also
bilin, mtimes

Extra doc: https://github.com/casadi/casadi/wiki/L_1bp

◆ repmat()

MX casadi::MX::repmat ( const MX &  x,
casadi_int  n,
casadi_int  m = 1 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 2078 of file mx.cpp.

2078  {
2079  if (n==0 && m==0) {
2080  return MX();
2081  } else if (n==0) {
2082  return MX(0, x.size2()*m);
2083  } else if (m==0) {
2084  return MX(x.size1()*n, 0);
2085  } else if (n==1 && m==1) {
2086  return x;
2087  } else {
2088  return x->get_repmat(n, m);
2089  }
2090  }

References casadi::MXNode::get_repmat(), MX(), casadi::GenericMatrix< MatType >::size1(), and casadi::GenericMatrix< MatType >::size2().

Referenced by binary(), densify(), and set().

◆ repsum() [1/2]

MX casadi::GenericMatrix< MX >::repsum ( const MX &  x,
casadi_int  n,
casadi_int  m = 1 
)
staticinherited

Definition at line 667 of file generic_matrix.hpp.

5461  {
5462  casadi_assert(n>0 && x.size1() % n==0,
5463  "repsum: x.size1() (" + str(x.size1()) + ") must be a multiple of n (" + str(n) + ")");
5464  casadi_assert(m>0 && x.size2() % m==0,
5465  "repsum: x.size2() (" + str(x.size2()) + ") must be a multiple of m (" + str(m) + ")");
5466  std::vector< std::vector< MatType> > s =
5467  blocksplit(x, x.size1()/n, x.size2()/m);
5468  MatType sum = 0;
5469  for (casadi_int i=0;i<s.size();++i) {
5470  for (casadi_int j=0;j<s[i].size();++j) {
5471  sum = sum + s[i][j];
5472  }
5473  }
5474  return sum;
5475  }
static std::vector< std::vector< MatType > > blocksplit(const MatType &x, const std::vector< casadi_int > &vert_offset, const std::vector< casadi_int > &horz_offset)
friend MatType sum(const MatType &x)
Sum all elements.

◆ repsum() [2/2]

MX casadi::MX::repsum ( const MX &  x,
casadi_int  n,
casadi_int  m = 1 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2092 of file mx.cpp.

2092  {
2093  return x->get_repsum(n, m);
2094  }

References casadi::MXNode::get_repsum().

◆ reset_dump_count()

void casadi::MX::reset_dump_count ( )

Definition at line 761 of file mx.cpp.

761  {
762  casadi_assert(op()==OP_DUMP, "reset_dump_count: not a dump node");
763  static_cast<Dump*>(get())->reset_dump_count();
764  }
void reset_dump_count()
Reset the file counter of a dump node; raises an error on any other node.
Definition: mx.cpp:761
@ OP_DUMP
Definition: calculus.hpp:212

References get(), op(), and casadi::OP_DUMP.

◆ reset_input()

void casadi::MX::reset_input ( ) const

Extra doc: https://github.com/casadi/casadi/wiki/L_qt

Definition at line 1025 of file mx.cpp.

1025  {
1026  (*this)->reset_input();
1027  }

◆ reshape() [1/2]

MX casadi::MX::reshape ( const MX &  x,
casadi_int  nrow,
casadi_int  ncol 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1334 of file mx.cpp.

1334  {
1335  // Quick return if trivial
1336  if (nrow==x.size1() && ncol==x.size2()) return x;
1337 
1338  // Reshape the sparsity pattern
1339  return reshape(x, Sparsity::reshape(x.sparsity(), nrow, ncol));
1340  }
static Sparsity reshape(const Sparsity &x, casadi_int nrow, casadi_int ncol)
Accessed by SparsityInterface.
Definition: sparsity.cpp:262

References casadi::Sparsity::reshape(), casadi::GenericMatrix< MatType >::size1(), casadi::GenericMatrix< MatType >::size2(), and sparsity().

Referenced by MX().

◆ reshape() [2/2]

MX casadi::MX::reshape ( const MX &  x,
const Sparsity &  sp 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1342 of file mx.cpp.

1342  {
1343  casadi_assert(sp.is_reshape(x.sparsity()), "Reshape mismatch");
1344 
1345  // Quick return if trivial
1346  if (sp==x.sparsity()) return x;
1347 
1348  // Call internal method
1349  return x->get_reshape(sp);
1350  }

References casadi::MXNode::get_reshape(), casadi::Sparsity::is_reshape(), and sparsity().

◆ reverse()

std::vector< std::vector< MX > > casadi::MX::reverse ( const std::vector< MX > &  ex,
const std::vector< MX > &  arg,
const std::vector< std::vector< MX > > &  v,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1973 of file mx.cpp.

1975  {
1976  try {
1977  // Read options
1978  bool always_inline = true;
1979  bool never_inline = false;
1980 
1981 
1982  Dict h_opts;
1983  Dict opts_remainder = extract_from_dict(opts, "helper_options", h_opts);
1984  h_opts["allow_free"] = true;
1985 
1986  for (auto&& op : opts_remainder) {
1987  if (op.first=="always_inline") {
1988  always_inline = op.second;
1989  } else if (op.first=="never_inline") {
1990  never_inline = op.second;
1991  } else {
1992  casadi_error("No such option: " + std::string(op.first));
1993  }
1994  }
1995  // Call internal function on a temporary object
1996  Function temp("reverse_temp", arg, ex, h_opts);
1997  std::vector<std::vector<MX> > ret;
1998  temp->call_reverse(arg, ex, v, ret, always_inline, never_inline);
1999  return ret;
2000  } catch (std::exception& e) {
2001  CASADI_THROW_ERROR("reverse", e.what());
2002  }
2003  }

References casadi::FunctionInternal::call_reverse(), casadi::extract_from_dict(), and op().

Referenced by substitute_inplace().

◆ row() [1/2]

const casadi_int* casadi::GenericMatrix< MX >::row ( ) const
inlineinherited

The pattern is stored in compressed column format: colind has size2()+1 entries, the nonzeros of column j are the entries colind(j) up to colind(j+1) (exclusive), and row(el) is the row index of nonzero el. Without argument, the full vectors are returned. Out-of-range indices raise an error.

>>> x = DM(Sparsity.diag(2), [5, 6])
>>> x.row(), x.colind()
([0, 1], [0, 1, 2])
>>> x.row(1), x.colind(2)
(1, 2)

>> x = DM(Sparsity.diag(2), [5; 6]);
>> x.row(), x.colind()
0 1
0 1 2
>> fprintf('%d %d\n', x.row(1), x.colind(2))
1 2

julia> x = ca.DM(ca.Sparsity.diag(2), [5, 6]);
julia> ca.row(x), ca.colind(x)
([0, 1], [0, 1, 2])
julia> ca.row(x, 1), ca.colind(x, 2)
(1, 2)

Extra doc: https://github.com/casadi/casadi/wiki/L_1b8

Definition at line 605 of file generic_matrix.hpp.

605 { return sparsity().row(); }
const casadi_int * row() const
Get a reference to row-vector,.
Definition: sparsity.cpp:166

◆ row() [2/2]

casadi_int casadi::GenericMatrix< MX >::row ( casadi_int  el) const
inlineinherited

The pattern is stored in compressed column format: colind has size2()+1 entries, the nonzeros of column j are the entries colind(j) up to colind(j+1) (exclusive), and row(el) is the row index of nonzero el. Without argument, the full vectors are returned. Out-of-range indices raise an error.

>>> x = DM(Sparsity.diag(2), [5, 6])
>>> x.row(), x.colind()
([0, 1], [0, 1, 2])
>>> x.row(1), x.colind(2)
(1, 2)

>> x = DM(Sparsity.diag(2), [5; 6]);
>> x.row(), x.colind()
0 1
0 1 2
>> fprintf('%d %d\n', x.row(1), x.colind(2))
1 2

julia> x = ca.DM(ca.Sparsity.diag(2), [5, 6]);
julia> ca.row(x), ca.colind(x)
([0, 1], [0, 1, 2])
julia> ca.row(x, 1), ca.colind(x, 2)
(1, 2)

Extra doc: https://github.com/casadi/casadi/wiki/L_1b8

Definition at line 608 of file generic_matrix.hpp.

608 { return sparsity().row(el); }

◆ rows()

casadi_int casadi::GenericMatrix< MX >::rows ( ) const
inlineinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1at

Definition at line 283 of file generic_matrix.hpp.

283 {return size1();}

◆ separate_linear()

void casadi::MX::separate_linear ( const MX &  expr,
const MX &  sym_lin,
const MX &  sym_const,
MX &  expr_const,
MX &  expr_lin,
MX &  expr_nonlin 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2929 of file mx.cpp.

2931  {
2932 
2933  std::vector<MX> in = {sym_const, sym_lin};
2934  std::vector<MX> out = {expr};
2935 
2936  Function f("f", in, out, {{"live_variables", false},
2937  {"max_io", 0}, {"allow_free", true}});
2938  MXFunction *ff = f.get<MXFunction>();
2939 
2940  // Each work vector element has (const, lin, nonlin) part
2941  std::vector< std::array<MX, 3> > w(ff->workloc_.size()-1);
2942 
2943  // Split up inputs analogous to symbolic primitives
2944  std::vector<std::vector<MX> > arg_split(in.size());
2945  for (casadi_int i=0; i<in.size(); ++i) arg_split[i] = in[i].split_primitives(in[i]);
2946 
2947  // Allocate storage for split outputs
2948  std::array<std::vector<MX>, 3> res_split;
2949  for (int k=0;k<3;++k) {
2950  res_split[k].resize(expr.n_primitives());
2951  }
2952 
2953  std::vector<std::array<MX, 3> > arg1, res1;
2954 
2955  std::array<MX, 3> res;
2956 
2957  // Loop over computational nodes in forward order
2958  casadi_int alg_counter = 0;
2959  for (auto it=ff->algorithm_.begin(); it!=ff->algorithm_.end(); ++it, ++alg_counter) {
2960  if (it->op == OP_INPUT) {
2961  MX null = MX::zeros(arg_split.at(it->data->ind()).at(it->data->segment()).sparsity());
2962  w[it->res.front()][0] = null;
2963  w[it->res.front()][1] = null;
2964  w[it->res.front()][2] = null;
2965  w[it->res.front()][it->data->ind()] = arg_split.at(it->data->ind()).at(it->data->segment());
2966  } else if (it->op==OP_OUTPUT) {
2967  // Collect the results
2968  for (int i=0;i<3;++i) {
2969  res_split.at(i).at(it->data->segment()) = w[it->arg.front()][i];
2970  }
2971  } else if (it->op==OP_CONST) {
2972  // Fetch constant
2973  w[it->res.front()][0] = it->data;
2974  w[it->res.front()][1] = MX::zeros(it->data->sparsity());
2975  w[it->res.front()][2] = MX::zeros(it->data->sparsity());
2976  } else if (it->op==OP_PARAMETER) {
2977  // Fetch parameter
2978  w[it->res.front()][0] = MX::zeros(it->data->sparsity());
2979  w[it->res.front()][1] = MX::zeros(it->data->sparsity());
2980  w[it->res.front()][2] = it->data;
2981  } else {
2982  // Arguments of the operation
2983  arg1.resize(it->arg.size());
2984  for (casadi_int i=0; i<arg1.size(); ++i) {
2985  casadi_int el = it->arg[i]; // index of the argument
2986  for (int k=0;k<3;++k) {
2987  arg1[i][k] = el<0 ? MX(it->data->dep(i).size()) : w[el][k];
2988  }
2989  }
2990 
2991  // Perform the operation
2992  res1.clear();
2993  res1.resize(it->res.size());
2994  for (casadi_int i=0;i<it->res.size();++i) {
2995  for (int k=0;k<3;++k) {
2996  res1[i][k] = MX::zeros(it->data->sparsity());
2997  }
2998  }
2999  it->data->eval_linear(arg1, res1);
3000 
3001  // Get the result
3002  for (casadi_int i=0; i<res1.size(); ++i) {
3003  casadi_int el = it->res[i]; // index of the output
3004  for (int k=0;k<3;++k) {
3005  if (el>=0) w[el][k] = res1[i][k];
3006  }
3007  }
3008  }
3009  }
3010 
3011  // Join split outputs
3012  for (int k=0;k<3;++k) {
3013  res[k] = expr.join_primitives(res_split[k]);
3014  }
3015  expr_const = res[0];
3016  expr_lin = res[1];
3017  expr_nonlin = res[2];
3018  }
std::vector< MX > split_primitives(const MX &x) const
Split a value along the symbolic primitives of this expression.
Definition: mx.cpp:973

References join_primitives(), MX(), n_primitives(), casadi::OP_CONST, casadi::OP_INPUT, casadi::OP_OUTPUT, casadi::OP_PARAMETER, split_primitives(), and casadi::GenericMatrix< MX >::zeros().

◆ serialize()

void casadi::MX::serialize ( SerializingStream &  s) const

From Python, serialize through StringSerializer, FileSerializer or pickle within a pickle context; the stream object is not constructed directly.

>>> x = MX.sym("x")
>>> s = StringSerializer()
>>> s.pack(x + 1)
>>> d = StringDeserializer(s.encode())
>>> d.unpack()
MX((1+x))

>> x = MX.sym('x');
>> s = StringSerializer();
>> s.pack(x + 1);
>> d = StringDeserializer(s.encode());
>> d.unpack()
(1+x)

julia> x = ca.MX.sym("x");
julia> s = ca.StringSerializer();
julia> ca.pack(s, x + 1)
julia> d = ca.StringDeserializer(ca.encode(s));
julia> ca.unpack(d)
MX((1+x))

See also
deserialize, StringSerializer

Extra doc: https://github.com/casadi/casadi/wiki/L_qz

Definition at line 862 of file mx.cpp.

862  {
863  (*this)->serialize(s);
864  }

◆ set() [1/7]

void casadi::MX::set ( const MX &  m,
bool  ind1,
const Matrix< casadi_int > &  rr 
)

Expressions are immutable: assignment rebinds this object to a new SetNonzeros node whose dependencies are the old expression and m. Expressions built earlier from the old value are unaffected, but a second name bound to the same object (Y0 = Y) sees the new node; copy the handle with MX(Y) to keep the old value. The sparsity pattern grows to include the assigned elements; assigning a sparse m first erases the targeted elements. m must have the shape of the index set, be a scalar (broadcast), or be its transpose when the index set is a vector; anything else raises a dimension mismatch error. A Sparsity index assigns to the nonzero positions of that pattern. An MX index is only supported for the nonzero (x.nz[k]) form.

>>> Y = MX.sym("Y", 3, 3)
>>> alias, copy, twice = Y, MX(Y), 2*Y
>>> Y[[4]] = 5
>>> Y, Y.n_dep(), Y.dep(0), Y.dep(1)
(MX((Y[4] = 5)), 2, MX(Y), MX(5))
>>> alias, copy, twice
(MX((Y[4] = 5)), MX(Y), MX((2.*Y)))
>>> Z = MX(3, 3)
>>> Z[[0, 8]] = MX.sym("a", 2)
>>> Z.sparsity()
Sparsity(3x3,2nz)
>>> Y = MX.sym("Y", 3, 3)
>>> Y[Sparsity.lower(3)] = 1
>>> Y
MX((Y[0, 1, 2, 4, 5, 8] = ones(6x1)))

>> Y = MX.sym('Y', 3, 3);
>> alias = Y; copy = MX(Y); twice = 2*Y;
>> Y(5) = 5;
>> Y, Y.n_dep(), Y.dep(0), Y.dep(1)
(Y[4] = 5)
2
Y
5
>> alias, copy, twice
(Y[4] = 5)
Y
(2.*Y)
>> Z = MX(3, 3);
>> Z([1, 9]) = MX.sym('a', 2);
>> Z.sparsity()
3x3,2nz
>> Y = MX.sym('Y', 3, 3);
>> Y(Sparsity.lower(3)) = 1;
>> Y
(Y[0, 1, 2, 4, 5, 8] = ones(6x1))

julia> Y = ca.MX.sym("Y", 3, 3);
julia> alias, copy, twice = Y, ca.MX(Y), 2 * Y;
julia> Y[[5]] = 5;
julia> Y, ca.n_dep(Y), ca.dep(Y, 0), ca.dep(Y, 1)
((Y[4] = 5), 2, Y, 5)
julia> alias, copy, twice
((Y[4] = 5), Y, (2.*Y))
julia> Z = ca.MX(3, 3);
julia> Z[[1, 9]] = ca.MX.sym("a", 2);
julia> ca.sparsity(Z)
Sparsity(3x3,2nz)

See also
get, set_nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qc

Definition at line 321 of file mx.cpp.

321  {
322  // Assert dimensions of assigning matrix
323  if (rr.sparsity() != m.sparsity()) {
324  if (rr.size() == m.size()) {
325  // Remove submatrix to be replaced
326  erase(rr.nonzeros(), ind1);
327 
328  // Find the intersection between rr's and m's sparsity patterns
329  Sparsity sp = rr.sparsity() * m.sparsity();
330 
331  // Project both matrices to this sparsity
332  set(project(m, sp), ind1, Matrix<casadi_int>::project(rr, sp));
333  return;
334  } else if (m.is_scalar()) {
335  // m scalar means "set all"
336  if (m.is_dense()) {
337  set(MX(rr.sparsity(), m), ind1, rr);
338  } else {
339  set(MX(rr.size()), ind1, rr);
340  }
341  return;
342  } else if (rr.size1() == m.size2() && rr.size2() == m.size1()
343  && std::min(m.size1(), m.size2()) == 1) {
344  // m is transposed if necessary
345  set(m.T(), ind1, rr);
346  return;
347  } else {
348  // Error otherwise
349  casadi_error("Dimension mismatch. lhs is " + str(rr.size())
350  + ", while rhs is " + str(m.size()));
351  }
352  }
353 
354  // Dimensions of this
355  casadi_int sz1 = size1(), sz2 = size2(), sz = nnz(), nel = numel(), rrsz = rr.nnz();
356 
357  // Quick return if nothing to set
358  if (rrsz==0) return;
359 
360  // Check bounds
361  casadi_assert_in_range(rr.nonzeros(), -nel+ind1, nel+ind1);
362 
363  // Dense mode
364  if (is_dense() && m.is_dense()) {
365  set_nz(m, ind1, rr);
366  return;
367  }
368 
369  // Construct new sparsity pattern
370  std::vector<casadi_int> new_row=sparsity().get_row(), new_col=sparsity().get_col();
371  std::vector<casadi_int> nz(rr.nonzeros());
372  new_row.reserve(sz+rrsz);
373  new_col.reserve(sz+rrsz);
374  nz.reserve(rrsz);
375  for (std::vector<casadi_int>::iterator i=nz.begin(); i!=nz.end(); ++i) {
376  if (ind1) (*i)--;
377  if (*i<0) *i += nel;
378  new_row.push_back(*i % sz1);
379  new_col.push_back(*i / sz1);
380  }
381  Sparsity sp = Sparsity::triplet(sz1, sz2, new_row, new_col);
382 
383  // If needed, update pattern
384  if (sp != sparsity()) *this = project(*this, sp);
385 
386  // Find the nonzeros corresponding to rr
387  sparsity().get_nz(nz);
388 
389  // Create a nonzero assignment node
390  *this = m->get_nzassign(*this, nz);
391  }
void erase(const std::vector< casadi_int > &rr, const std::vector< casadi_int > &cc, bool ind1=false)
Erase a submatrix (leaving structural zeros in its place)
Definition: mx.cpp:619
void set_nz(const MX &m, bool ind1, const Slice &kk)
Assign to a set of nonzeros (what x.nz[k] = m does)
Definition: mx.cpp:464
void set(const MX &m, bool ind1, const Slice &rr)
Assign to a submatrix by linear index (what x[k] = m does)
Definition: mx.cpp:316
static Matrix< casadi_int > project(const Matrix< casadi_int > &x, const Sparsity &sp, bool intersect=false)
casadi_int get_nz(casadi_int rr, casadi_int cc) const
Nonzero index of entry (rr, cc), or -1 if it is a structural zero.
Definition: sparsity.cpp:248
std::vector< casadi_int > get_col() const
Column index of every nonzero, in nonzero (column-major) order.
Definition: sparsity.cpp:370
static Sparsity triplet(casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &row, const std::vector< casadi_int > &col, std::vector< casadi_int > &mapping, bool invert_mapping)
Create a sparsity pattern from the (row, col) index of every nonzero.
Definition: sparsity.cpp:1157

References erase(), casadi::Sparsity::get_col(), casadi::Sparsity::get_nz(), casadi::MXNode::get_nzassign(), casadi::Sparsity::get_row(), casadi::GenericMatrix< MX >::is_dense(), casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_scalar(), MX(), casadi::GenericMatrix< MatType >::nnz(), casadi::GenericMatrix< MX >::nnz(), casadi::Matrix< Scalar >::nonzeros(), casadi::GenericMatrix< MX >::numel(), casadi::GenericMatrix< MX >::nz(), project(), set(), set_nz(), casadi::GenericMatrix< MatType >::size(), casadi::GenericMatrix< MX >::size1(), casadi::GenericMatrix< MatType >::size1(), casadi::GenericMatrix< MX >::size2(), casadi::GenericMatrix< MatType >::size2(), casadi::Matrix< Scalar >::sparsity(), sparsity(), casadi::str(), T(), and casadi::Sparsity::triplet().

◆ set() [2/7]

void casadi::MX::set ( const MX &  m,
bool  ind1,
const Matrix< casadi_int > &  rr,
const Matrix< casadi_int > &  cc 
)

Same semantics as the single-index form. m must be len(rr)-by-len(cc), a scalar, or the transpose of a vector block.

>>> Y = MX.sym("Y", 3, 3)
>>> Y[:, 0] = MX.sym("c", 1, 3)
>>> Y
MX((Y[:3] = c'))
>>> Y[0:2, 0:2] = 0
>>> Y.sparsity()
Sparsity(3x3)
>>> try:
...   Y[:, 0] = MX.sym("d", 2)
... except Exception as e:
...   print("Dimension mismatch" in str(e))
True

>> Y = MX.sym('Y', 3, 3);
>> Y(:, 1) = MX.sym('c', 1, 3);
>> Y
(Y[:3] = c')
>> Y(1:2, 1:2) = 0;
>> Y.sparsity()
3x3
>> try, Y(:, 1) = MX.sym('d', 2); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y[:, 1] = ca.MX.sym("c", 1, 3);
julia> Y
MX((Y[:3] = c'))
julia> Y[1:2, 1:2] = 0;
julia> ca.sparsity(Y)
Sparsity(3x3)
julia> try
           Y[:, 1] = ca.MX.sym("d", 2)
       catch e
           println(occursin("Dimension mismatch", sprint(showerror, e)))
       end
true

See also
get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qd

Definition at line 252 of file mx.cpp.

252  {
253  // Row vector rr (e.g. in MATLAB) is transposed to column vector
254  if (rr.size1()==1 && rr.size2()>1) {
255  set(m, ind1, rr.T(), cc);
256  return;
257  }
258 
259  // Row vector cc (e.g. in MATLAB) is transposed to column vector
260  if (cc.size1()==1 && cc.size2()>1) {
261  set(m, ind1, rr, cc.T());
262  return;
263  }
264 
265  // Make sure rr and cc are dense vectors
266  casadi_assert(rr.is_dense() && rr.is_column(),
267  "MX::set: First index not dense vector");
268  casadi_assert(cc.is_dense() && cc.is_column(),
269  "MX::set: Second index not dense vector");
270 
271  // Assert dimensions of assigning matrix
272  if (rr.size1() != m.size1() || cc.size1() != m.size2()) {
273  if (m.is_scalar()) {
274  // m scalar means "set all"
275  set(repmat(m, rr.size1(), cc.size1()), ind1, rr, cc);
276  return;
277  } else if (rr.size1() == m.size2() && cc.size1() == m.size1()
278  && std::min(m.size1(), m.size2()) == 1) {
279  // m is transposed if necessary
280  set(m.T(), ind1, rr, cc);
281  return;
282  } else {
283  // Error otherwise
284  casadi_error("Dimension mismatch. lhs is " + str(rr.size1()) + "-by-"
285  + str(cc.size1()) + ", while rhs is " + str(m.size()));
286  }
287  }
288 
289  // Dimensions
290  casadi_int sz1 = size1(), sz2 = size2();
291 
292  // Report out-of-bounds
293  casadi_assert_in_range(rr.nonzeros(), -sz1+ind1, sz1+ind1);
294  casadi_assert_in_range(cc.nonzeros(), -sz2+ind1, sz2+ind1);
295 
296  // If we are assigning with something sparse, first remove existing entries
297  if (!m.is_dense()) {
298  erase(rr.nonzeros(), cc.nonzeros(), ind1);
299  }
300 
301  // Collect all assignments
302  IM el = IM::zeros(m.sparsity());
303  for (casadi_int j=0; j<el.size2(); ++j) { // Loop over columns of m
304  casadi_int this_j = cc->at(j) - ind1; // Corresponding column in this
305  if (this_j<0) this_j += sz2;
306  for (casadi_int k=el.colind(j); k<el.colind(j+1); ++k) { // Loop over rows of m
307  casadi_int i = m.row(k);
308  casadi_int this_i = rr->at(i) - ind1; // Corresponding row in this
309  if (this_i<0) this_i += sz1;
310  el->at(k) = this_i + this_j*sz1;
311  }
312  }
313  set(m, false, el);
314  }
Matrix< Scalar > T() const
Transpose the matrix.
Matrix< casadi_int > IM
Definition: im_fwd.hpp:31

References casadi::GenericMatrix< MatType >::colind(), erase(), casadi::GenericMatrix< MatType >::is_column(), casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_scalar(), casadi::Matrix< Scalar >::nonzeros(), repmat(), casadi::GenericMatrix< MatType >::row(), set(), casadi::GenericMatrix< MatType >::size(), casadi::GenericMatrix< MX >::size1(), casadi::GenericMatrix< MatType >::size1(), casadi::GenericMatrix< MX >::size2(), casadi::GenericMatrix< MatType >::size2(), sparsity(), casadi::str(), casadi::Matrix< Scalar >::T(), T(), and casadi::GenericMatrix< MatType >::zeros().

◆ set() [3/7]

void casadi::MX::set ( const MX &  m,
bool  ind1,
const Matrix< casadi_int > &  rr,
const Slice &  cc 
)

Same semantics as the single-index form. m must be len(rr)-by-len(cc), a scalar, or the transpose of a vector block.

>>> Y = MX.sym("Y", 3, 3)
>>> Y[:, 0] = MX.sym("c", 1, 3)
>>> Y
MX((Y[:3] = c'))
>>> Y[0:2, 0:2] = 0
>>> Y.sparsity()
Sparsity(3x3)
>>> try:
...   Y[:, 0] = MX.sym("d", 2)
... except Exception as e:
...   print("Dimension mismatch" in str(e))
True

>> Y = MX.sym('Y', 3, 3);
>> Y(:, 1) = MX.sym('c', 1, 3);
>> Y
(Y[:3] = c')
>> Y(1:2, 1:2) = 0;
>> Y.sparsity()
3x3
>> try, Y(:, 1) = MX.sym('d', 2); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y[:, 1] = ca.MX.sym("c", 1, 3);
julia> Y
MX((Y[:3] = c'))
julia> Y[1:2, 1:2] = 0;
julia> ca.sparsity(Y)
Sparsity(3x3)
julia> try
           Y[:, 1] = ca.MX.sym("d", 2)
       catch e
           println(occursin("Dimension mismatch", sprint(showerror, e)))
       end
true

See also
get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qd

Definition at line 247 of file mx.cpp.

247  {
248  // Fall back on (IM, IM)
249  set(m, ind1, rr, cc.all(size2(), ind1));
250  }

References casadi::Slice::all(), set(), and casadi::GenericMatrix< MX >::size2().

◆ set() [4/7]

void casadi::MX::set ( const MX &  m,
bool  ind1,
const Slice &  rr 
)

Expressions are immutable: assignment rebinds this object to a new SetNonzeros node whose dependencies are the old expression and m. Expressions built earlier from the old value are unaffected, but a second name bound to the same object (Y0 = Y) sees the new node; copy the handle with MX(Y) to keep the old value. The sparsity pattern grows to include the assigned elements; assigning a sparse m first erases the targeted elements. m must have the shape of the index set, be a scalar (broadcast), or be its transpose when the index set is a vector; anything else raises a dimension mismatch error. A Sparsity index assigns to the nonzero positions of that pattern. An MX index is only supported for the nonzero (x.nz[k]) form.

>>> Y = MX.sym("Y", 3, 3)
>>> alias, copy, twice = Y, MX(Y), 2*Y
>>> Y[[4]] = 5
>>> Y, Y.n_dep(), Y.dep(0), Y.dep(1)
(MX((Y[4] = 5)), 2, MX(Y), MX(5))
>>> alias, copy, twice
(MX((Y[4] = 5)), MX(Y), MX((2.*Y)))
>>> Z = MX(3, 3)
>>> Z[[0, 8]] = MX.sym("a", 2)
>>> Z.sparsity()
Sparsity(3x3,2nz)
>>> Y = MX.sym("Y", 3, 3)
>>> Y[Sparsity.lower(3)] = 1
>>> Y
MX((Y[0, 1, 2, 4, 5, 8] = ones(6x1)))

>> Y = MX.sym('Y', 3, 3);
>> alias = Y; copy = MX(Y); twice = 2*Y;
>> Y(5) = 5;
>> Y, Y.n_dep(), Y.dep(0), Y.dep(1)
(Y[4] = 5)
2
Y
5
>> alias, copy, twice
(Y[4] = 5)
Y
(2.*Y)
>> Z = MX(3, 3);
>> Z([1, 9]) = MX.sym('a', 2);
>> Z.sparsity()
3x3,2nz
>> Y = MX.sym('Y', 3, 3);
>> Y(Sparsity.lower(3)) = 1;
>> Y
(Y[0, 1, 2, 4, 5, 8] = ones(6x1))

julia> Y = ca.MX.sym("Y", 3, 3);
julia> alias, copy, twice = Y, ca.MX(Y), 2 * Y;
julia> Y[[5]] = 5;
julia> Y, ca.n_dep(Y), ca.dep(Y, 0), ca.dep(Y, 1)
((Y[4] = 5), 2, Y, 5)
julia> alias, copy, twice
((Y[4] = 5), Y, (2.*Y))
julia> Z = ca.MX(3, 3);
julia> Z[[1, 9]] = ca.MX.sym("a", 2);
julia> ca.sparsity(Z)
Sparsity(3x3,2nz)

See also
get, set_nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qc

Definition at line 316 of file mx.cpp.

316  {
317  // Fall back on IM
318  set(m, ind1, rr.all(numel(), ind1));
319  }

References casadi::Slice::all(), and casadi::GenericMatrix< MX >::numel().

Referenced by set().

◆ set() [5/7]

void casadi::MX::set ( const MX &  m,
bool  ind1,
const Slice &  rr,
const Matrix< casadi_int > &  cc 
)

Same semantics as the single-index form. m must be len(rr)-by-len(cc), a scalar, or the transpose of a vector block.

>>> Y = MX.sym("Y", 3, 3)
>>> Y[:, 0] = MX.sym("c", 1, 3)
>>> Y
MX((Y[:3] = c'))
>>> Y[0:2, 0:2] = 0
>>> Y.sparsity()
Sparsity(3x3)
>>> try:
...   Y[:, 0] = MX.sym("d", 2)
... except Exception as e:
...   print("Dimension mismatch" in str(e))
True

>> Y = MX.sym('Y', 3, 3);
>> Y(:, 1) = MX.sym('c', 1, 3);
>> Y
(Y[:3] = c')
>> Y(1:2, 1:2) = 0;
>> Y.sparsity()
3x3
>> try, Y(:, 1) = MX.sym('d', 2); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y[:, 1] = ca.MX.sym("c", 1, 3);
julia> Y
MX((Y[:3] = c'))
julia> Y[1:2, 1:2] = 0;
julia> ca.sparsity(Y)
Sparsity(3x3)
julia> try
           Y[:, 1] = ca.MX.sym("d", 2)
       catch e
           println(occursin("Dimension mismatch", sprint(showerror, e)))
       end
true

See also
get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qd

Definition at line 242 of file mx.cpp.

242  {
243  // Fall back on (IM, IM)
244  set(m, ind1, rr.all(size1(), ind1), cc);
245  }

References casadi::Slice::all(), set(), and casadi::GenericMatrix< MX >::size1().

◆ set() [6/7]

void casadi::MX::set ( const MX &  m,
bool  ind1,
const Slice &  rr,
const Slice &  cc 
)

Same semantics as the single-index form. m must be len(rr)-by-len(cc), a scalar, or the transpose of a vector block.

>>> Y = MX.sym("Y", 3, 3)
>>> Y[:, 0] = MX.sym("c", 1, 3)
>>> Y
MX((Y[:3] = c'))
>>> Y[0:2, 0:2] = 0
>>> Y.sparsity()
Sparsity(3x3)
>>> try:
...   Y[:, 0] = MX.sym("d", 2)
... except Exception as e:
...   print("Dimension mismatch" in str(e))
True

>> Y = MX.sym('Y', 3, 3);
>> Y(:, 1) = MX.sym('c', 1, 3);
>> Y
(Y[:3] = c')
>> Y(1:2, 1:2) = 0;
>> Y.sparsity()
3x3
>> try, Y(:, 1) = MX.sym('d', 2); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y[:, 1] = ca.MX.sym("c", 1, 3);
julia> Y
MX((Y[:3] = c'))
julia> Y[1:2, 1:2] = 0;
julia> ca.sparsity(Y)
Sparsity(3x3)
julia> try
           Y[:, 1] = ca.MX.sym("d", 2)
       catch e
           println(occursin("Dimension mismatch", sprint(showerror, e)))
       end
true

See also
get

Extra doc: https://github.com/casadi/casadi/wiki/L_2qd

Definition at line 237 of file mx.cpp.

237  {
238  // Fall back on (IM, IM)
239  set(m, ind1, rr.all(size1(), ind1), cc.all(size2(), ind1));
240  }

References casadi::Slice::all(), set(), casadi::GenericMatrix< MX >::size1(), and casadi::GenericMatrix< MX >::size2().

◆ set() [7/7]

void casadi::MX::set ( const MX &  m,
bool  ind1,
const Sparsity &  sp 
)

Expressions are immutable: assignment rebinds this object to a new SetNonzeros node whose dependencies are the old expression and m. Expressions built earlier from the old value are unaffected, but a second name bound to the same object (Y0 = Y) sees the new node; copy the handle with MX(Y) to keep the old value. The sparsity pattern grows to include the assigned elements; assigning a sparse m first erases the targeted elements. m must have the shape of the index set, be a scalar (broadcast), or be its transpose when the index set is a vector; anything else raises a dimension mismatch error. A Sparsity index assigns to the nonzero positions of that pattern. An MX index is only supported for the nonzero (x.nz[k]) form.

>>> Y = MX.sym("Y", 3, 3)
>>> alias, copy, twice = Y, MX(Y), 2*Y
>>> Y[[4]] = 5
>>> Y, Y.n_dep(), Y.dep(0), Y.dep(1)
(MX((Y[4] = 5)), 2, MX(Y), MX(5))
>>> alias, copy, twice
(MX((Y[4] = 5)), MX(Y), MX((2.*Y)))
>>> Z = MX(3, 3)
>>> Z[[0, 8]] = MX.sym("a", 2)
>>> Z.sparsity()
Sparsity(3x3,2nz)
>>> Y = MX.sym("Y", 3, 3)
>>> Y[Sparsity.lower(3)] = 1
>>> Y
MX((Y[0, 1, 2, 4, 5, 8] = ones(6x1)))

>> Y = MX.sym('Y', 3, 3);
>> alias = Y; copy = MX(Y); twice = 2*Y;
>> Y(5) = 5;
>> Y, Y.n_dep(), Y.dep(0), Y.dep(1)
(Y[4] = 5)
2
Y
5
>> alias, copy, twice
(Y[4] = 5)
Y
(2.*Y)
>> Z = MX(3, 3);
>> Z([1, 9]) = MX.sym('a', 2);
>> Z.sparsity()
3x3,2nz
>> Y = MX.sym('Y', 3, 3);
>> Y(Sparsity.lower(3)) = 1;
>> Y
(Y[0, 1, 2, 4, 5, 8] = ones(6x1))

julia> Y = ca.MX.sym("Y", 3, 3);
julia> alias, copy, twice = Y, ca.MX(Y), 2 * Y;
julia> Y[[5]] = 5;
julia> Y, ca.n_dep(Y), ca.dep(Y, 0), ca.dep(Y, 1)
((Y[4] = 5), 2, Y, 5)
julia> alias, copy, twice
((Y[4] = 5), Y, (2.*Y))
julia> Z = ca.MX(3, 3);
julia> Z[[1, 9]] = ca.MX.sym("a", 2);
julia> ca.sparsity(Z)
Sparsity(3x3,2nz)

See also
get, set_nz

Extra doc: https://github.com/casadi/casadi/wiki/L_2qc

Definition at line 393 of file mx.cpp.

393  {
394  casadi_assert(size()==sp.size(),
395  "set(Sparsity sp): shape mismatch. This matrix has shape "
396  + str(size()) + ", but supplied sparsity index has shape "
397  + str(sp.size()) + ".");
398  std::vector<casadi_int> ii = sp.find();
399  if (m.is_scalar()) {
400  (*this)(ii) = densify(m);
401  } else {
402  (*this)(ii) = densify(m(ii));
403  }
404  }

References densify(), casadi::Sparsity::find(), casadi::GenericMatrix< MatType >::is_scalar(), casadi::GenericMatrix< MX >::size(), casadi::Sparsity::size(), and casadi::str().

◆ set_max_depth()

void casadi::MX::set_max_depth ( casadi_int  eq_depth = 1)
static

Global setting (default 1) used when building expressions: operations such as x - y or x/y test whether their operands are equal up to this depth with is_equal and simplify to 0 or 1 when they are. Depth 0 compares node identity only; each extra level compares the operation and recurses into the dependencies. Larger depths find more simplifications at a cost per created node. Calling without an argument restores the default.

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> MX.get_max_depth(), (x + y) - (x + y)
(1, MX(0))
>>> MX.set_max_depth(0)
>>> (x + y) - (x + y)
MX(((x+y)-(x+y)))
>>> MX.set_max_depth()
>>> MX.get_max_depth()
1

>> x = MX.sym('x'); y = MX.sym('y');
>> MX.get_max_depth(), (x + y) - (x + y)
1
0
>> MX.set_max_depth(0);
>> (x + y) - (x + y)
((x+y)-(x+y))
>> MX.set_max_depth();
>> MX.get_max_depth()
1

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> ca.MX.get_max_depth(), (x + y) - (x + y)
(1, 0)
julia> ca.MX.set_max_depth(0)
julia> (x + y) - (x + y)
MX(((x+y)-(x+y)))
julia> ca.MX.set_max_depth()
julia> ca.MX.get_max_depth()
1

See also
get_max_depth, is_equal

Extra doc: https://github.com/casadi/casadi/wiki/L_rj

Definition at line 941 of file mx.cpp.

941  {
942  eq_depth_ = eq_depth;
943  }

◆ set_nz() [1/4]

void casadi::MX::set_nz ( const MX &  m,
bool  ind1,
casadi_int  kk 
)
inline

Rebinds this object to a SetNonzeros node; the sparsity pattern is unchanged. m must have as many nonzeros as the index set or be a scalar. With an MX index the assignment is parametric and resolved at evaluation time.

>>> Y = MX.sym("Y", 3, 3)
>>> Y.nz[0] = 7
>>> Y
MX((Y[0] = 7))
>>> k = MX.sym("k")
>>> Y.nz[k] = 8
>>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
(MX(((Y[0] = 7)[k] = 8)), True)

>> Y = MX.sym('Y', 3, 3);
>> Y.set_nz(7, true, 1);
>> Y
(Y[0] = 7)
>> k = MX.sym('k');
>> Y.set_nz(8, true, k);
>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
((Y[0] = 7)[(k-1)] = 8)
1

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y.nz[1] = 7;
julia> Y
MX((Y[0] = 7))
julia> k = ca.MX.sym("k");
julia> Y.nz[k] = 8;
julia> Y
MX(((Y[0] = 7)[(k-1)] = 8))
julia> ca.is_op(Y, ca.OP_SETNONZEROS_PARAM)
true

See also
get_nz, set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qf

Definition at line 3238 of file mx.hpp.

3238 { set_nz(m, ind1, Matrix<casadi_int>(kk)); }

References set_nz().

Referenced by set_nz().

◆ set_nz() [2/4]

void casadi::MX::set_nz ( const MX &  m,
bool  ind1,
const Matrix< casadi_int > &  kk 
)

Rebinds this object to a SetNonzeros node; the sparsity pattern is unchanged. m must have as many nonzeros as the index set or be a scalar. With an MX index the assignment is parametric and resolved at evaluation time.

>>> Y = MX.sym("Y", 3, 3)
>>> Y.nz[0] = 7
>>> Y
MX((Y[0] = 7))
>>> k = MX.sym("k")
>>> Y.nz[k] = 8
>>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
(MX(((Y[0] = 7)[k] = 8)), True)

>> Y = MX.sym('Y', 3, 3);
>> Y.set_nz(7, true, 1);
>> Y
(Y[0] = 7)
>> k = MX.sym('k');
>> Y.set_nz(8, true, k);
>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
((Y[0] = 7)[(k-1)] = 8)
1

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y.nz[1] = 7;
julia> Y
MX((Y[0] = 7))
julia> k = ca.MX.sym("k");
julia> Y.nz[k] = 8;
julia> Y
MX(((Y[0] = 7)[(k-1)] = 8))
julia> ca.is_op(Y, ca.OP_SETNONZEROS_PARAM)
true

See also
get_nz, set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qf

Definition at line 469 of file mx.cpp.

469  {
470  casadi_assert(kk.nnz()==m.nnz() || m.nnz()==1,
471  "MX::set_nz: length of non-zero indices (" + str(kk.nnz()) + ") " +
472  "must match size of rhs (" + str(m.nnz()) + ").");
473 
474  // Assert dimensions of assigning matrix
475  if (kk.sparsity() != m.sparsity()) {
476  if (m.is_scalar()) {
477  // m scalar means "set all"
478  if (!m.is_dense()) return; // Nothing to set
479  set_nz(MX(kk.sparsity(), m), ind1, kk);
480  return;
481  } else if (kk.size() == m.size()) {
482  // Project sparsity if needed
483  set_nz(project(m, kk.sparsity()), ind1, kk);
484  return;
485  } else if (kk.size1() == m.size2() && kk.size2() == m.size1()
486  && std::min(m.size1(), m.size2()) == 1) {
487  // m is transposed if necessary
488  set_nz(m.T(), ind1, kk);
489  return;
490  } else {
491  // Error otherwise
492  casadi_error("Dimension mismatch. lhs is " + str(kk.size())
493  + ", while rhs is " + str(m.size()));
494  }
495  }
496 
497  // Call recursively if points both objects point to the same node
498  if (this==&m) {
499  MX m_copy = m;
500  set_nz(m_copy, ind1, kk);
501  return;
502  }
503 
504  // Check bounds
505  casadi_int sz = nnz();
506  casadi_assert_in_range(kk.nonzeros(), -sz+ind1, sz+ind1);
507 
508  // Quick return if no assignments to be made
509  if (kk.nnz()==0) return;
510 
511  // Handle index-1, negative indices
512  if (ind1 || *std::min_element(kk->begin(), kk->end())<0) {
513  Matrix<casadi_int> kk_mod = kk;
514  for (auto&& i : kk_mod.nonzeros()) {
515  casadi_assert(!(ind1 && i<=0),
516  "Matlab is 1-based, but requested index " + str(i) + ". "
517  "Note that negative slices are disabled in the Matlab interface. "
518  "Possibly you may want to use 'end'.");
519  if (ind1) i--;
520  if (i<0) i += sz;
521  }
522  set_nz(m, false, kk_mod); // Call recursively
523  return;
524  }
525 
526  // Create a nonzero assignment node
527  *this = m->get_nzassign(*this, kk.nonzeros());
528  }

References casadi::MXNode::get_nzassign(), casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_scalar(), MX(), casadi::GenericMatrix< MX >::nnz(), casadi::GenericMatrix< MatType >::nnz(), casadi::Matrix< Scalar >::nonzeros(), project(), set_nz(), casadi::GenericMatrix< MatType >::size(), casadi::GenericMatrix< MatType >::size1(), casadi::GenericMatrix< MatType >::size2(), casadi::Matrix< Scalar >::sparsity(), sparsity(), casadi::str(), and T().

◆ set_nz() [3/4]

void casadi::MX::set_nz ( const MX &  m,
bool  ind1,
const MX &  kk 
)

Rebinds this object to a SetNonzeros node; the sparsity pattern is unchanged. m must have as many nonzeros as the index set or be a scalar. With an MX index the assignment is parametric and resolved at evaluation time.

>>> Y = MX.sym("Y", 3, 3)
>>> Y.nz[0] = 7
>>> Y
MX((Y[0] = 7))
>>> k = MX.sym("k")
>>> Y.nz[k] = 8
>>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
(MX(((Y[0] = 7)[k] = 8)), True)

>> Y = MX.sym('Y', 3, 3);
>> Y.set_nz(7, true, 1);
>> Y
(Y[0] = 7)
>> k = MX.sym('k');
>> Y.set_nz(8, true, k);
>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
((Y[0] = 7)[(k-1)] = 8)
1

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y.nz[1] = 7;
julia> Y
MX((Y[0] = 7))
julia> k = ca.MX.sym("k");
julia> Y.nz[k] = 8;
julia> Y
MX(((Y[0] = 7)[(k-1)] = 8))
julia> ca.is_op(Y, ca.OP_SETNONZEROS_PARAM)
true

See also
get_nz, set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qf

Definition at line 530 of file mx.cpp.

530  {
531  *this = m->get_nzassign(*this, ind1 ? kk-1 : kk);
532  }

References casadi::MXNode::get_nzassign().

◆ set_nz() [4/4]

void casadi::MX::set_nz ( const MX &  m,
bool  ind1,
const Slice &  kk 
)

Rebinds this object to a SetNonzeros node; the sparsity pattern is unchanged. m must have as many nonzeros as the index set or be a scalar. With an MX index the assignment is parametric and resolved at evaluation time.

>>> Y = MX.sym("Y", 3, 3)
>>> Y.nz[0] = 7
>>> Y
MX((Y[0] = 7))
>>> k = MX.sym("k")
>>> Y.nz[k] = 8
>>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
(MX(((Y[0] = 7)[k] = 8)), True)

>> Y = MX.sym('Y', 3, 3);
>> Y.set_nz(7, true, 1);
>> Y
(Y[0] = 7)
>> k = MX.sym('k');
>> Y.set_nz(8, true, k);
>> Y, Y.is_op(OP_SETNONZEROS_PARAM)
((Y[0] = 7)[(k-1)] = 8)
1

julia> Y = ca.MX.sym("Y", 3, 3);
julia> Y.nz[1] = 7;
julia> Y
MX((Y[0] = 7))
julia> k = ca.MX.sym("k");
julia> Y.nz[k] = 8;
julia> Y
MX(((Y[0] = 7)[(k-1)] = 8))
julia> ca.is_op(Y, ca.OP_SETNONZEROS_PARAM)
true

See also
get_nz, set

Extra doc: https://github.com/casadi/casadi/wiki/L_2qf

Definition at line 464 of file mx.cpp.

464  {
465  // Fallback on IM
466  set_nz(m, ind1, kk.all(nnz(), ind1));
467  }

References casadi::Slice::all(), and casadi::GenericMatrix< MX >::nnz().

Referenced by set(), and set_nz().

◆ set_temp()

void casadi::MX::set_temp ( casadi_int  t) const

Definition at line 897 of file mx.cpp.

897  {
898  (*this)->temp = t;
899  }

◆ shared()

void casadi::MX::shared ( std::vector< MX > &  ex,
std::vector< MX > &  v,
std::vector< MX > &  vdef,
const std::string &  v_prefix,
const std::string &  v_suffix 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1906 of file mx.cpp.

1907  {
1908  // Call new, more generic function
1909  extract(ex, v, vdef, Dict{{"lift_shared", true}, {"lift_calls", false},
1910  {"prefix", v_prefix}, {"suffix", v_suffix}});
1911  }
static void extract(std::vector< MX > &ex, std::vector< MX > &v, std::vector< MX > &vdef, const Dict &opts=Dict())
Definition: mx.cpp:1733

References extract().

◆ simplify()

MX casadi::MX::simplify ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1302 of file mx.cpp.

1302  {
1303  return x;
1304  }

◆ simplify_combine_terms()

bool casadi::MX::simplify_combine_terms ( std::vector< MX > &  arg,
std::vector< MX > &  res,
const Dict &  opts = Dict() 
)
static

Definition at line 1295 of file mx.cpp.

1297  {
1298  // No term-combining available for MX; leave the graph untouched
1299  return false;
1300  }

◆ simplify_const_folding()

bool casadi::MX::simplify_const_folding ( std::vector< MX > &  arg,
std::vector< MX > &  res,
const Dict &  opts = Dict() 
)
static

Definition at line 2381 of file mx.cpp.

2383  {
2384  simplify_const_folding_order(arg, res, opts);
2385  Dict temp_opts = {{"live_variables", false},
2386  {"max_io", 0},
2387  {"cse", false},
2388  {"allow_free", true}};
2389  Function f("temp", arg, res, temp_opts);
2390  MXFunction *ff = f.get<MXFunction>();
2391  const std::vector<casadi_int>& workloc_ = ff->workloc_;
2392  const auto& algorithm_ = ff->algorithm_;
2393 
2394  // Data structures for numeric evaluation
2395  std::vector<double> w_vec(f.sz_w());
2396  double* w = get_ptr(w_vec);
2397  std::vector<casadi_int> iw_vec(f.sz_iw());
2398  casadi_int* iw = get_ptr(iw_vec);
2399  std::vector<const double*> arg_num_vec(f.sz_arg());
2400  const double** arg_num = get_ptr(arg_num_vec);
2401  std::vector<double*> res_num_vec(f.sz_res());
2402  double** res_num = get_ptr(res_num_vec);
2403 
2404  // Is the work vector entry numeric?
2405  std::vector<bool> is_numeric(workloc_.size()-1);
2406 
2407  // Data structures for symbolic evaluation
2408 
2409  // Symbolic work, non-differentiated
2410  std::vector<MX> swork(workloc_.size()-1);
2411 
2412  // Split up inputs analogous to symbolic primitives
2413  std::vector<std::vector<MX> > arg_split(arg.size());
2414  for (casadi_int i=0; i<arg.size(); ++i) arg_split[i] = arg[i].split_primitives(arg[i]);
2415 
2416  // Allocate storage for split outputs
2417  std::vector<std::vector<MX> > res_split(res.size());
2418  for (casadi_int i=0; i<res.size(); ++i) res_split[i].resize(res[i].n_primitives());
2419 
2420  std::vector<MX> arg1, res1;
2421 
2422  std::unordered_multimap< std::size_t, std::pair<MX, DM> > cache;
2423 
2424  bool performed_folding = false;
2425 
2426  // Loop over computational nodes in forward order
2427  for (auto it=algorithm_.begin(); it!=algorithm_.end(); ++it) {
2428  if (it->op == OP_INPUT) {
2429  swork[it->res.front()] = project(arg_split.at(it->data->ind()).at(it->data->segment()),
2430  it->data.sparsity(), true);
2431  is_numeric[it->res.front()] = false;
2432  } else if (it->op==OP_OUTPUT) {
2433  // Collect the results
2434  MX& target = res_split.at(it->data->ind()).at(it->data->segment());
2435  casadi_int el = it->arg.front();
2436  if (is_numeric[el] && !it->data->dep().is_constant()) {
2437  target = get_const(it->data->dep().sparsity(), w + workloc_[el], cache);
2438  } else {
2439  target = swork[el];
2440  }
2441  } else if (it->op==OP_PARAMETER) {
2442  // Fetch parameter
2443  swork[it->res.front()] = it->data;
2444  is_numeric[it->res.front()] = false;
2445  } else {
2446  // Arguments of the operation
2447  arg1.resize(it->arg.size());
2448 
2449  // Is current algel numeric?
2450  bool numeric = true;
2451 
2452  // Loop over algel inputs
2453  for (casadi_int i=0; i<arg1.size(); ++i) {
2454  casadi_int el = it->arg[i];
2455  if (el<0) {
2456  // Populate arg1 vector
2457  arg1[i] = MX(it->data->dep(i).size());
2458  } else {
2459  // Populate arg1 vector
2460  arg1[i] = swork[el];
2461  // Can only be numeric if arguments are
2462  numeric = numeric && is_numeric[el];
2463  }
2464  }
2465 
2466  if (numeric) {
2467  // Set up arg_num and res_num for numerical evaluation
2468  for (casadi_int i=0; i<it->arg.size(); ++i)
2469  arg_num[i] = it->arg[i]>=0 ? w+workloc_[it->arg[i]] : nullptr;
2470  for (casadi_int i=0; i<it->res.size(); ++i)
2471  res_num[i] = it->res[i]>=0 ? w+workloc_[it->res[i]] : nullptr;
2472 
2473  if (it->data->eval(arg_num, res_num, iw, w)) casadi_error("Evaluation error");
2474  performed_folding = true;
2475  } else {
2476  // Prepare for symbolic evaluation
2477  for (casadi_int i=0; i<arg1.size(); ++i) {
2478  casadi_int el = it->arg[i];
2479  if (el>=0) {
2480  MX& target = arg1[i];
2481  if (is_numeric[el] && !it->data->dep(i).is_constant()) {
2482  target = get_const(it->data->dep(i).sparsity(), w + workloc_[el], cache);
2483  } else {
2484  target = swork[el];
2485  }
2486  }
2487  }
2488  }
2489 
2490  // Perform the operation
2491  res1.resize(it->res.size());
2492  it->data->eval_mx(arg1, res1);
2493 
2494  // Process results
2495  for (casadi_int i=0; i<res1.size(); ++i) {
2496  casadi_int el = it->res[i]; // index of the output
2497  if (el>=0) {
2498  swork[el] = res1[i]; // store symbolic result
2499  is_numeric[el] = numeric; // store flag
2500  }
2501  }
2502  }
2503  }
2504 
2505  // Join split outputs
2506  for (casadi_int i=0; i<res.size(); ++i) res[i] = res[i].join_primitives(res_split[i]);
2507 
2508  return performed_folding;
2509  }
MX get_const(const Sparsity &sp, const double *v, std::unordered_multimap< std::size_t, std::pair< MX, DM > > &cache)
Definition: mx.cpp:2353
bool simplify_const_folding_order(std::vector< MX > &arg, std::vector< MX > &res, const Dict &opts)
Definition: mx.cpp:2254

References casadi::MXFunction::algorithm_, casadi::MXNode::eval_mx(), casadi::Function::get(), casadi::get_const(), casadi::get_ptr(), join_primitives(), MX(), n_primitives(), casadi::OP_INPUT, casadi::OP_OUTPUT, casadi::OP_PARAMETER, project(), casadi::simplify_const_folding_order(), split_primitives(), casadi::Function::sz_arg(), casadi::Function::sz_iw(), casadi::Function::sz_res(), casadi::Function::sz_w(), and casadi::MXFunction::workloc_.

◆ simplify_ref_count()

bool casadi::MX::simplify_ref_count ( std::vector< MX > &  arg,
std::vector< MX > &  res,
const Dict &  opts = Dict() 
)
static

Definition at line 2511 of file mx.cpp.

2513  {
2514  Dict temp_opts = {{"live_variables", false},
2515  {"max_io", 0},
2516  {"cse", false},
2517  {"allow_free", true}};
2518  Function f("temp", arg, res, temp_opts);
2519  MXFunction *ff = f.get<MXFunction>();
2520  const std::vector<casadi_int>& workloc_ = ff->workloc_;
2521  const auto& algorithm_ = ff->algorithm_;
2522 
2523  std::vector<casadi_int> rwork(workloc_.size()-1);
2524  for (auto it=algorithm_.begin(); it!=algorithm_.end(); ++it) {
2525  if (it->op == OP_INPUT) {
2526  } else if (it->op==OP_OUTPUT) {
2527  rwork[it->arg.front()]++;
2528  } else if (it->op==OP_PARAMETER) {
2529  rwork[it->res.front()]++;
2530  } else {
2531  for (casadi_int i=0; i<it->arg.size(); ++i) {
2532  casadi_int el = it->arg[i];
2533  if (el>=0) {
2534  rwork[el]++;
2535  }
2536  }
2537  }
2538  }
2539 
2540  // Forward pass
2541  {
2542 
2543  // Symbolic work, non-differentiated
2544  std::vector<MX> swork(workloc_.size()-1);
2545 
2546  // Split up inputs analogous to symbolic primitives
2547  std::vector<std::vector<MX> > arg_split(arg.size());
2548  for (casadi_int i=0; i<arg.size(); ++i) arg_split[i] = arg[i].split_primitives(arg[i]);
2549 
2550  // Allocate storage for split outputs
2551  std::vector<std::vector<MX> > res_split(res.size());
2552  for (casadi_int i=0; i<res.size(); ++i) res_split[i].resize(res[i].n_primitives());
2553 
2554  std::vector<MX> arg1, res1;
2555 
2556  // Loop over computational nodes in forward order
2557  for (auto it=algorithm_.begin(); it!=algorithm_.end(); ++it) {
2558  if (it->op == OP_INPUT) {
2559  swork[it->res.front()] = project(arg_split.at(it->data->ind()).at(it->data->segment()),
2560  it->data.sparsity(), true);
2561  } else if (it->op==OP_OUTPUT) {
2562  // Collect the results
2563  res_split.at(it->data->ind()).at(it->data->segment()) = swork[it->arg.front()];
2564  } else if (it->op==OP_PARAMETER) {
2565  // Fetch parameter
2566  swork[it->res.front()] = it->data;
2567  } else {
2568  // Arguments of the operation
2569  arg1.resize(it->arg.size());
2570 
2571  std::vector<bool> unique(it->arg.size(), true);
2572  for (casadi_int i=0; i<arg1.size(); ++i) {
2573  casadi_int el = it->arg[i];
2574  if (el<0) {
2575  arg1[i] = MX(it->data->dep(i).size());
2576  } else {
2577  arg1[i] = swork[el];
2578  if (rwork[el]>1) unique[i] = false;
2579  }
2580  }
2581 
2582  // Perform the operation
2583  res1.resize(it->res.size());
2584  it->data->eval_mx(arg1, res1, unique);
2585 
2586  // Get the result
2587  for (casadi_int i=0; i<res1.size(); ++i) {
2588  casadi_int el = it->res[i]; // index of the output
2589  if (el>=0) {
2590  swork[el] = res1[i];
2591  }
2592  }
2593  }
2594  }
2595 
2596  // Join split outputs
2597  for (casadi_int i=0; i<res.size(); ++i) res[i] = res[i].join_primitives(res_split[i]);
2598  }
2599  return true;
2600  }

References casadi::MXFunction::algorithm_, casadi::Function::get(), join_primitives(), MX(), n_primitives(), casadi::OP_INPUT, casadi::OP_OUTPUT, casadi::OP_PARAMETER, project(), split_primitives(), and casadi::MXFunction::workloc_.

◆ size() [1/2]

std::pair< casadi_int, casadi_int > casadi::GenericMatrix< MX >::size
inherited

>>> x = MX.sym("x", 2, 3)
>>> x.size(), x.size(1), x.size(2)
((2, 3), 2, 3)

>> x = MX.sym('x', 2, 3);
>> size(x)
2 3
>> fprintf('%d %d\n', size(x, 1), size(x, 2))
2 3

julia> x = ca.MX.sym("x", 2, 3);
julia> size(x), size(x, 1), size(x, 2)
((2, 3), 2, 3)

See also
size1, size2, numel, dim

Extra doc: https://github.com/casadi/casadi/wiki/L_1ax

Definition at line 358 of file generic_matrix.hpp.

5264  {
5265  return sparsity().size();
5266  }
std::pair< casadi_int, casadi_int > size() const
Shape as a pair (number of rows, number of columns)
Definition: sparsity.cpp:154

◆ size() [2/2]

casadi_int casadi::GenericMatrix< MX >::size ( casadi_int  axis) const
inherited
Parameters
axis1 for the number of rows, 2 for the number of columns; any other value raises an error

Extra doc: https://github.com/casadi/casadi/wiki/L_1ay

Definition at line 366 of file generic_matrix.hpp.

5269  {
5270  return sparsity().size(axis);
5271  }

◆ size1()

casadi_int casadi::GenericMatrix< MX >::size1
inherited

>>> x = MX.sym("x", 2, 3)
>>> x.size1(), x.size2()
(2, 3)

>> x = MX.sym('x', 2, 3);
>> fprintf('%d %d\n', x.size1(), x.size2())
2 3

julia> x = ca.MX.sym("x", 2, 3);
julia> ca.size1(x), ca.size2(x)
(2, 3)

See also
size2, size, rows

Extra doc: https://github.com/casadi/casadi/wiki/L_1as

Definition at line 278 of file generic_matrix.hpp.

5254  {
5255  return sparsity().size1();
5256  }
casadi_int size1() const
Number of rows.
Definition: sparsity.cpp:124

◆ size2()

casadi_int casadi::GenericMatrix< MX >::size2
inherited
See also
size1, size, columns

Extra doc: https://github.com/casadi/casadi/wiki/L_1au

Definition at line 290 of file generic_matrix.hpp.

5259  {
5260  return sparsity().size2();
5261  }
casadi_int size2() const
Number of columns.
Definition: sparsity.cpp:128

◆ skew()

MX casadi::GenericMatrix< MX >::skew ( const MX &  a)
staticinherited

Definition at line 663 of file generic_matrix.hpp.

5432  {
5433  casadi_assert(a.is_vector() && (a.size1()==3 || a.size2()==3),
5434  "skew(a): Expecting 3-vector, got " + a.dim() + ".");
5435 
5436  MatType x = a(0);
5437  MatType y = a(1);
5438  MatType z = a(2);
5439  return blockcat(std::vector< std::vector<MatType> >({{0, -z, y}, {z, 0, -x}, {-y, x, 0}}));
5440  }
friend MatType blockcat(const std::vector< std::vector< MatType > > &v)
Construct a matrix from a list of lists of blocks.

◆ soc()

static MX casadi::GenericMatrix< MX >::soc ( const MX &  x,
const MX &  y 
)
staticinherited

Functions called by friend functions defined here

◆ solve() [1/2]

MX casadi::MX::solve ( const MX &  a,
const MX &  b 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2108 of file mx.cpp.

2108  {
2109  if (a.is_triu()) {
2110  // A is upper triangular
2111  return a->get_solve_triu(b, false);
2112  } else if (a.is_tril()) {
2113  // A is lower triangular
2114  return a->get_solve_tril(b, false);
2115  } else if (a.sparsity().is_orthonormal()) {
2116  // A is orthonormal -> inv(A)==A.T
2117  MX nz = sparsity_cast(a, Sparsity::dense(a.nnz()));
2118  const Sparsity& Q = a.sparsity();
2119  return mtimes(MX(Q, 1/nz).T(), b);
2120  } else {
2121  // Fall-back to QR factorization
2122  return solve(a, b, "qr");
2123  }
2124  }
static MX sparsity_cast(const MX &x, const Sparsity &sp)
Definition: mx.cpp:1352

References casadi::Sparsity::dense(), casadi::MXNode::get_solve_tril(), casadi::MXNode::get_solve_triu(), casadi::Sparsity::is_orthonormal(), casadi::GenericMatrix< MatType >::is_tril(), casadi::GenericMatrix< MatType >::is_triu(), mtimes(), MX(), casadi::GenericMatrix< MatType >::nnz(), casadi::GenericMatrix< MX >::nz(), casadi::Q, sparsity(), sparsity_cast(), and T().

Referenced by casadi::Conic::get_forward(), casadi::Nlpsol::get_forward(), casadi::Conic::get_reverse(), casadi::Nlpsol::get_reverse(), inv(), mldivide(), mrdivide(), pinv(), and solve().

◆ solve() [2/2]

MX casadi::MX::solve ( const MX &  a,
const MX &  b,
const std::string &  lsolver,
const Dict &  dict = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2126 of file mx.cpp.

2126  {
2127  if (a.sparsity().is_orthonormal()) return solve(a, b);
2128  Linsol mysolver("tmp_solve", lsolver, a.sparsity(), dict);
2129  return mysolver.solve(a, b, false);
2130  }

References casadi::Sparsity::is_orthonormal(), casadi::Linsol::solve(), solve(), and sparsity().

◆ sparsity()

const Sparsity & casadi::MX::sparsity ( ) const

Every node has a fixed sparsity pattern, known at construction time.

>>> MX.sym("S", Sparsity.lower(2)).sparsity()
Sparsity(2x2,3nz)
>>> (MX.sym("S", Sparsity.lower(2)) + 1).sparsity()
Sparsity(2x2)

>> MX.sym('S', Sparsity.lower(2)).sparsity()
2x2,3nz
>> e = MX.sym('S', Sparsity.lower(2)) + 1;
>> e.sparsity()
2x2

julia> ca.sparsity(ca.MX.sym("S", ca.Sparsity.lower(2)))
Sparsity(2x2,3nz)
julia> ca.sparsity(ca.MX.sym("S", ca.Sparsity.lower(2)) + 1)
Sparsity(2x2)

Extra doc: https://github.com/casadi/casadi/wiki/L_qc

Definition at line 615 of file mx.cpp.

615  {
616  return (*this)->sparsity();
617  }

Referenced by casadi::MXNode::_get_binary(), casadi::Constant< Value >::_get_binary(), casadi::UnaryMX::_get_binary(), casadi::GetNonzeros::ad_forward(), casadi::SetNonzeros< Add >::ad_forward(), casadi::GetNonzeros::ad_reverse(), casadi::KronContract::ad_reverse(), casadi::Solve< Tr >::ad_reverse(), casadi::SparsityCast::ad_reverse(), casadi::DaeBuilderInternal::add(), casadi::Assertion::Assertion(), casadi::BinaryMX< ScX, ScY >::BinaryMX(), casadi::OptiNode::canon_expr(), casadi::Convexify::Convexify(), casadi::GetNonzerosParam::create(), casadi::SetNonzeros< Add >::create(), casadi::GetNonzeros::create(), cumsum(), densify(), det(), diag(), casadi::Diagsplit::Diagsplit(), casadi::Dot::Dot(), casadi::dplesol(), casadi::Dump::Dump(), enlarge(), erase(), casadi::GetNonzeros::eval_mx(), casadi::SetNonzeros< Add >::eval_mx(), expm(), expm_const(), casadi::MXFunction::export_code_body(), casadi::MXFunction::generate_lifted(), get(), casadi::MXNode::get_binary(), casadi::Variable::get_der(), casadi::MXNode::get_dot(), casadi::Nlpsol::get_forward(), casadi::MXNode::get_kron_contract(), casadi::MXNode::get_mac(), casadi::Project::get_nzref(), casadi::Nlpsol::get_reverse(), casadi::HorzRepmat::HorzRepmat(), casadi::HorzRepsum::HorzRepsum(), casadi::Horzsplit::Horzsplit(), casadi::Scpgen::init(), casadi::RuntimeIntegrator::jump_function(), casadi::Kron::Kron(), casadi::KronContract::KronContract(), lift(), casadi::Onnx::load(), casadi::Low::Low(), matrix_expand(), casadi::Monitor::Monitor(), mtimes(), casadi::Multiplication::Multiplication(), MX(), nullspace(), casadi::Horzcat::off(), casadi::Vertcat::off(), casadi::Diagcat::off(), casadi::DaeBuilderInternal::outputs(), casadi::MXFunction::print_arg(), project(), casadi::Rank1::Rank1(), casadi::register_symbol(), reshape(), set(), set_nz(), casadi::SetNonzeros< Add >::SetNonzeros(), casadi::SetNonzerosParam< Add >::SetNonzerosParam(), casadi::simpleIRK(), solve(), casadi::Solve< Tr >::Solve(), casadi::Bilin::sp_forward(), casadi::KronContract::sp_forward(), casadi::Bilin::sp_reverse(), casadi::KronContract::sp_reverse(), casadi::Project::sp_reverse(), sparsity_cast(), casadi::Transpose::Transpose(), casadi::PseudoDenseMultiplication::try_create(), unite(), and casadi::Vertsplit::Vertsplit().

◆ sparsity_cast()

MX casadi::MX::sparsity_cast ( const MX &  x,
const Sparsity &  sp 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1352 of file mx.cpp.

1352  {
1353  casadi_assert(x.nnz()==sp.nnz(),
1354  "Mismatching nonzero count: " + str(x.nnz()) + " versus " +
1355  str(sp.nnz()) + ".");
1356 
1357  // Quick return if trivial
1358  if (sp==x.sparsity()) return x;
1359 
1360  // Call internal method
1361  return x->get_sparsity_cast(sp);
1362  }

References casadi::MXNode::get_sparsity_cast(), casadi::GenericMatrix< MatType >::nnz(), casadi::Sparsity::nnz(), sparsity(), and casadi::str().

Referenced by solve().

◆ split_primitives() [1/3]

std::vector< DM > casadi::MX::split_primitives ( const DM &  x) const

Uses this expression (a valid Function input, see is_valid_input) as a template: x must have the same shape and is cut into one piece per primitive, each with the shape of that primitive. The typical use is to split a solver result back into the variables it was concatenated from. Works with numeric (DM), SX and MX values. A shape mismatch raises an error.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> X = vertcat(x, y)
>>> X.split_primitives(DM([1, 2, 3, 4, 5]))
[DM([1, 2]), DM([3, 4, 5])]
>>> X.split_primitives(SX.sym("z", 5))
[SX([z_0, z_1]), SX([z_2, z_3, z_4])]

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> X = [x; y];
>> parts = X.split_primitives(DM([1; 2; 3; 4; 5]));
>> parts{1}, parts{2}
[1, 2]
[3, 4, 5]
>> parts = X.split_primitives(SX.sym('z', 5));
>> parts{1}, parts{2}
[z_0, z_1]
[z_2, z_3, z_4]

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> X = [x; y];
julia> ca.split_primitives(X, ca.DM([1, 2, 3, 4, 5]))
2-element Vector{DM}:
 DM([1, 2])
 DM([3, 4, 5])
julia> ca.split_primitives(X, ca.SX.sym("z", 5))
2-element Vector{SX}:
 SX([z_0, z_1])
 SX([z_2, z_3, z_4])

See also
join_primitives, primitives

Extra doc: https://github.com/casadi/casadi/wiki/L_qq

Definition at line 989 of file mx.cpp.

989  {
990  std::vector<DM> ret(n_primitives());
991  std::vector<DM>::iterator it=ret.begin();
992  (*this)->split_primitives(x, it);
993  casadi_assert_dev(it==ret.end());
994  return ret;
995  }

References n_primitives().

◆ split_primitives() [2/3]

std::vector< MX > casadi::MX::split_primitives ( const MX &  x) const

Uses this expression (a valid Function input, see is_valid_input) as a template: x must have the same shape and is cut into one piece per primitive, each with the shape of that primitive. The typical use is to split a solver result back into the variables it was concatenated from. Works with numeric (DM), SX and MX values. A shape mismatch raises an error.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> X = vertcat(x, y)
>>> X.split_primitives(DM([1, 2, 3, 4, 5]))
[DM([1, 2]), DM([3, 4, 5])]
>>> X.split_primitives(SX.sym("z", 5))
[SX([z_0, z_1]), SX([z_2, z_3, z_4])]

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> X = [x; y];
>> parts = X.split_primitives(DM([1; 2; 3; 4; 5]));
>> parts{1}, parts{2}
[1, 2]
[3, 4, 5]
>> parts = X.split_primitives(SX.sym('z', 5));
>> parts{1}, parts{2}
[z_0, z_1]
[z_2, z_3, z_4]

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> X = [x; y];
julia> ca.split_primitives(X, ca.DM([1, 2, 3, 4, 5]))
2-element Vector{DM}:
 DM([1, 2])
 DM([3, 4, 5])
julia> ca.split_primitives(X, ca.SX.sym("z", 5))
2-element Vector{SX}:
 SX([z_0, z_1])
 SX([z_2, z_3, z_4])

See also
join_primitives, primitives

Extra doc: https://github.com/casadi/casadi/wiki/L_qq

Definition at line 973 of file mx.cpp.

973  {
974  std::vector<MX> ret(n_primitives());
975  std::vector<MX>::iterator it=ret.begin();
976  (*this)->split_primitives(x, it);
977  casadi_assert_dev(it==ret.end());
978  return ret;
979  }

References n_primitives().

Referenced by extract_parametric(), casadi::DaeBuilderInternal::load_fmi_description(), separate_linear(), simplify_const_folding(), and simplify_ref_count().

◆ split_primitives() [3/3]

std::vector< SX > casadi::MX::split_primitives ( const SX &  x) const

Uses this expression (a valid Function input, see is_valid_input) as a template: x must have the same shape and is cut into one piece per primitive, each with the shape of that primitive. The typical use is to split a solver result back into the variables it was concatenated from. Works with numeric (DM), SX and MX values. A shape mismatch raises an error.

>>> x = MX.sym("x", 2)
>>> y = MX.sym("y", 3)
>>> X = vertcat(x, y)
>>> X.split_primitives(DM([1, 2, 3, 4, 5]))
[DM([1, 2]), DM([3, 4, 5])]
>>> X.split_primitives(SX.sym("z", 5))
[SX([z_0, z_1]), SX([z_2, z_3, z_4])]

>> x = MX.sym('x', 2); y = MX.sym('y', 3);
>> X = [x; y];
>> parts = X.split_primitives(DM([1; 2; 3; 4; 5]));
>> parts{1}, parts{2}
[1, 2]
[3, 4, 5]
>> parts = X.split_primitives(SX.sym('z', 5));
>> parts{1}, parts{2}
[z_0, z_1]
[z_2, z_3, z_4]

julia> x = ca.MX.sym("x", 2); y = ca.MX.sym("y", 3);
julia> X = [x; y];
julia> ca.split_primitives(X, ca.DM([1, 2, 3, 4, 5]))
2-element Vector{DM}:
 DM([1, 2])
 DM([3, 4, 5])
julia> ca.split_primitives(X, ca.SX.sym("z", 5))
2-element Vector{SX}:
 SX([z_0, z_1])
 SX([z_2, z_3, z_4])

See also
join_primitives, primitives

Extra doc: https://github.com/casadi/casadi/wiki/L_qq

Definition at line 981 of file mx.cpp.

981  {
982  std::vector<SX> ret(n_primitives());
983  std::vector<SX>::iterator it=ret.begin();
984  (*this)->split_primitives(x, it);
985  casadi_assert_dev(it==ret.end());
986  return ret;
987  }

References n_primitives().

◆ sprank()

static casadi_int casadi::GenericMatrix< MX >::sprank ( const MX &  x)
inlinestaticinherited

Definition at line 650 of file generic_matrix.hpp.

650 { return Sparsity::sprank(x.sparsity());}

◆ stop_diff() [1/2]

MX casadi::MX::stop_diff ( const MX &  expr,
casadi_int  order 
)
static

Functions called by friend functions defined for this class

Definition at line 3020 of file mx.cpp.

3020  {
3021  std::vector<MX> s = symvar(expr);
3022  MX x = veccat(s);
3023  Dict options;
3024  options["never_inline"] = true;
3025 
3026  Dict inline_options;
3027  inline_options["never_inline"] = false;
3028  inline_options["always_inline"] = true;
3029  Dict der_options = Dict{{"forward_options", inline_options},
3030  {"reverse_options", inline_options},
3031  {"jacobian_options", inline_options}};
3032  if (order==1) {
3033  options["is_diff_in"] = std::vector<bool>{false};
3034  options["is_diff_out"] = std::vector<bool>{true};
3035  options = combine(options, der_options);
3036  } else if (order==2) {
3037  options["der_options"] = der_options;
3038  options["forward_options"] = Dict{{"is_diff_in", std::vector<bool>{false, true, true} },
3039  {"is_diff_out", std::vector<bool>{true}}};
3040  options["reverse_options"] = Dict{{"is_diff_in", std::vector<bool>{false, true, true} },
3041  {"is_diff_out", std::vector<bool>{true}}};
3042  options["jacobian_options"] = Dict{{"is_diff_in", std::vector<bool>{false, true} },
3043  {"is_diff_out", std::vector<bool>{false}}};
3044  } else {
3045  casadi_error("stop_diff: order must be 1 or 2, got " + str(order) + ".");
3046  }
3047 
3048  Function FS("FS", {x}, {expr}, {"x"}, {"z"}, options);
3049  return FS(std::vector<MX>{x})[0];
3050  }
Dict combine(const Dict &first, const Dict &second, bool recurse)
Combine two dicts. First has priority.

References casadi::combine(), casadi::str(), symvar(), and casadi::SparsityInterface< MatType >::veccat().

◆ stop_diff() [2/2]

MX casadi::MX::stop_diff ( const MX &  expr,
const MX &  var,
casadi_int  order 
)
static

Functions called by friend functions defined for this class

Definition at line 3052 of file mx.cpp.

3052  {
3053  casadi_warning("stop_diff(expr, var, order) is not well tested.");
3054  std::vector<MX> xv = symvar(var);
3055  std::vector<MX> s = symvar(expr);
3056  std::vector<MX> yv = difference(s, xv);
3057 
3058  MX x = veccat(xv);
3059  MX y = veccat(yv);
3060 
3061  Dict options;
3062  options["never_inline"] = true;
3063 
3064  Dict inline_options;
3065  inline_options["never_inline"] = false;
3066  inline_options["always_inline"] = true;
3067  Dict der_options = Dict{{"forward_options", inline_options},
3068  {"reverse_options", inline_options},
3069  {"jacobian_options", inline_options}};
3070  if (order==1) {
3071  options["is_diff_in"] = std::vector<bool>{false, true};
3072  options["is_diff_out"] = std::vector<bool>{true};
3073  options = combine(options, der_options);
3074  } else if (order==2) {
3075  options["der_options"] = der_options;
3076  options["forward_options"] = Dict{{"is_diff_in",
3077  std::vector<bool>{false, true, false, true, true} },
3078  {"is_diff_out", std::vector<bool>{true}}};
3079  options["reverse_options"] = Dict{{"is_diff_in",
3080  std::vector<bool>{false, true, false, true}},
3081  {"is_diff_out", std::vector<bool>{false, true}}};
3082  options["jacobian_options"] = Dict{{"is_diff_in", std::vector<bool>{false, true, true}},
3083  {"is_diff_out", std::vector<bool>{true}}};
3084  } else {
3085  casadi_error("stop_diff: order must be 1 or 2, got " + str(order) + ".");
3086  }
3087 
3088  Function FS("FS", {x, y}, {expr}, {"x", "y"}, {"z"}, options);
3089  return FS(std::vector<MX>{x, y})[0];
3090  }
static std::vector< MX > difference(const std::vector< MX > &a, const std::vector< MX > &b)
Definition: mx.cpp:3092

References casadi::combine(), difference(), casadi::str(), symvar(), and casadi::SparsityInterface< MatType >::veccat().

◆ substitute() [1/2]

MX casadi::MX::substitute ( const MX &  ex,
const MX &  v,
const MX &  vdef 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1518 of file mx.cpp.

1518  {
1519  return substitute(std::vector<MX>{ex}, std::vector<MX>{v}, std::vector<MX>{vdef}).front();
1520  }
static MX substitute(const MX &ex, const MX &v, const MX &vdef)
Definition: mx.cpp:1518

Referenced by casadi::RuntimeIntegrator::jump_function(), and casadi::DaeBuilderInternal::transition().

◆ substitute() [2/2]

std::vector< MX > casadi::MX::substitute ( const std::vector< MX > &  ex,
const std::vector< MX > &  v,
const std::vector< MX > &  vdef 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1522 of file mx.cpp.

1523  {
1524  // Assert consistent dimensions
1525  casadi_assert_dev(v.size()==vdef.size());
1526 
1527  // Quick return if all equal
1528  bool all_equal = true;
1529  for (casadi_int k=0; k<v.size(); ++k) {
1530  if (v[k].size()!=vdef[k].size() || !is_equal(v[k], vdef[k])) {
1531  all_equal = false;
1532  break;
1533  }
1534  }
1535  if (all_equal) return ex;
1536 
1537  // Otherwise, evaluate symbolically
1538  Function F("tmp_substitute", v, ex, Dict{{"max_io", 0}, {"allow_free", true}});
1539  std::vector<MX> ret;
1540  F.call(vdef, ret, true);
1541  return ret;
1542  }

References casadi::Function::call(), is_equal(), and casadi::GenericMatrix< MX >::size().

◆ substitute_inplace()

void casadi::MX::substitute_inplace ( const std::vector< MX > &  v,
std::vector< MX > &  vdef,
std::vector< MX > &  ex,
bool  reverse 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1496 of file mx.cpp.

1497  {
1498  casadi_assert(v.size()==vdef.size(),
1499  "Mismatch in the number of expression to substitute.");
1500  for (casadi_int k=0; k<v.size(); ++k) {
1501  casadi_assert(v[k].is_symbolic(),
1502  "Variable " + str(k) + " is not symbolic");
1503  casadi_assert(v[k].size() == vdef[k].size(),
1504  "Inconsistent shape for variable " + str(k) + ".");
1505  }
1506  casadi_assert(reverse==false, "Not implemented");
1507 
1508  // quick return if nothing to replace
1509  if (v.empty()) return;
1510 
1511  // implemented in MXFunction
1512  std::vector<MX> f_out = vdef;
1513  f_out.insert(f_out.end(), ex.begin(), ex.end());
1514  Function temp("tmp_substitute_inplace", {v}, f_out, Dict{{"max_io", 0}, {"allow_free", true}});
1515  temp.get<MXFunction>()->substitute_inplace(vdef, ex);
1516  }
static void substitute_inplace(const std::vector< MX > &v, std::vector< MX > &vdef, std::vector< MX > &ex, bool reverse)
Definition: mx.cpp:1496
static std::vector< std::vector< MX > > reverse(const std::vector< MX > &ex, const std::vector< MX > &arg, const std::vector< std::vector< MX > > &v, const Dict &opts=Dict())
Definition: mx.cpp:1973
bool is_symbolic() const
Check if the node is a symbolic primitive (created by MX.sym)
Definition: mx.cpp:798

References casadi::Function::get(), is_symbolic(), reverse(), casadi::GenericMatrix< MX >::size(), and casadi::str().

◆ sum1()

MX casadi::MX::sum1 ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1476 of file mx.cpp.

1476  {
1477  return mtimes(MX::ones(1, x.size1()), x);
1478  }

References mtimes(), casadi::GenericMatrix< MX >::ones(), and casadi::GenericMatrix< MatType >::size1().

◆ sum2()

MX casadi::MX::sum2 ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1472 of file mx.cpp.

1472  {
1473  return mtimes(x, MX::ones(x.size2(), 1));
1474  }

References mtimes(), casadi::GenericMatrix< MX >::ones(), and casadi::GenericMatrix< MatType >::size2().

◆ sumsqr()

static MX casadi::GenericMatrix< MX >::sumsqr ( const MX &  x)
inlinestaticinherited

Definition at line 660 of file generic_matrix.hpp.

660 { return dot(x, x);}
friend MX dot(const MX &x, const MX &y)
Inner product of two matrices.

◆ swap()

Definition at line 105 of file generic_shared_impl.hpp.

131  {
132  GenericShared<Shared, Internal> temp = *this;
133  *this = other;
134  other = temp;
135  }

◆ sym() [1/7]

static std::vector<MX > casadi::GenericMatrix< MX >::sym ( const std::string &  name,
casadi_int  nrow,
casadi_int  ncol,
casadi_int  p 
)
inlinestaticinherited

>>> SX.sym("x", 1, 1, 2)
[SX(x0), SX(x1)]

>> v = SX.sym('x', 1, 1, 2);
>> v{1}, v{2}
x0
x1

julia> ca.SX.sym("x", 1, 1, 2)
2-element Vector{SX}:
 SX(x0)
 SX(x1)

Extra doc: https://github.com/casadi/casadi/wiki/L_1de

Definition at line 5063 of file generic_matrix.hpp.

5064  {
5065  return sym(name, Sparsity::dense(nrow, ncol), p);
5066  }

◆ sym() [2/7]

static std::vector<std::vector<MX > > casadi::GenericMatrix< MX >::sym ( const std::string &  name,
casadi_int  nrow,
casadi_int  ncol,
casadi_int  p,
casadi_int  r 
)
inlinestaticinherited

>>> MX.sym("x", 1, 1, 2, 2)
[[MX(x_00), MX(x_01)], [MX(x_10), MX(x_11)]]

>> v = MX.sym('x', 1, 1, 2, 2);
>> numel(v), v{1}{2}, v{2}{1}
2
x_01
x_10

julia> ca.MX.sym("x", 1, 1, 2, 2)
2-element Vector{Vector{MX}}:
 MX[x_00, x_01]
 MX[x_10, x_11]

Extra doc: https://github.com/casadi/casadi/wiki/L_1dg

Definition at line 5107 of file generic_matrix.hpp.

5107  {
5108  return sym(name, Sparsity::dense(nrow, ncol), p, r);
5109  }

◆ sym() [3/7]

static MX casadi::GenericMatrix< MX >::sym ( const std::string &  name,
casadi_int  nrow = 1,
casadi_int  ncol = 1 
)
inlinestaticinherited

Creates a new, dense symbol; two symbols with the same name are still different symbols. For SX each entry is a separate scalar symbol named name_k (k the column-major index), while an MX symbol is a single node with the given name. Only SX and MX have symbols; DM.sym raises an error.

Parameters
nameName used for printing. For SX, a name of the form "[a,b,c]" assigns individual names to the numel() entries.
nrowNumber of rows, default 1
ncolNumber of columns, default 1

>>> SX.sym("x"), MX.sym("x", 2, 3).dim()
(SX(x), '2x3')
>>> SX.sym("x", 2, 2)
SX(
[[x_0, x_2],
 [x_1, x_3]])
>>> SX.sym("[a,b,c]", 3)
SX([a, b, c])
>>> is_equal(SX.sym("x"), SX.sym("x"))
False

>> SX.sym('x'), MX.sym('x', 2, 3).dim()
x
2x3
>> SX.sym('x', 2, 2)
[[x_0, x_2],
 [x_1, x_3]]
>> SX.sym('[a,b,c]', 3)
[a, b, c]
>> is_equal(SX.sym('x'), SX.sym('x'))
0

julia> ca.SX.sym("x"), ca.dim(ca.MX.sym("x", 2, 3))
(x, "2x3")
julia> ca.SX.sym("x", 2, 2)
SX(
[[x_0, x_2],
 [x_1, x_3]])
julia> ca.SX.sym("[a,b,c]", 3)
SX([a, b, c])
julia> isequal(ca.SX.sym("x"), ca.SX.sym("x"))
false

See also
symvar, zeros, ones

Extra doc: https://github.com/casadi/casadi/wiki/L_1da

Definition at line 4948 of file generic_matrix.hpp.

4948  {
4949  return sym(name, Sparsity::dense(nrow, ncol));
4950  }

◆ sym() [4/7]

static MX casadi::GenericMatrix< MX >::sym ( const std::string &  name,
const Sparsity &  sp 
)
inlinestaticinherited

Only the structural nonzeros of sp become symbolic entries; for SX they are numbered by nonzero index.

>>> SX.sym("p", Sparsity.diag(2))
SX(
[[p_0, 00],
 [00, p_1]])
>>> MX.sym("p", Sparsity.diag(2)).dim(True)
'2x2,2nz'

>> SX.sym('p', Sparsity.diag(2))
[[p_0, 00],
 [00, p_1]]
>> MX.sym('p', Sparsity.diag(2)).dim(true)
2x2,2nz

julia> ca.SX.sym("p", ca.Sparsity.diag(2))
SX(
[[p_0, 00],
 [00, p_1]])
julia> ca.dim(ca.MX.sym("p", ca.Sparsity.diag(2)), true)
"2x2,2nz"

Extra doc: https://github.com/casadi/casadi/wiki/L_1dc

Definition at line 4997 of file generic_matrix.hpp.

4997  {
4998  return MatType::_sym(name, sp);
4999  }

◆ sym() [5/7]

std::vector< MX > casadi::GenericMatrix< MX >::sym ( const std::string &  name,
const Sparsity &  sp,
casadi_int  p 
)
staticinherited

The k-th symbol is named name followed by k (no separator).

>>> MX.sym("x", Sparsity.dense(2, 1), 3)
[MX(x0), MX(x1), MX(x2)]

>> v = MX.sym('x', Sparsity.dense(2, 1), 3);
>> numel(v), v{1}, v{3}
3
x0
x2

julia> ca.MX.sym("x", ca.Sparsity.dense(2, 1), 3)
3-element Vector{MX}:
 MX(x0)
 MX(x1)
 MX(x2)

Extra doc: https://github.com/casadi/casadi/wiki/L_1dd

Definition at line 5033 of file generic_matrix.hpp.

5287  {
5288  std::vector<MatType> ret(p);
5289  std::stringstream ss;
5290  for (casadi_int k=0; k<p; ++k) {
5291  ss.str("");
5292  ss << name << k;
5293  ret[k] = sym(ss.str(), sp);
5294  }
5295  return ret;
5296  }

◆ sym() [6/7]

std::vector< std::vector< MX > > casadi::GenericMatrix< MX >::sym ( const std::string &  name,
const Sparsity &  sp,
casadi_int  p,
casadi_int  r 
)
staticinherited

with given sparsity. The symbol at outer index i and inner index k is named name_ik.

Extra doc: https://github.com/casadi/casadi/wiki/L_1df

Definition at line 5075 of file generic_matrix.hpp.

5301  {
5302  std::vector<std::vector<MatType> > ret(r);
5303  for (casadi_int k=0; k<r; ++k) {
5304  std::stringstream ss;
5305  ss << name << "_" << k;
5306  ret[k] = sym(ss.str(), sp, p);
5307  }
5308  return ret;
5309  }

◆ sym() [7/7]

static MX casadi::GenericMatrix< MX >::sym ( const std::string &  name,
const std::pair< casadi_int, casadi_int > &  rc 
)
inlinestaticinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_1db

Definition at line 4955 of file generic_matrix.hpp.

4955  {
4956  return sym(name, rc.first, rc.second);
4957  }

◆ symvar()

std::vector< MX > casadi::MX::symvar ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2034 of file mx.cpp.

2034  {
2035  Function f("f", std::vector<MX>{}, {x}, {{"allow_free", true}});
2036  return f.free_mx();
2037  }

References casadi::Function::free_mx().

Referenced by conditional(), if_else(), matrix_expand(), casadi::OptiNode::set_initial(), casadi::OptiNode::set_linear_scale(), casadi::OptiNode::set_value(), stop_diff(), casadi::OptiNode::symvar(), transform(), and casadi::OptiNode::update_user_dict().

◆ T()

MX casadi::MX::T ( ) const

In Python use the property x.T. Scalars are returned as is, vectors become a reshape node and matrices a transpose node. Transposing twice returns the original node.

>>> A = MX.sym("A", 2, 3)
>>> A.T, A.T.shape, A.T.T
(MX(A'), (3, 2), MX(A))

>> A = MX.sym('A', 2, 3);
>> At = A';
>> At, size(At), At'
A'
3 2
A

julia> A = ca.MX.sym("A", 2, 3);
julia> A', size(A'), (A')'
(A', (3, 2), A)

See also
is_transpose, transpose

Extra doc: https://github.com/casadi/casadi/wiki/L_2qn

Definition at line 1098 of file mx.cpp.

1098  {
1099  return (*this)->get_transpose();
1100  }

References casadi::MXNode::get_transpose().

Referenced by casadi::Determinant::ad_forward(), casadi::Solve< Tr >::ad_forward(), casadi::BSplineCommon::ad_reverse(), casadi::Determinant::ad_reverse(), casadi::Inverse::ad_reverse(), casadi::conic_kkt_res(), casadi::BSplineInterpolant::construct_graph(), cumsum(), casadi::do_inline(), casadi::LinearInterpolant::do_inline(), casadi::get_boor(), casadi::MXNode::get_find(), casadi::Dple::get_forward(), casadi::Conic::get_reverse(), casadi::Expm::get_reverse(), casadi::Nlpsol::get_reverse(), casadi::SqicInterface::init(), mrdivide(), pinv(), casadi::Call::projectArg(), casadi::Conic::sens_kkt(), set(), set_nz(), solve(), vertcat(), and vertsplit().

◆ tangent()

static MX casadi::GenericMatrix< MX >::tangent ( const MX &  ex,
const MX &  arg,
const Dict &  opts = Dict() 
)
staticinherited

Functions called by friend functions defined here

◆ test_cast()

bool casadi::MX::test_cast ( const SharedObjectInternal *  ptr)
static

Definition at line 1102 of file mx.cpp.

1102  {
1103  return dynamic_cast<const MXNode*>(ptr)!=nullptr;
1104  }

◆ trace()

MX casadi::MX::trace ( const MX &  x)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1446 of file mx.cpp.

1446  {
1447  casadi_assert(x.is_square(), "trace: must be square");
1448  MX res(0);
1449  for (casadi_int i=0; i < x.size2(); i ++) {
1450  res += x(i, i);
1451  }
1452  return res;
1453  }

References casadi::GenericMatrix< MatType >::is_square(), and casadi::GenericMatrix< MatType >::size2().

◆ transform() [1/4]

MX casadi::MX::transform ( const MX &  x,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1306 of file mx.cpp.

1306  {
1307  return transform(std::vector<MX>{x}, opts).at(0);
1308  }
static MX transform(const MX &x, const Dict &opts=Dict())
Definition: mx.cpp:1306

Referenced by transform().

◆ transform() [2/4]

MX casadi::MX::transform ( const MX &  x,
const std::vector< std::vector< GenericType > > &  passes,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1310 of file mx.cpp.

1311  {
1312  return transform(std::vector<MX>{x}, passes, opts).at(0);
1313  }

References transform().

◆ transform() [3/4]

std::vector< MX > casadi::MX::transform ( const std::vector< MX > &  x,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1315 of file mx.cpp.

1315  {
1316  // Route through Function::transform; inputs are the free variables across all of x
1317  std::vector<MX> arg = symvar(veccat(x));
1318  Function f("transform", arg, x,
1319  {{"allow_free", true}, {"allow_duplicate_io_names", true}});
1320  f = f.transform(opts);
1321  return f(arg);
1322  }

References symvar(), casadi::Function::transform(), and casadi::SparsityInterface< MatType >::veccat().

◆ transform() [4/4]

std::vector< MX > casadi::MX::transform ( const std::vector< MX > &  x,
const std::vector< std::vector< GenericType > > &  passes,
const Dict &  opts = Dict() 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1324 of file mx.cpp.

1325  {
1326  // Route through Function::transform; inputs are the free variables across all of x
1327  std::vector<MX> arg = symvar(veccat(x));
1328  Function f("transform", arg, x,
1329  {{"allow_free", true}, {"allow_duplicate_io_names", true}});
1330  f = f.transform(passes, opts);
1331  return f(arg);
1332  }

References symvar(), casadi::Function::transform(), and casadi::SparsityInterface< MatType >::veccat().

◆ tril()

static MX casadi::GenericMatrix< MX >::tril ( const MX &  x,
bool  includeDiagonal = true 
)
inlinestaticinherited

Definition at line 654 of file generic_matrix.hpp.

654  {
655  return project(x, Sparsity::tril(x.sparsity(), includeDiagonal));
656  }
friend MX project(const MX &A, const Sparsity &sp, bool intersect=false)
Create a new matrix with a given sparsity pattern but with the.

◆ tril2symm()

MX casadi::GenericMatrix< MX >::tril2symm ( const MX &  x)
staticinherited

Definition at line 665 of file generic_matrix.hpp.

5452  {
5453  casadi_assert(x.is_square(),
5454  "Shape error in tril2symm. Expecting square shape but got " + x.dim());
5455  casadi_assert(x.nnz_upper()-x.nnz_diag()==0,
5456  "Sparsity error in tril2symm. Found above-diagonal entries in argument: " + x.dim());
5457  return x + x.T() - diag(diag(x));
5458  }
friend MX diag(const MX &A)
Get the diagonal of a matrix or construct a diagonal.

◆ triu()

static MX casadi::GenericMatrix< MX >::triu ( const MX &  x,
bool  includeDiagonal = true 
)
inlinestaticinherited

Definition at line 657 of file generic_matrix.hpp.

657  {
658  return project(x, Sparsity::triu(x.sparsity(), includeDiagonal));
659  }

◆ triu2symm()

MX casadi::GenericMatrix< MX >::triu2symm ( const MX &  x)
staticinherited

Definition at line 666 of file generic_matrix.hpp.

5478  {
5479  casadi_assert(x.is_square(),
5480  "Shape error in triu2symm. Expecting square shape but got " + x.dim());
5481  casadi_assert(x.nnz_lower()-x.nnz_diag()==0,
5482  "Sparsity error in triu2symm. Found below-diagonal entries in argument: " + x.dim());
5483  return x + x.T() - diag(diag(x));
5484  }

◆ type_name()

static std::string casadi::MX::type_name ( )
inlinestatic

Extra doc: https://github.com/casadi/casadi/wiki/L_pz

Definition at line 150 of file mx.hpp.

150 {return "MX";}

◆ unary()

MX casadi::MX::unary ( casadi_int  op,
const MX &  x,
bool  unique = false 
)
static

Low-level constructors behind the operators: MX.binary(OP_ADD, x, y) is x + y. Operands must have the same shape, or one of them is a scalar, or one is a horizontal repetition of the other (which is repmat-ed). The usual simplifications are applied. An invalid operation code is not checked.

Parameters
opOne of the OP_* constants
unique_x,unique_yInternal hints for in-place simplification; leave false

>>> x = MX.sym("x")
>>> y = MX.sym("y")
>>> MX.binary(OP_ADD, x, y), MX.unary(OP_SIN, x)
(MX((x+y)), MX(sin(x)))
>>> MX.binary(OP_ADD, MX.sym("V", 2, 4), MX.sym("W", 2, 2))
MX((V+repmat(W, 2)))
>>> try:
...   MX.binary(OP_ADD, MX.sym("v", 2), MX.sym("w", 3))
... except Exception as e:
...   print("Dimension mismatch" in str(e))
True

>> x = MX.sym('x'); y = MX.sym('y');
>> MX.binary(OP_ADD, x, y), MX.unary(OP_SIN, x)
(x+y)
sin(x)
>> MX.binary(OP_ADD, MX.sym('V', 2, 4), MX.sym('W', 2, 2))
(V+repmat(W, 2))
>> v = MX.sym('v', 2); w = MX.sym('w', 3);
>> try, MX.binary(OP_ADD, v, w); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> x = ca.MX.sym("x"); y = ca.MX.sym("y");
julia> ca.MX.binary(ca.OP_ADD, x, y), ca.MX.unary(ca.OP_SIN, x)
((x+y), sin(x))
julia> ca.MX.binary(ca.OP_ADD, ca.MX.sym("V", 2, 4), ca.MX.sym("W", 2, 2))
MX((V+repmat(W, 2)))
julia> try
           ca.MX.binary(ca.OP_ADD, ca.MX.sym("v", 2), ca.MX.sym("w", 3))
       catch e
           println(occursin("Dimension mismatch", sprint(showerror, e)))
       end
true

See also
op

Extra doc: https://github.com/casadi/casadi/wiki/L_r1

Definition at line 562 of file mx.cpp.

562  {
563  casadi_assert(casadi_math<double>::is_unary(op), "Not a unary operation: " + str(op));
564  return x->get_unary(Operation(op), unique);
565  }
Operation
Enum for quick access to any node.
Definition: calculus.hpp:60
static bool is_unary(unsigned char op)
Is unary operation?
Definition: calculus.hpp:1637

References casadi::MXNode::get_unary(), op(), and casadi::str().

Referenced by casadi::UnaryMX::eval_mx().

◆ unite()

MX casadi::MX::unite ( const MX &  A,
const MX &  B 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 1420 of file mx.cpp.

1420  {
1421  // Join the sparsity patterns
1422  std::vector<unsigned char> mapping;
1423  Sparsity sp = A.sparsity().unite(B.sparsity(), mapping);
1424 
1425  // Split up the mapping
1426  std::vector<casadi_int> nzA, nzB;
1427 
1428  // Copy sparsity
1429  for (casadi_int k=0; k<mapping.size(); ++k) {
1430  if (mapping[k]==1) {
1431  nzA.push_back(k);
1432  } else if (mapping[k]==2) {
1433  nzB.push_back(k);
1434  } else {
1435  throw CasadiException("Pattern intersection not empty");
1436  }
1437  }
1438 
1439  // Create mapping
1440  MX ret = MX::zeros(sp);
1441  ret = A->get_nzassign(ret, nzA);
1442  ret = B->get_nzassign(ret, nzB);
1443  return ret;
1444  }
Sparsity unite(const Sparsity &y, std::vector< unsigned char > &mapping) const
Union of two sparsity patterns of the same shape (also available as the + operator)
Definition: sparsity.cpp:411

References casadi::MXNode::get_nzassign(), mapping(), casadi::GenericMatrix< MatType >::size(), casadi::GenericMatrix< MatType >::sparsity(), sparsity(), casadi::Sparsity::unite(), and casadi::GenericMatrix< MX >::zeros().

◆ vertcat()

MX casadi::MX::vertcat ( const std::vector< MX > &  x)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1168 of file mx.cpp.

1168  {
1169  // Check dimensions
1170  if (x.size()>1) {
1171  std::vector<MX> ne = trim_empty(x, true);
1172  for (casadi_int i=0;i<ne.size();i++) {
1173  casadi_assert(ne[i].size2()==ne[0].size2(),
1174  "vertcat dimension mismatch x[" + str(i) + "]:" + ne[i].dim() +
1175  " and x[0]: " + ne[0].dim() + ".");
1176  }
1177  }
1178 
1179  if (x.empty()) {
1180  return MX(0, 1);
1181  } else if (x.size()==1) {
1182  return x.front();
1183  } else if (has_empty(x)) {
1184  std::vector<MX> ret = trim_empty(x);
1185  if (ret.empty()) {
1186  // We still want vertcat(zeros(5,0),zeros(5,0)) -> zeros(10,0)
1187  ret = trim_empty(x, true);
1188  casadi_int s = 0;
1189  casadi_int ncol = 0;
1190  for (casadi_int i=0;i<ret.size();++i) {
1191  s+= ret[i].size1();
1192  casadi_assert_dev(ncol==0 || ret[i].size2()==ncol);
1193  ncol = ret[i].size2();
1194  }
1195  return MX::zeros(s, ncol);
1196  } else {
1197  return vertcat(ret);
1198  }
1199  } else if (!x.front().is_column()) {
1200  // Vertcat operation only supports vectors, rewrite using horzcat
1201  std::vector<MX> xT = x;
1202  for (std::vector<MX>::iterator i=xT.begin(); i!=xT.end(); ++i) *i = i->T();
1203  return horzcat(xT).T();
1204  } else {
1205  return x.front()->get_vertcat(x);
1206  }
1207  }
virtual MX get_vertcat(const std::vector< MX > &x) const
Create a vertical concatenation node (vectors only)
Definition: mx_node.cpp:1171

References casadi::GenericMatrix< MX >::dim(), casadi::MXNode::get_vertcat(), casadi::has_empty(), horzcat(), MX(), casadi::GenericExpression< MX >::ne(), casadi::GenericMatrix< MatType >::size(), casadi::GenericMatrix< MX >::size2(), casadi::str(), T(), casadi::trim_empty(), and casadi::GenericMatrix< MX >::zeros().

Referenced by blockcat(), casadi::Nlpsol::get_forward(), casadi::Nlpsol::get_reverse(), casadi::Blocksqp::init(), and linspace().

◆ vertsplit()

std::vector< MX > casadi::MX::vertsplit ( const MX &  x,
const std::vector< casadi_int > &  offset 
)
static

Functions called by friend functions defined for SparsityInterface

Definition at line 1234 of file mx.cpp.

1234  {
1235  if (x.is_column()) {
1236  // Consistency check
1237  check_offset(offset, x.size1(), "vertsplit");
1238 
1239  // Trivial return if possible
1240  if (offset.size()==1) {
1241  return std::vector<MX>();
1242  } else if (offset.size()==2) {
1243  return std::vector<MX>(1, x);
1244  } else {
1245  return x->get_vertsplit(offset);
1246  }
1247  } else {
1248  std::vector<MX> ret = horzsplit(x.T(), offset);
1249  for (auto&& e : ret) e = e.T();
1250  return ret;
1251  }
1252  }
static std::vector< MX > horzsplit(const MX &x, const std::vector< casadi_int > &offset)
Definition: mx.cpp:1209

References casadi::check_offset(), casadi::MXNode::get_vertsplit(), horzsplit(), casadi::GenericMatrix< MatType >::is_column(), casadi::SparsityInterface< MatType >::offset(), casadi::GenericMatrix< MatType >::size1(), and T().

◆ weak()

Extra doc: https://github.com/casadi/casadi/wiki/L_aw

Definition at line 130 of file generic_shared_impl.hpp.

143  {
144  return (*this)->weak();
145  }

◆ which_depends()

std::vector< bool > casadi::MX::which_depends ( const MX &  expr,
const MX &  var,
casadi_int  order = 1,
bool  tr = false 
)
static

Functions called by friend functions defined for GenericMatrix

Definition at line 2005 of file mx.cpp.

2005  {
2006  return _which_depends(expr, var, order, tr);
2007  }
std::vector< bool > _which_depends(const MatType &expr, const MatType &var, casadi_int order, bool tr)

References casadi::_which_depends().

◆ which_function()

Function casadi::MX::which_function ( ) const

Only valid when is_call() is true; raises an error otherwise, also for the OutputNode of a call (use dep(0) to reach the call node).

>>> a = SX.sym("a")
>>> f = Function("f", [a], [2*a])
>>> x = MX.sym("x")
>>> r = f(x)
>>> r.dep(0).which_function().name()
'f'
>>> try:
...   r.which_function()
... except Exception as e:
...   print("'which_function' not defined" in str(e))
True

>> a = SX.sym('a');
>> f = Function('f', {a}, {2*a});
>> x = MX.sym('x');
>> r = f(x);
>> call = r.dep(0);
>> call.which_function().name()
f
>> try, r.which_function(); catch e, disp('error'); end
error

julia> a = ca.SX.sym("a");
julia> f = ca.Function("f", [a], [2 * a]);
julia> x = ca.MX.sym("x");
julia> r = f(x);
julia> ca.name(ca.which_function(ca.dep(r, 0)))
"f"
julia> try
           ca.which_function(r)
       catch e
           println(occursin("'which_function' not defined", sprint(showerror, e)))
       end
true

See also
is_call

Extra doc: https://github.com/casadi/casadi/wiki/L_2py

Definition at line 810 of file mx.cpp.

810  {
811  return (*this)->which_function();
812  }

Referenced by casadi::DaeBuilderInternal::create(), cse(), casadi::Onnx::load(), and casadi::BlazingSplineFunction::merge().

◆ which_output()

casadi_int casadi::MX::which_output ( ) const

Only valid when is_output() is true; raises an error otherwise.

>>> a = SX.sym("a")
>>> f = Function("f", [a], [a + 1, 2*a])
>>> x = MX.sym("x")
>>> r0, r1 = f(x, )
>>> r0.which_output(), r1.which_output()
(0, 1)

>> a = SX.sym('a');
>> f = Function('f', {a}, {a + 1, 2*a});
>> x = MX.sym('x');
>> [r0, r1] = f(x);
>> r0.which_output(), r1.which_output()
0
1

julia> a = ca.SX.sym("a");
julia> f = ca.Function("f", [a], [a + 1, 2 * a]);
julia> x = ca.MX.sym("x");
julia> r0, r1 = f(x);
julia> ca.which_output(r0), ca.which_output(r1)
(0, 1)

See also
is_output

Extra doc: https://github.com/casadi/casadi/wiki/L_2q0

Definition at line 822 of file mx.cpp.

822  {
823  return (*this)->which_output();
824  }

Referenced by casadi::DaeBuilderInternal::create(), cse(), and casadi::DaeBuilderInternal::jac_vdef_v_from_calls().

◆ zeros() [1/3]

static MX casadi::GenericMatrix< MX >::zeros ( casadi_int  nrow = 1,
casadi_int  ncol = 1 
)
inlinestaticinherited

zeros(nrow, ncol) stores nrow*ncol numerical zeros; zeros(sp) stores a zero at every structural nonzero of sp. To get structural zeros instead, construct from a shape, e.g. DM(2, 2).

>>> DM.zeros(2, 2).nnz(), DM.zeros(Sparsity.diag(2)).nnz(), DM(2, 2).nnz()
(4, 2, 0)
>>> MX.zeros(2, 3)
MX(zeros(2x3))

>> Z = DM.zeros(Sparsity.diag(2));
>> fprintf('%d %d %d\n', DM.zeros(2, 2).nnz(), Z.nnz(), DM(2, 2).nnz())
4 2 0
>> MX.zeros(2, 3)
zeros(2x3)

julia> Z = ca.DM.zeros(ca.Sparsity.diag(2));
julia> ca.nnz(ca.DM.zeros(2, 2)), ca.nnz(Z), ca.nnz(ca.DM(2, 2))
(4, 2, 0)
julia> ca.MX.zeros(2, 3)
MX(zeros(2x3))

See also
ones, Sparsity

Extra doc: https://github.com/casadi/casadi/wiki/L_1dh

Definition at line 5151 of file generic_matrix.hpp.

5151  {
5152  return zeros(Sparsity::dense(nrow, ncol));
5153  }

◆ zeros() [2/3]

static MX casadi::GenericMatrix< MX >::zeros ( const Sparsity &  sp)
inlinestaticinherited

zeros(nrow, ncol) stores nrow*ncol numerical zeros; zeros(sp) stores a zero at every structural nonzero of sp. To get structural zeros instead, construct from a shape, e.g. DM(2, 2).

>>> DM.zeros(2, 2).nnz(), DM.zeros(Sparsity.diag(2)).nnz(), DM(2, 2).nnz()
(4, 2, 0)
>>> MX.zeros(2, 3)
MX(zeros(2x3))

>> Z = DM.zeros(Sparsity.diag(2));
>> fprintf('%d %d %d\n', DM.zeros(2, 2).nnz(), Z.nnz(), DM(2, 2).nnz())
4 2 0
>> MX.zeros(2, 3)
zeros(2x3)

julia> Z = ca.DM.zeros(ca.Sparsity.diag(2));
julia> ca.nnz(ca.DM.zeros(2, 2)), ca.nnz(Z), ca.nnz(ca.DM(2, 2))
(4, 2, 0)
julia> ca.MX.zeros(2, 3)
MX(zeros(2x3))

See also
ones, Sparsity

Extra doc: https://github.com/casadi/casadi/wiki/L_1dh

Definition at line 5154 of file generic_matrix.hpp.

5154 { return MatType(sp, 0, false);}

◆ zeros() [3/3]

static MX casadi::GenericMatrix< MX >::zeros ( const std::pair< casadi_int, casadi_int > &  rc)
inlinestaticinherited

zeros(nrow, ncol) stores nrow*ncol numerical zeros; zeros(sp) stores a zero at every structural nonzero of sp. To get structural zeros instead, construct from a shape, e.g. DM(2, 2).

>>> DM.zeros(2, 2).nnz(), DM.zeros(Sparsity.diag(2)).nnz(), DM(2, 2).nnz()
(4, 2, 0)
>>> MX.zeros(2, 3)
MX(zeros(2x3))

>> Z = DM.zeros(Sparsity.diag(2));
>> fprintf('%d %d %d\n', DM.zeros(2, 2).nnz(), Z.nnz(), DM(2, 2).nnz())
4 2 0
>> MX.zeros(2, 3)
zeros(2x3)

julia> Z = ca.DM.zeros(ca.Sparsity.diag(2));
julia> ca.nnz(ca.DM.zeros(2, 2)), ca.nnz(Z), ca.nnz(ca.DM(2, 2))
(4, 2, 0)
julia> ca.MX.zeros(2, 3)
MX(zeros(2x3))

See also
ones, Sparsity

Extra doc: https://github.com/casadi/casadi/wiki/L_1dh

Definition at line 5155 of file generic_matrix.hpp.

5155  {
5156  return zeros(rc.first, rc.second);
5157  }

The documentation for this class was generated from the following files: