List of all members | Public Types | Public Member Functions | Static Public Member Functions | Static Public Attributes | Protected Member Functions | Static Private Member Functions
casadi::Sparsity Class Reference

General sparsity class. More...

#include <sparsity.hpp>

Detailed Description

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

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

  1. "colind" [length size2()+1], which contains the index to the first non-zero element on or after the corresponding column. All the non-zero elements of a particular column i are thus the elements with index el that fulfills: colind[i] <= el < colind[i+1].
  2. "row" [same length as the number of non-zero elements, nnz()] The rows for each of the structural non-zeros.

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

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

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

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

Every DM, SX and MX carries a pattern, obtained with sparsity(), and a symbolic or numeric matrix can be created from one, e.g. SX.sym("x", sp) or DM(sp, 1). Entries outside the pattern are structural zeros: they are never stored and never computed with. The row indices within a column are strictly increasing.

Patterns are immutable and cached: constructing a pattern that already exists returns a reference to the cached object, so equal patterns are cheap to compare. The in-place methods (resize, enlarge, erase, append, add_nz, ...) rebind the object to a new pattern rather than modify the shared one. Use is_equal or the == operator to compare patterns; object identity is not meaningful in the target languages.

A default-constructed Sparsity is a null object (is_null() is true): it carries no pattern and most methods raise an error on it. It is used as "no pattern" sentinel, e.g. as the result of a coloring that exceeds its cutoff. Empty patterns are allowed: a 0-by-n or n-by-0 pattern has no nonzeros, is dense, and is_empty() is true for it.

   >>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
   >>> DM(sp, 1)
   DM(
   [[1, 00, 00, 1],
    [00, 00, 1, 00],
    [1, 00, 00, 00]])
   >>> sp
   Sparsity(3x4,4nz)
   >>> sp.size1(), sp.size2(), sp.nnz(), sp.numel()
   (3, 4, 4, 12)
   >>> sp.colind(), sp.row()
   ([0, 2, 2, 3, 4], [0, 2, 1, 0])
   >>> sp == Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
   True
   >>> SX.sym("x", sp)
   SX(
   [[x_0, 00, 00, x_3],
    [00, 00, x_2, 00],
    [x_1, 00, 00, 00]])
   >>> Sparsity.dense(0, 3), Sparsity().is_null()
   (Sparsity(0x3), True)

   >> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
   >> DM(sp, 1)
   [[1, 00, 00, 1],
    [00, 00, 1, 00],
    [1, 00, 00, 00]]
   >> sp
   3x4,4nz
   >> fprintf('%d %d %d %d\n', sp.size1(), sp.size2(), sp.nnz(), sp.numel())
   3 4 4 12
   >> sp.colind(), sp.row()
   0 2 2 3 4
   0 2 1 0
   >> sp == Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
   1
   >> SX.sym('x', sp)
   [[x_0, 00, 00, x_3],
    [00, 00, x_2, 00],
    [x_1, 00, 00, 00]]
   >> Sparsity.dense(0, 3), Sparsity().is_null()
   0x3
   1

   julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
   julia> ca.DM(sp, 1)
   DM(
   [[1, 00, 00, 1],
    [00, 00, 1, 00],
    [1, 00, 00, 00]])
   julia> sp
   Sparsity(3x4,4nz)
   julia> ca.size1(sp), ca.size2(sp), ca.nnz(sp), ca.numel(sp)
   (3, 4, 4, 12)
   julia> ca.colind(sp), ca.row(sp)
   ([0, 2, 2, 3, 4], [0, 2, 1, 0])
   julia> ca.is_equal(sp, ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]))
   true
   julia> ca.SX.sym("x", sp)
   SX(
   [[x_0, 00, 00, x_3],
    [00, 00, x_2, 00],
    [x_1, 00, 00, 00]])
   julia> ca.Sparsity.dense(0, 3), ca.is_null(ca.Sparsity())
   (0x3, true)

See also
Matrix
Author
Joel Andersson
Date
2010-2015

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

Definition at line 197 of file sparsity.hpp.

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

Public Types

typedef SparsityInterface< Sparsity > B
 Base class. More...
 
typedef std::unordered_multimap< std::size_t, WeakRef > CachingMap
 
using internal_base_type = SharedObjectInternal
 
using base_type = SharedObject
 

Public Member Functions

 Sparsity (casadi_int dummy=0)
 Default constructor: a null object that holds no pattern. More...
 
 Sparsity (casadi_int nrow, casadi_int ncol)
 Pattern of the given shape with all structural zeros. More...
 
 Sparsity (casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &colind, const std::vector< casadi_int > &row, bool order_rows=false)
 Construct from compressed column storage vectors. More...
 
 Sparsity (const std::pair< casadi_int, casadi_int > &rc)
 Pattern with all structural zeros, shape given as a pair (nrow, ncol) More...
 
 Sparsity (casadi_int nrow, casadi_int ncol, const casadi_int *colind, const casadi_int *row, bool order_rows=false)
 Construct from sparsity pattern vectors given in compressed column storage format. More...
 
SparsityInternal * get () const
 
const std::vector< casadi_int > permutation_vector (bool invert=false) const
 Recover the permutation vector p from the pattern of a permutation matrix. More...
 
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. More...
 
std::vector< casadi_int > compress (bool canonical=true) const
 Compact single-vector representation of the pattern. More...
 
const SparsityInternal * operator-> () const
 Access a member function or object. More...
 
const SparsityInternal & operator* () const
 Reference to internal structure. More...
 
bool operator!= (const Sparsity &y) const
 Check whether two sparsity patterns differ (negation of is_equal) More...
 
bool is_stacked (const Sparsity &y, casadi_int n) const
 Check whether the pattern is n copies of y placed side by side. More...
 
 operator const casadi_int * () const
 Implicit or explicit type conversion to C representation. More...
 
 operator const std::vector< casadi_int > & () const
 Implicit or explicit type conversion to compact representation. More...
 
 operator SparsityStruct () const
 Implicit or explicit type conversion to C representation. More...
 
Dict info () const
 The pattern as a dictionary with entries nrow, ncol, colind and row. More...
 
void to_file (const std::string &filename, const std::string &format_hint="") const
 Write the pattern to a file. More...
 
void serialize (std::ostream &stream) const
 Serialize. More...
 
std::string serialize () const
 Serialize the pattern to a string. More...
 
void serialize (SerializingStream &s) const
 Serialize an object. More...
 
const casadi_int * row () const
 Get a reference to row-vector,. More...
 
const casadi_int * colind () const
 Get a reference to the colindex of all column element (see class description) More...
 
std::vector< casadi_int > get_row () const
 Row index of every nonzero, in nonzero (column-major) order. More...
 
std::vector< casadi_int > get_colind () const
 Column offsets of the compressed column storage. More...
 
casadi_int colind (casadi_int cc) const
 Index of the first nonzero of column cc. More...
 
casadi_int row (casadi_int el) const
 Row index of nonzero el. More...
 
std::vector< casadi_int > get_col () const
 Column index of every nonzero, in nonzero (column-major) order. More...
 
void resize (casadi_int nrow, casadi_int ncol)
 Change the shape in place, keeping the nonzeros that still fit. More...
 
casadi_int add_nz (casadi_int rr, casadi_int cc)
 Nonzero index of entry (rr, cc), inserting the entry into the pattern if needed. More...
 
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. More...
 
bool has_nz (casadi_int rr, casadi_int cc) const
 Check whether entry (rr, cc) is a structural nonzero. More...
 
std::vector< casadi_int > get_nz (const std::vector< casadi_int > &rr, const std::vector< casadi_int > &cc) const
 Nonzero indices of the block of entries with rows rr and columns cc. More...
 
void get_nz (std::vector< casadi_int > &indices) const
 Map flat (column-major) element indices to nonzero indices. More...
 
std::vector< casadi_int > get_lower () const
 Nonzero indices of the entries in the lower triangular part (row >= col) More...
 
std::vector< casadi_int > get_upper () const
 Nonzero indices of the entries in the upper triangular part (row <= col) More...
 
void get_ccs (std::vector< casadi_int > &colind, std::vector< casadi_int > &row) const
 The pattern in compressed column storage: the colind and row vectors. More...
 
void get_crs (std::vector< casadi_int > &rowind, std::vector< casadi_int > &col) const
 The pattern in compressed row storage: the rowind and col vectors. More...
 
void get_triplet (std::vector< casadi_int > &row, std::vector< casadi_int > &col) const
 The pattern in sparse triplet format: the row and column of every nonzero. More...
 
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. More...
 
Sparsity sub (const std::vector< casadi_int > &rr, const Sparsity &sp, std::vector< casadi_int > &mapping, bool ind1=false) const
 Pattern of a set of elements, arranged according to a given pattern. More...
 
Sparsity T () const
 Transposed pattern. More...
 
Sparsity transpose (std::vector< casadi_int > &mapping, bool invert_mapping=false) const
 Transposed pattern together with the reordering of the nonzeros. More...
 
bool is_transpose (const Sparsity &y) const
 Check whether y is the transpose of this pattern. More...
 
bool is_reshape (const Sparsity &y) const
 Check whether y is a reshape of this pattern. More...
 
bool is_compactible (std::vector< casadi_int > &row, std::vector< casadi_int > &col) const
 Check if the nonzero pattern is the Cartesian product of a row and a column subset. More...
 
bool is_subset (const Sparsity &rhs) const
 Check whether every nonzero of this pattern is also a nonzero of rhs. More...
 
Sparsity sparsity_cast_mod (const Sparsity &X, const Sparsity &Y) const
 Propagate a subset of a pattern through a sparsity cast. More...
 
Sparsity pattern_inverse () const
 Complement of the pattern: structural zeros become nonzeros and vice versa. 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 the pattern in place by inserting empty rows and columns. More...
 
void enlargeRows (casadi_int nrow, const std::vector< casadi_int > &rr, bool ind1=false)
 Enlarge the pattern in place by inserting empty rows. More...
 
void enlargeColumns (casadi_int ncol, const std::vector< casadi_int > &cc, bool ind1=false)
 Enlarge the pattern in place by inserting empty columns. More...
 
Sparsity makeDense (std::vector< casadi_int > &mapping) const
 Dense pattern of the same shape, with the flat index of every nonzero. More...
 
std::vector< casadi_int > erase (const std::vector< casadi_int > &rr, const std::vector< casadi_int > &cc, bool ind1=false)
 Turn the entries with rows rr and columns cc into structural zeros, in place. More...
 
std::vector< casadi_int > erase (const std::vector< casadi_int > &rr, bool ind1=false)
 Turn the entries with flat (column-major) indices rr into structural zeros. More...
 
void append (const Sparsity &sp)
 Append a pattern below this one, in place (vertical concatenation) More...
 
void appendColumns (const Sparsity &sp)
 Append a pattern to the right of this one, in place (horizontal concatenation) More...
 
bool is_scalar (bool scalar_and_dense=false) const
 Check whether the pattern is 1-by-1. More...
 
bool is_dense () const
 Check whether every entry is a structural nonzero, i.e. nnz() == numel() More...
 
bool is_row () const
 Check whether the pattern is a row vector, i.e. size1() == 1. More...
 
bool is_column () const
 Check whether the pattern is a column vector, i.e. size2() == 1. More...
 
bool is_vector () const
 Check whether the pattern is a row or a column vector. More...
 
bool is_diag () const
 Check whether the pattern is square with exactly the full diagonal as nonzeros. More...
 
bool is_square () const
 Check whether the number of rows equals the number of columns. More...
 
bool is_symmetric () const
 Check whether the pattern equals its transpose. More...
 
bool is_triu (bool strictly=false) const
 Check whether all nonzeros are on or above the diagonal (row <= col) More...
 
bool is_tril (bool strictly=false) const
 Check whether all nonzeros are on or below the diagonal (row >= col) More...
 
bool is_singular () const
 Check whether a square pattern is structurally singular. More...
 
bool is_permutation () const
 Check whether the pattern is that of a permutation matrix. More...
 
bool is_selection (bool allow_empty=false) const
 Check whether the pattern is that of a selection matrix. More...
 
bool is_orthonormal (bool allow_empty=false) const
 Check whether every row and every column has at most one nonzero. More...
 
bool is_orthonormal_rows (bool allow_empty=false) const
 Check whether the rows are orthonormal: one nonzero per row, at most one per column. More...
 
bool is_orthonormal_columns (bool allow_empty=false) const
 Check whether the columns are orthonormal (see is_orthonormal_rows) More...
 
bool rowsSequential (bool strictly=true) const
 Check whether the row indices are increasing within every column. More...
 
void removeDuplicates (std::vector< casadi_int > &mapping)
 Remove duplicate entries, in place. More...
 
std::vector< casadi_int > etree (bool ata=false) const
 Elimination tree of the pattern. More...
 
Sparsity ldl (std::vector< casadi_int > &p, bool amd=true) const
 Symbolic LDL factorization of a symmetric pattern. More...
 
void qr_sparse (Sparsity &V, Sparsity &R, std::vector< casadi_int > &prinv, std::vector< casadi_int > &pc, bool amd=true) const
 Symbolic QR factorization. More...
 
casadi_int dfs (casadi_int j, casadi_int top, std::vector< casadi_int > &SWIG_INOUT1(xi), std::vector< casadi_int > &SWIG_INOUT2(pstack), const std::vector< casadi_int > &pinv, std::vector< bool > &SWIG_INOUT3(marked)) const
 Depth-first search on the adjacency graph of the sparsity. More...
 
casadi_int scc (std::vector< casadi_int > &index, std::vector< casadi_int > &offset) const
 Strongly connected components of the directed graph of a square pattern. More...
 
casadi_int btf (std::vector< casadi_int > &rowperm, std::vector< casadi_int > &colperm, std::vector< casadi_int > &rowblock, std::vector< casadi_int > &colblock, std::vector< casadi_int > &coarse_rowblock, std::vector< casadi_int > &coarse_colblock) const
 Block triangular form (BTF) through the Dulmage-Mendelsohn decomposition. More...
 
std::vector< casadi_int > amd () const
 Approximate minimum degree (AMD) ordering of a symmetric pattern. More...
 
void spsolve (bvec_t *X, bvec_t *B, bool tr) const
 Propagate sparsity through a linear solve. More...
 
std::vector< casadi_int > find (bool ind1=SWIG_IND1) const
 Flat (column-major) element index of every nonzero. More...
 
void find (std::vector< casadi_int > &loc, bool ind1=false) const
 Get the location of all nonzero elements (inplace version) More...
 
Sparsity uni_coloring (const Sparsity &AT=Sparsity(), casadi_int cutoff=std::numeric_limits< casadi_int >::max()) const
 Unidirectional (column) coloring for compressed Jacobian evaluation. More...
 
Sparsity star_coloring_new (std::vector< casadi_int > &which_color, const Dict &opts=Dict()) const
 Star coloring of a symmetric pattern, with the color that recovers each nonzero. More...
 
Sparsity star_coloring (casadi_int ordering=1, casadi_int cutoff=std::numeric_limits< casadi_int >::max()) const
 Star coloring of a symmetric pattern (greedy distance-2 coloring) More...
 
Sparsity star_coloring2 (casadi_int ordering=1, casadi_int cutoff=std::numeric_limits< casadi_int >::max()) const
 Star coloring of a symmetric pattern with the newer algorithm. More...
 
std::vector< casadi_int > largest_first () const
 Column indices ordered by decreasing number of nonzeros. More...
 
Sparsity pmult (const std::vector< casadi_int > &p, bool permute_rows=true, bool permute_columns=true, bool invert_permutation=false) const
 Permute the rows and/or columns of the pattern. More...
 
std::string dim (bool with_nz=false) const
 Dimensions as a string "nrow x ncol", optionally with the number of nonzeros. More...
 
std::string postfix_dim () const
 Dimension string to append to a name, as used when printing symbolic primitives. More...
 
std::string repr_el (casadi_int k) const
 Describe the position of nonzero k as a string. More...
 
void spy (std::ostream &stream=casadi::uout()) const
 Print a textual picture of the pattern. More...
 
void spy_matlab (const std::string &mfile) const
 Write a MATLAB/Octave script that builds the pattern as a sparse matrix and calls spy. More...
 
void export_code (const std::string &lang, std::ostream &stream=casadi::uout(), const Dict &options=Dict()) const
 Write code that reconstructs the pattern in another language. More...
 
std::size_t hash () const
 Hash of the pattern (dimensions, colind and row) More...
 
template<typename T >
void set (T *data, const T *val_data, const Sparsity &val_sp) const
 Assign the nonzero entries of one sparsity pattern to the nonzero. More...
 
template<typename T >
void add (T *data, const T *val_data, const Sparsity &val_sp) const
 Add the nonzero entries of one sparsity pattern to the nonzero entries. More...
 
template<typename T >
void bor (T *data, const T *val_data, const Sparsity &val_sp) const
 Bitwise or of the nonzero entries of one sparsity pattern and the nonzero. More...
 
template<typename DataType >
void set (DataType *data, const DataType *val_data, const Sparsity &val_sp) const
 
template<typename DataType >
void add (DataType *data, const DataType *val_data, const Sparsity &val_sp) const
 
template<typename DataType >
void bor (DataType *data, const DataType *val_data, const Sparsity &val_sp) const
 
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...
 
bool is_equal (const Sparsity &y) const
 Check whether two sparsity patterns are identical. More...
 
bool is_equal (casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &colind, const std::vector< casadi_int > &row) const
 Check whether two sparsity patterns are identical. More...
 
bool is_equal (casadi_int nrow, casadi_int ncol, const casadi_int *colind, const casadi_int *row) const
 Check whether two sparsity patterns are identical. More...
 
bool operator== (const Sparsity &y) const
 Check whether two sparsity patterns are identical. More...
 
Size and element counting
casadi_int size1 () const
 Number of rows. More...
 
casadi_int rows () const
 Number of rows, Octave-style alias of size1. More...
 
casadi_int size2 () const
 Number of columns. More...
 
casadi_int columns () const
 Number of columns, Octave-style alias of size2. More...
 
casadi_int numel () const
 Total number of entries, structural zeros included, i.e. size1()*size2() More...
 
double density () const
 Percentage of nonzeros: 100*nnz()/numel() More...
 
bool is_empty (bool both=false) const
 Check whether the pattern has a zero dimension. More...
 
casadi_int nnz () const
 Number of structural nonzeros. More...
 
casadi_int nnz_upper (bool strictly=false) const
 Number of nonzeros in the upper triangular part, i.e. entries (i, j) with i <= j. More...
 
casadi_int nnz_lower (bool strictly=false) const
 Number of nonzeros in the lower triangular part, i.e. entries (i, j) with i >= j. More...
 
casadi_int nnz_diag () const
 Number of nonzeros on the main diagonal, i.e. entries (i, i) More...
 
casadi_int bw_upper () const
 Upper half-bandwidth: the largest j - i over all nonzeros (i, j) with j > i. More...
 
casadi_int bw_lower () const
 Lower half-bandwidth: the largest i - j over all nonzeros (i, j) with i > j. More...
 
std::pair< casadi_int, casadi_int > size () const
 Shape as a pair (number of rows, number of columns) More...
 
casadi_int size (casadi_int axis) const
 Size along one dimension. More...
 
Sparsity combine (const Sparsity &y, bool f0x_is_zero, bool function0_is_zero, std::vector< unsigned char > &mapping) const
 Combine two patterns of the same shape, as the result of a binary operation. More...
 
Sparsity combine (const Sparsity &y, bool f0x_is_zero, bool function0_is_zero) const
 Combine two patterns of the same shape, as the result of a binary operation. More...
 
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) More...
 
Sparsity unite (const Sparsity &y) const
 Union of two sparsity patterns of the same shape (also available as the + operator) More...
 
Sparsity operator+ (const Sparsity &b) const
 Union of two sparsity patterns of the same shape (also available as the + operator) More...
 
Sparsity intersect (const Sparsity &y, std::vector< unsigned char > &mapping) const
 Intersection of two sparsity patterns of the same shape (also the * operator) More...
 
Sparsity intersect (const Sparsity &y) const
 Intersection of two sparsity patterns of the same shape (also the * operator) More...
 
Sparsity operator* (const Sparsity &b) const
 Intersection of two sparsity patterns of the same shape (also the * operator) More...
 

Static Public Member Functions

static Sparsity create (SparsityInternal *node)
 Create from node. More...
 
static Sparsity upper (casadi_int n)
 Create an upper triangular square sparsity pattern. More...
 
static Sparsity lower (casadi_int n)
 Create a lower triangular square sparsity pattern. More...
 
static Sparsity band (casadi_int n, casadi_int p)
 Create a single band in a square sparsity pattern. More...
 
static Sparsity banded (casadi_int n, casadi_int p)
 Create a banded square sparsity pattern. More...
 
static Sparsity rowcol (const std::vector< casadi_int > &row, const std::vector< casadi_int > &col, casadi_int nrow, casadi_int ncol)
 Create the pattern of a block: all entries (i, j) with i in row and j in col. More...
 
static Sparsity nonzeros (casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &nz, bool ind1=SWIG_IND1)
 Create a sparsity pattern from the flat (column-major) index of every nonzero. More...
 
static Sparsity permutation (const std::vector< casadi_int > &p, bool invert=false)
 Construct the pattern of a permutation matrix P from a permutation vector p. More...
 
static Sparsity from_file (const std::string &filename, const std::string &format_hint="")
 Read a pattern from a file written by to_file (Matrix Market pattern format) More...
 
static Sparsity deserialize (std::istream &stream)
 Build a Sparsity from a serialized stream. More...
 
static Sparsity deserialize (const std::string &s)
 Build a Sparsity from a string produced by serialize() More...
 
static Sparsity deserialize (DeserializingStream &s)
 Deserialize. More...
 
static void mul_sparsityF (const bvec_t *x, const Sparsity &x_sp, const bvec_t *y, const Sparsity &y_sp, bvec_t *z, const Sparsity &z_sp, bvec_t *w)
 Propagate sparsity using 0-1 logic through a matrix product,. More...
 
static void mul_activityF (const bvec_t *x, const Sparsity &x_sp, const bvec_t *y, const Sparsity &y_sp, bvec_t *z, const Sparsity &z_sp, bvec_t *w)
 Propagate signal activity through a matrix product, forward mode. More...
 
static void mul_sparsityR (bvec_t *x, const Sparsity &x_sp, bvec_t *y, const Sparsity &y_sp, bvec_t *z, const Sparsity &z_sp, bvec_t *w)
 Propagate sparsity using 0-1 logic through a matrix product,. More...
 
static CachingMap & getCache ()
 Cached sparsity patterns. More...
 
static const Sparsity & getScalar ()
 (Dense) scalar More...
 
static const Sparsity & getScalarSparse ()
 (Sparse) scalar More...
 
static const Sparsity & getEmpty ()
 Empty zero-by-zero. More...
 
static std::string type_name ()
 Readable name of the public class. More...
 
static bool test_cast (const SharedObjectInternal *ptr)
 Check if a particular cast is allowed. More...
 
static Sparsity kkt (const Sparsity &H, const Sparsity &J, bool with_x_diag=true, bool with_lam_g_diag=true)
 Pattern of a KKT system [H + I1, J'; J, I2]. More...
 
static std::string file_format (const std::string &filename, const std::string &format_hint, const std::set< std::string > &file_formats)
 
static Sparsity scalar (bool dense_scalar=true)
 Create a 1-by-1 sparsity pattern. More...
 
static Sparsity dense (casadi_int nrow, casadi_int ncol=1)
 Create a dense rectangular sparsity pattern. More...
 
static Sparsity dense (const std::pair< casadi_int, casadi_int > &rc)
 Create a dense rectangular sparsity pattern. More...
 
static Sparsity unit (casadi_int n, casadi_int el)
 Create the pattern of a unit vector: a column of length n with one nonzero. More...
 
static Sparsity diag (casadi_int nrow)
 Create a diagonal sparsity pattern. More...
 
static Sparsity diag (casadi_int nrow, casadi_int ncol)
 Create a diagonal sparsity pattern. More...
 
static Sparsity diag (const std::pair< casadi_int, casadi_int > &rc)
 Create a diagonal sparsity pattern. More...
 
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. More...
 
static Sparsity triplet (casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &row, const std::vector< casadi_int > &col)
 Create a sparsity pattern from the (row, col) index of every nonzero. More...
 
static Sparsity compressed (const std::vector< casadi_int > &v, bool order_rows=false)
 Create from the compact single-vector representation of a pattern. More...
 
static Sparsity compressed (const casadi_int *v, bool order_rows=false)
 Create from the compact single-vector representation of a pattern. More...
 
static Sparsity horzcat (const std::vector< Sparsity > &sp)
 Accessed by SparsityInterface. More...
 
static Sparsity vertcat (const std::vector< Sparsity > &sp)
 Accessed by SparsityInterface. More...
 
static Sparsity blockcat (const std::vector< std::vector< Sparsity > > &v)
 Accessed by SparsityInterface. More...
 
static Sparsity diagcat (const std::vector< Sparsity > &v)
 Accessed by SparsityInterface. More...
 
static std::vector< Sparsity > horzsplit (const Sparsity &x, const std::vector< casadi_int > &offset)
 Accessed by SparsityInterface. More...
 
static std::vector< Sparsity > vertsplit (const Sparsity &x, const std::vector< casadi_int > &offset)
 Accessed by SparsityInterface. More...
 
static std::vector< Sparsity > diagsplit (const Sparsity &x, const std::vector< casadi_int > &offset1, const std::vector< casadi_int > &offset2)
 Accessed by SparsityInterface. More...
 
static Sparsity mtimes (const Sparsity &x, const Sparsity &y, const std::string &blas="reference")
 Accessed by SparsityInterface. More...
 
static Sparsity mac (const Sparsity &x, const Sparsity &y, const Sparsity &z, const std::string &="reference")
 Accessed by SparsityInterface. More...
 
static Sparsity reshape (const Sparsity &x, casadi_int nrow, casadi_int ncol)
 Accessed by SparsityInterface. More...
 
static Sparsity reshape (const Sparsity &x, const Sparsity &sp)
 Accessed by SparsityInterface. More...
 
static Sparsity sparsity_cast (const Sparsity &x, const Sparsity &sp)
 Accessed by SparsityInterface. More...
 
static casadi_int sprank (const Sparsity &x)
 Accessed by SparsityInterface. More...
 
static casadi_int norm_0_mul (const Sparsity &x, const Sparsity &A)
 Accessed by SparsityInterface. More...
 
static Sparsity kron (const Sparsity &a, const Sparsity &b)
 Accessed by SparsityInterface. More...
 
static Sparsity kron_contract (const Sparsity &sp_m, const Sparsity &sp_x, bool inner)
 Output sparsity of casadi::KronContract. More...
 
static Sparsity triu (const Sparsity &x, bool includeDiagonal=true)
 Accessed by SparsityInterface. More...
 
static Sparsity tril (const Sparsity &x, bool includeDiagonal=true)
 Accessed by SparsityInterface. More...
 
static Sparsity sum2 (const Sparsity &x)
 Accessed by SparsityInterface. More...
 
static Sparsity sum1 (const Sparsity &x)
 Accessed by SparsityInterface. More...
 

Static Public Attributes

static std::set< std::string > file_formats = {"mtx"}
 

Protected Member Functions

void count_up ()
 
void count_down ()
 

Static Private Member Functions

static std::vector< Sparsity > diagsplit (const Sparsity &x, const std::vector< casadi_int > &output_offset)
 
static std::vector< Sparsity > diagsplit (const Sparsity &x, casadi_int incr)
 
static std::vector< Sparsity > diagsplit (const Sparsity &x, casadi_int incr1, casadi_int incr2)
 
static Sparsity mtimes (const std::vector< Sparsity > &args, const std::string &blas="reference")
 
static std::vector< Sparsity > horzsplit (const Sparsity &x, casadi_int incr)
 
static std::vector< Sparsity > vertsplit (const Sparsity &x, casadi_int incr)
 

Member Typedef Documentation

◆ B

Definition at line 399 of file sparsity.hpp.

◆ base_type

Definition at line 103 of file shared_object.hpp.

◆ CachingMap

typedef std::unordered_multimap<std::size_t, WeakRef> casadi::Sparsity::CachingMap

Definition at line 4620 of file sparsity.hpp.

◆ internal_base_type

Definition at line 102 of file shared_object.hpp.

Constructor & Destructor Documentation

◆ Sparsity() [1/5]

casadi::Sparsity::Sparsity ( casadi_int  dummy = 0)
explicit

is_null() is true for the result and most other methods raise an error on it. A null Sparsity is the "no pattern" sentinel used by e.g. uni_coloring (as default for AT) and returned by the colorings when the cutoff is exceeded.

Parameters
dummyMust be 0 (any other value raises an error)

>>> sp = Sparsity()
>>> sp.is_null(), sp
(True, Sparsity(NULL))
>>> try: sp.nnz()
... except Exception as e: print("error")
error

>> sp = Sparsity();
>> sp.is_null(), sp
1
NULL
>> try, sp.nnz(); catch e, disp('error'); end
error

julia> sp = ca.Sparsity();
julia> ca.is_null(sp), sp
(true, NULL)
julia> try
           ca.nnz(sp)
       catch e
           println("error")
       end
error

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

Definition at line 68 of file sparsity.cpp.

68  {
69  casadi_assert_dev(dummy==0);
70  }

Referenced by band(), banded(), blockcat(), compressed(), dense(), deserialize(), diag(), diagcat(), enlargeColumns(), enlargeRows(), horzcat(), horzsplit(), kkt(), kron(), kron_contract(), ldl(), lower(), permutation(), triplet(), unit(), upper(), and vertcat().

◆ Sparsity() [2/5]

casadi::Sparsity::Sparsity ( casadi_int  nrow,
casadi_int  ncol 
)
Parameters
nrowNumber of rows, nonnegative
ncolNumber of columns, nonnegative

>>> sp = Sparsity(2, 3)
>>> sp, sp.nnz(), sp.is_dense()
(Sparsity(2x3,0nz), 0, False)
>>> Sparsity(0, 0), Sparsity(0, 0).is_dense()
(Sparsity(0x0), True)
>>> DM(Sparsity(2, 2), 1)
DM(
[[00, 00],
 [00, 00]])

>> sp = Sparsity(2, 3);
>> sp, sp.nnz(), sp.is_dense()
2x3,0nz
0
0
>> Sparsity(0, 0), Sparsity(0, 0).is_dense()
0x0
1
>> DM(Sparsity(2, 2), 1)
[[00, 00],
 [00, 00]]

julia> sp = ca.Sparsity(2, 3)
Sparsity(2x3,0nz)
julia> ca.nnz(sp), ca.is_dense(sp)
(0, false)
julia> ca.Sparsity(0, 0), ca.is_dense(ca.Sparsity(0, 0))
(0x0, true)
julia> ca.DM(ca.Sparsity(2, 2), 1)
DM(
[[00, 00],
 [00, 00]])

See also
dense, is_empty

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

Definition at line 78 of file sparsity.cpp.

78  {
79  casadi_assert(nrow>=0 && ncol>=0,
80  "Dimensions must be non-negative, got " + str(nrow) + "-by-" + str(ncol));
81  std::vector<casadi_int> row, colind(ncol+1, 0);
82  assign_cached(nrow, ncol, colind, row);
83  }
const casadi_int * row() const
Get a reference to row-vector,.
Definition: sparsity.cpp:166
const casadi_int * colind() const
Get a reference to the colindex of all column element (see class description)
Definition: sparsity.cpp:170
std::string str(const T &v)
String representation, any type.

References colind(), row(), and casadi::str().

◆ Sparsity() [3/5]

casadi::Sparsity::Sparsity ( casadi_int  nrow,
casadi_int  ncol,
const std::vector< casadi_int > &  colind,
const std::vector< casadi_int > &  row,
bool  order_rows = false 
)
Parameters
nrowNumber of rows
ncolNumber of columns
colindColumn offsets, length ncol+1, colind[0] == 0, nondecreasing
rowRow index of each nonzero, length colind[ncol], each in [0, nrow), strictly increasing within a column
order_rowsIf true, row indices that are not sorted within a column are sorted (duplicates merged) instead of raising an error

An invalid colind or an out-of-range row index raises an error. A pattern with colind[ncol] == nrow*ncol is the dense pattern.

>>> sp = Sparsity(3, 2, [0, 2, 3], [0, 2, 1])
>>> DM(sp, 1)
DM(
[[1, 00],
 [00, 1],
 [1, 00]])
>>> Sparsity(2, 2, [0, 2, 4], [0, 1, 0, 1]).is_dense()
True
>>> try: Sparsity(3, 2, [0, 2, 3], [2, 0, 1])
... except Exception as e: print("not sorted")
not sorted
>>> Sparsity(3, 2, [0, 2, 3], [2, 0, 1], True).row()
[0, 2, 1]

>> sp = Sparsity(3, 2, [0, 2, 3], [0, 2, 1]);
>> DM(sp, 1)
[[1, 00],
 [00, 1],
 [1, 00]]
>> Sparsity(2, 2, [0, 2, 4], [0, 1, 0, 1]).is_dense()
1
>> try, Sparsity(3, 2, [0, 2, 3], [2, 0, 1]); catch e, disp('not sorted'); end
not sorted
>> Sparsity(3, 2, [0, 2, 3], [2, 0, 1], true).row()
0 2 1

julia> sp = ca.Sparsity(3, 2, [0, 2, 3], [0, 2, 1]);
julia> ca.DM(sp, 1)
DM(
[[1, 00],
 [00, 1],
 [1, 00]])
julia> ca.is_dense(ca.Sparsity(2, 2, [0, 2, 4], [0, 1, 0, 1]))
true
julia> try
           ca.Sparsity(3, 2, [0, 2, 3], [2, 0, 1])
       catch e
           println("not sorted")
       end
not sorted
julia> ca.row(ca.Sparsity(3, 2, [0, 2, 3], [2, 0, 1], true))
3-element Vector{Int64}:
 0
 2
 1

See also
compressed, triplet, get_ccs

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

Definition at line 92 of file sparsity.cpp.

93  {
94  casadi_assert(nrow>=0 && ncol>=0,
95  "Dimensions must be non-negative, got " + str(nrow) + "-by-" + str(ncol));
96  assign_cached(nrow, ncol, colind, row, order_rows);
97  }

References colind(), row(), and casadi::str().

◆ Sparsity() [4/5]

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

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

Definition at line 85 of file sparsity.cpp.

85  {
86  casadi_assert(rc.first>=0 && rc.second>=0,
87  "Dimensions must be non-negative, got " + str(rc.first) + "-by-" + str(rc.second));
88  std::vector<casadi_int> row, colind(rc.second+1, 0);
89  assign_cached(rc.first, rc.second, colind, row);
90  }

References colind(), row(), and casadi::str().

◆ Sparsity() [5/5]

casadi::Sparsity::Sparsity ( casadi_int  nrow,
casadi_int  ncol,
const casadi_int *  colind,
const casadi_int *  row,
bool  order_rows = false 
)

Definition at line 99 of file sparsity.cpp.

100  {
101  casadi_assert(nrow>=0 && ncol>=0,
102  "Dimensions must be non-negative, got " + str(nrow) + "-by-" + str(ncol));
103  if (colind==nullptr || colind[ncol]==nrow*ncol) {
104  *this = dense(nrow, ncol);
105  } else {
106  std::vector<casadi_int> colindv(colind, colind+ncol+1);
107  std::vector<casadi_int> rowv(row, row+colind[ncol]);
108  assign_cached(nrow, ncol, colindv, rowv, order_rows);
109  }
110  }
static Sparsity dense(casadi_int nrow, casadi_int ncol=1)
Create a dense rectangular sparsity pattern.
Definition: sparsity.cpp:1041

References colind(), dense(), row(), and casadi::str().

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  }

◆ add() [1/2]

template<typename DataType >
void casadi::Sparsity::add ( DataType *  data,
const DataType *  val_data,
const Sparsity &  val_sp 
) const

Definition at line 6187 of file sparsity.hpp.

6187  {
6188  // Get dimensions of this
6189  const casadi_int sz = nnz();
6190  const casadi_int sz1 = size1();
6191  const casadi_int sz2 = size2();
6192  const casadi_int nel = sz1*sz2;
6193 
6194  // Get dimensions of assigning matrix
6195  const casadi_int val_sz = val_sp.nnz();
6196  const casadi_int val_sz1 = val_sp.size1();
6197  const casadi_int val_sz2 = val_sp.size2();
6198  const casadi_int val_nel = val_sz1*val_sz2;
6199 
6200  // Check if sparsity matches
6201  if (val_sp==*this) {
6202  for (casadi_int k=0; k<sz; ++k) {
6203  data[k] += val_data[k];
6204  }
6205  } else if (this->is_empty()) {
6206  // Quick return
6207  return;
6208  } else if (val_sp.is_empty()) {
6209  // Quick return
6210  return;
6211  } else if (val_nel==1) { // if scalar
6212  if (val_sz!=0) {
6213  for (casadi_int k=0; k<sz; ++k) {
6214  data[k] += val_data[0];
6215  }
6216  }
6217  } else {
6218  // Quick return if empty
6219  if (nel==0 && val_nel==0) return;
6220 
6221  // Make sure that dimension matches
6222  casadi_assert(sz2==val_sz2 && sz1==val_sz1,
6223  "Sparsity::add<DataType>: shape mismatch. lhs is "
6224  + dim() + ", while rhs is " + val_sp.dim() + ".");
6225 
6226  // Sparsity
6227  const casadi_int* c = row();
6228  const casadi_int* rind = colind();
6229  const casadi_int* v_c = val_sp.row();
6230  const casadi_int* v_rind = val_sp.colind();
6231 
6232  // For all columns
6233  for (casadi_int i=0; i<sz2; ++i) {
6234 
6235  // Nonzero of the assigning matrix
6236  casadi_int v_el = v_rind[i];
6237 
6238  // First nonzero of the following column
6239  casadi_int v_el_end = v_rind[i+1];
6240 
6241  // Next row of the assigning matrix
6242  casadi_int v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6243 
6244  // Assign all nonzeros
6245  for (casadi_int el=rind[i]; el!=rind[i+1]; ++el) {
6246 
6247  // Get row
6248  casadi_int j=c[el];
6249 
6250  // Forward the assigning nonzero
6251  while (v_j<j) {
6252  v_el++;
6253  v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6254  }
6255 
6256  // Assign nonzero
6257  if (v_j==j) {
6258  data[el] += val_data[v_el++];
6259  v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6260  }
6261  }
6262  }
6263  }
6264  }
casadi_int size1() const
Number of rows.
Definition: sparsity.cpp:124
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
casadi_int nnz() const
Number of structural nonzeros.
Definition: sparsity.cpp:150
casadi_int size2() const
Number of columns.
Definition: sparsity.cpp:128
bool is_empty(bool both=false) const
Check whether the pattern has a zero dimension.
Definition: sparsity.cpp:146

References colind(), dim(), is_empty(), nnz(), row(), size1(), and size2().

◆ add() [2/2]

template<typename T >
void casadi::Sparsity::add ( T *  data,
const T *  val_data,
const Sparsity &  val_sp 
) const

of another sparsity pattern

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

◆ add_nz()

casadi_int casadi::Sparsity::add_nz ( casadi_int  rr,
casadi_int  cc 
)

Returns the position of the entry among the nonzeros. If the entry is a structural zero, the object is rebound to a pattern that includes it (nonzero indices after it shift by one). Negative indices count from the end. An index out of bounds raises an error.

>>> sp = Sparsity(3, 3)
>>> sp.add_nz(1, 1), sp.add_nz(0, 0), sp.add_nz(1, 1), sp
(0, 0, 1, Sparsity(3x3,2nz))
>>> DM(sp, 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 00]])
>>> try: sp.add_nz(3, 0)
... except Exception as e: print("out of bounds")
out of bounds

>> sp = Sparsity(3, 3);
>> [sp.add_nz(1, 1), sp.add_nz(0, 0), sp.add_nz(1, 1)], sp
0 0 1
3x3,2nz
>> DM(sp, 1)
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 00]]
>> try, sp.add_nz(3, 0); catch e, disp('out of bounds'); end
out of bounds

julia> sp = ca.Sparsity(3, 3);
julia> ca.add_nz(sp, 1, 1), ca.add_nz(sp, 0, 0), ca.add_nz(sp, 1, 1)
(0, 0, 1)
julia> ca.DM(sp, 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 00]])
julia> try
           ca.add_nz(sp, 3, 0)
       catch e
           println("out of bounds")
       end
out of bounds

See also
get_nz, has_nz

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

Definition at line 196 of file sparsity.cpp.

196  {
197  // If negative index, count from the back
198  if (rr<0) rr += size1();
199  if (cc<0) cc += size2();
200 
201  // Check consistency
202  casadi_assert(rr>=0 && rr<size1(), "Row index out of bounds");
203  casadi_assert(cc>=0 && cc<size2(), "Column index out of bounds");
204 
205  // Quick return if matrix is dense
206  if (is_dense()) return rr+cc*size1();
207 
208  // Get sparsity pattern
209  casadi_int size1=this->size1(), size2=this->size2(), nnz=this->nnz();
210  const casadi_int *colind = this->colind(), *row = this->row();
211 
212  // Quick return if we are adding an element to the end
213  if (colind[cc]==nnz || (colind[cc+1]==nnz && row[nnz-1]<rr)) {
214  std::vector<casadi_int> rowv(nnz+1);
215  std::copy(row, row+nnz, rowv.begin());
216  rowv[nnz] = rr;
217  std::vector<casadi_int> colindv(colind, colind+size2+1);
218  for (casadi_int c=cc; c<size2; ++c) colindv[c+1]++;
219  assign_cached(size1, size2, colindv, rowv);
220  return rowv.size()-1;
221  }
222 
223  // go to the place where the element should be
224  casadi_int ind;
225  for (ind=colind[cc]; ind<colind[cc+1]; ++ind) { // better: loop from the back to the front
226  if (row[ind] == rr) {
227  return ind; // element exists
228  } else if (row[ind] > rr) {
229  break; // break at the place where the element should be added
230  }
231  }
232 
233  // insert the element
234  std::vector<casadi_int> rowv = get_row(), colindv = get_colind();
235  rowv.insert(rowv.begin()+ind, rr);
236  for (casadi_int c=cc+1; c<size2+1; ++c) colindv[c]++;
237 
238  // Return the location of the new element
239  assign_cached(size1, size2, colindv, rowv);
240  return ind;
241  }
std::vector< casadi_int > get_colind() const
Column offsets of the compressed column storage.
Definition: sparsity.cpp:366
std::vector< casadi_int > get_row() const
Row index of every nonzero, in nonzero (column-major) order.
Definition: sparsity.cpp:374
bool is_dense() const
Check whether every entry is a structural nonzero, i.e. nnz() == numel()
Definition: sparsity.cpp:275

References colind(), get_colind(), get_row(), is_dense(), nnz(), row(), size1(), and size2().

◆ amd()

std::vector< casadi_int > casadi::Sparsity::amd ( ) const

Fill-reducing ordering p to apply to a symmetric linear system before factorization: factorize A[p, p] instead of A. The pattern must be symmetric, otherwise an error is raised; for an unsymmetric A, order the pattern of A^T*A (as qr_sparse does). Used by ldl and qr_sparse when their amd argument is true.

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

>>> Sparsity.banded(4, 1).amd(), Sparsity.dense(3, 3).amd(), Sparsity(0, 0).amd()
([3, 2, 0, 1], [0, 1, 2], [])
>>> try: Sparsity.upper(3).amd()
... except Exception as e: print("not symmetric")
not symmetric

>> Sparsity.banded(4, 1).amd(), Sparsity.dense(3, 3).amd()
3 2 0 1
0 1 2
>> isempty(Sparsity(0, 0).amd())
1
>> try, Sparsity.upper(3).amd(); catch e, disp('not symmetric'); end
not symmetric

julia> ca.amd(ca.Sparsity.banded(4, 1)), ca.amd(ca.Sparsity.dense(3, 3))
([3, 2, 0, 1], [0, 1, 2])
julia> ca.amd(ca.Sparsity(0, 0))
Int64[]
julia> try
           ca.amd(ca.Sparsity.upper(3))
       catch e
           println("not symmetric")
       end
not symmetric

See also
ldl, qr_sparse, etree, is_symmetric

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

Definition at line 719 of file sparsity.cpp.

719  {
720  return (*this)->amd();
721  }

Referenced by casadi::LinsolLdl::init(), ldl(), and qr_sparse().

◆ append()

void casadi::Sparsity::append ( const Sparsity &  sp)

The number of columns must match, otherwise an error is raised; a 0-by-0 pattern on either side is ignored. Equivalent to rebinding to vertcat(self, sp); only cheap when both are column vectors.

>>> sp = Sparsity.dense(2, 2); sp.append(Sparsity.diag(2)); print(DM(sp, 1))
[[1, 1], 
 [1, 1], 
 [1, 00], 
 [00, 1]]
>>> sp = Sparsity(0, 0); sp.append(Sparsity.diag(2)); print(sp)
2x2,2nz
>>> try: Sparsity.dense(2, 2).append(Sparsity.dense(2, 3))
... except Exception as e: print("column mismatch")
column mismatch

>> sp = Sparsity.dense(2, 2); sp.append(Sparsity.diag(2)); disp(DM(sp, 1))
[[1, 1],
 [1, 1],
 [1, 00],
 [00, 1]]
>> sp = Sparsity(0, 0); sp.append(Sparsity.diag(2)); disp(sp)
2x2,2nz
>> try, sp.append(Sparsity.dense(2, 3)); catch e, disp('column mismatch'); end
column mismatch

julia> sp = ca.Sparsity.dense(2, 2); ca.append(sp, ca.Sparsity.diag(2)); ca.DM(sp, 1)
DM(
[[1, 1],
 [1, 1],
 [1, 00],
 [00, 1]])
julia> sp = ca.Sparsity(0, 0); ca.append(sp, ca.Sparsity.diag(2)); print(sp)
2x2,2nz
julia> try
           ca.append(ca.Sparsity.dense(2, 2), ca.Sparsity.dense(2, 3))
       catch e
           println("column mismatch")
       end
column mismatch

See also
appendColumns, vertcat

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

Definition at line 473 of file sparsity.cpp.

473  {
474  if (sp.size1()==0 && sp.size2()==0) {
475  // Appending pattern is empty
476  return;
477  } else if (size1()==0 && size2()==0) {
478  // This is empty
479  *this = sp;
480  } else {
481  casadi_assert(size2()==sp.size2(),
482  "Sparsity::append: Dimension mismatch. "
483  "You attempt to append a shape " + sp.dim()
484  + " to a shape " + dim()
485  + ". The number of columns must match.");
486  if (sp.size1()==0) {
487  // No rows to add
488  return;
489  } else if (size1()==0) {
490  // No rows before
491  *this = sp;
492  } else if (is_column()) {
493  // Append to vector (inefficient)
494  *this = (*this)->_appendVector(*sp);
495  } else {
496  // Append to matrix (inefficient)
497  *this = vertcat({*this, sp});
498  }
499  }
500  }
static Sparsity vertcat(const std::vector< Sparsity > &sp)
Accessed by SparsityInterface.
Definition: sparsity.cpp:1567
bool is_column() const
Check whether the pattern is a column vector, i.e. size2() == 1.
Definition: sparsity.cpp:287

References casadi::SparsityInternal::_appendVector(), dim(), is_column(), size1(), size2(), and vertcat().

◆ appendColumns()

void casadi::Sparsity::appendColumns ( const Sparsity &  sp)

The number of rows must match, otherwise an error is raised; a 0-by-0 pattern on either side is ignored. Equivalent to rebinding to horzcat(self, sp).

>>> sp = Sparsity.dense(2, 2); sp.appendColumns(Sparsity.diag(2)); print(DM(sp, 1))
[[1, 1, 1, 00], 
 [1, 1, 00, 1]]
>>> try: Sparsity.dense(2, 2).appendColumns(Sparsity.dense(3, 2))
... except Exception as e: print("row mismatch")
row mismatch

>> sp = Sparsity.dense(2, 2); sp.appendColumns(Sparsity.diag(2)); disp(DM(sp, 1))
[[1, 1, 1, 00],
 [1, 1, 00, 1]]
>> try, sp.appendColumns(Sparsity.dense(3, 2)); catch e, disp('row mismatch'); end
row mismatch

julia> sp = ca.Sparsity.dense(2, 2); ca.appendColumns(sp, ca.Sparsity.diag(2)); ca.DM(sp, 1)
DM(
[[1, 1, 1, 00],
 [1, 1, 00, 1]])
julia> try
           ca.appendColumns(ca.Sparsity.dense(2, 2), ca.Sparsity.dense(3, 2))
       catch e
           println("row mismatch")
       end
row mismatch

See also
append, horzcat

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

Definition at line 502 of file sparsity.cpp.

502  {
503  if (sp.size1()==0 && sp.size2()==0) {
504  // Appending pattern is empty
505  return;
506  } else if (size1()==0 && size2()==0) {
507  // This is empty
508  *this = sp;
509  } else {
510  casadi_assert(size1()==sp.size1(),
511  "Sparsity::appendColumns: Dimension mismatch. You attempt to "
512  "append a shape " + sp.dim() + " to a shape "
513  + dim() + ". The number of rows must match.");
514  if (sp.size2()==0) {
515  // No columns to add
516  return;
517  } else if (size2()==0) {
518  // No columns before
519  *this = sp;
520  } else {
521  // Append to matrix (expensive)
522  *this = (*this)->_appendColumns(*sp);
523  }
524  }
525  }

References casadi::SparsityInternal::_appendColumns(), dim(), size1(), and size2().

Referenced by casadi::Sqpmethod::init().

◆ 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  }

◆ band()

Sparsity casadi::Sparsity::band ( casadi_int  n,
casadi_int  p 
)
static

The nonzeros are the entries (i+p, i): band(n, 0) equals diag(n), band(n, 1) is the first subdiagonal and band(n, -1) the first superdiagonal.

Parameters
nSize of the square pattern
pOffset of the band from the diagonal, positive below the diagonal and negative above it; |p| must be smaller than n, otherwise an error is raised

>>> DM(Sparsity.band(4, 1), 1)
DM(
[[00, 00, 00, 00],
 [1, 00, 00, 00],
 [00, 1, 00, 00],
 [00, 00, 1, 00]])
>>> DM(Sparsity.band(4, -2), 1)
DM(
[[00, 00, 1, 00],
 [00, 00, 00, 1],
 [00, 00, 00, 00],
 [00, 00, 00, 00]])
>>> Sparsity.band(4, 0) == Sparsity.diag(4)
True

>> DM(Sparsity.band(4, 1), 1)
[[00, 00, 00, 00],
 [1, 00, 00, 00],
 [00, 1, 00, 00],
 [00, 00, 1, 00]]
>> DM(Sparsity.band(4, -2), 1)
[[00, 00, 1, 00],
 [00, 00, 00, 1],
 [00, 00, 00, 00],
 [00, 00, 00, 00]]
>> Sparsity.band(4, 0) == Sparsity.diag(4)
1

julia> ca.DM(ca.Sparsity.band(4, 1), 1)
DM(
[[00, 00, 00, 00],
 [1, 00, 00, 00],
 [00, 1, 00, 00],
 [00, 00, 1, 00]])
julia> ca.DM(ca.Sparsity.band(4, -2), 1)
DM(
[[00, 00, 1, 00],
 [00, 00, 00, 1],
 [00, 00, 00, 00],
 [00, 00, 00, 00]])
julia> ca.is_equal(ca.Sparsity.band(4, 0), ca.Sparsity.diag(4))
true

See also
banded, diag

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

Definition at line 1099 of file sparsity.cpp.

1099  {
1100  casadi_assert(n>=0, "Sparsity::band expects a positive integer as argument");
1101  casadi_assert((p<0? -p : p)<n,
1102  "Sparsity::band: position of band should be smaller than size argument");
1103 
1104  casadi_int nc = n-(p<0? -p : p);
1105 
1106  std::vector< casadi_int > row(nc);
1107 
1108  casadi_int offset = std::max(p, casadi_int(0));
1109  for (casadi_int i=0;i<nc;i++) {
1110  row[i]=i+offset;
1111  }
1112 
1113  std::vector< casadi_int > colind(n+1);
1114 
1115  offset = std::min(p, casadi_int(0));
1116  for (casadi_int i=0;i<n+1;i++) {
1117  colind[i] = std::max(std::min(i+offset, nc), casadi_int(0));
1118  }
1119 
1120  return Sparsity(n, n, colind, row);
1121 
1122  }
static std::vector< casadi_int > offset(const std::vector< Sparsity > &v, bool vert=true)
Sparsity(casadi_int dummy=0)
Default constructor: a null object that holds no pattern.
Definition: sparsity.cpp:68

References colind(), casadi::SparsityInterface< Sparsity >::offset(), row(), and Sparsity().

Referenced by banded(), and casadi::SlicotDple::init_mem().

◆ banded()

Sparsity casadi::Sparsity::banded ( casadi_int  n,
casadi_int  p 
)
static

Union of band(n, k) for all k in [-p, p]: banded(n, 0) equals diag(n) and banded(n, 1) is tridiagonal.

Parameters
nSize of the square pattern
pHalf-bandwidth; p >= n gives a dense pattern and a negative p an all-zero pattern

>>> DM(Sparsity.banded(4, 1), 1)
DM(
[[1, 1, 00, 00],
 [1, 1, 1, 00],
 [00, 1, 1, 1],
 [00, 00, 1, 1]])
>>> Sparsity.banded(4, 1).bw_upper(), Sparsity.banded(4, 1).bw_lower()
(1, 1)

>> DM(Sparsity.banded(4, 1), 1)
[[1, 1, 00, 00],
 [1, 1, 1, 00],
 [00, 1, 1, 1],
 [00, 00, 1, 1]]
>> [Sparsity.banded(4, 1).bw_upper(), Sparsity.banded(4, 1).bw_lower()]
1 1

julia> ca.DM(ca.Sparsity.banded(4, 1), 1)
DM(
[[1, 1, 00, 00],
 [1, 1, 1, 00],
 [00, 1, 1, 1],
 [00, 00, 1, 1]])
julia> ca.bw_upper(ca.Sparsity.banded(4, 1)), ca.bw_lower(ca.Sparsity.banded(4, 1))
(1, 1)

See also
band, bw_upper, bw_lower

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

Definition at line 1124 of file sparsity.cpp.

1124  {
1125  // This is not an efficient implementation
1126  Sparsity ret = Sparsity(n, n);
1127  p = std::min(p, n-1);
1128  for (casadi_int i=-p;i<=p;++i) {
1129  ret = ret + Sparsity::band(n, i);
1130  }
1131  return ret;
1132  }
static Sparsity band(casadi_int n, casadi_int p)
Create a single band in a square sparsity pattern.
Definition: sparsity.cpp:1099

References band(), and Sparsity().

◆ blockcat()

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

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

Definition at line 1688 of file sparsity.cpp.

1688  {
1689  std::vector< Sparsity > ret;
1690  for (casadi_int i=0; i<v.size(); ++i)
1691  if (!v[i].empty()) ret.push_back(horzcat(v[i]));
1692  if (ret.empty()) return Sparsity(0, 0);
1693  return vertcat(ret);
1694  }
static Sparsity horzcat(const std::vector< Sparsity > &sp)
Accessed by SparsityInterface.
Definition: sparsity.cpp:1424

References horzcat(), Sparsity(), and vertcat().

Referenced by kkt().

◆ bor() [1/2]

template<typename DataType >
void casadi::Sparsity::bor ( DataType *  data,
const DataType *  val_data,
const Sparsity &  val_sp 
) const

Definition at line 6267 of file sparsity.hpp.

6267  {
6268  // Get dimensions of this
6269  const casadi_int sz = nnz();
6270  const casadi_int sz1 = size1();
6271  const casadi_int sz2 = size2();
6272  const casadi_int nel = sz1*sz2;
6273 
6274  // Get dimensions of assigning matrix
6275  const casadi_int val_sz = val_sp.nnz();
6276  const casadi_int val_sz1 = val_sp.size1();
6277  const casadi_int val_sz2 = val_sp.size2();
6278  const casadi_int val_nel = val_sz1*val_sz2;
6279 
6280  // Check if sparsity matches
6281  if (val_sp==*this) {
6282  for (casadi_int k=0; k<sz; ++k) {
6283  data[k] |= val_data[k];
6284  }
6285  } else if (this->is_empty()) {
6286  // Quick return
6287  return;
6288  } else if (val_sp.is_empty()) {
6289  // Quick return
6290  return;
6291  } else if (val_nel==1) { // if scalar
6292  if (val_sz!=0) {
6293  for (casadi_int k=0; k<sz; ++k) {
6294  data[k] |= val_data[0];
6295  }
6296  }
6297  } else {
6298  // Quick return if empty
6299  if (nel==0 && val_nel==0) return;
6300 
6301  // Make sure that dimension matches
6302  casadi_assert(sz2==val_sz2 && sz1==val_sz1,
6303  "Sparsity::add<DataType>: shape mismatch. lhs is "
6304  + dim() + ", while rhs is " + val_sp.dim() + ".");
6305 
6306  // Sparsity
6307  const casadi_int* c = row();
6308  const casadi_int* rind = colind();
6309  const casadi_int* v_c = val_sp.row();
6310  const casadi_int* v_rind = val_sp.colind();
6311 
6312  // For all columns
6313  for (casadi_int i=0; i<sz2; ++i) {
6314 
6315  // Nonzero of the assigning matrix
6316  casadi_int v_el = v_rind[i];
6317 
6318  // First nonzero of the following column
6319  casadi_int v_el_end = v_rind[i+1];
6320 
6321  // Next row of the assigning matrix
6322  casadi_int v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6323 
6324  // Assign all nonzeros
6325  for (casadi_int el=rind[i]; el!=rind[i+1]; ++el) {
6326 
6327  // Get row
6328  casadi_int j=c[el];
6329 
6330  // Forward the assigning nonzero
6331  while (v_j<j) {
6332  v_el++;
6333  v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6334  }
6335 
6336  // Assign nonzero
6337  if (v_j==j) {
6338  data[el] |= val_data[v_el++];
6339  v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6340  }
6341  }
6342  }
6343  }
6344  }

References colind(), dim(), is_empty(), nnz(), row(), size1(), and size2().

◆ bor() [2/2]

template<typename T >
void casadi::Sparsity::bor ( T *  data,
const T *  val_data,
const Sparsity &  val_sp 
) const

entries of another sparsity pattern

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

Referenced by casadi::Project::sp_reverse().

◆ btf()

casadi_int casadi::Sparsity::btf ( std::vector< casadi_int > &  rowperm,
std::vector< casadi_int > &  colperm,
std::vector< casadi_int > &  rowblock,
std::vector< casadi_int > &  colblock,
std::vector< casadi_int > &  coarse_rowblock,
std::vector< casadi_int > &  coarse_colblock 
) const

Computes a row permutation and a column permutation that bring the pattern into block upper triangular form, see Direct Methods for Sparse Linear Systems by Davis (2006). The pattern may be rectangular.

Returns
  • the number of fine blocks nb
  • rowperm, colperm: row and column permutation vectors, so that A[rowperm, colperm] is in block upper triangular form
  • rowblock, colblock (length nb+1): block k spans rows rowblock[k] to rowblock[k+1]-1 and columns colblock[k] to colblock[k+1]-1 of the permuted matrix
  • coarse_rowblock, coarse_colblock (length 5): boundaries of the coarse decomposition into the underdetermined, square (well-determined) and overdetermined parts; coarse_colblock[3] is the structural rank (sprank)

Only structure is used: the distance of entries to the diagonal plays no role, so a randomly permuted block-diagonal matrix is not necessarily brought back to block diagonal form, and the row and column permutations differ in general, which destroys symmetry. The result is cached in the pattern.

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

>>> B = Sparsity.triplet(3, 3, [0, 0, 1, 2], [0, 2, 1, 2])
>>> DM(B, 1)
DM(
[[1, 00, 1],
 [00, 1, 00],
 [00, 00, 1]])
>>> nb, rowperm, colperm, rowblock, colblock, crb, ccb = B.btf()
>>> nb, rowperm, colperm, rowblock, colblock
(3, [2, 0, 1], [2, 0, 1], [0, 1, 2, 3], [0, 1, 2, 3])
>>> crb, ccb
([0, 0, 0, 3, 3], [0, 0, 3, 3, 3])
>>> DM(B, 1)[rowperm, colperm]
DM(
[[1, 00, 00],
 [1, 1, 00],
 [00, 00, 1]])
>>> sprank(Sparsity.nonzeros(3, 3, [0, 1, 2])), sprank(Sparsity.diag(3))
(1, 3)

>> B = Sparsity.triplet(3, 3, [0, 0, 1, 2], [0, 2, 1, 2]);
>> DM(B, 1)
[[1, 00, 1],
 [00, 1, 00],
 [00, 00, 1]]
>> [nb, rowperm, colperm, rowblock, colblock, crb, ccb] = B.btf();
>> nb, rowperm, colperm, rowblock, colblock
3
2 0 1
2 0 1
0 1 2 3
0 1 2 3
>> crb, ccb
0 0 0 3 3
0 0 3 3 3
>> Bf = DM(B, 1); disp(Bf(rowperm + 1, colperm + 1))
[[1, 00, 00],
 [1, 1, 00],
 [00, 00, 1]]
>> [sprank(Sparsity.nonzeros(3, 3, [1, 2, 3])), sprank(Sparsity.diag(3))]
1 3

julia> B = ca.Sparsity.triplet(3, 3, [0, 0, 1, 2], [0, 2, 1, 2]);
julia> ca.DM(B, 1)
DM(
[[1, 00, 1],
 [00, 1, 00],
 [00, 00, 1]])
julia> ca.btf(B)
(3, [2, 0, 1], [2, 0, 1], [0, 1, 2, 3], [0, 1, 2, 3], [0, 0, 0, 3, 3], [0, 0, 3, 3, 3])
julia> ca.sprank(ca.Sparsity.nonzeros(3, 3, [0, 1, 2])), ca.sprank(ca.Sparsity.diag(3))
(1, 3)

See also
scc, sprank, is_singular

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

Examples
matrix/btf.py.

Definition at line 723 of file sparsity.cpp.

726  {
727  try {
728  return (*this)->btf(rowperm, colperm, rowblock, colblock,
729  coarse_rowblock, coarse_colblock);
730  } catch (std::exception &e) {
731  CASADI_THROW_ERROR("btf", e.what());
732  }
733  }

Referenced by casadi::SymbolicQr::det(), casadi::SymbolicQr::init(), and sprank().

◆ bw_lower()

casadi_int casadi::Sparsity::bw_lower ( ) const

Zero for a diagonal, upper triangular or all-zero pattern.

>>> Sparsity.banded(5, 2).bw_lower(), Sparsity.band(5, 2).bw_lower()
(2, 2)
>>> Sparsity.band(5, -2).bw_lower()
0
>>> Sparsity.dense(5, 2).bw_lower()
4

>> [Sparsity.banded(5, 2).bw_lower(), Sparsity.band(5, 2).bw_lower()]
2 2
>> Sparsity.band(5, -2).bw_lower()
0
>> Sparsity.dense(5, 2).bw_lower()
4

julia> ca.bw_lower(ca.Sparsity.banded(5, 2)), ca.bw_lower(ca.Sparsity.band(5, 2))
(2, 2)
julia> ca.bw_lower(ca.Sparsity.band(5, -2))
0
julia> ca.bw_lower(ca.Sparsity.dense(5, 2))
4

See also
bw_upper, banded

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

Definition at line 1420 of file sparsity.cpp.

1420  {
1421  return (*this)->bw_lower();
1422  }

◆ bw_upper()

casadi_int casadi::Sparsity::bw_upper ( ) const

Zero for a diagonal, lower triangular or all-zero pattern.

>>> Sparsity.banded(5, 2).bw_upper(), Sparsity.band(5, -2).bw_upper()
(2, 2)
>>> Sparsity.band(5, 2).bw_upper(), Sparsity.diag(3).bw_upper()
(0, 0)
>>> Sparsity(3, 3).bw_upper(), Sparsity.dense(2, 5).bw_upper()
(0, 4)

>> [Sparsity.banded(5, 2).bw_upper(), Sparsity.band(5, -2).bw_upper()]
2 2
>> [Sparsity.band(5, 2).bw_upper(), Sparsity.diag(3).bw_upper()]
0 0
>> [Sparsity(3, 3).bw_upper(), Sparsity.dense(2, 5).bw_upper()]
0 4

julia> ca.bw_upper(ca.Sparsity.banded(5, 2)), ca.bw_upper(ca.Sparsity.band(5, -2))
(2, 2)
julia> ca.bw_upper(ca.Sparsity.band(5, 2)), ca.bw_upper(ca.Sparsity.diag(3))
(0, 0)
julia> ca.bw_upper(ca.Sparsity(3, 3)), ca.bw_upper(ca.Sparsity.dense(2, 5))
(0, 4)

See also
bw_lower, banded

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

Definition at line 1416 of file sparsity.cpp.

1416  {
1417  return (*this)->bw_upper();
1418  }

◆ class_name()

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

◆ colind() [1/2]

const casadi_int * casadi::Sparsity::colind ( ) const

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

Definition at line 170 of file sparsity.cpp.

170  {
171  return (*this)->colind();
172  }

Referenced by casadi::SparsityInternal::_mtimes(), add(), add_nz(), band(), casadi::SparsityInternal::bfs(), casadi::KinsolInterface::bjac(), bor(), casadi::Blocksqp::calcHessianUpdateExact(), casadi::Blocksqp::calcLagrangeGradient(), casadi::casadi_func_cons_jac(), casadi::GenericMatrix< MatType >::colind(), colind(), casadi::SparsityInternal::combineGen(), compressed(), casadi::ConoptInterface::ConoptInterface(), casadi::construct_nlpsol(), casadi::IndexReduction::dae_struct_detect(), dense(), casadi::detect_simple_bounds_gen(), diag(), diagcat(), casadi::KinsolInterface::djac(), casadi::Transpose::eval_gen(), casadi::BonminUserClass::eval_h(), casadi::IpoptUserClass::eval_h(), casadi::AlpaqaProblem::eval_hess_L(), casadi::AlpaqaProblem::eval_hess_ψ(), casadi::AlpaqaProblem::eval_jac_g(), casadi::BonminUserClass::eval_jac_g(), casadi::IpoptUserClass::eval_jac_g(), casadi::FmuFunction::eval_task(), casadi::FmuFunction::finalize_hessian(), get_ccs(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::FunctionInternal::get_sparsity_out(), horzsplit(), casadi::SqicInterface::init(), casadi::Dple::init(), casadi::AmplInterface::init(), casadi::Blocksqp::init(), casadi::BonminInterface::init(), casadi::ConoptInterface::init(), casadi::FatropConicInterface::init(), casadi::HpipmInterface::init(), casadi::HpmpcInterface::init(), casadi::SlicotDple::init(), casadi::SuperscsInterface::init(), casadi::ClarabelInterface::init_dependent(), casadi::HighsInterface::init_dependent(), casadi::MosekInterface::init_dependent(), casadi::XpressInterface::init_dependent(), casadi::CplexInterface::init_mem(), is_equal(), casadi::SparsityInternal::is_equal(), casadi::SparsityInternal::is_stacked(), casadi::XFunction< DerivedType, MatType, NodeType >::jac(), kron(), kron_contract(), casadi::kron_sp_gen(), lower(), casadi::mul_bvec_fwd(), mul_sparsityR(), casadi::SparsityInternal::multiply(), norm_0_mul(), permutation(), casadi::FunctionInternal::print_canonical(), casadi::Matrix< Scalar >::print_dense(), casadi::Matrix< Scalar >::print_sparse(), casadi::CvodesInterface::psetupF(), casadi::IdasInterface::psetupF(), casadi::Conic::sdp_to_socp_init(), set(), casadi::WorhpInterface::set_work(), casadi::CbcInterface::solve(), casadi::ClpInterface::solve(), casadi::CplexInterface::solve(), casadi::GurobiInterface::solve(), casadi::OoqpInterface::solve(), casadi::OsqpInterface::solve(), casadi::QpoasesInterface::solve(), casadi::SuperscsInterface::solve(), casadi::ConoptInterface::solve(), casadi::WorhpInterface::solve(), casadi::Blocksqp::solveQP(), casadi::KronContract::sp_forward(), casadi::Rank1::sp_forward(), casadi::Solve< Tr >::sp_forward(), casadi::Transpose::sp_forward(), casadi::FunctionInternal::sp_forward_block(), casadi::KronContract::sp_reverse(), casadi::Rank1::sp_reverse(), casadi::Solve< Tr >::sp_reverse(), casadi::Transpose::sp_reverse(), casadi::FunctionInternal::sp_reverse(), Sparsity(), casadi::SparsityInternal::star_coloring_new(), casadi::SparsityInternal::uni_coloring(), unit(), casadi::DaeBuilderInternal::update_dependencies(), upper(), and casadi::SnoptInterface::userfun().

◆ colind() [2/2]

casadi_int casadi::Sparsity::colind ( casadi_int  cc) const
Parameters
ccColumn, in [0, size2()]; colind(size2()) equals nnz(). An index out of range raises an error.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.row(1), sp.colind(1), sp.colind(4)
(2, 2, 4)
>>> try: sp.row(4)
... except Exception as e: print("out of range")
out of range

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [sp.row(1), sp.colind(1), sp.colind(4)]
2 2 4
>> try, sp.row(4); catch e, disp('out of range'); end
out of range

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.row(sp, 1), ca.colind(sp, 1), ca.colind(sp, 4)
(2, 2, 4)
julia> try
           ca.row(sp, 4)
       catch e
           println("out of range")
       end
out of range

See also
row, get_colind

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

Definition at line 182 of file sparsity.cpp.

182  {
183  if (cc<0 || cc>size2()) {
184  throw std::out_of_range("Sparsity::colind: Index "
185  + str(cc) + " out of range [0," + str(size2()) + "]");
186  }
187  return colind()[cc];
188  }

References colind(), size2(), and casadi::str().

◆ columns()

casadi_int casadi::Sparsity::columns ( ) const
inline

Definition at line 1549 of file sparsity.hpp.

1549 {return size2();}

◆ combine() [1/2]

Sparsity casadi::Sparsity::combine ( const Sparsity &  y,
bool  f0x_is_zero,
bool  function0_is_zero 
) const

Models the pattern of f(x, y) applied elementwise, where y has this pattern's shape. An entry is kept in the result when both arguments are nonzero; an entry where only y is nonzero is kept unless f0x_is_zero (f(0, y) == 0) and an entry where only x is nonzero is kept unless function0_is_zero (f(x, 0) == 0). So combine(y, False, False) is the union (unite) and combine(y, True, True) is the intersection (intersect). A shape mismatch raises an error.

The C++ overload with mapping returns, per nonzero of the union, bit 1 if the first argument is nonzero, bit 2 if the second is and bit 4 if the entry was dropped from the result.

Parameters
yPattern with the same shape
f0x_is_zeroTrue if entries where only y is nonzero are structural zeros
function0_is_zeroTrue if entries where only this pattern is nonzero are structural zeros

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> a.combine(b, False, False) == a + b, a.combine(b, True, True) == a * b
(True, True)
>>> DM(a.combine(b, True, False), 1)
DM(
[[1, 00],
 [00, 1]])
>>> DM(a.combine(b, False, True), 1)
DM(
[[00, 1],
 [00, 1]])

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> a.combine(b, false, false) == a + b, a.combine(b, true, true) == a .* b
1
1
>> DM(a.combine(b, true, false), 1)
[[1, 00],
 [00, 1]]
>> DM(a.combine(b, false, true), 1)
[[00, 1],
 [00, 1]]

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.is_equal(ca.combine(a, b, false, false), ca.unite(a, b))
true
julia> ca.DM(ca.combine(a, b, true, false), 1)
DM(
[[1, 00],
 [00, 1]])
julia> ca.DM(ca.combine(a, b, false, true), 1)
DM(
[[00, 1],
 [00, 1]])

See also
unite, intersect

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

Definition at line 406 of file sparsity.cpp.

407  {
408  return (*this)->combine(y, f0x_is_zero, fx0_is_zero);
409  }

References casadi::SparsityInternal::combine().

◆ combine() [2/2]

Sparsity casadi::Sparsity::combine ( const Sparsity &  y,
bool  f0x_is_zero,
bool  function0_is_zero,
std::vector< unsigned char > &  mapping 
) const

Models the pattern of f(x, y) applied elementwise, where y has this pattern's shape. An entry is kept in the result when both arguments are nonzero; an entry where only y is nonzero is kept unless f0x_is_zero (f(0, y) == 0) and an entry where only x is nonzero is kept unless function0_is_zero (f(x, 0) == 0). So combine(y, False, False) is the union (unite) and combine(y, True, True) is the intersection (intersect). A shape mismatch raises an error.

The C++ overload with mapping returns, per nonzero of the union, bit 1 if the first argument is nonzero, bit 2 if the second is and bit 4 if the entry was dropped from the result.

Parameters
yPattern with the same shape
f0x_is_zeroTrue if entries where only y is nonzero are structural zeros
function0_is_zeroTrue if entries where only this pattern is nonzero are structural zeros

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> a.combine(b, False, False) == a + b, a.combine(b, True, True) == a * b
(True, True)
>>> DM(a.combine(b, True, False), 1)
DM(
[[1, 00],
 [00, 1]])
>>> DM(a.combine(b, False, True), 1)
DM(
[[00, 1],
 [00, 1]])

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> a.combine(b, false, false) == a + b, a.combine(b, true, true) == a .* b
1
1
>> DM(a.combine(b, true, false), 1)
[[1, 00],
 [00, 1]]
>> DM(a.combine(b, false, true), 1)
[[00, 1],
 [00, 1]]

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.is_equal(ca.combine(a, b, false, false), ca.unite(a, b))
true
julia> ca.DM(ca.combine(a, b, true, false), 1)
DM(
[[1, 00],
 [00, 1]])
julia> ca.DM(ca.combine(a, b, false, true), 1)
DM(
[[00, 1],
 [00, 1]])

See also
unite, intersect

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

Definition at line 400 of file sparsity.cpp.

402  {
403  return (*this)->combine(y, f0x_is_zero, fx0_is_zero, mapping);
404  }

References casadi::SparsityInternal::combine().

Referenced by casadi::MXNode::get_binary().

◆ compress()

std::vector< casadi_int > casadi::Sparsity::compress ( bool  canonical = true) const

Returns [nrow, ncol, colind..., row...], the layout accepted by compressed() and used for sparsity patterns in generated C code. With canonical false, a dense pattern is abbreviated to [nrow, ncol, 1] (an abbreviation that compressed() given a vector does not accept).

>>> Sparsity.diag(2).compress()
[2, 2, 0, 1, 2, 0, 1]
>>> Sparsity.dense(2, 2).compress()
[2, 2, 0, 2, 4, 0, 1, 0, 1]
>>> Sparsity.dense(2, 2).compress(False)
[2, 2, 1]
>>> Sparsity(0, 2).compress()
[0, 2, 0, 0, 0]

>> Sparsity.diag(2).compress()
2 2 0 1 2 0 1
>> Sparsity.dense(2, 2).compress()
2 2 0 2 4 0 1 0 1
>> Sparsity.dense(2, 2).compress(false)
2 2 1
>> Sparsity(0, 2).compress()
0 2 0 0 0

julia> println(ca.compress(ca.Sparsity.diag(2)))
[2, 2, 0, 1, 2, 0, 1]
julia> println(ca.compress(ca.Sparsity.dense(2, 2)))
[2, 2, 0, 2, 4, 0, 1, 0, 1]
julia> println(ca.compress(ca.Sparsity.dense(2, 2), false))
[2, 2, 1]
julia> println(ca.compress(ca.Sparsity(0, 2)))
[0, 2, 0, 0, 0]

See also
compressed, get_ccs

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

Definition at line 1335 of file sparsity.cpp.

1335  {
1336  if (canonical) {
1337  // fallback
1338  } else if (is_dense()) {
1339  return {size1(), size2(), 1};
1340  }
1341  return (*this)->sp();
1342  }

References is_dense(), size1(), and size2().

Referenced by casadi::CodeGenerator::add_sparsity(), and serialize().

◆ compressed() [1/2]

Sparsity casadi::Sparsity::compressed ( const casadi_int *  v,
bool  order_rows = false 
)
static

The vector is laid out as [nrow, ncol, colind (ncol+1 entries), row (colind[ncol] entries)]. This is the format returned by compress() and used by generated C code (casadi_int arrays). When colind[ncol] equals nrow*ncol the row entries may be omitted (a dense pattern). An inconsistent vector raises an error.

Parameters
vCompact representation
order_rowsIf true, unsorted row indices within a column are sorted instead of raising an error

>>> sp = Sparsity.compressed([3, 2, 0, 1, 2, 0, 2])
>>> DM(sp, 1)
DM(
[[1, 00],
 [00, 00],
 [00, 1]])
>>> Sparsity.compressed(sp.compress()) == sp
True
>>> Sparsity.compressed([2, 2, 0, 2, 4])
Sparsity(2x2)

>> sp = Sparsity.compressed([3, 2, 0, 1, 2, 0, 2]);
>> DM(sp, 1)
[[1, 00],
 [00, 00],
 [00, 1]]
>> Sparsity.compressed(sp.compress()) == sp
1
>> Sparsity.compressed([2, 2, 0, 2, 4])
2x2

julia> sp = ca.Sparsity.compressed([3, 2, 0, 1, 2, 0, 2]);
julia> ca.DM(sp, 1)
DM(
[[1, 00],
 [00, 00],
 [00, 1]])
julia> ca.is_equal(ca.Sparsity.compressed(ca.compress(sp)), sp)
true
julia> ca.Sparsity.compressed([2, 2, 0, 2, 4])
Sparsity(2x2)

See also
compress, Sparsity(nrow, ncol, colind, row)

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

Definition at line 1372 of file sparsity.cpp.

1372  {
1373  casadi_assert_dev(v!=nullptr);
1374 
1375  // Get sparsity pattern
1376  casadi_int nrow = v[0];
1377  casadi_int ncol = v[1];
1378  const casadi_int *colind = v+2;
1379  if (colind[0]==1) {
1380  // Dense matrix - deviation from canonical form
1381  return Sparsity::dense(nrow, ncol);
1382  }
1383  casadi_int nnz = colind[ncol];
1384  if (nrow*ncol == nnz) {
1385  // Dense matrix
1386  return Sparsity::dense(nrow, ncol);
1387  } else {
1388  // Sparse matrix
1389  const casadi_int *row = v + 2 + ncol+1;
1390  return Sparsity(nrow, ncol,
1391  std::vector<casadi_int>(colind, colind+ncol+1),
1392  std::vector<casadi_int>(row, row+nnz), order_rows);
1393  }
1394  }

References colind(), dense(), nnz(), row(), and Sparsity().

◆ compressed() [2/2]

Sparsity casadi::Sparsity::compressed ( const std::vector< casadi_int > &  v,
bool  order_rows = false 
)
static

The vector is laid out as [nrow, ncol, colind (ncol+1 entries), row (colind[ncol] entries)]. This is the format returned by compress() and used by generated C code (casadi_int arrays). When colind[ncol] equals nrow*ncol the row entries may be omitted (a dense pattern). An inconsistent vector raises an error.

Parameters
vCompact representation
order_rowsIf true, unsorted row indices within a column are sorted instead of raising an error

>>> sp = Sparsity.compressed([3, 2, 0, 1, 2, 0, 2])
>>> DM(sp, 1)
DM(
[[1, 00],
 [00, 00],
 [00, 1]])
>>> Sparsity.compressed(sp.compress()) == sp
True
>>> Sparsity.compressed([2, 2, 0, 2, 4])
Sparsity(2x2)

>> sp = Sparsity.compressed([3, 2, 0, 1, 2, 0, 2]);
>> DM(sp, 1)
[[1, 00],
 [00, 00],
 [00, 1]]
>> Sparsity.compressed(sp.compress()) == sp
1
>> Sparsity.compressed([2, 2, 0, 2, 4])
2x2

julia> sp = ca.Sparsity.compressed([3, 2, 0, 1, 2, 0, 2]);
julia> ca.DM(sp, 1)
DM(
[[1, 00],
 [00, 00],
 [00, 1]])
julia> ca.is_equal(ca.Sparsity.compressed(ca.compress(sp)), sp)
true
julia> ca.Sparsity.compressed([2, 2, 0, 2, 4])
Sparsity(2x2)

See also
compress, Sparsity(nrow, ncol, colind, row)

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

Definition at line 1355 of file sparsity.cpp.

1355  {
1356  // Check consistency
1357  casadi_assert_dev(v.size() >= 2);
1358  casadi_int nrow = v[0];
1359  casadi_int ncol = v[1];
1360  // Dense matrix - deviation from canonical form
1361  if (v.size()==3 && v[2]==1) return Sparsity::dense(nrow, ncol);
1362  casadi_assert_dev(v.size() >= 2 + ncol+1);
1363  casadi_int nnz = v[2 + ncol];
1364  bool dense = v.size() == 2 + ncol+1 && nrow*ncol==nnz;
1365  bool sparse = v.size() == 2 + ncol+1 + nnz;
1366  casadi_assert_dev(dense || sparse);
1367 
1368  // Call array version
1369  return compressed(&v.front(), order_rows);
1370  }
std::pair< casadi_int, casadi_int > size() const
Shape as a pair (number of rows, number of columns)
Definition: sparsity.cpp:154
static Sparsity compressed(const std::vector< casadi_int > &v, bool order_rows=false)
Create from the compact single-vector representation of a pattern.
Definition: sparsity.cpp:1355

References dense(), nnz(), and size().

Referenced by deserialize(), casadi::GenericExternal::get_jac_sparsity(), casadi::GenericExternal::get_sparsity_in(), casadi::GenericExternal::get_sparsity_out(), and qr_sparse().

◆ 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()

Sparsity casadi::Sparsity::create ( SparsityInternal *  node)
static

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

Definition at line 72 of file sparsity.cpp.

72  {
73  Sparsity ret;
74  ret.own(node);
75  return ret;
76  }

References casadi::GenericShared< Shared, Internal >::own().

◆ 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

◆ dense() [1/2]

Sparsity casadi::Sparsity::dense ( casadi_int  nrow,
casadi_int  ncol = 1 
)
static

All nrow*ncol entries are nonzeros, stored column by column. This is the pattern of every matrix created without an explicit sparsity, e.g. SX.sym("x", 2, 3).

Parameters
nrowNumber of rows, nonnegative
ncolNumber of columns, nonnegative; default 1 (a dense column vector)

The shape can also be given as a single pair (nrow, ncol).

>>> sp = Sparsity.dense(2, 3)
>>> sp, sp.nnz(), sp.is_dense()
(Sparsity(2x3), 6, True)
>>> sp.colind(), sp.row()
([0, 2, 4, 6], [0, 1, 0, 1, 0, 1])
>>> Sparsity.dense(3), Sparsity.dense((2, 3))
(Sparsity(3x1), Sparsity(2x3))
>>> Sparsity.dense(0, 3).nnz(), Sparsity.dense(0, 3).is_dense()
(0, True)

>> sp = Sparsity.dense(2, 3);
>> sp, sp.nnz(), sp.is_dense()
2x3
6
1
>> sp.colind(), sp.row()
0 2 4 6
0 1 0 1 0 1
>> Sparsity.dense(3), Sparsity.dense([2, 3])
3x1
2x3
>> Sparsity.dense(0, 3).nnz(), Sparsity.dense(0, 3).is_dense()
0
1

julia> sp = ca.Sparsity.dense(2, 3)
Sparsity(2x3)
julia> ca.nnz(sp), ca.is_dense(sp)
(6, true)
julia> ca.colind(sp), ca.row(sp)
([0, 2, 4, 6], [0, 1, 0, 1, 0, 1])
julia> ca.Sparsity.dense(3), ca.Sparsity.dense(2, 3)
(3x1, 2x3)
julia> ca.nnz(ca.Sparsity.dense(0, 3)), ca.is_dense(ca.Sparsity.dense(0, 3))
(0, true)

See also
Sparsity(nrow, ncol), scalar, is_dense

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

Definition at line 1041 of file sparsity.cpp.

1041  {
1042  casadi_assert(nrow>=0 && ncol>=0,
1043  "Dimensions must be non-negative, got " + str(nrow) + "-by-" + str(ncol));
1044  // Column offset
1045  std::vector<casadi_int> colind(ncol+1);
1046  for (casadi_int cc=0; cc<ncol+1; ++cc) colind[cc] = cc*nrow;
1047 
1048  // Row
1049  std::vector<casadi_int> row(ncol*nrow);
1050  for (casadi_int cc=0; cc<ncol; ++cc)
1051  for (casadi_int rr=0; rr<nrow; ++rr)
1052  row[rr+cc*nrow] = rr;
1053 
1054  return Sparsity(nrow, ncol, colind, row);
1055  }

References colind(), row(), Sparsity(), and casadi::str().

Referenced by casadi::Constant< Value >::_get_binary(), casadi::SparsityInternal::_mtimes(), casadi::BSpline::BSpline(), casadi::BSplineParametric::BSplineParametric(), compressed(), casadi::GetNonzerosParam::create(), casadi::Matrix< Scalar >::densify(), casadi::MX::densify(), casadi::Determinant::Determinant(), casadi::OnnxFunction::get_forward(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::OnnxFunction::get_jacobian(), casadi::MXNode::get_mac(), casadi::Nlpsol::get_reverse(), casadi::OnnxFunction::get_reverse(), casadi::BlazingSplineFunction::get_sparsity_in(), casadi::Expm::get_sparsity_in(), casadi::FmuFunction::get_sparsity_in(), casadi::Integrator::get_sparsity_in(), casadi::Interpolant::get_sparsity_in(), casadi::RuntimeIntegrator::get_sparsity_in(), casadi::BlazingSplineFunction::get_sparsity_out(), casadi::Conic::get_sparsity_out(), casadi::FmuFunction::get_sparsity_out(), casadi::Integrator::get_sparsity_out(), casadi::Interpolant::get_sparsity_out(), casadi::Nlpsol::get_sparsity_out(), casadi::RuntimeIntegrator::get_sparsity_out(), casadi::MX::inf(), casadi::SqicInterface::init(), casadi::Dple::init(), casadi::Blocksqp::init(), casadi::HpipmInterface::init(), casadi::HpmpcInterface::init(), casadi::Feasiblesqpmethod::init(), casadi::Qrsqp::init(), casadi::Sqpmethod::init(), casadi::SlicotDple::init_mem(), casadi::Inverse::Inverse(), casadi::FunctionInternal::jac_sparsity(), kron(), casadi::Onnx::load(), casadi::LogSumExp::LogSumExp(), casadi::SparsityInternal::makeDense(), casadi::MX::MX(), casadi::MX::nan(), casadi::GenericMatrix< MatType >::ones(), casadi::SparsityInternal::pattern_inverse(), casadi::Convexify::setup(), casadi::MX::solve(), Sparsity(), sum1(), sum2(), casadi::GenericMatrix< MatType >::sym(), casadi::SymbolicMX::SymbolicMX(), casadi::OnnxFunction::tensor_sparsity(), and casadi::GenericMatrix< MatType >::zeros().

◆ dense() [2/2]

static Sparsity casadi::Sparsity::dense ( const std::pair< casadi_int, casadi_int > &  rc)
inlinestatic

All nrow*ncol entries are nonzeros, stored column by column. This is the pattern of every matrix created without an explicit sparsity, e.g. SX.sym("x", 2, 3).

Parameters
nrowNumber of rows, nonnegative
ncolNumber of columns, nonnegative; default 1 (a dense column vector)

The shape can also be given as a single pair (nrow, ncol).

>>> sp = Sparsity.dense(2, 3)
>>> sp, sp.nnz(), sp.is_dense()
(Sparsity(2x3), 6, True)
>>> sp.colind(), sp.row()
([0, 2, 4, 6], [0, 1, 0, 1, 0, 1])
>>> Sparsity.dense(3), Sparsity.dense((2, 3))
(Sparsity(3x1), Sparsity(2x3))
>>> Sparsity.dense(0, 3).nnz(), Sparsity.dense(0, 3).is_dense()
(0, True)

>> sp = Sparsity.dense(2, 3);
>> sp, sp.nnz(), sp.is_dense()
2x3
6
1
>> sp.colind(), sp.row()
0 2 4 6
0 1 0 1 0 1
>> Sparsity.dense(3), Sparsity.dense([2, 3])
3x1
2x3
>> Sparsity.dense(0, 3).nnz(), Sparsity.dense(0, 3).is_dense()
0
1

julia> sp = ca.Sparsity.dense(2, 3)
Sparsity(2x3)
julia> ca.nnz(sp), ca.is_dense(sp)
(6, true)
julia> ca.colind(sp), ca.row(sp)
([0, 2, 4, 6], [0, 1, 0, 1, 0, 1])
julia> ca.Sparsity.dense(3), ca.Sparsity.dense(2, 3)
(3x1, 2x3)
julia> ca.nnz(ca.Sparsity.dense(0, 3)), ca.is_dense(ca.Sparsity.dense(0, 3))
(0, true)

See also
Sparsity(nrow, ncol), scalar, is_dense

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

Definition at line 521 of file sparsity.hpp.

521  {
522  return dense(rc.first, rc.second);
523  }

◆ density()

double casadi::Sparsity::density ( ) const

Computed in floating point, so it does not overflow for large shapes. An empty pattern (numel() == 0) is dense and gives 100.

>>> Sparsity.diag(4).density(), Sparsity.dense(2, 2).density()
(25.0, 100.0)
>>> Sparsity(0, 3).density()
100.0

>> fprintf('%g %g\n', Sparsity.diag(4).density(), Sparsity.dense(2, 2).density())
25 100
>> Sparsity(0, 3).density()
100

julia> ca.density(ca.Sparsity.diag(4)), ca.density(ca.Sparsity.dense(2, 2))
(25.0, 100.0)
julia> ca.density(ca.Sparsity(0, 3))
100.0

See also
nnz, numel, is_dense

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

Definition at line 136 of file sparsity.cpp.

136  {
137  // Empty patterns are dense
138  if (numel()==0) return 100;
139  double r = 100;
140  r *= static_cast<double>(nnz());
141  r /= static_cast<double>(size1());
142  r /= static_cast<double>(size2());
143  return r;
144  }
casadi_int numel() const
Total number of entries, structural zeros included, i.e. size1()*size2()
Definition: sparsity.cpp:132

References nnz(), numel(), size1(), and size2().

Referenced by casadi::FunctionInternal::get_jac_sparsity_gen(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), and casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm().

◆ deserialize() [1/3]

Sparsity casadi::Sparsity::deserialize ( const std::string &  s)
static
See also
serialize

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

Definition at line 2109 of file sparsity.cpp.

2109  {
2110  std::stringstream ss;
2111  ss << s;
2112  return deserialize(ss);
2113  }
static Sparsity deserialize(std::istream &stream)
Build a Sparsity from a serialized stream.
Definition: sparsity.cpp:2080

References deserialize().

◆ deserialize() [2/3]

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

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

Definition at line 2093 of file sparsity.cpp.

2093  {
2094  std::vector<casadi_int> i;
2095  s.unpack("SparsityInternal::compressed", i);
2096  if (i.empty()) {
2097  return Sparsity();
2098  } else {
2099  return Sparsity::compressed(i);
2100  }
2101  }

References compressed(), Sparsity(), and casadi::DeserializingStream::unpack().

◆ deserialize() [3/3]

Sparsity casadi::Sparsity::deserialize ( std::istream &  stream)
static

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

Definition at line 2080 of file sparsity.cpp.

2080  {
2081  DeserializingStream s(stream);
2082  return Sparsity::deserialize(s);
2083  }

Referenced by deserialize().

◆ dfs()

casadi_int casadi::Sparsity::dfs ( casadi_int  j,
casadi_int  top,
std::vector< casadi_int > &  SWIG_INOUT1xi,
std::vector< casadi_int > &  SWIG_INOUT2pstack,
const std::vector< casadi_int > &  pinv,
std::vector< bool > &  SWIG_INOUT3marked 
) const

Low-level building block of scc (cs_dfs in CSparse). Starting from column j, it visits the columns reachable through the nonzeros and writes them, in reverse finishing order, into xi below position top. See Direct Methods for Sparse Linear Systems by Davis (2006).

Parameters
jStart node (column)
topCurrent top of the output stack in xi
xiOutput stack, length at least size2(); the visited nodes are stored in xi[new_top:top]
pstackWork vector, length at least size2()
pinvInverse row permutation, or an empty vector for none
markedVisited flags per node, updated in place
Returns
The new top of the stack, with the updated xi, pstack and marked vectors

>>> Sparsity.banded(3, 1).dfs(0, 3, [0, 0, 0], [0, 0, 0], [], [False] * 3)
(0, [0, 1, 2], [1, 4, 5], [True, True, True])

>> sp = Sparsity.banded(3, 1); xi = [0, 0, 0]; pstack = [0, 0, 0];
>> [top, xi, pstack, marked] = sp.dfs(0, 3, xi, pstack, [], [false, false, false]);
>> top, xi, pstack, marked
0
0 1 2
1 4 5
1 1 1

julia> ca.dfs(ca.Sparsity.banded(3, 1), 0, 3, [0, 0, 0], [0, 0, 0], [], [false, false, false])
(0, [0, 1, 2], [1, 4, 5], Bool[1, 1, 1])

See also
scc

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

Definition at line 707 of file sparsity.cpp.

710  {
711  return (*this)->dfs(j, top, xi, pstack, pinv, marked);
712  }

Referenced by casadi::SparsityInternal::scc().

◆ diag() [1/3]

static Sparsity casadi::Sparsity::diag ( casadi_int  nrow)
inlinestatic

The nonzeros are the entries (i, i) for i < min(nrow, ncol); a rectangular diagonal pattern is allowed. The shape can be given as one integer (square), as two integers or as a pair.

>>> DM(Sparsity.diag(3), 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
>>> DM(Sparsity.diag(2, 4), 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 00]])
>>> Sparsity.diag((4, 2)).nnz(), Sparsity.diag(0).nnz()
(2, 0)

>> DM(Sparsity.diag(3), 1)
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]]
>> DM(Sparsity.diag(2, 4), 1)
[[1, 00, 00, 00],
 [00, 1, 00, 00]]
>> Sparsity.diag([4, 2]).nnz(), Sparsity.diag(0).nnz()
2
0

julia> ca.DM(ca.Sparsity.diag(3), 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
julia> ca.DM(ca.Sparsity.diag(2, 4), 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 00]])
julia> ca.nnz(ca.Sparsity.diag(4, 2)), ca.nnz(ca.Sparsity.diag(0))
(2, 0)

See also
band, is_diag, get_diag

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

Definition at line 723 of file sparsity.hpp.

723 { return diag(nrow, nrow);}
static Sparsity diag(casadi_int nrow)
Create a diagonal sparsity pattern.
Definition: sparsity.hpp:723

References diag().

Referenced by casadi::SolveUnity< Tr >::A_sp(), casadi::OsqpInterface::codegen_init_mem(), diag(), casadi::Factory< MatType >::get_output(), casadi::Blocksqp::init(), casadi::SundialsInterface::init(), casadi::SuperscsInterface::init(), casadi::Sqpmethod::init(), casadi::OsqpInterface::init_mem(), casadi::SlicotDple::init_mem(), kkt(), casadi::Convexify::setup(), casadi::Integrator::sp_jac_dae(), and casadi::Integrator::sp_jac_rdae().

◆ diag() [2/3]

Sparsity casadi::Sparsity::diag ( casadi_int  nrow,
casadi_int  ncol 
)
static

The nonzeros are the entries (i, i) for i < min(nrow, ncol); a rectangular diagonal pattern is allowed. The shape can be given as one integer (square), as two integers or as a pair.

>>> DM(Sparsity.diag(3), 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
>>> DM(Sparsity.diag(2, 4), 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 00]])
>>> Sparsity.diag((4, 2)).nnz(), Sparsity.diag(0).nnz()
(2, 0)

>> DM(Sparsity.diag(3), 1)
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]]
>> DM(Sparsity.diag(2, 4), 1)
[[1, 00, 00, 00],
 [00, 1, 00, 00]]
>> Sparsity.diag([4, 2]).nnz(), Sparsity.diag(0).nnz()
2
0

julia> ca.DM(ca.Sparsity.diag(3), 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
julia> ca.DM(ca.Sparsity.diag(2, 4), 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 00]])
julia> ca.nnz(ca.Sparsity.diag(4, 2)), ca.nnz(ca.Sparsity.diag(0))
(2, 0)

See also
band, is_diag, get_diag

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

Definition at line 573 of file sparsity.cpp.

573  {
574  casadi_assert(nrow>=0 && ncol>=0,
575  "Dimensions must be non-negative, got " + str(nrow) + "-by-" + str(ncol));
576 
577  // Smallest dimension
578  casadi_int n = std::min(nrow, ncol);
579 
580  // Column offset
581  std::vector<casadi_int> colind(ncol+1, n);
582  for (casadi_int cc=0; cc<n; ++cc) colind[cc] = cc;
583 
584  // Row
585  std::vector<casadi_int> row = range(n);
586 
587  // Create pattern from vectors
588  return Sparsity(nrow, ncol, colind, row);
589  }
std::vector< casadi_int > range(casadi_int start, casadi_int stop, casadi_int step, casadi_int len)
Range function.

References colind(), casadi::range(), row(), Sparsity(), and casadi::str().

◆ diag() [3/3]

static Sparsity casadi::Sparsity::diag ( const std::pair< casadi_int, casadi_int > &  rc)
inlinestatic

The nonzeros are the entries (i, i) for i < min(nrow, ncol); a rectangular diagonal pattern is allowed. The shape can be given as one integer (square), as two integers or as a pair.

>>> DM(Sparsity.diag(3), 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
>>> DM(Sparsity.diag(2, 4), 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 00]])
>>> Sparsity.diag((4, 2)).nnz(), Sparsity.diag(0).nnz()
(2, 0)

>> DM(Sparsity.diag(3), 1)
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]]
>> DM(Sparsity.diag(2, 4), 1)
[[1, 00, 00, 00],
 [00, 1, 00, 00]]
>> Sparsity.diag([4, 2]).nnz(), Sparsity.diag(0).nnz()
2
0

julia> ca.DM(ca.Sparsity.diag(3), 1)
DM(
[[1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
julia> ca.DM(ca.Sparsity.diag(2, 4), 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 00]])
julia> ca.nnz(ca.Sparsity.diag(4, 2)), ca.nnz(ca.Sparsity.diag(0))
(2, 0)

See also
band, is_diag, get_diag

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

Definition at line 725 of file sparsity.hpp.

725  {
726  return diag(rc.first, rc.second);
727  }

◆ diagcat()

Sparsity casadi::Sparsity::diagcat ( const std::vector< Sparsity > &  v)
static

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

Definition at line 1609 of file sparsity.cpp.

1609  {
1610  casadi_int n = 0;
1611  casadi_int m = 0;
1612 
1613  std::vector<casadi_int> colind(1, 0);
1614  std::vector<casadi_int> row;
1615 
1616  casadi_int nz = 0;
1617  for (casadi_int i=0;i<v.size();++i) {
1618  const casadi_int* colind_ = v[i].colind();
1619  casadi_int ncol = v[i].size2();
1620  const casadi_int* row_ = v[i].row();
1621  casadi_int sz = v[i].nnz();
1622  for (casadi_int k=1; k<ncol+1; ++k) {
1623  colind.push_back(colind_[k]+nz);
1624  }
1625  for (casadi_int k=0; k<sz; ++k) {
1626  row.push_back(row_[k]+m);
1627  }
1628  n+= v[i].size2();
1629  m+= v[i].size1();
1630  nz+= v[i].nnz();
1631  }
1632 
1633  return Sparsity(m, n, colind, row);
1634  }

References colind(), row(), and Sparsity().

◆ diagsplit()

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

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

Definition at line 1696 of file sparsity.cpp.

1698  {
1699  // Consistency check
1700  check_offset(offset1, x.size1(), "diagsplit");
1701  check_offset(offset2, x.size2(), "diagsplit");
1702  casadi_assert(offset1.size()==offset2.size(),
1703  "diagsplit: offset1 and offset2 must have the same length");
1704 
1705  // Number of outputs
1706  casadi_int n = offset1.size()-1;
1707 
1708  // Return value
1709  std::vector<Sparsity> ret;
1710 
1711  // Caveat: this is a very silly implementation
1712  IM x2 = IM::zeros(x);
1713 
1714  casadi_int nnz = 0;
1715  for (casadi_int i=0; i<n; ++i) {
1716  ret.push_back(x2(Slice(offset1[i], offset1[i+1]),
1717  Slice(offset2[i], offset2[i+1])).sparsity());
1718  nnz += ret.back().nnz();
1719  }
1720  casadi_assert(nnz==x.nnz(),
1721  "diagsplit: the presence of nonzeros outside the diagonal blocks is unsupported.");
1722 
1723  return ret;
1724  }
static MatType zeros(casadi_int nrow=1, casadi_int ncol=1)
Create a dense matrix or a matrix with specified sparsity with all entries zero.
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.
Matrix< casadi_int > IM
Definition: im_fwd.hpp:31

References casadi::check_offset(), nnz(), size1(), size2(), and casadi::GenericMatrix< MatType >::zeros().

◆ dim()

std::string casadi::Sparsity::dim ( bool  with_nz = false) const
Parameters
with_nzIf true, append ",<nnz>nz"

This is the string printed for a Sparsity: with the nonzero count when the pattern is not dense.

>>> sp = Sparsity.diag(2, 3)
>>> sp.dim(), sp.dim(True)
('2x3', '2x3,2nz')
>>> Sparsity.dense(2, 2).dim(), Sparsity.dense(2, 2).dim(True)
('2x2', '2x2,4nz')
>>> sp
Sparsity(2x3,2nz)

>> sp = Sparsity.diag(2, 3);
>> sp.dim(), sp.dim(true)
2x3
2x3,2nz
>> Sparsity.dense(2, 2).dim(), Sparsity.dense(2, 2).dim(true)
2x2
2x2,4nz
>> sp
2x3,2nz

julia> sp = ca.Sparsity.diag(2, 3);
julia> ca.dim(sp), ca.dim(sp, true)
("2x3", "2x3,2nz")
julia> ca.dim(ca.Sparsity.dense(2, 2)), ca.dim(ca.Sparsity.dense(2, 2), true)
("2x2", "2x2,4nz")
julia> sp
Sparsity(2x3,2nz)

See also
postfix_dim, repr_el

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

Definition at line 595 of file sparsity.cpp.

595  {
596  return (*this)->dim(with_nz);
597  }

Referenced by add(), append(), appendColumns(), bor(), casadi::Conic::Conic(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), get_nz(), casadi::Dple::init(), casadi::Nlpsol::init(), is_singular(), casadi::MXNode::join_primitives_gen(), mtimes(), casadi::mul_bvec_fwd(), mul_sparsityR(), norm_0_mul(), postfix_dim(), casadi::FunctionInternal::print_canonical(), casadi::MX::project(), scc(), and set().

◆ 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().

◆ enlarge()

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

The existing nonzeros are kept and scattered: row i of the old pattern becomes row rr[i] and column j becomes column cc[j] of the new nrow-by-ncol pattern, so that B[rr, cc] has the old pattern. The new rows and columns are structural zeros. Nonzero indices are unchanged. The object is rebound to the new pattern.

Parameters
nrowNew number of rows
ncolNew number of columns
rrNew row of every old row: length size1(), strictly increasing, entries in [0, nrow); negative entries count from the end
ccNew column of every old column: length size2(), strictly increasing, entries in [0, ncol)
ind1If true, indices are one-based

A wrong length or an index out of range raises an error.

>>> sp = Sparsity.dense(2, 2)
>>> sp.enlarge(4, 3, [0, 3], [1, 2])
>>> DM(sp, 1)
DM(
[[00, 1, 1],
 [00, 00, 00],
 [00, 00, 00],
 [00, 1, 1]])
>>> try: Sparsity.dense(2, 2).enlarge(4, 3, [0], [1, 2])
... except Exception as e: print("wrong length")
wrong length

>> sp = Sparsity.dense(2, 2);
>> sp.enlarge(4, 3, [0, 3], [1, 2]);
>> DM(sp, 1)
[[00, 1, 1],
 [00, 00, 00],
 [00, 00, 00],
 [00, 1, 1]]
>> try, Sparsity.dense(2, 2).enlarge(4, 3, 0, [1, 2]); catch e, disp('wrong length'); end
wrong length

julia> sp = ca.Sparsity.dense(2, 2);
julia> ca.enlarge(sp, 4, 3, [0, 3], [1, 2])
julia> ca.DM(sp, 1)
DM(
[[00, 1, 1],
 [00, 00, 00],
 [00, 00, 00],
 [00, 1, 1]])
julia> try
           ca.enlarge(ca.Sparsity.dense(2, 2), 4, 3, [0], [1, 2])
       catch e
           println("wrong length")
       end
wrong length

See also
enlargeRows, enlargeColumns, resize, erase

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

Definition at line 547 of file sparsity.cpp.

548  {
549  enlargeColumns(ncol, cc, ind1);
550  enlargeRows(nrow, rr, ind1);
551  }
void enlargeColumns(casadi_int ncol, const std::vector< casadi_int > &cc, bool ind1=false)
Enlarge the pattern in place by inserting empty columns.
Definition: sparsity.cpp:553
void enlargeRows(casadi_int nrow, const std::vector< casadi_int > &rr, bool ind1=false)
Enlarge the pattern in place by inserting empty rows.
Definition: sparsity.cpp:563

References enlargeColumns(), and enlargeRows().

Referenced by casadi::MX::enlarge(), and casadi::Sqpmethod::init().

◆ enlargeColumns()

void casadi::Sparsity::enlargeColumns ( casadi_int  ncol,
const std::vector< casadi_int > &  cc,
bool  ind1 = false 
)

Same as enlarge with the rows left unchanged.

Parameters
ncolNew number of columns
ccNew column of every old column, length size2(), strictly increasing
ind1If true, indices are one-based

>>> sp = Sparsity.dense(2, 2); sp.enlargeColumns(3, [0, 2]); print(DM(sp, 1))
[[1, 00, 1], 
 [1, 00, 1]]

>> sp = Sparsity.dense(2, 2); sp.enlargeColumns(3, [0, 2]); disp(DM(sp, 1))
[[1, 00, 1],
 [1, 00, 1]]

julia> sp = ca.Sparsity.dense(2, 2); ca.enlargeColumns(sp, 3, [0, 2]); ca.DM(sp, 1)
DM(
[[1, 00, 1],
 [1, 00, 1]])

See also
enlarge, enlargeRows

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

Definition at line 553 of file sparsity.cpp.

553  {
554  casadi_assert(cc.size()==size2(),
555  "Expected " + str(size2()) + " column indices, but got " + str(cc.size()) + ".");
556  if (cc.empty()) {
557  *this = Sparsity(size1(), ncol);
558  } else {
559  *this = (*this)->_enlargeColumns(ncol, cc, ind1);
560  }
561  }

References size1(), size2(), Sparsity(), and casadi::str().

Referenced by enlarge(), and casadi::FunctionInternal::from_compact().

◆ enlargeRows()

void casadi::Sparsity::enlargeRows ( casadi_int  nrow,
const std::vector< casadi_int > &  rr,
bool  ind1 = false 
)

Same as enlarge with the columns left unchanged.

Parameters
nrowNew number of rows
rrNew row of every old row, length size1(), strictly increasing
ind1If true, indices are one-based

>>> sp = Sparsity.dense(2, 2); sp.enlargeRows(3, [0, 2]); print(DM(sp, 1))
[[1, 1], 
 [00, 00], 
 [1, 1]]

>> sp = Sparsity.dense(2, 2); sp.enlargeRows(3, [0, 2]); disp(DM(sp, 1))
[[1, 1],
 [00, 00],
 [1, 1]]

julia> sp = ca.Sparsity.dense(2, 2); ca.enlargeRows(sp, 3, [0, 2]); ca.DM(sp, 1)
DM(
[[1, 1],
 [00, 00],
 [1, 1]])

See also
enlarge, enlargeColumns

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

Definition at line 563 of file sparsity.cpp.

563  {
564  casadi_assert(rr.size()==size1(),
565  "Expected " + str(size1()) + " row indices, but got " + str(rr.size()) + ".");
566  if (rr.empty()) {
567  *this = Sparsity(nrow, size2());
568  } else {
569  *this = (*this)->_enlargeRows(nrow, rr, ind1);
570  }
571  }

References size1(), size2(), Sparsity(), and casadi::str().

Referenced by enlarge(), and casadi::FunctionInternal::from_compact().

◆ erase() [1/2]

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

The shape is unchanged. Indices may be unsorted and negative; out of range raises an error. The object is rebound to the new pattern.

Parameters
rrFlat element indices, in [0, numel())
ind1If true, indices are one-based
Returns
Mapping of length nnz() of the result: nonzero k of the result was nonzero mapping[k] of the original pattern

>>> sp = Sparsity.dense(3, 3)
>>> sp.erase([0, 4, 8]), sp
([1, 2, 3, 5, 6, 7], Sparsity(3x3,6nz))
>>> DM(sp, 1)
DM(
[[00, 1, 1],
 [1, 00, 1],
 [1, 1, 00]])
>>> try: Sparsity.dense(3, 3).erase([9])
... except Exception as e: print("out of range")
out of range

>> sp = Sparsity.dense(3, 3);
>> sp.erase([0, 4, 8]), sp
1 2 3 5 6 7
3x3,6nz
>> DM(sp, 1)
[[00, 1, 1],
 [1, 00, 1],
 [1, 1, 00]]
>> try, Sparsity.dense(3, 3).erase(9); catch e, disp('out of range'); end
out of range

julia> sp = ca.Sparsity.dense(3, 3);
julia> println(ca.erase(sp, [0, 4, 8]))
[1, 2, 3, 5, 6, 7]
julia> ca.DM(sp, 1)
DM(
[[00, 1, 1],
 [1, 00, 1],
 [1, 1, 00]])
julia> try
           ca.erase(ca.Sparsity.dense(3, 3), [9])
       catch e
           println("out of range")
       end
out of range

See also
erase(rr, cc), find

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

Definition at line 348 of file sparsity.cpp.

348  {
349  std::vector<casadi_int> mapping;
350  *this = (*this)->_erase(rr, ind1, mapping);
351  return mapping;
352  }

◆ erase() [2/2]

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

The shape is unchanged: only the nonzeros in the block rr x cc are removed. An entry is removed when its row is in rr and its column is in cc, so an empty rr or cc removes nothing. Indices may be unsorted and negative (counting from the end); out of range raises an error. The object is rebound to the new pattern.

Parameters
rrRows of the block to clear
ccColumns of the block to clear
ind1If true, indices are one-based
Returns
Mapping of length nnz() of the result: nonzero k of the result was nonzero mapping[k] of the original pattern

>>> sp = Sparsity.dense(3, 3)
>>> mapping = sp.erase([0, 2], [1])
>>> DM(sp, 1), mapping
(DM(
[[1, 00, 1],
 [1, 1, 1],
 [1, 00, 1]]), [0, 1, 2, 4, 6, 7, 8])

>> sp = Sparsity.dense(3, 3);
>> mapping = sp.erase([0, 2], 1);
>> DM(sp, 1), mapping
[[1, 00, 1],
 [1, 1, 1],
 [1, 00, 1]]
0 1 2 4 6 7 8

julia> sp = ca.Sparsity.dense(3, 3);
julia> mapping = ca.erase(sp, [0, 2], [1]);
julia> println(mapping)
[0, 1, 2, 4, 6, 7, 8]
julia> ca.DM(sp, 1)
DM(
[[1, 00, 1],
 [1, 1, 1],
 [1, 00, 1]])

See also
erase(rr), sub, enlarge

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

Definition at line 341 of file sparsity.cpp.

342  {
343  std::vector<casadi_int> mapping;
344  *this = (*this)->_erase(rr, cc, ind1, mapping);
345  return mapping;
346  }

Referenced by casadi::MX::erase(), and casadi::FmuFunction::init().

◆ etree()

std::vector< casadi_int > casadi::Sparsity::etree ( bool  ata = false) const

Returns, for every column, the index of its parent in the elimination tree, or -1 for a root. See Direct Methods for Sparse Linear Systems by Davis (2006). With ata false the result matches MATLAB's etree(A) with zero-based indices (the pattern is treated as symmetric, only the upper triangular part is used); with ata true it matches etree(A, 'col'), the tree of A'*A.

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

>>> Sparsity.banded(4, 1).etree(), Sparsity.diag(4).etree()
([1, 2, 3, -1], [-1, -1, -1, -1])
>>> Sparsity.dense(2, 3).etree(True)
[1, 2, -1]

>> Sparsity.banded(4, 1).etree(), Sparsity.diag(4).etree()
1 2 3 -1
-1 -1 -1 -1
>> Sparsity.dense(2, 3).etree(true)
1 2 -1

julia> ca.etree(ca.Sparsity.banded(4, 1)), ca.etree(ca.Sparsity.diag(4))
([1, 2, 3, -1], [-1, -1, -1, -1])
julia> println(ca.etree(ca.Sparsity.dense(2, 3), true))
[1, 2, -1]

See also
ldl, qr_sparse, amd

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

Definition at line 625 of file sparsity.cpp.

625  {
626  std::vector<casadi_int> parent(size2()), w(size1() + size2());
627  SparsityInternal::etree(*this, get_ptr(parent), get_ptr(w), ata);
628  return parent;
629  }
static void etree(const casadi_int *sp, casadi_int *parent, casadi_int *w, casadi_int ata)
Calculate the elimination tree for a matrix.
T * get_ptr(std::vector< T > &v)
Get a pointer to the data contained in the vector.

References casadi::SparsityInternal::etree(), casadi::get_ptr(), size1(), and size2().

◆ export_code()

void casadi::Sparsity::export_code ( const std::string &  lang,
std::ostream &  stream = casadi::uout(),
const Dict &  options = Dict() 
) const

Only "matlab" is supported: the code defines the dimensions, one-based column and row indices and the nonzero values of a sparse matrix. The code is written to the standard output or to the given stream.

Parameters
langTarget language, must be "matlab"
optionsDictionary with
  • "name": name of the generated variable (default "sp")
  • "as_matrix": also emit "<name> = sparse(...)" (default true)
  • "nonzeros": list of strings used as the nonzero values (default: ones)
  • "indent_level": number of two-space indents (default 0)
  • "inline": not supported, true raises an error

An unknown option raises an error.

>>> Sparsity.diag(2, 3).export_code("matlab")
sp_m = 2;
sp_n = 3;
sp_j = [1, 2];
sp_i = [1, 2];
sp_v = ones(size(sp_i));
sp = sparse(sp_i, sp_j, sp_v, sp_m, sp_n);
>>> opts = {"name": "A", "as_matrix": False, "nonzeros": ["1.5", "2"]}
>>> Sparsity.diag(2).export_code("matlab", opts)
A_m = 2;
A_n = 2;
A_j = [1, 2];
A_i = [1, 2];
A_v = [1.5, 2];
>>> try: Sparsity.diag(2).export_code("python")
... except Exception as e: print("unsupported language")
unsupported language

>> Sparsity.diag(2, 3).export_code('matlab');
sp_m = 2;
sp_n = 3;
sp_j = [1, 2];
sp_i = [1, 2];
sp_v = ones(size(sp_i));
sp = sparse(sp_i, sp_j, sp_v, sp_m, sp_n);
>> opts = struct('name', 'A', 'as_matrix', false, 'nonzeros', {{'1.5', '2'}});
>> Sparsity.diag(2).export_code('matlab', opts);
A_m = 2;
A_n = 2;
A_j = [1, 2];
A_i = [1, 2];
A_v = [1.5, 2];
>> try, Sparsity.diag(2).export_code('python'); catch e, disp('unsupported language'); end
unsupported language

julia> ca.export_code(ca.Sparsity.diag(2, 3), "matlab")
sp_m = 2;
sp_n = 3;
sp_j = [1, 2];
sp_i = [1, 2];
sp_v = ones(size(sp_i));
sp = sparse(sp_i, sp_j, sp_v, sp_m, sp_n);
julia> opts = Dict("name" => "A", "as_matrix" => false, "nonzeros" => ["1.5", "2"]);
julia> ca.export_code(ca.Sparsity.diag(2), "matlab", opts)
A_m = 2;
A_n = 2;
A_j = [1, 2];
A_i = [1, 2];
A_v = [1.5, 2];
julia> try
           ca.export_code(ca.Sparsity.diag(2), "python")
       catch e
           println("unsupported language")
       end
unsupported language

See also
spy_matlab, compress

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

Definition at line 802 of file sparsity.cpp.

803  {
804  (*this)->export_code(lang, stream, options);
805  }

Referenced by casadi::XFunction< DerivedType, MatType, NodeType >::export_code(), casadi::MXFunction::export_code_body(), and casadi::Linsol::nfact().

◆ file_format()

std::string casadi::Sparsity::file_format ( const std::string &  filename,
const std::string &  format_hint,
const std::set< std::string > &  file_formats 
)
static

Definition at line 1984 of file sparsity.cpp.

1985  {
1986  if (format_hint.empty()) {
1987  std::string extension = filename.substr(filename.rfind(".")+1);
1988  auto it = file_formats.find(extension);
1989  casadi_assert(it!=file_formats.end(),
1990  "Extension '" + extension + "' not recognised. "
1991  "Valid options: " + str(file_formats) + ".");
1992  return extension;
1993  } else {
1994  auto it = file_formats.find(format_hint);
1995  casadi_assert(it!=file_formats.end(),
1996  "File format hint '" + format_hint + "' not recognised. "
1997  "Valid options: " + str(file_formats) + ".");
1998  return format_hint;
1999  }
2000 
2001  }
static std::set< std::string > file_formats
Definition: sparsity.hpp:6068
std::string filename(const std::string &path)
Definition: ghc.cpp:55

References file_formats, casadi::filename(), and casadi::str().

Referenced by from_file(), and to_file().

◆ find() [1/2]

std::vector< casadi_int > casadi::Sparsity::find ( bool  ind1 = SWIG_IND1) const

Returns, in nonzero order, the position each nonzero would have in a dense column-major matrix of the same shape: row + col*size1(). Indexing a dense matrix A of this shape with the result picks the entries that are nonzeros of the pattern. Inverse of nonzeros(). For a dense pattern this is 0, ..., numel()-1.

Parameters
ind1If true, the indices are one-based

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.find(), sp.find(True)
([0, 2, 7, 9], [1, 3, 8, 10])
>>> Sparsity.dense(2, 2).find(), Sparsity(2, 2).find(), Sparsity(0, 3).find()
([0, 1, 2, 3], [], [])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> sp.find(), sp.find(false)
1 3 8 10
0 2 7 9
>> Sparsity.dense(2, 2).find()
1 2 3 4
>> [isempty(Sparsity(2, 2).find()), isempty(Sparsity(0, 3).find())]
1 1

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.find(sp), ca.find(sp, true)
([0, 2, 7, 9], [1, 3, 8, 10])
julia> println(ca.find(ca.Sparsity.dense(2, 2)))
[0, 1, 2, 3]
julia> ca.find(ca.Sparsity(2, 2)), ca.find(ca.Sparsity(0, 3))
(Int64[], Int64[])

See also
nonzeros, get_nz, makeDense

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

Definition at line 747 of file sparsity.cpp.

747  {
748  std::vector<casadi_int> loc;
749  find(loc, ind1);
750  return loc;
751  }
std::vector< casadi_int > find(bool ind1=SWIG_IND1) const
Flat (column-major) element index of every nonzero.
Definition: sparsity.cpp:747

Referenced by casadi::GetNonzeros::ad_forward(), casadi::SetNonzeros< Add >::ad_forward(), casadi::GetNonzeros::ad_reverse(), casadi::SetNonzeros< Add >::ad_reverse(), casadi::GetNonzeros::eval_mx(), casadi::SetNonzeros< Add >::eval_mx(), casadi::Matrix< Scalar >::set(), and casadi::MX::set().

◆ find() [2/2]

void casadi::Sparsity::find ( std::vector< casadi_int > &  loc,
bool  ind1 = false 
) const

Definition at line 753 of file sparsity.cpp.

753  {
754  (*this)->find(loc, ind1);
755  }

◆ from_file()

Sparsity casadi::Sparsity::from_file ( const std::string &  filename,
const std::string &  format_hint = "" 
)
static
Parameters
filenamePath of the file to read; a missing file raises an error
format_hintFormat name, e.g. "mtx", when the extension does not tell
See also
to_file

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

Definition at line 2021 of file sparsity.cpp.

2021  {
2022  std::string format = file_format(filename, format_hint, file_formats);
2023  auto in_ptr = Filesystem::ifstream_ptr(filename);
2024  std::istream& in = *in_ptr;
2025  if (format=="mtx") {
2026  std::string line;
2027  std::vector<casadi_int> row, col;
2028  casadi_int size1, size2, nnz;
2029  int line_num = 0;
2030  while (std::getline(in, line)) {
2031  if (line_num==0) {
2032  if (!line.empty() && line.back()=='\r') line.pop_back();
2033  casadi_assert(line=="%%MatrixMarket matrix coordinate pattern general", "Wrong header");
2034  line_num = 1;
2035  } else if (line_num==1) {
2036  std::stringstream stream(line);
2037  stream >> size1;
2038  stream >> size2;
2039  stream >> nnz;
2040  row.reserve(nnz);
2041  col.reserve(nnz);
2042  line_num = 2;
2043  } else {
2044  std::stringstream stream(line);
2045  casadi_int r, c;
2046  stream >> r;
2047  stream >> c;
2048  row.push_back(r-1);
2049  col.push_back(c-1);
2050  }
2051  }
2052  return triplet(size1, size2, row, col);
2053  } else {
2054  casadi_error("Unknown format '" + format + "'");
2055  }
2056  }
static std::unique_ptr< std::istream > ifstream_ptr(const std::string &path, std::ios_base::openmode mode=std::ios_base::in, bool fail=true)
Definition: filesystem.cpp:135
static std::string file_format(const std::string &filename, const std::string &format_hint, const std::set< std::string > &file_formats)
Definition: sparsity.cpp:1984
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 file_format(), file_formats, casadi::filename(), casadi::Filesystem::ifstream_ptr(), nnz(), row(), size1(), size2(), and triplet().

◆ get()

SparsityInternal * casadi::Sparsity::get ( ) const

Definition at line 2115 of file sparsity.cpp.

2115  {
2116  return static_cast<SparsityInternal*>(SharedObject::get());
2117  }
SharedObjectInternal * get() const
Get a const pointer to the node.

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

Referenced by casadi::SparsityInternal::is_equal(), casadi::SparsityInternal::maxtrans(), and operator*().

◆ get_ccs()

void casadi::Sparsity::get_ccs ( std::vector< casadi_int > &  colind,
std::vector< casadi_int > &  row 
) const

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> colind, row = sp.get_ccs()
>>> colind, row
([0, 2, 2, 3, 4], [0, 2, 1, 0])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [colind, row] = sp.get_ccs(); disp(colind), disp(row)
0 2 2 3 4
0 2 1 0

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> colind, row = ca.get_ccs(sp);
julia> colind, row
([0, 2, 2, 3, 4], [0, 2, 1, 0])

See also
get_crs, get_triplet, get_colind, get_row

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

Definition at line 378 of file sparsity.cpp.

378  {
379  colind = get_colind();
380  row = get_row();
381  }

References colind(), get_colind(), get_row(), and row().

Referenced by get_crs().

◆ get_col()

std::vector< casadi_int > casadi::Sparsity::get_col ( ) const

◆ get_colind()

std::vector< casadi_int > casadi::Sparsity::get_colind ( ) const

Length size2()+1: entry j is the index of the first nonzero of column j and the last entry equals nnz(). In the target languages this method is called colind(), the same name as the single-column accessor.

See also
get_row, get_ccs

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

Definition at line 366 of file sparsity.cpp.

366  {
367  return (*this)->get_colind();
368  }

Referenced by add_nz(), casadi::OsqpInterface::codegen_body(), casadi::OsqpInterface::codegen_init_mem(), get_ccs(), casadi::GenericMatrix< MatType >::get_colind(), info(), casadi::FatropInterface::init(), casadi::HpipmInterface::init(), casadi::OsqpInterface::init_mem(), and casadi::SuperscsInterface::init_mem().

◆ get_crs()

void casadi::Sparsity::get_crs ( std::vector< casadi_int > &  rowind,
std::vector< casadi_int > &  col 
) const

Equivalent to the compressed column storage of the transpose. Note that the resulting order of the nonzeros (row-major) differs from the storage order of the pattern.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> rowind, col = sp.get_crs()
>>> rowind, col
([0, 2, 3, 4], [0, 3, 2, 0])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [rowind, col] = sp.get_crs(); disp(rowind), disp(col)
0 2 3 4
0 3 2 0

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> rowind, col = ca.get_crs(sp);
julia> rowind, col
([0, 2, 3, 4], [0, 3, 2, 0])

See also
get_ccs, T

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

Definition at line 383 of file sparsity.cpp.

383  {
384  T().get_ccs(rowind, col);
385  }
Sparsity T() const
Transposed pattern.
Definition: sparsity.cpp:396
void get_ccs(std::vector< casadi_int > &colind, std::vector< casadi_int > &row) const
The pattern in compressed column storage: the colind and row vectors.
Definition: sparsity.cpp:378

References get_ccs(), and T().

◆ get_diag()

Sparsity casadi::Sparsity::get_diag ( std::vector< casadi_int > &  mapping) const

If the pattern is not a vector, the result is the min(nrow, ncol)-by-1 pattern of the main diagonal: it has a nonzero for every diagonal entry (i, i) present in the pattern. If the pattern is a row or column vector of length n, the result is the n-by-n pattern with the vector entries on the diagonal.

Returns
The pattern and a mapping: mapping[k] is the nonzero index in the original pattern of nonzero k of the result

>>> sp, mapping = Sparsity.banded(3, 1).get_diag()
>>> sp, mapping
(Sparsity(3x1), [0, 3, 6])
>>> sp, mapping = Sparsity.unit(3, 1).get_diag()
>>> DM(sp, 1), mapping
(DM(
[[00, 00, 00],
 [00, 1, 00],
 [00, 00, 00]]), [0])
>>> sp, mapping = Sparsity(2, 3).get_diag()
>>> sp, mapping
(Sparsity(2x1,0nz), [])

>> [sp, mapping] = Sparsity.banded(3, 1).get_diag(); disp(sp), disp(mapping)
3x1
0 3 6
>> [sp, mapping] = Sparsity.unit(3, 1).get_diag(); disp(DM(sp, 1)), disp(mapping)
[[00, 00, 00],
 [00, 1, 00],
 [00, 00, 00]]
0
>> [sp, mapping] = Sparsity(2, 3).get_diag(); disp(sp), disp(isempty(mapping))
2x1,0nz
1

julia> ca.get_diag(ca.Sparsity.banded(3, 1))
(3x1, [0, 3, 6])
julia> ca.get_diag(ca.Sparsity.unit(3, 1))
(3x3,1nz, [0])
julia> ca.get_diag(ca.Sparsity(2, 3))
(2x1,0nz, Int64[])

See also
diag, nnz_diag

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

Definition at line 621 of file sparsity.cpp.

621  {
622  return (*this)->get_diag(mapping);
623  }

References casadi::SparsityInternal::get_diag().

Referenced by casadi::MX::diag().

◆ get_lower()

std::vector< casadi_int > casadi::Sparsity::get_lower ( ) const

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.get_lower(), sp.get_upper()
([0, 1], [0, 2, 3])
>>> Sparsity.dense(2, 2).get_lower(), Sparsity.dense(2, 2).get_upper()
([0, 1, 3], [0, 2, 3])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> sp.get_lower(), sp.get_upper()
0 1
0 2 3
>> Sparsity.dense(2, 2).get_lower(), Sparsity.dense(2, 2).get_upper()
0 1 3
0 2 3

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.get_lower(sp), ca.get_upper(sp)
([0, 1], [0, 2, 3])
julia> ca.get_lower(ca.Sparsity.dense(2, 2)), ca.get_upper(ca.Sparsity.dense(2, 2))
([0, 1, 3], [0, 2, 3])

See also
get_upper, nnz_lower, tril

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

Definition at line 1016 of file sparsity.cpp.

1016  {
1017  return (*this)->get_lower();
1018  }

◆ get_nz() [1/3]

casadi_int casadi::Sparsity::get_nz ( casadi_int  rr,
casadi_int  cc 
) const

Negative indices count from the end. An index out of bounds raises an error. For a dense pattern the result is rr + cc*size1(). The returned index addresses the nonzeros() vector of a matrix with this pattern.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.get_nz(0, 0), sp.get_nz(2, 0), sp.get_nz(1, 0), sp.get_nz(-1, 0)
(0, 1, -1, 1)
>>> try: sp.get_nz(3, 0)
... except Exception as e: print("out of bounds")
out of bounds

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [sp.get_nz(0, 0), sp.get_nz(2, 0), sp.get_nz(1, 0), sp.get_nz(-1, 0)]
0 1 -1 1
>> try, sp.get_nz(3, 0); catch e, disp('out of bounds'); end
out of bounds

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.get_nz(sp, 0, 0), ca.get_nz(sp, 2, 0), ca.get_nz(sp, 1, 0), ca.get_nz(sp, -1, 0)
(0, 1, -1, 1)
julia> try
           ca.get_nz(sp, 3, 0)
       catch e
           println("out of bounds")
       end
out of bounds

See also
has_nz, add_nz, find

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

Definition at line 248 of file sparsity.cpp.

248  {
249  return (*this)->get_nz(rr, cc);
250  }

Referenced by casadi::GetNonzeros::ad_forward(), casadi::SetNonzeros< Add >::ad_forward(), casadi::GetNonzeros::ad_reverse(), casadi::SetNonzeros< Add >::eval_mx(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), has_nz(), and casadi::MX::set().

◆ get_nz() [2/3]

std::vector< casadi_int > casadi::Sparsity::get_nz ( const std::vector< casadi_int > &  rr,
const std::vector< casadi_int > &  cc 
) const

Returns one index per (row, column) combination, in column-major order over the block (all rows of the first column first); -1 marks a structural zero. Indices must be in range (no negative indices); otherwise an error is raised.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.get_nz([0, 2], [0, 3])
[0, 1, 3, -1]

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> sp.get_nz([0, 2], [0, 3])
0 1 3 -1

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> println(ca.get_nz(sp, [0, 2], [0, 3]))
[0, 1, 3, -1]

See also
get_nz(rr, cc), sub

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

Definition at line 266 of file sparsity.cpp.

267  {
268  return (*this)->get_nz(rr, cc);
269  }

◆ get_nz() [3/3]

void casadi::Sparsity::get_nz ( std::vector< casadi_int > &  indices) const

Each entry of indices is replaced by the nonzero index of that element, or by -1 if the element is a structural zero. Entries that are already negative are left alone. The indices need not be sorted. An index of numel() or more raises an error.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.get_nz([0, 2, 4, 9, 1])
[0, 1, -1, 3, -1]
>>> Sparsity.dense(2, 2).get_nz([3, 0])
[3, 0]

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> sp.get_nz([0, 2, 4, 9, 1])
0 1 -1 3 -1
>> Sparsity.dense(2, 2).get_nz([3, 0])
3 0

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.get_nz(sp, [0, 2, 4, 9, 1])
5-element Vector{Int64}:
  0
  1
 -1
  3
 -1
julia> ca.get_nz(ca.Sparsity.dense(2, 2), [3, 0])
2-element Vector{Int64}:
 3
 0

See also
find, nonzeros

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

Definition at line 757 of file sparsity.cpp.

757  {
758  for (casadi_int k : indices) {
759  casadi_assert(k<numel(), "Index " + str(k) + " out of bounds for " + dim() + " pattern.");
760  }
761  (*this)->get_nz(indices);
762  }

References dim(), numel(), and casadi::str().

◆ get_row()

std::vector< casadi_int > casadi::Sparsity::get_row ( ) const

Length nnz(). Together with get_colind() this is the compressed column storage of the pattern; together with get_col() it is the triplet form. In the target languages this method is called row(), the same name as the single-element accessor.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> DM(sp, 1)
DM(
[[1, 00, 00, 1],
 [00, 00, 1, 00],
 [1, 00, 00, 00]])
>>> sp.row(), sp.colind(), sp.get_col()
([0, 2, 1, 0], [0, 2, 2, 3, 4], [0, 0, 2, 3])
>>> Sparsity.dense(2, 2).row(), Sparsity(2, 2).colind()
([0, 1, 0, 1], [0, 0, 0])
>>> Sparsity(0, 2).colind(), Sparsity(2, 0).colind()
([0, 0, 0], [0])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> DM(sp, 1)
[[1, 00, 00, 1],
 [00, 00, 1, 00],
 [1, 00, 00, 00]]
>> sp.row(), sp.colind(), sp.get_col()
0 2 1 0
0 2 2 3 4
0 0 2 3
>> Sparsity.dense(2, 2).row(), Sparsity(2, 2).colind()
0 1 0 1
0 0 0
>> Sparsity(0, 2).colind(), Sparsity(2, 0).colind()
0 0 0
0

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.row(sp), ca.colind(sp), ca.get_col(sp)
([0, 2, 1, 0], [0, 2, 2, 3, 4], [0, 0, 2, 3])
julia> ca.row(ca.Sparsity.dense(2, 2)), ca.colind(ca.Sparsity(2, 2))
([0, 1, 0, 1], [0, 0, 0])
julia> ca.colind(ca.Sparsity(0, 2)), ca.colind(ca.Sparsity(2, 0))
([0, 0, 0], [0])

See also
get_colind, get_col, get_ccs, get_triplet

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

Definition at line 374 of file sparsity.cpp.

374  {
375  return (*this)->get_row();
376  }

Referenced by add_nz(), casadi::OsqpInterface::codegen_init_mem(), get_ccs(), casadi::GenericMatrix< MatType >::get_row(), get_triplet(), casadi::DaeBuilderInternal::hess_sparsity(), info(), casadi::FatropInterface::init(), casadi::HpipmInterface::init(), casadi::OsqpInterface::init_mem(), casadi::SuperscsInterface::init_mem(), casadi::SparsityInternal::is_compactible(), permutation_vector(), casadi::MX::set(), casadi::KnitroInterface::solve(), to_file(), and casadi::UnoInterface::UnoInterface().

◆ 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_triplet()

void casadi::Sparsity::get_triplet ( std::vector< casadi_int > &  row,
std::vector< casadi_int > &  col 
) const

Inverse of triplet(): Sparsity.triplet(nrow, ncol, row, col) rebuilds the pattern.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> row, col = sp.get_triplet()
>>> row, col
([0, 2, 1, 0], [0, 0, 2, 3])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [row, col] = sp.get_triplet(); disp(row), disp(col)
0 2 1 0
0 0 2 3

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> row, col = ca.get_triplet(sp);
julia> row, col
([0, 2, 1, 0], [0, 0, 2, 3])

See also
triplet, get_row, get_col

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

Definition at line 387 of file sparsity.cpp.

387  {
388  row = get_row();
389  col = get_col();
390  }
std::vector< casadi_int > get_col() const
Column index of every nonzero, in nonzero (column-major) order.
Definition: sparsity.cpp:370

References get_col(), get_row(), and row().

Referenced by casadi::PiqpInterface::solve(), and casadi::ProxqpInterface::solve().

◆ get_upper()

std::vector< casadi_int > casadi::Sparsity::get_upper ( ) const
See also
get_lower, nnz_upper, triu

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

Definition at line 1020 of file sparsity.cpp.

1020  {
1021  return (*this)->get_upper();
1022  }

◆ getCache()

Sparsity::CachingMap & casadi::Sparsity::getCache ( )
static

Definition at line 527 of file sparsity.cpp.

527  {
528  static CachingMap ret;
529  return ret;
530  }
std::unordered_multimap< std::size_t, WeakRef > CachingMap
Definition: sparsity.hpp:4620

◆ 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  }

◆ getEmpty()

const Sparsity & casadi::Sparsity::getEmpty ( )
static

Definition at line 542 of file sparsity.cpp.

542  {
543  static EmptySparsity ret;
544  return ret;
545  }

◆ getScalar()

const Sparsity & casadi::Sparsity::getScalar ( )
static

Definition at line 532 of file sparsity.cpp.

532  {
533  static ScalarSparsity ret;
534  return ret;
535  }

◆ getScalarSparse()

const Sparsity & casadi::Sparsity::getScalarSparse ( )
static

Definition at line 537 of file sparsity.cpp.

537  {
538  static ScalarSparseSparsity ret;
539  return ret;
540  }

◆ has_nz()

bool casadi::Sparsity::has_nz ( casadi_int  rr,
casadi_int  cc 
) const

Same index rules as get_nz.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.has_nz(2, 0), sp.has_nz(1, 0)
(True, False)

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [sp.has_nz(2, 0), sp.has_nz(1, 0)]
1 0

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.has_nz(sp, 2, 0), ca.has_nz(sp, 1, 0)
(true, false)

See also
get_nz

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

Definition at line 243 of file sparsity.cpp.

243  {
244  return get_nz(rr, cc)!=-1;
245  }
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

References get_nz().

◆ hash()

std::size_t casadi::Sparsity::hash ( ) const

Equal patterns have equal hashes; the hash is used for the pattern cache. In Python, Sparsity objects are not hashable with the built-in hash(); use this method.

>>> sp = Sparsity.diag(2, 3)
>>> sp.hash() == Sparsity.diag(2, 3).hash(), sp.hash() == Sparsity.dense(2, 3).hash()
(True, False)

>> sp = Sparsity.diag(2, 3);
>> class(sp.hash())
uint64
>> [sp.hash() == Sparsity.diag(2, 3).hash(), sp.hash() == Sparsity.dense(2, 3).hash()]
1 0

julia> sp = ca.Sparsity.diag(2, 3);
julia> ca.hash(sp) == ca.hash(ca.Sparsity.diag(2, 3)), ca.hash(sp) == ca.hash(ca.Sparsity.dense(2, 3))
(true, false)
julia> sp == ca.Sparsity.diag(2, 3), hash(sp) == hash(ca.Sparsity.diag(2, 3))
(true, true)

See also
is_equal

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

Definition at line 824 of file sparsity.cpp.

824  {
825  return (*this)->hash();
826  }

Referenced by casadi::get_const().

◆ horzcat()

Sparsity casadi::Sparsity::horzcat ( const std::vector< Sparsity > &  sp)
static

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

Definition at line 1424 of file sparsity.cpp.

1424  {
1425  // Quick return if possible
1426  if (sp.empty()) return Sparsity(1, 0);
1427  if (sp.size()==1) return sp.front();
1428 
1429  // Count total nnz
1430  casadi_int nnz_total = 0;
1431  for (casadi_int i=0; i<sp.size(); ++i) nnz_total += sp[i].nnz();
1432 
1433  // Construct from vectors (triplet format)
1434  std::vector<casadi_int> ret_row, ret_col;
1435  ret_row.reserve(nnz_total);
1436  ret_col.reserve(nnz_total);
1437  casadi_int ret_ncol = 0;
1438  casadi_int ret_nrow = 0;
1439  for (casadi_int i=0; i<sp.size() && ret_nrow==0; ++i)
1440  ret_nrow = sp[i].size1();
1441 
1442  // Append all patterns
1443  for (std::vector<Sparsity>::const_iterator i=sp.begin(); i!=sp.end(); ++i) {
1444  // Get sparsity pattern
1445  casadi_int sp_nrow = i->size1();
1446  casadi_int sp_ncol = i->size2();
1447  const casadi_int* sp_colind = i->colind();
1448  const casadi_int* sp_row = i->row();
1449  casadi_assert(sp_nrow==ret_nrow || sp_nrow==0,
1450  "Sparsity::horzcat: Mismatching number of rows");
1451 
1452  // Add entries to pattern
1453  for (casadi_int cc=0; cc<sp_ncol; ++cc) {
1454  for (casadi_int k=sp_colind[cc]; k<sp_colind[cc+1]; ++k) {
1455  ret_row.push_back(sp_row[k]);
1456  ret_col.push_back(cc + ret_ncol);
1457  }
1458  }
1459 
1460  // Update offset
1461  ret_ncol += sp_ncol;
1462  }
1463  return Sparsity::triplet(ret_nrow, ret_ncol, ret_row, ret_col);
1464  }

References nnz(), size1(), Sparsity(), and triplet().

Referenced by blockcat().

◆ horzsplit()

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

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

Definition at line 1636 of file sparsity.cpp.

1637  {
1638  // Consistency check
1639  check_offset(offset, x.size2(), "horzsplit");
1640 
1641  // Number of outputs
1642  casadi_int n = offset.size()-1;
1643 
1644  // Get the sparsity of the input
1645  const casadi_int* colind_x = x.colind();
1646  const casadi_int* row_x = x.row();
1647 
1648  // Allocate result
1649  std::vector<Sparsity> ret;
1650  ret.reserve(n);
1651 
1652  // Sparsity pattern as CCS vectors
1653  std::vector<casadi_int> colind, row;
1654  casadi_int ncol, nrow = x.size1();
1655 
1656  // Get the sparsity patterns of the outputs
1657  for (casadi_int i=0; i<n; ++i) {
1658  casadi_int first_col = offset[i];
1659  casadi_int last_col = offset[i+1];
1660  ncol = last_col - first_col;
1661 
1662  // Construct the sparsity pattern
1663  colind.resize(ncol+1);
1664  std::copy(colind_x+first_col, colind_x+last_col+1, colind.begin());
1665  for (std::vector<casadi_int>::iterator it=colind.begin()+1; it!=colind.end(); ++it)
1666  *it -= colind[0];
1667  colind[0] = 0;
1668  row.resize(colind.back());
1669  std::copy(row_x+colind_x[first_col], row_x+colind_x[last_col], row.begin());
1670 
1671  // Append to the list
1672  ret.push_back(Sparsity(nrow, ncol, colind, row));
1673  }
1674 
1675  // Return (RVO)
1676  return ret;
1677  }

References casadi::check_offset(), colind(), casadi::SparsityInterface< Sparsity >::offset(), row(), size1(), size2(), and Sparsity().

Referenced by vertsplit().

◆ info()

Dict casadi::Sparsity::info ( ) const

An empty dictionary for a null object.

>>> Sparsity.diag(2, 3).info()
{'colind': [0, 1, 2, 2], 'ncol': 3, 'nrow': 2, 'row': [0, 1]}
>>> Sparsity().info()
{}

>> s = Sparsity.diag(2, 3).info(); disp(s)
colind: [0 1 2 2]
ncol: 3
nrow: 2
row: [0 1]
>> isempty(fieldnames(Sparsity().info()))
1

julia> ca.info(ca.Sparsity.diag(2, 3))
Dict{String, Any} with 4 entries:
  "nrow" => 2
  "colind" => [0, 1, 2, 2]
  "ncol" => 3
  "row" => [0, 1]
julia> ca.info(ca.Sparsity())
Dict{String, Any}()

See also
get_ccs, compress

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

Definition at line 1977 of file sparsity.cpp.

1977  {
1978  if (is_null()) return Dict();
1979  return {{"nrow", size1()}, {"ncol", size2()}, {"colind", get_colind()}, {"row", get_row()}};
1980  }
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.

References get_colind(), get_row(), casadi::GenericShared< SharedObject, SharedObjectInternal >::is_null(), size1(), and size2().

◆ intersect() [1/2]

Sparsity casadi::Sparsity::intersect ( const Sparsity &  y) const

The pattern of the elementwise product x * y for matrices with these patterns. A shape mismatch raises an error. In MATLAB this is the .* operator; * and mtimes give the pattern of the matrix product.

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> DM(a.intersect(b), 1)
DM(
[[00, 00],
 [00, 1]])

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> DM(a.intersect(b), 1)
[[00, 00],
 [00, 1]]

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.DM(ca.intersect(a, b), 1)
DM(
[[00, 00],
 [00, 1]])

See also
unite, combine

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

Definition at line 424 of file sparsity.cpp.

424  {
425  return (*this)->combine(y, true, true);
426  }

References casadi::SparsityInternal::combine().

◆ intersect() [2/2]

Sparsity casadi::Sparsity::intersect ( const Sparsity &  y,
std::vector< unsigned char > &  mapping 
) const

The pattern of the elementwise product x * y for matrices with these patterns. A shape mismatch raises an error. In MATLAB this is the .* operator; * and mtimes give the pattern of the matrix product.

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> DM(a.intersect(b), 1)
DM(
[[00, 00],
 [00, 1]])

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> DM(a.intersect(b), 1)
[[00, 00],
 [00, 1]]

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.DM(ca.intersect(a, b), 1)
DM(
[[00, 00],
 [00, 1]])

See also
unite, combine

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

Definition at line 419 of file sparsity.cpp.

420  {
421  return (*this)->combine(y, true, true, mapping);
422  }

References casadi::SparsityInternal::combine().

Referenced by casadi::MXNode::get_dot(), casadi::Project::get_nzref(), operator*(), and casadi::MX::project().

◆ is_column()

bool casadi::Sparsity::is_column ( ) const

>>> Sparsity.dense(3, 1).is_column(), Sparsity.dense(1, 3).is_column()
(True, False)
>>> Sparsity(1, 1).is_column()
True

>> [Sparsity.dense(3, 1).is_column(), Sparsity.dense(1, 3).is_column()]
1 0
>> Sparsity(1, 1).is_column()
1

julia> ca.is_column(ca.Sparsity.dense(3, 1)), ca.is_column(ca.Sparsity.dense(1, 3))
(true, false)
julia> ca.is_column(ca.Sparsity(1, 1))
true

See also
is_row, is_vector

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

Definition at line 287 of file sparsity.cpp.

287  {
288  return (*this)->is_column();
289  }

Referenced by append(), casadi::Rootfinder::init(), casadi::GenericMatrix< MatType >::is_column(), postfix_dim(), casadi::Matrix< Scalar >::print_default(), and casadi::Matrix< Scalar >::print_vector().

◆ is_compactible()

bool casadi::Sparsity::is_compactible ( std::vector< casadi_int > &  row,
std::vector< casadi_int > &  col 
) const

If true, returns the (sorted) row and column index sets such that nz(i, j) <-> i in row and j in col. The nonzero buffer of a compactible matrix in CCS is laid out exactly as a column-major dense row.size() x col.size() matrix, so it can be consumed by dense kernels without gather/scatter. The index sets are returned in either case (the nonempty rows and columns); a pattern without nonzeros is compactible.

>>> ok, row, col = Sparsity.rowcol([0, 2], [0, 2], 3, 3).is_compactible()
>>> ok, row, col
(True, [0, 2], [0, 2])
>>> ok, row, col = Sparsity.diag(3).is_compactible()
>>> ok, row, col
(False, [0, 1, 2], [0, 1, 2])

>> [ok, row, col] = Sparsity.rowcol([0, 2], [0, 2], 3, 3).is_compactible();
>> ok, row, col
1
0 2
0 2
>> [ok, row, col] = Sparsity.diag(3).is_compactible(); disp(ok), disp(row), disp(col)
0
0 1 2
0 1 2

julia> ca.is_compactible(ca.Sparsity.rowcol([0, 2], [0, 2], 3, 3))
(true, [0, 2], [0, 2])
julia> ca.is_compactible(ca.Sparsity.diag(3))
(false, [0, 1, 2], [0, 1, 2])

See also
rowcol

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

Definition at line 819 of file sparsity.cpp.

820  {
821  return (*this)->is_compactible(row, col);
822  }

References row().

Referenced by casadi::PseudoDenseMultiplication::try_create().

◆ is_dense()

bool casadi::Sparsity::is_dense ( ) const

An empty pattern (a zero dimension) is dense. Note that a DM built from a nested list is dense even if it holds numerical zeros.

>>> Sparsity.dense(2, 3).is_dense(), Sparsity.diag(3).is_dense()
(True, False)
>>> Sparsity(0, 3).is_dense(), Sparsity(1, 1).is_dense()
(True, False)
>>> DM([[1, 0], [0, 1]]).sparsity().is_dense()
True

>> [Sparsity.dense(2, 3).is_dense(), Sparsity.diag(3).is_dense()]
1 0
>> [Sparsity(0, 3).is_dense(), Sparsity(1, 1).is_dense()]
1 0
>> sparsity(DM([1, 0; 0, 1])).is_dense()
1

julia> ca.is_dense(ca.Sparsity.dense(2, 3)), ca.is_dense(ca.Sparsity.diag(3))
(true, false)
julia> ca.is_dense(ca.Sparsity(0, 3)), ca.is_dense(ca.Sparsity(1, 1))
(true, false)
julia> ca.is_dense(ca.sparsity(ca.DM([1 0; 0 1])))
true

See also
dense, density, makeDense

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

Definition at line 275 of file sparsity.cpp.

275  {
276  return (*this)->is_dense();
277  }

Referenced by casadi::SparsityInternal::_mtimes(), add_nz(), compress(), casadi::AlpaqaProblem::eval_hess_L(), casadi::AlpaqaProblem::eval_hess_ψ(), casadi::AlpaqaProblem::eval_jac_g(), casadi::XFunction< DerivedType, MatType, NodeType >::export_code(), casadi::AlpaqaProblem::get_hess_L_num_nonzeros(), casadi::AlpaqaProblem::get_hess_ψ_num_nonzeros(), casadi::AlpaqaProblem::get_jac_g_num_nonzeros(), casadi::MXNode::get_project(), casadi::Constant< Value >::get_project(), casadi::Integrator::init(), casadi::Rootfinder::init(), casadi::GenericMatrix< MatType >::is_dense(), casadi::Function::jac_sparsity(), kron(), casadi::Onnx::load(), casadi::Integrator::map2oracle(), postfix_dim(), casadi::FunctionInternal::print_canonical(), and casadi::Scpgen::regularize().

◆ is_diag()

bool casadi::Sparsity::is_diag ( ) const

True only for Sparsity.diag(n) (including n == 0); a rectangular diagonal pattern, an all-zero square pattern or a pattern with off-diagonal entries is not diagonal.

>>> Sparsity.diag(3).is_diag(), Sparsity.diag(2, 3).is_diag()
(True, False)
>>> Sparsity.dense(1, 1).is_diag(), Sparsity(2, 2).is_diag()
(True, False)
>>> Sparsity(0, 0).is_diag(), Sparsity.dense(2, 2).is_diag()
(True, False)

>> [Sparsity.diag(3).is_diag(), Sparsity.diag(2, 3).is_diag()]
1 0
>> [Sparsity.dense(1, 1).is_diag(), Sparsity(2, 2).is_diag()]
1 0
>> [Sparsity(0, 0).is_diag(), Sparsity.dense(2, 2).is_diag()]
1 0

julia> ca.is_diag(ca.Sparsity.diag(3)), ca.is_diag(ca.Sparsity.diag(2, 3))
(true, false)
julia> ca.is_diag(ca.Sparsity.dense(1, 1)), ca.is_diag(ca.Sparsity(2, 2))
(true, false)
julia> ca.is_diag(ca.Sparsity(0, 0)), ca.is_diag(ca.Sparsity.dense(2, 2))
(true, false)

See also
diag, nnz_diag

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

Definition at line 279 of file sparsity.cpp.

279  {
280  return (*this)->is_diag();
281  }

Referenced by casadi::SparsityInternal::_mtimes().

◆ is_empty()

bool casadi::Sparsity::is_empty ( bool  both = false) const
Parameters
bothIf false (default), true when the number of rows or the number of columns is zero; if true, only when both are zero

A pattern without nonzeros but with positive dimensions is not empty.

>>> Sparsity(0, 3).is_empty(), Sparsity(0, 3).is_empty(True)
(True, False)
>>> Sparsity(0, 0).is_empty(True)
True
>>> Sparsity(3, 3).is_empty(), Sparsity(3, 3).nnz()
(False, 0)

>> Sparsity(0, 3).is_empty(), Sparsity(0, 3).is_empty(true)
1
0
>> Sparsity(0, 0).is_empty(true)
1
>> Sparsity(3, 3).is_empty(), Sparsity(3, 3).nnz()
0
0

julia> ca.is_empty(ca.Sparsity(0, 3)), ca.is_empty(ca.Sparsity(0, 3), true)
(true, false)
julia> ca.is_empty(ca.Sparsity(0, 0), true)
true
julia> ca.is_empty(ca.Sparsity(3, 3)), ca.nnz(ca.Sparsity(3, 3))
(false, 0)

See also
numel, nnz

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

Definition at line 146 of file sparsity.cpp.

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

Referenced by casadi::SparsityInternal::_mtimes(), add(), bor(), casadi::FunctionInternal::check_mat(), casadi::ConstantMX::create(), casadi::MXNode::get_mmax(), casadi::MXNode::get_mmin(), casadi::ZeroByZero::get_reshape(), casadi::Integrator::init(), casadi::Nlpsol::init(), casadi::GenericMatrix< MatType >::is_empty(), casadi::Integrator::map2oracle(), postfix_dim(), casadi::Matrix< Scalar >::print_default(), casadi::Call::projectArg(), and set().

◆ is_equal() [1/3]

bool casadi::Sparsity::is_equal ( casadi_int  nrow,
casadi_int  ncol,
const casadi_int *  colind,
const casadi_int *  row 
) const

True when the dimensions and the nonzero positions coincide. This is the comparison behind the == operator. Shared (cached) patterns are detected in constant time; otherwise colind and row are compared. The second overload compares against a pattern given in compressed column storage vectors.

>>> a = Sparsity.diag(2)
>>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2), a != Sparsity.dense(2, 2)
(True, True, True)
>>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
True
>>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
False
>>> Sparsity(2, 2) == Sparsity.dense(2, 2)
False

>> a = Sparsity.diag(2);
>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2)
1
1
>> a ~= Sparsity.dense(2, 2)
1
>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
1
>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
0
>> Sparsity(2, 2) == Sparsity.dense(2, 2)
0

julia> a = ca.Sparsity.diag(2);
julia> ca.is_equal(a, ca.Sparsity.diag(2)), !ca.is_equal(a, ca.Sparsity.dense(2, 2))
(true, true)
julia> ca.is_equal(a, 2, 2, [0, 1, 2], [0, 1])
true
julia> ca.is_equal(ca.Sparsity.dense(2, 2), ca.Sparsity.dense(2, 3))
false
julia> ca.is_equal(ca.Sparsity(2, 2), ca.Sparsity.dense(2, 2))
false

See also
is_subset, is_transpose, is_reshape, hash

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

Definition at line 455 of file sparsity.cpp.

456  {
457  return (*this)->is_equal(nrow, ncol, colind, row);
458  }

References colind(), and row().

◆ is_equal() [2/3]

bool casadi::Sparsity::is_equal ( casadi_int  nrow,
casadi_int  ncol,
const std::vector< casadi_int > &  colind,
const std::vector< casadi_int > &  row 
) const

True when the dimensions and the nonzero positions coincide. This is the comparison behind the == operator. Shared (cached) patterns are detected in constant time; otherwise colind and row are compared. The second overload compares against a pattern given in compressed column storage vectors.

>>> a = Sparsity.diag(2)
>>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2), a != Sparsity.dense(2, 2)
(True, True, True)
>>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
True
>>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
False
>>> Sparsity(2, 2) == Sparsity.dense(2, 2)
False

>> a = Sparsity.diag(2);
>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2)
1
1
>> a ~= Sparsity.dense(2, 2)
1
>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
1
>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
0
>> Sparsity(2, 2) == Sparsity.dense(2, 2)
0

julia> a = ca.Sparsity.diag(2);
julia> ca.is_equal(a, ca.Sparsity.diag(2)), !ca.is_equal(a, ca.Sparsity.dense(2, 2))
(true, true)
julia> ca.is_equal(a, 2, 2, [0, 1, 2], [0, 1])
true
julia> ca.is_equal(ca.Sparsity.dense(2, 2), ca.Sparsity.dense(2, 3))
false
julia> ca.is_equal(ca.Sparsity(2, 2), ca.Sparsity.dense(2, 2))
false

See also
is_subset, is_transpose, is_reshape, hash

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

Definition at line 450 of file sparsity.cpp.

451  {
452  return (*this)->is_equal(nrow, ncol, colind, row);
453  }

References colind(), and row().

◆ is_equal() [3/3]

bool casadi::Sparsity::is_equal ( const Sparsity &  y) const

True when the dimensions and the nonzero positions coincide. This is the comparison behind the == operator. Shared (cached) patterns are detected in constant time; otherwise colind and row are compared. The second overload compares against a pattern given in compressed column storage vectors.

>>> a = Sparsity.diag(2)
>>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2), a != Sparsity.dense(2, 2)
(True, True, True)
>>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
True
>>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
False
>>> Sparsity(2, 2) == Sparsity.dense(2, 2)
False

>> a = Sparsity.diag(2);
>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2)
1
1
>> a ~= Sparsity.dense(2, 2)
1
>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
1
>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
0
>> Sparsity(2, 2) == Sparsity.dense(2, 2)
0

julia> a = ca.Sparsity.diag(2);
julia> ca.is_equal(a, ca.Sparsity.diag(2)), !ca.is_equal(a, ca.Sparsity.dense(2, 2))
(true, true)
julia> ca.is_equal(a, 2, 2, [0, 1, 2], [0, 1])
true
julia> ca.is_equal(ca.Sparsity.dense(2, 2), ca.Sparsity.dense(2, 3))
false
julia> ca.is_equal(ca.Sparsity(2, 2), ca.Sparsity.dense(2, 2))
false

See also
is_subset, is_transpose, is_reshape, hash

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

Definition at line 446 of file sparsity.cpp.

446  {
447  return (*this)->is_equal(y);
448  }

◆ is_null()

Definition at line 116 of file generic_shared_impl.hpp.

120  {
121  return node==nullptr;
122  }

◆ is_orthonormal()

bool casadi::Sparsity::is_orthonormal ( bool  allow_empty = false) const

Without allow_empty the pattern must also be square with exactly one nonzero per row and column (a permutation pattern). With allow_empty, rows and columns without nonzeros are disregarded and the shape may be rectangular.

Parameters
allow_emptyDisregard empty rows and columns in the analysis

>>> Sparsity.diag(3).is_orthonormal()
True
>>> Sparsity.triplet(3, 3, [0, 1], [0, 1]).is_orthonormal()
False
>>> Sparsity.triplet(3, 3, [0, 1], [0, 1]).is_orthonormal(True)
True
>>> Sparsity.triplet(3, 3, [0, 0], [0, 1]).is_orthonormal(True)
False
>>> Sparsity.diag(2, 3).is_orthonormal(), Sparsity.diag(2, 3).is_orthonormal(True)
(False, True)

>> Sparsity.diag(3).is_orthonormal()
1
>> Sparsity.triplet(3, 3, [0, 1], [0, 1]).is_orthonormal()
0
>> Sparsity.triplet(3, 3, [0, 1], [0, 1]).is_orthonormal(true)
1
>> Sparsity.triplet(3, 3, [0, 0], [0, 1]).is_orthonormal(true)
0
>> [Sparsity.diag(2, 3).is_orthonormal(), Sparsity.diag(2, 3).is_orthonormal(true)]
0 1

julia> ca.is_orthonormal(ca.Sparsity.diag(3))
true
julia> ca.is_orthonormal(ca.Sparsity.triplet(3, 3, [0, 1], [0, 1]))
false
julia> ca.is_orthonormal(ca.Sparsity.triplet(3, 3, [0, 1], [0, 1]), true)
true
julia> ca.is_orthonormal(ca.Sparsity.triplet(3, 3, [0, 0], [0, 1]), true)
false
julia> sp = ca.Sparsity.diag(2, 3);
julia> ca.is_orthonormal(sp), ca.is_orthonormal(sp, true)
(false, true)

See also
is_orthonormal_rows, is_orthonormal_columns, is_permutation

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

Definition at line 307 of file sparsity.cpp.

307  {
308  return (*this)->is_orthonormal(allow_empty);
309  }

Referenced by casadi::MX::solve().

◆ is_orthonormal_columns()

bool casadi::Sparsity::is_orthonormal_columns ( bool  allow_empty = false) const

Without allow_empty the pattern must have at most as many columns as rows and exactly one nonzero per column. With allow_empty, columns without nonzeros are disregarded.

Parameters
allow_emptyDisregard empty columns in the analysis
See also
is_orthonormal_rows, is_orthonormal

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

Definition at line 315 of file sparsity.cpp.

315  {
316  return (*this)->is_orthonormal_columns(allow_empty);
317  }

◆ is_orthonormal_rows()

bool casadi::Sparsity::is_orthonormal_rows ( bool  allow_empty = false) const

Without allow_empty the pattern must have at most as many rows as columns and exactly one nonzero per row. With allow_empty, rows without nonzeros are disregarded.

Parameters
allow_emptyDisregard empty rows in the analysis

>>> sp = Sparsity.diag(2, 3)
>>> sp.is_orthonormal_rows(), sp.is_orthonormal_columns()
(True, False)
>>> sp.T.is_orthonormal_rows(), sp.T.is_orthonormal_columns()
(False, True)

>> sp = Sparsity.diag(2, 3);
>> [sp.is_orthonormal_rows(), sp.is_orthonormal_columns()]
1 0
>> [sp.T.is_orthonormal_rows(), sp.T.is_orthonormal_columns()]
0 1

julia> sp = ca.Sparsity.diag(2, 3);
julia> ca.is_orthonormal_rows(sp), ca.is_orthonormal_columns(sp)
(true, false)
julia> ca.is_orthonormal_rows(ca.T(sp)), ca.is_orthonormal_columns(ca.T(sp))
(false, true)

See also
is_orthonormal_columns, is_selection

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

Definition at line 311 of file sparsity.cpp.

311  {
312  return (*this)->is_orthonormal_rows(allow_empty);
313  }

◆ is_permutation()

bool casadi::Sparsity::is_permutation ( ) const

A square pattern with exactly one nonzero in every row and every column, so that multiplying a dense vector permutes its entries. Equivalent to is_orthonormal().

>>> Sparsity.permutation([1, 2, 0]).is_permutation()
True
>>> Sparsity.diag(3).is_permutation()
True
>>> Sparsity.dense(2, 2).is_permutation(), Sparsity.diag(2, 3).is_permutation()
(False, False)

>> Sparsity.permutation([1, 2, 0]).is_permutation()
1
>> Sparsity.diag(3).is_permutation()
1
>> [Sparsity.dense(2, 2).is_permutation(), Sparsity.diag(2, 3).is_permutation()]
0 0

julia> ca.is_permutation(ca.Sparsity.permutation([1, 2, 0]))
true
julia> ca.is_permutation(ca.Sparsity.diag(3))
true
julia> ca.is_permutation(ca.Sparsity.dense(2, 2)), ca.is_permutation(ca.Sparsity.diag(2, 3))
(false, false)

See also
permutation, permutation_vector, is_selection, is_orthonormal

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

Definition at line 299 of file sparsity.cpp.

299  {
300  return (*this)->is_permutation();
301  }

Referenced by permutation_vector().

◆ is_reshape()

bool casadi::Sparsity::is_reshape ( const Sparsity &  y) const

True when both have the same number of elements and the same flat (column-major) nonzero positions, i.e. reshape(A, y.size()) has pattern y.

>>> Sparsity.dense(2, 3).is_reshape(Sparsity.dense(6, 1))
True
>>> Sparsity.diag(2).is_reshape(Sparsity.nonzeros(4, 1, [0, 3]))
True
>>> Sparsity.diag(2).is_reshape(Sparsity.nonzeros(4, 1, [0, 2]))
False

>> Sparsity.dense(2, 3).is_reshape(Sparsity.dense(6, 1))
1
>> Sparsity.diag(2).is_reshape(Sparsity.nonzeros(4, 1, [1, 4]))
1
>> Sparsity.diag(2).is_reshape(Sparsity.nonzeros(4, 1, [1, 3]))
0

julia> ca.is_reshape(ca.Sparsity.dense(2, 3), ca.Sparsity.dense(6, 1))
true
julia> ca.is_reshape(ca.Sparsity.diag(2), ca.Sparsity.nonzeros(4, 1, [0, 3]))
true
julia> ca.is_reshape(ca.Sparsity.diag(2), ca.Sparsity.nonzeros(4, 1, [0, 2]))
false

See also
reshape, find

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

Definition at line 815 of file sparsity.cpp.

815  {
816  return (*this)->is_reshape(*y);
817  }

Referenced by casadi::MXNode::get_reshape(), casadi::SparsityCast::get_reshape(), casadi::MX::MX(), casadi::MX::reshape(), and reshape().

◆ is_row()

bool casadi::Sparsity::is_row ( ) const

The number of columns (including zero) and the nonzeros play no role.

>>> Sparsity.dense(1, 3).is_row(), Sparsity.dense(3, 1).is_row()
(True, False)
>>> Sparsity(1, 0).is_row()
True

>> [Sparsity.dense(1, 3).is_row(), Sparsity.dense(3, 1).is_row()]
1 0
>> Sparsity(1, 0).is_row()
1

julia> ca.is_row(ca.Sparsity.dense(1, 3)), ca.is_row(ca.Sparsity.dense(3, 1))
(true, false)
julia> ca.is_row(ca.Sparsity(1, 0))
true

See also
is_column, is_vector

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

Definition at line 283 of file sparsity.cpp.

283  {
284  return (*this)->is_row();
285  }

Referenced by casadi::GenericMatrix< MatType >::is_row().

◆ is_scalar()

bool casadi::Sparsity::is_scalar ( bool  scalar_and_dense = false) const
Parameters
scalar_and_denseIf true, additionally require the single entry to be a nonzero (a 1-by-1 pattern with zero nonzeros is a structural zero)

>>> Sparsity.dense(1, 1).is_scalar(), Sparsity(1, 1).is_scalar()
(True, True)
>>> Sparsity(1, 1).is_scalar(True), Sparsity.dense(2, 1).is_scalar()
(False, False)

>> [Sparsity.dense(1, 1).is_scalar(), Sparsity(1, 1).is_scalar()]
1 1
>> [Sparsity(1, 1).is_scalar(true), Sparsity.dense(2, 1).is_scalar()]
0 0

julia> ca.is_scalar(ca.Sparsity.dense(1, 1)), ca.is_scalar(ca.Sparsity(1, 1))
(true, true)
julia> ca.is_scalar(ca.Sparsity(1, 1), true), ca.is_scalar(ca.Sparsity.dense(2, 1))
(false, false)

See also
scalar, is_dense

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

Definition at line 271 of file sparsity.cpp.

271  {
272  return (*this)->is_scalar(scalar_and_dense);
273  }

Referenced by casadi::SparsityInternal::_mtimes(), casadi::Matrix< Scalar >::_sym(), casadi::FunctionInternal::check_mat(), casadi::Integrator::init(), casadi::Integrator::map2oracle(), postfix_dim(), and casadi::FunctionInternal::print_canonical().

◆ is_selection()

bool casadi::Sparsity::is_selection ( bool  allow_empty = false) const

A selection matrix S picks a subset of the entries of a dense vector: S @ v is a vector of distinct entries of v. The pattern has at most one nonzero per column and exactly one per row. Equivalent to is_orthonormal_rows(allow_empty).

Parameters
allow_emptyIf true, rows without nonzeros are allowed (the result may contain structural zeros)

>>> S = Sparsity.triplet(2, 3, [0, 1], [2, 0])
>>> DM(S, 1) @ DM([10, 20, 30])
DM([30, 10])
>>> S.is_selection(), Sparsity.triplet(2, 3, [0], [2]).is_selection()
(True, False)
>>> Sparsity.triplet(2, 3, [0], [2]).is_selection(True)
True
>>> Sparsity.diag(3, 2).is_selection()
False

>> S = Sparsity.triplet(2, 3, [0, 1], [2, 0]);
>> DM(S, 1) * DM([10; 20; 30])
[30, 10]
>> [S.is_selection(), Sparsity.triplet(2, 3, 0, 2).is_selection()]
1 0
>> Sparsity.triplet(2, 3, 0, 2).is_selection(true)
1
>> Sparsity.diag(3, 2).is_selection()
0

julia> S = ca.Sparsity.triplet(2, 3, [0, 1], [2, 0]);
julia> ca.DM(S, 1) * ca.DM([10, 20, 30])
DM([30, 10])
julia> ca.is_selection(S), ca.is_selection(ca.Sparsity.triplet(2, 3, [0], [2]))
(true, false)
julia> ca.is_selection(ca.Sparsity.triplet(2, 3, [0], [2]), true)
true
julia> ca.is_selection(ca.Sparsity.diag(3, 2))
false

See also
is_permutation, is_orthonormal_rows

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

Definition at line 303 of file sparsity.cpp.

303  {
304  return (*this)->is_selection(allow_empty);
305  }

◆ is_singular()

bool casadi::Sparsity::is_singular ( ) const

True when the structural rank (sprank) is smaller than the size, i.e. no choice of nonzero values can make a matrix with this pattern invertible. A non-square pattern raises an error.

>>> Sparsity.diag(3).is_singular(), Sparsity(3, 3).is_singular()
(False, True)
>>> Sparsity.nonzeros(3, 3, [0, 1, 2]).is_singular(), Sparsity(0, 0).is_singular()
(True, False)
>>> try: Sparsity.dense(2, 3).is_singular()
... except Exception as e: print("not square")
not square

>> [Sparsity.diag(3).is_singular(), Sparsity(3, 3).is_singular()]
0 1
>> [Sparsity.nonzeros(3, 3, [1, 2, 3]).is_singular(), Sparsity(0, 0).is_singular()]
1 0
>> try, Sparsity.dense(2, 3).is_singular(); catch e, disp('not square'); end
not square

julia> ca.is_singular(ca.Sparsity.diag(3)), ca.is_singular(ca.Sparsity(3, 3))
(false, true)
julia> ca.is_singular(ca.Sparsity.nonzeros(3, 3, [0, 1, 2]))
true
julia> ca.is_singular(ca.Sparsity(0, 0))
false
julia> try
           ca.is_singular(ca.Sparsity.dense(2, 3))
       catch e
           println("not square")
       end
not square

See also
sprank, btf

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

Definition at line 1329 of file sparsity.cpp.

1329  {
1330  casadi_assert(is_square(),
1331  "is_singular: only defined for square matrices, but got " + dim());
1332  return sprank(*this)!=size2();
1333  }
static casadi_int sprank(const Sparsity &x)
Accessed by SparsityInterface.
Definition: sparsity.cpp:1734
bool is_square() const
Check whether the number of rows equals the number of columns.
Definition: sparsity.cpp:295

References dim(), is_square(), size2(), and sprank().

Referenced by casadi::Integrator::init(), casadi::Rootfinder::init(), and casadi::CsparseInterface::nfact().

◆ is_square()

bool casadi::Sparsity::is_square ( ) const

>>> Sparsity.dense(2, 2).is_square(), Sparsity.dense(2, 3).is_square()
(True, False)
>>> Sparsity(0, 0).is_square()
True

>> [Sparsity.dense(2, 2).is_square(), Sparsity.dense(2, 3).is_square()]
1 0
>> Sparsity(0, 0).is_square()
1

julia> ca.is_square(ca.Sparsity.dense(2, 2)), ca.is_square(ca.Sparsity.dense(2, 3))
(true, false)
julia> ca.is_square(ca.Sparsity(0, 0))
true

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

Definition at line 295 of file sparsity.cpp.

295  {
296  return (*this)->is_square();
297  }

Referenced by casadi::Expm::Expm(), is_singular(), casadi::GenericMatrix< MatType >::is_square(), kkt(), scc(), and casadi::Convexify::setup().

◆ is_stacked()

bool casadi::Sparsity::is_stacked ( const Sparsity &  y,
casadi_int  n 
) const

True when this pattern equals horzcat(y, ..., y) with n repetitions, i.e. the pattern of repmat(y, 1, n). The patterns are compared structurally, so a dense pattern of the right shape does not count as a stack of a sparse one.

>>> sp = horzcat(Sparsity.diag(2), Sparsity.diag(2), Sparsity.diag(2))
>>> sp.is_stacked(Sparsity.diag(2), 3), sp.is_stacked(Sparsity.diag(2), 2)
(True, False)
>>> Sparsity.dense(2, 6).is_stacked(Sparsity.diag(2), 3)
False

>> sp = [Sparsity.diag(2), Sparsity.diag(2), Sparsity.diag(2)];
>> sp.is_stacked(Sparsity.diag(2), 3), sp.is_stacked(Sparsity.diag(2), 2)
1
0
>> Sparsity.dense(2, 6).is_stacked(Sparsity.diag(2), 3)
0

julia> sp = ca.repmat(ca.Sparsity.diag(2), 1, 3)
Sparsity(2x6,6nz)
julia> ca.is_stacked(sp, ca.Sparsity.diag(2), 3), ca.is_stacked(sp, ca.Sparsity.diag(2), 2)
(true, false)
julia> ca.is_stacked(ca.Sparsity.dense(2, 6), ca.Sparsity.diag(2), 3)
false

See also
is_equal, horzcat

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

Definition at line 442 of file sparsity.cpp.

442  {
443  return (*this)->is_stacked(y, n);
444  }

◆ is_subset()

bool casadi::Sparsity::is_subset ( const Sparsity &  rhs) const

Both patterns must have the same shape, otherwise an error is raised. A pattern is a subset of itself and an all-zero pattern is a subset of any pattern of its shape.

>>> Sparsity.diag(3).is_subset(Sparsity.dense(3, 3))
True
>>> Sparsity.dense(3, 3).is_subset(Sparsity.diag(3))
False
>>> Sparsity(3, 3).is_subset(Sparsity.diag(3))
True
>>> Sparsity.diag(3).is_subset(Sparsity.diag(3))
True

>> Sparsity.diag(3).is_subset(Sparsity.dense(3, 3))
1
>> Sparsity.dense(3, 3).is_subset(Sparsity.diag(3))
0
>> Sparsity(3, 3).is_subset(Sparsity.diag(3))
1
>> Sparsity.diag(3).is_subset(Sparsity.diag(3))
1

julia> ca.is_subset(ca.Sparsity.diag(3), ca.Sparsity.dense(3, 3))
true
julia> ca.is_subset(ca.Sparsity.dense(3, 3), ca.Sparsity.diag(3))
false
julia> ca.is_subset(ca.Sparsity(3, 3), ca.Sparsity.diag(3))
true
julia> ca.is_subset(ca.Sparsity.diag(3), ca.Sparsity.diag(3))
true

See also
unite, intersect, is_equal

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

Definition at line 428 of file sparsity.cpp.

428  {
429  return (*this)->is_subset(rhs);
430  }

Referenced by casadi::SparsityCast::ad_reverse(), and casadi::Project::get_project().

◆ is_symmetric()

bool casadi::Sparsity::is_symmetric ( ) const

Structural symmetry only: (i, j) is a nonzero if and only if (j, i) is. Required by amd, ldl and the star colorings. A rectangular pattern is never symmetric.

>>> Sparsity.banded(3, 1).is_symmetric(), Sparsity.upper(3).is_symmetric()
(True, False)
>>> Sparsity(3, 3).is_symmetric(), Sparsity.dense(2, 3).is_symmetric()
(True, False)

>> [Sparsity.banded(3, 1).is_symmetric(), Sparsity.upper(3).is_symmetric()]
1 0
>> [Sparsity(3, 3).is_symmetric(), Sparsity.dense(2, 3).is_symmetric()]
1 0

julia> ca.is_symmetric(ca.Sparsity.banded(3, 1)), ca.is_symmetric(ca.Sparsity.upper(3))
(true, false)
julia> ca.is_symmetric(ca.Sparsity(3, 3)), ca.is_symmetric(ca.Sparsity.dense(2, 3))
(true, false)

See also
is_transpose, T

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

Definition at line 319 of file sparsity.cpp.

319  {
320  return (*this)->is_symmetric();
321  }

Referenced by casadi::Conic::Conic(), casadi::Dple::init(), casadi::FatropInterface::init(), casadi::Feasiblesqpmethod::init(), casadi::Sqpmethod::init(), casadi::FunctionInternal::jac_sparsity(), ldl(), and casadi::Convexify::setup().

◆ is_transpose()

bool casadi::Sparsity::is_transpose ( const Sparsity &  y) const

>>> Sparsity.band(3, 1).is_transpose(Sparsity.band(3, -1))
True
>>> Sparsity.band(3, 1).is_transpose(Sparsity.band(3, 1))
False
>>> Sparsity.dense(2, 3).is_transpose(Sparsity.dense(3, 2))
True

>> Sparsity.band(3, 1).is_transpose(Sparsity.band(3, -1))
1
>> Sparsity.band(3, 1).is_transpose(Sparsity.band(3, 1))
0
>> Sparsity.dense(2, 3).is_transpose(Sparsity.dense(3, 2))
1

julia> ca.is_transpose(ca.Sparsity.band(3, 1), ca.Sparsity.band(3, -1))
true
julia> ca.is_transpose(ca.Sparsity.band(3, 1), ca.Sparsity.band(3, 1))
false
julia> ca.is_transpose(ca.Sparsity.dense(2, 3), ca.Sparsity.dense(3, 2))
true

See also
T, is_symmetric

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

Definition at line 811 of file sparsity.cpp.

811  {
812  return (*this)->is_transpose(*y);
813  }

◆ is_tril()

bool casadi::Sparsity::is_tril ( bool  strictly = false) const
Parameters
strictlyIf true, require row > col (no diagonal entries)

>>> Sparsity.lower(3).is_tril(), Sparsity.lower(3).is_tril(True)
(True, False)
>>> Sparsity.band(3, 1).is_tril(True), Sparsity.diag(3).is_tril()
(True, True)
>>> Sparsity.dense(3, 1).is_tril(), Sparsity.dense(1, 3).is_tril()
(True, False)

>> [Sparsity.lower(3).is_tril(), Sparsity.lower(3).is_tril(true)]
1 0
>> [Sparsity.band(3, 1).is_tril(true), Sparsity.diag(3).is_tril()]
1 1
>> [Sparsity.dense(3, 1).is_tril(), Sparsity.dense(1, 3).is_tril()]
1 0

julia> ca.is_tril(ca.Sparsity.lower(3)), ca.is_tril(ca.Sparsity.lower(3), true)
(true, false)
julia> ca.is_tril(ca.Sparsity.band(3, 1), true), ca.is_tril(ca.Sparsity.diag(3))
(true, true)
julia> ca.is_tril(ca.Sparsity.dense(3, 1)), ca.is_tril(ca.Sparsity.dense(1, 3))
(true, false)

See also
is_triu, lower, tril, nnz_lower

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

Definition at line 323 of file sparsity.cpp.

323  {
324  return (*this)->is_tril(strictly);
325  }

Referenced by casadi::MadmpecInterface::init(), casadi::MadnlpInterface::init(), casadi::GenericMatrix< MatType >::is_tril(), and casadi::Convexify::setup().

◆ is_triu()

bool casadi::Sparsity::is_triu ( bool  strictly = false) const
Parameters
strictlyIf true, require row < col (no diagonal entries)

Defined for any shape; a pattern without nonzeros is upper triangular.

>>> Sparsity.upper(3).is_triu(), Sparsity.upper(3).is_triu(True)
(True, False)
>>> Sparsity.band(3, -1).is_triu(True), Sparsity(3, 3).is_triu()
(True, True)
>>> Sparsity.dense(1, 3).is_triu(), Sparsity.dense(3, 1).is_triu()
(True, False)

>> [Sparsity.upper(3).is_triu(), Sparsity.upper(3).is_triu(true)]
1 0
>> [Sparsity.band(3, -1).is_triu(true), Sparsity(3, 3).is_triu()]
1 1
>> [Sparsity.dense(1, 3).is_triu(), Sparsity.dense(3, 1).is_triu()]
1 0

julia> ca.is_triu(ca.Sparsity.upper(3)), ca.is_triu(ca.Sparsity.upper(3), true)
(true, false)
julia> ca.is_triu(ca.Sparsity.band(3, -1), true), ca.is_triu(ca.Sparsity(3, 3))
(true, true)
julia> ca.is_triu(ca.Sparsity.dense(1, 3)), ca.is_triu(ca.Sparsity.dense(3, 1))
(true, false)

See also
is_tril, upper, triu, nnz_upper

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

Definition at line 327 of file sparsity.cpp.

327  {
328  return (*this)->is_triu(strictly);
329  }

Referenced by casadi::IpoptInterface::init(), casadi::GenericMatrix< MatType >::is_triu(), and casadi::Convexify::setup().

◆ is_vector()

bool casadi::Sparsity::is_vector ( ) const

A 1-by-1 pattern is a vector; a 0-by-3 pattern is not.

>>> Sparsity.dense(3, 1).is_vector(), Sparsity.dense(1, 3).is_vector()
(True, True)
>>> Sparsity.dense(1, 1).is_vector(), Sparsity.dense(2, 2).is_vector()
(True, False)
>>> Sparsity(0, 3).is_vector()
False

>> [Sparsity.dense(3, 1).is_vector(), Sparsity.dense(1, 3).is_vector()]
1 1
>> [Sparsity.dense(1, 1).is_vector(), Sparsity.dense(2, 2).is_vector()]
1 0
>> Sparsity(0, 3).is_vector()
0

julia> ca.is_vector(ca.Sparsity.dense(3, 1)), ca.is_vector(ca.Sparsity.dense(1, 3))
(true, true)
julia> ca.is_vector(ca.Sparsity.dense(1, 1)), ca.is_vector(ca.Sparsity.dense(2, 2))
(true, false)
julia> ca.is_vector(ca.Sparsity(0, 3))
false

See also
is_row, is_column

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

Definition at line 291 of file sparsity.cpp.

291  {
292  return (*this)->is_vector();
293  }

Referenced by casadi::FunctionInternal::check_mat(), casadi::Integrator::init(), casadi::GenericMatrix< MatType >::is_vector(), casadi::Integrator::map2oracle(), and casadi::Call::projectArg().

◆ kkt()

Sparsity casadi::Sparsity::kkt ( const Sparsity &  H,
const Sparsity &  J,
bool  with_x_diag = true,
bool  with_lam_g_diag = true 
)
static

Block pattern of the KKT matrix of an NLP with Hessian H (square, n-by-n) and constraint Jacobian J (m-by-n), where I1 and I2 are the n-by-n and m-by-m diagonal patterns that are included on request. Shape (n+m)-by-(n+m).

Parameters
HHessian pattern, must be square
JJacobian pattern, its number of columns must equal the size of H
with_x_diagAdd the diagonal to the H block
with_lam_g_diagMake the lower right block diagonal instead of all-zero

>>> DM(Sparsity.kkt(Sparsity.diag(2), Sparsity.dense(1, 2)), 1)
DM(
[[1, 00, 1],
 [00, 1, 1],
 [1, 1, 1]])
>>> DM(Sparsity.kkt(Sparsity(2, 2), Sparsity.dense(1, 2), False, False), 1)
DM(
[[00, 00, 1],
 [00, 00, 1],
 [1, 1, 00]])
>>> try: Sparsity.kkt(Sparsity.diag(2), Sparsity.dense(1, 3))
... except Exception as e: print("dimension mismatch")
dimension mismatch

>> DM(Sparsity.kkt(Sparsity.diag(2), Sparsity.dense(1, 2)), 1)
[[1, 00, 1],
 [00, 1, 1],
 [1, 1, 1]]
>> DM(Sparsity.kkt(Sparsity(2, 2), Sparsity.dense(1, 2), false, false), 1)
[[00, 00, 1],
 [00, 00, 1],
 [1, 1, 00]]
>> J = Sparsity.dense(1, 3);
>> try, Sparsity.kkt(Sparsity.diag(2), J); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> ca.DM(ca.Sparsity.kkt(ca.Sparsity.diag(2), ca.Sparsity.dense(1, 2)), 1)
DM(
[[1, 00, 1],
 [00, 1, 1],
 [1, 1, 1]])
julia> ca.DM(ca.Sparsity.kkt(ca.Sparsity(2, 2), ca.Sparsity.dense(1, 2), false, false), 1)
DM(
[[00, 00, 1],
 [00, 00, 1],
 [1, 1, 00]])
julia> try
           ca.Sparsity.kkt(ca.Sparsity.diag(2), ca.Sparsity.dense(1, 3))
       catch e
           println("dimension mismatch")
       end
dimension mismatch

See also
blockcat

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

Definition at line 2058 of file sparsity.cpp.

2059  {
2060  // Consistency check
2061  casadi_assert(H.is_square(), "H must be square");
2062  casadi_assert(H.size1() == J.size2(), "Dimension mismatch");
2063 
2064  // Add diagonal to H recursively
2065  if (with_x_diag) return kkt(H + diag(H.size()), J, false, with_lam_g_diag);
2066 
2067  // Lower right entry
2068  int ng = J.size1();
2069  Sparsity B = with_lam_g_diag ? diag(ng, ng) : Sparsity(ng, ng);
2070 
2071  // Concatenate
2072  return blockcat({{H, J.T()}, {J, B}});
2073  }
static Sparsity blockcat(const std::vector< std::vector< Sparsity > > &v)
Accessed by SparsityInterface.
Definition: sparsity.cpp:1688
static Sparsity kkt(const Sparsity &H, const Sparsity &J, bool with_x_diag=true, bool with_lam_g_diag=true)
Pattern of a KKT system [H + I1, J'; J, I2].
Definition: sparsity.cpp:2058
SparsityInterface< Sparsity > B
Base class.
Definition: sparsity.hpp:399

References blockcat(), diag(), is_square(), size(), size1(), size2(), Sparsity(), and T().

Referenced by casadi::Ipqp::init(), and casadi::Qrqp::init().

◆ kron()

Sparsity casadi::Sparsity::kron ( const Sparsity &  a,
const Sparsity &  b 
)
static

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

Definition at line 1466 of file sparsity.cpp.

1466  {
1467  casadi_int a_ncol = a.size2();
1468  casadi_int b_ncol = b.size2();
1469  casadi_int a_nrow = a.size1();
1470  casadi_int b_nrow = b.size1();
1471  if (a.is_dense() && b.is_dense()) return Sparsity::dense(a_nrow*b_nrow, a_ncol*b_ncol);
1472 
1473  const casadi_int* a_colind = a.colind();
1474  const casadi_int* a_row = a.row();
1475  const casadi_int* b_colind = b.colind();
1476  const casadi_int* b_row = b.row();
1477 
1478  std::vector<casadi_int> r_colind(a_ncol*b_ncol+1, 0);
1479  std::vector<casadi_int> r_row(a.nnz()*b.nnz());
1480 
1481  casadi_int* r_colind_ptr = get_ptr(r_colind);
1482  casadi_int* r_row_ptr = get_ptr(r_row);
1483 
1484  casadi_int i=0;
1485  casadi_int j=0;
1486  // Loop over the columns
1487  for (casadi_int a_cc=0; a_cc<a_ncol; ++a_cc) {
1488  casadi_int a_start = a_colind[a_cc];
1489  casadi_int a_stop = a_colind[a_cc+1];
1490  // Loop over the columns
1491  for (casadi_int b_cc=0; b_cc<b_ncol; ++b_cc) {
1492  casadi_int b_start = b_colind[b_cc];
1493  casadi_int b_stop = b_colind[b_cc+1];
1494  // Loop over existing nonzeros
1495  for (casadi_int a_el=a_start; a_el<a_stop; ++a_el) {
1496  casadi_int a_r = a_row[a_el];
1497  // Loop over existing nonzeros
1498  for (casadi_int b_el=b_start; b_el<b_stop; ++b_el) {
1499  casadi_int b_r = b_row[b_el];
1500  r_row_ptr[i++] = a_r*b_nrow+b_r;
1501  }
1502  }
1503  j+=1;
1504  r_colind_ptr[j] = r_colind_ptr[j-1] + (b_stop-b_start)*(a_stop-a_start);
1505  }
1506  }
1507  return Sparsity(a_nrow*b_nrow, a_ncol*b_ncol, r_colind, r_row);
1508  }

References colind(), dense(), casadi::get_ptr(), is_dense(), nnz(), row(), size1(), size2(), and Sparsity().

Referenced by casadi::MXNode::get_kron(), and casadi::Kron::Kron().

◆ kron_contract()

Sparsity casadi::Sparsity::kron_contract ( const Sparsity &  sp_m,
const Sparsity &  sp_x,
bool  inner 
)
static

Given an (mA*mB, nA*nB) pattern sp_m and an (xrow, xcol) pattern sp_x, computes the output sparsity. Both modes share the same (yrow, ycol) = sp_m.size() / sp_x.size() shape; what differs is which axis pair indexes the output:

  • inner = true: (i, j) ∈ y iff ∃ (r, s) ∈ sp_x with (i*xrow + r, j*xcol + s) ∈ sp_m; output indexed by the outer block of M.
  • inner = false: (r, s) ∈ y iff ∃ (i, j) ∈ sp_x with (i*yrow + r, j*ycol + s) ∈ sp_m; output indexed by the inner block of M.

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

Definition at line 1510 of file sparsity.cpp.

1510  {
1511  casadi_int xrow = sp_x.size1();
1512  casadi_int xcol = sp_x.size2();
1513  casadi_assert(xrow > 0 && xcol > 0,
1514  "Sparsity::kron_contract: sp_x must be nonempty");
1515  casadi_assert(sp_m.size1() % xrow == 0 && sp_m.size2() % xcol == 0,
1516  "Sparsity::kron_contract: sp_m dims must be multiples of sp_x dims");
1517  casadi_int yrow = sp_m.size1() / xrow;
1518  casadi_int ycol = sp_m.size2() / xcol;
1519  // Block-split factor of M's row/col indices. Inner: M_row=i*xrow+r, so
1520  // split_r=xrow. Outer: M_row=i*yrow+r, so split_r=yrow. Same for cols.
1521  casadi_int split_r = inner ? xrow : yrow;
1522  casadi_int split_c = inner ? xcol : ycol;
1523  // Densify x's pattern into a dense lookup
1524  std::vector<bool> x_dense(xrow * xcol, false);
1525  const casadi_int* x_colind = sp_x.colind();
1526  const casadi_int* x_row = sp_x.row();
1527  for (casadi_int cc = 0; cc < xcol; ++cc) {
1528  for (casadi_int el = x_colind[cc]; el < x_colind[cc+1]; ++el) {
1529  x_dense[cc*xrow + x_row[el]] = true;
1530  }
1531  }
1532  // Walk m's CSC. For each (outer, inner) decomposition of m's row/col,
1533  // the (y, x) assignment swaps with `inner`.
1534  std::vector<bool> y_dense(yrow * ycol, false);
1535  const casadi_int* m_colind = sp_m.colind();
1536  const casadi_int* m_row = sp_m.row();
1537  casadi_int outer_c_count = sp_m.size2() / split_c; // ycol if inner, xcol otherwise
1538  for (casadi_int outer_c = 0; outer_c < outer_c_count; ++outer_c) {
1539  for (casadi_int inner_c = 0; inner_c < split_c; ++inner_c) {
1540  casadi_int cc = outer_c*split_c + inner_c;
1541  casadi_int y_c = inner ? outer_c : inner_c;
1542  casadi_int x_c = inner ? inner_c : outer_c;
1543  for (casadi_int el = m_colind[cc]; el < m_colind[cc+1]; ++el) {
1544  casadi_int rr = m_row[el];
1545  casadi_int outer_r = rr / split_r;
1546  casadi_int inner_r = rr % split_r;
1547  casadi_int y_r = inner ? outer_r : inner_r;
1548  casadi_int x_r = inner ? inner_r : outer_r;
1549  if (x_dense[x_c*xrow + x_r]) {
1550  y_dense[y_c*yrow + y_r] = true;
1551  }
1552  }
1553  }
1554  }
1555  // Build CSC from y_dense
1556  std::vector<casadi_int> y_colind(ycol + 1, 0);
1557  std::vector<casadi_int> y_row;
1558  for (casadi_int j = 0; j < ycol; ++j) {
1559  for (casadi_int i = 0; i < yrow; ++i) {
1560  if (y_dense[j*yrow + i]) y_row.push_back(i);
1561  }
1562  y_colind[j+1] = y_row.size();
1563  }
1564  return Sparsity(yrow, ycol, y_colind, y_row);
1565  }

References colind(), row(), size1(), size2(), and Sparsity().

Referenced by casadi::MXNode::get_kron_contract(), and casadi::KronContract::KronContract().

◆ largest_first()

std::vector< casadi_int > casadi::Sparsity::largest_first ( ) const

Columns with the same number of nonzeros keep their relative order. Used as the ordering of the star colorings.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.largest_first(), Sparsity.diag(3).largest_first()
([0, 2, 3, 1], [0, 1, 2])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> sp.largest_first(), Sparsity.diag(3).largest_first()
0 2 3 1
0 1 2

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.largest_first(sp), ca.largest_first(ca.Sparsity.diag(3))
([0, 2, 3, 1], [0, 1, 2])

See also
star_coloring

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

Definition at line 789 of file sparsity.cpp.

789  {
790  return (*this)->largest_first();
791  }

◆ ldl()

Sparsity casadi::Sparsity::ldl ( std::vector< casadi_int > &  p,
bool  amd = true 
) const

Computes the pattern of the factor in A[p, p] = L*D*L^T, where L is unit lower triangular. Returns the pattern of the strictly upper triangular L^T (the unit diagonal is not stored) and the ordering p. A non-symmetric pattern raises an error. The numerical counterpart is ldl() applied to a matrix.

Parameters
amdIf true (default), a fill-reducing AMD ordering is computed and returned in p; if false, p is the identity
Returns
Pattern of L^T and the permutation vector p

>>> Lt, p = Sparsity.banded(4, 1).ldl(False)
>>> DM(Lt, 1), p
(DM(
[[00, 1, 00, 00],
 [00, 00, 1, 00],
 [00, 00, 00, 1],
 [00, 00, 00, 00]]), [0, 1, 2, 3])
>>> A = Sparsity.nonzeros(4, 4, [0, 3, 5, 10, 12, 15])
>>> Lt, p = A.ldl()
>>> Lt.nnz(), p
(1, [1, 2, 0, 3])
>>> try: Sparsity.upper(3).ldl()
... except Exception as e: print("not symmetric")
not symmetric

>> [Lt, p] = Sparsity.banded(4, 1).ldl(false);
>> DM(Lt, 1), p
[[00, 1, 00, 00],
 [00, 00, 1, 00],
 [00, 00, 00, 1],
 [00, 00, 00, 00]]
0 1 2 3
>> A = Sparsity.nonzeros(4, 4, [1, 4, 6, 11, 13, 16]);
>> [Lt, p] = A.ldl(); disp(Lt.nnz()), disp(p)
1
1 2 0 3
>> try, Sparsity.upper(3).ldl(); catch e, disp('not symmetric'); end
not symmetric

julia> ca.ldl(ca.Sparsity.banded(4, 1), false)
(4x4,3nz, [0, 1, 2, 3])
julia> A = ca.Sparsity.nonzeros(4, 4, [0, 3, 5, 10, 12, 15]);
julia> ca.nnz(first(ca.ldl(A)))
1
julia> try
           ca.ldl(ca.Sparsity.upper(3))
       catch e
           println("not symmetric")
       end
not symmetric

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

See also
amd, etree, qr_sparse

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

Definition at line 631 of file sparsity.cpp.

631  {
632  casadi_assert(is_symmetric(),
633  "LDL factorization requires a symmetric matrix");
634  // Recursive call if AMD
635  if (amd) {
636  // Get AMD reordering
637  p = this->amd();
638  // Permute sparsity pattern
639  std::vector<casadi_int> tmp;
640  Sparsity Aperm = sub(p, p, tmp);
641  // Call recursively
642  return Aperm.ldl(tmp, false);
643  }
644  // Dimension
645  casadi_int n=size1();
646  // Natural ordering
647  p = range(n);
648  // Work vector
649  std::vector<casadi_int> w(3*n);
650  // Elimination tree
651  std::vector<casadi_int> parent(n);
652  // Calculate colind in L (strictly lower entries only)
653  std::vector<casadi_int> L_colind(1+n);
654  SparsityInternal::ldl_colind(*this, get_ptr(parent), get_ptr(L_colind), get_ptr(w));
655  // Get rows in L (strictly lower entries only)
656  std::vector<casadi_int> L_row(L_colind.back());
657  SparsityInternal::ldl_row(*this, get_ptr(parent), get_ptr(L_colind), get_ptr(L_row),
658  get_ptr(w));
659  // Sparsity of L^T
660  return Sparsity(n, n, L_colind, L_row, true).T();
661  }
static void ldl_colind(const casadi_int *sp, casadi_int *parent, casadi_int *l_colind, casadi_int *w)
Calculate the column offsets for the L factor of an LDL^T factorization.
static void ldl_row(const casadi_int *sp, const casadi_int *parent, casadi_int *l_colind, casadi_int *l_row, casadi_int *w)
Calculate the row indices for the L factor of an LDL^T factorization.
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
std::vector< casadi_int > amd() const
Approximate minimum degree (AMD) ordering of a symmetric pattern.
Definition: sparsity.cpp:719
bool is_symmetric() const
Check whether the pattern equals its transpose.
Definition: sparsity.cpp:319

References amd(), casadi::get_ptr(), is_symmetric(), ldl(), casadi::SparsityInternal::ldl_colind(), casadi::SparsityInternal::ldl_row(), casadi::range(), size1(), Sparsity(), and sub().

Referenced by casadi::SuperscsInterface::init(), casadi::LinsolLdl::init(), and ldl().

◆ lower()

Sparsity casadi::Sparsity::lower ( casadi_int  n)
static

Column j contains the rows j, ..., n-1, so the diagonal is included and the pattern has n*(n+1)/2 nonzeros.

Parameters
nSize of the square pattern, nonnegative

>>> DM(Sparsity.lower(3), 1)
DM(
[[1, 00, 00],
 [1, 1, 00],
 [1, 1, 1]])
>>> SX.sym("x", Sparsity.lower(2))
SX(
[[x_0, 00],
 [x_1, x_2]])

>> DM(Sparsity.lower(3), 1)
[[1, 00, 00],
 [1, 1, 00],
 [1, 1, 1]]
>> SX.sym('x', Sparsity.lower(2))
[[x_0, 00],
 [x_1, x_2]]

julia> ca.DM(ca.Sparsity.lower(3), 1)
DM(
[[1, 00, 00],
 [1, 1, 00],
 [1, 1, 1]])
julia> ca.SX.sym("x", ca.Sparsity.lower(2))
SX(
[[x_0, 00],
 [x_1, x_2]])

See also
upper, tril, is_tril

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

Definition at line 1078 of file sparsity.cpp.

1078  {
1079  casadi_assert(n>=0, "Sparsity::lower expects a positive integer as argument");
1080  casadi_int nrow=n, ncol=n;
1081  std::vector<casadi_int> colind, row;
1082  colind.reserve(ncol+1);
1083  row.reserve((n*(n+1))/2);
1084 
1085  // Loop over columns
1086  colind.push_back(0);
1087  for (casadi_int cc=0; cc<ncol; ++cc) {
1088  // Loop over rows for the lower triangular half
1089  for (casadi_int rr=cc; rr<nrow; ++rr) {
1090  row.push_back(rr);
1091  }
1092  colind.push_back(row.size());
1093  }
1094 
1095  // Return the pattern
1096  return Sparsity(nrow, ncol, colind, row);
1097  }

References colind(), row(), and Sparsity().

Referenced by casadi::OptiNode::parameter(), casadi::Convexify::setup(), and casadi::OptiNode::variable().

◆ mac()

static Sparsity casadi::Sparsity::mac ( const Sparsity &  x,
const Sparsity &  y,
const Sparsity &  z,
const std::string &  = "reference" 
)
inlinestatic

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

Definition at line 3435 of file sparsity.hpp.

3436  { return z;}

◆ makeDense()

Sparsity casadi::Sparsity::makeDense ( std::vector< casadi_int > &  mapping) const
Returns
The dense pattern and a mapping of length nnz(): mapping[k] is the flat (column-major) element index of nonzero k, as returned by find()

>>> sp = Sparsity.triplet(3, 2, [0, 2], [0, 1])
>>> dense, mapping = sp.makeDense()
>>> dense, mapping
(Sparsity(3x2), [0, 5])

>> sp = Sparsity.triplet(3, 2, [0, 2], [0, 1]);
>> [dense, mapping] = sp.makeDense(); disp(dense), disp(mapping)
3x2
0 5

julia> sp = ca.Sparsity.triplet(3, 2, [0, 2], [0, 1]);
julia> ca.makeDense(sp)
(3x2, [0, 5])

See also
find, dense

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

Definition at line 591 of file sparsity.cpp.

591  {
592  return (*this)->makeDense(mapping);
593  }

References casadi::SparsityInternal::makeDense().

◆ mtimes()

Sparsity casadi::Sparsity::mtimes ( const Sparsity &  x,
const Sparsity &  y,
const std::string &  blas = "reference" 
)
static

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

Definition at line 432 of file sparsity.cpp.

433  {
434  // Check matching dimensions
435  casadi_assert(x.size2()==y.size1(),
436  "Matrix product with incompatible dimensions. Lhs is "
437  + x.dim() + " and rhs is " + y.dim() + ".");
438 
439  return x->_mtimes(y);
440  }

References casadi::SparsityInternal::_mtimes(), dim(), size1(), and size2().

Referenced by casadi::MX::mtimes(), qr_sparse(), sum1(), and sum2().

◆ mul_activityF()

void casadi::Sparsity::mul_activityF ( const bvec_t *  x,
const Sparsity &  x_sp,
const bvec_t *  y,
const Sparsity &  y_sp,
bvec_t *  z,
const Sparsity &  z_sp,
bvec_t *  w 
)
static

Like mul_sparsityF, but combines the two factors of each term with AND rather than OR (an inactive factor annihilates that term), so an output is active only where some term has both factors active. No memory allocation; work vector w.

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

Definition at line 1880 of file sparsity.cpp.

1883  {
1884  mul_bvec_fwd<true>(x, x_sp, y, y_sp, z, z_sp, w);
1885  }

Referenced by casadi::Multiplication::eval_activity().

◆ mul_sparsityF()

void casadi::Sparsity::mul_sparsityF ( const bvec_t *  x,
const Sparsity &  x_sp,
const bvec_t *  y,
const Sparsity &  y_sp,
bvec_t *  z,
const Sparsity &  z_sp,
bvec_t *  w 
)
static

no memory allocation: z = mul(x, y) with work vector Forward mode.

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

Definition at line 1873 of file sparsity.cpp.

1876  {
1877  mul_bvec_fwd<false>(x, x_sp, y, y_sp, z, z_sp, w);
1878  }

Referenced by casadi::Multiplication::sp_forward().

◆ mul_sparsityR()

void casadi::Sparsity::mul_sparsityR ( bvec_t *  x,
const Sparsity &  x_sp,
bvec_t *  y,
const Sparsity &  y_sp,
bvec_t *  z,
const Sparsity &  z_sp,
bvec_t *  w 
)
static

no memory allocation: z = mul(x, y) with work vector Reverse mode.

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

Definition at line 1887 of file sparsity.cpp.

1890  {
1891  // Assert dimensions
1892  casadi_assert(z_sp.size1()==x_sp.size1() && x_sp.size2()==y_sp.size1()
1893  && y_sp.size2()==z_sp.size2(),
1894  "Dimension error. Got x=" + x_sp.dim() + ", y=" + y_sp.dim()
1895  + " and z=" + z_sp.dim() + ".");
1896 
1897  // Direct access to the arrays
1898  const casadi_int* y_colind = y_sp.colind();
1899  const casadi_int* y_row = y_sp.row();
1900  const casadi_int* x_colind = x_sp.colind();
1901  const casadi_int* x_row = x_sp.row();
1902  const casadi_int* z_colind = z_sp.colind();
1903  const casadi_int* z_row = z_sp.row();
1904 
1905  // Clear residual work vector data from preceding operations (not necessary
1906  // for data from this method if conditional clear code is made unconditional
1907  // in loop)
1908  casadi_int nrow = z_sp.size1();
1909  casadi_fill(w, nrow, static_cast<bvec_t>(0));
1910 
1911  // Loop over the columns of y and z
1912  casadi_int ncol = z_sp.size2();
1913  for (casadi_int cc=0; cc<ncol; ++cc) {
1914  // Get the dense column of z
1915  for (casadi_int kk=z_colind[cc]; kk<z_colind[cc+1]; ++kk) {
1916  w[z_row[kk]] = z[kk];
1917  }
1918 
1919  // Loop over the nonzeros of y
1920  for (casadi_int kk=y_colind[cc]; kk<y_colind[cc+1]; ++kk) {
1921  casadi_int rr = y_row[kk];
1922 
1923  // Loop over corresponding columns of x
1924  bvec_t yy = 0;
1925  for (casadi_int kk1=x_colind[rr]; kk1<x_colind[rr+1]; ++kk1) {
1926  yy |= w[x_row[kk1]];
1927  x[kk1] |= w[x_row[kk1]];
1928  }
1929  y[kk] |= yy;
1930  }
1931 
1932  // Get the sparse column of z, clear work vector for next column
1933  for (casadi_int kk=z_colind[cc]; kk<z_colind[cc+1]; ++kk) {
1934  z[kk] = w[z_row[kk]];
1935  w[z_row[kk]] = 0;
1936  }
1937  }
1938  }
unsigned long long bvec_t
void casadi_fill(T1 *x, casadi_int n, T1 alpha)
FILL: x <- alpha.

References casadi::casadi_fill(), colind(), dim(), row(), size1(), and size2().

Referenced by casadi::Multiplication::sp_reverse().

◆ nnz()

casadi_int casadi::Sparsity::nnz ( ) const

Equals colind[size2()] and the length of the row vector. Zero for an empty pattern and for a pattern created with Sparsity(nrow, ncol).

See also
numel, density, nnz_upper, nnz_lower, nnz_diag

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

Definition at line 150 of file sparsity.cpp.

150  {
151  return (*this)->nnz();
152  }

Referenced by casadi::Matrix< Scalar >::_sym(), casadi::MX::_sym(), casadi::SetNonzeros< Add >::ad_forward(), casadi::GetNonzeros::ad_reverse(), casadi::SetNonzeros< Add >::ad_reverse(), add(), add_nz(), bor(), casadi::Switch::codegen_body(), casadi::FastNewton::codegen_body(), casadi::Sqpmethod::codegen_body(), casadi::OsqpInterface::codegen_init_mem(), casadi::Sqpmethod::codegen_solve_elastic_mode(), casadi::SparsityInternal::combineGen1(), compressed(), casadi::ConoptInterface::ConoptInterface(), casadi::ConstantFile::ConstantFile(), casadi::ConstantMX::create(), density(), diagsplit(), casadi::FmuFunction::eval(), casadi::Switch::eval(), casadi::HorzRepsum::eval_gen(), casadi::AlpaqaProblem::eval_hess_L(), casadi::AlpaqaProblem::eval_hess_ψ(), casadi::AlpaqaProblem::eval_jac_g(), casadi::Scpgen::eval_mat(), casadi::SetNonzeros< Add >::eval_mx(), casadi::Switch::eval_sx(), casadi::LinsolQr::finalize(), from_file(), casadi::LinsolLdl::generate(), casadi::HorzRepsum::generate(), casadi::UnaryMX::generate(), casadi::CodeGenerator::generate_dump(), casadi::LinsolQr::generate_factorize(), casadi::get_const(), casadi::AlpaqaProblem::get_hess_L_num_nonzeros(), casadi::AlpaqaProblem::get_hess_ψ_num_nonzeros(), casadi::AlpaqaProblem::get_jac_g_num_nonzeros(), casadi::FunctionInternal::get_jac_sparsity_gen(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::BonminInterface::get_nlp_info(), casadi::IpoptInterface::get_nlp_info(), casadi::Call::get_output(), casadi::MultipleOutput::get_output(), casadi::MXNode::get_project(), casadi::MXNode::get_sparsity_cast(), casadi::FunctionInternal::get_sparsity_out(), horzcat(), casadi::FmuFunction::init(), casadi::Switch::init(), casadi::AmplInterface::init(), casadi::Blocksqp::init(), casadi::BonminInterface::init(), casadi::CbcInterface::init(), casadi::ClpInterface::init(), casadi::ConoptInterface::init(), casadi::FatropConicInterface::init(), casadi::FatropInterface::init(), casadi::HpipmInterface::init(), casadi::HpmpcInterface::init(), casadi::IpoptInterface::init(), casadi::MosekInterface::init(), casadi::OsqpInterface::init(), casadi::PiqpInterface::init(), casadi::SLEQPInterface::init(), casadi::SnoptInterface::init(), casadi::KinsolInterface::init(), casadi::SundialsInterface::init(), casadi::SuperscsInterface::init(), casadi::XpressInterface::init(), casadi::FastNewton::init(), casadi::Feasiblesqpmethod::init(), casadi::Ipqp::init(), casadi::Newton::init(), casadi::Qrqp::init(), casadi::Qrsqp::init(), casadi::Scpgen::init(), casadi::Sqpmethod::init(), casadi::ClarabelInterface::init_dependent(), casadi::HighsInterface::init_dependent(), casadi::MosekInterface::init_dependent(), casadi::XpressInterface::init_dependent(), casadi::Blocksqp::init_mem(), casadi::CbcInterface::init_mem(), casadi::ClpInterface::init_mem(), casadi::ConoptInterface::init_mem(), casadi::CplexInterface::init_mem(), casadi::HpmpcInterface::init_mem(), casadi::OsqpInterface::init_mem(), casadi::PiqpInterface::init_mem(), casadi::ProxqpInterface::init_mem(), casadi::QpoasesInterface::init_mem(), casadi::SuperscsInterface::init_mem(), casadi::LinsolLdl::init_mem(), casadi::LinsolQr::init_mem(), casadi::Lsqr::init_mem(), kron(), casadi::MosekInterface::MosekInterface(), casadi::MX::MX(), casadi::LinsolQr::nfact(), norm_0_mul(), casadi::FunctionInternal::print_canonical(), casadi::Matrix< Scalar >::print_default(), casadi::Matrix< Scalar >::print_dense(), casadi::MXFunction::print_res(), casadi::Matrix< Scalar >::print_sparse(), casadi::Matrix< Scalar >::print_vector(), casadi::CodeGenerator::project(), casadi::QpoasesInterface::qpoases_init(), repr_el(), casadi::Reshape::Reshape(), row(), set(), casadi::MadmpecInterface::set_ccopt_prob(), casadi::FatropInterface::set_fatrop_prob(), casadi::IpoptInterface::set_ipopt_prob(), casadi::MadnlpInterface::set_madnlp_prob(), casadi::Blocksqp::set_work(), casadi::BonminInterface::set_work(), casadi::IpoptInterface::set_work(), casadi::SLEQPInterface::set_work(), casadi::SnoptInterface::set_work(), casadi::KinsolInterface::set_work(), casadi::SundialsInterface::set_work(), casadi::WorhpInterface::set_work(), casadi::FastNewton::set_work(), casadi::Newton::set_work(), casadi::Qrsqp::set_work(), casadi::Scpgen::set_work(), casadi::Convexify::setup(), casadi::CplexInterface::solve(), casadi::PiqpInterface::solve(), casadi::ProxqpInterface::solve(), casadi::QpoasesInterface::solve(), casadi::SuperscsInterface::solve(), casadi::Ipqp::solve(), casadi::ConoptInterface::solve(), casadi::KnitroInterface::solve(), casadi::Feasiblesqpmethod::solve(), casadi::Qrsqp::solve(), casadi::Sqpmethod::solve(), casadi::Sqpmethod::solve_elastic_mode(), casadi::MXNode::sp_forward(), casadi::HorzRepsum::sp_forward(), casadi::Split::sp_forward(), casadi::FunctionInternal::sp_forward_block(), casadi::MXNode::sp_reverse(), casadi::HorzRepmat::sp_reverse(), casadi::HorzRepsum::sp_reverse(), casadi::Split::sp_reverse(), casadi::FunctionInternal::sp_reverse(), casadi::MX::sparsity_cast(), sparsity_cast(), casadi::SparsityCast::SparsityCast(), to_file(), vertcat(), and casadi::XpressInterface::XpressInterface().

◆ nnz_diag()

casadi_int casadi::Sparsity::nnz_diag ( ) const
See also
nnz_upper, nnz_lower, get_diag

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

Definition at line 362 of file sparsity.cpp.

362  {
363  return (*this)->nnz_diag();
364  }

◆ nnz_lower()

casadi_int casadi::Sparsity::nnz_lower ( bool  strictly = false) const
Parameters
strictlyIf true, exclude the diagonal (count i > j only)
See also
nnz_upper, nnz_diag, get_lower, is_tril

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

Definition at line 354 of file sparsity.cpp.

354  {
355  return (*this)->nnz_lower(strictly);
356  }

Referenced by casadi::WorhpInterface::set_work().

◆ nnz_upper()

casadi_int casadi::Sparsity::nnz_upper ( bool  strictly = false) const
Parameters
strictlyIf true, exclude the diagonal (count i < j only)

Defined for any shape, not only square patterns.

>>> sp = Sparsity.dense(3, 3)
>>> sp.nnz_upper(), sp.nnz_upper(True), sp.nnz_lower(), sp.nnz_lower(True)
(6, 3, 6, 3)
>>> sp.nnz_diag()
3
>>> sp = Sparsity.dense(2, 4)
>>> sp.nnz_upper(), sp.nnz_lower(), sp.nnz_diag()
(7, 3, 2)
>>> Sparsity.lower(3).nnz_upper(), Sparsity.lower(3).nnz_upper(True)
(3, 0)

>> sp = Sparsity.dense(3, 3);
>> [sp.nnz_upper(), sp.nnz_upper(true), sp.nnz_lower(), sp.nnz_lower(true)]
6 3 6 3
>> sp.nnz_diag()
3
>> sp = Sparsity.dense(2, 4);
>> [sp.nnz_upper(), sp.nnz_lower(), sp.nnz_diag()]
7 3 2
>> [Sparsity.lower(3).nnz_upper(), Sparsity.lower(3).nnz_upper(true)]
3 0

julia> sp = ca.Sparsity.dense(3, 3);
julia> ca.nnz_upper(sp), ca.nnz_upper(sp, true), ca.nnz_lower(sp), ca.nnz_lower(sp, true)
(6, 3, 6, 3)
julia> ca.nnz_diag(sp)
3
julia> sp = ca.Sparsity.dense(2, 4);
julia> ca.nnz_upper(sp), ca.nnz_lower(sp), ca.nnz_diag(sp)
(7, 3, 2)
julia> ca.nnz_upper(ca.Sparsity.lower(3)), ca.nnz_upper(ca.Sparsity.lower(3), true)
(3, 0)

See also
nnz_lower, nnz_diag, get_upper, is_triu

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

Definition at line 358 of file sparsity.cpp.

358  {
359  return (*this)->nnz_upper(strictly);
360  }

Referenced by casadi::OsqpInterface::codegen_init_mem(), casadi::OoqpInterface::init(), casadi::OsqpInterface::init(), casadi::MumpsInterface::init_mem(), and casadi::OsqpInterface::init_mem().

◆ nonzeros()

Sparsity casadi::Sparsity::nonzeros ( casadi_int  nrow,
casadi_int  ncol,
const std::vector< casadi_int > &  nz,
bool  ind1 = SWIG_IND1 
)
static

Inverse of find(): Sparsity.nonzeros(sp.size1(), sp.size2(), sp.find()) equals sp. Duplicates are merged.

Parameters
nrowNumber of rows, must be positive
ncolNumber of columns
nzFlat indices, each in [0, nrow*ncol); an index out of range raises an error
ind1If true, the indices are one-based

>>> DM(Sparsity.nonzeros(3, 2, [0, 4]), 1)
DM(
[[1, 00],
 [00, 1],
 [00, 00]])
>>> sp = Sparsity.banded(3, 1)
>>> Sparsity.nonzeros(3, 3, sp.find()) == sp
True
>>> Sparsity.nonzeros(3, 2, [1, 5], True) == Sparsity.nonzeros(3, 2, [0, 4])
True

>> DM(Sparsity.nonzeros(3, 2, [1, 5]), 1)
[[1, 00],
 [00, 1],
 [00, 00]]
>> sp = Sparsity.banded(3, 1);
>> Sparsity.nonzeros(3, 3, sp.find()) == sp
1
>> Sparsity.nonzeros(3, 2, [0, 4], false) == Sparsity.nonzeros(3, 2, [1, 5])
1

julia> ca.DM(ca.Sparsity.nonzeros(3, 2, [0, 4]), 1)
DM(
[[1, 00],
 [00, 1],
 [00, 00]])
julia> sp = ca.Sparsity.banded(3, 1);
julia> ca.is_equal(ca.Sparsity.nonzeros(3, 3, ca.find(sp)), sp)
true
julia> sp1 = ca.Sparsity.nonzeros(3, 2, [1, 5], true);
julia> ca.is_equal(sp1, ca.Sparsity.nonzeros(3, 2, [0, 4]))
true

See also
find, triplet

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

Definition at line 1315 of file sparsity.cpp.

1316  {
1317  casadi_assert(nrow>0, "nrow must be >0.");
1318  std::vector<casadi_int> row(nz.size());
1319  std::vector<casadi_int> col(nz.size());
1320  for (casadi_int i=0;i<nz.size();++i) {
1321  casadi_int k = nz[i];
1322  k-= ind1;
1323  row[i] = k % nrow;
1324  col[i] = k / nrow;
1325  }
1326  return triplet(nrow, ncol, row, col);
1327  }

References row(), and triplet().

◆ norm_0_mul()

casadi_int casadi::Sparsity::norm_0_mul ( const Sparsity &  x,
const Sparsity &  A 
)
static

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

Definition at line 1744 of file sparsity.cpp.

1744  {
1745  // Implementation borrowed from Scipy's sparsetools/csr.h
1746  casadi_assert(A.size1()==x.size2(), "Dimension error. Got " + x.dim()
1747  + " times " + A.dim() + ".");
1748 
1749  casadi_int n_row = A.size2();
1750  casadi_int n_col = x.size1();
1751 
1752  // Allocate work vectors
1753  std::vector<bool> Bwork(n_col);
1754  std::vector<casadi_int> Iwork(n_row+1+n_col);
1755 
1756  const casadi_int* Aj = A.row();
1757  const casadi_int* Ap = A.colind();
1758  const casadi_int* Bj = x.row();
1759  const casadi_int* Bp = x.colind();
1760  casadi_int *Cp = get_ptr(Iwork);
1761  casadi_int *mask = Cp+n_row+1;
1762 
1763  // Pass 1
1764  // method that uses O(n) temp storage
1765  std::fill(mask, mask+n_col, -1);
1766 
1767  Cp[0] = 0;
1768  casadi_int nnz = 0;
1769  for (casadi_int i = 0; i < n_row; i++) {
1770  casadi_int row_nnz = 0;
1771  for (casadi_int jj = Ap[i]; jj < Ap[i+1]; jj++) {
1772  casadi_int j = Aj[jj];
1773  for (casadi_int kk = Bp[j]; kk < Bp[j+1]; kk++) {
1774  casadi_int k = Bj[kk];
1775  if (mask[k] != i) {
1776  mask[k] = i;
1777  row_nnz++;
1778  }
1779  }
1780  }
1781  casadi_int next_nnz = nnz + row_nnz;
1782  nnz = next_nnz;
1783  Cp[i+1] = nnz;
1784  }
1785 
1786  // Pass 2
1787  casadi_int *next = get_ptr(Iwork) + n_row+1;
1788  std::fill(next, next+n_col, -1);
1789  std::vector<bool> & sums = Bwork;
1790  std::fill(sums.begin(), sums.end(), false);
1791  nnz = 0;
1792  Cp[0] = 0;
1793  for (casadi_int i = 0; i < n_row; i++) {
1794  casadi_int head = -2;
1795  casadi_int length = 0;
1796  casadi_int jj_start = Ap[i];
1797  casadi_int jj_end = Ap[i+1];
1798  for (casadi_int jj = jj_start; jj < jj_end; jj++) {
1799  casadi_int j = Aj[jj];
1800  casadi_int kk_start = Bp[j];
1801  casadi_int kk_end = Bp[j+1];
1802  for (casadi_int kk = kk_start; kk < kk_end; kk++) {
1803  casadi_int k = Bj[kk];
1804  sums[k] = true;
1805  if (next[k] == -1) {
1806  next[k] = head;
1807  head = k;
1808  length++;
1809  }
1810  }
1811  }
1812  for (casadi_int jj = 0; jj < length; jj++) {
1813  if (sums[head]) {
1814  nnz++;
1815  }
1816  casadi_int temp = head;
1817  head = next[head];
1818  next[temp] = -1; //clear arrays
1819  sums[temp] = false;
1820  }
1821  Cp[i+1] = nnz;
1822  }
1823  return nnz;
1824  }

References colind(), dim(), casadi::get_ptr(), nnz(), row(), size1(), and size2().

Referenced by casadi::GenericMatrix< MatType >::norm_0_mul().

◆ numel()

casadi_int casadi::Sparsity::numel ( ) const

The product may overflow for very large shapes; nnz() never exceeds it.

>>> sp = Sparsity.diag(2, 3)
>>> sp.numel(), sp.nnz(), Sparsity(0, 3).numel()
(6, 2, 0)

>> sp = Sparsity.diag(2, 3);
>> fprintf('%d %d %d\n', sp.numel(), sp.nnz(), Sparsity(0, 3).numel())
6 2 0

julia> sp = ca.Sparsity.diag(2, 3);
julia> ca.numel(sp), ca.nnz(sp), ca.numel(ca.Sparsity(0, 3))
(6, 2, 0)

See also
nnz, size

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

Definition at line 132 of file sparsity.cpp.

132  {
133  return (*this)->numel();
134  }

Referenced by density(), get_nz(), casadi::FunctionInternal::get_sparsity_out(), casadi::Nlpsol::init(), casadi::Matrix< Scalar >::print_default(), and casadi::reduce_index_gen().

◆ operator const casadi_int *()

casadi::Sparsity::operator const casadi_int * ( ) const

In the C runtime, sparsity patterns are represented as a "const casadi_int*". This enables using the C runtime functions using a natural syntax.

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

Definition at line 1740 of file sparsity.cpp.

1740  {
1741  return &(*this)->sp().front();
1742  }

◆ operator const std::vector< casadi_int > &()

casadi::Sparsity::operator const std::vector< casadi_int > & ( ) const

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

Definition at line 1344 of file sparsity.cpp.

1344  {
1345  return (*this)->sp();
1346  }

◆ operator SparsityStruct()

casadi::Sparsity::operator SparsityStruct ( ) const

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

Definition at line 1348 of file sparsity.cpp.

1348  {
1349  const casadi_int* sp = *this;
1350  casadi_int nrow = sp[0], ncol = sp[1];
1351  const casadi_int* colind = sp+2, *row = sp+2+ncol+1;
1352  return SparsityStruct{nrow, ncol, colind, row};
1353  }

◆ operator!=()

bool casadi::Sparsity::operator!= ( const Sparsity &  y) const
inline

Definition at line 1443 of file sparsity.hpp.

1443 {return !is_equal(y);}
bool is_equal(const Sparsity &y) const
Check whether two sparsity patterns are identical.
Definition: sparsity.cpp:446

References casadi::is_equal().

◆ operator*() [1/2]

const SparsityInternal & casadi::Sparsity::operator* ( ) const

Definition at line 116 of file sparsity.cpp.

116  {
117  return *static_cast<const SparsityInternal*>(get());
118  }
SparsityInternal * get() const
Definition: sparsity.cpp:2115

References get().

◆ operator*() [2/2]

Sparsity casadi::Sparsity::operator* ( const Sparsity &  b) const

The pattern of the elementwise product x * y for matrices with these patterns. A shape mismatch raises an error. In MATLAB this is the .* operator; * and mtimes give the pattern of the matrix product.

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> DM(a.intersect(b), 1)
DM(
[[00, 00],
 [00, 1]])

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> DM(a.intersect(b), 1)
[[00, 00],
 [00, 1]]

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.DM(ca.intersect(a, b), 1)
DM(
[[00, 00],
 [00, 1]])

See also
unite, combine

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

Definition at line 464 of file sparsity.cpp.

464  {
465  std::vector< unsigned char > mapping;
466  return intersect(b, mapping);
467  }
Sparsity intersect(const Sparsity &y, std::vector< unsigned char > &mapping) const
Intersection of two sparsity patterns of the same shape (also the * operator)
Definition: sparsity.cpp:419

References intersect().

◆ operator+()

Sparsity casadi::Sparsity::operator+ ( const Sparsity &  b) const

The pattern of x + y for matrices with these patterns. A shape mismatch raises an error.

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> DM(a.unite(b), 1)
DM(
[[1, 1],
 [00, 1]])
>>> a + b == a.unite(b), a * b == a.intersect(b)
(True, True)
>>> try: a + Sparsity.dense(3, 3)
... except Exception as e: print("dimension mismatch")
dimension mismatch

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> DM(a.unite(b), 1)
[[1, 1],
 [00, 1]]
>> a + b == a.unite(b), a .* b == a.intersect(b)
1
1
>> try, a + Sparsity.dense(3, 3); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.DM(ca.unite(a, b), 1)
DM(
[[1, 1],
 [00, 1]])
julia> try
           ca.unite(a, ca.Sparsity.dense(3, 3))
       catch e
           println("dimension mismatch")
       end
dimension mismatch

See also
intersect, combine, is_subset

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

Definition at line 460 of file sparsity.cpp.

460  {
461  return unite(b);
462  }
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 unite().

◆ operator->()

const SparsityInternal * casadi::Sparsity::operator-> ( ) const

Definition at line 112 of file sparsity.cpp.

112  {
113  return static_cast<const SparsityInternal*>(SharedObject::operator->());
114  }
SharedObjectInternal * operator->() const
Access a member function or object.

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

◆ operator==()

bool casadi::Sparsity::operator== ( const Sparsity &  y) const
inline

True when the dimensions and the nonzero positions coincide. This is the comparison behind the == operator. Shared (cached) patterns are detected in constant time; otherwise colind and row are compared. The second overload compares against a pattern given in compressed column storage vectors.

>>> a = Sparsity.diag(2)
>>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2), a != Sparsity.dense(2, 2)
(True, True, True)
>>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
True
>>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
False
>>> Sparsity(2, 2) == Sparsity.dense(2, 2)
False

>> a = Sparsity.diag(2);
>> a.is_equal(Sparsity.diag(2)), a == Sparsity.diag(2)
1
1
>> a ~= Sparsity.dense(2, 2)
1
>> a.is_equal(2, 2, [0, 1, 2], [0, 1])
1
>> Sparsity.dense(2, 2) == Sparsity.dense(2, 3)
0
>> Sparsity(2, 2) == Sparsity.dense(2, 2)
0

julia> a = ca.Sparsity.diag(2);
julia> ca.is_equal(a, ca.Sparsity.diag(2)), !ca.is_equal(a, ca.Sparsity.dense(2, 2))
(true, true)
julia> ca.is_equal(a, 2, 2, [0, 1, 2], [0, 1])
true
julia> ca.is_equal(ca.Sparsity.dense(2, 2), ca.Sparsity.dense(2, 3))
false
julia> ca.is_equal(ca.Sparsity(2, 2), ca.Sparsity.dense(2, 2))
false

See also
is_subset, is_transpose, is_reshape, hash

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

Definition at line 1439 of file sparsity.hpp.

1439 { return is_equal(y);}

References casadi::is_equal().

◆ 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.

◆ pattern_inverse()

Sparsity casadi::Sparsity::pattern_inverse ( ) const

The result has the same shape; a dense pattern becomes all-zero and an all-zero pattern becomes dense.

>>> DM(Sparsity.diag(2).pattern_inverse(), 1)
DM(
[[00, 1],
 [1, 00]])
>>> Sparsity.dense(2, 2).pattern_inverse(), Sparsity(2, 2).pattern_inverse()
(Sparsity(2x2,0nz), Sparsity(2x2))

>> DM(Sparsity.diag(2).pattern_inverse(), 1)
[[00, 1],
 [1, 00]]
>> Sparsity.dense(2, 2).pattern_inverse(), Sparsity(2, 2).pattern_inverse()
2x2,0nz
2x2

julia> ca.DM(ca.pattern_inverse(ca.Sparsity.diag(2)), 1)
DM(
[[00, 1],
 [1, 00]])
julia> ca.pattern_inverse(ca.Sparsity.dense(2, 2)), ca.pattern_inverse(ca.Sparsity(2, 2))
(2x2,0nz, 2x2)

See also
unite, intersect

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

Definition at line 469 of file sparsity.cpp.

469  {
470  return (*this)->pattern_inverse();
471  }

References casadi::SparsityInternal::pattern_inverse().

Referenced by casadi::HpipmInterface::init(), and casadi::HpmpcInterface::init().

◆ permutation()

Sparsity casadi::Sparsity::permutation ( const std::vector< casadi_int > &  p,
bool  invert = false 
)
static

P is square with one nonzero per row and column, placed such that multiplying a column vector v from the left gives the same result as indexing it: P @ v == v[p]. The inverse of a permutation matrix is its transpose, so invert true returns the transpose pattern, for which P @ v puts v[i] at position p[i].

Parameters
pPermutation vector: every integer in [0, len(p)) exactly once; anything else raises an error
invertIf true, build the inverse (transposed) permutation

>>> P = Sparsity.permutation([2, 0, 1])
>>> DM(P, 1)
DM(
[[00, 00, 1],
 [1, 00, 00],
 [00, 1, 00]])
>>> DM(P, 1) @ DM([10, 20, 30])
DM([30, 10, 20])
>>> DM(Sparsity.permutation([2, 0, 1], True), 1) @ DM([10, 20, 30])
DM([20, 30, 10])
>>> Sparsity.permutation([2, 0, 1], True) == P.T
True
>>> try: Sparsity.permutation([0, 0, 1])
... except Exception as e: print("not a permutation")
not a permutation

>> P = Sparsity.permutation([2, 0, 1]);
>> DM(P, 1)
[[00, 00, 1],
 [1, 00, 00],
 [00, 1, 00]]
>> DM(P, 1) * DM([10; 20; 30])
[30, 10, 20]
>> DM(Sparsity.permutation([2, 0, 1], true), 1) * DM([10; 20; 30])
[20, 30, 10]
>> Sparsity.permutation([2, 0, 1], true) == P.T
1
>> try, Sparsity.permutation([0, 0, 1]); catch e, disp('not a permutation'); end
not a permutation

julia> P = ca.Sparsity.permutation([2, 0, 1]);
julia> ca.DM(P, 1)
DM(
[[00, 00, 1],
 [1, 00, 00],
 [00, 1, 00]])
julia> ca.DM(P, 1) * ca.DM([10, 20, 30])
DM([30, 10, 20])
julia> ca.DM(ca.Sparsity.permutation([2, 0, 1], true), 1) * ca.DM([10, 20, 30])
DM([20, 30, 10])
julia> ca.is_equal(ca.Sparsity.permutation([2, 0, 1], true), ca.T(P))
true
julia> try
           ca.Sparsity.permutation([0, 0, 1])
       catch e
           println("not a permutation")
       end
not a permutation

See also
permutation_vector, is_permutation, pmult

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

Definition at line 1396 of file sparsity.cpp.

1396  {
1397  casadi_assert(casadi::is_permutation(p),
1398  "Sparsity::permutation supplied list is not a permutation.");
1399  std::vector<casadi_int> colind = range(p.size()+1);
1400  if (invert) {
1401  return Sparsity(p.size(), p.size(), colind, p);
1402  } else {
1403  return Sparsity(p.size(), p.size(), colind, invert_permutation(p));
1404  }
1405  }
std::vector< casadi_int > invert_permutation(const std::vector< casadi_int > &a)
inverse a permutation vector
bool is_permutation(const std::vector< casadi_int > &order)
Does the list represent a permutation?

References colind(), casadi::invert_permutation(), casadi::is_permutation(), casadi::range(), and Sparsity().

◆ permutation_vector()

const std::vector< casadi_int > casadi::Sparsity::permutation_vector ( bool  invert = false) const

Inverse of permutation(): Sparsity.permutation(p).permutation_vector() returns p. Raises an error if is_permutation() is false.

Parameters
invertIf true, return the inverse permutation instead

>>> Sparsity.permutation([2, 0, 1]).permutation_vector()
[2, 0, 1]
>>> Sparsity.permutation([2, 0, 1]).permutation_vector(True)
[1, 2, 0]
>>> try: Sparsity.dense(2, 2).permutation_vector()
... except Exception as e: print("not a permutation matrix")
not a permutation matrix

>> Sparsity.permutation([2, 0, 1]).permutation_vector()
2 0 1
>> Sparsity.permutation([2, 0, 1]).permutation_vector(true)
1 2 0
>> try, Sparsity.dense(2, 2).permutation_vector(); catch e, disp('not a permutation'); end
not a permutation

julia> ca.permutation_vector(ca.Sparsity.permutation([2, 0, 1]))
3-element Vector{Int64}:
 2
 0
 1
julia> ca.permutation_vector(ca.Sparsity.permutation([2, 0, 1]), true)
3-element Vector{Int64}:
 1
 2
 0
julia> try
           ca.permutation_vector(ca.Sparsity.dense(2, 2))
       catch e
           println("not a permutation matrix")
       end
not a permutation matrix

See also
permutation, is_permutation

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

Definition at line 1407 of file sparsity.cpp.

1407  {
1408  casadi_assert(is_permutation(), "Sparsity::permutation called on non-permutation matrix.");
1409  if (invert) {
1410  return get_row();
1411  } else {
1412  return invert_permutation(get_row());
1413  }
1414  }
bool is_permutation() const
Check whether the pattern is that of a permutation matrix.
Definition: sparsity.cpp:299

References get_row(), casadi::invert_permutation(), and is_permutation().

Referenced by casadi::MXNode::get_mac().

◆ pmult()

Sparsity casadi::Sparsity::pmult ( const std::vector< casadi_int > &  p,
bool  permute_rows = true,
bool  permute_columns = true,
bool  invert_permutation = false 
) const

Nonzero (i, j) moves to (p[i], p[j]) when both rows and columns are permuted, to (p[i], j) for rows only and to (i, p[j]) for columns only. In matrix terms this is P^T*A*P, P^T*A or A*P with P the matrix of Sparsity.permutation(p). With invert_permutation the inverse of p is used instead, so that pmult(p, True, True, True) is the pattern of A[p, p].

Parameters
pPermutation vector; its length must equal the number of rows (if permute_rows) and the number of columns (if permute_columns)
permute_rowsPermute the rows
permute_columnsPermute the columns
invert_permutationUse the inverse permutation

>>> A = Sparsity.triplet(3, 3, [0, 1, 2, 0], [1, 2, 0, 0])
>>> DM(A, 1)
DM(
[[1, 1, 00],
 [00, 00, 1],
 [1, 00, 00]])
>>> p = [2, 0, 1]
>>> DM(A.pmult(p), 1)
DM(
[[00, 1, 00],
 [00, 00, 1],
 [1, 00, 1]])
>>> P = DM(Sparsity.permutation(p), 1)
>>> A.pmult(p) == (P.T @ DM(A, 1) @ P).sparsity()
True
>>> A.pmult(p, True, True, True) == A.sub(p, p)[0]
True
>>> DM(A.pmult(p, True, False), 1)
DM(
[[00, 00, 1],
 [1, 00, 00],
 [1, 1, 00]])

>> A = Sparsity.triplet(3, 3, [0, 1, 2, 0], [1, 2, 0, 0]);
>> DM(A, 1)
[[1, 1, 00],
 [00, 00, 1],
 [1, 00, 00]]
>> p = [2, 0, 1];
>> DM(A.pmult(p), 1)
[[00, 1, 00],
 [00, 00, 1],
 [1, 00, 1]]
>> P = DM(Sparsity.permutation(p), 1);
>> A.pmult(p) == sparsity(P' * DM(A, 1) * P)
1
>> [sub, mapping] = A.sub(p, p); disp(A.pmult(p, true, true, true) == sub)
1
>> DM(A.pmult(p, true, false), 1)
[[00, 00, 1],
 [1, 00, 00],
 [1, 1, 00]]

julia> A = ca.Sparsity.triplet(3, 3, [0, 1, 2, 0], [1, 2, 0, 0]);
julia> ca.DM(A, 1)
DM(
[[1, 1, 00],
 [00, 00, 1],
 [1, 00, 00]])
julia> p = [2, 0, 1];
julia> ca.DM(ca.pmult(A, p), 1)
DM(
[[00, 1, 00],
 [00, 00, 1],
 [1, 00, 1]])
julia> P = ca.DM(ca.Sparsity.permutation(p), 1);
julia> ca.is_equal(ca.pmult(A, p), ca.sparsity(P' * ca.DM(A, 1) * P))
true
julia> ca.is_equal(ca.pmult(A, p, true, true, true), first(ca.sub(A, p, p)))
true
julia> ca.DM(ca.pmult(A, p, true, false), 1)
DM(
[[00, 00, 1],
 [1, 00, 00],
 [1, 1, 00]])

See also
permutation, sub

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

Definition at line 793 of file sparsity.cpp.

794  {
795  return (*this)->pmult(p, permute_rows, permute_columns, invert_permutation);
796  }

References casadi::invert_permutation(), and casadi::SparsityInternal::pmult().

Referenced by casadi::SparsityInternal::star_coloring(), and casadi::SparsityInternal::star_coloring2().

◆ postfix_dim()

std::string casadi::Sparsity::postfix_dim ( ) const

Rules:

  1. Dense scalar: ""
  2. 0-by-0: "[]"
  3. Dense column vector: "[5]"
  4. Other dense pattern: "[5x10]"
  5. Otherwise: "[5x10,3nz]"

>>> repr(Sparsity.dense(1, 1).postfix_dim()), repr(Sparsity(0, 0).postfix_dim())
("''", "'[]'")
>>> Sparsity.dense(5).postfix_dim(), Sparsity.dense(5, 10).postfix_dim()
('[5]', '[5x10]')
>>> Sparsity.diag(5, 10).postfix_dim(), Sparsity(1, 1).postfix_dim()
('[5x10,5nz]', '[1x1,0nz]')
>>> Sparsity.dense(1, 5).postfix_dim(), Sparsity(0, 3).postfix_dim()
('[1x5]', '[0x3]')

>> fprintf('"%s" "%s"\n', Sparsity.dense(1, 1).postfix_dim(), Sparsity(0, 0).postfix_dim())
"" "[]"
>> Sparsity.dense(5).postfix_dim(), Sparsity.dense(5, 10).postfix_dim()
[5]
[5x10]
>> Sparsity.diag(5, 10).postfix_dim(), Sparsity(1, 1).postfix_dim()
[5x10,5nz]
[1x1,0nz]
>> Sparsity.dense(1, 5).postfix_dim(), Sparsity(0, 3).postfix_dim()
[1x5]
[0x3]

julia> ca.postfix_dim(ca.Sparsity.dense(1, 1)), ca.postfix_dim(ca.Sparsity(0, 0))
("", "[]")
julia> ca.postfix_dim(ca.Sparsity.dense(5)), ca.postfix_dim(ca.Sparsity.dense(5, 10))
("[5]", "[5x10]")
julia> ca.postfix_dim(ca.Sparsity.diag(5, 10)), ca.postfix_dim(ca.Sparsity(1, 1))
("[5x10,5nz]", "[1x1,0nz]")
julia> ca.postfix_dim(ca.Sparsity.dense(1, 5)), ca.postfix_dim(ca.Sparsity(0, 3))
("[1x5]", "[0x3]")

See also
dim

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

Definition at line 599 of file sparsity.cpp.

599  {
600  if (is_dense()) {
601  if (is_scalar()) {
602  return "";
603  } else if (is_empty(true)) {
604  return "[]";
605  } else if (is_column()) {
606  return "[" + str(size1()) + "]";
607  } else {
608  return "[" + dim(false) + "]";
609  }
610  } else {
611  return "[" + dim(true) + "]";
612  }
613  }
bool is_scalar(bool scalar_and_dense=false) const
Check whether the pattern is 1-by-1.
Definition: sparsity.cpp:271

References dim(), is_column(), is_dense(), is_empty(), is_scalar(), size1(), 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().

◆ qr_sparse()

void casadi::Sparsity::qr_sparse ( Sparsity &  V,
Sparsity &  R,
std::vector< casadi_int > &  prinv,
std::vector< casadi_int > &  pc,
bool  amd = true 
) const

Computes the patterns of V (the Householder vectors, a compact representation of Q) and R for the factorization of this pattern with its columns permuted by pc, plus the row permutation prinv used by the numerical factorization (qr_sparse on a matrix) and solution. V and R may have more rows than the pattern (the matrix is extended with zero rows when it has fewer rows than columns in the structural sense).

Parameters
amdIf true (default), the columns are reordered with the AMD ordering of A^T*A, returned in pc; if false, pc is the identity
Returns
V, R, prinv, pc

>>> V, R, prinv, pc = Sparsity.dense(3, 2).qr_sparse()
>>> V, R, prinv, pc
(Sparsity(3x2,5nz), Sparsity(3x2,3nz), [0, 1, 2], [0, 1])
>>> V, R, prinv, pc = Sparsity.banded(4, 1).qr_sparse(False)
>>> V, R, prinv, pc
(Sparsity(4x4,7nz), Sparsity(4x4,9nz), [0, 1, 2, 3], [0, 1, 2, 3])

>> [V, R, prinv, pc] = Sparsity.dense(3, 2).qr_sparse();
>> V, R, prinv, pc
3x2,5nz
3x2,3nz
0 1 2
0 1
>> [V, R, prinv, pc] = Sparsity.banded(4, 1).qr_sparse(false);
>> V, R, prinv, pc
4x4,7nz
4x4,9nz
0 1 2 3
0 1 2 3

julia> V, R, prinv, pc = ca.qr_sparse(ca.Sparsity.dense(3, 2));
julia> V, R, prinv, pc
(3x2,5nz, 3x2,3nz, [0, 1, 2], [0, 1])
julia> V, R, prinv, pc = ca.qr_sparse(ca.Sparsity.banded(4, 1), false);
julia> V, R, prinv, pc
(4x4,7nz, 4x4,9nz, [0, 1, 2, 3], [0, 1, 2, 3])

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

See also
ldl, amd, etree

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

Definition at line 663 of file sparsity.cpp.

665  {
666  // Dimensions
667  casadi_int size1=this->size1(), size2=this->size2();
668 
669  // Recursive call if AMD
670  if (amd) {
671  // Get AMD reordering
672  pc = mtimes(T(), *this).amd();
673  // Permute sparsity pattern
674  std::vector<casadi_int> tmp;
675  Sparsity Aperm = sub(range(size1), pc, tmp);
676  // Call recursively
677  Aperm.qr_sparse(V, R, prinv, tmp, false);
678  return;
679  }
680 
681  // No column permutation
682  pc = range(size2);
683 
684  // Allocate memory
685  std::vector<casadi_int> leftmost(size1);
686  std::vector<casadi_int> parent(size2);
687  prinv.resize(size1 + size2);
688  std::vector<casadi_int> iw(size1 + 7*size2 + 1);
689 
690  // Initialize QP solve
691  casadi_int nrow_ext, v_nnz, r_nnz;
692  SparsityInternal::qr_init(*this, T(),
693  get_ptr(leftmost), get_ptr(parent), get_ptr(prinv),
694  &nrow_ext, &v_nnz, &r_nnz, get_ptr(iw));
695 
696  // Calculate sparsities
697  std::vector<casadi_int> sp_v(2 + size2 + 1 + v_nnz);
698  std::vector<casadi_int> sp_r(2 + size2 + 1 + r_nnz);
699  SparsityInternal::qr_sparsities(*this, nrow_ext, get_ptr(sp_v), get_ptr(sp_r),
700  get_ptr(leftmost), get_ptr(parent), get_ptr(prinv),
701  get_ptr(iw));
702  prinv.resize(nrow_ext);
703  V = compressed(sp_v, true);
704  R = compressed(sp_r, true);
705  }
static void qr_init(const casadi_int *sp, const casadi_int *sp_tr, casadi_int *leftmost, casadi_int *parent, casadi_int *pinv, casadi_int *nrow_ext, casadi_int *v_nnz, casadi_int *r_nnz, casadi_int *w)
Setup QP solver.
static void qr_sparsities(const casadi_int *sp_a, casadi_int nrow_ext, casadi_int *sp_v, casadi_int *sp_r, const casadi_int *leftmost, const casadi_int *parent, const casadi_int *pinv, casadi_int *iw)
Get the row indices for V and R in QR factorization.
static Sparsity mtimes(const Sparsity &x, const Sparsity &y, const std::string &blas="reference")
Accessed by SparsityInterface.
Definition: sparsity.cpp:432

References amd(), compressed(), casadi::get_ptr(), mtimes(), casadi::SparsityInternal::qr_init(), qr_sparse(), casadi::SparsityInternal::qr_sparsities(), casadi::range(), size1(), size2(), sub(), and T().

Referenced by casadi::FastNewton::init(), casadi::LinsolQr::init(), casadi::Qrqp::init(), and qr_sparse().

◆ removeDuplicates()

void casadi::Sparsity::removeDuplicates ( std::vector< casadi_int > &  mapping)

Patterns created through the public interface have no duplicates, so this is a no-op for them. The entries of mapping (one per nonzero) corresponding to the removed duplicates are removed as well.

Parameters
mappingVector of length nnz(), filtered in the same way as the nonzeros

>>> sp = Sparsity.banded(3, 1)
>>> m = sp.removeDuplicates([0, 1, 2, 3, 4, 5, 6])
>>> m, sp
([0, 1, 2, 3, 4, 5, 6], Sparsity(3x3,7nz))

>> sp = Sparsity.banded(3, 1);
>> m = sp.removeDuplicates([0, 1, 2, 3, 4, 5, 6]);
>> m, sp
0 1 2 3 4 5 6
3x3,7nz

julia> sp = ca.Sparsity.banded(3, 1);
julia> m = ca.removeDuplicates(sp, [0, 1, 2, 3, 4, 5, 6]);
julia> m, sp
([0, 1, 2, 3, 4, 5, 6], 3x3,7nz)

See also
rowsSequential, triplet

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

Definition at line 743 of file sparsity.cpp.

743  {
744  *this = (*this)->_removeDuplicates(mapping);
745  }

◆ repr_el()

std::string casadi::Sparsity::repr_el ( casadi_int  k) const

Gives "(row i, col j)", prefixed with "nonzero index k " when the pattern is not dense. Indices follow the global start_index option (zero-based by default). k must be in [0, nnz()); it is not checked.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sp.repr_el(1)
'nonzero index 1 (row 2, col 0)'
>>> Sparsity.dense(2, 2).repr_el(3)
'(row 1, col 1)'

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> sp.repr_el(1)
nonzero index 2 (row 3, col 1)
>> Sparsity.dense(2, 2).repr_el(3)
(row 2, col 2)

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.repr_el(sp, 1)
"nonzero index 1 (row 2, col 0)"
julia> ca.repr_el(ca.Sparsity.dense(2, 2), 3)
"(row 1, col 1)"

See also
dim, get_nz

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

Definition at line 615 of file sparsity.cpp.

615  {
616  casadi_assert(k>=0 && k<nnz(),
617  "Index " + str(k) + " out of range for " + str(nnz()) + " nonzeros.");
618  return (*this)->repr_el(k);
619  }

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

Referenced by casadi::OracleFunction::calc_function().

◆ reshape() [1/2]

Sparsity casadi::Sparsity::reshape ( const Sparsity &  x,
casadi_int  nrow,
casadi_int  ncol 
)
static

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

Definition at line 262 of file sparsity.cpp.

262  {
263  return x->_reshape(nrow, ncol);
264  }

References casadi::SparsityInternal::_reshape().

Referenced by casadi::MX::reshape().

◆ reshape() [2/2]

Sparsity casadi::Sparsity::reshape ( const Sparsity &  x,
const Sparsity &  sp 
)
static

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

Definition at line 252 of file sparsity.cpp.

252  {
253  casadi_assert_dev(x.is_reshape(sp));
254  return sp;
255  }

References is_reshape().

◆ resize()

void casadi::Sparsity::resize ( casadi_int  nrow,
casadi_int  ncol 
)

Nonzeros with row >= nrow or column >= ncol are dropped; growing adds structural zeros. Unlike reshape, the (row, col) position of the kept nonzeros is unchanged. The object is rebound to the new pattern; other references to the old pattern are unaffected.

Parameters
nrowNew number of rows, nonnegative
ncolNew number of columns, nonnegative

>>> sp = Sparsity.dense(3, 3); sp.resize(2, 2); print(sp)
2x2
>>> sp.resize(4, 4); print(DM(sp, 1))
[[1, 1, 00, 00], 
 [1, 1, 00, 00], 
 [00, 00, 00, 00], 
 [00, 00, 00, 00]]
>>> sp.resize(0, 2); print(sp)
0x2

>> sp = Sparsity.dense(3, 3); sp.resize(2, 2); disp(sp)
2x2
>> sp.resize(4, 4); disp(DM(sp, 1))
[[1, 1, 00, 00],
 [1, 1, 00, 00],
 [00, 00, 00, 00],
 [00, 00, 00, 00]]
>> sp.resize(0, 2); disp(sp)
0x2

julia> sp = ca.Sparsity.dense(3, 3); ca.resize(sp, 2, 2); sp
Sparsity(2x2)
julia> ca.resize(sp, 4, 4); ca.DM(sp, 1)
DM(
[[1, 1, 00, 00],
 [1, 1, 00, 00],
 [00, 00, 00, 00],
 [00, 00, 00, 00]])
julia> ca.resize(sp, 0, 2); sp
Sparsity(0x2)

See also
enlarge, reshape

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

Definition at line 190 of file sparsity.cpp.

190  {
191  if (size1()!=nrow || size2() != ncol) {
192  *this = (*this)->_resize(nrow, ncol);
193  }
194  }

References size1(), and size2().

Referenced by casadi::SparsityInternal::combineGen1(), casadi::SparsityInternal::dmperm(), and casadi::SparsityInternal::pmult().

◆ row() [1/2]

const casadi_int * casadi::Sparsity::row ( ) const

containing rows for all non-zero elements (see class description)

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

Definition at line 166 of file sparsity.cpp.

166  {
167  return (*this)->row();
168  }

Referenced by casadi::SparsityInternal::_mtimes(), casadi::GetNonzeros::ad_forward(), casadi::SetNonzeros< Add >::ad_forward(), casadi::SetNonzeros< Add >::ad_reverse(), add(), add_nz(), band(), casadi::SparsityInternal::bfs(), casadi::KinsolInterface::bjac(), bor(), casadi::Blocksqp::calcHessianUpdateExact(), casadi::Blocksqp::calcLagrangeGradient(), casadi::casadi_func_cons_jac(), casadi::SparsityInternal::combineGen(), compressed(), casadi::ConoptInterface::ConoptInterface(), casadi::construct_nlpsol(), casadi::IndexReduction::dae_struct_detect(), dense(), casadi::detect_simple_bounds_gen(), diag(), diagcat(), casadi::KinsolInterface::djac(), casadi::BonminUserClass::eval_h(), casadi::IpoptUserClass::eval_h(), casadi::AlpaqaProblem::eval_hess_L(), casadi::AlpaqaProblem::eval_hess_ψ(), casadi::AlpaqaProblem::eval_jac_g(), casadi::BonminUserClass::eval_jac_g(), casadi::IpoptUserClass::eval_jac_g(), casadi::GetNonzeros::eval_mx(), casadi::SetNonzeros< Add >::eval_mx(), casadi::FmuFunction::eval_task(), casadi::FmuFunction::finalize_hessian(), from_file(), get_ccs(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::FunctionInternal::get_sparsity_out(), get_triplet(), horzsplit(), casadi::SqicInterface::init(), casadi::FmuFunction::init(), casadi::AmplInterface::init(), casadi::Blocksqp::init(), casadi::ConoptInterface::init(), casadi::FatropConicInterface::init(), casadi::HpipmInterface::init(), casadi::HpmpcInterface::init(), casadi::SuperscsInterface::init(), casadi::ClarabelInterface::init_dependent(), casadi::HighsInterface::init_dependent(), casadi::MosekInterface::init_dependent(), casadi::XpressInterface::init_dependent(), casadi::CplexInterface::init_mem(), is_compactible(), is_equal(), casadi::SparsityInternal::is_equal(), casadi::SparsityInternal::is_stacked(), casadi::XFunction< DerivedType, MatType, NodeType >::jac(), kron(), kron_contract(), lower(), casadi::mul_bvec_fwd(), mul_sparsityR(), casadi::SparsityInternal::multiply(), nonzeros(), norm_0_mul(), casadi::FunctionInternal::print_canonical(), casadi::Matrix< Scalar >::print_dense(), casadi::Matrix< Scalar >::print_sparse(), casadi::Matrix< Scalar >::print_vector(), casadi::CvodesInterface::psetupF(), casadi::IdasInterface::psetupF(), casadi::GenericMatrix< MatType >::row(), row(), rowcol(), casadi::Conic::sdp_to_socp_init(), set(), casadi::WorhpInterface::set_work(), casadi::CbcInterface::solve(), casadi::ClpInterface::solve(), casadi::CplexInterface::solve(), casadi::GurobiInterface::solve(), casadi::OoqpInterface::solve(), casadi::QpoasesInterface::solve(), casadi::SuperscsInterface::solve(), casadi::ConoptInterface::solve(), casadi::WorhpInterface::solve(), casadi::Blocksqp::solveQP(), casadi::KronContract::sp_forward(), casadi::Rank1::sp_forward(), casadi::Solve< Tr >::sp_forward(), casadi::FunctionInternal::sp_forward_block(), casadi::KronContract::sp_reverse(), casadi::Rank1::sp_reverse(), casadi::Solve< Tr >::sp_reverse(), casadi::FunctionInternal::sp_reverse(), Sparsity(), casadi::SparsityInternal::star_coloring_new(), to_file(), triplet(), casadi::SparsityInternal::uni_coloring(), unit(), casadi::DaeBuilderInternal::update_dependencies(), and upper().

◆ row() [2/2]

casadi_int casadi::Sparsity::row ( casadi_int  el) const
Parameters
elNonzero index, in [0, nnz()); out of range raises an error
See also
colind, get_row

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

Definition at line 174 of file sparsity.cpp.

174  {
175  if (el<0 || el>=nnz()) {
176  throw std::out_of_range("Sparsity::row: Index " + str(el)
177  + " out of range [0," + str(nnz()) + ")");
178  }
179  return row()[el];
180  }

References nnz(), row(), and casadi::str().

◆ rowcol()

Sparsity casadi::Sparsity::rowcol ( const std::vector< casadi_int > &  row,
const std::vector< casadi_int > &  col,
casadi_int  nrow,
casadi_int  ncol 
)
static

Every combination of a row index and a column index becomes a nonzero; the block need not be contiguous. Duplicate indices are merged.

Parameters
rowRow indices, each in [0, nrow)
colColumn indices, each in [0, ncol)
nrowNumber of rows of the pattern
ncolNumber of columns of the pattern

>>> DM(Sparsity.rowcol([0, 2], [1, 2], 3, 4), 1)
DM(
[[00, 1, 1, 00],
 [00, 00, 00, 00],
 [00, 1, 1, 00]])
>>> Sparsity.rowcol([], [1], 3, 4).nnz()
0

>> DM(Sparsity.rowcol([0, 2], [1, 2], 3, 4), 1)
[[00, 1, 1, 00],
 [00, 00, 00, 00],
 [00, 1, 1, 00]]
>> Sparsity.rowcol([], [1], 3, 4).nnz()
0

julia> ca.DM(ca.Sparsity.rowcol([0, 2], [1, 2], 3, 4), 1)
DM(
[[00, 1, 1, 00],
 [00, 00, 00, 00],
 [00, 1, 1, 00]])
julia> ca.nnz(ca.Sparsity.rowcol([], [1], 3, 4))
0

See also
triplet

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

Definition at line 1141 of file sparsity.cpp.

1142  {
1143  std::vector<casadi_int> all_rows, all_cols;
1144  all_rows.reserve(row.size()*col.size());
1145  all_cols.reserve(row.size()*col.size());
1146  for (std::vector<casadi_int>::const_iterator c_it=col.begin(); c_it!=col.end(); ++c_it) {
1147  casadi_assert(*c_it>=0 && *c_it<ncol, "Sparsity::rowcol: Column index out of bounds");
1148  for (std::vector<casadi_int>::const_iterator r_it=row.begin(); r_it!=row.end(); ++r_it) {
1149  casadi_assert(*r_it>=0 && *r_it<nrow, "Sparsity::rowcol: Row index out of bounds");
1150  all_rows.push_back(*r_it);
1151  all_cols.push_back(*c_it);
1152  }
1153  }
1154  return Sparsity::triplet(nrow, ncol, all_rows, all_cols);
1155  }

References row(), and triplet().

◆ rows()

casadi_int casadi::Sparsity::rows ( ) const
inline

Definition at line 1543 of file sparsity.hpp.

1543 {return size1();}

◆ rowsSequential()

bool casadi::Sparsity::rowsSequential ( bool  strictly = true) const

A pattern constructed through the public interface always satisfies this: row indices are sorted and unique within a column.

Parameters
strictlyIf true (default), duplicate rows within a column are not allowed

>>> Sparsity.banded(3, 1).rowsSequential()
True
>>> Sparsity.dense(2, 2).rowsSequential(False)
True

>> Sparsity.banded(3, 1).rowsSequential()
1
>> Sparsity.dense(2, 2).rowsSequential(false)
1

julia> ca.rowsSequential(ca.Sparsity.banded(3, 1))
true
julia> ca.rowsSequential(ca.Sparsity.dense(2, 2), false)
true

See also
removeDuplicates

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

Definition at line 739 of file sparsity.cpp.

739  {
740  return (*this)->rowsSequential(strictly);
741  }

◆ scalar()

static Sparsity casadi::Sparsity::scalar ( bool  dense_scalar = true)
inlinestatic
Parameters
dense_scalarIf true (default), the single entry is a nonzero; if false, the pattern is 1-by-1 with zero nonzeros (a structurally zero scalar)

>>> Sparsity.scalar(), Sparsity.scalar().nnz()
(Sparsity(1x1), 1)
>>> Sparsity.scalar(False), Sparsity.scalar(False).nnz()
(Sparsity(1x1,0nz), 0)
>>> Sparsity.scalar() == Sparsity.dense(1, 1)
True

>> Sparsity.scalar(), Sparsity.scalar().nnz()
1x1
1
>> Sparsity.scalar(false), Sparsity.scalar(false).nnz()
1x1,0nz
0
>> Sparsity.scalar() == Sparsity.dense(1, 1)
1

julia> ca.Sparsity.scalar(), ca.nnz(ca.Sparsity.scalar())
(1x1, 1)
julia> ca.Sparsity.scalar(false), ca.nnz(ca.Sparsity.scalar(false))
(1x1,0nz, 0)
julia> ca.is_equal(ca.Sparsity.scalar(), ca.Sparsity.dense(1, 1))
true

See also
dense, is_scalar

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

Definition at line 454 of file sparsity.hpp.

455  { return dense_scalar ? dense(1, 1) : Sparsity(1, 1); }

Referenced by casadi::Bilin::Bilin(), casadi::Call::Call(), casadi::Dot::Dot(), casadi::Find::Find(), casadi::FunctionInternal::get_sparsity_in(), casadi::Switch::get_sparsity_in(), casadi::FunctionInternal::get_sparsity_out(), casadi::Conic::get_sparsity_out(), casadi::MMax::MMax(), casadi::MMin::MMin(), casadi::Norm::Norm(), casadi::simpleIntegrator(), and casadi::Split::Split().

◆ scc()

casadi_int casadi::Sparsity::scc ( std::vector< casadi_int > &  index,
std::vector< casadi_int > &  offset 
) const

Node j is the j-th row/column and nonzero (i, j) is an edge from j to i. See Direct Methods for Sparse Linear Systems by Davis (2006).

Returns
The number of components n, the node indices grouped by component, and the offsets (length n+1): component i consists of the nodes index[offset[i]], ..., index[offset[i+1]-1], in increasing order.

The components are ordered so that the symmetric permutation A[index, index] is block upper triangular with n diagonal blocks; for a symmetric pattern it is block diagonal, with the block boundaries given by offset.

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

>>> A = Sparsity.nonzeros(4, 4, [0, 2, 5, 7, 10, 13, 15])
>>> DM(A, 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 1],
 [1, 00, 1, 00],
 [00, 1, 00, 1]])
>>> n, index, offset = A.scc()
>>> n, index, offset
(3, [2, 0, 1, 3], [0, 1, 2, 4])
>>> DM(A, 1)[index, index]
DM(
[[1, 1, 00, 00],
 [00, 1, 00, 00],
 [00, 00, 1, 1],
 [00, 00, 1, 1]])
>>> Sparsity.diag(3).scc(), Sparsity.dense(3, 3).scc(), Sparsity(0, 0).scc()
((3, [0, 1, 2], [0, 1, 2, 3]), (1, [0, 1, 2], [0, 3]), (0, [], [0]))

>> A = Sparsity.nonzeros(4, 4, [1, 3, 6, 8, 11, 14, 16]);
>> DM(A, 1)
[[1, 00, 00, 00],
 [00, 1, 00, 1],
 [1, 00, 1, 00],
 [00, 1, 00, 1]]
>> [n, index, offset] = A.scc(); disp(n), disp(index), disp(offset)
3
2 0 1 3
0 1 2 4
>> Af = DM(A, 1); disp(Af(index + 1, index + 1))
[[1, 1, 00, 00],
 [00, 1, 00, 00],
 [00, 00, 1, 1],
 [00, 00, 1, 1]]
>> [n, index, offset] = Sparsity.diag(3).scc(); disp(n), disp(index), disp(offset)
3
0 1 2
0 1 2 3
>> [n, index, offset] = Sparsity.dense(3, 3).scc(); disp(n), disp(index), disp(offset)
1
0 1 2
0 3
>> [n, index, offset] = Sparsity(0, 0).scc(); disp(n), disp(isempty(index)), disp(offset)
0
1
0

julia> A = ca.Sparsity.nonzeros(4, 4, [0, 2, 5, 7, 10, 13, 15]);
julia> ca.DM(A, 1)
DM(
[[1, 00, 00, 00],
 [00, 1, 00, 1],
 [1, 00, 1, 00],
 [00, 1, 00, 1]])
julia> ca.scc(A)
(3, [2, 0, 1, 3], [0, 1, 2, 4])
julia> ca.scc(ca.Sparsity.diag(3)), ca.scc(ca.Sparsity.dense(3, 3))
((3, [0, 1, 2], [0, 1, 2, 3]), (1, [0, 1, 2], [0, 3]))
julia> ca.scc(ca.Sparsity(0, 0))
(0, Int64[], [0])

See also
btf, dfs

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

Examples
matrix/scc.py.

Definition at line 714 of file sparsity.cpp.

714  {
715  casadi_assert(is_square(), "Expected a square pattern, but got " + dim() + ".");
716  return (*this)->scc(index, offset);
717  }

References dim(), is_square(), and casadi::SparsityInterface< Sparsity >::offset().

Referenced by casadi::Conic::sdp_to_socp_init(), and casadi::Convexify::setup().

◆ serialize() [1/3]

std::string casadi::Sparsity::serialize ( ) const

The string can be stored and turned back into an equal pattern with deserialize(). A null object serializes and deserializes as a null object. Pickling in Python uses this mechanism.

>>> s = Sparsity.diag(2, 3).serialize()
>>> type(s).__name__, Sparsity.deserialize(s) == Sparsity.diag(2, 3)
('str', True)
>>> Sparsity.deserialize(Sparsity().serialize()).is_null()
True
>>> import pickle
>>> pickle.loads(pickle.dumps(Sparsity.diag(2, 3)))
Sparsity(2x3,2nz)

>> s = Sparsity.diag(2, 3).serialize();
>> class(s), Sparsity.deserialize(s) == Sparsity.diag(2, 3)
char
1
>> Sparsity.deserialize(Sparsity().serialize()).is_null()
1

julia> s = ca.serialize(ca.Sparsity.diag(2, 3));
julia> typeof(s), ca.is_equal(ca.Sparsity.deserialize(s), ca.Sparsity.diag(2, 3))
(String, true)
julia> ca.is_null(ca.Sparsity.deserialize(ca.serialize(ca.Sparsity())))
true

See also
deserialize, compress

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

Definition at line 2103 of file sparsity.cpp.

2103  {
2104  std::stringstream ss;
2105  serialize(ss);
2106  return ss.str();
2107  }
std::string serialize() const
Serialize the pattern to a string.
Definition: sparsity.cpp:2103

Referenced by serialize().

◆ serialize() [2/3]

void casadi::Sparsity::serialize ( SerializingStream &  s) const

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

Definition at line 2085 of file sparsity.cpp.

2085  {
2086  if (is_null()) {
2087  s.pack("SparsityInternal::compressed", std::vector<casadi_int>{});
2088  } else {
2089  s.pack("SparsityInternal::compressed", compress());
2090  }
2091  }
std::vector< casadi_int > compress(bool canonical=true) const
Compact single-vector representation of the pattern.
Definition: sparsity.cpp:1335

References compress(), casadi::GenericShared< SharedObject, SharedObjectInternal >::is_null(), and casadi::SerializingStream::pack().

◆ serialize() [3/3]

void casadi::Sparsity::serialize ( std::ostream &  stream) const

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

Definition at line 2075 of file sparsity.cpp.

2075  {
2076  SerializingStream s(stream);
2077  serialize(s);
2078  }

References serialize().

◆ set() [1/2]

template<typename DataType >
void casadi::Sparsity::set ( DataType *  data,
const DataType *  val_data,
const Sparsity &  val_sp 
) const

Definition at line 6096 of file sparsity.hpp.

6096  {
6097  // Get dimensions of this
6098  const casadi_int sz = nnz();
6099  const casadi_int sz1 = size1();
6100  const casadi_int sz2 = size2();
6101 
6102  // Get dimensions of assigning matrix
6103  const casadi_int val_sz = val_sp.nnz();
6104  const casadi_int val_sz1 = val_sp.size1();
6105  const casadi_int val_sz2 = val_sp.size2();
6106  const casadi_int val_nel = val_sz1*val_sz2;
6107 
6108  // Check if sparsity matches
6109  if (val_sp==*this) {
6110  std::copy(val_data, val_data+sz, data);
6111  } else if (this->is_empty()) {
6112  // Quick return
6113  return;
6114  } else if (val_sp.is_empty()) {
6115  // Quick return
6116  return;
6117  } else if (val_nel==1) { // if scalar
6118  std::fill(data, data+sz, val_sz==0 ? DataType(0) : val_data[0]);
6119  } else if (sz2==val_sz2 && sz1==val_sz1) {
6120  // Matching dimensions
6121  // Sparsity
6122  const casadi_int* c = row();
6123  const casadi_int* rind = colind();
6124  const casadi_int* v_c = val_sp.row();
6125  const casadi_int* v_rind = val_sp.colind();
6126 
6127  // For all columns
6128  for (casadi_int i=0; i<sz2; ++i) {
6129 
6130  // Nonzero of the assigning matrix
6131  casadi_int v_el = v_rind[i];
6132 
6133  // First nonzero of the following column
6134  casadi_int v_el_end = v_rind[i+1];
6135 
6136  // Next row of the assigning matrix
6137  casadi_int v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6138 
6139  // Assign all nonzeros
6140  for (casadi_int el=rind[i]; el!=rind[i+1]; ++el) {
6141 
6142  // Get row
6143  casadi_int j=c[el];
6144 
6145  // Forward the assigning nonzero
6146  while (v_j<j) {
6147  v_el++;
6148  v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6149  }
6150 
6151  // Assign nonzero
6152  if (v_j==j) {
6153  data[el] = val_data[v_el++];
6154  v_j = v_el<v_el_end ? v_c[v_el] : sz1;
6155  } else {
6156  data[el] = 0;
6157  }
6158  }
6159  }
6160  } else if (sz1==val_sz2 && sz2==val_sz1 && sz2 == 1) {
6161  // Assign transposed (this is column)
6162  const casadi_int* v_cind = val_sp.colind();
6163  const casadi_int* r = row();
6164  for (casadi_int el=0; el<sz; ++el) {
6165  casadi_int rr=r[el];
6166  data[el] = v_cind[rr]==v_cind[rr+1] ? 0 : val_data[v_cind[rr]];
6167  }
6168  } else if (sz1==val_sz2 && sz2==val_sz1 && sz1 == 1) {
6169  // Assign transposed (this is row)
6170  for (casadi_int el=0; el<sz; ++el) data[el] = 0;
6171  const casadi_int* cind = colind();
6172  const casadi_int* v_r = val_sp.row();
6173  for (casadi_int el=0; el<val_sz; ++el) {
6174  casadi_int rr=v_r[el];
6175  if (cind[rr]!=cind[rr+1]) {
6176  data[cind[rr]] = val_data[el];
6177  }
6178  }
6179  } else {
6180  // Make sure that dimension matches
6181  casadi_error("Sparsity::set<DataType>: shape mismatch. lhs is "
6182  + dim() + ", while rhs is " + val_sp.dim() + ".");
6183  }
6184  }

References colind(), dim(), is_empty(), nnz(), row(), size1(), and size2().

◆ set() [2/2]

template<typename T >
void casadi::Sparsity::set ( T *  data,
const T *  val_data,
const Sparsity &  val_sp 
) const

entries of another sparsity pattern

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

Referenced by casadi::Project::sp_forward().

◆ size() [1/2]

std::pair< casadi_int, casadi_int > casadi::Sparsity::size ( ) const

◆ size() [2/2]

casadi_int casadi::Sparsity::size ( casadi_int  axis) const
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_c0

Definition at line 158 of file sparsity.cpp.

158  {
159  switch (axis) {
160  case 1: return size1();
161  case 2: return size2();
162  }
163  casadi_error("Axis must be 1 or 2.");
164  }

References size1(), and size2().

◆ size1()

casadi_int casadi::Sparsity::size1 ( ) const

>>> sp = Sparsity.diag(2, 3)
>>> sp.size1(), sp.rows(), sp.size2(), sp.columns()
(2, 2, 3, 3)

>> sp = Sparsity.diag(2, 3);
>> fprintf('%d %d %d %d\n', sp.size1(), sp.rows(), sp.size2(), sp.columns())
2 2 3 3

julia> sp = ca.Sparsity.diag(2, 3);
julia> ca.size1(sp), ca.rows(sp), ca.size2(sp), ca.columns(sp)
(2, 2, 3, 3)

See also
size2, size, numel

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

Definition at line 124 of file sparsity.cpp.

124  {
125  return (*this)->size1();
126  }

Referenced by casadi::SolveUnity< Tr >::A_sp(), casadi::GetNonzeros::ad_forward(), casadi::SetNonzeros< Add >::ad_forward(), casadi::SetNonzeros< Add >::ad_reverse(), add(), add_nz(), append(), appendColumns(), casadi::Function::assert_sparsity_out(), bor(), casadi::FunctionInternal::check_mat(), casadi::FastNewton::codegen_body(), casadi::FunctionInternal::codegen_meta(), casadi::SparsityInternal::combineGen(), compress(), casadi::Conic::Conic(), casadi::conic_kkt_res(), casadi::IndexReduction::dae_struct_detect(), density(), diagsplit(), enlargeColumns(), enlargeRows(), casadi::FunctionInternal::ensure_stacked(), etree(), casadi::DenseKronContract::eval_kernel(), casadi::DenseSparseKronContract::eval_kernel(), casadi::GetNonzeros::eval_mx(), casadi::SetNonzeros< Add >::eval_mx(), casadi::XFunction< DerivedType, MatType, NodeType >::export_code(), casadi::FmuFunction::finalize_hessian(), casadi::FunctionInternal::from_compact(), from_file(), casadi::DenseKronContract::generate(), casadi::DenseSparseKronContract::generate(), casadi::Expm::get_forward(), casadi::OnnxFunction::get_forward(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::OnnxFunction::get_jacobian(), casadi::FunctionInternal::get_partition(), casadi::Dple::get_reverse(), casadi::Expm::get_reverse(), casadi::OnnxFunction::get_reverse(), casadi::FunctionInternal::get_sparsity_out(), horzcat(), horzsplit(), info(), casadi::Dple::init(), casadi::FmuFunction::init(), casadi::Rootfinder::init(), casadi::Switch::init(), casadi::FatropInterface::init(), casadi::IpoptInterface::init(), casadi::SlicotExpm::init(), casadi::FastNewton::init(), casadi::LinsolLdl::init(), casadi::SymbolicQr::init_mem(), casadi::SparsityInternal::is_equal(), casadi::SparsityInternal::is_stacked(), casadi::FunctionInternal::jac_sparsity(), kkt(), kron(), kron_contract(), ldl(), casadi::Onnx::load(), mtimes(), casadi::mul_bvec_fwd(), mul_sparsityR(), casadi::SparsityInternal::multiply(), norm_0_mul(), casadi::Vertcat::off(), casadi::Diagcat::off(), casadi::OptiNode::parameter(), postfix_dim(), casadi::Matrix< Scalar >::print_default(), casadi::Matrix< Scalar >::print_dense(), casadi::Matrix< Scalar >::print_sparse(), casadi::Matrix< Scalar >::print_vector(), casadi::Call::projectArg(), casadi::IdasInterface::psetupF(), qr_sparse(), casadi::replace_mat(), resize(), casadi::Conic::sdp_to_socp_init(), set(), casadi::MadmpecInterface::set_ccopt_prob(), casadi::FatropInterface::set_fatrop_prob(), casadi::IpoptInterface::set_ipopt_prob(), casadi::MadnlpInterface::set_madnlp_prob(), casadi::FastNewton::set_work(), casadi::Convexify::setup(), casadi::simpleIntegrator(), size(), casadi::CbcInterface::solve(), casadi::ClpInterface::solve(), casadi::PiqpInterface::solve(), casadi::ProxqpInterface::solve(), casadi::QpoasesInterface::solve(), casadi::SuperscsInterface::solve(), casadi::KronContract::sp_forward(), casadi::Solve< Tr >::sp_forward(), casadi::Integrator::sp_jac_aug(), casadi::KronContract::sp_reverse(), casadi::Solve< Tr >::sp_reverse(), sum1(), to_file(), and casadi::OptiNode::variable().

◆ size2()

casadi_int casadi::Sparsity::size2 ( ) const

Definition at line 128 of file sparsity.cpp.

128  {
129  return (*this)->size2();
130  }

Referenced by casadi::SparsityInternal::_mtimes(), casadi::GetNonzeros::ad_forward(), casadi::SetNonzeros< Add >::ad_reverse(), add(), add_nz(), append(), appendColumns(), casadi::Function::assert_sparsity_out(), casadi::KinsolInterface::bjac(), bor(), casadi::casadi_func_cons_jac(), casadi::FunctionInternal::check_mat(), casadi::FastNewton::codegen_body(), casadi::FunctionInternal::codegen_meta(), colind(), casadi::SparsityInternal::combineGen(), compress(), casadi::Conic::Conic(), casadi::conic_kkt_res(), casadi::IndexReduction::dae_struct_detect(), density(), diagsplit(), casadi::KinsolInterface::djac(), enlargeColumns(), enlargeRows(), casadi::FunctionInternal::ensure_stacked(), etree(), casadi::Transpose::eval_gen(), casadi::BonminUserClass::eval_h(), casadi::IpoptUserClass::eval_h(), casadi::BonminUserClass::eval_jac_g(), casadi::IpoptUserClass::eval_jac_g(), casadi::DenseKronContract::eval_kernel(), casadi::DenseSparseKronContract::eval_kernel(), casadi::GetNonzeros::eval_mx(), casadi::FmuFunction::eval_task(), casadi::XFunction< DerivedType, MatType, NodeType >::export_code(), casadi::FunctionInternal::from_compact(), from_file(), casadi::DenseKronContract::generate(), casadi::DenseSparseKronContract::generate(), casadi::OnnxFunction::get_forward(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::OnnxFunction::get_jacobian(), casadi::FunctionInternal::get_partition(), casadi::OnnxFunction::get_reverse(), casadi::FunctionInternal::get_sparsity_out(), horzsplit(), info(), casadi::Dple::init(), casadi::FmuFunction::init(), casadi::FatropConicInterface::init(), casadi::FatropInterface::init(), casadi::HpipmInterface::init(), casadi::HpmpcInterface::init(), casadi::IpoptInterface::init(), casadi::SuperscsInterface::init(), casadi::FastNewton::init(), casadi::SymbolicQr::init(), casadi::ClarabelInterface::init_dependent(), casadi::HighsInterface::init_dependent(), casadi::MosekInterface::init_dependent(), casadi::XpressInterface::init_dependent(), casadi::Blocksqp::init_mem(), casadi::CbcInterface::init_mem(), casadi::ClpInterface::init_mem(), casadi::CplexInterface::init_mem(), casadi::QpoasesInterface::init_mem(), casadi::SparsityInternal::is_equal(), is_singular(), casadi::SparsityInternal::is_stacked(), casadi::XFunction< DerivedType, MatType, NodeType >::jac(), casadi::FunctionInternal::jac_sparsity(), kkt(), kron(), kron_contract(), casadi::kron_sp_gen(), casadi::Onnx::load(), mtimes(), casadi::mul_bvec_fwd(), mul_sparsityR(), casadi::SparsityInternal::multiply(), norm_0_mul(), casadi::Horzcat::off(), casadi::Diagcat::off(), casadi::OptiNode::parameter(), casadi::FunctionInternal::print_canonical(), casadi::Matrix< Scalar >::print_default(), casadi::Matrix< Scalar >::print_dense(), casadi::Matrix< Scalar >::print_sparse(), casadi::Call::projectArg(), casadi::CvodesInterface::psetupF(), qr_sparse(), casadi::replace_mat(), resize(), casadi::Conic::sdp_to_socp_init(), set(), casadi::FastNewton::set_work(), size(), casadi::CbcInterface::solve(), casadi::ClpInterface::solve(), casadi::CplexInterface::solve(), casadi::GurobiInterface::solve(), casadi::PiqpInterface::solve(), casadi::ProxqpInterface::solve(), casadi::QpoasesInterface::solve(), casadi::KronContract::sp_forward(), casadi::Rank1::sp_forward(), casadi::Transpose::sp_forward(), casadi::FunctionInternal::sp_forward_block(), casadi::Integrator::sp_jac_aug(), casadi::KronContract::sp_reverse(), casadi::Rank1::sp_reverse(), casadi::Transpose::sp_reverse(), casadi::FunctionInternal::sp_reverse(), casadi::SparsityInternal::star_coloring_new(), sum2(), to_file(), casadi::OptiNode::variable(), and vertcat().

◆ sparsity_cast()

Sparsity casadi::Sparsity::sparsity_cast ( const Sparsity &  x,
const Sparsity &  sp 
)
static

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

Definition at line 257 of file sparsity.cpp.

257  {
258  casadi_assert_dev(x.nnz()==sp.nnz());
259  return sp;
260  }

References nnz().

◆ sparsity_cast_mod()

Sparsity casadi::Sparsity::sparsity_cast_mod ( const Sparsity &  X,
const Sparsity &  Y 
) const

X and Y have the same number of nonzeros and sparsity_cast(X, Y) maps nonzero k of X to nonzero k of Y. Given that this pattern is a subset of X, the result is the subset of Y made of the nonzeros of Y whose counterpart in X is in this pattern.

>>> X = Sparsity.diag(4)
>>> Y = Sparsity.dense(2, 2)
>>> x = Sparsity.nonzeros(4, 4, [0, 10, 15])
>>> DM(x.sparsity_cast_mod(X, Y), 1)
DM(
[[1, 1],
 [00, 1]])

>> X = Sparsity.diag(4);
>> Y = Sparsity.dense(2, 2);
>> x = Sparsity.nonzeros(4, 4, [1, 11, 16]);
>> DM(x.sparsity_cast_mod(X, Y), 1)
[[1, 1],
 [00, 1]]

julia> X = ca.Sparsity.diag(4);
julia> Y = ca.Sparsity.dense(2, 2);
julia> x = ca.Sparsity.nonzeros(4, 4, [0, 10, 15]);
julia> ca.DM(ca.sparsity_cast_mod(x, X, Y), 1)
DM(
[[1, 1],
 [00, 1]])

See also
sparsity_cast, is_subset

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

Definition at line 1940 of file sparsity.cpp.

1940  {
1941  const Sparsity& x = *this;
1942  if (X==x) return Y;
1943  if (X==Y) return x;
1944  std::vector<unsigned char> mapping;
1945  X.unite(x, mapping);
1946 
1947 
1948  const casadi_int* Y_colind = Y.colind();
1949  const casadi_int* Y_row = Y.row();
1950  std::vector<casadi_int> y_colind(Y.size2()+1, 0);
1951  std::vector<casadi_int> y_row;
1952  y_row.reserve(Y.nnz());
1953  casadi_assert_dev(Y.nnz()==mapping.size());
1954 
1955  casadi_int i = 0;
1956  // Loop over columns of Y
1957  for (casadi_int cc=0; cc<Y.size2(); ++cc) {
1958  y_colind[cc+1] = y_colind[cc];
1959  // Loop over nonzeros of Y in column cc
1960  for (casadi_int kk=Y_colind[cc]; kk<Y_colind[cc+1]; ++kk) {
1961  // Get corresponding map entry
1962  casadi_int e = mapping[i++];
1963  if (e==3) {
1964  // Preserve element
1965  y_colind[cc+1]++;
1966  y_row.push_back(Y_row[kk]);
1967  } else {
1968  casadi_assert_dev(e==1);
1969  }
1970  }
1971  }
1972 
1973  Sparsity ret(Y.size1(), Y.size2(), y_colind, y_row, true);
1974  return ret;
1975  }

References casadi::X, and casadi::Y.

Referenced by casadi::SparsityCast::ad_forward(), casadi::SparsityCast::ad_reverse(), and casadi::SparsityCast::eval_mx().

◆ sprank()

casadi_int casadi::Sparsity::sprank ( const Sparsity &  x)
static

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

Definition at line 1734 of file sparsity.cpp.

1734  {
1735  std::vector<casadi_int> rowperm, colperm, rowblock, colblock, coarse_rowblock, coarse_colblock;
1736  x.btf(rowperm, colperm, rowblock, colblock, coarse_rowblock, coarse_colblock);
1737  return coarse_colblock.at(3);
1738  }

References btf().

Referenced by is_singular(), and casadi::GenericMatrix< MatType >::sprank().

◆ spsolve()

void casadi::Sparsity::spsolve ( bvec_t *  X,
bvec_t *  B,
bool  tr 
) const

◆ spy()

void casadi::Sparsity::spy ( std::ostream &  stream = casadi::uout()) const

Writes one line per row, with "*" for a structural nonzero and "." for a structural zero, to the standard output (or the given stream). Large patterns produce nrow lines of ncol characters.

See also
spy_matlab, export_code

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

Definition at line 807 of file sparsity.cpp.

807  {
808  (*this)->spy(stream);
809  }

◆ spy_matlab()

void casadi::Sparsity::spy_matlab ( const std::string &  mfile) const

The file is overwritten. The script defines a sparse matrix A of ones with this pattern (see export_code) and ends with spy(A).

Parameters
mfilePath of the .m file to write

>>> import os, tempfile
>>> d = tempfile.mkdtemp()
>>> f = os.path.join(d, "show_pattern.m")
>>> Sparsity.diag(2, 3).spy_matlab(f)
>>> print(open(f).read())
% This function was automatically generated by CasADi
A_m = 2;
A_n = 3;
A_j = [1, 2];
A_i = [1, 2];
A_v = ones(size(A_i));
A = sparse(A_i, A_j, A_v, A_m, A_n);
spy(A);
>>> os.remove(f); os.rmdir(d)

>> f = [tempname '.m'];
>> Sparsity.diag(2, 3).spy_matlab(f);
>> fileread(f)
% This function was automatically generated by CasADi
A_m = 2;
A_n = 3;
A_j = [1, 2];
A_i = [1, 2];
A_v = ones(size(A_i));
A = sparse(A_i, A_j, A_v, A_m, A_n);
spy(A);
>> delete(f);

julia> d = mktempdir();
julia> f = joinpath(d, "show_pattern.m");
julia> ca.spy_matlab(ca.Sparsity.diag(2, 3), f)
julia> print(read(f, String))
% This function was automatically generated by CasADi
A_m = 2;
A_n = 3;
A_j = [1, 2];
A_i = [1, 2];
A_v = ones(size(A_i));
A = sparse(A_i, A_j, A_v, A_m, A_n);
spy(A);
julia> rm(d, recursive=true)

See also
spy, export_code

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

Definition at line 798 of file sparsity.cpp.

798  {
799  (*this)->spy_matlab(mfile);
800  }

◆ star_coloring()

Sparsity casadi::Sparsity::star_coloring ( casadi_int  ordering = 1,
casadi_int  cutoff = std::numeric_limits<casadi_int>::max() 
) const

Algorithm 4.1 in Gebremedhin, Manne and Pothen, What Color Is Your Jacobian?, SIAM Rev. 47(4), 2006. Exploits symmetry so that fewer colors than uni_coloring are needed to recover all nonzeros of a Hessian. A non-symmetric pattern raises an error.

Parameters
ordering0 for the natural column order, 1 (default) to color in largest_first() order
cutoffIf more than this many colors are needed, a null Sparsity is returned
Returns
A size2()-by-ncolors pattern: column c lists the columns with color c

>>> H = Sparsity.banded(4, 1)
>>> DM(H.star_coloring(), 1)
DM(
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
>>> Sparsity.diag(5).star_coloring()
Sparsity(5x1)
>>> Sparsity.dense(4, 4).star_coloring(1, 2).is_null()
True

>> H = Sparsity.banded(4, 1);
>> DM(H.star_coloring(), 1)
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]]
>> Sparsity.diag(5).star_coloring()
5x1
>> Sparsity.dense(4, 4).star_coloring(1, 2).is_null()
1

julia> H = ca.Sparsity.banded(4, 1);
julia> ca.DM(ca.star_coloring(H, 1, 1000), 1)
DM(
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
julia> ca.star_coloring(ca.Sparsity.diag(5), 1, 1000)
Sparsity(5x1)
julia> ca.is_null(ca.star_coloring(ca.Sparsity.dense(4, 4), 0, 2))
true

See also
star_coloring_new, star_coloring2, uni_coloring, largest_first

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

Definition at line 781 of file sparsity.cpp.

781  {
782  return (*this)->star_coloring(ordering, cutoff);
783  }

References casadi::SparsityInternal::star_coloring().

Referenced by casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::FunctionInternal::get_partition(), and casadi::SparsityInternal::star_coloring().

◆ star_coloring2()

Sparsity casadi::Sparsity::star_coloring2 ( casadi_int  ordering = 1,
casadi_int  cutoff = std::numeric_limits<casadi_int>::max() 
) const

Algorithm 4.1 in Gebremedhin, Tarafdar, Manne and Pothen, New Acyclic and Star Coloring Algorithms with Application to Computing Hessians, SIAM J. Sci. Comput. 29(3), 2007. Same arguments and return value as star_coloring.

>>> H = Sparsity.banded(4, 1)
>>> DM(H.star_coloring2(), 1)
DM(
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])

>> H = Sparsity.banded(4, 1);
>> DM(H.star_coloring2(), 1)
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]]

julia> H = ca.Sparsity.banded(4, 1);
julia> ca.DM(ca.star_coloring2(H, 1, 1000), 1)
DM(
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])

See also
star_coloring, star_coloring_new

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

Definition at line 785 of file sparsity.cpp.

785  {
786  return (*this)->star_coloring2(ordering, cutoff);
787  }

References casadi::SparsityInternal::star_coloring2().

Referenced by casadi::SparsityInternal::star_coloring2().

◆ star_coloring_new()

Sparsity casadi::Sparsity::star_coloring_new ( std::vector< casadi_int > &  which_color,
const Dict &  opts = Dict() 
) const

Front end to star_coloring and star_coloring2 for compressed Hessian evaluation. A non-symmetric pattern raises an error.

Parameters
optsOptions: "new_algo" (bool, default false) selects star_coloring2 instead of star_coloring; "largest_first" (bool, default true) selects the largest-first ordering; "cutoff" (int) returns a null pattern when more colors are needed
Returns
The coloring (a size2()-by-ncolors pattern as in uni_coloring) and which_color, one entry per nonzero: the color whose directional derivative yields that nonzero, or -1 when the nonzero is obtained from its symmetric counterpart instead (the lowest color index is preferred)

>>> H = Sparsity.banded(4, 1)
>>> coloring, which_color = H.star_coloring_new()
>>> DM(coloring, 1)
DM(
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]])
>>> for k in range(H.nnz()): print(H.row()[k], H.get_col()[k], which_color[k])
0 0 1
1 0 -1
0 1 0
1 1 0
2 1 0
1 2 -1
2 2 1
3 2 1
2 3 -1
3 3 2
>>> try: Sparsity.upper(3).star_coloring_new()
... except Exception as e: print("not symmetric")
not symmetric

>> H = Sparsity.banded(4, 1);
>> [coloring, which_color] = H.star_coloring_new();
>> DM(coloring, 1)
[[00, 1, 00],
 [1, 00, 00],
 [00, 1, 00],
 [00, 00, 1]]
>> [H.row(); H.get_col(); which_color]'
0 0 1
1 0 -1
0 1 0
1 1 0
2 1 0
1 2 -1
2 2 1
3 2 1
2 3 -1
3 3 2
>> try, Sparsity.upper(3).star_coloring_new(); catch e, disp('not symmetric'); end
not symmetric

julia> H = ca.Sparsity.banded(4, 1);
julia> ca.star_coloring_new(H)
(4x3,4nz, [1, -1, 0, 0, 0, -1, 1, 1, -1, 2])
julia> try
           ca.star_coloring_new(ca.Sparsity.upper(3))
       catch e
           println("not symmetric")
       end
not symmetric

See also
star_coloring, star_coloring2, uni_coloring

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

Definition at line 772 of file sparsity.cpp.

773  {
774  try {
775  return (*this)->star_coloring_new(which_color, opts);
776  } catch (std::exception &e) {
777  CASADI_THROW_ERROR("star_coloring_new", e.what());
778  }
779  }

References casadi::SparsityInternal::star_coloring_new().

Referenced by casadi::FmuFunction::init().

◆ sub() [1/2]

Sparsity casadi::Sparsity::sub ( const std::vector< casadi_int > &  rr,
const Sparsity &  sp,
std::vector< casadi_int > &  mapping,
bool  ind1 = false 
) const

rr lists one flat (column-major) element index per nonzero of sp. The result has the shape of sp and keeps the nonzeros of sp whose element in this pattern is a structural nonzero. This is the sparsity counterpart of indexing a matrix with a Sparsity or with a list of element indices.

Parameters
rrFlat element indices, length sp.nnz(); negative indices count from the end, out of range raises an error
spPattern that lays out the result
ind1If true, indices are one-based
Returns
The pattern and a mapping: nonzero k of the result is nonzero mapping[k] of this pattern

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sub, mapping = sp.sub([0, 2, 9], Sparsity.dense(3, 1))
>>> sub, mapping
(Sparsity(3x1), [0, 1, 3])
>>> sub, mapping = sp.sub([0, 1, 2, 3], Sparsity.dense(2, 2))
>>> DM(sub, 1), mapping
(DM(
[[1, 1],
 [00, 00]]), [0, 1])
>>> try: sp.sub([0, 2], Sparsity.dense(3, 1))
... except Exception as e: print("length mismatch")
length mismatch

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [sub, mapping] = sp.sub([0, 2, 9], Sparsity.dense(3, 1)); disp(sub), disp(mapping)
3x1
0 1 3
>> [sub, mapping] = sp.sub([0, 1, 2, 3], Sparsity.dense(2, 2));
>> DM(sub, 1), mapping
[[1, 1],
 [00, 00]]
0 1
>> try, sp.sub([0, 2], Sparsity.dense(3, 1)); catch e, disp('length mismatch'); end
length mismatch

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.sub(sp, [0, 2, 9], ca.Sparsity.dense(3, 1))
(3x1, [0, 1, 3])
julia> ca.sub(sp, [0, 1, 2, 3], ca.Sparsity.dense(2, 2))
(2x2,2nz, [0, 1])
julia> try
           ca.sub(sp, [0, 2], ca.Sparsity.dense(3, 1))
       catch e
           println("length mismatch")
       end
length mismatch

See also
get_nz, find

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

Definition at line 331 of file sparsity.cpp.

332  {
333  return (*this)->sub(rr, *sp, mapping, ind1);
334  }

References casadi::SparsityInternal::sub().

◆ sub() [2/2]

Sparsity casadi::Sparsity::sub ( const std::vector< casadi_int > &  rr,
const std::vector< casadi_int > &  cc,
std::vector< casadi_int > &  mapping,
bool  ind1 = false 
) const

This is the sparsity counterpart of slicing a matrix as A[rr, cc]. Indices may repeat and may be negative (counting from the end); an index out of range raises an error.

Parameters
rrRow indices of the submatrix
ccColumn indices of the submatrix
ind1If true, indices are one-based
Returns
The len(rr)-by-len(cc) pattern and a mapping with one entry per nonzero of the result: nonzero k of the submatrix is nonzero mapping[k] of this pattern

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> sub, mapping = sp.sub([0, 2], [0, 3])
>>> DM(sub, 1), mapping
(DM(
[[1, 1],
 [1, 00]]), [0, 1, 3])
>>> sub, mapping = sp.sub([-1], [0])
>>> sub, mapping
(Sparsity(1x1), [1])
>>> sub, mapping = sp.sub([0, 0], [0])
>>> sub, mapping
(Sparsity(2x1), [0, 0])
>>> try: sp.sub([3], [0])
... except Exception as e: print("out of range")
out of range

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [sub, mapping] = sp.sub([0, 2], [0, 3]); disp(DM(sub, 1)), disp(mapping)
[[1, 1],
 [1, 00]]
0 1 3
>> [sub, mapping] = sp.sub(-1, 0); disp(sub), disp(mapping)
1x1
1
>> [sub, mapping] = sp.sub([0, 0], 0); disp(sub), disp(mapping)
2x1
0 0
>> try, sp.sub(3, 0); catch e, disp('out of range'); end
out of range

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.sub(sp, [0, 2], [0, 3])
(2x2,3nz, [0, 1, 3])
julia> ca.sub(sp, [-1], [0])
(1x1, [1])
julia> ca.sub(sp, [0, 0], [0])
(2x1, [0, 0])
julia> try
           ca.sub(sp, [3], [0])
       catch e
           println("out of range")
       end
out of range

See also
get_nz, erase, pmult

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

Definition at line 336 of file sparsity.cpp.

337  {
338  return (*this)->sub(rr, cc, mapping, ind1);
339  }

References casadi::SparsityInternal::sub().

Referenced by casadi::Matrix< Scalar >::get(), casadi::MX::get(), casadi::FmuInternal::hess_sparsity(), casadi::LinsolLdl::init(), casadi::FmuInternal::jac_sparsity(), ldl(), qr_sparse(), casadi::Convexify::setup(), casadi::SuperscsInterface::solve(), and casadi::FunctionInternal::to_compact().

◆ sum1()

Sparsity casadi::Sparsity::sum1 ( const Sparsity &  x)
static

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

Definition at line 1730 of file sparsity.cpp.

1730  {
1731  return mtimes(Sparsity::dense(1, x.size1()), x);
1732  }

References dense(), mtimes(), and size1().

Referenced by casadi::SparsityInternal::is_compactible().

◆ sum2()

Sparsity casadi::Sparsity::sum2 ( const Sparsity &  x)
static

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

Definition at line 1726 of file sparsity.cpp.

1726  {
1727  return mtimes(x, Sparsity::dense(x.size2(), 1));
1728 
1729  }

References dense(), mtimes(), and size2().

Referenced by casadi::SparsityInternal::is_compactible().

◆ 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  }

◆ T()

Sparsity casadi::Sparsity::T ( ) const

In Python, T is a property (sp.T); the method transpose() also returns the nonzero reordering.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> DM(sp.T, 1)
DM(
[[1, 00, 1],
 [00, 00, 00],
 [00, 1, 00],
 [1, 00, 00]])
>>> sp.T.colind(), sp.T.row()
([0, 2, 3, 4], [0, 3, 2, 0])
>>> Sparsity.dense(2, 3).T, Sparsity(0, 3).T
(Sparsity(3x2), Sparsity(3x0))

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> DM(sp.T, 1)
[[1, 00, 1],
 [00, 00, 00],
 [00, 1, 00],
 [1, 00, 00]]
>> sp.T.colind(), sp.T.row()
0 2 3 4
0 3 2 0
>> Sparsity.dense(2, 3).T, Sparsity(0, 3).T
3x2
3x0

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.DM(ca.T(sp), 1)
DM(
[[1, 00, 1],
 [00, 00, 00],
 [00, 1, 00],
 [1, 00, 00]])
julia> ca.colind(ca.T(sp)), ca.row(ca.T(sp))
([0, 2, 3, 4], [0, 3, 2, 0])
julia> ca.T(ca.Sparsity.dense(2, 3)), ca.T(ca.Sparsity(0, 3))
(3x2, 3x0)

See also
transpose, is_transpose, get_crs

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

Definition at line 396 of file sparsity.cpp.

396  {
397  return (*this)->T();
398  }

References casadi::SparsityInternal::T().

Referenced by casadi::construct_nlpsol(), casadi::detect_simple_bounds_gen(), casadi::MX::get(), get_crs(), casadi::FmuFunction::get_jac_sparsity(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::Matrix< Scalar >::get_nz(), casadi::MX::get_nz(), casadi::FunctionInternal::get_partition(), casadi::FmuFunction::get_sparsity_out(), casadi::Onnx::import_symbolic(), casadi::FmuFunction::init(), casadi::AmplInterface::init(), casadi::FatropConicInterface::init(), casadi::FatropInterface::init(), casadi::HpipmInterface::init(), casadi::HpmpcInterface::init(), casadi::OoqpInterface::init(), casadi::Qrqp::init(), casadi::Scpgen::init(), casadi::XFunction< DerivedType, MatType, NodeType >::jac(), casadi::FunctionInternal::jac_sparsity(), kkt(), qr_sparse(), casadi::Convexify::setup(), casadi::Transpose::Transpose(), uni_coloring(), and vertsplit().

◆ test_cast()

bool casadi::Sparsity::test_cast ( const SharedObjectInternal *  ptr)
static

Definition at line 120 of file sparsity.cpp.

120  {
121  return dynamic_cast<const SparsityInternal*>(ptr)!=nullptr;
122  }

◆ to_file()

void casadi::Sparsity::to_file ( const std::string &  filename,
const std::string &  format_hint = "" 
) const

The only supported format is Matrix Market ("mtx", coordinate pattern general), with one-based (row, col) pairs. The format is taken from the file extension unless format_hint is given; an unknown format raises an error. The file is overwritten.

Parameters
filenamePath of the file to write
format_hintFormat name, e.g. "mtx", when the extension does not tell

>>> import os, tempfile
>>> d = tempfile.mkdtemp()
>>> f = os.path.join(d, "pattern.mtx")
>>> sp = Sparsity.triplet(3, 2, [0, 2, 1], [0, 0, 1])
>>> sp.to_file(f)
>>> print(open(f).read())
%%MatrixMarket matrix coordinate pattern general
3 2 3
1 1
3 1
2 2
>>> print(Sparsity.from_file(f) == sp)
True
>>> os.remove(f); os.rmdir(d)
>>> try: sp.to_file("pattern.txt")
... except Exception as e: print("unknown extension")
unknown extension

>> f = [tempname '.mtx'];
>> sp = Sparsity.triplet(3, 2, [0, 2, 1], [0, 0, 1]);
>> sp.to_file(f);
>> fileread(f)
%%MatrixMarket matrix coordinate pattern general
3 2 3
1 1
3 1
2 2
>> Sparsity.from_file(f) == sp
1
>> delete(f);
>> try, sp.to_file('pattern.txt'); catch e, disp('unknown extension'); end
unknown extension

julia> d = mktempdir();
julia> f = joinpath(d, "pattern.mtx");
julia> sp = ca.Sparsity.triplet(3, 2, [0, 2, 1], [0, 0, 1]);
julia> ca.to_file(sp, f)
julia> print(read(f, String))
%%MatrixMarket matrix coordinate pattern general
3 2 3
1 1
3 1
2 2
julia> ca.is_equal(ca.Sparsity.from_file(f), sp)
true
julia> rm(d, recursive=true)
julia> try
           ca.to_file(sp, "pattern.txt")
       catch e
           println("unknown extension")
       end
unknown extension

See also
from_file, DM::to_file

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

Definition at line 2002 of file sparsity.cpp.

2002  {
2003  std::string format = file_format(filename, format_hint, file_formats);
2004  auto out_ptr = Filesystem::ofstream_ptr(filename);
2005  std::ostream& out = *out_ptr;
2006  if (format=="mtx") {
2007  out << std::scientific << std::setprecision(std::numeric_limits<double>::digits10 + 1);
2008  out << "%%MatrixMarket matrix coordinate pattern general" << std::endl;
2009  out << size1() << " " << size2() << " " << nnz() << std::endl;
2010  std::vector<casadi_int> row = get_row();
2011  std::vector<casadi_int> col = get_col();
2012 
2013  for (casadi_int k=0;k<row.size();++k) {
2014  out << row[k]+1 << " " << col[k]+1 << std::endl;
2015  }
2016  } else {
2017  casadi_error("Unknown format '" + format + "'");
2018  }
2019  }
static std::unique_ptr< std::ostream > ofstream_ptr(const std::string &path, std::ios_base::openmode mode=std::ios_base::out)
Definition: filesystem.cpp:115

References file_format(), file_formats, casadi::filename(), get_col(), get_row(), nnz(), casadi::Filesystem::ofstream_ptr(), row(), size1(), and size2().

Referenced by casadi::FatropInterface::init().

◆ transpose()

Sparsity casadi::Sparsity::transpose ( std::vector< casadi_int > &  mapping,
bool  invert_mapping = false 
) const
Parameters
invert_mappingDirection of the mapping
Returns
The transposed pattern and a mapping of length nnz(). By default mapping[k] is the nonzero of the original pattern that becomes nonzero k of the transpose; with invert_mapping true, mapping[k] is the nonzero of the transpose that original nonzero k becomes.

>>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3])
>>> spT, mapping = sp.transpose()
>>> spT, mapping
(Sparsity(4x3,4nz), [0, 3, 2, 1])

>> sp = Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
>> [spT, mapping] = sp.transpose(); disp(spT), disp(mapping)
4x3,4nz
0 3 2 1

julia> sp = ca.Sparsity.triplet(3, 4, [0, 2, 1, 0], [0, 0, 2, 3]);
julia> ca.transpose(sp, false)
(4x3,4nz, [0, 3, 2, 1])

See also
T

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

Definition at line 392 of file sparsity.cpp.

392  {
393  return (*this)->transpose(mapping, invert_mapping);
394  }

References casadi::SparsityInternal::transpose().

Referenced by casadi::XFunction< DerivedType, MatType, NodeType >::jac(), and casadi::Conic::sdp_to_socp_init().

◆ tril()

Sparsity casadi::Sparsity::tril ( const Sparsity &  x,
bool  includeDiagonal = true 
)
static

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

Definition at line 1008 of file sparsity.cpp.

1008  {
1009  return x->_tril(includeDiagonal);
1010  }

References casadi::SparsityInternal::_tril().

Referenced by casadi::Convexify::setup(), and casadi::GenericMatrix< MatType >::tril().

◆ triplet() [1/2]

Sparsity casadi::Sparsity::triplet ( casadi_int  nrow,
casadi_int  ncol,
const std::vector< casadi_int > &  row,
const std::vector< casadi_int > &  col 
)
static

The entries may be given in any order; duplicates are merged. An index out of range or vectors of different length raise an error.

Parameters
nrowNumber of rows
ncolNumber of columns
rowRow index of each entry, in [0, nrow)
colColumn index of each entry, in [0, ncol), same length as row
invert_mappingSelects the direction of the returned mapping (see below)

The overload with invert_mapping additionally returns a mapping between the given entries and the nonzeros of the result (which are in column-major order). With invert_mapping false, mapping[k] is the position in the input of nonzero k (length nnz(); for duplicates the first occurrence). With invert_mapping true, mapping[i] is the nonzero index of input entry i (length of the input).

>>> DM(Sparsity.triplet(3, 3, [0, 2, 1], [0, 0, 2]), 1)
DM(
[[1, 00, 00],
 [00, 00, 1],
 [1, 00, 00]])
>>> Sparsity.triplet(2, 2, [0, 0, 1], [0, 0, 1]).nnz()
2
>>> sp, mapping = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], False)
>>> mapping
[1, 2, 0]
>>> sp, mapping = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], True)
>>> mapping
[2, 0, 1]
>>> try: Sparsity.triplet(2, 2, [0, 2], [0, 0])
... except Exception as e: print("out of bounds")
out of bounds

>> DM(Sparsity.triplet(3, 3, [0, 2, 1], [0, 0, 2]), 1)
[[1, 00, 00],
 [00, 00, 1],
 [1, 00, 00]]
>> Sparsity.triplet(2, 2, [0, 0, 1], [0, 0, 1]).nnz()
2
>> [sp, mapping] = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], false); disp(mapping)
1 2 0
>> [sp, mapping] = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], true); disp(mapping)
2 0 1
>> try, Sparsity.triplet(2, 2, [0, 2], [0, 0]); catch e, disp('out of bounds'); end
out of bounds

julia> ca.DM(ca.Sparsity.triplet(3, 3, [0, 2, 1], [0, 0, 2]), 1)
DM(
[[1, 00, 00],
 [00, 00, 1],
 [1, 00, 00]])
julia> ca.nnz(ca.Sparsity.triplet(2, 2, [0, 0, 1], [0, 0, 1]))
2
julia> sp, mapping = ca.Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], false);
julia> mapping
3-element Vector{Int64}:
 1
 2
 0
julia> sp, mapping = ca.Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], true);
julia> mapping
3-element Vector{Int64}:
 2
 0
 1
julia> try
           ca.Sparsity.triplet(2, 2, [0, 2], [0, 0])
       catch e
           println("out of bounds")
       end
out of bounds

See also
get_triplet, rowcol, nonzeros, Sparsity(nrow, ncol, colind, row)

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

Definition at line 1309 of file sparsity.cpp.

1310  {
1311  std::vector<casadi_int> mapping;
1312  return Sparsity::triplet(nrow, ncol, row, col, mapping, false);
1313  }

References row(), and triplet().

◆ triplet() [2/2]

Sparsity casadi::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 
)
static

The entries may be given in any order; duplicates are merged. An index out of range or vectors of different length raise an error.

Parameters
nrowNumber of rows
ncolNumber of columns
rowRow index of each entry, in [0, nrow)
colColumn index of each entry, in [0, ncol), same length as row
invert_mappingSelects the direction of the returned mapping (see below)

The overload with invert_mapping additionally returns a mapping between the given entries and the nonzeros of the result (which are in column-major order). With invert_mapping false, mapping[k] is the position in the input of nonzero k (length nnz(); for duplicates the first occurrence). With invert_mapping true, mapping[i] is the nonzero index of input entry i (length of the input).

>>> DM(Sparsity.triplet(3, 3, [0, 2, 1], [0, 0, 2]), 1)
DM(
[[1, 00, 00],
 [00, 00, 1],
 [1, 00, 00]])
>>> Sparsity.triplet(2, 2, [0, 0, 1], [0, 0, 1]).nnz()
2
>>> sp, mapping = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], False)
>>> mapping
[1, 2, 0]
>>> sp, mapping = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], True)
>>> mapping
[2, 0, 1]
>>> try: Sparsity.triplet(2, 2, [0, 2], [0, 0])
... except Exception as e: print("out of bounds")
out of bounds

>> DM(Sparsity.triplet(3, 3, [0, 2, 1], [0, 0, 2]), 1)
[[1, 00, 00],
 [00, 00, 1],
 [1, 00, 00]]
>> Sparsity.triplet(2, 2, [0, 0, 1], [0, 0, 1]).nnz()
2
>> [sp, mapping] = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], false); disp(mapping)
1 2 0
>> [sp, mapping] = Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], true); disp(mapping)
2 0 1
>> try, Sparsity.triplet(2, 2, [0, 2], [0, 0]); catch e, disp('out of bounds'); end
out of bounds

julia> ca.DM(ca.Sparsity.triplet(3, 3, [0, 2, 1], [0, 0, 2]), 1)
DM(
[[1, 00, 00],
 [00, 00, 1],
 [1, 00, 00]])
julia> ca.nnz(ca.Sparsity.triplet(2, 2, [0, 0, 1], [0, 0, 1]))
2
julia> sp, mapping = ca.Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], false);
julia> mapping
3-element Vector{Int64}:
 1
 2
 0
julia> sp, mapping = ca.Sparsity.triplet(3, 3, [2, 0, 1], [1, 0, 0], true);
julia> mapping
3-element Vector{Int64}:
 2
 0
 1
julia> try
           ca.Sparsity.triplet(2, 2, [0, 2], [0, 0])
       catch e
           println("out of bounds")
       end
out of bounds

See also
get_triplet, rowcol, nonzeros, Sparsity(nrow, ncol, colind, row)

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

Definition at line 1157 of file sparsity.cpp.

1159  {
1160  // Assert dimensions
1161  casadi_assert(nrow>=0 && ncol>=0,
1162  "Dimensions must be non-negative, got " + str(nrow) + "-by-" + str(ncol));
1163  casadi_assert(col.size()==row.size(), "inconsistent lengths");
1164 
1165  // Create the return sparsity pattern and access vectors
1166  std::vector<casadi_int> r_colind(ncol+1, 0);
1167  std::vector<casadi_int> r_row;
1168  r_row.reserve(row.size());
1169 
1170  // Consistency check and check if elements are already perfectly ordered with no duplicates
1171  casadi_int last_col=-1, last_row=-1;
1172  bool perfectly_ordered=true;
1173  for (casadi_int k=0; k<col.size(); ++k) {
1174  // Consistency check
1175  casadi_assert(col[k]>=0 && col[k]<ncol,
1176  "Column index (" + str(col[k]) + ") out of bounds [0," + str(ncol) + "[");
1177  casadi_assert(row[k]>=0 && row[k]<nrow,
1178  "Row index (" + str(row[k]) + ") out of bounds [0," + str(nrow) + "[");
1179 
1180  // Check if ordering is already perfect
1181  perfectly_ordered = perfectly_ordered && (col[k]<last_col ||
1182  (col[k]==last_col && row[k]<=last_row));
1183  last_col = col[k];
1184  last_row = row[k];
1185  }
1186 
1187  // Quick return if perfectly ordered
1188  if (perfectly_ordered) {
1189  // Save rows
1190  r_row.resize(row.size());
1191  std::copy(row.begin(), row.end(), r_row.begin());
1192 
1193  // Find offset index
1194  casadi_int el=0;
1195  for (casadi_int i=0; i<ncol; ++i) {
1196  while (el<col.size() && col[el]==i) el++;
1197  r_colind[i+1] = el;
1198  }
1199 
1200  // Identity mapping
1201  mapping.resize(row.size());
1202  for (casadi_int k=0; k<row.size(); ++k) mapping[k] = k;
1203 
1204  // Quick return
1205  return Sparsity(nrow, ncol, r_colind, r_row);
1206  }
1207 
1208  // Reuse data
1209  std::vector<casadi_int>& mapping1 = invert_mapping ? r_row : mapping;
1210  std::vector<casadi_int>& mapping2 = invert_mapping ? mapping : r_row;
1211 
1212  // Make sure that enough memory is allocated to use as a work vector
1213  mapping1.reserve(std::max(nrow+1, static_cast<casadi_int>(col.size())));
1214 
1215  // Number of elements in each row
1216  std::vector<casadi_int>& rowcount = mapping1; // reuse memory
1217  rowcount.resize(nrow+1);
1218  std::fill(rowcount.begin(), rowcount.end(), 0);
1219  for (std::vector<casadi_int>::const_iterator it=row.begin(); it!=row.end(); ++it) {
1220  rowcount[*it+1]++;
1221  }
1222 
1223  // Cumsum to get index offset for each row
1224  for (casadi_int i=0; i<nrow; ++i) {
1225  rowcount[i+1] += rowcount[i];
1226  }
1227 
1228  // New row for each old row
1229  mapping2.resize(row.size());
1230  for (casadi_int k=0; k<row.size(); ++k) {
1231  mapping2[rowcount[row[k]]++] = k;
1232  }
1233 
1234  // Number of elements in each col
1235  // reuse memory, r_colind is already the right size
1236  std::vector<casadi_int>& colcount = r_colind;
1237  // and is filled with zeros
1238  for (std::vector<casadi_int>::const_iterator it=mapping2.begin(); it!=mapping2.end(); ++it) {
1239  colcount[col[*it]+1]++;
1240  }
1241 
1242  // Cumsum to get index offset for each col
1243  for (casadi_int i=0; i<ncol; ++i) {
1244  colcount[i+1] += colcount[i];
1245  }
1246 
1247  // New col for each old col
1248  mapping1.resize(col.size());
1249  for (std::vector<casadi_int>::const_iterator it=mapping2.begin(); it!=mapping2.end(); ++it) {
1250  mapping1[colcount[col[*it]]++] = *it;
1251  }
1252 
1253  // Current element in the return matrix
1254  casadi_int r_el = 0;
1255  r_row.resize(col.size());
1256 
1257  // Current nonzero
1258  std::vector<casadi_int>::const_iterator it=mapping1.begin();
1259 
1260  // Loop over columns
1261  r_colind[0] = 0;
1262  for (casadi_int i=0; i<ncol; ++i) {
1263 
1264  // Previous row (to detect duplicates)
1265  casadi_int j_prev = -1;
1266 
1267  // Loop over nonzero elements of the col
1268  while (it!=mapping1.end() && col[*it]==i) {
1269 
1270  // Get the element
1271  casadi_int el = *it;
1272  it++;
1273 
1274  // Get the row
1275  casadi_int j = row[el];
1276 
1277  // If not a duplicate, save to return matrix
1278  if (j!=j_prev)
1279  r_row[r_el++] = j;
1280 
1281  if (invert_mapping) {
1282  // Save to the inverse mapping
1283  mapping2[el] = r_el-1;
1284  } else {
1285  // If not a duplicate, save to the mapping vector
1286  if (j!=j_prev)
1287  mapping1[r_el-1] = el;
1288  }
1289 
1290  // Save row
1291  j_prev = j;
1292  }
1293 
1294  // Update col offset
1295  r_colind[i+1] = r_el;
1296  }
1297 
1298  // Resize the row vector
1299  r_row.resize(r_el);
1300 
1301  // Resize mapping matrix
1302  if (!invert_mapping) {
1303  mapping1.resize(r_el);
1304  }
1305 
1306  return Sparsity(nrow, ncol, r_colind, r_row);
1307  }

References row(), Sparsity(), and casadi::str().

Referenced by casadi::SparsityInternal::_mtimes(), casadi::SparsityInternal::_reshape(), casadi::BSpline::dual(), from_file(), casadi::FunctionInternal::get_jac_sparsity_gen(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::DaeBuilderInternal::hess_sparsity(), horzcat(), casadi::XFunction< DerivedType, MatType, NodeType >::jac(), casadi::DaeBuilderInternal::jac_sparsity(), nonzeros(), casadi::SparsityInternal::pmult(), casadi::QpoasesInterface::qpoases_init(), rowcol(), casadi::Matrix< Scalar >::set(), casadi::MX::set(), casadi::SparsityInternal::star_coloring(), casadi::SparsityInternal::sub(), casadi::SparsityInternal::transpose(), triplet(), and vertcat().

◆ triu()

Sparsity casadi::Sparsity::triu ( const Sparsity &  x,
bool  includeDiagonal = true 
)
static

◆ type_name()

static std::string casadi::Sparsity::type_name ( )
inlinestatic

Definition at line 5925 of file sparsity.hpp.

5925 {return "Sparsity";}

◆ uni_coloring()

Sparsity casadi::Sparsity::uni_coloring ( const Sparsity &  AT = Sparsity(),
casadi_int  cutoff = std::numeric_limits<casadi_int>::max() 
) const

Greedy distance-2 coloring (Algorithm 3.1 in Gebremedhin, Manne and Pothen, What Color Is Your Jacobian?, SIAM Rev. 47(4), 2006): columns that have no row in common may share a color, so that one directional derivative per color recovers all nonzeros. This is the coloring used for forward-mode Jacobians (and, applied to the transpose, for reverse mode).

Parameters
ATThe transpose of this pattern, if already available; a null Sparsity (default) computes it
cutoffIf more than this many colors are needed, a null Sparsity is returned instead
Returns
A size2()-by-ncolors pattern: column c lists the columns of this pattern that received color c

>>> A = Sparsity.triplet(3, 4, [0, 1, 2, 0], [0, 1, 2, 3])
>>> DM(A, 1)
DM(
[[1, 00, 00, 1],
 [00, 1, 00, 00],
 [00, 00, 1, 00]])
>>> c = A.uni_coloring()
>>> DM(c, 1)
DM(
[[1, 00],
 [1, 00],
 [1, 00],
 [00, 1]])
>>> c.size2(), [c.row()[c.colind()[j]:c.colind()[j + 1]] for j in range(c.size2())]
(2, [[0, 1, 2], [3]])
>>> A.uni_coloring(Sparsity(), 1).is_null()
True
>>> Sparsity.dense(3, 3).uni_coloring(), Sparsity.diag(3).uni_coloring()
(Sparsity(3x3,3nz), Sparsity(3x1))

>> A = Sparsity.triplet(3, 4, [0, 1, 2, 0], [0, 1, 2, 3]);
>> DM(A, 1)
[[1, 00, 00, 1],
 [00, 1, 00, 00],
 [00, 00, 1, 00]]
>> c = A.uni_coloring();
>> DM(c, 1)
[[1, 00],
 [1, 00],
 [1, 00],
 [00, 1]]
>> disp(c.size2()), ci = c.colind(); r = c.row();
2
>> for j = 1:c.size2(), disp(r(ci(j) + 1:ci(j + 1))), end
0 1 2
3
>> A.uni_coloring(Sparsity(), 1).is_null()
1
>> Sparsity.dense(3, 3).uni_coloring(), Sparsity.diag(3).uni_coloring()
3x3,3nz
3x1

julia> A = ca.Sparsity.triplet(3, 4, [0, 1, 2, 0], [0, 1, 2, 3]);
julia> ca.DM(A, 1)
DM(
[[1, 00, 00, 1],
 [00, 1, 00, 00],
 [00, 00, 1, 00]])
julia> c = ca.uni_coloring(A, ca.Sparsity(), 1000);
julia> ca.DM(c, 1)
DM(
[[1, 00],
 [1, 00],
 [1, 00],
 [00, 1]])
julia> ca.size2(c), [ca.row(c)[ca.colind(c)[j]+1:ca.colind(c)[j+1]] for j in 1:ca.size2(c)]
(2, [[0, 1, 2], [3]])
julia> ca.is_null(ca.uni_coloring(A, ca.Sparsity(), 1))
true
julia> ca.uni_coloring(ca.Sparsity.dense(3, 3), ca.Sparsity(), 1000)
Sparsity(3x3,3nz)
julia> ca.uni_coloring(ca.Sparsity.diag(3), ca.Sparsity(), 1000)
Sparsity(3x1)

See also
star_coloring, star_coloring_new

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

Examples
matrix/coloring.py.

Definition at line 764 of file sparsity.cpp.

764  {
765  if (AT.is_null()) {
766  return (*this)->uni_coloring(T(), cutoff);
767  } else {
768  return (*this)->uni_coloring(AT, cutoff);
769  }
770  }

References casadi::GenericShared< Shared, Internal >::is_null(), T(), and casadi::SparsityInternal::uni_coloring().

Referenced by casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_partition(), and casadi::FmuFunction::init().

◆ unit()

Sparsity casadi::Sparsity::unit ( casadi_int  n,
casadi_int  el 
)
static
Parameters
nLength of the column vector
elRow of the nonzero, in [0, n); an index outside this range raises an error

>>> DM(Sparsity.unit(4, 1), 1)
DM([00, 1, 00, 00])
>>> Sparsity.unit(4, 1).row()
[1]

>> DM(Sparsity.unit(4, 1), 1)
[00, 1, 00, 00]
>> Sparsity.unit(4, 1).row()
1

julia> ca.DM(ca.Sparsity.unit(4, 1), 1)
DM([00, 1, 00, 00])
julia> ca.row(ca.Sparsity.unit(4, 1))
1-element Vector{Int64}:
 1

See also
nonzeros, triplet

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

Definition at line 1134 of file sparsity.cpp.

1134  {
1135  std::vector<casadi_int> row(1, el), colind(2);
1136  colind[0] = 0;
1137  colind[1] = 1;
1138  return Sparsity(n, 1, colind, row);
1139  }

References colind(), row(), and Sparsity().

Referenced by casadi::SuperscsInterface::init().

◆ unite() [1/2]

Sparsity casadi::Sparsity::unite ( const Sparsity &  y) const

The pattern of x + y for matrices with these patterns. A shape mismatch raises an error.

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> DM(a.unite(b), 1)
DM(
[[1, 1],
 [00, 1]])
>>> a + b == a.unite(b), a * b == a.intersect(b)
(True, True)
>>> try: a + Sparsity.dense(3, 3)
... except Exception as e: print("dimension mismatch")
dimension mismatch

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> DM(a.unite(b), 1)
[[1, 1],
 [00, 1]]
>> a + b == a.unite(b), a .* b == a.intersect(b)
1
1
>> try, a + Sparsity.dense(3, 3); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.DM(ca.unite(a, b), 1)
DM(
[[1, 1],
 [00, 1]])
julia> try
           ca.unite(a, ca.Sparsity.dense(3, 3))
       catch e
           println("dimension mismatch")
       end
dimension mismatch

See also
intersect, combine, is_subset

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

Definition at line 415 of file sparsity.cpp.

415  {
416  return (*this)->combine(y, false, false);
417  }

References casadi::SparsityInternal::combine().

◆ unite() [2/2]

Sparsity casadi::Sparsity::unite ( const Sparsity &  y,
std::vector< unsigned char > &  mapping 
) const

The pattern of x + y for matrices with these patterns. A shape mismatch raises an error.

>>> a = Sparsity.diag(2)
>>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1])
>>> DM(a.unite(b), 1)
DM(
[[1, 1],
 [00, 1]])
>>> a + b == a.unite(b), a * b == a.intersect(b)
(True, True)
>>> try: a + Sparsity.dense(3, 3)
... except Exception as e: print("dimension mismatch")
dimension mismatch

>> a = Sparsity.diag(2);
>> b = Sparsity.triplet(2, 2, [0, 1], [1, 1]);
>> DM(a.unite(b), 1)
[[1, 1],
 [00, 1]]
>> a + b == a.unite(b), a .* b == a.intersect(b)
1
1
>> try, a + Sparsity.dense(3, 3); catch e, disp('dimension mismatch'); end
dimension mismatch

julia> a = ca.Sparsity.diag(2);
julia> b = ca.Sparsity.triplet(2, 2, [0, 1], [1, 1]);
julia> ca.DM(ca.unite(a, b), 1)
DM(
[[1, 1],
 [00, 1]])
julia> try
           ca.unite(a, ca.Sparsity.dense(3, 3))
       catch e
           println("dimension mismatch")
       end
dimension mismatch

See also
intersect, combine, is_subset

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

Definition at line 411 of file sparsity.cpp.

411  {
412  return (*this)->combine(y, false, false, mapping);
413  }

References casadi::SparsityInternal::combine().

Referenced by casadi::SetNonzeros< Add >::ad_forward(), casadi::GetNonzeros::ad_reverse(), casadi::SetNonzeros< Add >::eval_mx(), casadi::Switch::get_sparsity_in(), casadi::Switch::get_sparsity_out(), operator+(), and casadi::MX::unite().

◆ upper()

Sparsity casadi::Sparsity::upper ( casadi_int  n)
static

Column j contains the rows 0, ..., j, so the diagonal is included and the pattern has n*(n+1)/2 nonzeros.

Parameters
nSize of the square pattern, nonnegative

>>> DM(Sparsity.upper(3), 1)
DM(
[[1, 1, 1],
 [00, 1, 1],
 [00, 00, 1]])
>>> Sparsity.upper(3).nnz(), Sparsity.upper(3).is_triu()
(6, True)

>> DM(Sparsity.upper(3), 1)
[[1, 1, 1],
 [00, 1, 1],
 [00, 00, 1]]
>> Sparsity.upper(3).nnz(), Sparsity.upper(3).is_triu()
6
1

julia> ca.DM(ca.Sparsity.upper(3), 1)
DM(
[[1, 1, 1],
 [00, 1, 1],
 [00, 00, 1]])
julia> ca.nnz(ca.Sparsity.upper(3)), ca.is_triu(ca.Sparsity.upper(3))
(6, true)

See also
lower, triu, is_triu

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

Definition at line 1057 of file sparsity.cpp.

1057  {
1058  casadi_assert(n>=0, "Sparsity::upper expects a positive integer as argument");
1059  casadi_int nrow=n, ncol=n;
1060  std::vector<casadi_int> colind, row;
1061  colind.reserve(ncol+1);
1062  row.reserve((n*(n+1))/2);
1063 
1064  // Loop over columns
1065  colind.push_back(0);
1066  for (casadi_int cc=0; cc<ncol; ++cc) {
1067  // Loop over rows for the upper triangular half
1068  for (casadi_int rr=0; rr<=cc; ++rr) {
1069  row.push_back(rr);
1070  }
1071  colind.push_back(row.size());
1072  }
1073 
1074  // Return the pattern
1075  return Sparsity(nrow, ncol, colind, row);
1076  }

References colind(), row(), and Sparsity().

Referenced by casadi::Convexify::setup().

◆ vertcat()

Sparsity casadi::Sparsity::vertcat ( const std::vector< Sparsity > &  sp)
static

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

Definition at line 1567 of file sparsity.cpp.

1567  {
1568  // Quick return if possible
1569  if (sp.empty()) return Sparsity(0, 1);
1570  if (sp.size()==1) return sp.front();
1571 
1572  // Count total nnz
1573  casadi_int nnz_total = 0;
1574  for (casadi_int i=0; i<sp.size(); ++i) nnz_total += sp[i].nnz();
1575 
1576  // Construct from vectors (triplet format)
1577  std::vector<casadi_int> ret_row, ret_col;
1578  ret_row.reserve(nnz_total);
1579  ret_col.reserve(nnz_total);
1580  casadi_int ret_nrow = 0;
1581  casadi_int ret_ncol = 0;
1582  for (casadi_int i=0; i<sp.size() && ret_ncol==0; ++i)
1583  ret_ncol = sp[i].size2();
1584 
1585  // Append all patterns
1586  for (std::vector<Sparsity>::const_iterator i=sp.begin(); i!=sp.end(); ++i) {
1587  // Get sparsity pattern
1588  casadi_int sp_nrow = i->size1();
1589  casadi_int sp_ncol = i->size2();
1590  const casadi_int* sp_colind = i->colind();
1591  const casadi_int* sp_row = i->row();
1592  casadi_assert(sp_ncol==ret_ncol || sp_ncol==0,
1593  "Sparsity::vertcat: Mismatching number of columns");
1594 
1595  // Add entries to pattern
1596  for (casadi_int cc=0; cc<sp_ncol; ++cc) {
1597  for (casadi_int k=sp_colind[cc]; k<sp_colind[cc+1]; ++k) {
1598  ret_row.push_back(sp_row[k] + ret_nrow);
1599  ret_col.push_back(cc);
1600  }
1601  }
1602 
1603  // Update offset
1604  ret_nrow += sp_nrow;
1605  }
1606  return Sparsity::triplet(ret_nrow, ret_ncol, ret_row, ret_col);
1607  }

References nnz(), size2(), Sparsity(), and triplet().

Referenced by append(), and blockcat().

◆ vertsplit()

std::vector< Sparsity > casadi::Sparsity::vertsplit ( const Sparsity &  x,
const std::vector< casadi_int > &  offset 
)
static

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

Definition at line 1679 of file sparsity.cpp.

1680  {
1681  std::vector<Sparsity> ret = horzsplit(x.T(), offset);
1682  for (std::vector<Sparsity>::iterator it=ret.begin(); it!=ret.end(); ++it) {
1683  *it = it->T();
1684  }
1685  return ret;
1686  }
static std::vector< Sparsity > horzsplit(const Sparsity &x, const std::vector< casadi_int > &offset)
Accessed by SparsityInterface.
Definition: sparsity.cpp:1636

References horzsplit(), casadi::SparsityInterface< Sparsity >::offset(), 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  }

Member Data Documentation

◆ file_formats

std::set< std::string > casadi::Sparsity::file_formats = {"mtx"}
static

Definition at line 6068 of file sparsity.hpp.

Referenced by file_format(), from_file(), and to_file().


The documentation for this class was generated from the following files: