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

Function object. More...

#include <function.hpp>

Detailed Description

A Function instance is a general multiple-input, multiple-output function where each input and output can be a sparse matrix.
For an introduction to this class, see the CasADi user guide.
Function is a reference counted and immutable class; copying a class instance is very cheap and its behavior (with some exceptions) is not affected by calling its member functions.
Each input and output has a name (name_in, name_out) and a fixed sparsity pattern (sparsity_in, sparsity_out). The same object can be evaluated numerically (DM arguments) or symbolically (SX or MX arguments), differentiated (jacobian, forward, reverse, factory), transformed (map, mapaccum, fold, expand), code-generated (generate), serialized (serialize, save) and inspected (print_dimensions, stats, info).

Instances are created from expressions (the SX and MX constructors), from a C body (jit), by combining other functions (conditional, if_else, map, mapaccum) or by the solver constructors nlpsol, qpsol, rootfinder, integrator, external. Printing shows the signature and the class name, e.g. f:(x,y[2])->(r[2],s) SXFunction.

The exceptions to immutability are options changed with change_option and the cache of derivative functions.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f
Function(f:(x,y[2])->(r[2],s) SXFunction)
>>> r, s = f(2, [3, 4])
>>> r, s
(DM([6, 8]), DM(0.909297))
>>> f(x=2, y=[3, 4])
{'r': DM([6, 8]), 's': DM(0.909297)}
>>> z = MX.sym("z")
>>> f(z, [3, 4])
(MX(f(z, [3, 4]){0}), MX(f(z, [3, 4]){1}))

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> f
f:(x,y[2])->(r[2],s) SXFunction
>> [r, s] = f(2, [3; 4]); disp(r), disp(s)
[6, 8]
0.909297
>> res = f('x', 2, 'y', [3; 4]); disp(res.r), disp(res.s)
[6, 8]
0.909297
>> z = MX.sym('z'); [r, s] = f(z, [3; 4]); disp(r), disp(s)
f(z, [3, 4]){0}
f(z, [3, 4]){1}

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
Function(f:(x,y[2])->(r[2],s) SXFunction)
julia> r, s = f(2, [3, 4])
([6, 8], 0.909297)
julia> f(x=2, y=[3, 4])
Dict{String, DM} with 2 entries:
  "r" => [6, 8]
  "s" => 0.909297
julia> z = ca.MX.sym("z");
julia> f(z, [3, 4])
(f(z, [3, 4]){0}, f(z, [3, 4]){1})

Author
Joel Andersson
Date
2010-2017

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

List of available options
IdTypeDescriptionUsed in
ad_weightOT_DOUBLEWeighting factor for derivative calculation.When there is an option of either using forward or reverse mode directional derivatives, the condition ad_weight*nf<=(1-ad_weight)*na is used where nf and na are estimates of the number of forward/reverse mode directional derivatives needed. By default, ad_weight is calculated automatically, but this can be overridden by setting this option. In particular, 0 means forcing forward mode and 1 forcing reverse mode. Leave unset for (class specific) heuristics.casadi::FunctionInternal
ad_weight_spOT_DOUBLEWeighting factor for sparsity pattern calculation calculation.Overrides default behavior. Set to 0 and 1 to force forward and reverse mode respectively. Cf. option "ad_weight". When set to -1, sparsity is completely ignored and dense matrices are used.casadi::FunctionInternal
always_inlineOT_BOOLForce inlining.casadi::FunctionInternal
cacheOT_DICTPrepopulate the function cache. Default: emptycasadi::FunctionInternal
codegen_optionsOT_DICTOptions to be passed to the code generator of jit, e.g. {"stats": true} to record statistics inside the compiled code. Default: nonecasadi::FunctionInternal
compilerOT_STRINGJust-in-time compiler plugin to be used.casadi::FunctionInternal
custom_jacobianOT_FUNCTIONOverride CasADi's AD. Use together with 'jac_penalty': 0. Note: Highly experimental. Syntax may break often.casadi::FunctionInternal
der_optionsOT_DICTDefault options to be used to populate forward_options, reverse_options, and jacobian_options before those options are merged in.casadi::FunctionInternal
derivative_ofOT_FUNCTIONThe function is a derivative of another function. The type of derivative (directional derivative, Jacobian) is inferred from the function name.casadi::FunctionInternal
dumpOT_BOOLDump function to file upon first evaluation. [false]casadi::FunctionInternal
dump_dirOT_STRINGDirectory to dump inputs/outputs and traces to. Make sure the directory exists [.]casadi::FunctionInternal
dump_formatOT_STRINGChoose file format to dump matrices. See DM.from_file [mtx]casadi::FunctionInternal
dump_inOT_BOOLDump numerical values of inputs to file (readable with DM.from_file) [default: false] A counter is used to generate unique names. The counter may be reset using reset_dump_count.casadi::FunctionInternal
dump_outOT_BOOLDump numerical values of outputs to file (readable with DM.from_file) [default: false] A counter is used to generate unique names. The counter may be reset using reset_dump_count.casadi::FunctionInternal
enable_fdOT_BOOLEnable derivative calculation by finite differencing. [default: false]]casadi::FunctionInternal
enable_forwardOT_BOOLEnable derivative calculation using generated functions for Jacobian-times-vector products - typically using forward mode AD - if available. [default: true]casadi::FunctionInternal
enable_jacobianOT_BOOLEnable derivative calculation using generated functions for Jacobians of all differentiable outputs with respect to all differentiable inputs - if available. [default: true]casadi::FunctionInternal
enable_reverseOT_BOOLEnable derivative calculation using generated functions for transposed Jacobian-times-vector products - typically using reverse mode AD - if available. [default: true]casadi::FunctionInternal
error_on_failOT_BOOLThrow exceptions when function evaluation fails (default true).casadi::ProtoFunction
external_transformOT_VECTORVECTORList of external_transform instruction arguments. Default: emptycasadi::FunctionInternal
fd_methodOT_STRINGMethod for finite differencing [default 'central']casadi::FunctionInternal
fd_optionsOT_DICTOptions to be passed to the finite difference instancecasadi::FunctionInternal
forward_optionsOT_DICTOptions to be passed to a forward mode constructorcasadi::FunctionInternal
gather_statsOT_BOOLDeprecated option (ignored): Statistics are now always collected.casadi::FunctionInternal
inputs_checkOT_BOOLThrow exceptions when the numerical values of the inputs don't make sensecasadi::FunctionInternal
is_diff_inOT_BOOLVECTORIndicate for each input if it should be differentiable.casadi::FunctionInternal
is_diff_outOT_BOOLVECTORIndicate for each output if it should be differentiable.casadi::FunctionInternal
jac_penaltyOT_DOUBLEWhen requested for a number of forward/reverse directions, it may be cheaper to compute first the full jacobian and then multiply with seeds, rather than obtain the requested directions in a straightforward manner. Casadi uses a heuristic to decide which is cheaper. A high value of 'jac_penalty' makes it less likely for the heurstic to chose the full Jacobian strategy. The special value -1 indicates never to use the full Jacobian strategycasadi::FunctionInternal
jacobian_optionsOT_DICTOptions to be passed to a Jacobian constructorcasadi::FunctionInternal
jitOT_BOOLUse just-in-time compiler to speed up the evaluationcasadi::FunctionInternal
jit_cleanupOT_BOOLCleanup up the temporary source file that jit creates. Default: truecasadi::FunctionInternal
jit_nameOT_STRINGThe file name used to write out code. The actual file names used depend on 'jit_temp_suffix' and include extensions. Default: 'jit_tmp'casadi::FunctionInternal
jit_optionsOT_DICTOptions to be passed to the jit compiler.casadi::FunctionInternal
jit_serializeOT_STRINGSpecify behaviour when serializing a jitted function: SOURCE|link|embed.casadi::FunctionInternal
jit_temp_suffixOT_BOOLUse a temporary (seemingly random) filename suffix for generated code and libraries. This is desired for thread-safety. This behaviour may defeat caching compiler wrappers. Default: truecasadi::FunctionInternal
max_ioOT_INTAcceptable number of inputs and outputs. Warn if exceeded.casadi::FunctionInternal
max_num_dirOT_INTSpecify the maximum number of directions for derivative functions. Overrules the builtin optimized_num_dir.casadi::FunctionInternal
never_inlineOT_BOOLForbid inlining.casadi::FunctionInternal
post_expandOT_BOOLAfter construction, expand this Function. Default: Falsecasadi::FunctionInternal
post_expand_optionsOT_DICTOptions to be passed to post-construction expansion. Default: emptycasadi::FunctionInternal
print_canonicalOT_BOOLWhen printing numerical matrices, use a format that is exact and reproducible in generated C code.casadi::FunctionInternal
print_inOT_BOOLPrint numerical values of inputs [default: false]casadi::FunctionInternal
print_outOT_BOOLPrint numerical values of outputs [default: false]casadi::FunctionInternal
print_timeOT_BOOLprint information about execution time. Implies record_time.casadi::ProtoFunction
record_timeOT_BOOLrecord information about execution time, for retrieval with stats().casadi::ProtoFunction
regularity_checkOT_BOOLThrow exceptions when NaN or Inf appears during evaluationcasadi::ProtoFunction
reverse_optionsOT_DICTOptions to be passed to a reverse mode constructorcasadi::FunctionInternal
user_dataOT_VOIDPTRA user-defined field that can be used to identify the function or pass additional informationcasadi::FunctionInternal
verboseOT_BOOLVerbose evaluation – for debuggingcasadi::ProtoFunction
Examples
SX/SXFunction_constr_oct.m, SX/SXFunction_constr_py.py, integrators/simulator.py, solvers/callback.py, solvers/exacthessian.py, and solvers/ipopt.py.

Definition at line 124 of file function.hpp.

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

Public Types

typedef std::map< std::string, std::vector< std::string > > AuxOut
 
using internal_base_type = SharedObjectInternal
 
using base_type = SharedObject
 

Public Member Functions

 Function ()
 Default constructor, creates a null object. More...
 
 Function (const std::string &fname)
 Construct from a file; not implemented, raises an error. More...
 
 ~Function ()
 Destructor. More...
 
casadi_int n_in () const
 Get the number of function inputs. More...
 
casadi_int n_out () const
 Get the number of function outputs. More...
 
std::vector< bool > activity (const std::vector< bool > &arg) const
 Output signal activity induced by a given input activity. More...
 
const std::vector< std::string > & name_in () const
 Get the names of all inputs, in order. More...
 
const std::vector< std::string > & name_out () const
 Get the names of all outputs, in order. More...
 
const std::string & name_in (casadi_int ind) const
 Get the name of input ind; out of range raises an error. More...
 
const std::string & name_out (casadi_int ind) const
 Get the name of output ind; out of range raises an error. More...
 
casadi_int index_in (const std::string &name) const
 Get the index of the input with a given name. More...
 
casadi_int index_out (const std::string &name) const
 Get the index of the output with a given name; unknown names raise an error. More...
 
bool has_in (const std::string &name) const
 Check whether an input with the given name exists. More...
 
bool has_out (const std::string &name) const
 Check whether an output with the given name exists. More...
 
double default_in (casadi_int ind) const
 Get the value used for input ind when a call by name omits it. More...
 
double max_in (casadi_int ind) const
 Get the largest admissible value of input ind (inf unless a solver. More...
 
double min_in (casadi_int ind) const
 Get the smallest admissible value of input ind (-inf unless a solver. More...
 
std::vector< double > nominal_in (casadi_int ind) const
 Get the nominal value of each nonzero of input ind. More...
 
std::vector< double > nominal_out (casadi_int ind) const
 Get the nominal value of each nonzero of output ind; all ones by default. More...
 
Function factory (const std::string &name, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const AuxOut &aux=AuxOut(), const Dict &opts=Dict()) const
 Build a function computing derivatives by naming inputs and outputs. More...
 
Function oracle () const
 Get the user-supplied problem function behind a solver object. More...
 
std::vector< bool > which_depends (const std::string &s_in, const std::vector< std::string > &s_out, casadi_int order=1, bool tr=false) const
 Find which entries of an input the outputs depend on, linearly or not. More...
 
void print_dimensions (std::ostream &stream=casadi::uout()) const
 Print the name and shape of every input and output. More...
 
void print_options (std::ostream &stream=casadi::uout()) const
 Print the name, type and description of every option of this class. More...
 
void print_option (const std::string &name, std::ostream &stream=casadi::uout()) const
 Print the type and description of one option; unknown names print a. More...
 
bool has_option (const std::string &option_name) const
 Check whether this class accepts an option with the given name. More...
 
void change_option (const std::string &option_name, const GenericType &option_value)
 Change a debugging option on an existing object. More...
 
void reset_dump_count ()
 Reset to zero the counter that numbers the files written by dump_in,. More...
 
bool uses_output () const
 Check whether the derivative functions read the nondifferentiated outputs. More...
 
Function jacobian_old (casadi_int iind, casadi_int oind) const
 [DEPRECATED] Jacobian of output oind w.r.t. input iind, followed by More...
 
Function hessian_old (casadi_int iind, casadi_int oind) const
 [DEPRECATED] Hessian and gradient of scalar output oind w.r.t. input More...
 
Function jacobian () const
 Get a function computing all Jacobian blocks at once. More...
 
bool operator== (const Function &f) const
 Check if same as another function. More...
 
int operator() (const double **arg, double **res, casadi_int *iw, double *w, int mem) const
 Evaluate memory-less, numerically. More...
 
int operator() (const double **arg, double **res, casadi_int *iw, double *w) const
 Evaluate numerically with checkout/release. More...
 
int operator() (const SXElem **arg, SXElem **res, casadi_int *iw, SXElem *w, int mem=0) const
 Evaluate memory-less SXElem. More...
 
int operator() (const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, int mem=0) const
 Propagate sparsity forward. More...
 
int eval_activity (const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, int mem=0) const
 Propagate signal activity forward (bit set = active (possibly nonzero)) More...
 
int rev (bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, int mem=0) const
 Propagate sparsity backward. More...
 
int rev (std::vector< bvec_t * > arg, std::vector< bvec_t * > res) const
 Propagate sparsity backward with temporary memory allocation. More...
 
std::vector< MX > mapsum (const std::vector< MX > &x, const std::string &parallelization="serial") const
 Evaluate on horizontally stacked MX arguments and sum the results. More...
 
Function map (casadi_int n, const std::string &parallelization="serial") const
 Create a function that evaluates this function n times on stacked arguments. More...
 
Function map (casadi_int n, const std::string &parallelization, casadi_int max_num_threads) const
 
Function slice (const std::string &name, const std::vector< casadi_int > &order_in, const std::vector< casadi_int > &order_out, const Dict &opts=Dict()) const
 Create a function with a subset or reordering of the inputs and outputs. More...
 
Function forward (casadi_int nfwd) const
 Get a function computing nfwd forward directional derivatives. More...
 
Function reverse (casadi_int nadj) const
 Get a function computing nadj reverse (adjoint) directional derivatives. More...
 
const std::vector< Sparsity > & jac_sparsity (bool compact=false) const
 Get the sparsity patterns of all Jacobian blocks. More...
 
Sparsity jac_sparsity (casadi_int oind, casadi_int iind, bool compact=false) const
 Get the sparsity pattern of the Jacobian of output oind w.r.t. input. More...
 
std::string generate (const std::string &fname, const Dict &opts=Dict()) const
 Generate self-contained C code for the function. More...
 
std::string generate (const Dict &opts=Dict()) const
 Generate C code into a file named after the function (name() + ".c") More...
 
std::string generate_dependencies (const std::string &fname, const Dict &opts=Dict()) const
 Generate C code for the problem functions of a solver object. More...
 
FunctionInternal * get () const
 
template<typename T >
T * get () const
 Get a pointer and typecast. More...
 
FunctionInternal * operator-> () const
 Const access functions of the node. More...
 
Dict stats (int mem=0) const
 Get the statistics recorded by the last numerical evaluation. More...
 
bool has_free () const
 Check whether the outputs contain symbols that are not inputs. More...
 
std::vector< std::string > get_free () const
 Get the names of the free variables; empty when there are none. More...
 
std::vector< SX > free_sx () const
 Get the free variables of an SXFunction as SX symbols; other classes raise. More...
 
std::vector< MX > free_mx () const
 Get the free variables of an MXFunction as MX symbols; other classes raise. More...
 
void generate_lifted (Function &vdef_fcn, Function &vinit_fcn) const
 Extract the functions needed for the Lifted Newton method (MXFunction only) More...
 
casadi_int n_nodes () const
 Get the number of nodes in the expression graph (SXFunction and MXFunction) More...
 
casadi_int n_instructions () const
 Get the number of instructions of the algorithm (SXFunction and MXFunction) More...
 
casadi_int instruction_id (casadi_int k) const
 Get the operation code of instruction k (SXFunction and MXFunction) More...
 
std::vector< casadi_int > instruction_input (casadi_int k) const
 Get the work-vector locations read by instruction k. More...
 
double instruction_constant (casadi_int k) const
 Get the value of a constant instruction (OP_CONST) of an SXFunction. More...
 
std::vector< casadi_int > instruction_output (casadi_int k) const
 Get the work-vector locations written by instruction k. More...
 
MX instruction_MX (casadi_int k) const
 Get the MX expression computed by instruction k of an MXFunction. More...
 
SX instructions_sx () const
 Get the SX expression of every instruction of an SXFunction, as one vector. More...
 
size_t sz_arg () const
 Get the length of the input pointer array needed to evaluate (at least n_in) More...
 
size_t sz_res () const
 Get the length of the output pointer array needed to evaluate (at least. More...
 
size_t sz_iw () const
 Get the length of the integer work vector needed to evaluate. More...
 
size_t sz_w () const
 Get the length of the real work vector needed to evaluate. More...
 
void sz_work (size_t &sz_arg, size_t &sz_res, size_t &sz_iw, size_t &sz_w) const
 Get number of temporary variables needed. More...
 
void set_work (const double **&arg, double **&res, casadi_int *&iw, double *&w, int mem=0) const
 Set the (persistent) work vectors. More...
 
void set_temp (const double **arg, double **res, casadi_int *iw, double *w, int mem=0) const
 Set the (temporary) work vectors. More...
 
void setup (const double **arg, double **res, casadi_int *iw, double *w, int mem=0) const
 Set the (persistent and temporary) work vectors. More...
 
template<typename M >
void call_gen (const std::map< std::string, M > &arg, std::map< std::string, M > &res, bool always_inline, bool never_inline) const
 Call using a map. More...
 
void merge (const std::vector< MX > &arg, std::vector< MX > &subs_from, std::vector< MX > &subs_to) const
 List merge opportunitities. More...
 
const std::string & name () const
 Get the name given at construction ("null" for a null object) More...
 
bool is_a (const std::string &type, bool recursive=true) const
 Check whether the function is of a given class. More...
 
void assert_size_in (casadi_int i, casadi_int nrow, casadi_int ncol) const
 Raise an error unless input i is nrow-by-ncol. More...
 
void assert_size_out (casadi_int i, casadi_int nrow, casadi_int ncol) const
 Raise an error unless output i is nrow-by-ncol. More...
 
void assert_sparsity_out (casadi_int i, const Sparsity &sp, casadi_int n=1, bool allow_all_zero_sparse=true) const
 Raise an error unless output i has the sparsity sp repeated n. More...
 
casadi_int checkout () const
 Reserve a memory object for evaluation and return its index. More...
 
void release (int mem) const
 Give back a memory object obtained with checkout. More...
 
void * memory (int ind) const
 Get memory object. More...
 
Dict cache () const
 Get the derivative and map functions currently cached for this function. More...
 
std::vector< std::string > get_function () const
 Get the names of the functions this function directly owns. More...
 
Function get_function (const std::string &name) const
 Get a directly owned function by name; unknown names raise an error. More...
 
bool has_function (const std::string &fname) const
 Check if a particular dependency exists. More...
 
std::vector< Function > find_functions (casadi_int max_depth=-1) const
 Get all functions embedded in this function, recursively. More...
 
Function find_function (const std::string &name, casadi_int max_depth=-1) const
 Get an embedded function by name, searching recursively. More...
 
Dict info () const
 Get class-specific information as a dict. More...
 
template<>
const SX CASADI_EXPORT sym_in (casadi_int iind) const
 
template<>
const std::vector< SX > CASADI_EXPORT sym_in () 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...
 
 Function (const std::string &name, const std::vector< SX > &ex_in, const std::vector< SX > &ex_out, const Dict &opts=Dict())
 Construct a function from SX input and output expressions. More...
 
 Function (const std::string &name, const std::vector< SX > &ex_in, const std::vector< SX > &ex_out, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Construct a function from SX input and output expressions. More...
 
 Function (const std::string &name, const std::map< std::string, SX > &dict, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Construct a function from SX input and output expressions. More...
 
 Function (const std::string &name, const std::vector< MX > &ex_in, const std::vector< MX > &ex_out, const Dict &opts=Dict())
 Construct a function from MX input and output expressions. More...
 
 Function (const std::string &name, const std::vector< MX > &ex_in, const std::vector< MX > &ex_out, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Construct a function from MX input and output expressions. More...
 
 Function (const std::string &name, const std::map< std::string, MX > &dict, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Construct a function from MX input and output expressions. More...
 
 Function (const std::string &name, SXIList ex_in, const SXVector &ex_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, const SXVector &ex_in, SXIList ex_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, SXIList ex_in, SXIList ex_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, SXIList ex_in, const SXVector &ex_out, const StringVector &name_in, const StringVector &name_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, const SXVector &ex_in, SXIList ex_out, const StringVector &name_in, const StringVector &name_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, SXIList ex_in, SXIList ex_out, const StringVector &name_in, const StringVector &name_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, MXIList ex_in, const MXVector &ex_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, const MXVector &ex_in, MXIList ex_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, MXIList ex_in, MXIList ex_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, MXIList ex_in, const MXVector &ex_out, const StringVector &name_in, const StringVector &name_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, const MXVector &ex_in, MXIList ex_out, const StringVector &name_in, const StringVector &name_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
 Function (const std::string &name, MXIList ex_in, MXIList ex_out, const StringVector &name_in, const StringVector &name_out, const Dict &opts=Dict())
 To resolve ambiguity on some compilers. More...
 
Function expand () const
 Convert an MXFunction into an equivalent SXFunction. More...
 
Function expand (const std::string &name, const Dict &opts=Dict()) const
 Convert an MXFunction into an equivalent SXFunction. More...
 
Function transform (const Dict &opts=Dict()) const
 Rebuild the function after graph simplification or other passes. More...
 
Function transform (const std::string &fname, const Dict &opts=Dict()) const
 Rebuild the function after graph simplification or other passes. More...
 
Function transform (const std::vector< std::vector< GenericType > > &passes, const Dict &opts=Dict()) const
 Rebuild the function after graph simplification or other passes. More...
 
Function transform (const std::string &fname, const std::vector< std::vector< GenericType > > &passes, const Dict &opts=Dict()) const
 Rebuild the function after graph simplification or other passes. More...
 
casadi_int size1_in (casadi_int ind) const
 Get the shape of an input: rows, columns or both. More...
 
casadi_int size1_in (const std::string &iname) const
 Get the shape of an input: rows, columns or both. More...
 
casadi_int size2_in (casadi_int ind) const
 Get the shape of an input: rows, columns or both. More...
 
casadi_int size2_in (const std::string &iname) const
 Get the shape of an input: rows, columns or both. More...
 
std::pair< casadi_int, casadi_int > size_in (casadi_int ind) const
 Get the shape of an input: rows, columns or both. More...
 
std::pair< casadi_int, casadi_int > size_in (const std::string &iname) const
 Get the shape of an input: rows, columns or both. More...
 
casadi_int size1_out (casadi_int ind) const
 Get the shape of an output: rows, columns or both. More...
 
casadi_int size1_out (const std::string &oname) const
 Get the shape of an output: rows, columns or both. More...
 
casadi_int size2_out (casadi_int ind) const
 Get the shape of an output: rows, columns or both. More...
 
casadi_int size2_out (const std::string &oname) const
 Get the shape of an output: rows, columns or both. More...
 
std::pair< casadi_int, casadi_int > size_out (casadi_int ind) const
 Get the shape of an output: rows, columns or both. More...
 
std::pair< casadi_int, casadi_int > size_out (const std::string &oname) const
 Get the shape of an output: rows, columns or both. More...
 
casadi_int nnz_in () const
 Get the number of structural nonzeros of one input, or of all inputs. More...
 
casadi_int nnz_in (casadi_int ind) const
 Get the number of structural nonzeros of one input, or of all inputs. More...
 
casadi_int nnz_in (const std::string &iname) const
 Get the number of structural nonzeros of one input, or of all inputs. More...
 
casadi_int nnz_out () const
 Get the number of structural nonzeros of one output, or of all outputs. More...
 
casadi_int nnz_out (casadi_int ind) const
 Get the number of structural nonzeros of one output, or of all outputs. More...
 
casadi_int nnz_out (const std::string &oname) const
 Get the number of structural nonzeros of one output, or of all outputs. More...
 
casadi_int numel_in () const
 Get the number of elements (rows times columns) of one input, or of all. More...
 
casadi_int numel_in (casadi_int ind) const
 Get the number of elements (rows times columns) of one input, or of all. More...
 
casadi_int numel_in (const std::string &iname) const
 Get the number of elements (rows times columns) of one input, or of all. More...
 
casadi_int numel_out () const
 Get the number of elements (rows times columns) of one output, or of all. More...
 
casadi_int numel_out (casadi_int ind) const
 Get the number of elements (rows times columns) of one output, or of all. More...
 
casadi_int numel_out (const std::string &oname) const
 Get the number of elements (rows times columns) of one output, or of all. More...
 
const Sparsity & sparsity_in (casadi_int ind) const
 Get the sparsity pattern of an input, by index or name. More...
 
const Sparsity & sparsity_in (const std::string &iname) const
 Get the sparsity pattern of an input, by index or name. More...
 
const Sparsity & sparsity_out (casadi_int ind) const
 Get the sparsity pattern of an output, by index or name. More...
 
const Sparsity & sparsity_out (const std::string &iname) const
 Get the sparsity pattern of an output, by index or name. More...
 
bool is_diff_in (casadi_int ind) const
 Check which inputs or outputs are marked differentiable. More...
 
bool is_diff_out (casadi_int ind) const
 Check which inputs or outputs are marked differentiable. More...
 
std::vector< bool > is_diff_in () const
 Check which inputs or outputs are marked differentiable. More...
 
std::vector< bool > is_diff_out () const
 Check which inputs or outputs are marked differentiable. More...
 
Function wrap () const
 Wrap in an MXFunction whose graph is a single call to this function. More...
 
Function wrap (const std::string &name) const
 Wrap in an MXFunction whose graph is a single call to this function. More...
 
Function wrap_as_needed (const Dict &opts) const
 Wrap in an MXFunction constructed with the given options. More...
 
Function wrap_as_needed (const std::string &name, const Dict &opts) const
 Wrap in an MXFunction constructed with the given options. More...
 
const Sparsity sparsity_jac (casadi_int iind, casadi_int oind, bool compact=false, bool symmetric=false) const
 
const Sparsity sparsity_jac (const std::string &iind, casadi_int oind=0, bool compact=false, bool symmetric=false) const
 
const Sparsity sparsity_jac (casadi_int iind, const std::string &oind, bool compact=false, bool symmetric=false) const
 
const Sparsity sparsity_jac (const std::string &iind, const std::string &oind, bool compact=false, bool symmetric=false) const
 
void call (const std::vector< DM > &arg, std::vector< DM > &res, bool always_inline=false, bool never_inline=false) const
 Evaluate with a list or a dict of arguments; the result has the same form. More...
 
void call (const std::vector< SX > &arg, std::vector< SX > &res, bool always_inline=false, bool never_inline=false) const
 Evaluate with a list or a dict of arguments; the result has the same form. More...
 
void call (const std::vector< MX > &arg, std::vector< MX > &res, bool always_inline=false, bool never_inline=false) const
 Evaluate with a list or a dict of arguments; the result has the same form. More...
 
void call (const DMDict &arg, DMDict &res, bool always_inline=false, bool never_inline=false) const
 Evaluate with a list or a dict of arguments; the result has the same form. More...
 
void call (const SXDict &arg, SXDict &res, bool always_inline=false, bool never_inline=false) const
 Evaluate with a list or a dict of arguments; the result has the same form. More...
 
void call (const MXDict &arg, MXDict &res, bool always_inline=false, bool never_inline=false) const
 Evaluate with a list or a dict of arguments; the result has the same form. More...
 
std::vector< DM > operator() (const std::vector< DM > &arg) const
 
std::vector< SX > operator() (const std::vector< SX > &arg) const
 
std::vector< MX > operator() (const std::vector< MX > &arg) const
 
const DMDict operator() (const DMDict &arg) const
 
const SXDict operator() (const SXDict &arg) const
 
const MXDict operator() (const MXDict &arg) const
 
void operator() (std::vector< const double * > arg, std::vector< double * > res) const
 Evaluate with temporary memory allocation. More...
 
void operator() (std::vector< const bvec_t * > arg, std::vector< bvec_t * > res) const
 Evaluate with temporary memory allocation. More...
 
void operator() (std::vector< const SXElem * > arg, std::vector< SXElem * > res) const
 Evaluate with temporary memory allocation. More...
 
template<typename D >
void call_gen (std::vector< const D * > arg, std::vector< D * > res) const
 Evaluate with temporary memory allocation. More...
 
void operator() (VecArg arg, VecRes res) const
 Numerical evaluation. More...
 
void operator() (VecArg arg, MapRes res) const
 Numerical evaluation. More...
 
void operator() (VecArg arg, VPrRes res) const
 Numerical evaluation. More...
 
void operator() (VecArg arg, MPrRes res) const
 Numerical evaluation. More...
 
void operator() (MapArg arg, VecRes res) const
 Numerical evaluation. More...
 
void operator() (MapArg arg, MapRes res) const
 Numerical evaluation. More...
 
void operator() (MapArg arg, VPrRes res) const
 Numerical evaluation. More...
 
void operator() (MapArg arg, MPrRes res) const
 Numerical evaluation. More...
 
std::vector< DM > operator() (const DM &arg0) const
 
std::vector< SX > operator() (const SX &arg0) const
 
std::vector< MX > operator() (const MX &arg0) const
 
Function mapaccum (const std::string &name, casadi_int N, const Dict &opts=Dict()) const
 Create a function that applies this function N times, feeding outputs back. More...
 
Function mapaccum (const std::string &name, casadi_int N, casadi_int n_accum, const Dict &opts=Dict()) const
 Create a function that applies this function N times, feeding outputs back. More...
 
Function mapaccum (const std::string &name, casadi_int n, const std::vector< casadi_int > &accum_in, const std::vector< casadi_int > &accum_out, const Dict &opts=Dict()) const
 Create a function that applies this function N times, feeding outputs back. More...
 
Function mapaccum (const std::string &name, casadi_int n, const std::vector< std::string > &accum_in, const std::vector< std::string > &accum_out, const Dict &opts=Dict()) const
 Create a function that applies this function N times, feeding outputs back. More...
 
Function mapaccum (casadi_int N, const Dict &opts=Dict()) const
 Create a function that applies this function N times, feeding outputs back. More...
 
Function fold (casadi_int N, const Dict &opts=Dict()) const
 Create a function that applies this function N times, feeding outputs back. More...
 
Function map (const std::string &name, const std::string &parallelization, casadi_int n, const std::vector< casadi_int > &reduce_in, const std::vector< casadi_int > &reduce_out, const Dict &opts=Dict()) const
 Map where some inputs are shared and some outputs are summed. More...
 
Function map (const std::string &name, const std::string &parallelization, casadi_int n, const std::vector< std::string > &reduce_in, const std::vector< std::string > &reduce_out, const Dict &opts=Dict()) const
 Map where some inputs are shared and some outputs are summed. More...
 
Function map (casadi_int n, const std::vector< bool > &reduce_in, const std::vector< bool > &reduce_out=std::vector< bool >(), const Dict &opts=Dict()) const
 Map where some inputs are shared and some outputs are summed. More...
 
void generate_in (const std::string &fname, const std::vector< DM > &arg)
 Write or read a text file with the nonzeros of all inputs. More...
 
std::vector< DM > generate_in (const std::string &fname)
 Write or read a text file with the nonzeros of all inputs. More...
 
void generate_out (const std::string &fname, const std::vector< DM > &arg)
 Write or read a text file with the nonzeros of all outputs. More...
 
std::vector< DM > generate_out (const std::string &fname)
 Write or read a text file with the nonzeros of all outputs. More...
 
void export_code (const std::string &lang, const std::string &fname, const Dict &options=Dict()) const
 Export the algorithm as source code in another language. More...
 
void serialize (std::ostream &stream, const Dict &opts=Dict()) const
 Serialize. More...
 
void serialize (SerializingStream &s) const
 Serialize an object. More...
 
std::string serialize (const Dict &opts=Dict()) const
 Serialize to a string that deserialize turns back into an equal function. More...
 
void export_graph (const std::string &fname, const Dict &opts=Dict()) const
 Export a Function graph as .html, .dot, or .casadi_viz. More...
 
std::string export_graph (const Dict &opts=Dict()) const
 Return the .casadi_viz JSON bundle without writing a file. More...
 
void save (const std::string &fname, const Dict &opts=Dict()) const
 Save the function to a file that load reads back. More...
 
std::string export_code (const std::string &lang, const Dict &options=Dict()) const
 Export the algorithm as source code in another language. More...
 
void export_code (const std::string &lang, std::ostream &stream, const Dict &options=Dict()) const
 Export the algorithm as source code in another language. More...
 
const SX sx_in (casadi_int iind) const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
const SX sx_in (const std::string &iname) const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
const std::vector< SX > sx_in () const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
const MX mx_in (casadi_int ind) const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
const MX mx_in (const std::string &iname) const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
const std::vector< MX > mx_in () const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
template<typename T >
const T sym_in (casadi_int iind) const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
template<typename T >
const T sym_in (const std::string &iname) const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
template<typename T >
const std::vector< T > sym_in () const
 Create fresh symbols with the names and sparsity patterns of the inputs. More...
 
const SX sx_out (casadi_int oind) const
 Create fresh symbols with the names and sparsity patterns of the outputs. More...
 
const SX sx_out (const std::string &oname) const
 Create fresh symbols with the names and sparsity patterns of the outputs. More...
 
const std::vector< SX > sx_out () const
 Create fresh symbols with the names and sparsity patterns of the outputs. More...
 
const MX mx_out (casadi_int ind) const
 Create fresh symbols with the names and sparsity patterns of the outputs. More...
 
const MX mx_out (const std::string &oname) const
 Create fresh symbols with the names and sparsity patterns of the outputs. More...
 
const std::vector< MX > mx_out () const
 Create fresh symbols with the names and sparsity patterns of the outputs. More...
 
std::vector< double > nz_from_in (const std::vector< DM > &arg) const
 Convert between a list of input/output matrices and one flat list of. More...
 
std::vector< double > nz_from_out (const std::vector< DM > &arg) const
 Convert between a list of input/output matrices and one flat list of. More...
 
std::vector< DM > nz_to_in (const std::vector< double > &arg) const
 Convert between a list of input/output matrices and one flat list of. More...
 
std::vector< DM > nz_to_out (const std::vector< double > &arg) const
 Convert between a list of input/output matrices and one flat list of. More...
 
DMDict convert_in (const std::vector< DM > &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
std::vector< DM > convert_in (const DMDict &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
DMDict convert_out (const std::vector< DM > &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
std::vector< DM > convert_out (const DMDict &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
SXDict convert_in (const std::vector< SX > &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
std::vector< SX > convert_in (const SXDict &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
SXDict convert_out (const std::vector< SX > &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
std::vector< SX > convert_out (const SXDict &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
MXDict convert_in (const std::vector< MX > &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
std::vector< MX > convert_in (const MXDict &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
MXDict convert_out (const std::vector< MX > &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
std::vector< MX > convert_out (const MXDict &arg) const
 Convert between a list and a dict of inputs or outputs. More...
 
bool has_spfwd () const
 Check whether the class supports forward (has_spfwd) or reverse (has_sprev) More...
 
bool has_sprev () const
 Check whether the class supports forward (has_spfwd) or reverse (has_sprev) More...
 

Static Public Member Functions

static std::string type_name ()
 Get the type name, always "Function". More...
 
static Function create (FunctionInternal *node)
 Create from node. More...
 
static Function create (FunctionInternal *node, const Dict &opts)
 Create from node and initialize. More...
 
static Function conditional (const std::string &name, const std::vector< Function > &f, const Function &f_def, const Dict &opts=Dict())
 Create a function that selects one of several functions by an index input. More...
 
static Function conditional (const std::string &name, const Function &f, const Dict &opts=Dict())
 Create a function that calls f when its first input is nonzero and. More...
 
static Function bspline (const std::string &name, const std::vector< std::vector< double > > &knots, const std::vector< double > &coeffs, const std::vector< casadi_int > &degree, casadi_int m=1, const Dict &opts=Dict())
 Create a function evaluating a B-spline with known coefficients. More...
 
static Function if_else (const std::string &name, const Function &f_true, const Function &f_false, const Dict &opts=Dict())
 Create a function that evaluates f_true or f_false depending on. More...
 
static bool test_cast (const SharedObjectInternal *ptr)
 Check if a particular cast is allowed. More...
 
static bool check_name (const std::string &name)
 Check whether a string is a valid function name. More...
 
static std::string fix_name (const std::string &name)
 Turn any string into a valid function name as defined by check_name. More...
 
static Function deserialize (std::istream &stream)
 Build a function from a serialization stream. More...
 
static Function deserialize (const std::string &s)
 Build a function from a string produced by serialize. More...
 
static Function load (const std::string &filename)
 Read a function from a file written by save. More...
 
static Function deserialize (DeserializingStream &s)
 Build a function from a DeserializingStream (C++ serialization API) More...
 
static std::vector< SX > order (const std::vector< SX > &expr)
 
static std::vector< MX > order (const std::vector< MX > &expr)
 
static Function jit (const std::string &name, const std::string &body, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Create a just-in-time compiled function from a C language string. More...
 
static Function jit (const std::string &name, const std::string &body, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const std::vector< Sparsity > &sparsity_in, const std::vector< Sparsity > &sparsity_out, const Dict &opts=Dict())
 Create a just-in-time compiled function from a C language string. More...
 

Protected Member Functions

Function mapaccum (const std::string &name, const std::vector< Function > &chain, casadi_int n_accum=1, const Dict &opts=Dict()) const
 Helper function for mapaccum. More...
 
void count_up ()
 
void count_down ()
 
void construct (const std::string &name, const std::vector< SX > &ex_in, const std::vector< SX > &ex_out, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts)
 Called by constructors. More...
 
void construct (const std::string &name, const std::vector< MX > &ex_in, const std::vector< MX > &ex_out, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts)
 Called by constructors. More...
 
template<typename M >
void construct (const std::string &name, const std::map< std::string, M > &dict, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts)
 Called by constructors. More...
 

Static Protected Member Functions

static bool proceed_to (std::istream &file, const std::string &str)
 Helper function for parsing .casadi files. More...
 
typedef const std::vector< std::vector< double > > & VecArg
 Supported arguments for numerical evaluation and converters. More...
 
typedef std::vector< std::vector< double > > & VecRes
 Supported arguments for numerical evaluation and converters. More...
 
typedef std::vector< std::vector< double > * > VPrRes
 Supported arguments for numerical evaluation and converters. More...
 
typedef const std::map< std::string, std::vector< double > > & MapArg
 Supported arguments for numerical evaluation and converters. More...
 
typedef std::map< std::string, std::vector< double > > & MapRes
 Supported arguments for numerical evaluation and converters. More...
 
typedef std::map< std::string, std::vector< double > * > MPrRes
 Supported arguments for numerical evaluation and converters. More...
 
std::vector< const double * > buf_in (VecArg arg) const
 Supported arguments for numerical evaluation and converters. More...
 
std::vector< double * > buf_out (VecRes res) const
 Supported arguments for numerical evaluation and converters. More...
 
std::vector< double * > buf_out (VPrRes res) const
 Supported arguments for numerical evaluation and converters. More...
 
std::vector< const double * > buf_in (MapArg arg) const
 Supported arguments for numerical evaluation and converters. More...
 
std::vector< double * > buf_out (MapRes res) const
 Supported arguments for numerical evaluation and converters. More...
 
std::vector< double * > buf_out (MPrRes res) const
 Supported arguments for numerical evaluation and converters. More...
 

Member Typedef Documentation

◆ AuxOut

typedef std::map<std::string, std::vector<std::string> > casadi::Function::AuxOut

Definition at line 1546 of file function.hpp.

◆ base_type

Definition at line 103 of file shared_object.hpp.

◆ internal_base_type

Definition at line 102 of file shared_object.hpp.

◆ MapArg

typedef const std::map<std::string, std::vector<double> >& casadi::Function::MapArg

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

Definition at line 2459 of file function.hpp.

◆ MapRes

typedef std::map<std::string, std::vector<double> >& casadi::Function::MapRes

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

Definition at line 2461 of file function.hpp.

◆ MPrRes

typedef std::map<std::string, std::vector<double>*> casadi::Function::MPrRes

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

Definition at line 2463 of file function.hpp.

◆ VecArg

typedef const std::vector<std::vector<double> >& casadi::Function::VecArg

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

Definition at line 2452 of file function.hpp.

◆ VecRes

typedef std::vector<std::vector<double> >& casadi::Function::VecRes

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

Definition at line 2454 of file function.hpp.

◆ VPrRes

typedef std::vector<std::vector<double>*> casadi::Function::VPrRes

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

Definition at line 2456 of file function.hpp.

Constructor & Destructor Documentation

◆ Function() [1/20]

casadi::Function::Function ( )

A null Function has name "null", is_null() is true, and any other member function raises an error. Use it only as a placeholder to be assigned later.

>>> f = Function()
>>> f.is_null(), f.name()
(True, 'null')

>> f = Function(); disp(f.is_null()), disp(f.name())
1
null

julia> f = ca.Function();
julia> ca.is_null(f), ca.name(f)
(true, "null")

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

Definition at line 58 of file function.cpp.

58  {
59  }

Referenced by bspline(), deserialize(), expand(), find_function(), fold(), map(), mapaccum(), and transform().

◆ Function() [2/20]

casadi::Function::Function ( const std::string &  fname)

Use Function::load to read a file written by Function::save.

See also
load, save

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

Definition at line 92 of file function.cpp.

92  {
93  casadi_error("Not implemented");
94  }

◆ Function() [3/20]

casadi::Function::Function ( const std::string &  name,
const std::vector< SX > &  ex_in,
const std::vector< SX > &  ex_out,
const Dict &  opts = Dict() 
)

The result is an SXFunction: a flat list of scalar instructions that is cheap to evaluate but has no notion of matrix structure (see expand for the difference with an MXFunction).

Every symbolic primitive that appears in ex_out must be present in ex_in, otherwise construction fails with "Initialization failed since variables [...] are free" (the symbol was forgotten in the input list). Pass option "allow_free": true to construct anyway; such a function can only be called symbolically. Each input must be a purely symbolic matrix (symbols or a concatenation of symbols); an output may be any expression, including constants and empty matrices. The sparsity patterns of the expressions become sparsity_in and sparsity_out.

Parameters
nameDisplay name, used in error messages and generated code. Must start with a letter and contain only letters, digits and non-consecutive underscores (see check_name); otherwise an error is raised.
ex_inList of input expressions, each a symbolic SX
ex_outList of output expressions
name_inNames of the inputs; defaults to i0, i1, ...; duplicates raise an error unless option "allow_duplicate_io_names" is set
name_outNames of the outputs; defaults to o0, o1, ...
optsOptions, see the table below. The common ones are "cse" (eliminate common subexpressions), "live_variables", "is_diff_in"/"is_diff_out", "default_in", "allow_free", "jit"

The dict overload takes a single map from name to expression; name_in and name_out select which keys are inputs and outputs, in that order. A key that is in neither list raises "Unknown dictionary entry". A missing key gives an empty (0-by-0) input or output.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)])
>>> f
Function(f:(i0,i1[2])->(o0[2],o1) SXFunction)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.name_in(), f.name_out()
(['x', 'y'], ['r', 's'])
>>> g = Function("g", {"x": x, "y": y, "r": x*y}, ["x", "y"], ["r"])
>>> g
Function(g:(x,y[2])->(r[2]) SXFunction)
>>> p = SX.sym("p")
>>> try:
...   Function("h", [x], [x*p])
... except RuntimeError as e:
...   print("Initialization failed" in str(e), "[p] are free" in str(e))
True True
>>> h = Function("h", [x], [x*p], {"allow_free": True})
>>> h.get_free()
['p']
>>> try:
...   Function("my func", [x], [x])
... except RuntimeError as e:
...   print("Function name is not valid" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}); disp(f)
f:(i0,i1[2])->(o0[2],o1) SXFunction
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> f.name_in(), f.name_out()
x
y
r
s
>> g = Function('g', struct('x', x, 'y', y, 'r', x*y), {'x', 'y'}, {'r'}); disp(g)
g:(x,y[2])->(r[2]) SXFunction
>> p = SX.sym('p');
>> try, Function('h', {x}, {x*p}); catch e, disp(contains(e.message, '[p] are free')); end
1
>> h = Function('h', {x}, {x*p}, struct('allow_free', true)); disp(h.get_free())
p
>> try, Function('my func', {x}, {x}); catch e, disp(contains(e.message, 'not valid')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)])
Function(f:(i0,i1[2])->(o0[2],o1) SXFunction)
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.name_in(f), ca.name_out(f)
(["x", "y"], ["r", "s"])
julia> g = ca.Function("g", Dict("x" => x, "y" => y, "r" => x*y), ["x", "y"], ["r"])
Function(g:(x,y[2])->(r[2]) SXFunction)
julia> p = ca.SX.sym("p");
julia> try
           ca.Function("h", [x], [x*p])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Initialization failed", msg), " ",
                   occursin("[p] are free", msg))
       end
true true
julia> h = ca.Function("h", [x], [x*p], Dict("allow_free" => true));
julia> ca.get_free(h)
1-element Vector{String}:
 "p"
julia> try
           ca.Function("my func", [x], [x])
       catch e
           println(occursin("Function name is not valid", sprint(showerror, e)))
       end
true

See also
expand, check_name, has_free

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

Definition at line 96 of file function.cpp.

98  {
99  construct(name, ex_in, ex_out, {}, {}, opts);
100  }
void construct(const std::string &name, const std::vector< SX > &ex_in, const std::vector< SX > &ex_out, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts)
Called by constructors.
Definition: function.cpp:221
const std::string & name() const
Get the name given at construction ("null" for a null object)
Definition: function.cpp:1504

References construct(), and name().

◆ Function() [4/20]

casadi::Function::Function ( const std::string &  name,
const std::vector< SX > &  ex_in,
const std::vector< SX > &  ex_out,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts = Dict() 
)

The result is an SXFunction: a flat list of scalar instructions that is cheap to evaluate but has no notion of matrix structure (see expand for the difference with an MXFunction).

Every symbolic primitive that appears in ex_out must be present in ex_in, otherwise construction fails with "Initialization failed since variables [...] are free" (the symbol was forgotten in the input list). Pass option "allow_free": true to construct anyway; such a function can only be called symbolically. Each input must be a purely symbolic matrix (symbols or a concatenation of symbols); an output may be any expression, including constants and empty matrices. The sparsity patterns of the expressions become sparsity_in and sparsity_out.

Parameters
nameDisplay name, used in error messages and generated code. Must start with a letter and contain only letters, digits and non-consecutive underscores (see check_name); otherwise an error is raised.
ex_inList of input expressions, each a symbolic SX
ex_outList of output expressions
name_inNames of the inputs; defaults to i0, i1, ...; duplicates raise an error unless option "allow_duplicate_io_names" is set
name_outNames of the outputs; defaults to o0, o1, ...
optsOptions, see the table below. The common ones are "cse" (eliminate common subexpressions), "live_variables", "is_diff_in"/"is_diff_out", "default_in", "allow_free", "jit"

The dict overload takes a single map from name to expression; name_in and name_out select which keys are inputs and outputs, in that order. A key that is in neither list raises "Unknown dictionary entry". A missing key gives an empty (0-by-0) input or output.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)])
>>> f
Function(f:(i0,i1[2])->(o0[2],o1) SXFunction)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.name_in(), f.name_out()
(['x', 'y'], ['r', 's'])
>>> g = Function("g", {"x": x, "y": y, "r": x*y}, ["x", "y"], ["r"])
>>> g
Function(g:(x,y[2])->(r[2]) SXFunction)
>>> p = SX.sym("p")
>>> try:
...   Function("h", [x], [x*p])
... except RuntimeError as e:
...   print("Initialization failed" in str(e), "[p] are free" in str(e))
True True
>>> h = Function("h", [x], [x*p], {"allow_free": True})
>>> h.get_free()
['p']
>>> try:
...   Function("my func", [x], [x])
... except RuntimeError as e:
...   print("Function name is not valid" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}); disp(f)
f:(i0,i1[2])->(o0[2],o1) SXFunction
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> f.name_in(), f.name_out()
x
y
r
s
>> g = Function('g', struct('x', x, 'y', y, 'r', x*y), {'x', 'y'}, {'r'}); disp(g)
g:(x,y[2])->(r[2]) SXFunction
>> p = SX.sym('p');
>> try, Function('h', {x}, {x*p}); catch e, disp(contains(e.message, '[p] are free')); end
1
>> h = Function('h', {x}, {x*p}, struct('allow_free', true)); disp(h.get_free())
p
>> try, Function('my func', {x}, {x}); catch e, disp(contains(e.message, 'not valid')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)])
Function(f:(i0,i1[2])->(o0[2],o1) SXFunction)
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.name_in(f), ca.name_out(f)
(["x", "y"], ["r", "s"])
julia> g = ca.Function("g", Dict("x" => x, "y" => y, "r" => x*y), ["x", "y"], ["r"])
Function(g:(x,y[2])->(r[2]) SXFunction)
julia> p = ca.SX.sym("p");
julia> try
           ca.Function("h", [x], [x*p])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Initialization failed", msg), " ",
                   occursin("[p] are free", msg))
       end
true true
julia> h = ca.Function("h", [x], [x*p], Dict("allow_free" => true));
julia> ca.get_free(h)
1-element Vector{String}:
 "p"
julia> try
           ca.Function("my func", [x], [x])
       catch e
           println(occursin("Function name is not valid", sprint(showerror, e)))
       end
true

See also
expand, check_name, has_free

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

Definition at line 102 of file function.cpp.

106  {
107  construct(name, ex_in, ex_out, name_in, name_out, opts);
108  }
const std::vector< std::string > & name_in() const
Get the names of all inputs, in order.
Definition: function.cpp:1113
const std::vector< std::string > & name_out() const
Get the names of all outputs, in order.
Definition: function.cpp:1117

References construct(), name(), name_in(), and name_out().

◆ Function() [5/20]

casadi::Function::Function ( const std::string &  name,
const std::map< std::string, SX > &  dict,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts = Dict() 
)

The result is an SXFunction: a flat list of scalar instructions that is cheap to evaluate but has no notion of matrix structure (see expand for the difference with an MXFunction).

Every symbolic primitive that appears in ex_out must be present in ex_in, otherwise construction fails with "Initialization failed since variables [...] are free" (the symbol was forgotten in the input list). Pass option "allow_free": true to construct anyway; such a function can only be called symbolically. Each input must be a purely symbolic matrix (symbols or a concatenation of symbols); an output may be any expression, including constants and empty matrices. The sparsity patterns of the expressions become sparsity_in and sparsity_out.

Parameters
nameDisplay name, used in error messages and generated code. Must start with a letter and contain only letters, digits and non-consecutive underscores (see check_name); otherwise an error is raised.
ex_inList of input expressions, each a symbolic SX
ex_outList of output expressions
name_inNames of the inputs; defaults to i0, i1, ...; duplicates raise an error unless option "allow_duplicate_io_names" is set
name_outNames of the outputs; defaults to o0, o1, ...
optsOptions, see the table below. The common ones are "cse" (eliminate common subexpressions), "live_variables", "is_diff_in"/"is_diff_out", "default_in", "allow_free", "jit"

The dict overload takes a single map from name to expression; name_in and name_out select which keys are inputs and outputs, in that order. A key that is in neither list raises "Unknown dictionary entry". A missing key gives an empty (0-by-0) input or output.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)])
>>> f
Function(f:(i0,i1[2])->(o0[2],o1) SXFunction)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.name_in(), f.name_out()
(['x', 'y'], ['r', 's'])
>>> g = Function("g", {"x": x, "y": y, "r": x*y}, ["x", "y"], ["r"])
>>> g
Function(g:(x,y[2])->(r[2]) SXFunction)
>>> p = SX.sym("p")
>>> try:
...   Function("h", [x], [x*p])
... except RuntimeError as e:
...   print("Initialization failed" in str(e), "[p] are free" in str(e))
True True
>>> h = Function("h", [x], [x*p], {"allow_free": True})
>>> h.get_free()
['p']
>>> try:
...   Function("my func", [x], [x])
... except RuntimeError as e:
...   print("Function name is not valid" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}); disp(f)
f:(i0,i1[2])->(o0[2],o1) SXFunction
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> f.name_in(), f.name_out()
x
y
r
s
>> g = Function('g', struct('x', x, 'y', y, 'r', x*y), {'x', 'y'}, {'r'}); disp(g)
g:(x,y[2])->(r[2]) SXFunction
>> p = SX.sym('p');
>> try, Function('h', {x}, {x*p}); catch e, disp(contains(e.message, '[p] are free')); end
1
>> h = Function('h', {x}, {x*p}, struct('allow_free', true)); disp(h.get_free())
p
>> try, Function('my func', {x}, {x}); catch e, disp(contains(e.message, 'not valid')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)])
Function(f:(i0,i1[2])->(o0[2],o1) SXFunction)
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.name_in(f), ca.name_out(f)
(["x", "y"], ["r", "s"])
julia> g = ca.Function("g", Dict("x" => x, "y" => y, "r" => x*y), ["x", "y"], ["r"])
Function(g:(x,y[2])->(r[2]) SXFunction)
julia> p = ca.SX.sym("p");
julia> try
           ca.Function("h", [x], [x*p])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Initialization failed", msg), " ",
                   occursin("[p] are free", msg))
       end
true true
julia> h = ca.Function("h", [x], [x*p], Dict("allow_free" => true));
julia> ca.get_free(h)
1-element Vector{String}:
 "p"
julia> try
           ca.Function("my func", [x], [x])
       catch e
           println(occursin("Function name is not valid", sprint(showerror, e)))
       end
true

See also
expand, check_name, has_free

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

Definition at line 183 of file function.cpp.

185  {
186  construct(name, dict, name_in, name_out, opts);
187  }

References construct(), name(), name_in(), and name_out().

◆ Function() [6/20]

casadi::Function::Function ( const std::string &  name,
const std::vector< MX > &  ex_in,
const std::vector< MX > &  ex_out,
const Dict &  opts = Dict() 
)

The result is an MXFunction: a graph of matrix-valued nodes that may embed calls to other Function objects (solvers, integrators, SX functions, ...). Compared with an SXFunction it uses less memory and supports every operation, but is slower per node to evaluate; call expand to convert when all nodes are expandable.

The rules on free variables, naming and the dict overload are the same as for the SX constructor. Additional MX-only options: "post_expand" (expand right after construction) and "post_expand_options".

Parameters
nameDisplay name, must satisfy check_name
ex_inList of symbolic MX inputs
ex_outList of MX output expressions
name_inInput names; defaults to i0, i1, ...
name_outOutput names; defaults to o0, o1, ...
optsOptions, see the table below

>>> x = MX.sym("x", 2); A = MX.sym("A", 2, 2)
>>> f = Function("f", [A, x], [A @ x, norm_2(x)], ["A", "x"], ["Ax", "nrm"])
>>> f
Function(f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction)
>>> f.class_name(), f.n_instructions()
('MXFunction', 7)
>>> f.expand()
Function(f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction)
>>> g = Function("g", [x], [x], {"post_expand": True})
>>> g.class_name()
'SXFunction'

>> x = MX.sym('x', 2); A = MX.sym('A', 2, 2);
>> f = Function('f', {A, x}, {A*x, norm_2(x)}, {'A', 'x'}, {'Ax', 'nrm'}); disp(f)
f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction
>> f.class_name(), f.n_instructions()
MXFunction
7
>> f.expand()
f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction
>> g = Function('g', {x}, {x}, struct('post_expand', true)); disp(g.class_name())
SXFunction

julia> x = ca.MX.sym("x", 2); A = ca.MX.sym("A", 2, 2);
julia> f = ca.Function("f", [A, x], [A * x, ca.norm_2(x)], ["A", "x"], ["Ax", "nrm"])
Function(f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction)
julia> ca.class_name(f), ca.n_instructions(f)
("MXFunction", 7)
julia> ca.expand(f)
Function(f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction)
julia> g = ca.Function("g", [x], [x], Dict("post_expand" => true));
julia> ca.class_name(g)
"SXFunction"

See also
expand, has_free

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

Definition at line 110 of file function.cpp.

112  {
113  construct(name, ex_in, ex_out, {}, {}, opts);
114  }

References construct(), and name().

◆ Function() [7/20]

casadi::Function::Function ( const std::string &  name,
const std::vector< MX > &  ex_in,
const std::vector< MX > &  ex_out,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts = Dict() 
)

The result is an MXFunction: a graph of matrix-valued nodes that may embed calls to other Function objects (solvers, integrators, SX functions, ...). Compared with an SXFunction it uses less memory and supports every operation, but is slower per node to evaluate; call expand to convert when all nodes are expandable.

The rules on free variables, naming and the dict overload are the same as for the SX constructor. Additional MX-only options: "post_expand" (expand right after construction) and "post_expand_options".

Parameters
nameDisplay name, must satisfy check_name
ex_inList of symbolic MX inputs
ex_outList of MX output expressions
name_inInput names; defaults to i0, i1, ...
name_outOutput names; defaults to o0, o1, ...
optsOptions, see the table below

>>> x = MX.sym("x", 2); A = MX.sym("A", 2, 2)
>>> f = Function("f", [A, x], [A @ x, norm_2(x)], ["A", "x"], ["Ax", "nrm"])
>>> f
Function(f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction)
>>> f.class_name(), f.n_instructions()
('MXFunction', 7)
>>> f.expand()
Function(f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction)
>>> g = Function("g", [x], [x], {"post_expand": True})
>>> g.class_name()
'SXFunction'

>> x = MX.sym('x', 2); A = MX.sym('A', 2, 2);
>> f = Function('f', {A, x}, {A*x, norm_2(x)}, {'A', 'x'}, {'Ax', 'nrm'}); disp(f)
f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction
>> f.class_name(), f.n_instructions()
MXFunction
7
>> f.expand()
f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction
>> g = Function('g', {x}, {x}, struct('post_expand', true)); disp(g.class_name())
SXFunction

julia> x = ca.MX.sym("x", 2); A = ca.MX.sym("A", 2, 2);
julia> f = ca.Function("f", [A, x], [A * x, ca.norm_2(x)], ["A", "x"], ["Ax", "nrm"])
Function(f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction)
julia> ca.class_name(f), ca.n_instructions(f)
("MXFunction", 7)
julia> ca.expand(f)
Function(f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction)
julia> g = ca.Function("g", [x], [x], Dict("post_expand" => true));
julia> ca.class_name(g)
"SXFunction"

See also
expand, has_free

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

Definition at line 116 of file function.cpp.

120  {
121  construct(name, ex_in, ex_out, name_in, name_out, opts);
122  }

References construct(), name(), name_in(), and name_out().

◆ Function() [8/20]

casadi::Function::Function ( const std::string &  name,
const std::map< std::string, MX > &  dict,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts = Dict() 
)

The result is an MXFunction: a graph of matrix-valued nodes that may embed calls to other Function objects (solvers, integrators, SX functions, ...). Compared with an SXFunction it uses less memory and supports every operation, but is slower per node to evaluate; call expand to convert when all nodes are expandable.

The rules on free variables, naming and the dict overload are the same as for the SX constructor. Additional MX-only options: "post_expand" (expand right after construction) and "post_expand_options".

Parameters
nameDisplay name, must satisfy check_name
ex_inList of symbolic MX inputs
ex_outList of MX output expressions
name_inInput names; defaults to i0, i1, ...
name_outOutput names; defaults to o0, o1, ...
optsOptions, see the table below

>>> x = MX.sym("x", 2); A = MX.sym("A", 2, 2)
>>> f = Function("f", [A, x], [A @ x, norm_2(x)], ["A", "x"], ["Ax", "nrm"])
>>> f
Function(f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction)
>>> f.class_name(), f.n_instructions()
('MXFunction', 7)
>>> f.expand()
Function(f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction)
>>> g = Function("g", [x], [x], {"post_expand": True})
>>> g.class_name()
'SXFunction'

>> x = MX.sym('x', 2); A = MX.sym('A', 2, 2);
>> f = Function('f', {A, x}, {A*x, norm_2(x)}, {'A', 'x'}, {'Ax', 'nrm'}); disp(f)
f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction
>> f.class_name(), f.n_instructions()
MXFunction
7
>> f.expand()
f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction
>> g = Function('g', {x}, {x}, struct('post_expand', true)); disp(g.class_name())
SXFunction

julia> x = ca.MX.sym("x", 2); A = ca.MX.sym("A", 2, 2);
julia> f = ca.Function("f", [A, x], [A * x, ca.norm_2(x)], ["A", "x"], ["Ax", "nrm"])
Function(f:(A[2x2],x[2])->(Ax[2],nrm) MXFunction)
julia> ca.class_name(f), ca.n_instructions(f)
("MXFunction", 7)
julia> ca.expand(f)
Function(f:(A[2x2],x[2])->(Ax[2],nrm) SXFunction)
julia> g = ca.Function("g", [x], [x], Dict("post_expand" => true));
julia> ca.class_name(g)
"SXFunction"

See also
expand, has_free

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

Definition at line 189 of file function.cpp.

191  {
192  construct(name, dict, name_in, name_out, opts);
193  }

References construct(), name(), name_in(), and name_out().

◆ Function() [9/20]

casadi::Function::Function ( const std::string &  name,
SXIList  ex_in,
const SXVector &  ex_out,
const Dict &  opts = Dict() 
)

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

Definition at line 124 of file function.cpp.

125  {
126  construct(name, SXVector(ex_in), ex_out, {}, {}, opts);
127  }
std::vector< SX > SXVector
Definition: sx_fwd.hpp:37

References construct(), and name().

◆ Function() [10/20]

casadi::Function::Function ( const std::string &  name,
const SXVector &  ex_in,
SXIList  ex_out,
const Dict &  opts = Dict() 
)

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

Definition at line 129 of file function.cpp.

130  {
131  construct(name, ex_in, SXVector(ex_out), {}, {}, opts);
132  }

References construct(), and name().

◆ Function() [11/20]

casadi::Function::Function ( const std::string &  name,
SXIList  ex_in,
SXIList  ex_out,
const Dict &  opts = Dict() 
)

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

Definition at line 134 of file function.cpp.

134  {
135  construct(name, SXVector(ex_in), SXVector(ex_out), {}, {}, opts);
136  }

References construct(), and name().

◆ Function() [12/20]

casadi::Function::Function ( const std::string &  name,
SXIList  ex_in,
const SXVector &  ex_out,
const StringVector &  name_in,
const StringVector &  name_out,
const Dict &  opts = Dict() 
)

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

Definition at line 138 of file function.cpp.

140  {
141  construct(name, SXVector(ex_in), ex_out, name_in, name_out, opts);
142  }

References construct(), name(), name_in(), and name_out().

◆ Function() [13/20]

casadi::Function::Function ( const std::string &  name,
const SXVector &  ex_in,
SXIList  ex_out,
const StringVector &  name_in,
const StringVector &  name_out,
const Dict &  opts = Dict() 
)

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

Definition at line 144 of file function.cpp.

145  {
146  construct(name, ex_in, SXVector(ex_out), name_in, name_out, opts);
147  }

References construct(), name(), name_in(), and name_out().

◆ Function() [14/20]

casadi::Function::Function ( const std::string &  name,
SXIList  ex_in,
SXIList  ex_out,
const StringVector &  name_in,
const StringVector &  name_out,
const Dict &  opts = Dict() 
)

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

Definition at line 149 of file function.cpp.

150  {
151  construct(name, SXVector(ex_in), SXVector(ex_out), name_in, name_out, opts);
152  }

References construct(), name(), name_in(), and name_out().

◆ Function() [15/20]

casadi::Function::Function ( const std::string &  name,
MXIList  ex_in,
const MXVector &  ex_out,
const Dict &  opts = Dict() 
)

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

Definition at line 154 of file function.cpp.

155  {
156  construct(name, MXVector(ex_in), ex_out, {}, {}, opts);
157  }
std::vector< MX > MXVector
Definition: mx.hpp:5148

References construct(), and name().

◆ Function() [16/20]

casadi::Function::Function ( const std::string &  name,
const MXVector &  ex_in,
MXIList  ex_out,
const Dict &  opts = Dict() 
)

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

Definition at line 159 of file function.cpp.

160  {
161  construct(name, ex_in, MXVector(ex_out), {}, {}, opts);
162  }

References construct(), and name().

◆ Function() [17/20]

casadi::Function::Function ( const std::string &  name,
MXIList  ex_in,
MXIList  ex_out,
const Dict &  opts = Dict() 
)

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

Definition at line 164 of file function.cpp.

164  {
165  construct(name, MXVector(ex_in), MXVector(ex_out), {}, {}, opts);
166  }

References construct(), and name().

◆ Function() [18/20]

casadi::Function::Function ( const std::string &  name,
MXIList  ex_in,
const MXVector &  ex_out,
const StringVector &  name_in,
const StringVector &  name_out,
const Dict &  opts = Dict() 
)

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

Definition at line 168 of file function.cpp.

169  {
170  construct(name, MXVector(ex_in), ex_out, name_in, name_out, opts);
171  }

References construct(), name(), name_in(), and name_out().

◆ Function() [19/20]

casadi::Function::Function ( const std::string &  name,
const MXVector &  ex_in,
MXIList  ex_out,
const StringVector &  name_in,
const StringVector &  name_out,
const Dict &  opts = Dict() 
)

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

Definition at line 173 of file function.cpp.

174  {
175  construct(name, ex_in, MXVector(ex_out), name_in, name_out, opts);
176  }

References construct(), name(), name_in(), and name_out().

◆ Function() [20/20]

casadi::Function::Function ( const std::string &  name,
MXIList  ex_in,
MXIList  ex_out,
const StringVector &  name_in,
const StringVector &  name_out,
const Dict &  opts = Dict() 
)

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

Definition at line 178 of file function.cpp.

179  {
180  construct(name, MXVector(ex_in), MXVector(ex_out), name_in, name_out, opts);
181  }

References construct(), name(), name_in(), and name_out().

◆ ~Function()

casadi::Function::~Function ( )

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

Definition at line 61 of file function.cpp.

61  {
62  }

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  }

◆ activity()

std::vector< bool > casadi::Function::activity ( const std::vector< bool > &  arg) const

arg is a flat activity mask over all input nonzeros (size nnz_in(), true = active = possibly nonzero); the result is the corresponding mask over all output nonzeros (size nnz_out()). An output that comes out inactive (false) is guaranteed zero for any value of the active inputs. Unlike sparsity propagation this exploits annihilation: an inactive operand of a multiply kills the product.

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

Definition at line 1269 of file function.cpp.

1269  {
1270  casadi_assert(arg.size()==static_cast<size_t>(nnz_in()),
1271  "activity: expected mask of size nnz_in()=" + str(nnz_in())
1272  + ", got " + str(arg.size()) + ".");
1273 
1274  // bvec buffers for the concatenated input/output nonzeros
1275  std::vector<bvec_t> in_buf(nnz_in()), out_buf(nnz_out(), 0);
1276  for (casadi_int k=0; k<nnz_in(); ++k) in_buf[k] = arg[k] ? ~static_cast<bvec_t>(0) : 0;
1277 
1278  // Per-input/output pointers into the buffers
1279  std::vector<const bvec_t*> argp(sz_arg(), nullptr);
1280  std::vector<bvec_t*> resp(sz_res(), nullptr);
1281  casadi_int off = 0;
1282  for (casadi_int i=0; i<n_in(); ++i) { argp[i] = get_ptr(in_buf)+off; off += nnz_in(i); }
1283  off = 0;
1284  for (casadi_int i=0; i<n_out(); ++i) { resp[i] = get_ptr(out_buf)+off; off += nnz_out(i); }
1285 
1286  // Work vectors
1287  std::vector<casadi_int> iw(sz_iw());
1288  std::vector<bvec_t> w(sz_w());
1289 
1290  eval_activity(get_ptr(argp), get_ptr(resp), get_ptr(iw), get_ptr(w));
1291 
1292  std::vector<bool> ret(nnz_out());
1293  for (casadi_int k=0; k<nnz_out(); ++k) ret[k] = out_buf[k]!=0;
1294  return ret;
1295  }
casadi_int nnz_out() const
Get the number of structural nonzeros of one output, or of all outputs.
Definition: function.cpp:1007
size_t sz_res() const
Get the length of the output pointer array needed to evaluate (at least.
Definition: function.cpp:1237
size_t sz_iw() const
Get the length of the integer work vector needed to evaluate.
Definition: function.cpp:1239
casadi_int n_out() const
Get the number of function outputs.
Definition: function.cpp:975
casadi_int n_in() const
Get the number of function inputs.
Definition: function.cpp:971
size_t sz_w() const
Get the length of the real work vector needed to evaluate.
Definition: function.cpp:1241
size_t sz_arg() const
Get the length of the input pointer array needed to evaluate (at least n_in)
Definition: function.cpp:1235
casadi_int nnz_in() const
Get the number of structural nonzeros of one input, or of all inputs.
Definition: function.cpp:1003
int eval_activity(const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, int mem=0) const
Propagate signal activity forward (bit set = active (possibly nonzero))
Definition: function.cpp:1260
std::string str(const T &v)
String representation, any type.
T * get_ptr(std::vector< T > &v)
Get a pointer to the data contained in the vector.

References eval_activity(), casadi::get_ptr(), n_in(), n_out(), nnz_in(), nnz_out(), casadi::str(), sz_arg(), sz_iw(), sz_res(), and sz_w().

Referenced by casadi::Call::create().

◆ assert_size_in()

void casadi::Function::assert_size_in ( casadi_int  i,
casadi_int  nrow,
casadi_int  ncol 
) const

>>> f = Function("f", [SX.sym("x", 2)], [SX(1, 3)])
>>> f.assert_size_in(0, 2, 1)
>>> try:
...   f.assert_size_out(0, 2, 1)
... except RuntimeError as e:
...   print("Expected 2-by-1 but got 1-by-3" in str(e))
True

>> f = Function('f', {SX.sym('x', 2)}, {SX(1, 3)});
>> f.assert_size_in(0, 2, 1)
>> try, f.assert_size_out(0, 2, 1); catch e, msg = e.message; end
>> contains(msg, 'Expected 2-by-1 but got 1-by-3')
1

julia> f = ca.Function("f", [ca.SX.sym("x", 2)], [ca.SX(1, 3)]);
julia> ca.assert_size_in(f, 0, 2, 1)
julia> try
           ca.assert_size_out(f, 0, 2, 1)
       catch e
           println(occursin("Expected 2-by-1 but got 1-by-3", sprint(showerror, e)))
       end
true

See also
assert_size_out, size_in

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

Definition at line 1982 of file function.cpp.

1982  {
1983  casadi_assert(size1_in(i)==nrow && size2_in(i)==ncol,
1984  "Incorrect shape for " + str(*this) + " input " + str(i) + " \""
1985  + name_in(i) + "\". Expected " + str(nrow) + "-by-" + str(ncol)
1986  + " but got " + str(size1_in(i)) + "-by-" + str(size2_in(i)));
1987 
1988  }
casadi_int size1_in(casadi_int ind) const
Get the shape of an input: rows, columns or both.
Definition: function.cpp:979
casadi_int size2_in(casadi_int ind) const
Get the shape of an input: rows, columns or both.
Definition: function.cpp:983

References name_in(), size1_in(), size2_in(), and casadi::str().

Referenced by casadi::FunctionInternal::forward(), and casadi::FunctionInternal::reverse().

◆ assert_size_out()

void casadi::Function::assert_size_out ( casadi_int  i,
casadi_int  nrow,
casadi_int  ncol 
) const

Definition at line 1990 of file function.cpp.

1990  {
1991  casadi_assert(size1_out(i)==nrow && size2_out(i)==ncol,
1992  "Incorrect shape for " + str(*this) + " output " + str(i) + " \""
1993  + name_out(i) + "\". Expected " + str(nrow) + "-by-" + str(ncol)
1994  + " but got " + str(size1_out(i)) + "-by-" + str(size2_out(i)));
1995  }
casadi_int size2_out(casadi_int ind) const
Get the shape of an output: rows, columns or both.
Definition: function.cpp:991
casadi_int size1_out(casadi_int ind) const
Get the shape of an output: rows, columns or both.
Definition: function.cpp:987

References name_out(), size1_out(), size2_out(), and casadi::str().

Referenced by assert_sparsity_out().

◆ assert_sparsity_out()

void casadi::Function::assert_sparsity_out ( casadi_int  i,
const Sparsity &  sp,
casadi_int  n = 1,
bool  allow_all_zero_sparse = true 
) const

times horizontally

With allow_all_zero_sparse, an output without nonzeros of the right shape passes. Used to check derivative functions.

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

Definition at line 1997 of file function.cpp.

1998  {
1999  // Assert shape
2000  assert_size_out(i, sp.size1(), sp.size2() * n);
2001  // Quick return if empty sparse
2002  if (allow_all_zero_sparse && sparsity_out(i).nnz() == 0) return;
2003  // Check sparsities
2004  casadi_assert(sparsity_out(i).is_stacked(sp, n), "Mismatching sparsity "
2005  "(but correct dimensions) for " + str(*this) + " output " + name_out(i));
2006  }
const Sparsity & sparsity_out(casadi_int ind) const
Get the sparsity pattern of an output, by index or name.
Definition: function.cpp:1183
void assert_size_out(casadi_int i, casadi_int nrow, casadi_int ncol) const
Raise an error unless output i is nrow-by-ncol.
Definition: function.cpp:1990

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

Referenced by casadi::FunctionInternal::forward(), and casadi::FunctionInternal::reverse().

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

◆ bspline()

Function casadi::Function::bspline ( const std::string &  name,
const std::vector< std::vector< double > > &  knots,
const std::vector< double > &  coeffs,
const std::vector< casadi_int > &  degree,
casadi_int  m = 1,
const Dict &  opts = Dict() 
)
static

The result maps a point of dimension len(knots) (one column vector input) to the m-dimensional spline value. Coefficients are stored flat in coeffs with the value dimension m fastest, then the first spline dimension, etc.; the number of coefficients per dimension is len(knots[d]) - degree[d] - 1. A mismatch between the lengths of knots and degree raises an error. For data-driven splines or general interpolation see interpolant.

Parameters
nameName of the result
knotsKnot vector per dimension, non-decreasing, with repeated end knots
coeffsFlat coefficient list
degreePolynomial degree per dimension
mDimension of the spline value
opts"lookup_mode" (per dimension: "linear", "exact", "binary") and Function options

>>> f = Function.bspline("f", [[0, 0, 0, 1, 2, 2, 2]], [0, 1, 2, 3], [2])
>>> f
Function(f:(i0)->(o0) MXFunction)
>>> f(0), f(0.5), f(2)
(DM(0), DM(0.875), DM(3))
>>> g = Function.bspline("g", [[0, 0, 1, 1], [0, 0, 1, 1]], [0, 1, 2, 3], [1, 1])
>>> g([0.5, 0.5])
DM(1.5)
>>> try:
...   Function.bspline("f", [[0, 0, 0, 1, 2, 2, 2]], [0, 1, 2, 3], [2, 2])
... except RuntimeError as e:
...   print("must match knot list length" in str(e))
True

>> knots = {[0, 0, 0, 1, 2, 2, 2]};
>> f = Function.bspline('f', knots, [0, 1, 2, 3], 2); disp(f)
f:(i0)->(o0) MXFunction
>> [f(0), f(0.5), f(2)]
[[0, 0.875, 3]]
>> g = Function.bspline('g', {[0, 0, 1, 1], [0, 0, 1, 1]}, [0, 1, 2, 3], [1, 1]);
>> g([0.5; 0.5])
1.5
>> try, Function.bspline('f', knots, [0, 1, 2, 3], [2, 2]); catch e, msg = e.message; end
>> contains(msg, 'must match knot list length')
1

julia> f = ca.Function.bspline("f", [[0, 0, 0, 1, 2, 2, 2]], [0, 1, 2, 3], [2]);
julia> f
Function(f:(i0)->(o0) MXFunction)
julia> f(0), f(0.5), f(2)
(0, 0.875, 3)
julia> g = ca.Function.bspline("g", [[0, 0, 1, 1], [0, 0, 1, 1]], [0, 1, 2, 3], [1, 1]);
julia> g([0.5, 0.5])
DM(1.5)
julia> try
           ca.Function.bspline("f", [[0, 0, 0, 1, 2, 2, 2]], [0, 1, 2, 3], [2, 2])
       catch e
           println(occursin("must match knot list length", sprint(showerror, e)))
       end
true

See also
interpolant, MX::bspline

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

Definition at line 943 of file function.cpp.

946  {
947  try {
948  casadi_assert(degree.size()==knots.size(), "Degree list length (" + str(degree.size()) + ") "
949  "must match knot list length (" + str(knots.size()) + ").");
950  MX x = MX::sym("x", degree.size());
951  std::vector<std::string> lookup_mode;
952  Dict opts_remainder = extract_from_dict(opts, "lookup_mode", lookup_mode);
953  Dict opts_bspline;
954  opts_bspline["lookup_mode"] = lookup_mode;
955  MX y = MX::bspline(x, DM(coeffs), knots, degree, m, opts_bspline);
956  return Function(name, {x}, {y}, opts_remainder);
957  } catch(std::exception& e) {
958  THROW_ERROR_NOOBJ("bspline", e.what(), "BSpline");
959  }
960  }
Function()
Default constructor, creates a null object.
Definition: function.cpp:58
static MX sym(const std::string &name, casadi_int nrow=1, casadi_int ncol=1)
Create an nrow-by-ncol symbolic primitive.
static MX bspline(const MX &x, const DM &coeffs, const std::vector< std::vector< double > > &knots, const std::vector< casadi_int > &degree, casadi_int m, const Dict &opts=Dict())
Definition: mx.cpp:2217
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.
Matrix< double > DM
Definition: dm_fwd.hpp:33
Dict extract_from_dict(const Dict &d, const std::string &key, T &value)

References casadi::MX::bspline(), casadi::extract_from_dict(), Function(), name(), casadi::str(), and casadi::GenericMatrix< MX >::sym().

◆ buf_in() [1/2]

std::vector< const double * > casadi::Function::buf_in ( Function::MapArg  arg) const

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

Definition at line 570 of file function.cpp.

570  {
571  // Return value (RVO)
572  std::vector<const double*> ret(sz_arg(), nullptr);
573 
574  // Read inputs
575  for (auto i=arg.begin(); i!=arg.end(); ++i) {
576  casadi_int ind = index_in(i->first);
577  casadi_assert_dev(i->second.size()==nnz_in(ind));
578  ret[ind] = get_ptr(i->second);
579  }
580 
581  return ret;
582  }
casadi_int index_in(const std::string &name) const
Get the index of the input with a given name.
Definition: function.cpp:1121

References casadi::get_ptr(), index_in(), nnz_in(), and sz_arg().

◆ buf_in() [2/2]

std::vector< const double * > casadi::Function::buf_in ( Function::VecArg  arg) const

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

Definition at line 536 of file function.cpp.

536  {
537  casadi_assert_dev(arg.size()==n_in());
538  auto arg_it=arg.begin();
539  std::vector<const double*> buf_arg(sz_arg());
540  for (casadi_uint i=0; i<arg.size(); ++i) {
541  casadi_assert_dev(arg_it->size()==nnz_in(i));
542  buf_arg[i] = get_ptr(*arg_it++);
543  }
544  return buf_arg;
545  }

References casadi::get_ptr(), n_in(), nnz_in(), and sz_arg().

◆ buf_out() [1/4]

std::vector< double * > casadi::Function::buf_out ( Function::MapRes  res) const

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

Definition at line 584 of file function.cpp.

584  {
585  // Return value (RVO)
586  std::vector<double*> ret(sz_res(), nullptr);
587 
588  // Read outputs
589  for (auto i=res.begin(); i!=res.end(); ++i) {
590  casadi_int ind = index_out(i->first);
591  i->second.resize(nnz_out(ind));
592  ret[ind] = get_ptr(i->second);
593  }
594 
595  return ret;
596  }
casadi_int index_out(const std::string &name) const
Get the index of the output with a given name; unknown names raise an error.
Definition: function.cpp:1129

References casadi::get_ptr(), index_out(), nnz_out(), and sz_res().

◆ buf_out() [2/4]

std::vector< double * > casadi::Function::buf_out ( Function::MPrRes  res) const

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

Definition at line 598 of file function.cpp.

598  {
599  // Return value (RVO)
600  std::vector<double*> ret(sz_res(), nullptr);
601 
602  // Read outputs
603  for (auto i=res.begin(); i!=res.end(); ++i) {
604  casadi_int ind = index_out(i->first);
605  casadi_assert_dev(i->second!=0);
606  i->second->resize(nnz_out(ind));
607  ret[ind] = get_ptr(*i->second);
608  }
609 
610  return ret;
611  }

References casadi::get_ptr(), index_out(), nnz_out(), and sz_res().

◆ buf_out() [3/4]

std::vector< double * > casadi::Function::buf_out ( Function::VecRes  res) const

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

Definition at line 547 of file function.cpp.

547  {
548  res.resize(n_out());
549  auto res_it=res.begin();
550  std::vector<double*> buf_res(sz_res());
551  for (casadi_uint i=0; i<res.size(); ++i) {
552  res_it->resize(nnz_out(i));
553  buf_res[i] = get_ptr(*res_it++);
554  }
555  return buf_res;
556  }

References casadi::get_ptr(), n_out(), nnz_out(), and sz_res().

◆ buf_out() [4/4]

std::vector< double * > casadi::Function::buf_out ( Function::VPrRes  res) const

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

Definition at line 558 of file function.cpp.

558  {
559  casadi_assert_dev(res.size()==n_out());
560  auto res_it=res.begin();
561  std::vector<double*> buf_res(sz_res());
562  for (casadi_uint i=0; i<res.size(); ++i) {
563  casadi_assert_dev(*res_it!=0);
564  (*res_it)->resize(nnz_out(i));
565  buf_res[i] = get_ptr(**res_it++);
566  }
567  return buf_res;
568  }

References casadi::get_ptr(), n_out(), nnz_out(), and sz_res().

◆ cache()

Dict casadi::Function::cache ( ) const

jacobian, forward, reverse, wrap and serial map store their result in a cache keyed by name (jac_f, fwd1_f, adj1_f, wrap_f, map3_f, ...). The cache holds weak references: an entry stays only while some other reference keeps the function alive. Option "cache" prepopulates it, e.g. with a hand-written Jacobian.

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)])
>>> f.cache()
{}
>>> J = f.jacobian()
>>> list(f.cache().keys())
['jac_f']

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)});
>> isempty(fieldnames(f.cache()))
1
>> J = f.jacobian(); disp(strjoin(fieldnames(f.cache()), ' '))
jac_f

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)]);
julia> ca.cache(f)
Dict{String, Any}()
julia> J = ca.jacobian(f);
julia> collect(keys(ca.cache(f)))
1-element Vector{String}:
 "jac_f"

See also
jacobian, forward, reverse

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

Definition at line 2032 of file function.cpp.

2032  {
2033  try {
2034  return (*this)->cache();
2035  } catch(std::exception& e) {
2036  THROW_ERROR("cache", e.what());
2037  return {};
2038  }
2039  }

◆ call() [1/6]

void casadi::Function::call ( const DMDict &  arg,
DMDict &  res,
bool  always_inline = false,
bool  never_inline = false 
) const

This is the general evaluation entry point; the call operator (f(...) in Python, C++ and MATLAB) is a shorthand for it. Argument lists must have exactly n_in() entries. A dict maps input names to values; missing inputs take default_in, unknown names raise an error. The result is a list of n_out() values, or a dict keyed by output name.

The argument type selects the evaluation mode:

  • DM (or anything convertible to DM, such as numbers and numeric arrays): numerical evaluation, returns DM
  • SX: symbolic evaluation producing an SX expression; an MX function is expanded on the fly (fails if it contains non-expandable nodes)
  • MX: symbolic evaluation producing a call node f(args){k} in the MX graph, unless the function is inlined

Shapes: each argument must have the input shape, or be a scalar (broadcast to all entries), a transposed vector, an empty matrix (treated as all zeros), or N-by-(P*M) for an N-by-M input (P evaluations, outputs stacked horizontally; other arguments are repeated). Anything else raises an error that lists these rules. Sparsity is projected: entries outside sparsity_in are ignored. When all inputs are scalar and the arguments are matrices of one common shape, the function is applied elementwise. Numerical evaluation of a function with free variables raises "Cannot evaluate ... since variables [...] are free".

Parameters
argList or dict of arguments, all of the same type
resOutput: list or dict of results
always_inlineMX only: expand the call into the caller's graph instead of creating a call node (SX functions are then inlined as scalar operations); combined with never_inline raises an error
never_inlineSX only: keep the call as an opaque call node inside the SX expression instead of inlining it

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.call([2, [3, 4]])
[DM([6, 8]), DM(0.909297)]
>>> f.call({"x": 2})
{'r': DM([0, 0]), 's': DM(0.909297)}
>>> f(2, [3, 4])
(DM([6, 8]), DM(0.909297))
>>> f(x=2, y=[3, 4])
{'r': DM([6, 8]), 's': DM(0.909297)}
>>> f(2, DM([[3, 5], [4, 6]]))
(DM(
[[6, 10],
 [8, 12]]), DM([[0.909297, 0.909297]]))
>>> f(DM(0, 0), 3)
(DM([0, 0]), DM(0))
>>> z = MX.sym("z"); w = MX.sym("w", 2)
>>> f.call([z, w])
[MX(f(z, w){0}), MX(f(z, w){1})]
>>> f.call([z, w], True)
[MX(vertcat((z*w[0]), (z*w[1]))), MX(sin(z))]
>>> a = SX.sym("a")
>>> f.call([a, [1, 2]])
[SX([a, (2.*a)]), SX(sin(a))]
>>> try:
...   f(1)
... except RuntimeError as e:
...   print("Incorrect number of inputs: Expected 2, got 1" in str(e))
True
>>> try:
...   f(1, [1, 2, 3])
... except RuntimeError as e:
...   print("Input 1 (y) has mismatching shape. Got 3-by-1" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> res = f.call({2, [3; 4]}); disp(res{1}), disp(res{2})
[6, 8]
0.909297
>> res = f.call(struct('x', 2)); disp(res.r), disp(res.s)
[0, 0]
0.909297
>> [r, s] = f(2, [3; 4]); disp(r), disp(s)
[6, 8]
0.909297
>> res = f('x', 2, 'y', [3; 4]); disp(res.r), disp(res.s)
[6, 8]
0.909297
>> [r, s] = f(2, DM([3, 5; 4, 6])); disp(r), disp(s)
[[6, 10],
 [8, 12]]
[[0.909297, 0.909297]]
>> [r, s] = f(DM(0, 0), 3); disp(r), disp(s)
[0, 0]
0
>> z = MX.sym('z'); w = MX.sym('w', 2);
>> res = f.call({z, w}); disp(res{1}), disp(res{2})
f(z, w){0}
f(z, w){1}
>> res = f.call({z, w}, true); disp(res{1}), disp(res{2})
vertcat((z*w[0]), (z*w[1]))
sin(z)
>> a = SX.sym('a'); res = f.call({a, [1; 2]}); disp(res{1}), disp(res{2})
[a, (2.*a)]
sin(a)
>> try, f(1); catch e, disp(contains(e.message, 'Expected 2, got 1')); end
1
>> try, f(1, [1; 2; 3]); catch e, disp(contains(e.message, 'Got 3-by-1')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.call(f, [2, [3, 4]])
2-element Vector{DM}:
 DM([6, 8])
 DM(0.909297)
julia> ca.call(f, Dict("x" => 2))
Dict{String, DM} with 2 entries:
  "r" => [0, 0]
  "s" => 0.909297
julia> f(2, [3, 4])
([6, 8], 0.909297)
julia> f(x=2, y=[3, 4])
Dict{String, DM} with 2 entries:
  "r" => [6, 8]
  "s" => 0.909297
julia> r, s = f(2, [3 5; 4 6]);
julia> r
DM(
[[6, 10],
 [8, 12]])
julia> s
DM([[0.909297, 0.909297]])
julia> f(ca.DM(0, 0), 3)
([0, 0], 0)
julia> z = ca.MX.sym("z"); w = ca.MX.sym("w", 2);
julia> ca.call(f, [z, w])
2-element Vector{MX}:
 MX(f(z, w){0})
 MX(f(z, w){1})
julia> ca.call(f, [z, w], true)
2-element Vector{MX}:
 MX(vertcat((z*w[0]), (z*w[1])))
 MX(sin(z))
julia> a = ca.SX.sym("a");
julia> ca.call(f, [a, [1, 2]])
2-element Vector{SX}:
 SX([a, (2.*a)])
 SX(sin(a))
julia> try
           f(1)
       catch e
           msg = sprint(showerror, e)
           println(occursin("Incorrect number of inputs: Expected 2, got 1", msg))
       end
true
julia> try
           f(1, [1, 2, 3])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Input 1 (y) has mismatching shape. Got 3-by-1", msg))
       end
true

See also
default_in, convert_in, map, mapsum

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

Definition at line 1650 of file function.cpp.

1651  {
1652  try {
1653  call_gen(arg, res, always_inline, never_inline);
1654  } catch(std::exception& e) {
1655  THROW_ERROR("call", e.what());
1656  }
1657  }
void call_gen(std::vector< const D * > arg, std::vector< D * > res) const
Evaluate with temporary memory allocation.
Definition: function.cpp:614

References call_gen().

◆ call() [2/6]

void casadi::Function::call ( const MXDict &  arg,
MXDict &  res,
bool  always_inline = false,
bool  never_inline = false 
) const

This is the general evaluation entry point; the call operator (f(...) in Python, C++ and MATLAB) is a shorthand for it. Argument lists must have exactly n_in() entries. A dict maps input names to values; missing inputs take default_in, unknown names raise an error. The result is a list of n_out() values, or a dict keyed by output name.

The argument type selects the evaluation mode:

  • DM (or anything convertible to DM, such as numbers and numeric arrays): numerical evaluation, returns DM
  • SX: symbolic evaluation producing an SX expression; an MX function is expanded on the fly (fails if it contains non-expandable nodes)
  • MX: symbolic evaluation producing a call node f(args){k} in the MX graph, unless the function is inlined

Shapes: each argument must have the input shape, or be a scalar (broadcast to all entries), a transposed vector, an empty matrix (treated as all zeros), or N-by-(P*M) for an N-by-M input (P evaluations, outputs stacked horizontally; other arguments are repeated). Anything else raises an error that lists these rules. Sparsity is projected: entries outside sparsity_in are ignored. When all inputs are scalar and the arguments are matrices of one common shape, the function is applied elementwise. Numerical evaluation of a function with free variables raises "Cannot evaluate ... since variables [...] are free".

Parameters
argList or dict of arguments, all of the same type
resOutput: list or dict of results
always_inlineMX only: expand the call into the caller's graph instead of creating a call node (SX functions are then inlined as scalar operations); combined with never_inline raises an error
never_inlineSX only: keep the call as an opaque call node inside the SX expression instead of inlining it

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.call([2, [3, 4]])
[DM([6, 8]), DM(0.909297)]
>>> f.call({"x": 2})
{'r': DM([0, 0]), 's': DM(0.909297)}
>>> f(2, [3, 4])
(DM([6, 8]), DM(0.909297))
>>> f(x=2, y=[3, 4])
{'r': DM([6, 8]), 's': DM(0.909297)}
>>> f(2, DM([[3, 5], [4, 6]]))
(DM(
[[6, 10],
 [8, 12]]), DM([[0.909297, 0.909297]]))
>>> f(DM(0, 0), 3)
(DM([0, 0]), DM(0))
>>> z = MX.sym("z"); w = MX.sym("w", 2)
>>> f.call([z, w])
[MX(f(z, w){0}), MX(f(z, w){1})]
>>> f.call([z, w], True)
[MX(vertcat((z*w[0]), (z*w[1]))), MX(sin(z))]
>>> a = SX.sym("a")
>>> f.call([a, [1, 2]])
[SX([a, (2.*a)]), SX(sin(a))]
>>> try:
...   f(1)
... except RuntimeError as e:
...   print("Incorrect number of inputs: Expected 2, got 1" in str(e))
True
>>> try:
...   f(1, [1, 2, 3])
... except RuntimeError as e:
...   print("Input 1 (y) has mismatching shape. Got 3-by-1" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> res = f.call({2, [3; 4]}); disp(res{1}), disp(res{2})
[6, 8]
0.909297
>> res = f.call(struct('x', 2)); disp(res.r), disp(res.s)
[0, 0]
0.909297
>> [r, s] = f(2, [3; 4]); disp(r), disp(s)
[6, 8]
0.909297
>> res = f('x', 2, 'y', [3; 4]); disp(res.r), disp(res.s)
[6, 8]
0.909297
>> [r, s] = f(2, DM([3, 5; 4, 6])); disp(r), disp(s)
[[6, 10],
 [8, 12]]
[[0.909297, 0.909297]]
>> [r, s] = f(DM(0, 0), 3); disp(r), disp(s)
[0, 0]
0
>> z = MX.sym('z'); w = MX.sym('w', 2);
>> res = f.call({z, w}); disp(res{1}), disp(res{2})
f(z, w){0}
f(z, w){1}
>> res = f.call({z, w}, true); disp(res{1}), disp(res{2})
vertcat((z*w[0]), (z*w[1]))
sin(z)
>> a = SX.sym('a'); res = f.call({a, [1; 2]}); disp(res{1}), disp(res{2})
[a, (2.*a)]
sin(a)
>> try, f(1); catch e, disp(contains(e.message, 'Expected 2, got 1')); end
1
>> try, f(1, [1; 2; 3]); catch e, disp(contains(e.message, 'Got 3-by-1')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.call(f, [2, [3, 4]])
2-element Vector{DM}:
 DM([6, 8])
 DM(0.909297)
julia> ca.call(f, Dict("x" => 2))
Dict{String, DM} with 2 entries:
  "r" => [0, 0]
  "s" => 0.909297
julia> f(2, [3, 4])
([6, 8], 0.909297)
julia> f(x=2, y=[3, 4])
Dict{String, DM} with 2 entries:
  "r" => [6, 8]
  "s" => 0.909297
julia> r, s = f(2, [3 5; 4 6]);
julia> r
DM(
[[6, 10],
 [8, 12]])
julia> s
DM([[0.909297, 0.909297]])
julia> f(ca.DM(0, 0), 3)
([0, 0], 0)
julia> z = ca.MX.sym("z"); w = ca.MX.sym("w", 2);
julia> ca.call(f, [z, w])
2-element Vector{MX}:
 MX(f(z, w){0})
 MX(f(z, w){1})
julia> ca.call(f, [z, w], true)
2-element Vector{MX}:
 MX(vertcat((z*w[0]), (z*w[1])))
 MX(sin(z))
julia> a = ca.SX.sym("a");
julia> ca.call(f, [a, [1, 2]])
2-element Vector{SX}:
 SX([a, (2.*a)])
 SX(sin(a))
julia> try
           f(1)
       catch e
           msg = sprint(showerror, e)
           println(occursin("Incorrect number of inputs: Expected 2, got 1", msg))
       end
true
julia> try
           f(1, [1, 2, 3])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Input 1 (y) has mismatching shape. Got 3-by-1", msg))
       end
true

See also
default_in, convert_in, map, mapsum

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

Definition at line 1668 of file function.cpp.

1669  {
1670  try {
1671  call_gen(arg, res, always_inline, never_inline);
1672  } catch(std::exception& e) {
1673  THROW_ERROR("call", e.what());
1674  }
1675  }

References call_gen().

◆ call() [3/6]

void casadi::Function::call ( const std::vector< DM > &  arg,
std::vector< DM > &  res,
bool  always_inline = false,
bool  never_inline = false 
) const

This is the general evaluation entry point; the call operator (f(...) in Python, C++ and MATLAB) is a shorthand for it. Argument lists must have exactly n_in() entries. A dict maps input names to values; missing inputs take default_in, unknown names raise an error. The result is a list of n_out() values, or a dict keyed by output name.

The argument type selects the evaluation mode:

  • DM (or anything convertible to DM, such as numbers and numeric arrays): numerical evaluation, returns DM
  • SX: symbolic evaluation producing an SX expression; an MX function is expanded on the fly (fails if it contains non-expandable nodes)
  • MX: symbolic evaluation producing a call node f(args){k} in the MX graph, unless the function is inlined

Shapes: each argument must have the input shape, or be a scalar (broadcast to all entries), a transposed vector, an empty matrix (treated as all zeros), or N-by-(P*M) for an N-by-M input (P evaluations, outputs stacked horizontally; other arguments are repeated). Anything else raises an error that lists these rules. Sparsity is projected: entries outside sparsity_in are ignored. When all inputs are scalar and the arguments are matrices of one common shape, the function is applied elementwise. Numerical evaluation of a function with free variables raises "Cannot evaluate ... since variables [...] are free".

Parameters
argList or dict of arguments, all of the same type
resOutput: list or dict of results
always_inlineMX only: expand the call into the caller's graph instead of creating a call node (SX functions are then inlined as scalar operations); combined with never_inline raises an error
never_inlineSX only: keep the call as an opaque call node inside the SX expression instead of inlining it

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.call([2, [3, 4]])
[DM([6, 8]), DM(0.909297)]
>>> f.call({"x": 2})
{'r': DM([0, 0]), 's': DM(0.909297)}
>>> f(2, [3, 4])
(DM([6, 8]), DM(0.909297))
>>> f(x=2, y=[3, 4])
{'r': DM([6, 8]), 's': DM(0.909297)}
>>> f(2, DM([[3, 5], [4, 6]]))
(DM(
[[6, 10],
 [8, 12]]), DM([[0.909297, 0.909297]]))
>>> f(DM(0, 0), 3)
(DM([0, 0]), DM(0))
>>> z = MX.sym("z"); w = MX.sym("w", 2)
>>> f.call([z, w])
[MX(f(z, w){0}), MX(f(z, w){1})]
>>> f.call([z, w], True)
[MX(vertcat((z*w[0]), (z*w[1]))), MX(sin(z))]
>>> a = SX.sym("a")
>>> f.call([a, [1, 2]])
[SX([a, (2.*a)]), SX(sin(a))]
>>> try:
...   f(1)
... except RuntimeError as e:
...   print("Incorrect number of inputs: Expected 2, got 1" in str(e))
True
>>> try:
...   f(1, [1, 2, 3])
... except RuntimeError as e:
...   print("Input 1 (y) has mismatching shape. Got 3-by-1" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> res = f.call({2, [3; 4]}); disp(res{1}), disp(res{2})
[6, 8]
0.909297
>> res = f.call(struct('x', 2)); disp(res.r), disp(res.s)
[0, 0]
0.909297
>> [r, s] = f(2, [3; 4]); disp(r), disp(s)
[6, 8]
0.909297
>> res = f('x', 2, 'y', [3; 4]); disp(res.r), disp(res.s)
[6, 8]
0.909297
>> [r, s] = f(2, DM([3, 5; 4, 6])); disp(r), disp(s)
[[6, 10],
 [8, 12]]
[[0.909297, 0.909297]]
>> [r, s] = f(DM(0, 0), 3); disp(r), disp(s)
[0, 0]
0
>> z = MX.sym('z'); w = MX.sym('w', 2);
>> res = f.call({z, w}); disp(res{1}), disp(res{2})
f(z, w){0}
f(z, w){1}
>> res = f.call({z, w}, true); disp(res{1}), disp(res{2})
vertcat((z*w[0]), (z*w[1]))
sin(z)
>> a = SX.sym('a'); res = f.call({a, [1; 2]}); disp(res{1}), disp(res{2})
[a, (2.*a)]
sin(a)
>> try, f(1); catch e, disp(contains(e.message, 'Expected 2, got 1')); end
1
>> try, f(1, [1; 2; 3]); catch e, disp(contains(e.message, 'Got 3-by-1')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.call(f, [2, [3, 4]])
2-element Vector{DM}:
 DM([6, 8])
 DM(0.909297)
julia> ca.call(f, Dict("x" => 2))
Dict{String, DM} with 2 entries:
  "r" => [0, 0]
  "s" => 0.909297
julia> f(2, [3, 4])
([6, 8], 0.909297)
julia> f(x=2, y=[3, 4])
Dict{String, DM} with 2 entries:
  "r" => [6, 8]
  "s" => 0.909297
julia> r, s = f(2, [3 5; 4 6]);
julia> r
DM(
[[6, 10],
 [8, 12]])
julia> s
DM([[0.909297, 0.909297]])
julia> f(ca.DM(0, 0), 3)
([0, 0], 0)
julia> z = ca.MX.sym("z"); w = ca.MX.sym("w", 2);
julia> ca.call(f, [z, w])
2-element Vector{MX}:
 MX(f(z, w){0})
 MX(f(z, w){1})
julia> ca.call(f, [z, w], true)
2-element Vector{MX}:
 MX(vertcat((z*w[0]), (z*w[1])))
 MX(sin(z))
julia> a = ca.SX.sym("a");
julia> ca.call(f, [a, [1, 2]])
2-element Vector{SX}:
 SX([a, (2.*a)])
 SX(sin(a))
julia> try
           f(1)
       catch e
           msg = sprint(showerror, e)
           println(occursin("Incorrect number of inputs: Expected 2, got 1", msg))
       end
true
julia> try
           f(1, [1, 2, 3])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Input 1 (y) has mismatching shape. Got 3-by-1", msg))
       end
true

See also
default_in, convert_in, map, mapsum

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

Definition at line 509 of file function.cpp.

510  {
511  try {
512  (*this)->call(arg, res, always_inline, never_inline);
513  } catch(std::exception& e) {
514  THROW_ERROR("call", e.what());
515  }
516  }

Referenced by call_gen(), casadi::construct_nlpsol(), casadi::GraphBuilderInternal::create_function(), casadi::detect_simple_bounds_gen(), casadi::FunctionInternal::eval_mx(), casadi::Onnx::import_symbolic(), map(), casadi::MX::matrix_expand(), operator()(), and casadi::MX::substitute().

◆ call() [4/6]

void casadi::Function::call ( const std::vector< MX > &  arg,
std::vector< MX > &  res,
bool  always_inline = false,
bool  never_inline = false 
) const

This is the general evaluation entry point; the call operator (f(...) in Python, C++ and MATLAB) is a shorthand for it. Argument lists must have exactly n_in() entries. A dict maps input names to values; missing inputs take default_in, unknown names raise an error. The result is a list of n_out() values, or a dict keyed by output name.

The argument type selects the evaluation mode:

  • DM (or anything convertible to DM, such as numbers and numeric arrays): numerical evaluation, returns DM
  • SX: symbolic evaluation producing an SX expression; an MX function is expanded on the fly (fails if it contains non-expandable nodes)
  • MX: symbolic evaluation producing a call node f(args){k} in the MX graph, unless the function is inlined

Shapes: each argument must have the input shape, or be a scalar (broadcast to all entries), a transposed vector, an empty matrix (treated as all zeros), or N-by-(P*M) for an N-by-M input (P evaluations, outputs stacked horizontally; other arguments are repeated). Anything else raises an error that lists these rules. Sparsity is projected: entries outside sparsity_in are ignored. When all inputs are scalar and the arguments are matrices of one common shape, the function is applied elementwise. Numerical evaluation of a function with free variables raises "Cannot evaluate ... since variables [...] are free".

Parameters
argList or dict of arguments, all of the same type
resOutput: list or dict of results
always_inlineMX only: expand the call into the caller's graph instead of creating a call node (SX functions are then inlined as scalar operations); combined with never_inline raises an error
never_inlineSX only: keep the call as an opaque call node inside the SX expression instead of inlining it

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.call([2, [3, 4]])
[DM([6, 8]), DM(0.909297)]
>>> f.call({"x": 2})
{'r': DM([0, 0]), 's': DM(0.909297)}
>>> f(2, [3, 4])
(DM([6, 8]), DM(0.909297))
>>> f(x=2, y=[3, 4])
{'r': DM([6, 8]), 's': DM(0.909297)}
>>> f(2, DM([[3, 5], [4, 6]]))
(DM(
[[6, 10],
 [8, 12]]), DM([[0.909297, 0.909297]]))
>>> f(DM(0, 0), 3)
(DM([0, 0]), DM(0))
>>> z = MX.sym("z"); w = MX.sym("w", 2)
>>> f.call([z, w])
[MX(f(z, w){0}), MX(f(z, w){1})]
>>> f.call([z, w], True)
[MX(vertcat((z*w[0]), (z*w[1]))), MX(sin(z))]
>>> a = SX.sym("a")
>>> f.call([a, [1, 2]])
[SX([a, (2.*a)]), SX(sin(a))]
>>> try:
...   f(1)
... except RuntimeError as e:
...   print("Incorrect number of inputs: Expected 2, got 1" in str(e))
True
>>> try:
...   f(1, [1, 2, 3])
... except RuntimeError as e:
...   print("Input 1 (y) has mismatching shape. Got 3-by-1" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> res = f.call({2, [3; 4]}); disp(res{1}), disp(res{2})
[6, 8]
0.909297
>> res = f.call(struct('x', 2)); disp(res.r), disp(res.s)
[0, 0]
0.909297
>> [r, s] = f(2, [3; 4]); disp(r), disp(s)
[6, 8]
0.909297
>> res = f('x', 2, 'y', [3; 4]); disp(res.r), disp(res.s)
[6, 8]
0.909297
>> [r, s] = f(2, DM([3, 5; 4, 6])); disp(r), disp(s)
[[6, 10],
 [8, 12]]
[[0.909297, 0.909297]]
>> [r, s] = f(DM(0, 0), 3); disp(r), disp(s)
[0, 0]
0
>> z = MX.sym('z'); w = MX.sym('w', 2);
>> res = f.call({z, w}); disp(res{1}), disp(res{2})
f(z, w){0}
f(z, w){1}
>> res = f.call({z, w}, true); disp(res{1}), disp(res{2})
vertcat((z*w[0]), (z*w[1]))
sin(z)
>> a = SX.sym('a'); res = f.call({a, [1; 2]}); disp(res{1}), disp(res{2})
[a, (2.*a)]
sin(a)
>> try, f(1); catch e, disp(contains(e.message, 'Expected 2, got 1')); end
1
>> try, f(1, [1; 2; 3]); catch e, disp(contains(e.message, 'Got 3-by-1')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.call(f, [2, [3, 4]])
2-element Vector{DM}:
 DM([6, 8])
 DM(0.909297)
julia> ca.call(f, Dict("x" => 2))
Dict{String, DM} with 2 entries:
  "r" => [0, 0]
  "s" => 0.909297
julia> f(2, [3, 4])
([6, 8], 0.909297)
julia> f(x=2, y=[3, 4])
Dict{String, DM} with 2 entries:
  "r" => [6, 8]
  "s" => 0.909297
julia> r, s = f(2, [3 5; 4 6]);
julia> r
DM(
[[6, 10],
 [8, 12]])
julia> s
DM([[0.909297, 0.909297]])
julia> f(ca.DM(0, 0), 3)
([0, 0], 0)
julia> z = ca.MX.sym("z"); w = ca.MX.sym("w", 2);
julia> ca.call(f, [z, w])
2-element Vector{MX}:
 MX(f(z, w){0})
 MX(f(z, w){1})
julia> ca.call(f, [z, w], true)
2-element Vector{MX}:
 MX(vertcat((z*w[0]), (z*w[1])))
 MX(sin(z))
julia> a = ca.SX.sym("a");
julia> ca.call(f, [a, [1, 2]])
2-element Vector{SX}:
 SX([a, (2.*a)])
 SX(sin(a))
julia> try
           f(1)
       catch e
           msg = sprint(showerror, e)
           println(occursin("Incorrect number of inputs: Expected 2, got 1", msg))
       end
true
julia> try
           f(1, [1, 2, 3])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Input 1 (y) has mismatching shape. Got 3-by-1", msg))
       end
true

See also
default_in, convert_in, map, mapsum

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

Definition at line 527 of file function.cpp.

528  {
529  try {
530  (*this)->call(arg, res, always_inline, never_inline);
531  } catch(std::exception& e) {
532  THROW_ERROR("call", e.what());
533  }
534  }

◆ call() [5/6]

void casadi::Function::call ( const std::vector< SX > &  arg,
std::vector< SX > &  res,
bool  always_inline = false,
bool  never_inline = false 
) const

This is the general evaluation entry point; the call operator (f(...) in Python, C++ and MATLAB) is a shorthand for it. Argument lists must have exactly n_in() entries. A dict maps input names to values; missing inputs take default_in, unknown names raise an error. The result is a list of n_out() values, or a dict keyed by output name.

The argument type selects the evaluation mode:

  • DM (or anything convertible to DM, such as numbers and numeric arrays): numerical evaluation, returns DM
  • SX: symbolic evaluation producing an SX expression; an MX function is expanded on the fly (fails if it contains non-expandable nodes)
  • MX: symbolic evaluation producing a call node f(args){k} in the MX graph, unless the function is inlined

Shapes: each argument must have the input shape, or be a scalar (broadcast to all entries), a transposed vector, an empty matrix (treated as all zeros), or N-by-(P*M) for an N-by-M input (P evaluations, outputs stacked horizontally; other arguments are repeated). Anything else raises an error that lists these rules. Sparsity is projected: entries outside sparsity_in are ignored. When all inputs are scalar and the arguments are matrices of one common shape, the function is applied elementwise. Numerical evaluation of a function with free variables raises "Cannot evaluate ... since variables [...] are free".

Parameters
argList or dict of arguments, all of the same type
resOutput: list or dict of results
always_inlineMX only: expand the call into the caller's graph instead of creating a call node (SX functions are then inlined as scalar operations); combined with never_inline raises an error
never_inlineSX only: keep the call as an opaque call node inside the SX expression instead of inlining it

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.call([2, [3, 4]])
[DM([6, 8]), DM(0.909297)]
>>> f.call({"x": 2})
{'r': DM([0, 0]), 's': DM(0.909297)}
>>> f(2, [3, 4])
(DM([6, 8]), DM(0.909297))
>>> f(x=2, y=[3, 4])
{'r': DM([6, 8]), 's': DM(0.909297)}
>>> f(2, DM([[3, 5], [4, 6]]))
(DM(
[[6, 10],
 [8, 12]]), DM([[0.909297, 0.909297]]))
>>> f(DM(0, 0), 3)
(DM([0, 0]), DM(0))
>>> z = MX.sym("z"); w = MX.sym("w", 2)
>>> f.call([z, w])
[MX(f(z, w){0}), MX(f(z, w){1})]
>>> f.call([z, w], True)
[MX(vertcat((z*w[0]), (z*w[1]))), MX(sin(z))]
>>> a = SX.sym("a")
>>> f.call([a, [1, 2]])
[SX([a, (2.*a)]), SX(sin(a))]
>>> try:
...   f(1)
... except RuntimeError as e:
...   print("Incorrect number of inputs: Expected 2, got 1" in str(e))
True
>>> try:
...   f(1, [1, 2, 3])
... except RuntimeError as e:
...   print("Input 1 (y) has mismatching shape. Got 3-by-1" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> res = f.call({2, [3; 4]}); disp(res{1}), disp(res{2})
[6, 8]
0.909297
>> res = f.call(struct('x', 2)); disp(res.r), disp(res.s)
[0, 0]
0.909297
>> [r, s] = f(2, [3; 4]); disp(r), disp(s)
[6, 8]
0.909297
>> res = f('x', 2, 'y', [3; 4]); disp(res.r), disp(res.s)
[6, 8]
0.909297
>> [r, s] = f(2, DM([3, 5; 4, 6])); disp(r), disp(s)
[[6, 10],
 [8, 12]]
[[0.909297, 0.909297]]
>> [r, s] = f(DM(0, 0), 3); disp(r), disp(s)
[0, 0]
0
>> z = MX.sym('z'); w = MX.sym('w', 2);
>> res = f.call({z, w}); disp(res{1}), disp(res{2})
f(z, w){0}
f(z, w){1}
>> res = f.call({z, w}, true); disp(res{1}), disp(res{2})
vertcat((z*w[0]), (z*w[1]))
sin(z)
>> a = SX.sym('a'); res = f.call({a, [1; 2]}); disp(res{1}), disp(res{2})
[a, (2.*a)]
sin(a)
>> try, f(1); catch e, disp(contains(e.message, 'Expected 2, got 1')); end
1
>> try, f(1, [1; 2; 3]); catch e, disp(contains(e.message, 'Got 3-by-1')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.call(f, [2, [3, 4]])
2-element Vector{DM}:
 DM([6, 8])
 DM(0.909297)
julia> ca.call(f, Dict("x" => 2))
Dict{String, DM} with 2 entries:
  "r" => [0, 0]
  "s" => 0.909297
julia> f(2, [3, 4])
([6, 8], 0.909297)
julia> f(x=2, y=[3, 4])
Dict{String, DM} with 2 entries:
  "r" => [6, 8]
  "s" => 0.909297
julia> r, s = f(2, [3 5; 4 6]);
julia> r
DM(
[[6, 10],
 [8, 12]])
julia> s
DM([[0.909297, 0.909297]])
julia> f(ca.DM(0, 0), 3)
([0, 0], 0)
julia> z = ca.MX.sym("z"); w = ca.MX.sym("w", 2);
julia> ca.call(f, [z, w])
2-element Vector{MX}:
 MX(f(z, w){0})
 MX(f(z, w){1})
julia> ca.call(f, [z, w], true)
2-element Vector{MX}:
 MX(vertcat((z*w[0]), (z*w[1])))
 MX(sin(z))
julia> a = ca.SX.sym("a");
julia> ca.call(f, [a, [1, 2]])
2-element Vector{SX}:
 SX([a, (2.*a)])
 SX(sin(a))
julia> try
           f(1)
       catch e
           msg = sprint(showerror, e)
           println(occursin("Incorrect number of inputs: Expected 2, got 1", msg))
       end
true
julia> try
           f(1, [1, 2, 3])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Input 1 (y) has mismatching shape. Got 3-by-1", msg))
       end
true

See also
default_in, convert_in, map, mapsum

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

Definition at line 518 of file function.cpp.

519  {
520  try {
521  (*this)->call(arg, res, always_inline, never_inline);
522  } catch(std::exception& e) {
523  THROW_ERROR("call", e.what());
524  }
525  }

◆ call() [6/6]

void casadi::Function::call ( const SXDict &  arg,
SXDict &  res,
bool  always_inline = false,
bool  never_inline = false 
) const

This is the general evaluation entry point; the call operator (f(...) in Python, C++ and MATLAB) is a shorthand for it. Argument lists must have exactly n_in() entries. A dict maps input names to values; missing inputs take default_in, unknown names raise an error. The result is a list of n_out() values, or a dict keyed by output name.

The argument type selects the evaluation mode:

  • DM (or anything convertible to DM, such as numbers and numeric arrays): numerical evaluation, returns DM
  • SX: symbolic evaluation producing an SX expression; an MX function is expanded on the fly (fails if it contains non-expandable nodes)
  • MX: symbolic evaluation producing a call node f(args){k} in the MX graph, unless the function is inlined

Shapes: each argument must have the input shape, or be a scalar (broadcast to all entries), a transposed vector, an empty matrix (treated as all zeros), or N-by-(P*M) for an N-by-M input (P evaluations, outputs stacked horizontally; other arguments are repeated). Anything else raises an error that lists these rules. Sparsity is projected: entries outside sparsity_in are ignored. When all inputs are scalar and the arguments are matrices of one common shape, the function is applied elementwise. Numerical evaluation of a function with free variables raises "Cannot evaluate ... since variables [...] are free".

Parameters
argList or dict of arguments, all of the same type
resOutput: list or dict of results
always_inlineMX only: expand the call into the caller's graph instead of creating a call node (SX functions are then inlined as scalar operations); combined with never_inline raises an error
never_inlineSX only: keep the call as an opaque call node inside the SX expression instead of inlining it

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> f.call([2, [3, 4]])
[DM([6, 8]), DM(0.909297)]
>>> f.call({"x": 2})
{'r': DM([0, 0]), 's': DM(0.909297)}
>>> f(2, [3, 4])
(DM([6, 8]), DM(0.909297))
>>> f(x=2, y=[3, 4])
{'r': DM([6, 8]), 's': DM(0.909297)}
>>> f(2, DM([[3, 5], [4, 6]]))
(DM(
[[6, 10],
 [8, 12]]), DM([[0.909297, 0.909297]]))
>>> f(DM(0, 0), 3)
(DM([0, 0]), DM(0))
>>> z = MX.sym("z"); w = MX.sym("w", 2)
>>> f.call([z, w])
[MX(f(z, w){0}), MX(f(z, w){1})]
>>> f.call([z, w], True)
[MX(vertcat((z*w[0]), (z*w[1]))), MX(sin(z))]
>>> a = SX.sym("a")
>>> f.call([a, [1, 2]])
[SX([a, (2.*a)]), SX(sin(a))]
>>> try:
...   f(1)
... except RuntimeError as e:
...   print("Incorrect number of inputs: Expected 2, got 1" in str(e))
True
>>> try:
...   f(1, [1, 2, 3])
... except RuntimeError as e:
...   print("Input 1 (y) has mismatching shape. Got 3-by-1" in str(e))
True

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> res = f.call({2, [3; 4]}); disp(res{1}), disp(res{2})
[6, 8]
0.909297
>> res = f.call(struct('x', 2)); disp(res.r), disp(res.s)
[0, 0]
0.909297
>> [r, s] = f(2, [3; 4]); disp(r), disp(s)
[6, 8]
0.909297
>> res = f('x', 2, 'y', [3; 4]); disp(res.r), disp(res.s)
[6, 8]
0.909297
>> [r, s] = f(2, DM([3, 5; 4, 6])); disp(r), disp(s)
[[6, 10],
 [8, 12]]
[[0.909297, 0.909297]]
>> [r, s] = f(DM(0, 0), 3); disp(r), disp(s)
[0, 0]
0
>> z = MX.sym('z'); w = MX.sym('w', 2);
>> res = f.call({z, w}); disp(res{1}), disp(res{2})
f(z, w){0}
f(z, w){1}
>> res = f.call({z, w}, true); disp(res{1}), disp(res{2})
vertcat((z*w[0]), (z*w[1]))
sin(z)
>> a = SX.sym('a'); res = f.call({a, [1; 2]}); disp(res{1}), disp(res{2})
[a, (2.*a)]
sin(a)
>> try, f(1); catch e, disp(contains(e.message, 'Expected 2, got 1')); end
1
>> try, f(1, [1; 2; 3]); catch e, disp(contains(e.message, 'Got 3-by-1')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> ca.call(f, [2, [3, 4]])
2-element Vector{DM}:
 DM([6, 8])
 DM(0.909297)
julia> ca.call(f, Dict("x" => 2))
Dict{String, DM} with 2 entries:
  "r" => [0, 0]
  "s" => 0.909297
julia> f(2, [3, 4])
([6, 8], 0.909297)
julia> f(x=2, y=[3, 4])
Dict{String, DM} with 2 entries:
  "r" => [6, 8]
  "s" => 0.909297
julia> r, s = f(2, [3 5; 4 6]);
julia> r
DM(
[[6, 10],
 [8, 12]])
julia> s
DM([[0.909297, 0.909297]])
julia> f(ca.DM(0, 0), 3)
([0, 0], 0)
julia> z = ca.MX.sym("z"); w = ca.MX.sym("w", 2);
julia> ca.call(f, [z, w])
2-element Vector{MX}:
 MX(f(z, w){0})
 MX(f(z, w){1})
julia> ca.call(f, [z, w], true)
2-element Vector{MX}:
 MX(vertcat((z*w[0]), (z*w[1])))
 MX(sin(z))
julia> a = ca.SX.sym("a");
julia> ca.call(f, [a, [1, 2]])
2-element Vector{SX}:
 SX([a, (2.*a)])
 SX(sin(a))
julia> try
           f(1)
       catch e
           msg = sprint(showerror, e)
           println(occursin("Incorrect number of inputs: Expected 2, got 1", msg))
       end
true
julia> try
           f(1, [1, 2, 3])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Input 1 (y) has mismatching shape. Got 3-by-1", msg))
       end
true

See also
default_in, convert_in, map, mapsum

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

Definition at line 1659 of file function.cpp.

1660  {
1661  try {
1662  call_gen(arg, res, always_inline, never_inline);
1663  } catch(std::exception& e) {
1664  THROW_ERROR("call", e.what());
1665  }
1666  }

References call_gen().

◆ call_gen() [1/2]

template<typename M >
void casadi::Function::call_gen ( const std::map< std::string, M > &  arg,
std::map< std::string, M > &  res,
bool  always_inline,
bool  never_inline 
) const

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

Definition at line 1616 of file function.cpp.

1617  {
1618  // Convert to vector arguments
1619  std::vector<M> arg_v = (*this)->convert_arg(arg);
1620 
1621  // Make call
1622  std::vector<M> res_v;
1623  call(arg_v, res_v, always_inline, never_inline);
1624 
1625  // Save to map
1626  res.clear();
1627  for (casadi_int i=0; i<res_v.size(); ++i) {
1628  res[name_out(i)] = res_v[i];
1629  }
1630  }
void call(const std::vector< DM > &arg, std::vector< DM > &res, bool always_inline=false, bool never_inline=false) const
Evaluate with a list or a dict of arguments; the result has the same form.
Definition: function.cpp:509

References call(), and name_out().

◆ call_gen() [2/2]

template<typename D >
void casadi::Function::call_gen ( std::vector< const D * >  arg,
std::vector< D * >  res 
) const

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

Definition at line 614 of file function.cpp.

614  {
615  // Input buffer
616  casadi_assert_dev(arg.size()>=n_in());
617  arg.resize(sz_arg());
618 
619  // Output buffer
620  casadi_assert_dev(res.size()>=n_out());
621  res.resize(sz_res());
622 
623  // Work vectors
624  std::vector<casadi_int> iw(sz_iw());
625  std::vector<D> w(sz_w());
626 
627  // Evaluate memoryless
628  (*this)(get_ptr(arg), get_ptr(res), get_ptr(iw), get_ptr(w), 0);
629  }

References casadi::get_ptr(), n_in(), n_out(), sz_arg(), sz_iw(), sz_res(), and sz_w().

Referenced by call(), and operator()().

◆ change_option()

void casadi::Function::change_option ( const std::string &  option_name,
const GenericType &  option_value 
)

Only options that do not change the numerical result can be changed: "verbose", "regularity_check", "print_in", "print_out", "dump", "dump_in", "dump_out", "dump_trace", "dump_dir", "dump_format", "print_time", "record_time" and "print_instructions". Any other existing option raises "cannot be changed"; an unknown name raises "does not exist".

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.change_option("verbose", False)
>>> try:
...   f.change_option("cse", True)
... except RuntimeError as e:
...   print("Option 'cse' cannot be changed" in str(e))
True

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> f.change_option('verbose', false)
>> try, f.change_option('cse', true); catch e, msg = e.message; end
>> contains(msg, 'Option ''cse'' cannot be changed')
1

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.change_option(f, "verbose", false)
julia> try
           ca.change_option(f, "cse", true)
       catch e
           println(occursin("Option 'cse' cannot be changed", sprint(showerror, e)))
       end
true

See also
has_option

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

Definition at line 1361 of file function.cpp.

1361  {
1362  try {
1363  // Assert existance
1364  if (!has_option(option_name))
1365  casadi_error("Option '" + option_name + "' does not exist");
1366  // Call internal class
1367  (*this)->change_option(option_name, option_value);
1368  } catch(std::exception& e) {
1369  THROW_ERROR("change_option", e.what());
1370  }
1371  }
bool has_option(const std::string &option_name) const
Check whether this class accepts an option with the given name.
Definition: function.cpp:1352

References has_option().

◆ check_name()

bool casadi::Function::check_name ( const std::string &  name)
static

A valid name starts with a letter and continues with letters, digits and underscores, with no two consecutive underscores; it may not be one of the keywords "null", "jac", "hess". Constructors and generate raise for invalid names; names must be valid C identifiers because they appear in generated code.

>>> Function.check_name("f_1"), Function.check_name("1f")
(True, False)
>>> Function.check_name("a__b"), Function.check_name("jac"), Function.check_name("")
(False, False, False)

>> fprintf('%d %d\n', Function.check_name('f_1'), Function.check_name('1f'))
1 0
>> fprintf('%d %d\n', Function.check_name('a__b'), Function.check_name('jac'))
0 0
>> Function.check_name('')
0

julia> F = ca.Function;
julia> F.check_name("f_1"), F.check_name("1f")
(true, false)
julia> F.check_name("a__b"), F.check_name("jac"), F.check_name("")
(false, false, false)

See also
fix_name

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

Definition at line 1513 of file function.cpp.

1513  {
1514  // Check if empty
1515  if (name.empty()) return false;
1516 
1517  // Check if keyword
1518  for (const char* kw : {"null", "jac", "hess"}) {
1519  if (name==kw) return false;
1520  }
1521 
1522  // Make sure that the first character is a letter
1523  auto it=name.begin();
1524  if (!std::isalpha(*it++)) return false;
1525 
1526  // Check remain_ing characters
1527  for (; it!=name.end(); ++it) {
1528  if (*it=='_') {
1529  // Make sure that the next character isn't also an underscore
1530  if (it+1!=name.end() && *(it+1)=='_') return false;
1531  } else {
1532  // Make sure alphanumeric
1533  if (!std::isalnum(*it)) return false;
1534  }
1535  }
1536 
1537  // Valid function name if reached this point
1538  return true;
1539  }

References name().

Referenced by casadi::CodeGenerator::CodeGenerator(), fix_name(), and casadi::FunctionInternal::FunctionInternal().

◆ checkout()

casadi_int casadi::Function::checkout ( ) const

Each memory object holds the state of one evaluation context (solver workspace, statistics); ordinary calls use index 0. Reserving separate objects allows concurrent evaluation from several threads with the low-level interface and separate stats. Release it with release when done.

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> m = f.checkout()
>>> m
1
>>> f.release(m)

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> m = f.checkout(); disp(m)
1
>> f.release(m)

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> m = ca.checkout(f)
1
julia> ca.release(f, m)

See also
release, stats, FunctionBuffer

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

Definition at line 1970 of file function.cpp.

1970  {
1971  return (*this)->checkout();
1972  }

Referenced by casadi::QpToNlp::alloc_mem(), casadi::FunctionBuffer::FunctionBuffer(), and casadi::FunctionBuffer::operator=().

◆ class_name()

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

◆ conditional() [1/2]

Function casadi::Function::conditional ( const std::string &  name,
const Function &  f,
const Dict &  opts = Dict() 
)
static

returns zeros otherwise

Shorthand for if_else with a zero-returning function of the same signature as the false branch; evaluating with a zero condition skips f entirely.

>>> x = SX.sym("x")
>>> f = Function("f", [x], [x**2])
>>> c = Function.conditional("c", f)
>>> c, c(0, 3), c(1, 3)
(Function(c:(i0,i1)->(o0) Switch), DM(0), DM(9))

>> x = SX.sym('x');
>> f = Function('f', {x}, {x^2});
>> c = Function.conditional('c', f); disp(c)
c:(i0,i1)->(o0) Switch
>> [c(0, 3), c(1, 3)]
[[0, 9]]

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [x^2]);
julia> c = ca.Function.conditional("c", f);
julia> println(c); c(0, 3), c(1, 3)
c:(i0,i1)->(o0) Switch
(0, 9)

See also
if_else

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

Definition at line 926 of file function.cpp.

927  {
928  try {
929  // Create a dummy function with the same signature as f
930  std::vector<MX> dummy_in = f.mx_in();
931  std::vector<MX> dummy_out(f.n_out());
932  for (casadi_int i = 0; i < dummy_out.size(); ++i) {
933  dummy_out.at(i) = MX::zeros(f.sparsity_out(i));
934  }
935  Function dummy("dummy_" + f.name(), dummy_in, dummy_out, f.name_in(), f.name_out());
936  // Form a conditional call
937  return if_else(name, f, dummy, opts);
938  } catch(std::exception& e) {
939  THROW_ERROR_NOOBJ("conditional", e.what(), "Switch");
940  }
941  }
static Function if_else(const std::string &name, const Function &f_true, const Function &f_false, const Dict &opts=Dict())
Create a function that evaluates f_true or f_false depending on.
Definition: function.cpp:962
static MX zeros(casadi_int nrow=1, casadi_int ncol=1)
Create a dense matrix or a matrix with specified sparsity with all entries zero.

References if_else(), mx_in(), n_out(), name(), name_in(), name_out(), sparsity_out(), and casadi::GenericMatrix< MX >::zeros().

◆ conditional() [2/2]

Function casadi::Function::conditional ( const std::string &  name,
const std::vector< Function > &  f,
const Function &  f_def,
const Dict &  opts = Dict() 
)
static

The result takes an index as first input followed by the inputs of the branch functions. At evaluation the index is truncated to an integer k; branch f[k] is evaluated when 0 <= k < len(f), otherwise f_def. All branches must have the same number of inputs and outputs; the signature (names, shapes) is taken from f_def and arguments are projected when a branch has a different sparsity. Derivatives are the derivatives of the selected branch. Symbolic MX evaluation gives a call node; unlike if_else on expressions, only the selected branch is evaluated numerically.

Parameters
nameName of the result
fBranch functions, selected by index 0, 1, ...
f_defDefault branch for indices out of range
optsFunction options

>>> x = SX.sym("x")
>>> f0 = Function("f0", [x], [x]); f1 = Function("f1", [x], [x**2])
>>> fdef = Function("fdef", [x], [-x])
>>> sw = Function.conditional("sw", [f0, f1], fdef)
>>> sw
Function(sw:(i0,i1)->(o0) Switch)
>>> sw(0, 3), sw(1, 3), sw(1.9, 3), sw(2, 3), sw(-1, 3)
(DM(3), DM(9), DM(9), DM(-3), DM(-3))
>>> sw(MX.sym("k"), MX.sym("v"))
MX(sw(k, v){0})

>> x = SX.sym('x');
>> f0 = Function('f0', {x}, {x}); f1 = Function('f1', {x}, {x^2});
>> fdef = Function('fdef', {x}, {-x});
>> sw = Function.conditional('sw', {f0, f1}, fdef); disp(sw)
sw:(i0,i1)->(o0) Switch
>> [sw(0, 3), sw(1, 3), sw(1.9, 3), sw(2, 3), sw(-1, 3)]
[[3, 9, 9, -3, -3]]
>> sw(MX.sym('k'), MX.sym('v'))
sw(k, v){0}

julia> x = ca.SX.sym("x");
julia> f0 = ca.Function("f0", [x], [x]); f1 = ca.Function("f1", [x], [x^2]);
julia> fdef = ca.Function("fdef", [x], [-x]);
julia> sw = ca.Function.conditional("sw", [f0, f1], fdef);
julia> sw
Function(sw:(i0,i1)->(o0) Switch)
julia> sw(0, 3), sw(1, 3), sw(1.9, 3), sw(2, 3), sw(-1, 3)
(3, 9, 9, -3, -3)
julia> sw(ca.MX.sym("k"), ca.MX.sym("v"))
MX(sw(k, v){0})

See also
if_else

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

Definition at line 917 of file function.cpp.

918  {
919  try {
920  return create(new Switch(name, f, f_def), opts);
921  } catch(std::exception& e) {
922  THROW_ERROR_NOOBJ("conditional", e.what(), "Switch");
923  }
924  }
static Function create(FunctionInternal *node)
Create from node.
Definition: function.cpp:488

References create(), and name().

Referenced by casadi::MX::conditional(), casadi::Switch::get_forward(), casadi::Switch::get_reverse(), and casadi::DaeBuilderInternal::transition().

◆ construct() [1/3]

template<typename M >
void casadi::Function::construct ( const std::string &  name,
const std::map< std::string, M > &  dict,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts 
)
protected

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

Definition at line 196 of file function.cpp.

199  {
200  std::vector<M> ex_in(name_in.size()), ex_out(name_out.size());
201  for (auto&& i : dict) {
202  std::vector<std::string>::const_iterator it;
203  it = std::find(name_in.begin(), name_in.end(), i.first);
204  if (it!=name_in.end()) {
205  // Input expression
206  ex_in[it-name_in.begin()] = i.second;
207  } else {
208  it = std::find(name_out.begin(), name_out.end(), i.first);
209  if (it!=name_out.end()) {
210  // Output expression
211  ex_out[it-name_out.begin()] = i.second;
212  } else {
213  // Neither
214  casadi_error("Unknown dictionary entry: '" + i.first + "'");
215  }
216  }
217  }
218  construct(name, ex_in, ex_out, name_in, name_out, opts);
219  }

References construct(), name(), name_in(), and name_out().

◆ construct() [2/3]

void casadi::Function::construct ( const std::string &  name,
const std::vector< MX > &  ex_in,
const std::vector< MX > &  ex_out,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts 
)
protected

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

Definition at line 249 of file function.cpp.

253  {
254  try {
255  own(new MXFunction(name, ex_in, ex_out, name_in, name_out));
256  (*this)->construct(opts);
257 
258  // Perform post-construction expand
259  auto it = opts.find("post_expand");
260  if (it!=opts.end()) {
261  if (!it->second) return;
262  auto it = opts.find("post_expand_options");
263  if (it==opts.end()) {
264  operator=((*this).expand());
265  } else {
266  operator=((*this).expand((*this).name(), it->second));
267  }
268  }
269 
270  // Perform external transformations
271  it = opts.find("external_transform");
272  if (it!=opts.end()) {
273  auto v = it->second.to_vector_vector();
274  for (const std::vector<GenericType>& vec : v) {
275  casadi_assert(vec.size()>=2, "external_transform: inner list must be length >=2");
276  casadi_assert(vec.size()<=3, "external_transform: inner list must be length <=3");
277  std::string name = vec[0].to_string();
278  std::string op = vec[1].to_string();
279  Dict opts = vec.size()==3 ? vec[2].to_dict() : Dict();
280  operator=(external_transform(name, op, (*this), opts));
281  }
282  }
283 
284  } catch(std::exception& e) {
285  THROW_ERROR_NOOBJ("Function", e.what(), "MXFunction");
286  }
287  }
GenericShared & operator=(const GenericShared &ref)
Assignment operator.
Function external_transform(const std::string &name, const std::string &op, const Function &f, const Dict &opts)
Apply a transformation defined externally.
Definition: tools.cpp:44

References casadi::external_transform(), name(), name_in(), name_out(), casadi::GenericShared< SharedObject, SharedObjectInternal >::operator=(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

◆ construct() [3/3]

void casadi::Function::construct ( const std::string &  name,
const std::vector< SX > &  ex_in,
const std::vector< SX > &  ex_out,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts 
)
protected

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

Definition at line 221 of file function.cpp.

225  {
226  try {
227  own(new SXFunction(name, ex_in, ex_out, name_in, name_out));
228  (*this)->construct(opts);
229 
230  // Perform external transformations
231  auto it = opts.find("external_transform");
232  if (it!=opts.end()) {
233  auto v = it->second.to_vector_vector();
234  for (const std::vector<GenericType>& vec : v) {
235  casadi_assert(vec.size()>=2, "external_transform: inner list must be length >=2");
236  casadi_assert(vec.size()<=3, "external_transform: inner list must be length <=3");
237  std::string name = vec[0].to_string();
238  std::string op = vec[1].to_string();
239  Dict opts = vec.size()==3 ? vec[2].to_dict() : Dict();
240  operator=(external_transform(name, op, (*this), opts));
241  }
242  }
243 
244  } catch(std::exception& e) {
245  THROW_ERROR_NOOBJ("Function", e.what(), "SXFunction");
246  }
247  }

References casadi::external_transform(), name(), name_in(), name_out(), casadi::GenericShared< SharedObject, SharedObjectInternal >::operator=(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

Referenced by construct(), and Function().

◆ convert_in() [1/6]

std::vector< DM > casadi::Function::convert_in ( const DMDict &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1817 of file function.cpp.

1817  {
1818  return (*this)->convert_arg(arg);
1819  }

◆ convert_in() [2/6]

std::vector< MX > casadi::Function::convert_in ( const MXDict &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1849 of file function.cpp.

1849  {
1850  return (*this)->convert_arg(arg);
1851  }

◆ convert_in() [3/6]

DMDict casadi::Function::convert_in ( const std::vector< DM > &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1813 of file function.cpp.

1813  {
1814  return (*this)->convert_arg(arg);
1815  }

◆ convert_in() [4/6]

MXDict casadi::Function::convert_in ( const std::vector< MX > &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1845 of file function.cpp.

1845  {
1846  return (*this)->convert_arg(arg);
1847  }

◆ convert_in() [5/6]

SXDict casadi::Function::convert_in ( const std::vector< SX > &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1829 of file function.cpp.

1829  {
1830  return (*this)->convert_arg(arg);
1831  }

◆ convert_in() [6/6]

std::vector< SX > casadi::Function::convert_in ( const SXDict &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1833 of file function.cpp.

1833  {
1834  return (*this)->convert_arg(arg);
1835  }

◆ convert_out() [1/6]

std::vector< DM > casadi::Function::convert_out ( const DMDict &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1825 of file function.cpp.

1825  {
1826  return (*this)->convert_res(arg);
1827  }

◆ convert_out() [2/6]

std::vector< MX > casadi::Function::convert_out ( const MXDict &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1857 of file function.cpp.

1857  {
1858  return (*this)->convert_res(arg);
1859  }

◆ convert_out() [3/6]

DMDict casadi::Function::convert_out ( const std::vector< DM > &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1821 of file function.cpp.

1821  {
1822  return (*this)->convert_res(arg);
1823  }

◆ convert_out() [4/6]

MXDict casadi::Function::convert_out ( const std::vector< MX > &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1853 of file function.cpp.

1853  {
1854  return (*this)->convert_res(arg);
1855  }

◆ convert_out() [5/6]

SXDict casadi::Function::convert_out ( const std::vector< SX > &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1837 of file function.cpp.

1837  {
1838  return (*this)->convert_res(arg);
1839  }

◆ convert_out() [6/6]

std::vector< SX > casadi::Function::convert_out ( const SXDict &  arg) const

convert_in turns a list of n_in() values into a dict keyed by input name, and a dict into a list where absent inputs get default_in. convert_out does the same for outputs; absent outputs become nan. An unknown key or a list of the wrong length raises an error. Values are passed through unchanged (no shape or sparsity check), for any of DM, SX and MX. Useful to prepare arguments for call or generate_in.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0), SX(1)], ["x", "y"], ["a", "b"])
>>> f.convert_in([1, 2])
{'x': DM(1), 'y': DM(2)}
>>> f.convert_in({"y": 2})
[DM(0), DM(2)]
>>> f.convert_out({"b": 5})
[DM(nan), DM(5)]
>>> try:
...   f.convert_in({"z": 1})
... except RuntimeError as e:
...   print('could not find entry "z"' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0), SX(1)}, {'x', 'y'}, {'a', 'b'});
>> s = f.convert_in({1, 2}); disp(s.x), disp(s.y)
1
2
>> c = f.convert_in(struct('y', 2)); disp(c{1}), disp(c{2})
0
2
>> c = f.convert_out(struct('b', 5)); disp(c{1}), disp(c{2})
nan
5
>> try, f.convert_in(struct('z', 1)); catch e, msg = e.message; end
>> contains(msg, 'could not find entry "z"')
1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0), ca.SX(1)],
                       ["x", "y"], ["a", "b"]);
julia> ca.convert_in(f, Dict("y" => 2))
2-element Vector{DM}:
 DM(0)
 DM(2)
julia> ca.convert_out(f, Dict("b" => 5))
2-element Vector{DM}:
 DM(nan)
 DM(5)
julia> try
           ca.convert_in(f, Dict("z" => 1))
       catch e
           println(occursin("could not find entry \"z\"", sprint(showerror, e)))
       end
true

See also
call, default_in, nz_from_in

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

Definition at line 1841 of file function.cpp.

1841  {
1842  return (*this)->convert_res(arg);
1843  }

◆ 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() [1/2]

Function casadi::Function::create ( FunctionInternal *  node)
static

◆ create() [2/2]

Function casadi::Function::create ( FunctionInternal *  node,
const Dict &  opts 
)
static

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

Definition at line 494 of file function.cpp.

494  {
495  Function ret = create(node);
496  ret->construct(opts);
497  return ret;
498  }

References casadi::ProtoFunction::construct(), and create().

◆ 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

◆ default_in()

double casadi::Function::default_in ( casadi_int  ind) const

When calling with a dict (or keyword arguments), every input that is not given is filled with this scalar, broadcast to the input shape. For functions built from expressions it is 0 unless option "default_in" was set at construction. Solvers define their own: nlpsol uses -inf for lbx and lbg, inf for ubx and ubg, 0 for the rest.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x + y], ["x", "y"], ["r"])
>>> f.default_in(0), f(x=3)
(0.0, {'r': DM([3, 3])})
>>> g = Function("g", [x, y], [x + y], ["x", "y"], ["r"], {"default_in": [1, 2]})
>>> g.default_in(1), g(x=3), g(y=[0, 1])
(2.0, {'r': DM([5, 5])}, {'r': DM([1, 2])})

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x + y}, {'x', 'y'}, {'r'});
>> disp(f.default_in(0)), res = f('x', 3); disp(res.r)
0
[3, 3]
>> opts = struct('default_in', [1, 2]);
>> g = Function('g', {x, y}, {x + y}, {'x', 'y'}, {'r'}, opts);
>> disp(g.default_in(1)), res = g('x', 3); disp(res.r), res = g('y', [0; 1]); disp(res.r)
2
[5, 5]
[1, 2]

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x + y], ["x", "y"], ["r"]);
julia> ca.default_in(f, 0), f(x=3)["r"]
(0.0, [3, 3])
julia> opts = Dict("default_in" => [1, 2]);
julia> g = ca.Function("g", [x, y], [x + y], ["x", "y"], ["r"], opts);
julia> ca.default_in(g, 1), g(x=3)["r"], g(y=[0, 1])["r"]
(2.0, [5, 5], [1, 2])

See also
max_in, min_in, nominal_in, convert_in

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

Definition at line 1677 of file function.cpp.

1677  {
1678  return (*this)->get_default_in(ind);
1679  }

Referenced by casadi::Blocksqp::feasibilityRestorationPhase(), and casadi::FiniteDiff::get_default_in().

◆ deserialize() [1/3]

Function casadi::Function::deserialize ( const std::string &  s)
static

Raises "DeserializingStream sanity check failed" for data that is not a serialized CasADi object.

>>> x = SX.sym("x")
>>> f = Function.deserialize(Function("f", [x], [2*x]).serialize())
>>> f(3)
DM(6)
>>> try:
...   Function.deserialize("not a function")
... except RuntimeError as e:
...   print("sanity check failed" in str(e))
True

>> x = SX.sym('x');
>> f = Function.deserialize(Function('f', {x}, {2*x}).serialize());
>> f(3)
6
>> try, Function.deserialize('not a function'); catch e, msg = e.message; end
>> contains(msg, 'sanity check failed')
1

julia> x = ca.SX.sym("x");
julia> f = ca.Function.deserialize(ca.serialize(ca.Function("f", [x], [2x])));
julia> f(3)
DM(6)
julia> try
           ca.Function.deserialize("not a function")
       catch e
           println(occursin("sanity check failed", sprint(showerror, e)))
       end
true

See also
serialize, load

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

Definition at line 1556 of file function.cpp.

1556  {
1557  std::stringstream ss;
1558  ss << s;
1559  return deserialize(ss);
1560  }
static Function deserialize(std::istream &stream)
Build a function from a serialization stream.
Definition: function.cpp:1541

References deserialize().

◆ deserialize() [2/3]

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

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

Definition at line 1491 of file function.cpp.

1491  {
1492  bool is_null;
1493  s.unpack("Function::null", is_null);
1494  if (is_null) return Function();
1496  }
static Function deserialize(DeserializingStream &s)
Deserialize with type disambiguation.

References casadi::FunctionInternal::deserialize(), Function(), casadi::GenericShared< SharedObject, SharedObjectInternal >::is_null(), and casadi::DeserializingStream::unpack().

◆ deserialize() [3/3]

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

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

Definition at line 1541 of file function.cpp.

1541  {
1542  DeserializingStream s(stream);
1543  return deserialize(s);
1544  }

Referenced by deserialize().

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

◆ eval_activity()

int casadi::Function::eval_activity ( const bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t *  w,
int  mem = 0 
) const

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

Definition at line 1260 of file function.cpp.

1261  {
1262  try {
1263  return (*this)->eval_activity(arg, res, iw, w, memory(mem));
1264  } catch(std::exception& e) {
1265  THROW_ERROR("eval_activity", e.what());
1266  }
1267  }
void * memory(int ind) const
Get memory object.
Definition: function.cpp:1978

References memory().

Referenced by activity(), and casadi::Call::eval_activity().

◆ expand() [1/2]

Function casadi::Function::expand ( ) const

Evaluates the function symbolically with SX inputs and builds an SXFunction from the result: every matrix node is unrolled into scalar instructions. Evaluation of the result is typically faster per operation, at the cost of memory proportional to the number of scalar operations. The name, input/output names and the options of the original function (other than the SX-specific ones given in opts) are kept.

Fails when the graph contains a node that has no scalar expansion, with "eval_sx not defined for ...": for example calls to external functions or linear solves (solve, inv) with a numerical plugin; use the "symbolicqr" plugin for those. Fails when the function has free variables. An SXFunction is returned unchanged (as a copy).

Parameters
nameName of the new function; defaults to the current name
optsOptions for the SXFunction constructor, e.g. "live_variables", "cse"
Returns
SXFunction

>>> x = MX.sym("x", 2)
>>> f = Function("f", [x], [x.T @ x, 2*x], ["x"], ["q", "y"])
>>> f, f.n_instructions()
(Function(f:(x[2])->(q,y[2]) MXFunction), 7)
>>> g = f.expand()
>>> g, g.n_instructions()
(Function(f:(x[2])->(q,y[2]) SXFunction), 10)
>>> f([1, 2]), g([1, 2])
((DM(5), DM([2, 4])), (DM(5), DM([2, 4])))
>>> f.expand("f_sx", {"live_variables": False})
Function(f_sx:(x[2])->(q,y[2]) SXFunction)
>>> A = MX.sym("A", 2, 2)
>>> h = Function("h", [A, x], [solve(A, x)])
>>> try:
...   h.expand()
... except RuntimeError as e:
...   print("eval_sx not defined" in str(e))
True
>>> Function("h", [A, x], [solve(A, x, "symbolicqr")]).expand().class_name()
'SXFunction'

>> x = MX.sym('x', 2);
>> f = Function('f', {x}, {x'*x, 2*x}, {'x'}, {'q', 'y'});
>> f, f.n_instructions()
f:(x[2])->(q,y[2]) MXFunction
7
>> g = f.expand(); disp(g), disp(g.n_instructions())
f:(x[2])->(q,y[2]) SXFunction
10
>> [q, y] = g([1; 2]); disp(q), disp(y)
5
[2, 4]
>> f.expand('f_sx', struct('live_variables', false))
f_sx:(x[2])->(q,y[2]) SXFunction
>> A = MX.sym('A', 2, 2); h = Function('h', {A, x}, {solve(A, x)});
>> try, h.expand(); catch e, disp(contains(e.message, 'eval_sx not defined')); end
1
>> Function('h', {A, x}, {solve(A, x, 'symbolicqr')}).expand().class_name()
SXFunction

julia> x = ca.MX.sym("x", 2);
julia> f = ca.Function("f", [x], [x' * x, 2x], ["x"], ["q", "y"]);
julia> println(f); ca.n_instructions(f)
f:(x[2])->(q,y[2]) MXFunction
7
julia> g = ca.expand(f);
julia> println(g); ca.n_instructions(g)
f:(x[2])->(q,y[2]) SXFunction
10
julia> f([1, 2]), g([1, 2])
((5, [2, 4]), (5, [2, 4]))
julia> ca.expand(f, "f_sx", Dict("live_variables" => false))
Function(f_sx:(x[2])->(q,y[2]) SXFunction)
julia> A = ca.MX.sym("A", 2, 2);
julia> h = ca.Function("h", [A, x], [A \ x]);
julia> try
           ca.expand(h)
       catch e
           println(occursin("eval_sx not defined", sprint(showerror, e)))
       end
true
julia> ca.class_name(ca.expand(ca.Function("h", [A, x], [ca.solve(A, x, "symbolicqr")])))
"SXFunction"

See also
Function::Function, transform

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

Examples
Function/expand.py, and MX/matrix_expand.py.

Definition at line 312 of file function.cpp.

312  {
313  Dict opts = (*this)->generate_options("clone");
314  return expand(name(), opts);
315  }
Function expand() const
Convert an MXFunction into an equivalent SXFunction.
Definition: function.cpp:312

References casadi::FunctionInternal::generate_options(), and name().

Referenced by casadi::OracleFunction::expand(), casadi::OracleFunction::finalize(), casadi::Nlpsol::init(), casadi::OracleFunction::init(), casadi::MX::matrix_expand(), casadi::DaeBuilderInternal::oracle(), casadi::qpsol_nlp(), and transform().

◆ expand() [2/2]

Function casadi::Function::expand ( const std::string &  name,
const Dict &  opts = Dict() 
) const

Evaluates the function symbolically with SX inputs and builds an SXFunction from the result: every matrix node is unrolled into scalar instructions. Evaluation of the result is typically faster per operation, at the cost of memory proportional to the number of scalar operations. The name, input/output names and the options of the original function (other than the SX-specific ones given in opts) are kept.

Fails when the graph contains a node that has no scalar expansion, with "eval_sx not defined for ...": for example calls to external functions or linear solves (solve, inv) with a numerical plugin; use the "symbolicqr" plugin for those. Fails when the function has free variables. An SXFunction is returned unchanged (as a copy).

Parameters
nameName of the new function; defaults to the current name
optsOptions for the SXFunction constructor, e.g. "live_variables", "cse"
Returns
SXFunction

>>> x = MX.sym("x", 2)
>>> f = Function("f", [x], [x.T @ x, 2*x], ["x"], ["q", "y"])
>>> f, f.n_instructions()
(Function(f:(x[2])->(q,y[2]) MXFunction), 7)
>>> g = f.expand()
>>> g, g.n_instructions()
(Function(f:(x[2])->(q,y[2]) SXFunction), 10)
>>> f([1, 2]), g([1, 2])
((DM(5), DM([2, 4])), (DM(5), DM([2, 4])))
>>> f.expand("f_sx", {"live_variables": False})
Function(f_sx:(x[2])->(q,y[2]) SXFunction)
>>> A = MX.sym("A", 2, 2)
>>> h = Function("h", [A, x], [solve(A, x)])
>>> try:
...   h.expand()
... except RuntimeError as e:
...   print("eval_sx not defined" in str(e))
True
>>> Function("h", [A, x], [solve(A, x, "symbolicqr")]).expand().class_name()
'SXFunction'

>> x = MX.sym('x', 2);
>> f = Function('f', {x}, {x'*x, 2*x}, {'x'}, {'q', 'y'});
>> f, f.n_instructions()
f:(x[2])->(q,y[2]) MXFunction
7
>> g = f.expand(); disp(g), disp(g.n_instructions())
f:(x[2])->(q,y[2]) SXFunction
10
>> [q, y] = g([1; 2]); disp(q), disp(y)
5
[2, 4]
>> f.expand('f_sx', struct('live_variables', false))
f_sx:(x[2])->(q,y[2]) SXFunction
>> A = MX.sym('A', 2, 2); h = Function('h', {A, x}, {solve(A, x)});
>> try, h.expand(); catch e, disp(contains(e.message, 'eval_sx not defined')); end
1
>> Function('h', {A, x}, {solve(A, x, 'symbolicqr')}).expand().class_name()
SXFunction

julia> x = ca.MX.sym("x", 2);
julia> f = ca.Function("f", [x], [x' * x, 2x], ["x"], ["q", "y"]);
julia> println(f); ca.n_instructions(f)
f:(x[2])->(q,y[2]) MXFunction
7
julia> g = ca.expand(f);
julia> println(g); ca.n_instructions(g)
f:(x[2])->(q,y[2]) SXFunction
10
julia> f([1, 2]), g([1, 2])
((5, [2, 4]), (5, [2, 4]))
julia> ca.expand(f, "f_sx", Dict("live_variables" => false))
Function(f_sx:(x[2])->(q,y[2]) SXFunction)
julia> A = ca.MX.sym("A", 2, 2);
julia> h = ca.Function("h", [A, x], [A \ x]);
julia> try
           ca.expand(h)
       catch e
           println(occursin("eval_sx not defined", sprint(showerror, e)))
       end
true
julia> ca.class_name(ca.expand(ca.Function("h", [A, x], [ca.solve(A, x, "symbolicqr")])))
"SXFunction"

See also
Function::Function, transform

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

Definition at line 317 of file function.cpp.

317  {
318  casadi_assert(!has_free(),
319  "Function with free symbols cannot be expanded. "
320  "List of free variables in your Function: " +
321  join(get_free(), ","));
322 
323  Dict my_opts = (*this)->generate_options("clone");
324  update_dict(my_opts, opts);
325  std::vector<SX> ex_in = sx_in();
326  std::vector<SX> ex_out = Function(*this)(ex_in);
327  return Function(name, ex_in, ex_out, name_in(), name_out(), my_opts);
328  }
std::vector< std::string > get_free() const
Get the names of the free variables; empty when there are none.
Definition: function.cpp:1382
bool has_free() const
Check whether the outputs contain symbols that are not inputs.
Definition: function.cpp:1894
const std::vector< SX > sx_in() const
Create fresh symbols with the names and sparsity patterns of the inputs.
Definition: function.cpp:1765
std::string join(const std::vector< std::string > &l, const std::string &delim)
void update_dict(Dict &target, const Dict &source, bool recurse)
Update the target dictionary in place with source elements.

References Function(), get_free(), has_free(), casadi::join(), name(), name_in(), name_out(), sx_in(), and casadi::update_dict().

◆ export_code() [1/3]

std::string casadi::Function::export_code ( const std::string &  lang,
const Dict &  options = Dict() 
) const

Only "matlab" is supported, and only for SXFunction and MXFunction without free variables; other classes or languages raise an error. The code is a plain MATLAB function with the same name that evaluates the algorithm on numeric arguments, without any CasADi dependency. The file overload writes to fname, the other returns the code as a string.

Parameters
lang"matlab"
options"indent_level" (integer)

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)])
>>> f.export_code("matlab").splitlines()[0]
'function [varargout] = f(varargin)'
>>> try:
...   f.export_code("python")
... except RuntimeError as e:
...   print("Only matlab language supported" in str(e))
True

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)});
>> code = strsplit(f.export_code('matlab'), newline); disp(code{1})
function [varargout] = f(varargin)
>> try, f.export_code('python'); catch e, disp(contains(e.message, 'Only matlab')); end
1

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)]);
julia> first(split(ca.export_code(f, "matlab"), "\n"))
"function [varargout] = f(varargin)"
julia> try
           ca.export_code(f, "python")
       catch e
           println(occursin("Only matlab language supported", sprint(showerror, e)))
       end
true

See also
generate

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

Definition at line 1498 of file function.cpp.

1498  {
1499  std::stringstream ss;
1500  (*this)->export_code(lang, ss, options);
1501  return ss.str();
1502  }

◆ export_code() [2/3]

void casadi::Function::export_code ( const std::string &  lang,
const std::string &  fname,
const Dict &  options = Dict() 
) const

Only "matlab" is supported, and only for SXFunction and MXFunction without free variables; other classes or languages raise an error. The code is a plain MATLAB function with the same name that evaluates the algorithm on numeric arguments, without any CasADi dependency. The file overload writes to fname, the other returns the code as a string.

Parameters
lang"matlab"
options"indent_level" (integer)

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)])
>>> f.export_code("matlab").splitlines()[0]
'function [varargout] = f(varargin)'
>>> try:
...   f.export_code("python")
... except RuntimeError as e:
...   print("Only matlab language supported" in str(e))
True

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)});
>> code = strsplit(f.export_code('matlab'), newline); disp(code{1})
function [varargout] = f(varargin)
>> try, f.export_code('python'); catch e, disp(contains(e.message, 'Only matlab')); end
1

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)]);
julia> first(split(ca.export_code(f, "matlab"), "\n"))
"function [varargout] = f(varargin)"
julia> try
           ca.export_code(f, "python")
       catch e
           println(occursin("Only matlab language supported", sprint(showerror, e)))
       end
true

See also
generate

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

Definition at line 1459 of file function.cpp.

1460  {
1461  auto stream_ptr = Filesystem::ofstream_ptr(fname);
1462  (*this)->export_code(lang, *stream_ptr, options);
1463  }
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 casadi::Filesystem::ofstream_ptr().

◆ export_code() [3/3]

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

Only "matlab" is supported, and only for SXFunction and MXFunction without free variables; other classes or languages raise an error. The code is a plain MATLAB function with the same name that evaluates the algorithm on numeric arguments, without any CasADi dependency. The file overload writes to fname, the other returns the code as a string.

Parameters
lang"matlab"
options"indent_level" (integer)

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)])
>>> f.export_code("matlab").splitlines()[0]
'function [varargout] = f(varargin)'
>>> try:
...   f.export_code("python")
... except RuntimeError as e:
...   print("Only matlab language supported" in str(e))
True

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)});
>> code = strsplit(f.export_code('matlab'), newline); disp(code{1})
function [varargout] = f(varargin)
>> try, f.export_code('python'); catch e, disp(contains(e.message, 'Only matlab')); end
1

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)]);
julia> first(split(ca.export_code(f, "matlab"), "\n"))
"function [varargout] = f(varargin)"
julia> try
           ca.export_code(f, "python")
       catch e
           println(occursin("Only matlab language supported", sprint(showerror, e)))
       end
true

See also
generate

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

Definition at line 1454 of file function.cpp.

1455  {
1456  (*this)->export_code(lang, stream, options);
1457  }

◆ export_graph() [1/2]

std::string casadi::Function::export_graph ( const Dict &  opts = Dict()) const

Uses the same graph options as the filename overload.

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

Definition at line 507 of file visualizer.cpp.

507  {
508  return serialized_bundle(*this, opts, "function");
509 }

◆ export_graph() [2/2]

void casadi::Function::export_graph ( const std::string &  fname,
const Dict &  opts = Dict() 
) const

HTML and .casadi_viz embed the serialized Function, decoded by the browser viewer; any serializable Function works, and helpers such as nlp_hess_l can be explored. include_functions (default true) shows called and helper Functions in the viewer. DOT is standalone Graphviz of an SX/MX root graph only. Options show_matrix_contents and show_matrix_sizes (both default true) control matrix detail and dimensions. Load dump_trace JSONL files in the viewer to replay numerical evaluation. Options: view (function, expression; default function), direction (LR, RL, TB, BT; expression view only; default TB), viz_js (local Viz.js global bundle to embed; by default uses the viewer package renderer). viewer_url (string) overrides the HTML viewer ESM module URL; default is https://unpkg.com/@casadi/casadi-viz@MAJOR.MINOR/dist/index.js for this CasADi version.

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

Definition at line 511 of file visualizer.cpp.

511  {
512  const GraphOptions options(opts);
513  write_graph(fname, graph_extension(fname) == ".dot" ? graph_dot(*this, options)
514  : serialized_bundle(*this, opts, "function"), options);
515 }

◆ factory()

Function casadi::Function::factory ( const std::string &  name,
const std::vector< std::string > &  s_in,
const std::vector< std::string > &  s_out,
const AuxOut &  aux = AuxOut(),
const Dict &  opts = Dict() 
) const

Only defined for SXFunction and MXFunction (other classes raise an error). The new function takes the inputs listed in s_in and returns the outputs listed in s_out, in that order. Each entry is either an existing name or a derivative request built from existing names with ':' separators:

  • inputs: "fwd:x" a forward seed for input x, "adj:r" an adjoint seed for output r, "lam:r" a multiplier for output r (used by aux)
  • outputs: "fwd:r" forward sensitivity, "adj:x" adjoint sensitivity, "jac:r:x" the Jacobian of r with respect to x, "grad:r:x" its gradient (r must be scalar), "hess:r:x:y" the Hessian of scalar r with respect to x and y
  • an output may be prefixed with "triu:", "tril:" or "sym:" to return only the upper or lower triangle of a Hessian, or to symmetrize it

The output names of the result have ':' replaced by '_' (jac:r:x becomes jac_r_x). Non-differentiable inputs and outputs (is_diff_in/is_diff_out) give all-zero blocks. An input that is needed by an output but not listed in s_in is treated as zero. An unknown name raises an error listing the available names.

Parameters
nameName of the new function
s_inInput requests, see above
s_outOutput requests, see above
auxExtra scalar outputs defined as linear combinations: {"gamma": ["f", "g"]} defines gamma = lam_f'*f + lam_g'*g, so that "grad:gamma:x" and "hess:gamma:x:x" are the Lagrangian gradient and Hessian with inputs "lam:f" and "lam:g"
opts"helper_options" and "final_options" (dicts for the intermediate and the returned function) and any Function option for the result

>>> x = SX.sym("x", 2); p = SX.sym("p")
>>> f = Function("f", [x, p], [p*dot(x, x), x[0]*x[1]], ["x", "p"], ["f", "g"])
>>> g = f.factory("g", ["x", "p"], ["jac:f:x", "hess:f:x:x", "jac:g:x"])
>>> g
Function(g:(x[2],p)->(jac_f_x[1x2],hess_f_x_x[2x2,2nz],jac_g_x[1x2]) SXFunction)
>>> g([1, 2], 3)
(DM([[6, 12]]), DM(
[[6, 00],
 [00, 6]]), DM([[2, 1]]))
>>> L = f.factory("L", ["x", "p", "lam:f", "lam:g"], ["grad:gamma:x"],
...               {"gamma": ["f", "g"]})
>>> L, L([1, 2], 3, 1, 2)
(Function(L:(x[2],p,lam_f,lam_g)->(grad_gamma_x[2]) SXFunction), DM([10, 14]))
>>> h = f.factory("h", ["x", "p", "fwd:x", "fwd:p"], ["fwd:f"])
>>> h([1, 2], 3, [1, 0], 0)
DM(6)
>>> try:
...   f.factory("bad", ["x"], ["jac:q:x"])
... except RuntimeError as e:
...   print('Cannot process "q" as output. Available: f,g.' in str(e))
True

>> x = SX.sym('x', 2); p = SX.sym('p');
>> f = Function('f', {x, p}, {p*dot(x, x), x(1)*x(2)}, {'x', 'p'}, {'f', 'g'});
>> g = f.factory('g', {'x', 'p'}, {'jac:f:x', 'hess:f:x:x', 'jac:g:x'}); disp(g)
g:(x[2],p)->(jac_f_x[1x2],hess_f_x_x[2x2,2nz],jac_g_x[1x2]) SXFunction
>> [jac_f_x, hess_f_x_x, jac_g_x] = g([1; 2], 3);
>> jac_f_x, hess_f_x_x, jac_g_x
[[6, 12]]
[[6, 00],
 [00, 6]]
[[2, 1]]
>> aux = struct('gamma', {{'f', 'g'}});
>> L = f.factory('L', {'x', 'p', 'lam:f', 'lam:g'}, {'grad:gamma:x'}, aux);
>> L, L([1; 2], 3, 1, 2)
L:(x[2],p,lam_f,lam_g)->(grad_gamma_x[2]) SXFunction
[10, 14]
>> h = f.factory('h', {'x', 'p', 'fwd:x', 'fwd:p'}, {'fwd:f'});
>> h([1; 2], 3, [1; 0], 0)
6
>> try, f.factory('bad', {'x'}, {'jac:q:x'}); catch e, msg = e.message; end
>> contains(msg, 'Cannot process "q" as output. Available: f,g.')
1

julia> x = ca.SX.sym("x", 2); p = ca.SX.sym("p");
julia> f = ca.Function("f", [x, p], [p * ca.dot(x, x), x[1] * x[2]],
                       ["x", "p"], ["f", "g"]);
julia> g = ca.factory(f, "g", ["x", "p"], ["jac:f:x", "hess:f:x:x", "jac:g:x"]);
julia> g
Function(g:(x[2],p)->(jac_f_x[1x2],hess_f_x_x[2x2,2nz],jac_g_x[1x2]) SXFunction)
julia> jac_f_x, hess_f_x_x, jac_g_x = g([1, 2], 3);
julia> jac_f_x
DM([[6, 12]])
julia> hess_f_x_x
DM(
[[6, 00],
 [00, 6]])
julia> jac_g_x
DM([[2, 1]])
julia> L = ca.factory(f, "L", ["x", "p", "lam:f", "lam:g"], ["grad:gamma:x"],
                     Dict("gamma" => ["f", "g"]));
julia> println(L); L([1, 2], 3, 1, 2)
L:(x[2],p,lam_f,lam_g)->(grad_gamma_x[2]) SXFunction
DM([10, 14])
julia> h = ca.factory(f, "h", ["x", "p", "fwd:x", "fwd:p"], ["fwd:f"]);
julia> h([1, 2], 3, [1, 0], 0)
DM(6)
julia> try
           ca.factory(f, "bad", ["x"], ["jac:q:x"])
       catch e
           msg = sprint(showerror, e)
           println(occursin("Cannot process \"q\" as output. Available: f,g.", msg))
       end
true

See also
jacobian, forward, reverse, which_depends

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

Definition at line 2008 of file function.cpp.

2013  {
2014  try {
2015  return (*this)->factory(name, s_in, s_out, aux, opts);
2016  } catch(std::exception& e) {
2017  THROW_ERROR("factory", "Failed to create " + name + ":" + str(s_in) + "->" + str(s_out)
2018  + " with " + str(aux) + ":\n" + str(e.what()));
2019  }
2020  }

References casadi::FunctionInternal::factory(), name(), and casadi::str().

Referenced by casadi::DaeBuilderInternal::create(), casadi::OracleFunction::create_function(), casadi::FunctionInternal::factory(), casadi::KinsolInterface::get_jtimes(), hessian_old(), casadi::Rootfinder::init(), casadi::Blocksqp::init(), jacobian_old(), and casadi::Nlpsol::kkt().

◆ find_function()

Function casadi::Function::find_function ( const std::string &  name,
casadi_int  max_depth = -1 
) const
Parameters
nameName of the function; raises "'name' not found" when absent
max_depthMaximum nesting depth, negative for no limit
See also
find_functions

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

Definition at line 2084 of file function.cpp.

2084  {
2085  try {
2086  // If negative, make largest positive number
2087  if (max_depth < 0) max_depth = std::numeric_limits<casadi_int>::max();
2088  // The internal routine uses a map to avoid duplicate functions
2089  std::map<FunctionInternal*, std::pair<Function, size_t> > all_fun;
2090  (*this)->find(all_fun, max_depth);
2091  // Search this map
2092  for (auto&& e : all_fun) {
2093  if (e.second.first.name() == name) return e.second.first;
2094  }
2095  // Not found
2096  casadi_error("'" + name + "' not found");
2097  } catch(std::exception& e) {
2098  THROW_ERROR("find", e.what());
2099  return Function();
2100  }
2101  }

References Function(), and name().

◆ find_functions()

std::vector< Function > casadi::Function::find_functions ( casadi_int  max_depth = -1) const

Walks the owned functions (get_function) and their owned functions in turn, returning each distinct Function once, in depth-first discovery order.

Parameters
max_depthMaximum nesting depth to descend; 0 returns only the directly owned functions, a negative number means no limit
Returns
Unique list of embedded functions

>>> x = MX.sym("x")
>>> inner = Function("inner", [x], [sin(x)]).expand()
>>> middle = Function("middle", [x], [inner(x) + 1])
>>> outer = Function("outer", [x], [middle.call([x], False, True)[0]*2])
>>> [g.name() for g in outer.find_functions()]
['middle', 'inner']
>>> [g.name() for g in outer.find_functions(0)]
['middle']
>>> outer.find_function("inner")
Function(inner:(i0)->(o0) SXFunction)
>>> Function("o2", [x], [middle(x)*2]).get_function()
['inner']

>> x = MX.sym('x');
>> inner = Function('inner', {x}, {sin(x)}).expand();
>> middle = Function('middle', {x}, {inner(x) + 1});
>> res = middle.call({x}, false, true); outer = Function('outer', {x}, {res{1}*2});
>> fs = outer.find_functions(); cellfun(@(g) disp(g.name()), fs)
middle
inner
>> fs = outer.find_functions(0); disp(fs{1}.name())
middle
>> outer.find_function('inner')
inner:(i0)->(o0) SXFunction
>> Function('o2', {x}, {middle(x)*2}).get_function()
inner

julia> x = ca.MX.sym("x");
julia> inner = ca.expand(ca.Function("inner", [x], [sin(x)]));
julia> middle = ca.Function("middle", [x], [inner(x) + 1]);
julia> outer = ca.Function("outer", [x], [ca.call(middle, [x], false, true)[1] * 2]);
julia> [ca.name(g) for g in ca.find_functions(outer)]
2-element Vector{String}:
 "middle"
 "inner"
julia> [ca.name(g) for g in ca.find_functions(outer, 0)]
1-element Vector{String}:
 "middle"
julia> ca.find_function(outer, "inner")
Function(inner:(i0)->(o0) SXFunction)
julia> ca.get_function(ca.Function("o2", [x], [middle(x) * 2]))
1-element Vector{String}:
 "inner"

See also
find_function, get_function

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

Definition at line 2067 of file function.cpp.

2067  {
2068  try {
2069  // If negative, make largest positive number
2070  if (max_depth < 0) max_depth = std::numeric_limits<casadi_int>::max();
2071  // The internal routine uses a map to avoid duplicate functions
2072  std::map<FunctionInternal*, std::pair<Function, size_t> > all_fun;
2073  (*this)->find(all_fun, max_depth);
2074  // Create return object
2075  std::vector<Function> ret(all_fun.size());
2076  for (auto&& e : all_fun) ret[e.second.second] = e.second.first;
2077  return ret;
2078  } catch(std::exception& e) {
2079  THROW_ERROR("find", e.what());
2080  return {};
2081  }
2082  }

Referenced by casadi::FunctionInternal::codegen_decref(), casadi::FunctionInternal::codegen_incref(), and casadi::DaeBuilder::gather_fun().

◆ fix_name()

std::string casadi::Function::fix_name ( const std::string &  name)
static

Runs of non-alphanumeric characters become a single underscore, a leading non-letter gets an "a" prepended, the empty string becomes "unnamed" and a keyword gets "1" appended. A valid name is returned unchanged.

>>> Function.fix_name("my func!"), Function.fix_name("1f"), Function.fix_name("")
('my_func_', 'a1f', 'unnamed')
>>> Function.fix_name("jac"), Function.fix_name("ok")
('jac1', 'ok')

>> Function.fix_name('my func!'), Function.fix_name('1f')
my_func_
a1f
>> Function.fix_name(''), Function.fix_name('jac')
unnamed
jac1
>> Function.fix_name('ok')
ok

julia> F = ca.Function;
julia> F.fix_name("my func!"), F.fix_name("1f"), F.fix_name("")
("my_func_", "a1f", "unnamed")
julia> F.fix_name("jac"), F.fix_name("ok")
("jac1", "ok")

See also
check_name

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

Definition at line 1562 of file function.cpp.

1562  {
1563  // Quick return if already valid name
1564  if (check_name(name)) return name;
1565 
1566  // If empty, name it "unnamed"
1567  if (name.empty()) return "unnamed";
1568 
1569  // Construct a sane name
1570  std::stringstream ss;
1571 
1572  // If the first character isn't a character, prepend an "a"
1573  if (!std::isalpha(name.front())) ss << "a";
1574 
1575  // Treat other characters
1576  bool previous_is_underscore = false;
1577  for (char c : name) {
1578  if (std::isalnum(c)) {
1579  // Alphanumeric characters
1580  ss << c;
1581  previous_is_underscore = false;
1582  } else if (!previous_is_underscore) {
1583  // Everything else becomes an underscore
1584  ss << '_';
1585  previous_is_underscore = true;
1586  }
1587  }
1588 
1589  // If name became a keyword, append 1
1590  for (const char* kw : {"null", "jac", "hess"}) {
1591  if (ss.str()==kw) ss << "1";
1592  }
1593 
1594  return ss.str();
1595  }
static bool check_name(const std::string &name)
Check whether a string is a valid function name.
Definition: function.cpp:1513

References check_name(), and name().

◆ fold()

Function casadi::Function::fold ( casadi_int  N,
const Dict &  opts = Dict() 
) const

as inputs

The first n_accum inputs are accumulators: in every step they take the value of the first n_accum outputs of the previous step. For a step f:(x, u)->(x_next, y) the result is F:(x0, U)->(X, Y) with U = horzcat(u0, ..., u_(N-1)), X = horzcat(x1, ..., x_N), Y = horzcat(y0, ..., y_(N-1)) and x_(k+1), y_k = f(x_k, u_k). Non-accumulated inputs and all outputs are stacked horizontally over the N steps; the accumulator inputs keep their original shape. An accumulator output may be wider than its input (e.g. 1-by-2 feeding a 1-by-1 input): only the last columns are fed back.

Compared with writing the loop in the host language the construction is much faster and the graph is a tower of nested unrolled loops of at most base iterations (option "base", default 10; -1 unrolls completely). This keeps memory use proportional to base rather than N at a small evaluation cost.

The overloads differ in how accumulators are selected: a count n_accum (default 1), or explicit index/name lists accum_in and accum_out of equal length that may pick arbitrary inputs and outputs. The unnamed overload names the result "mapaccum_" + name(). fold is mapaccum returning only the final accumulator state.

Parameters
nameName of the result
NNumber of steps, must be positive
n_accumNumber of leading inputs/outputs that are accumulated; at most min(n_in, n_out)
opts"base" plus options for the resulting MXFunction

>>> x = SX.sym("x"); u = SX.sym("u")
>>> step = Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"])
>>> F = step.mapaccum(3)
>>> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> F(1, DM([[1, 2, 3]]))
(DM([[2, 4, 7]]), DM([[1, 4, 12]]))
>>> step.mapaccum("F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> step.fold(3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
>>> step.fold(3)(1, DM([[1, 2, 3]]))
(DM(7), DM([[1, 4, 12]]))
>>> try:
...   step.mapaccum(0)
... except RuntimeError as e:
...   print("mapaccum: N must be positive" in str(e))
True

>> x = SX.sym('x'); u = SX.sym('u');
>> step = Function('step', {x, u}, {x + u, x*u}, {'x', 'u'}, {'x_next', 'y'});
>> F = step.mapaccum(3); disp(F)
mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> [X, Y] = F(1, DM([1, 2, 3])); disp(X), disp(Y)
[[2, 4, 7]]
[[1, 4, 12]]
>> step.mapaccum('F', 3, {'x'}, {'x_next'})
F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> G = step.fold(3); disp(G)
fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction
>> [X, Y] = G(1, DM([1, 2, 3])); disp(X), disp(Y)
7
[[1, 4, 12]]
>> try, step.mapaccum(0); catch e, disp(contains(e.message, 'N must be positive')); end
1

julia> x = ca.SX.sym("x"); u = ca.SX.sym("u");
julia> step = ca.Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"]);
julia> F = ca.mapaccum(step, 3);
julia> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> F(1, [1 2 3])
([[2, 4, 7]], [[1, 4, 12]])
julia> ca.mapaccum(step, "F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> ca.fold(step, 3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
julia> ca.fold(step, 3)(1, [1 2 3])
(7, [[1, 4, 12]])
julia> try
           ca.mapaccum(step, 0)
       catch e
           println(occursin("mapaccum: N must be positive", sprint(showerror, e)))
       end
true

See also
map, fold

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

Definition at line 661 of file function.cpp.

661  {
662  Function base = mapaccum(N, opts);
663  std::vector<MX> base_in = base.mx_in();
664  std::vector<MX> out = base(base_in);
665  out[0] = out[0](Slice(), range((N-1)*size2_out(0), N*size2_out(0))); // NOLINT
666  return Function("fold_"+name(), base_in, out, name_in(), name_out(), opts);
667  }
Function mapaccum(const std::string &name, casadi_int N, const Dict &opts=Dict()) const
Create a function that applies this function N times, feeding outputs back.
Definition: function.cpp:671
std::vector< casadi_int > range(casadi_int start, casadi_int stop, casadi_int step, casadi_int len)
Range function.

References Function(), mapaccum(), mx_in(), name(), name_in(), name_out(), casadi::range(), and size2_out().

◆ forward()

Function casadi::Function::forward ( casadi_int  nfwd) const

The result is named fwd<nfwd>_<name> and has n_in + n_out + n_in inputs: the original inputs, the original outputs (out_<name>, read only when uses_output() is true) and the forward seeds fwd_<input>, each with nfwd times the columns of the input. Its n_out outputs fwd_<output> are the forward sensitivities, nfwd stacked horizontally. Uses the class' own forward mode when available ("enable_forward"), finite differences when "enable_fd" is set, or otherwise the full Jacobian; raises "Derivatives cannot be calculated" when none applies. Results are cached while alive. nfwd must be positive.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> F = f.forward(1)
>>> print(F)
fwd1_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],fwd_x,fwd_y[2])->(...) SXFunction
>>> F(1, [2, 3], 0, 0, 1, [0, 0])
(DM([2, 3]), DM(0.540302))
>>> print(f.forward(2))
fwd2_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],fwd_x[1x2],fwd_y[2x2])->(...) SXFunction

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> F = f.forward(1); disp(F)
fwd1_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],fwd_x,fwd_y[2])->(...) SXFunction
>> [fwd_r, fwd_s] = F(1, [2; 3], 0, 0, 1, [0; 0]); disp(fwd_r), disp(fwd_s)
[2, 3]
0.540302
>> f.forward(2)
fwd2_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],fwd_x[1x2],fwd_y[2x2])->(...) SXFunction

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> F = ca.forward(f, 1);
julia> F
Function(fwd1_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],fwd_x,fwd_y[2])->(fwd_r[2],fwd_s) SXFunction)
julia> F(1, [2, 3], 0, 0, 1, [0, 0])
([2, 3], 0.540302)
julia> F2 = ca.forward(f, 2);
julia> ca.name(F2), ca.size_in(F2, 4), ca.size_in(F2, 5)
("fwd2_f", (1, 2), (2, 2))

See also
reverse, jacobian, factory

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

Definition at line 1324 of file function.cpp.

1324  {
1325  try {
1326  return (*this)->forward(nfwd);
1327  } catch(std::exception& e) {
1328  THROW_ERROR("forward", e.what());
1329  }
1330  }

References casadi::FunctionInternal::forward().

Referenced by casadi::SXFunction::ad_forward(), casadi::DaeBuilderInternal::export_fmu(), casadi::FunctionInternal::forward(), casadi::Conic::get_forward(), casadi::Map::get_forward(), casadi::MapSum::get_forward(), casadi::Nlpsol::get_forward(), casadi::Switch::get_forward(), and casadi::ImplicitFixedStepIntegrator::init().

◆ free_mx()

std::vector< MX > casadi::Function::free_mx ( ) const

>>> x = MX.sym("x"); p = MX.sym("p")
>>> f = Function("f", [x], [x*p], {"allow_free": True})
>>> f.free_mx()
[MX(p)]

>> x = MX.sym('x'); p = MX.sym('p');
>> f = Function('f', {x}, {x*p}, struct('allow_free', true));
>> fr = f.free_mx(); disp(fr{1})
p

julia> x = ca.MX.sym("x"); p = ca.MX.sym("p");
julia> f = ca.Function("f", [x], [x*p], Dict("allow_free" => true));
julia> ca.free_mx(f)
1-element Vector{MX}:
 MX(p)

See also
has_free, free_sx

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

Definition at line 1878 of file function.cpp.

1878  {
1879  try {
1880  return (*this)->free_mx();
1881  } catch(std::exception& e) {
1882  THROW_ERROR("free_mx", e.what());
1883  }
1884  }

Referenced by casadi::MX::get_free(), and casadi::MX::symvar().

◆ free_sx()

std::vector< SX > casadi::Function::free_sx ( ) const
See also
has_free, free_mx

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

Definition at line 1870 of file function.cpp.

1870  {
1871  try {
1872  return (*this)->free_sx();
1873  } catch(std::exception& e) {
1874  THROW_ERROR("free_sx", e.what());
1875  }
1876  }

Referenced by casadi::Matrix< Scalar >::get_free().

◆ generate() [1/2]

std::string casadi::Function::generate ( const Dict &  opts = Dict()) const

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

Definition at line 1386 of file function.cpp.

1386  {
1387  return generate(name(), opts);
1388  }
std::string generate(const std::string &fname, const Dict &opts=Dict()) const
Generate self-contained C code for the function.
Definition: function.cpp:1390

References generate(), and name().

◆ generate() [2/2]

std::string casadi::Function::generate ( const std::string &  fname,
const Dict &  opts = Dict() 
) const

Writes fname (a ".c" suffix is added when missing; the base name must satisfy check_name) in the current directory and returns the file name. The generated file exports, for a function named f, the evaluation routine int f(const casadi_real** arg, casadi_real** res, casadi_int* iw, casadi_real* w, int mem) plus f_n_in, f_n_out, f_name_in, f_name_out, f_sparsity_in, f_sparsity_out, f_work, f_checkout, f_release, f_incref, f_decref and f_default_in. The arrays hold the nonzeros of each input and output in column-major order; work vector sizes come from f_work. Functions embedded in the graph (solvers, maps, ...) are generated too when they support code generation; otherwise an error is raised. The same file can hold several functions via the CodeGenerator class.

Parameters
fnameFile name, e.g. "f.c" or "f"
optsCode generator options: "with_header" (also write a .h file), "main" (add a main() reading inputs from a file written by generate_in), "casadi_real" (scalar type, default "double"), "casadi_int" (integer type), "with_mem" (simplified memory API), "mex", "cpp", "indent", "prefix", "verbose", "with_export", "with_import", "include_math", "infinity", "nan", "real_min", "unroll_args", "codegen_scalars", "avoid_stack", "thread_safe", "force_canonical"

>>> import os
>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> fname = f.generate("f.c")
>>> fname, os.path.isfile("f.c")
('f.c', True)
>>> src = open("f.c").read()
>>> print("int f(const casadi_real** arg, casadi_real** res" in src, "f_n_in" in src)
True True
>>> os.remove("f.c")
>>> f.generate("g", {"with_header": True}), sorted(os.listdir(".")).count("g.h")
('g.c', 1)
>>> os.remove("g.c"); os.remove("g.h")

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> fname = f.generate('f.c'); disp(fname), disp(isfile('f.c'))
f.c
1
>> src = fileread('f.c');
>> disp(contains(src, 'int f(const casadi_real** arg, casadi_real** res'))
1
>> contains(src, 'f_n_in')
1
>> delete('f.c');
>> f.generate('g', struct('with_header', true)), isfile('g.h')
g.c
1
>> delete('g.c'); delete('g.h');

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> fname = ca.generate(f, "f.c")
"f.c"
julia> isfile("f.c")
true
julia> src = read("f.c", String);
julia> occursin("int f(const casadi_real** arg, casadi_real** res", src)
true
julia> occursin("f_n_in", src)
true
julia> rm("f.c")
julia> ca.generate(f, "g", Dict("with_header" => true)), isfile("g.h")
("g.c", true)
julia> rm("g.c"); rm("g.h")

See also
CodeGenerator, generate_in, generate_out, jit, external

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

Examples
SX/generateCode.py.

Definition at line 1390 of file function.cpp.

1390  {
1391  CodeGenerator gen(fname, opts);
1392  gen.add(*this);
1393  return gen.generate();
1394  }

References casadi::CodeGenerator::add(), and casadi::CodeGenerator::generate().

Referenced by generate().

◆ generate_dependencies()

std::string casadi::Function::generate_dependencies ( const std::string &  fname,
const Dict &  opts = Dict() 
) const

Only defined for solver classes built on an oracle (nlpsol, rootfinder, integrator, ...): writes code for the helper functions (e.g. nlp_f, nlp_jac_g) into fname and returns the file name. Other classes raise an error. The library compiled from this file can be loaded with external and passed back to the solver constructor in place of the symbolic problem.

Parameters
fnameFile name
optsCode generator options, as for generate
See also
generate, external

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

Definition at line 1396 of file function.cpp.

1396  {
1397  return (*this)->generate_dependencies(fname, opts);
1398  }

◆ generate_in() [1/2]

std::vector< DM > casadi::Function::generate_in ( const std::string &  fname)

With arguments, writes the nonzeros of arg (one value per line, in input order) to fname; this is the input format read by code generated with option "main". Without arguments, reads such a file back into a list of DM with the input sparsities. The arguments follow the shape rules of call (scalars are broadcast); a file with the wrong number of values raises a dimension error.

>>> import os
>>> f = Function("f", [SX.sym("x"), SX.sym("y", 2)], [SX(0)])
>>> f.generate_in("f_in.txt", [1, [2, 3]])
>>> open("f_in.txt").read().split()
['1.0000000000000000e+00', '2.0000000000000000e+00', '3.0000000000000000e+00']
>>> f.generate_in("f_in.txt")
[DM(1), DM([2, 3])]
>>> os.remove("f_in.txt")

>> f = Function('f', {SX.sym('x'), SX.sym('y', 2)}, {SX(0)});
>> f.generate_in('f_in.txt', {1, [2; 3]});
>> fileread('f_in.txt')
1.0000000000000000e+00
2.0000000000000000e+00
3.0000000000000000e+00
>> arg = f.generate_in('f_in.txt'); disp(arg{1}), disp(arg{2})
1
[2, 3]
>> delete('f_in.txt');

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y", 2)], [ca.SX(0)]);
julia> ca.generate_in(f, "f_in.txt", [1, [2, 3]])
julia> split(read("f_in.txt", String))
3-element Vector{SubString{String}}:
 "1.0000000000000000e+00"
 "2.0000000000000000e+00"
 "3.0000000000000000e+00"
julia> ca.generate_in(f, "f_in.txt")
2-element Vector{DM}:
 DM(1)
 DM([2, 3])
julia> rm("f_in.txt")

See also
generate_out, nz_from_in, nz_to_in, generate

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

Definition at line 1430 of file function.cpp.

1430  {
1431  DM data = DM::from_file(fname, "txt");
1432  // Empty files are okay
1433  if (data.is_empty(true)) data = DM(0, 1);
1434  casadi_assert(data.is_vector() && data.is_dense(), "Expected dense vector");
1435  casadi_assert(data.numel()==nnz_in(),
1436  "Dimension mismatch: file contains a vector of size " + str(data.numel())
1437  + ", while size " + str(nnz_in()) + " was expected.");
1438 
1439  return nz_to_in(data.nonzeros());
1440  }
std::vector< DM > nz_to_in(const std::vector< double > &arg) const
Convert between a list of input/output matrices and one flat list of.
Definition: function.cpp:1805
static Matrix< double > from_file(const std::string &filename, const std::string &format_hint="")
Read a numerical matrix from a text file written by to_file (DM only)

References casadi::Matrix< double >::from_file(), casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_empty(), casadi::GenericMatrix< MatType >::is_vector(), nnz_in(), casadi::Matrix< Scalar >::nonzeros(), casadi::GenericMatrix< MatType >::numel(), nz_to_in(), and casadi::str().

◆ generate_in() [2/2]

void casadi::Function::generate_in ( const std::string &  fname,
const std::vector< DM > &  arg 
)

With arguments, writes the nonzeros of arg (one value per line, in input order) to fname; this is the input format read by code generated with option "main". Without arguments, reads such a file back into a list of DM with the input sparsities. The arguments follow the shape rules of call (scalars are broadcast); a file with the wrong number of values raises a dimension error.

>>> import os
>>> f = Function("f", [SX.sym("x"), SX.sym("y", 2)], [SX(0)])
>>> f.generate_in("f_in.txt", [1, [2, 3]])
>>> open("f_in.txt").read().split()
['1.0000000000000000e+00', '2.0000000000000000e+00', '3.0000000000000000e+00']
>>> f.generate_in("f_in.txt")
[DM(1), DM([2, 3])]
>>> os.remove("f_in.txt")

>> f = Function('f', {SX.sym('x'), SX.sym('y', 2)}, {SX(0)});
>> f.generate_in('f_in.txt', {1, [2; 3]});
>> fileread('f_in.txt')
1.0000000000000000e+00
2.0000000000000000e+00
3.0000000000000000e+00
>> arg = f.generate_in('f_in.txt'); disp(arg{1}), disp(arg{2})
1
[2, 3]
>> delete('f_in.txt');

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y", 2)], [ca.SX(0)]);
julia> ca.generate_in(f, "f_in.txt", [1, [2, 3]])
julia> split(read("f_in.txt", String))
3-element Vector{SubString{String}}:
 "1.0000000000000000e+00"
 "2.0000000000000000e+00"
 "3.0000000000000000e+00"
julia> ca.generate_in(f, "f_in.txt")
2-element Vector{DM}:
 DM(1)
 DM([2, 3])
julia> rm("f_in.txt")

See also
generate_out, nz_from_in, nz_to_in, generate

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

Definition at line 1400 of file function.cpp.

1400  {
1401  std::vector<double> d = nz_from_in(arg);
1402 
1403  // Set up output stream
1404  auto of_ptr = Filesystem::ofstream_ptr(fname);
1405  std::ostream& of = *of_ptr;
1406  normalized_setup(of);
1407 
1408  // Encode each output
1409  for (casadi_int i=0; i<d.size(); ++i) {
1410  normalized_out(of, d[i]);
1411  of << std::endl;
1412  }
1413  }
std::vector< double > nz_from_in(const std::vector< DM > &arg) const
Convert between a list of input/output matrices and one flat list of.
Definition: function.cpp:1797
void normalized_setup(std::istream &stream)
void normalized_out(std::ostream &stream, double val)

References casadi::normalized_out(), casadi::normalized_setup(), nz_from_in(), and casadi::Filesystem::ofstream_ptr().

◆ generate_lifted()

void casadi::Function::generate_lifted ( Function &  vdef_fcn,
Function &  vinit_fcn 
) const

Returns two functions: one defining the lifted variables and one for their initialization. Raises for other classes.

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

Definition at line 1898 of file function.cpp.

1898  {
1899  try {
1900  (*this)->generate_lifted(vdef_fcn, vinit_fcn);
1901  } catch(std::exception& e) {
1902  THROW_ERROR("generate_lifted", e.what());
1903  }
1904  }

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

◆ generate_out() [1/2]

std::vector< DM > casadi::Function::generate_out ( const std::string &  fname)

Same format as generate_in, for the outputs: the file written by generated code with option "main" can be read back and compared with the result of call.

>>> import os
>>> x = SX.sym("x")
>>> f = Function("f", [x], [x, 2*x])
>>> f.generate_out("f_out.txt", f.call([1.5]))
>>> f.generate_out("f_out.txt")
[DM(1.5), DM(3)]
>>> os.remove("f_out.txt")

>> x = SX.sym('x');
>> f = Function('f', {x}, {x, 2*x});
>> f.generate_out('f_out.txt', f.call({1.5}));
>> res = f.generate_out('f_out.txt'); disp(res{1}), disp(res{2})
1.5
3
>> delete('f_out.txt');

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [x, 2x]);
julia> ca.generate_out(f, "f_out.txt", ca.call(f, [1.5]))
julia> ca.generate_out(f, "f_out.txt")
2-element Vector{DM}:
 DM(1.5)
 DM(3)
julia> rm("f_out.txt")

See also
generate_in, nz_from_out, nz_to_out

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

Definition at line 1442 of file function.cpp.

1442  {
1443  DM data = DM::from_file(fname, "txt");
1444  // Empty files are okay
1445  if (data.is_empty(true)) data = DM(0, 1);
1446  casadi_assert(data.is_vector() && data.is_dense(), "Expected dense vector");
1447  casadi_assert(data.numel()==nnz_out(),
1448  "Dimension mismatch: file contains a vector of size " + str(data.numel())
1449  + ", while size " + str(nnz_out()) + " was expected.");
1450 
1451  return nz_to_out(data.nonzeros());
1452  }
std::vector< DM > nz_to_out(const std::vector< double > &arg) const
Convert between a list of input/output matrices and one flat list of.
Definition: function.cpp:1809

References casadi::Matrix< double >::from_file(), casadi::GenericMatrix< MatType >::is_dense(), casadi::GenericMatrix< MatType >::is_empty(), casadi::GenericMatrix< MatType >::is_vector(), nnz_out(), casadi::Matrix< Scalar >::nonzeros(), casadi::GenericMatrix< MatType >::numel(), nz_to_out(), and casadi::str().

◆ generate_out() [2/2]

void casadi::Function::generate_out ( const std::string &  fname,
const std::vector< DM > &  arg 
)

Same format as generate_in, for the outputs: the file written by generated code with option "main" can be read back and compared with the result of call.

>>> import os
>>> x = SX.sym("x")
>>> f = Function("f", [x], [x, 2*x])
>>> f.generate_out("f_out.txt", f.call([1.5]))
>>> f.generate_out("f_out.txt")
[DM(1.5), DM(3)]
>>> os.remove("f_out.txt")

>> x = SX.sym('x');
>> f = Function('f', {x}, {x, 2*x});
>> f.generate_out('f_out.txt', f.call({1.5}));
>> res = f.generate_out('f_out.txt'); disp(res{1}), disp(res{2})
1.5
3
>> delete('f_out.txt');

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [x, 2x]);
julia> ca.generate_out(f, "f_out.txt", ca.call(f, [1.5]))
julia> ca.generate_out(f, "f_out.txt")
2-element Vector{DM}:
 DM(1.5)
 DM(3)
julia> rm("f_out.txt")

See also
generate_in, nz_from_out, nz_to_out

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

Definition at line 1415 of file function.cpp.

1415  {
1416  std::vector<double> d = nz_from_out(res);
1417 
1418  // Set up output stream
1419  auto of_ptr = Filesystem::ofstream_ptr(fname);
1420  std::ostream& of = *of_ptr;
1421  normalized_setup(of);
1422 
1423  // Encode each output
1424  for (casadi_int i=0; i<d.size(); ++i) {
1425  normalized_out(of, d[i]);
1426  of << std::endl;
1427  }
1428  }
std::vector< double > nz_from_out(const std::vector< DM > &arg) const
Convert between a list of input/output matrices and one flat list of.
Definition: function.cpp:1801

References casadi::normalized_out(), casadi::normalized_setup(), nz_from_out(), and casadi::Filesystem::ofstream_ptr().

◆ get() [1/2]

FunctionInternal * casadi::Function::get ( ) const

Get a const pointer to the node

Definition at line 505 of file function.cpp.

505  {
506  return static_cast<FunctionInternal*>(SharedObject::get());
507  }
SharedObjectInternal * get() const
Get a const pointer to the node.

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

Referenced by casadi::FunctionInternal::add_embedded(), casadi::XFunction< DerivedType, MatType, NodeType >::call_forward(), casadi::XFunction< DerivedType, MatType, NodeType >::call_reverse(), casadi::LinearInterpolantJac::codegen_body(), casadi::conic_debug(), casadi::MX::cse(), casadi::CodeGenerator::define_local_mutex(), casadi::LinearInterpolantJac::eval(), casadi::MX::extract(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::XFunction< DerivedType, MatType, NodeType >::get_jacobian(), casadi::LinearInterpolantJac::has_parametric_grid(), casadi::LinearInterpolantJac::has_parametric_values(), casadi::RuntimeIntegrator::init(), casadi::SundialsInterface::init(), casadi::LinearInterpolantJac::init(), casadi::MX::jacobian(), casadi::CodeGenerator::local_mutex(), casadi::CodeGenerator::local_mutexes(), operator->(), operator==(), casadi::RuntimeIntegrator::root(), casadi::LinearInterpolantJac::serialize_type(), casadi::MX::simplify_const_folding(), casadi::simplify_const_folding_order(), casadi::MX::simplify_ref_count(), casadi::OptiNode::solve_prepare(), casadi::MX::substitute_inplace(), and casadi::CodeGenerator::wrapper().

◆ get() [2/2]

template<typename T >
T* casadi::Function::get ( ) const
inline

Definition at line 3796 of file function.hpp.

3796  {
3797  T* ret = dynamic_cast<T*>(get());
3798  casadi_assert_dev(ret!=nullptr);
3799  return ret;
3800  }
FunctionInternal * get() const
Definition: function.cpp:505

References casadi::T.

◆ get_free()

std::vector< std::string > casadi::Function::get_free ( ) const

◆ get_function() [1/2]

std::vector< std::string > casadi::Function::get_function ( ) const

For an SXFunction or MXFunction: the functions called in its graph (an MXFunction called with MX arguments is inlined and does not appear; SX functions, solvers and calls made with never_inline do); for a map: the mapped function; for a solver: its helper functions (e.g. nlp_f, nlp_jac_g for nlpsol, which can also be code-generated with generate_dependencies). Empty for leaf classes. Note that has_function only answers true for solver objects; for SX and MX functions it is false even for names in this list.

>>> x = MX.sym("x")
>>> f = Function("f", [x], [sin(x)]).expand()
>>> g = Function("g", [x], [f(x) + 1])
>>> g.get_function(), g.has_function("f")
(['f'], True)
>>> g.get_function("f")
Function(f:(i0)->(o0) SXFunction)
>>> try:
...   g.get_function("h")
... except RuntimeError as e:
...   print("No such function 'h'" in str(e))
True

>> x = MX.sym('x');
>> f = Function('f', {x}, {sin(x)}).expand();
>> g = Function('g', {x}, {f(x) + 1});
>> g.get_function(), g.has_function('f')
f
1
>> g.get_function('f')
f:(i0)->(o0) SXFunction
>> try, g.get_function('h'); catch e, disp(contains(e.message, 'No such function')); end
1

julia> x = ca.MX.sym("x");
julia> f = ca.expand(ca.Function("f", [x], [sin(x)]));
julia> g = ca.Function("g", [x], [f(x) + 1]);
julia> ca.get_function(g), ca.has_function(g, "f")
(["f"], true)
julia> ca.get_function(g, "f")
Function(f:(i0)->(o0) SXFunction)
julia> try
           ca.get_function(g, "h")
       catch e
           println(occursin("No such function 'h'", sprint(showerror, e)))
       end
true

See also
has_function, find_functions, oracle

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

Definition at line 2041 of file function.cpp.

2041  {
2042  try {
2043  return (*this)->get_function();
2044  } catch(std::exception& e) {
2045  THROW_ERROR("get_function", e.what());
2046  return {};
2047  }
2048  }

Referenced by casadi::IdasInterface::psetupF().

◆ get_function() [2/2]

Function casadi::Function::get_function ( const std::string &  name) const
See also
has_function, find_function

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

Definition at line 2050 of file function.cpp.

2050  {
2051  try {
2052  return (*this)->get_function(name);
2053  } catch(std::exception& e) {
2054  THROW_ERROR("get_function", e.what());
2055  }
2056  }

References name().

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

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

◆ has_free()

bool casadi::Function::has_free ( ) const

Only possible for SXFunction and MXFunction constructed with "allow_free". Such a function can be called symbolically but not numerically, expanded, code-generated or differentiated into a numerically usable form.

>>> x = SX.sym("x"); p = SX.sym("p")
>>> f = Function("f", [x], [x*p], {"allow_free": True})
>>> f.has_free(), f.get_free(), f.free_sx()
(True, ['p'], [SX(p)])
>>> try:
...   f(1)
... except RuntimeError as e:
...   print("since variables [p] are free" in str(e))
True
>>> f(SX.sym("q"))
SX((q*p))
>>> Function("g", [x], [x]).has_free()
False

>> x = SX.sym('x'); p = SX.sym('p');
>> f = Function('f', {x}, {x*p}, struct('allow_free', true));
>> disp(f.has_free()), disp(f.get_free()), fr = f.free_sx(); disp(fr{1})
1
p
p
>> try, f(1); catch e, disp(contains(e.message, 'variables [p] are free')); end
1
>> f(SX.sym('q'))
(q*p)
>> Function('g', {x}, {x}).has_free()
0

julia> x = ca.SX.sym("x"); p = ca.SX.sym("p");
julia> f = ca.Function("f", [x], [x*p], Dict("allow_free" => true));
julia> ca.has_free(f), ca.get_free(f), ca.free_sx(f)
(true, ["p"], SX[p])
julia> try
           f(1)
       catch e
           println(occursin("since variables [p] are free", sprint(showerror, e)))
       end
true
julia> f(ca.SX.sym("q"))
SX((q*p))
julia> ca.has_free(ca.Function("g", [x], [x]))
false

See also
get_free, free_sx, free_mx

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

Definition at line 1894 of file function.cpp.

1894  {
1895  return (*this)->has_free();
1896  }

Referenced by casadi::construct_nlpsol(), casadi::OracleFunction::create_function(), casadi::detect_simple_bounds_gen(), expand(), casadi::XFunction< DerivedType, MatType, NodeType >::factory(), casadi::integrator(), casadi::nlpsol(), casadi::rootfinder(), and casadi::DaeBuilderInternal::tearing_variables().

◆ has_function()

bool casadi::Function::has_function ( const std::string &  fname) const

True if fname is among the names returned by get_function().

See also
get_function

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

Definition at line 2058 of file function.cpp.

2058  {
2059  try {
2060  return (*this)->has_function(fname);
2061  } catch(std::exception& e) {
2062  THROW_ERROR("has_function", e.what());
2063  return false;
2064  }
2065  }

◆ has_in()

bool casadi::Function::has_in ( const std::string &  name) const

>>> f = Function("f", [SX.sym("x")], [SX(0)], ["x"], ["r"])
>>> f.has_in("x"), f.has_in("r"), f.has_out("r"), f.has_out("x")
(True, False, True, False)

>> f = Function('f', {SX.sym('x')}, {SX(0)}, {'x'}, {'r'});
>> fprintf('%d %d %d %d\n', f.has_in('x'), f.has_in('r'), f.has_out('r'), f.has_out('x'))
1 0 1 0

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)], ["x"], ["r"]);
julia> ca.has_in(f, "x"), ca.has_in(f, "r"), ca.has_out(f, "r"), ca.has_out(f, "x")
(true, false, true, false)

See also
has_out, index_in

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

Definition at line 1137 of file function.cpp.

1137  {
1138  for (const std::string& s : (*this)->name_in_) {
1139  if (s==name) return true;
1140  }
1141  return false;
1142  }

References name().

◆ has_option()

bool casadi::Function::has_option ( const std::string &  option_name) const

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.has_option("live_variables"), f.has_option("ipopt")
(True, False)

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> fprintf('%d %d\n', f.has_option('live_variables'), f.has_option('ipopt'))
1 0

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.has_option(f, "live_variables"), ca.has_option(f, "ipopt")
(true, false)

See also
print_options, change_option

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

Definition at line 1352 of file function.cpp.

1352  {
1353  try {
1354  return (*this)->has_option(option_name);
1355  } catch(std::exception& e) {
1356  THROW_ERROR("has_option", e.what());
1357  return false; // never reached
1358  }
1359  }

Referenced by change_option().

◆ has_out()

bool casadi::Function::has_out ( const std::string &  name) const
See also
has_in, index_out

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

Definition at line 1144 of file function.cpp.

1144  {
1145  for (const std::string& s : (*this)->name_out_) {
1146  if (s==name) return true;
1147  }
1148  return false;
1149  }

References name().

◆ has_spfwd()

bool casadi::Function::has_spfwd ( ) const

sparsity propagation

Both are true for SXFunction and MXFunction; classes without it fall back to dense Jacobian sparsity patterns.

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.has_spfwd(), f.has_sprev()
(True, True)

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> fprintf('%d %d\n', f.has_spfwd(), f.has_sprev())
1 1

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.has_spfwd(f), ca.has_sprev(f)
(true, true)

See also
jac_sparsity

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

Definition at line 1886 of file function.cpp.

1886  {
1887  return (*this)->has_spfwd();
1888  }

◆ has_sprev()

bool casadi::Function::has_sprev ( ) const

sparsity propagation

Both are true for SXFunction and MXFunction; classes without it fall back to dense Jacobian sparsity patterns.

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.has_spfwd(), f.has_sprev()
(True, True)

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> fprintf('%d %d\n', f.has_spfwd(), f.has_sprev())
1 1

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.has_spfwd(f), ca.has_sprev(f)
(true, true)

See also
jac_sparsity

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

Definition at line 1890 of file function.cpp.

1890  {
1891  return (*this)->has_sprev();
1892  }

◆ hessian_old()

Function casadi::Function::hessian_old ( casadi_int  iind,
casadi_int  oind 
) const

iind, followed by all outputs; use factory with "hess:out:in:in" instead

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

Definition at line 1048 of file function.cpp.

1048  {
1049  // Redirect to factory class
1050  std::vector<std::string> s_in = name_in();
1051  std::vector<std::string> s_out = name_out();
1052  s_out.insert(s_out.begin(), "grad:" + name_out(oind) + ":" + name_in(iind));
1053  s_out.insert(s_out.begin(),
1054  "hess:" + name_out(oind) + ":" + name_in(iind) + ":" + name_in(iind));
1055  return factory(name() + "_hess", s_in, s_out);
1056  }
Function factory(const std::string &name, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const AuxOut &aux=AuxOut(), const Dict &opts=Dict()) const
Build a function computing derivatives by naming inputs and outputs.
Definition: function.cpp:2009

References factory(), name(), name_in(), and name_out().

◆ if_else()

Function casadi::Function::if_else ( const std::string &  name,
const Function &  f_true,
const Function &  f_false,
const Dict &  opts = Dict() 
)
static

a condition input

The result takes the condition as first input followed by the inputs of the branches; a nonzero condition (truncated to integer) selects f_true, zero selects f_false. Only the selected branch is evaluated numerically. The signature is taken from f_false (see conditional).

>>> x = SX.sym("x")
>>> f = Function.if_else("f", Function("t", [x], [x**2]), Function("e", [x], [x]))
>>> f
Function(f:(i0,i1)->(o0) Switch)
>>> f(1, 3), f(0, 3), f(5, 3)
(DM(9), DM(3), DM(9))

>> x = SX.sym('x');
>> f_true = Function('t', {x}, {x^2}); f_false = Function('e', {x}, {x});
>> f = Function.if_else('f', f_true, f_false); disp(f)
f:(i0,i1)->(o0) Switch
>> [f(1, 3), f(0, 3), f(5, 3)]
[[9, 3, 9]]

julia> x = ca.SX.sym("x");
julia> f_true = ca.Function("t", [x], [x^2]); f_false = ca.Function("e", [x], [x]);
julia> f = ca.Function.if_else("f", f_true, f_false);
julia> f
Function(f:(i0,i1)->(o0) Switch)
julia> f(1, 3), f(0, 3), f(5, 3)
(9, 3, 9)

See also
conditional

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

Definition at line 962 of file function.cpp.

963  {
964  try {
965  return create(new Switch(name, std::vector<Function>(1, f_false), f_true), opts);
966  } catch(std::exception& e) {
967  THROW_ERROR_NOOBJ("if_else", e.what(), "Switch");
968  }
969  }

References create(), and name().

Referenced by conditional(), and casadi::MX::if_else().

◆ index_in()

casadi_int casadi::Function::index_in ( const std::string &  name) const

Raises an error listing the available names when no input is called name. Use has_in to test without raising.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0)], ["x", "y"], ["r"])
>>> f.index_in("y"), f.index_out("r")
(1, 0)
>>> try:
...   f.index_in("z")
... except RuntimeError as e:
...   print('could not find entry "z". Available names are: [x, y]' in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0)}, {'x', 'y'}, {'r'});
>> fprintf('%d %d\n', f.index_in('y'), f.index_out('r'))
1 0
>> try, f.index_in('z'); catch e, disp(contains(e.message, 'find entry "z"')); end
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y");
julia> f = ca.Function("f", [x, y], [ca.SX(0)], ["x", "y"], ["r"]);
julia> ca.index_in(f, "y"), ca.index_out(f, "r")
(1, 0)
julia> try
           ca.index_in(f, "z")
       catch e
           msg = sprint(showerror, e)
           println(occursin("could not find entry \"z\". Available names are: [x, y]", msg))
       end
true

See also
index_out, has_in, name_in

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

Definition at line 1121 of file function.cpp.

1121  {
1122  try {
1123  return (*this)->index_in(name);
1124  } catch(std::exception& e) {
1125  THROW_ERROR("index_in", e.what());
1126  }
1127  }

References name().

Referenced by buf_in(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::DaeBuilderInternal::load_fmi_description(), map(), mapaccum(), sparsity_in(), casadi::DaeBuilderInternal::transition(), and casadi::DaeBuilderInternal::update_dependencies().

◆ index_out()

casadi_int casadi::Function::index_out ( const std::string &  name) const
See also
index_in, has_out, name_out

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

Definition at line 1129 of file function.cpp.

1129  {
1130  try {
1131  return (*this)->index_out(name);
1132  } catch(std::exception& e) {
1133  THROW_ERROR("index_out", e.what());
1134  }
1135  }

References name().

Referenced by buf_out(), casadi::DaeBuilderInternal::load_fmi_description(), map(), mapaccum(), sparsity_out(), and casadi::DaeBuilderInternal::update_dependencies().

◆ info()

Dict casadi::Function::info ( ) const

Empty for most classes; e.g. a Switch (conditional, if_else) reports its branch functions.

>>> x = SX.sym("x")
>>> Function("f", [x], [x]).info()
{}

>> x = SX.sym('x');
>> isempty(fieldnames(Function('f', {x}, {x}).info()))
1

julia> x = ca.SX.sym("x");
julia> ca.info(ca.Function("f", [x], [x]))
Dict{String, Any}()

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

Definition at line 2138 of file function.cpp.

2138  {
2139  return (*this)->info();
2140  }

◆ instruction_constant()

double casadi::Function::instruction_constant ( casadi_int  k) const

Only meaningful for constant instructions; MXFunction raises.

See also
instruction_id, n_instructions

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

Definition at line 1946 of file function.cpp.

1946  {
1947  try {
1948  return (*this)->instruction_constant(k);
1949  } catch(std::exception& e) {
1950  THROW_ERROR("instruction_constant", e.what());
1951  }
1952  }

Referenced by casadi::SXFunction::export_code_body().

◆ instruction_id()

casadi_int casadi::Function::instruction_id ( casadi_int  k) const

The codes are the OP_* constants (OP_INPUT, OP_OUTPUT, OP_CONST, OP_ADD, OP_MUL, OP_SIN, ...; OP_CALL for a call node in an MXFunction).

See also
n_instructions, instruction_input, instruction_output

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

Definition at line 1930 of file function.cpp.

1930  {
1931  try {
1932  return (*this)->instruction_id(k);
1933  } catch(std::exception& e) {
1934  THROW_ERROR("instruction_id", e.what());
1935  }
1936  }

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

◆ instruction_input()

std::vector< casadi_int > casadi::Function::instruction_input ( casadi_int  k) const

For an input instruction (OP_INPUT) the pair is [input index, nonzero index]. (SXFunction and MXFunction)

See also
instruction_output, n_instructions

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

Definition at line 1938 of file function.cpp.

1938  {
1939  try {
1940  return (*this)->instruction_input(k);
1941  } catch(std::exception& e) {
1942  THROW_ERROR("instruction_input", e.what());
1943  }
1944  }

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

◆ instruction_MX()

MX casadi::Function::instruction_MX ( casadi_int  k) const

SXFunction raises; use instructions_sx instead.

>>> x = MX.sym("x")
>>> f = Function("f", [x], [2*sin(x)])
>>> [str(f.instruction_MX(k)) for k in range(f.n_instructions())]
['input[0][0]', 'sin(x)', '(2.*sin(x))', 'output[0][0]']

>> x = MX.sym('x');
>> f = Function('f', {x}, {2*sin(x)});
>> for k = 0:f.n_instructions()-1, disp(f.instruction_MX(k)); end
input[0][0]
sin(x)
(2.*sin(x))
output[0][0]

julia> x = ca.MX.sym("x");
julia> f = ca.Function("f", [x], [2sin(x)]);
julia> [string(ca.instruction_MX(f, k)) for k in 0:ca.n_instructions(f)-1]
4-element Vector{String}:
 "input[0][0]"
 "sin(x)"
 "(2.*sin(x))"
 "output[0][0]"

See also
n_instructions, instructions_sx

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

Definition at line 1914 of file function.cpp.

1914  {
1915  try {
1916  return (*this)->instruction_MX(k);
1917  } catch(std::exception& e) {
1918  THROW_ERROR("instruction_MX", e.what());
1919  }
1920  }

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

◆ instruction_output()

std::vector< casadi_int > casadi::Function::instruction_output ( casadi_int  k) const

For an output instruction (OP_OUTPUT) the pair is [output index, nonzero index]. (SXFunction and MXFunction)

See also
instruction_input, n_instructions

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

Definition at line 1954 of file function.cpp.

1954  {
1955  try {
1956  return (*this)->instruction_output(k);
1957  } catch(std::exception& e) {
1958  THROW_ERROR("instruction_output", e.what());
1959  }
1960  }

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

◆ instructions_sx()

SX casadi::Function::instructions_sx ( ) const

Entry k is the expression computed by instruction k; input and output instructions have no expression and are nan. MXFunction raises.

>>> x = SX.sym("x")
>>> f = Function("f", [x], [2*sin(x)])
>>> f.instructions_sx()
SX(@1=nan, @2=sin(x), [@1, @2, (2.*@2), @1])

>> x = SX.sym('x');
>> f = Function('f', {x}, {2*sin(x)});
>> f.instructions_sx()
@1=nan, @2=sin(x), [@1, @2, (2.*@2), @1]

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [2sin(x)]);
julia> ca.instructions_sx(f)
SX(@1=nan, @2=sin(x), [@1, @2, (2.*@2), @1])

See also
n_instructions, instruction_MX

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

Definition at line 1922 of file function.cpp.

1922  {
1923  try {
1924  return (*this)->instructions_sx();
1925  } catch(std::exception& e) {
1926  THROW_ERROR("instructions_sx", e.what());
1927  }
1928  }

◆ is_a()

bool casadi::Function::is_a ( const std::string &  type,
bool  recursive = true 
) const

type is a class name as printed after the signature: "SXFunction", "MXFunction", "Map", "Switch", "External", "Nlpsol", "Conic", "Integrator", "Rootfinder" and the plugin names (e.g. "Ipopt"). With recursive true (default) base classes match as well ("Nlpsol" for an Ipopt solver, "Map" for a ThreadMap, "FunctionInternal" for everything).

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.is_a("SXFunction"), f.is_a("MXFunction"), f.class_name()
(True, False, 'SXFunction')
>>> f.map(2, "thread").is_a("Map"), f.map(2, "thread").is_a("Map", False)
(True, False)

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> fprintf('%d %d %s\n', f.is_a('SXFunction'), f.is_a('MXFunction'), f.class_name())
1 0 SXFunction
>> F = f.map(2, 'thread'); fprintf('%d %d\n', F.is_a('Map'), F.is_a('Map', false))
1 0

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.is_a(f, "SXFunction"), ca.is_a(f, "MXFunction"), ca.class_name(f)
(true, false, "SXFunction")
julia> F = f.map(2, "thread");
julia> ca.is_a(F, "Map"), ca.is_a(F, "Map", false)
(true, false)

See also
class_name

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

Definition at line 1861 of file function.cpp.

1861  {
1862  return (*this)->is_a(type, recursive);
1863  }

Referenced by casadi::Integrator::augmented_dae(), casadi::Integrator::get_forward_dae(), casadi::MXFunction::get_stats(), map(), casadi::OracleFunction::set_function(), and transform().

◆ is_diff_in() [1/2]

std::vector< bool > casadi::Function::is_diff_in ( ) const

All true by default; set with options "is_diff_in" and "is_diff_out". A non-differentiable input or output is skipped by jacobian, forward, reverse and factory: the corresponding derivative blocks are all-zero sparse. The signature printout marks them with a '#'. Without argument, the list for all inputs or outputs is returned.

>>> x = SX.sym("x"); n = SX.sym("n")
>>> f = Function("f", [x, n], [x*n], ["x", "n"], ["r"], {"is_diff_in": [True, False]})
>>> f
Function(f:(x,#n)->(r) SXFunction)
>>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
([True, False], False, [True])
>>> f.jacobian()
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

>> x = SX.sym('x'); n = SX.sym('n');
>> opts = struct('is_diff_in', [true, false]);
>> f = Function('f', {x, n}, {x*n}, {'x', 'n'}, {'r'}, opts); disp(f)
f:(x,#n)->(r) SXFunction
>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
1 0
0
1
>> f.jacobian()
jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction

julia> x = ca.SX.sym("x"); n = ca.SX.sym("n");
julia> opts = Dict("is_diff_in" => [true, false]);
julia> f = ca.Function("f", [x, n], [x*n], ["x", "n"], ["r"], opts);
julia> f
Function(f:(x,#n)->(r) SXFunction)
julia> ca.is_diff_in(f), ca.is_diff_in(f, 1), ca.is_diff_out(f)
(Bool[1, 0], false, Bool[1])
julia> ca.jacobian(f)
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

See also
jacobian

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

Definition at line 1215 of file function.cpp.

1215  {
1216  try {
1217  return (*this)->is_diff_in_;
1218  } catch(std::exception& e) {
1219  THROW_ERROR("is_diff_in", e.what());
1220  }
1221  }

◆ is_diff_in() [2/2]

bool casadi::Function::is_diff_in ( casadi_int  ind) const

All true by default; set with options "is_diff_in" and "is_diff_out". A non-differentiable input or output is skipped by jacobian, forward, reverse and factory: the corresponding derivative blocks are all-zero sparse. The signature printout marks them with a '#'. Without argument, the list for all inputs or outputs is returned.

>>> x = SX.sym("x"); n = SX.sym("n")
>>> f = Function("f", [x, n], [x*n], ["x", "n"], ["r"], {"is_diff_in": [True, False]})
>>> f
Function(f:(x,#n)->(r) SXFunction)
>>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
([True, False], False, [True])
>>> f.jacobian()
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

>> x = SX.sym('x'); n = SX.sym('n');
>> opts = struct('is_diff_in', [true, false]);
>> f = Function('f', {x, n}, {x*n}, {'x', 'n'}, {'r'}, opts); disp(f)
f:(x,#n)->(r) SXFunction
>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
1 0
0
1
>> f.jacobian()
jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction

julia> x = ca.SX.sym("x"); n = ca.SX.sym("n");
julia> opts = Dict("is_diff_in" => [true, false]);
julia> f = ca.Function("f", [x, n], [x*n], ["x", "n"], ["r"], opts);
julia> f
Function(f:(x,#n)->(r) SXFunction)
julia> ca.is_diff_in(f), ca.is_diff_in(f, 1), ca.is_diff_out(f)
(Bool[1, 0], false, Bool[1])
julia> ca.jacobian(f)
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

See also
jacobian

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

Definition at line 1199 of file function.cpp.

1199  {
1200  try {
1201  return (*this)->is_diff_in_.at(ind);
1202  } catch(std::exception& e) {
1203  THROW_ERROR("is_diff_in", e.what());
1204  }
1205  }

Referenced by casadi::FunctionInternal::get_sparsity_out(), casadi::Map::init(), and casadi::MapSum::init().

◆ is_diff_out() [1/2]

std::vector< bool > casadi::Function::is_diff_out ( ) const

All true by default; set with options "is_diff_in" and "is_diff_out". A non-differentiable input or output is skipped by jacobian, forward, reverse and factory: the corresponding derivative blocks are all-zero sparse. The signature printout marks them with a '#'. Without argument, the list for all inputs or outputs is returned.

>>> x = SX.sym("x"); n = SX.sym("n")
>>> f = Function("f", [x, n], [x*n], ["x", "n"], ["r"], {"is_diff_in": [True, False]})
>>> f
Function(f:(x,#n)->(r) SXFunction)
>>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
([True, False], False, [True])
>>> f.jacobian()
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

>> x = SX.sym('x'); n = SX.sym('n');
>> opts = struct('is_diff_in', [true, false]);
>> f = Function('f', {x, n}, {x*n}, {'x', 'n'}, {'r'}, opts); disp(f)
f:(x,#n)->(r) SXFunction
>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
1 0
0
1
>> f.jacobian()
jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction

julia> x = ca.SX.sym("x"); n = ca.SX.sym("n");
julia> opts = Dict("is_diff_in" => [true, false]);
julia> f = ca.Function("f", [x, n], [x*n], ["x", "n"], ["r"], opts);
julia> f
Function(f:(x,#n)->(r) SXFunction)
julia> ca.is_diff_in(f), ca.is_diff_in(f, 1), ca.is_diff_out(f)
(Bool[1, 0], false, Bool[1])
julia> ca.jacobian(f)
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

See also
jacobian

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

Definition at line 1223 of file function.cpp.

1223  {
1224  try {
1225  return (*this)->is_diff_out_;
1226  } catch(std::exception& e) {
1227  THROW_ERROR("is_diff_out", e.what());
1228  }
1229  }

◆ is_diff_out() [2/2]

bool casadi::Function::is_diff_out ( casadi_int  ind) const

All true by default; set with options "is_diff_in" and "is_diff_out". A non-differentiable input or output is skipped by jacobian, forward, reverse and factory: the corresponding derivative blocks are all-zero sparse. The signature printout marks them with a '#'. Without argument, the list for all inputs or outputs is returned.

>>> x = SX.sym("x"); n = SX.sym("n")
>>> f = Function("f", [x, n], [x*n], ["x", "n"], ["r"], {"is_diff_in": [True, False]})
>>> f
Function(f:(x,#n)->(r) SXFunction)
>>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
([True, False], False, [True])
>>> f.jacobian()
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

>> x = SX.sym('x'); n = SX.sym('n');
>> opts = struct('is_diff_in', [true, false]);
>> f = Function('f', {x, n}, {x*n}, {'x', 'n'}, {'r'}, opts); disp(f)
f:(x,#n)->(r) SXFunction
>> f.is_diff_in(), f.is_diff_in(1), f.is_diff_out()
1 0
0
1
>> f.jacobian()
jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction

julia> x = ca.SX.sym("x"); n = ca.SX.sym("n");
julia> opts = Dict("is_diff_in" => [true, false]);
julia> f = ca.Function("f", [x, n], [x*n], ["x", "n"], ["r"], opts);
julia> f
Function(f:(x,#n)->(r) SXFunction)
julia> ca.is_diff_in(f), ca.is_diff_in(f, 1), ca.is_diff_out(f)
(Bool[1, 0], false, Bool[1])
julia> ca.jacobian(f)
Function(jac_f:(x,#n,out_r[1x1,0nz])->(jac_r_x,#jac_r_n[1x1,0nz]) SXFunction)

See also
jacobian

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

Definition at line 1207 of file function.cpp.

1207  {
1208  try {
1209  return (*this)->is_diff_out_.at(ind);
1210  } catch(std::exception& e) {
1211  THROW_ERROR("is_diff_out", e.what());
1212  }
1213  }

Referenced by casadi::FunctionInternal::get_sparsity_out(), casadi::Map::init(), and casadi::MapSum::init().

◆ is_null()

Definition at line 116 of file generic_shared_impl.hpp.

120  {
121  return node==nullptr;
122  }

◆ jac_sparsity() [1/2]

const std::vector< Sparsity > & casadi::Function::jac_sparsity ( bool  compact = false) const

One pattern per (output, input) pair, ordered by output first, as in jacobian. Patterns are computed by sparsity propagation the first time and cached.

Parameters
compactWhen true, the pattern is over the nonzeros of output and input (nnz_out-by-nnz_in) rather than over all elements (numel_out-by-numel_in)

>>> x = SX.sym("x"); D = SX.sym("D", Sparsity.diag(2))
>>> f = Function("f", [x, D], [x*D, sin(x)])
>>> f.jac_sparsity()
[Sparsity(4x1,2nz), Sparsity(4x4,2nz), Sparsity(1x1), Sparsity(1x4,0nz)]
>>> f.jac_sparsity(True)
[Sparsity(2x1), Sparsity(2x2,2nz), Sparsity(1x1), Sparsity(1x2,0nz)]

>> x = SX.sym('x'); D = SX.sym('D', Sparsity.diag(2));
>> f = Function('f', {x, D}, {x*D, sin(x)});
>> sp = f.jac_sparsity(); disp(numel(sp)), cellfun(@disp, sp)
4
4x1,2nz
4x4,2nz
1x1
1x4,0nz
>> cellfun(@disp, f.jac_sparsity(true))
2x1
2x2,2nz
1x1
1x2,0nz

julia> x = ca.SX.sym("x"); D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [x, D], [x*D, sin(x)]);
julia> ca.jac_sparsity(f)
4-element Vector{Sparsity}:
 Sparsity(4x1,2nz)
 Sparsity(4x4,2nz)
 Sparsity(1x1)
 Sparsity(1x4,0nz)
julia> ca.jac_sparsity(f, true)
4-element Vector{Sparsity}:
 Sparsity(2x1)
 Sparsity(2x2,2nz)
 Sparsity(1x1)
 Sparsity(1x2,0nz)

See also
jacobian, which_depends

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

Definition at line 1092 of file function.cpp.

1092  {
1093  // Make sure all are calculated
1094  for (casadi_int oind = 0; oind < n_out(); ++oind) {
1095  for (casadi_int iind = 0; iind < n_in(); ++iind) {
1096  (void)jac_sparsity(oind, iind, compact);
1097  }
1098  }
1099  // Return reference to internal cache
1100  return (*this)->jac_sparsity_[compact];
1101  }
const std::vector< Sparsity > & jac_sparsity(bool compact=false) const
Get the sparsity patterns of all Jacobian blocks.
Definition: function.cpp:1092

References n_in(), and n_out().

Referenced by casadi::_jacobian_sparsity(), casadi::CodeGenerator::add(), casadi::FunctionInternal::get_sparsity_out(), casadi::Integrator::sp_jac_dae(), casadi::Integrator::sp_jac_rdae(), and casadi::DaeBuilderInternal::update_dependencies().

◆ jac_sparsity() [2/2]

Sparsity casadi::Function::jac_sparsity ( casadi_int  oind,
casadi_int  iind,
bool  compact = false 
) const

iind

>>> x = SX.sym("x"); D = SX.sym("D", Sparsity.diag(2))
>>> f = Function("f", [x, D], [x*D, sin(x)])
>>> f.jac_sparsity(0, 1), f.jac_sparsity(0, 1, True), f.jac_sparsity(1, 1)
(Sparsity(4x4,2nz), Sparsity(2x2,2nz), Sparsity(1x4,0nz))

>> x = SX.sym('x'); D = SX.sym('D', Sparsity.diag(2));
>> f = Function('f', {x, D}, {x*D, sin(x)});
>> f.jac_sparsity(0, 1), f.jac_sparsity(0, 1, true), f.jac_sparsity(1, 1)
4x4,2nz
2x2,2nz
1x4,0nz

julia> x = ca.SX.sym("x"); D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [x, D], [x*D, sin(x)]);
julia> ca.jac_sparsity(f, 0, 1), ca.jac_sparsity(f, 0, 1, true), ca.jac_sparsity(f, 1, 1)
(4x4,2nz, 2x2,2nz, 1x4,0nz)

See also
jacobian

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

Definition at line 1103 of file function.cpp.

1103  {
1104  try {
1105  bool symm = (*this)->jac_is_symm(oind, iind);
1106  symm = symm && sparsity_out(oind).is_dense();
1107  return (*this)->jac_sparsity(oind, iind, compact, symm);
1108  } catch(std::exception& e) {
1109  THROW_ERROR("jac_sparsity", e.what());
1110  }
1111  }
bool is_dense() const
Check whether every entry is a structural nonzero, i.e. nnz() == numel()
Definition: sparsity.cpp:275

References casadi::Sparsity::is_dense(), and sparsity_out().

◆ jacobian()

Function casadi::Function::jacobian ( ) const

The result is named jac_<name> and takes all inputs followed by all outputs (named out_<output>); the output values are only read when uses_output() is true and may be passed as 0 otherwise. It returns one block per (output, input) pair, ordered by output first: for f:(x,y)->(r,s) the outputs are jac_r_x, jac_r_y, jac_s_x, jac_s_y. Blocks involving a non-differentiable input or output are all-zero sparse. Each block is a size_out(o)-times-size_in(i) matrix where the output and input are vectorized column-major; blocks that are structurally zero have an all-zero sparsity pattern.

The result is cached: calling jacobian again returns the same object as long as it is alive. The derivative itself is built by symbolic AD for SX and MX functions, by the solver's own sensitivity method for solver objects, or raises "Derivatives cannot be calculated" for classes without any derivative support. For a single block, factory("...", ..., ["jac:r:x"]) avoids computing the others.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> J = f.jacobian()
>>> print(J)
jac_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz])->(jac_r_x[2],jac_r_y[2x2,2nz],...) SXFunction
>>> J(1, [2, 3], 0, 0)
(DM([2, 3]), DM(
[[1, 00],
 [00, 1]]), DM(0.540302), DM([[00, 00]]))
>>> f.jacobian().name_out()
['jac_r_x', 'jac_r_y', 'jac_s_x', 'jac_s_y']

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> J = f.jacobian(); disp(J)
jac_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz])->(jac_r_x[2],jac_r_y[2x2,2nz],...) SXFunction
>> [jac_r_x, jac_r_y, jac_s_x, jac_s_y] = J(1, [2; 3], 0, 0);
>> jac_r_x, jac_r_y, jac_s_x, jac_s_y
[2, 3]
[[1, 00],
 [00, 1]]
0.540302
[[00, 00]]
>> J.name_out()
jac_r_x
jac_r_y
jac_s_x
jac_s_y

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> J = ca.jacobian(f);
julia> ca.name(J), ca.n_in(J), ca.n_out(J)
("jac_f", 4, 4)
julia> jac_r_x, jac_r_y, jac_s_x, jac_s_y = J(1, [2, 3], 0, 0);
julia> jac_r_x, jac_s_x, jac_s_y
([2, 3], 0.540302, [[00, 00]])
julia> jac_r_y
DM(
[[1, 00],
 [00, 1]])
julia> ca.name_out(J)
4-element Vector{String}:
 "jac_r_x"
 "jac_r_y"
 "jac_s_x"
 "jac_s_y"

See also
factory, forward, reverse, jac_sparsity, uses_output

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

Definition at line 1068 of file function.cpp.

1068  {
1069  try {
1070  return (*this)->jacobian();
1071  } catch(std::exception& e) {
1072  THROW_ERROR("jacobian", e.what());
1073  }
1074  }

References casadi::FunctionInternal::jacobian().

Referenced by casadi::DaeBuilderInternal::CallIO::calc_jac(), and casadi::FunctionInternal::jacobian().

◆ jacobian_old()

Function casadi::Function::jacobian_old ( casadi_int  iind,
casadi_int  oind 
) const

all outputs; use factory with "jac:out:in" instead

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

Definition at line 1040 of file function.cpp.

1040  {
1041  // Redirect to factory class
1042  std::vector<std::string> s_in = name_in();
1043  std::vector<std::string> s_out = name_out();
1044  s_out.insert(s_out.begin(), "jac:" + name_out(oind) + ":" + name_in(iind));
1045  return factory(name() + "_jac", s_in, s_out);
1046  }

References factory(), name(), name_in(), and name_out().

◆ jit() [1/2]

Function casadi::Function::jit ( const std::string &  name,
const std::string &  body,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts = Dict() 
)
static

body is the body of a C function that is compiled with the "compiler" plugin (option "compiler", default "shell" i.e. the system C compiler on most builds, or "clang") and loaded as an external function. This needs a working C compiler at run time; the source and library files are removed afterwards unless "jit_cleanup" is false.

Inside the body, the nonzeros of input k are available through a pointer named name_in[k] (type const casadi_real*) and the nonzeros of output k must be written through a pointer named name_out[k] (type casadi_real*), in column-major order of the sparsity pattern. casadi_real is double unless the code generator is told otherwise. By default (option "buffered": true) inputs and outputs are copied through a work vector, so the pointers are never null; with "buffered": false a null input means all-zero and a null output may be skipped. Write "return 1;" to signal an evaluation failure.

The result has no derivatives unless option "enable_fd": true (finite differences) is passed or a C body for the Jacobian is supplied with option "jac" (and "hess" for its Jacobian).

Parameters
nameFunction name
bodyC code of the function body, without the enclosing braces
name_inInput names, also the C variable names
name_outOutput names, also the C variable names
sparsity_inSparsity of each input; all scalar when omitted
sparsity_outSparsity of each output; all scalar when omitted
optsOptions; "compiler", "jit_options", "buffered", "jac", "hess" and the common Function options

Example (not run here because it invokes a compiler): f = Function.jit("f", "r[0] = x[0]*x[0] + y[0];", ["x", "y"], ["r"]) gives a function f:(x,y)->(r) that evaluates like any other Function.

See also
external

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

Definition at line 289 of file function.cpp.

292  {
293  // Pass empty vectors -> default values
294  std::vector<Sparsity> sparsity_in, sparsity_out;
295  return jit(name, body, name_in, name_out, sparsity_in, sparsity_out, opts);
296  }
const Sparsity & sparsity_in(casadi_int ind) const
Get the sparsity pattern of an input, by index or name.
Definition: function.cpp:1167
static Function jit(const std::string &name, const std::string &body, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
Create a just-in-time compiled function from a C language string.
Definition: function.cpp:289

References name(), name_in(), name_out(), sparsity_in(), and sparsity_out().

Referenced by casadi::JitFunction::get_jacobian().

◆ jit() [2/2]

Function casadi::Function::jit ( const std::string &  name,
const std::string &  body,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const std::vector< Sparsity > &  sparsity_in,
const std::vector< Sparsity > &  sparsity_out,
const Dict &  opts = Dict() 
)
static

body is the body of a C function that is compiled with the "compiler" plugin (option "compiler", default "shell" i.e. the system C compiler on most builds, or "clang") and loaded as an external function. This needs a working C compiler at run time; the source and library files are removed afterwards unless "jit_cleanup" is false.

Inside the body, the nonzeros of input k are available through a pointer named name_in[k] (type const casadi_real*) and the nonzeros of output k must be written through a pointer named name_out[k] (type casadi_real*), in column-major order of the sparsity pattern. casadi_real is double unless the code generator is told otherwise. By default (option "buffered": true) inputs and outputs are copied through a work vector, so the pointers are never null; with "buffered": false a null input means all-zero and a null output may be skipped. Write "return 1;" to signal an evaluation failure.

The result has no derivatives unless option "enable_fd": true (finite differences) is passed or a C body for the Jacobian is supplied with option "jac" (and "hess" for its Jacobian).

Parameters
nameFunction name
bodyC code of the function body, without the enclosing braces
name_inInput names, also the C variable names
name_outOutput names, also the C variable names
sparsity_inSparsity of each input; all scalar when omitted
sparsity_outSparsity of each output; all scalar when omitted
optsOptions; "compiler", "jit_options", "buffered", "jac", "hess" and the common Function options

Example (not run here because it invokes a compiler): f = Function.jit("f", "r[0] = x[0]*x[0] + y[0];", ["x", "y"], ["r"]) gives a function f:(x,y)->(r) that evaluates like any other Function.

See also
external

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

Definition at line 298 of file function.cpp.

303  {
304  try {
305  return create(new JitFunction(name, body, name_in, name_out,
306  sparsity_in, sparsity_out), opts);
307  } catch(std::exception& e) {
308  THROW_ERROR_NOOBJ("jit", e.what(), "JitFunction");
309  }
310  }

References create(), name(), name_in(), name_out(), sparsity_in(), and sparsity_out().

◆ load()

Function casadi::Function::load ( const std::string &  filename)
static

The file must contain exactly one Function (as written by save); a file written by FileSerializer with other objects raises an error pointing to FileDeserializer, a missing file raises "Could not open".

See also
save, deserialize, FileDeserializer

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

Definition at line 1546 of file function.cpp.

1546  {
1547  FileDeserializer fs(filename);
1548  auto t = fs.pop_type();
1549  if (t==SerializerBase::SerializationType::SERIALIZED_FUNCTION) {
1550  return fs.blind_unpack_function();
1551  } else {
1552  casadi_error("File is not loadable with 'load'. Use 'FileDeserializer' instead.");
1553  }
1554  }
std::string filename(const std::string &path)
Definition: ghc.cpp:55

References casadi::DeserializerBase::blind_unpack_function(), casadi::filename(), and casadi::DeserializerBase::pop_type().

Referenced by casadi::DaeBuilderInternal::load_fmi_description().

◆ map() [1/5]

Function casadi::Function::map ( casadi_int  n,
const std::string &  parallelization,
casadi_int  max_num_threads 
) const

Definition at line 830 of file function.cpp.

831  {
832  casadi_assert(max_num_threads>=1, "max_num_threads invalid.");
833  // No need for logic when we are not saturating the limit
834  if (n<=max_num_threads) return map(n, parallelization);
835 
836  // Floored division
837  casadi_int d = n/max_num_threads;
838  if (d*max_num_threads==n) {
839  // Easy when n is divisable by max_num_threads
840  return map(d, "serial").map(max_num_threads, parallelization);
841  } else {
842  // Create a base map that computes a bit too much
843  Function base = map(d+1, "serial").map(max_num_threads, parallelization);
844  std::vector<MX> ret_in, base_in;
845  casadi_int rem = (d+1)*max_num_threads-n;
846  for (casadi_int i=0;i<n_in();++i) {
847  MX arg = MX::sym("arg", repmat(sparsity_in(i), 1, n));
848  ret_in.push_back(arg);
849  MX last_arg = arg(Slice(), range((n-1)*size2_in(i), n*size2_in(i))); // NOLINT
850  base_in.push_back(horzcat(arg, repmat(last_arg, 1, rem)));
851  }
852  std::vector<MX> ret_out = base(base_in);
853  for (casadi_int i=0;i<n_out();++i) {
854  ret_out[i] = horzsplit(ret_out[i], {0, n*size2_out(i), ret_out[i].size2()})[0];
855  }
856  return Function("helper", ret_in, ret_out, name_in(), name_out());
857  }
858  }
Function map(casadi_int n, const std::string &parallelization="serial") const
Create a function that evaluates this function n times on stacked arguments.
Definition: function.cpp:861

References Function(), map(), n_in(), n_out(), name_in(), name_out(), casadi::range(), size2_in(), size2_out(), sparsity_in(), and casadi::GenericMatrix< MX >::sym().

◆ map() [2/5]

Function casadi::Function::map ( casadi_int  n,
const std::string &  parallelization = "serial" 
) const

For f:(a, p)->(s) the result is F:(A, P)->(S) with A = horzcat(a0, ..., a_(n-1)), the same for P, and S = horzcat(f(a0, p0), ..., f(a_(n-1), p_(n-1))). Every input and output is widened to n times its number of columns; when calling, a non-widened argument is repeated for all evaluations. The graph size and construction time are independent of n. For n == 1 the function itself is returned; n < 1 raises "Degenerate map operation".

Parameters
nNumber of evaluations
parallelizationHow the evaluations are run: "serial" (a Map node evaluated in a loop; cached, so repeated calls return the same object), "openmp" (OpenMP parallel loop, requires an OpenMP build), "thread" (std::thread per evaluation), "unroll" (n explicit calls in an MXFunction), "inline" (like unroll with the calls inlined). Other values raise an error.
max_num_threadsWith "thread" or "openmp": split the n evaluations into at most this many parallel chunks, each a serial map

>>> x = SX.sym("x"); p = SX.sym("p")
>>> f = Function("f", [x, p], [p*x**2], ["x", "p"], ["y"])
>>> F = f.map(3)
>>> F
Function(map3_f:(x[1x3],p[1x3])->(y[1x3]) Map)
>>> F(DM([[1, 2, 3]]), 2)
DM([[2, 8, 18]])
>>> f.map(4, "thread", 2)
Function(threadmap2_map2_f:(x[1x4],p[1x4])->(y[1x4]) ThreadMap)
>>> f.map(3, "unroll")
Function(f_3:(x[1x3],p[1x3])->(y[1x3]) MXFunction)
>>> f.map(1) is f, f.map(1).name()
(False, 'f')

>> x = SX.sym('x'); p = SX.sym('p');
>> f = Function('f', {x, p}, {p*x^2}, {'x', 'p'}, {'y'});
>> F = f.map(3); disp(F)
map3_f:(x[1x3],p[1x3])->(y[1x3]) Map
>> F(DM([1, 2, 3]), 2)
[[2, 8, 18]]
>> f.map(4, 'thread', 2)
threadmap2_map2_f:(x[1x4],p[1x4])->(y[1x4]) ThreadMap
>> f.map(3, 'unroll')
f_3:(x[1x3],p[1x3])->(y[1x3]) MXFunction
>> f.map(1).name()
f

julia> x = ca.SX.sym("x"); p = ca.SX.sym("p");
julia> f = ca.Function("f", [x, p], [p*x^2], ["x", "p"], ["y"]);
julia> F = f.map(3);
julia> F
Function(map3_f:(x[1x3],p[1x3])->(y[1x3]) Map)
julia> F([1 2 3], 2)
DM([[2, 8, 18]])
julia> f.map(4, "thread", 2)
Function(threadmap2_map2_f:(x[1x4],p[1x4])->(y[1x4]) ThreadMap)
julia> f.map(3, "unroll")
Function(f_3:(x[1x3],p[1x3])->(y[1x3]) MXFunction)
julia> f.map(1) === f, ca.name(f.map(1))
(false, "f")

See also
mapaccum, mapsum, call

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

Definition at line 861 of file function.cpp.

861  {
862  // Make sure not degenerate
863  casadi_assert(n>0, "Degenerate map operation");
864  // Quick return if possible
865  if (n==1) return *this;
866  // Unroll?
867  if (parallelization=="unroll" || parallelization=="inline") {
868  // Construct symbolic inputs
869  std::vector<MX> arg(n_in());
870  std::vector<std::vector<MX>> v(n, arg);
871  std::vector<MX> tmp(n);
872  for (casadi_int i=0; i<arg.size(); ++i) {
873  for (casadi_int k=0; k<n; ++k) {
874  tmp[k] = v[k][i] = MX::sym(name_in(i)+"_"+str(k), sparsity_in(i));
875  }
876  arg[i] = horzcat(tmp);
877  }
878  // Evaluate
879  if (parallelization=="unroll") {
880  for (auto&& w : v) w = (*this)(w);
881  } else {
882  for (auto&& w : v) call(std::vector<MX>(w), w, !is_a("SXFunction"), false);
883  }
884  // Gather outputs
885  std::vector<MX> res(n_out());
886  for (casadi_int i=0; i<res.size(); ++i) {
887  for (casadi_int k=0; k<n; ++k) tmp[k] = v[k][i];
888  res[i] = horzcat(tmp);
889  }
890  // Construct function
891  return Function(name() + "_" + str(n), arg, res, name_in(), name_out());
892  } else {
893  // Generate/retrieve potentially cached map
894  return (*this)->map(n, parallelization);
895  }
896  }
bool is_a(const std::string &type, bool recursive=true) const
Check whether the function is of a given class.
Definition: function.cpp:1861

References call(), Function(), is_a(), n_in(), n_out(), name(), name_in(), name_out(), sparsity_in(), casadi::str(), and casadi::GenericMatrix< MX >::sym().

Referenced by casadi::Dple::get_forward(), casadi::Expm::get_forward(), casadi::External::get_forward(), casadi::Map::get_forward(), casadi::Dple::get_reverse(), casadi::Expm::get_reverse(), casadi::External::get_reverse(), casadi::Map::get_reverse(), and map().

◆ map() [3/5]

Function casadi::Function::map ( casadi_int  n,
const std::vector< bool > &  reduce_in,
const std::vector< bool > &  reduce_out = std::vector<bool>(),
const Dict &  opts = Dict() 
) const

Inputs listed in reduce_in are not widened: the same value is used in all n evaluations. Outputs listed in reduce_out are summed over the evaluations instead of stacked. The index and name overloads build an MXFunction around a plain map (parallelization as in map; opts is currently ignored). The boolean-mask overload creates a dedicated serial MapSum node wrapped in an MXFunction built with opts; masks must have length n_in and n_out (an empty reduce_out means no reduction).

>>> x = SX.sym("x"); p = SX.sym("p")
>>> f = Function("f", [x, p], [p*x, x], ["x", "p"], ["y", "z"])
>>> F = f.map("F", "serial", 3, ["p"], ["y"])
>>> F
Function(F:(x[1x3],p)->(y,z[1x3]) MXFunction)
>>> F(DM([[1, 2, 3]]), 2)
(DM(12), DM([[1, 2, 3]]))
>>> f.map(3, [False, True], [True, False])(DM([[1, 2, 3]]), 2)
(DM(12), DM([[1, 2, 3]]))

>> x = SX.sym('x'); p = SX.sym('p');
>> f = Function('f', {x, p}, {p*x, x}, {'x', 'p'}, {'y', 'z'});
>> F = f.map('F', 'serial', 3, {'p'}, {'y'}); disp(F)
F:(x[1x3],p)->(y,z[1x3]) MXFunction
>> [y, z] = F(DM([1, 2, 3]), 2); disp(y), disp(z)
12
[[1, 2, 3]]
>> G = f.map(3, [false, true], [true, false]);
>> [y, z] = G(DM([1, 2, 3]), 2); disp(y), disp(z)
12
[[1, 2, 3]]

julia> x = ca.SX.sym("x"); p = ca.SX.sym("p");
julia> f = ca.Function("f", [x, p], [p*x, x], ["x", "p"], ["y", "z"]);
julia> F = f.map("F", "serial", 3, ["p"], ["y"]);
julia> F
Function(F:(x[1x3],p)->(y,z[1x3]) MXFunction)
julia> F([1 2 3], 2)
(12, [[1, 2, 3]])
julia> f.map(3, [false, true], [true, false])([1 2 3], 2)
(12, [[1, 2, 3]])

See also
map, mapsum

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

Definition at line 789 of file function.cpp.

792  {
793  return MapSum::create("mapsum_" + str(n) + "_" + name(), "serial",
794  *this, n, reduce_in, reduce_out, opts);
795  }
static Function create(const std::string &name, const std::string &parallelization, const Function &f, casadi_int n, const std::vector< bool > &reduce_in, const std::vector< bool > &reduce_out, const Dict &opts=Dict())
Definition: mapsum.cpp:31

References casadi::MapSum::create(), name(), and casadi::str().

◆ map() [4/5]

Function casadi::Function::map ( const std::string &  name,
const std::string &  parallelization,
casadi_int  n,
const std::vector< casadi_int > &  reduce_in,
const std::vector< casadi_int > &  reduce_out,
const Dict &  opts = Dict() 
) const

Inputs listed in reduce_in are not widened: the same value is used in all n evaluations. Outputs listed in reduce_out are summed over the evaluations instead of stacked. The index and name overloads build an MXFunction around a plain map (parallelization as in map; opts is currently ignored). The boolean-mask overload creates a dedicated serial MapSum node wrapped in an MXFunction built with opts; masks must have length n_in and n_out (an empty reduce_out means no reduction).

>>> x = SX.sym("x"); p = SX.sym("p")
>>> f = Function("f", [x, p], [p*x, x], ["x", "p"], ["y", "z"])
>>> F = f.map("F", "serial", 3, ["p"], ["y"])
>>> F
Function(F:(x[1x3],p)->(y,z[1x3]) MXFunction)
>>> F(DM([[1, 2, 3]]), 2)
(DM(12), DM([[1, 2, 3]]))
>>> f.map(3, [False, True], [True, False])(DM([[1, 2, 3]]), 2)
(DM(12), DM([[1, 2, 3]]))

>> x = SX.sym('x'); p = SX.sym('p');
>> f = Function('f', {x, p}, {p*x, x}, {'x', 'p'}, {'y', 'z'});
>> F = f.map('F', 'serial', 3, {'p'}, {'y'}); disp(F)
F:(x[1x3],p)->(y,z[1x3]) MXFunction
>> [y, z] = F(DM([1, 2, 3]), 2); disp(y), disp(z)
12
[[1, 2, 3]]
>> G = f.map(3, [false, true], [true, false]);
>> [y, z] = G(DM([1, 2, 3]), 2); disp(y), disp(z)
12
[[1, 2, 3]]

julia> x = ca.SX.sym("x"); p = ca.SX.sym("p");
julia> f = ca.Function("f", [x, p], [p*x, x], ["x", "p"], ["y", "z"]);
julia> F = f.map("F", "serial", 3, ["p"], ["y"]);
julia> F
Function(F:(x[1x3],p)->(y,z[1x3]) MXFunction)
julia> F([1 2 3], 2)
(12, [[1, 2, 3]])
julia> f.map(3, [false, true], [true, false])([1 2 3], 2)
(12, [[1, 2, 3]])

See also
map, mapsum

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

Definition at line 797 of file function.cpp.

799  {
800  // Wrap in an MXFunction
801  Function f = map(n, parallelization);
802  // Start with the fully mapped inputs
803  std::vector<MX> arg = f.mx_in();
804  std::vector<MX> f_arg = arg;
805  // Replace reduced inputs
806  for (casadi_int i : reduce_in) {
807  arg[i] = mx_in(i);
808  f_arg[i] = repmat(arg[i], 1, n);
809  }
810  // Get fully mapped outputs
811  std::vector<MX> res = f(f_arg);
812  // Replace reduced outputs
813  for (casadi_int i : reduce_out) {
814  res[i] = repsum(res[i], 1, n);
815  }
816  // Construct return
817  return Function(name, arg, res, name_in(), name_out());
818  }
const std::vector< MX > mx_in() const
Create fresh symbols with the names and sparsity patterns of the inputs.
Definition: function.cpp:1789

References Function(), map(), mx_in(), name(), name_in(), and name_out().

◆ map() [5/5]

Function casadi::Function::map ( const std::string &  name,
const std::string &  parallelization,
casadi_int  n,
const std::vector< std::string > &  reduce_in,
const std::vector< std::string > &  reduce_out,
const Dict &  opts = Dict() 
) const

Inputs listed in reduce_in are not widened: the same value is used in all n evaluations. Outputs listed in reduce_out are summed over the evaluations instead of stacked. The index and name overloads build an MXFunction around a plain map (parallelization as in map; opts is currently ignored). The boolean-mask overload creates a dedicated serial MapSum node wrapped in an MXFunction built with opts; masks must have length n_in and n_out (an empty reduce_out means no reduction).

>>> x = SX.sym("x"); p = SX.sym("p")
>>> f = Function("f", [x, p], [p*x, x], ["x", "p"], ["y", "z"])
>>> F = f.map("F", "serial", 3, ["p"], ["y"])
>>> F
Function(F:(x[1x3],p)->(y,z[1x3]) MXFunction)
>>> F(DM([[1, 2, 3]]), 2)
(DM(12), DM([[1, 2, 3]]))
>>> f.map(3, [False, True], [True, False])(DM([[1, 2, 3]]), 2)
(DM(12), DM([[1, 2, 3]]))

>> x = SX.sym('x'); p = SX.sym('p');
>> f = Function('f', {x, p}, {p*x, x}, {'x', 'p'}, {'y', 'z'});
>> F = f.map('F', 'serial', 3, {'p'}, {'y'}); disp(F)
F:(x[1x3],p)->(y,z[1x3]) MXFunction
>> [y, z] = F(DM([1, 2, 3]), 2); disp(y), disp(z)
12
[[1, 2, 3]]
>> G = f.map(3, [false, true], [true, false]);
>> [y, z] = G(DM([1, 2, 3]), 2); disp(y), disp(z)
12
[[1, 2, 3]]

julia> x = ca.SX.sym("x"); p = ca.SX.sym("p");
julia> f = ca.Function("f", [x, p], [p*x, x], ["x", "p"], ["y", "z"]);
julia> F = f.map("F", "serial", 3, ["p"], ["y"]);
julia> F
Function(F:(x[1x3],p)->(y,z[1x3]) MXFunction)
julia> F([1 2 3], 2)
(12, [[1, 2, 3]])
julia> f.map(3, [false, true], [true, false])([1 2 3], 2)
(12, [[1, 2, 3]])

See also
map, mapsum

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

Definition at line 820 of file function.cpp.

822  {
823  std::vector<casadi_int> reduce_in_num, reduce_out_num;
824  for (const std::string& s : reduce_in) reduce_in_num.push_back(index_in(s));
825  for (const std::string& s : reduce_out) reduce_out_num.push_back(index_out(s));
826  return map(name, parallelization, n, reduce_in_num, reduce_out_num, opts);
827  }

References index_in(), index_out(), map(), and name().

◆ mapaccum() [1/6]

Function casadi::Function::mapaccum ( casadi_int  N,
const Dict &  opts = Dict() 
) const

as inputs

The first n_accum inputs are accumulators: in every step they take the value of the first n_accum outputs of the previous step. For a step f:(x, u)->(x_next, y) the result is F:(x0, U)->(X, Y) with U = horzcat(u0, ..., u_(N-1)), X = horzcat(x1, ..., x_N), Y = horzcat(y0, ..., y_(N-1)) and x_(k+1), y_k = f(x_k, u_k). Non-accumulated inputs and all outputs are stacked horizontally over the N steps; the accumulator inputs keep their original shape. An accumulator output may be wider than its input (e.g. 1-by-2 feeding a 1-by-1 input): only the last columns are fed back.

Compared with writing the loop in the host language the construction is much faster and the graph is a tower of nested unrolled loops of at most base iterations (option "base", default 10; -1 unrolls completely). This keeps memory use proportional to base rather than N at a small evaluation cost.

The overloads differ in how accumulators are selected: a count n_accum (default 1), or explicit index/name lists accum_in and accum_out of equal length that may pick arbitrary inputs and outputs. The unnamed overload names the result "mapaccum_" + name(). fold is mapaccum returning only the final accumulator state.

Parameters
nameName of the result
NNumber of steps, must be positive
n_accumNumber of leading inputs/outputs that are accumulated; at most min(n_in, n_out)
opts"base" plus options for the resulting MXFunction

>>> x = SX.sym("x"); u = SX.sym("u")
>>> step = Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"])
>>> F = step.mapaccum(3)
>>> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> F(1, DM([[1, 2, 3]]))
(DM([[2, 4, 7]]), DM([[1, 4, 12]]))
>>> step.mapaccum("F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> step.fold(3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
>>> step.fold(3)(1, DM([[1, 2, 3]]))
(DM(7), DM([[1, 4, 12]]))
>>> try:
...   step.mapaccum(0)
... except RuntimeError as e:
...   print("mapaccum: N must be positive" in str(e))
True

>> x = SX.sym('x'); u = SX.sym('u');
>> step = Function('step', {x, u}, {x + u, x*u}, {'x', 'u'}, {'x_next', 'y'});
>> F = step.mapaccum(3); disp(F)
mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> [X, Y] = F(1, DM([1, 2, 3])); disp(X), disp(Y)
[[2, 4, 7]]
[[1, 4, 12]]
>> step.mapaccum('F', 3, {'x'}, {'x_next'})
F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> G = step.fold(3); disp(G)
fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction
>> [X, Y] = G(1, DM([1, 2, 3])); disp(X), disp(Y)
7
[[1, 4, 12]]
>> try, step.mapaccum(0); catch e, disp(contains(e.message, 'N must be positive')); end
1

julia> x = ca.SX.sym("x"); u = ca.SX.sym("u");
julia> step = ca.Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"]);
julia> F = ca.mapaccum(step, 3);
julia> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> F(1, [1 2 3])
([[2, 4, 7]], [[1, 4, 12]])
julia> ca.mapaccum(step, "F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> ca.fold(step, 3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
julia> ca.fold(step, 3)(1, [1 2 3])
(7, [[1, 4, 12]])
julia> try
           ca.mapaccum(step, 0)
       catch e
           println(occursin("mapaccum: N must be positive", sprint(showerror, e)))
       end
true

See also
map, fold

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

Definition at line 668 of file function.cpp.

668  {
669  return mapaccum("mapaccum_"+name(), N, opts);
670  }

References mapaccum(), and name().

◆ mapaccum() [2/6]

Function casadi::Function::mapaccum ( const std::string &  name,
casadi_int  N,
casadi_int  n_accum,
const Dict &  opts = Dict() 
) const

as inputs

The first n_accum inputs are accumulators: in every step they take the value of the first n_accum outputs of the previous step. For a step f:(x, u)->(x_next, y) the result is F:(x0, U)->(X, Y) with U = horzcat(u0, ..., u_(N-1)), X = horzcat(x1, ..., x_N), Y = horzcat(y0, ..., y_(N-1)) and x_(k+1), y_k = f(x_k, u_k). Non-accumulated inputs and all outputs are stacked horizontally over the N steps; the accumulator inputs keep their original shape. An accumulator output may be wider than its input (e.g. 1-by-2 feeding a 1-by-1 input): only the last columns are fed back.

Compared with writing the loop in the host language the construction is much faster and the graph is a tower of nested unrolled loops of at most base iterations (option "base", default 10; -1 unrolls completely). This keeps memory use proportional to base rather than N at a small evaluation cost.

The overloads differ in how accumulators are selected: a count n_accum (default 1), or explicit index/name lists accum_in and accum_out of equal length that may pick arbitrary inputs and outputs. The unnamed overload names the result "mapaccum_" + name(). fold is mapaccum returning only the final accumulator state.

Parameters
nameName of the result
NNumber of steps, must be positive
n_accumNumber of leading inputs/outputs that are accumulated; at most min(n_in, n_out)
opts"base" plus options for the resulting MXFunction

>>> x = SX.sym("x"); u = SX.sym("u")
>>> step = Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"])
>>> F = step.mapaccum(3)
>>> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> F(1, DM([[1, 2, 3]]))
(DM([[2, 4, 7]]), DM([[1, 4, 12]]))
>>> step.mapaccum("F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> step.fold(3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
>>> step.fold(3)(1, DM([[1, 2, 3]]))
(DM(7), DM([[1, 4, 12]]))
>>> try:
...   step.mapaccum(0)
... except RuntimeError as e:
...   print("mapaccum: N must be positive" in str(e))
True

>> x = SX.sym('x'); u = SX.sym('u');
>> step = Function('step', {x, u}, {x + u, x*u}, {'x', 'u'}, {'x_next', 'y'});
>> F = step.mapaccum(3); disp(F)
mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> [X, Y] = F(1, DM([1, 2, 3])); disp(X), disp(Y)
[[2, 4, 7]]
[[1, 4, 12]]
>> step.mapaccum('F', 3, {'x'}, {'x_next'})
F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> G = step.fold(3); disp(G)
fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction
>> [X, Y] = G(1, DM([1, 2, 3])); disp(X), disp(Y)
7
[[1, 4, 12]]
>> try, step.mapaccum(0); catch e, disp(contains(e.message, 'N must be positive')); end
1

julia> x = ca.SX.sym("x"); u = ca.SX.sym("u");
julia> step = ca.Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"]);
julia> F = ca.mapaccum(step, 3);
julia> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> F(1, [1 2 3])
([[2, 4, 7]], [[1, 4, 12]])
julia> ca.mapaccum(step, "F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> ca.fold(step, 3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
julia> ca.fold(step, 3)(1, [1 2 3])
(7, [[1, 4, 12]])
julia> try
           ca.mapaccum(step, 0)
       catch e
           println(occursin("mapaccum: N must be positive", sprint(showerror, e)))
       end
true

See also
map, fold

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

Definition at line 674 of file function.cpp.

675  {
676  Dict options = opts;
677 
678  // Default base
679  casadi_int base = 10;
680  auto it = options.find("base");
681  if (it!=options.end()) {
682  base = it->second;
683  options.erase(it);
684  }
685 
686  casadi_assert(N>0, "mapaccum: N must be positive");
687 
688  if (base==-1)
689  return mapaccum(name, std::vector<Function>(N, *this), n_accum, options);
690  casadi_assert(base>=2, "mapaccum: base must be positive");
691 
692  // Decompose N into
693  std::vector<Function> chain;
694  Function c = *this;
695  while (N!=0) {
696  casadi_int r = N % base;
697  chain.insert(chain.end(), r, c);
698  N = (N-r)/base;
699  c = c.mapaccum(c.name()+"_acc"+str(base), std::vector<Function>(base, c), n_accum, options);
700  }
701  return mapaccum(name, chain, n_accum, options);
702  }

References mapaccum(), name(), and casadi::str().

◆ mapaccum() [3/6]

Function casadi::Function::mapaccum ( const std::string &  name,
casadi_int  N,
const Dict &  opts = Dict() 
) const

as inputs

The first n_accum inputs are accumulators: in every step they take the value of the first n_accum outputs of the previous step. For a step f:(x, u)->(x_next, y) the result is F:(x0, U)->(X, Y) with U = horzcat(u0, ..., u_(N-1)), X = horzcat(x1, ..., x_N), Y = horzcat(y0, ..., y_(N-1)) and x_(k+1), y_k = f(x_k, u_k). Non-accumulated inputs and all outputs are stacked horizontally over the N steps; the accumulator inputs keep their original shape. An accumulator output may be wider than its input (e.g. 1-by-2 feeding a 1-by-1 input): only the last columns are fed back.

Compared with writing the loop in the host language the construction is much faster and the graph is a tower of nested unrolled loops of at most base iterations (option "base", default 10; -1 unrolls completely). This keeps memory use proportional to base rather than N at a small evaluation cost.

The overloads differ in how accumulators are selected: a count n_accum (default 1), or explicit index/name lists accum_in and accum_out of equal length that may pick arbitrary inputs and outputs. The unnamed overload names the result "mapaccum_" + name(). fold is mapaccum returning only the final accumulator state.

Parameters
nameName of the result
NNumber of steps, must be positive
n_accumNumber of leading inputs/outputs that are accumulated; at most min(n_in, n_out)
opts"base" plus options for the resulting MXFunction

>>> x = SX.sym("x"); u = SX.sym("u")
>>> step = Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"])
>>> F = step.mapaccum(3)
>>> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> F(1, DM([[1, 2, 3]]))
(DM([[2, 4, 7]]), DM([[1, 4, 12]]))
>>> step.mapaccum("F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> step.fold(3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
>>> step.fold(3)(1, DM([[1, 2, 3]]))
(DM(7), DM([[1, 4, 12]]))
>>> try:
...   step.mapaccum(0)
... except RuntimeError as e:
...   print("mapaccum: N must be positive" in str(e))
True

>> x = SX.sym('x'); u = SX.sym('u');
>> step = Function('step', {x, u}, {x + u, x*u}, {'x', 'u'}, {'x_next', 'y'});
>> F = step.mapaccum(3); disp(F)
mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> [X, Y] = F(1, DM([1, 2, 3])); disp(X), disp(Y)
[[2, 4, 7]]
[[1, 4, 12]]
>> step.mapaccum('F', 3, {'x'}, {'x_next'})
F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> G = step.fold(3); disp(G)
fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction
>> [X, Y] = G(1, DM([1, 2, 3])); disp(X), disp(Y)
7
[[1, 4, 12]]
>> try, step.mapaccum(0); catch e, disp(contains(e.message, 'N must be positive')); end
1

julia> x = ca.SX.sym("x"); u = ca.SX.sym("u");
julia> step = ca.Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"]);
julia> F = ca.mapaccum(step, 3);
julia> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> F(1, [1 2 3])
([[2, 4, 7]], [[1, 4, 12]])
julia> ca.mapaccum(step, "F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> ca.fold(step, 3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
julia> ca.fold(step, 3)(1, [1 2 3])
(7, [[1, 4, 12]])
julia> try
           ca.mapaccum(step, 0)
       catch e
           println(occursin("mapaccum: N must be positive", sprint(showerror, e)))
       end
true

See also
map, fold

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

Definition at line 671 of file function.cpp.

671  {
672  return mapaccum(name, N, 1, opts);
673  }

References name().

Referenced by casadi::MX::cumsum(), fold(), and mapaccum().

◆ mapaccum() [4/6]

Function casadi::Function::mapaccum ( const std::string &  name,
casadi_int  n,
const std::vector< casadi_int > &  accum_in,
const std::vector< casadi_int > &  accum_out,
const Dict &  opts = Dict() 
) const

as inputs

The first n_accum inputs are accumulators: in every step they take the value of the first n_accum outputs of the previous step. For a step f:(x, u)->(x_next, y) the result is F:(x0, U)->(X, Y) with U = horzcat(u0, ..., u_(N-1)), X = horzcat(x1, ..., x_N), Y = horzcat(y0, ..., y_(N-1)) and x_(k+1), y_k = f(x_k, u_k). Non-accumulated inputs and all outputs are stacked horizontally over the N steps; the accumulator inputs keep their original shape. An accumulator output may be wider than its input (e.g. 1-by-2 feeding a 1-by-1 input): only the last columns are fed back.

Compared with writing the loop in the host language the construction is much faster and the graph is a tower of nested unrolled loops of at most base iterations (option "base", default 10; -1 unrolls completely). This keeps memory use proportional to base rather than N at a small evaluation cost.

The overloads differ in how accumulators are selected: a count n_accum (default 1), or explicit index/name lists accum_in and accum_out of equal length that may pick arbitrary inputs and outputs. The unnamed overload names the result "mapaccum_" + name(). fold is mapaccum returning only the final accumulator state.

Parameters
nameName of the result
NNumber of steps, must be positive
n_accumNumber of leading inputs/outputs that are accumulated; at most min(n_in, n_out)
opts"base" plus options for the resulting MXFunction

>>> x = SX.sym("x"); u = SX.sym("u")
>>> step = Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"])
>>> F = step.mapaccum(3)
>>> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> F(1, DM([[1, 2, 3]]))
(DM([[2, 4, 7]]), DM([[1, 4, 12]]))
>>> step.mapaccum("F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> step.fold(3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
>>> step.fold(3)(1, DM([[1, 2, 3]]))
(DM(7), DM([[1, 4, 12]]))
>>> try:
...   step.mapaccum(0)
... except RuntimeError as e:
...   print("mapaccum: N must be positive" in str(e))
True

>> x = SX.sym('x'); u = SX.sym('u');
>> step = Function('step', {x, u}, {x + u, x*u}, {'x', 'u'}, {'x_next', 'y'});
>> F = step.mapaccum(3); disp(F)
mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> [X, Y] = F(1, DM([1, 2, 3])); disp(X), disp(Y)
[[2, 4, 7]]
[[1, 4, 12]]
>> step.mapaccum('F', 3, {'x'}, {'x_next'})
F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> G = step.fold(3); disp(G)
fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction
>> [X, Y] = G(1, DM([1, 2, 3])); disp(X), disp(Y)
7
[[1, 4, 12]]
>> try, step.mapaccum(0); catch e, disp(contains(e.message, 'N must be positive')); end
1

julia> x = ca.SX.sym("x"); u = ca.SX.sym("u");
julia> step = ca.Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"]);
julia> F = ca.mapaccum(step, 3);
julia> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> F(1, [1 2 3])
([[2, 4, 7]], [[1, 4, 12]])
julia> ca.mapaccum(step, "F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> ca.fold(step, 3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
julia> ca.fold(step, 3)(1, [1 2 3])
(7, [[1, 4, 12]])
julia> try
           ca.mapaccum(step, 0)
       catch e
           println(occursin("mapaccum: N must be positive", sprint(showerror, e)))
       end
true

See also
map, fold

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

Definition at line 749 of file function.cpp.

752  {
753  // Shorthands
754  casadi_int n_in = this->n_in(), n_out = this->n_out();
755  // Consistency checks
756  casadi_assert_dev(in_range(accum_in, n_in) && isUnique(accum_in));
757  casadi_assert_dev(in_range(accum_out, n_out) && isUnique(accum_out));
758  casadi_assert_dev(accum_in.size()==accum_out.size());
759  casadi_int n_accum=accum_in.size();
760 
761  // Quick return if no need to reorder
762  if (accum_in==range(n_accum) && accum_out==range(n_accum)) {
763  return mapaccum(name, n, n_accum, opts);
764  }
765 
766  // Need to do some reordering
767  std::vector<casadi_int> temp_in = complement(accum_in, n_in);
768  std::vector<casadi_int> order_in = accum_in;
769  order_in.insert(order_in.end(), temp_in.begin(), temp_in.end());
770  std::vector<casadi_int> temp_out = complement(accum_out, n_out);
771  std::vector<casadi_int> order_out = accum_out;
772  order_out.insert(order_out.end(), temp_out.begin(), temp_out.end());
773  Function ret = slice("slice_" + name, order_in, order_out);
774  ret = ret.mapaccum("mapacc_" + name, n, n_accum, opts);
775  return ret.slice(name, lookupvector(order_in, n_in),
776  lookupvector(order_out, n_out), opts);
777  }
Function slice(const std::string &name, const std::vector< casadi_int > &order_in, const std::vector< casadi_int > &order_out, const Dict &opts=Dict()) const
Create a function with a subset or reordering of the inputs and outputs.
Definition: function.cpp:899
bool isUnique(const std::vector< T > &v)
std::vector< casadi_int > lookupvector(const std::vector< casadi_int > &v, casadi_int size)
Returns a vector for quickly looking up entries of supplied list.
bool in_range(const std::vector< T > &v, casadi_int upper)
Check if for each element of v holds: v_i < upper.
std::vector< casadi_int > complement(const std::vector< casadi_int > &v, casadi_int size)
Returns the list of all i in [0, size[ not found in supplied list.

References casadi::complement(), casadi::in_range(), casadi::isUnique(), casadi::lookupvector(), mapaccum(), n_in(), n_out(), name(), casadi::range(), and slice().

◆ mapaccum() [5/6]

Function casadi::Function::mapaccum ( const std::string &  name,
casadi_int  n,
const std::vector< std::string > &  accum_in,
const std::vector< std::string > &  accum_out,
const Dict &  opts = Dict() 
) const

as inputs

The first n_accum inputs are accumulators: in every step they take the value of the first n_accum outputs of the previous step. For a step f:(x, u)->(x_next, y) the result is F:(x0, U)->(X, Y) with U = horzcat(u0, ..., u_(N-1)), X = horzcat(x1, ..., x_N), Y = horzcat(y0, ..., y_(N-1)) and x_(k+1), y_k = f(x_k, u_k). Non-accumulated inputs and all outputs are stacked horizontally over the N steps; the accumulator inputs keep their original shape. An accumulator output may be wider than its input (e.g. 1-by-2 feeding a 1-by-1 input): only the last columns are fed back.

Compared with writing the loop in the host language the construction is much faster and the graph is a tower of nested unrolled loops of at most base iterations (option "base", default 10; -1 unrolls completely). This keeps memory use proportional to base rather than N at a small evaluation cost.

The overloads differ in how accumulators are selected: a count n_accum (default 1), or explicit index/name lists accum_in and accum_out of equal length that may pick arbitrary inputs and outputs. The unnamed overload names the result "mapaccum_" + name(). fold is mapaccum returning only the final accumulator state.

Parameters
nameName of the result
NNumber of steps, must be positive
n_accumNumber of leading inputs/outputs that are accumulated; at most min(n_in, n_out)
opts"base" plus options for the resulting MXFunction

>>> x = SX.sym("x"); u = SX.sym("u")
>>> step = Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"])
>>> F = step.mapaccum(3)
>>> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> F(1, DM([[1, 2, 3]]))
(DM([[2, 4, 7]]), DM([[1, 4, 12]]))
>>> step.mapaccum("F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
>>> step.fold(3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
>>> step.fold(3)(1, DM([[1, 2, 3]]))
(DM(7), DM([[1, 4, 12]]))
>>> try:
...   step.mapaccum(0)
... except RuntimeError as e:
...   print("mapaccum: N must be positive" in str(e))
True

>> x = SX.sym('x'); u = SX.sym('u');
>> step = Function('step', {x, u}, {x + u, x*u}, {'x', 'u'}, {'x_next', 'y'});
>> F = step.mapaccum(3); disp(F)
mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> [X, Y] = F(1, DM([1, 2, 3])); disp(X), disp(Y)
[[2, 4, 7]]
[[1, 4, 12]]
>> step.mapaccum('F', 3, {'x'}, {'x_next'})
F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction
>> G = step.fold(3); disp(G)
fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction
>> [X, Y] = G(1, DM([1, 2, 3])); disp(X), disp(Y)
7
[[1, 4, 12]]
>> try, step.mapaccum(0); catch e, disp(contains(e.message, 'N must be positive')); end
1

julia> x = ca.SX.sym("x"); u = ca.SX.sym("u");
julia> step = ca.Function("step", [x, u], [x + u, x*u], ["x", "u"], ["x_next", "y"]);
julia> F = ca.mapaccum(step, 3);
julia> F
Function(mapaccum_step:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> F(1, [1 2 3])
([[2, 4, 7]], [[1, 4, 12]])
julia> ca.mapaccum(step, "F", 3, ["x"], ["x_next"])
Function(F:(x,u[1x3])->(x_next[1x3],y[1x3]) MXFunction)
julia> ca.fold(step, 3)
Function(fold_step:(x,u[1x3])->(x_next,y[1x3]) MXFunction)
julia> ca.fold(step, 3)(1, [1 2 3])
(7, [[1, 4, 12]])
julia> try
           ca.mapaccum(step, 0)
       catch e
           println(occursin("mapaccum: N must be positive", sprint(showerror, e)))
       end
true

See also
map, fold

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

Definition at line 779 of file function.cpp.

782  {
783  std::vector<casadi_int> accum_in_num, accum_out_num;
784  for (const std::string& s : accum_in) accum_in_num.push_back(index_in(s));
785  for (const std::string& s : accum_out) accum_out_num.push_back(index_out(s));
786  return mapaccum(name, n, accum_in_num, accum_out_num, opts);
787  }

References index_in(), index_out(), mapaccum(), and name().

◆ mapaccum() [6/6]

Function casadi::Function::mapaccum ( const std::string &  name,
const std::vector< Function > &  chain,
casadi_int  n_accum = 1,
const Dict &  opts = Dict() 
) const
protected

Definition at line 704 of file function.cpp.

706  {
707  // Shorthands
708  casadi_int n_in = this->n_in(), n_out = this->n_out();
709  // Consistency checks
710  casadi_assert(!chain.empty(), "mapaccum: chain must be non-empty");
711  casadi_assert(n_accum<=std::min(n_in, n_out), "mapaccum: too many accumulators");
712  // Quick return?
713  if (chain.size()==1) return chain[0];
714  // Get symbolic expressions for inputs and outputs
715  std::vector<MX> arg = mx_in();
716  std::vector<MX> res;
717  // Vectorized inputs and outputs
718  std::vector<std::vector<MX>> varg(n_in), vres(n_out);
719  for (casadi_int i=0; i<n_accum; ++i) varg[i].push_back(arg[i]);
720  // For each function call
721  for (const auto& f : chain) {
722 
723  // Stacked input expressions
724  for (casadi_int i=n_accum; i<n_in; ++i) {
725  arg[i] = MX::sym(name_in(i) + "_" + str(i), f.sparsity_in(i));
726  varg[i].push_back(arg[i]);
727  }
728 
729  // Call f
730  res = f(arg);
731  // Save output expressions
732  for (casadi_int i=0; i<n_out; ++i) vres[i].push_back(res[i]);
733  // Copy function output to input
734  std::copy_n(res.begin(), n_accum, arg.begin());
735  for (casadi_int i=0; i<n_accum; ++i) {
736  // Ony get last component (allows nested calls)
737  casadi_int ncol_out=f.size2_out(i), ncol_in=size2_in(i);
738  if (ncol_out>ncol_in) {
739  arg[i] = horzsplit(arg[i], {0, ncol_out-ncol_in, ncol_out}).back();
740  }
741  }
742  }
743  // Construct return
744  for (casadi_int i=0; i<n_in; ++i) arg[i] = horzcat(varg[i]);
745  for (casadi_int i=0; i<n_out; ++i) res[i] = horzcat(vres[i]);
746  return Function(name, arg, res, name_in(), name_out(), opts);
747  }

References Function(), mx_in(), n_in(), n_out(), name(), name_in(), name_out(), size2_in(), casadi::str(), and casadi::GenericMatrix< MX >::sym().

◆ mapsum()

std::vector< MX > casadi::Function::mapsum ( const std::vector< MX > &  x,
const std::string &  parallelization = "serial" 
) const

Each argument is either the input itself or n copies stacked horizontally (N-by-(n*M) for an N-by-M input); the largest such n sets the number of evaluations and non-stacked arguments are shared across evaluations. Returns the sum over the n evaluations of each output, as MX expressions calling an internal map-and-reduce function.

Parameters
xList of n_in() MX arguments
parallelization"serial" only; other values raise an error

>>> x = SX.sym("x"); y = SX.sym("y")
>>> f = Function("f", [x, y], [x*y, x - y], ["x", "y"], ["p", "d"])
>>> p, d = f.mapsum([MX.sym("a"), MX.sym("b", 1, 3)])
>>> p
MX(mapsum(a, b){0})
>>> f.mapsum([2, DM([[1, 2, 3]])])
[MX(mapsum(2, [[1, 2, 3]]){0}), MX(mapsum(2, [[1, 2, 3]]){1})]
>>> evalf(f.mapsum([2, DM([[1, 2, 3]])])[0])
DM(12)

>> x = SX.sym('x'); y = SX.sym('y');
>> f = Function('f', {x, y}, {x*y, x - y}, {'x', 'y'}, {'p', 'd'});
>> res = f.mapsum({MX.sym('a'), MX.sym('b', 1, 3)}); disp(res{1})
mapsum(a, b){0}
>> res = f.mapsum({2, DM([1, 2, 3])}); disp(res{1}), disp(res{2})
mapsum(2, [[1, 2, 3]]){0}
mapsum(2, [[1, 2, 3]]){1}
>> evalf(res{1})
12

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y");
julia> f = ca.Function("f", [x, y], [x*y, x - y], ["x", "y"], ["p", "d"]);
julia> p, d = ca.mapsum(f, [ca.MX.sym("a"), ca.MX.sym("b", 1, 3)]);
julia> p
MX(mapsum(a, b){0})
julia> ca.mapsum(f, [2, ca.DM([1 2 3])])
2-element Vector{MX}:
 MX(mapsum(2, [[1, 2, 3]]){0})
 MX(mapsum(2, [[1, 2, 3]]){1})
julia> ca.evalf(ca.mapsum(f, [2, ca.DM([1 2 3])])[1])
DM(12)

See also
map, call

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

Definition at line 908 of file function.cpp.

909  {
910  try {
911  return (*this)->mapsum_mx(x, parallelization);
912  } catch(std::exception& e) {
913  THROW_ERROR("mapsum", e.what());
914  }
915  }

◆ max_in()

double casadi::Function::max_in ( casadi_int  ind) const

restricts it)

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.max_in(0), f.min_in(0)
(inf, -inf)

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> fprintf('%g %g\n', f.max_in(0), f.min_in(0))
Inf -Inf

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.max_in(f, 0), ca.min_in(f, 0)
(Inf, -Inf)

See also
min_in, default_in

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

Definition at line 1681 of file function.cpp.

1681  {
1682  return (*this)->get_max_in(ind);
1683  }

◆ memory()

void * casadi::Function::memory ( int  ind) const

◆ merge()

void casadi::Function::merge ( const std::vector< MX > &  arg,
std::vector< MX > &  subs_from,
std::vector< MX > &  subs_to 
) const

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

Definition at line 1865 of file function.cpp.

1866  {
1867  (*this)->merge(arg, subs_from, subs_to);
1868  }

◆ min_in()

double casadi::Function::min_in ( casadi_int  ind) const

restricts it)

See also
max_in, default_in

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

Definition at line 1685 of file function.cpp.

1685  {
1686  return (*this)->get_min_in(ind);
1687  }

◆ mx_in() [1/3]

const std::vector< MX > casadi::Function::mx_in ( ) const

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

Definition at line 1789 of file function.cpp.

1789  {
1790  return (*this)->mx_in();
1791  }

Referenced by map(), and mapaccum().

◆ mx_in() [2/3]

const MX casadi::Function::mx_in ( casadi_int  ind) const

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

Definition at line 1781 of file function.cpp.

1781  {
1782  return (*this)->mx_in(ind);
1783  }

Referenced by conditional(), casadi::DaeBuilderInternal::create(), casadi::FixedStepIntegrator::create_advanced(), casadi::GraphBuilderInternal::create_function(), fold(), casadi::Map::get_forward(), casadi::MapSum::get_forward(), casadi::Switch::get_forward(), casadi::MX::get_input(), casadi::Map::get_reverse(), casadi::MapSum::get_reverse(), casadi::Switch::get_reverse(), casadi::RuntimeIntegrator::init(), casadi::Blocksqp::init(), casadi::Scpgen::init(), casadi::DaeBuilderInternal::load_fmi_description(), map(), transform(), and casadi::DaeBuilderInternal::transition().

◆ mx_in() [3/3]

const MX casadi::Function::mx_in ( const std::string &  iname) const
inline

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

Definition at line 3939 of file function.hpp.

3939  {
3940  return mx_in(index_in(iname));
3941  }

◆ mx_out() [1/3]

const std::vector< MX > casadi::Function::mx_out ( ) const

Useful as adjoint seeds or placeholders; see sx_in.

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

Definition at line 1793 of file function.cpp.

1793  {
1794  return (*this)->mx_out();
1795  }

◆ mx_out() [2/3]

const MX casadi::Function::mx_out ( casadi_int  ind) const

Useful as adjoint seeds or placeholders; see sx_in.

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

Definition at line 1785 of file function.cpp.

1785  {
1786  return (*this)->mx_out(ind);
1787  }

◆ mx_out() [3/3]

const MX casadi::Function::mx_out ( const std::string &  oname) const
inline

Useful as adjoint seeds or placeholders; see sx_in.

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

Definition at line 3967 of file function.hpp.

3967  {
3968  return mx_out(index_out(oname));
3969  }
const std::vector< MX > mx_out() const
Create fresh symbols with the names and sparsity patterns of the outputs.
Definition: function.cpp:1793

◆ n_in()

casadi_int casadi::Function::n_in ( ) const

>>> x = SX.sym("x"); y = SX.sym("y")
>>> f = Function("f", [x, y], [x+y, x-y, x*y])
>>> f.n_in(), f.n_out()
(2, 3)
>>> Function("g", [], [DM(1)]).n_in()
0

>> x = SX.sym('x'); y = SX.sym('y');
>> f = Function('f', {x, y}, {x+y, x-y, x*y});
>> fprintf('%d %d\n', f.n_in(), f.n_out())
2 3
>> Function('g', {}, {DM(1)}).n_in()
0

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y");
julia> f = ca.Function("f", [x, y], [x + y, x - y, x*y]);
julia> ca.n_in(f), ca.n_out(f)
(2, 3)
julia> ca.n_in(ca.Function("g", [], [ca.DM(1)]))
0

See also
n_out, name_in, size_in

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

Definition at line 971 of file function.cpp.

971  {
972  return (*this)->n_in_;
973  }

Referenced by activity(), casadi::CodeGenerator::add(), buf_in(), casadi::OracleFunction::calc_function(), casadi::DaeBuilderInternal::CallIO::calc_jac(), casadi::Call::Call(), call_gen(), casadi::Nlpsol::callback(), casadi::FiniteDiff::codegen_body(), casadi::Sqpmethod::codegen_qp_ela_solve(), casadi::Feasiblesqpmethod::codegen_qp_solve(), casadi::Sqpmethod::codegen_qp_solve(), casadi::construct_nlpsol(), casadi::Call::create(), casadi::MapSum::create(), casadi::OracleFunction::create_function(), casadi::FiniteDiff::eval(), casadi::Scpgen::eval_exp(), casadi::Scpgen::eval_mat(), casadi::Scpgen::eval_res(), casadi::CallSX::eval_sx(), casadi::Scpgen::eval_vec(), casadi::SXFunction::ExtendedAlgEl::ExtendedAlgEl(), casadi::External::factory(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::FunctionInternal::forward(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::FiniteDiff::get_default_in(), casadi::FunctionInternal::get_n_in(), casadi::FiniteDiff::get_n_in(), casadi::Switch::get_n_in(), casadi::FunctionInternal::get_n_out(), casadi::FunctionInternal::get_name_in(), casadi::FiniteDiff::get_name_in(), casadi::FunctionInternal::get_name_out(), casadi::FunctionInternal::get_sparsity_in(), casadi::FiniteDiff::get_sparsity_in(), casadi::FunctionInternal::get_sparsity_out(), casadi::Onnx::import_symbolic(), casadi::Integrator::init(), casadi::Nlpsol::init(), casadi::Rootfinder::init(), casadi::BonminInterface::init(), casadi::GurobiInterface::init(), casadi::IpoptInterface::init(), casadi::FastNewton::init(), casadi::Feasiblesqpmethod::init(), casadi::Newton::init(), casadi::Sqpmethod::init(), casadi::BonminInterface::intermediate_callback(), casadi::IpoptInterface::intermediate_callback(), jac_sparsity(), casadi::FunctionInternal::jacobian(), casadi::Onnx::load(), casadi::DaeBuilderInternal::load_fmi_description(), map(), mapaccum(), casadi::MapSum::MapSum(), casadi::SymbolicQr::nfact(), casadi::SXFunction::print(), casadi::SXNode::print_compact(), casadi::qpsol_nlp(), rev(), casadi::FunctionInternal::reverse(), casadi::simpleIntegrator(), casadi::simpleIRK(), casadi::simpleRK(), casadi::WorhpInterface::solve(), casadi::Scpgen::solve(), casadi::SymbolicQr::solve(), casadi::Sqpmethod::solve_ela_QP(), casadi::Feasiblesqpmethod::solve_LP(), casadi::Feasiblesqpmethod::solve_QP(), casadi::Qrsqp::solve_QP(), casadi::Scpgen::solve_qp(), casadi::Sqpmethod::solve_QP(), and casadi::ThreadsWork().

◆ n_instructions()

casadi_int casadi::Function::n_instructions ( ) const

The algorithm is the sequence of operations evaluated for a call, including the input and output instructions; instruction_id, instruction_input, instruction_output, instruction_constant and instruction_MX inspect them by index. Other classes raise.

>>> x = SX.sym("x"); y = SX.sym("y")
>>> f = Function("f", [x, y], [x*y + 1])
>>> f.n_instructions()
6
>>> for k in range(f.n_instructions()):
...   print(f.instruction_id(k), f.instruction_input(k), f.instruction_output(k))
45 [0, 0] [0]
45 [1, 0] [1]
3 [0, 1] [0]
44 [] [1]
1 [0, 1] [0]
46 [0] [0, 0]
>>> f.instruction_id(3) == OP_CONST, f.instruction_constant(3)
(True, 1.0)

>> x = SX.sym('x'); y = SX.sym('y');
>> f = Function('f', {x, y}, {x*y + 1});
>> f.n_instructions()
6
>> arrayfun(@(k) f.instruction_id(k), 0:5)
45 45 3 44 1 46
>> f.instruction_input(2), f.instruction_output(2)
0 1
0
>> f.instruction_id(3) == OP_CONST, f.instruction_constant(3)
1
1

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y");
julia> f = ca.Function("f", [x, y], [x*y + 1]);
julia> ca.n_instructions(f)
6
julia> for k in 0:ca.n_instructions(f)-1
           println(ca.instruction_id(f, k), " ", ca.instruction_input(f, k), " ",
                   ca.instruction_output(f, k))
       end
45 [0, 0] [0]
45 [1, 0] [1]
3 [0, 1] [0]
44 Int64[] [1]
1 [0, 1] [0]
46 [0] [0, 0]
julia> ca.instruction_id(f, 3) == ca.OP_CONST, ca.instruction_constant(f, 3)
(true, 1.0)

See also
instruction_id, instructions_sx, n_nodes

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

Definition at line 1906 of file function.cpp.

1906  {
1907  try {
1908  return (*this)->n_instructions();
1909  } catch(std::exception& e) {
1910  THROW_ERROR("n_instructions", e.what());
1911  }
1912  }

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

◆ n_nodes()

casadi_int casadi::Function::n_nodes ( ) const

Counts the unique nodes of the output expressions, inputs included; a cheap measure of graph size for comparing transformations. Other classes raise.

>>> x = MX.sym("x")
>>> Function("f", [x], [sin(x) + sin(x)]).n_nodes()
4

>> x = MX.sym('x');
>> Function('f', {x}, {sin(x) + sin(x)}).n_nodes()
4

julia> x = ca.MX.sym("x");
julia> ca.n_nodes(ca.Function("f", [x], [sin(x) + sin(x)]))
4

See also
n_instructions

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

Definition at line 1962 of file function.cpp.

1962  {
1963  try {
1964  return (*this)->n_nodes();
1965  } catch(std::exception& e) {
1966  THROW_ERROR("n_nodes", e.what());
1967  }
1968  }

Referenced by casadi::Scpgen::init(), casadi::MX::n_nodes(), and casadi::transform_stats().

◆ n_out()

casadi_int casadi::Function::n_out ( ) const

>>> x = SX.sym("x")
>>> Function("f", [x], [x, 2*x]).n_out()
2

>> x = SX.sym('x');
>> Function('f', {x}, {x, 2*x}).n_out()
2

julia> x = ca.SX.sym("x");
julia> ca.n_out(ca.Function("f", [x], [x, 2x]))
2

See also
n_in, name_out, size_out

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

Definition at line 975 of file function.cpp.

975  {
976  return (*this)->n_out_;
977  }

Referenced by activity(), casadi::CodeGenerator::add(), buf_out(), casadi::OracleFunction::calc_function(), casadi::DaeBuilderInternal::CallIO::calc_jac(), call_gen(), casadi::Nlpsol::callback(), casadi::FiniteDiff::codegen_body(), casadi::Sqpmethod::codegen_qp_ela_solve(), casadi::Feasiblesqpmethod::codegen_qp_solve(), casadi::Sqpmethod::codegen_qp_solve(), conditional(), casadi::construct_nlpsol(), casadi::Call::create(), casadi::MapSum::create(), casadi::OracleFunction::create_function(), casadi::FiniteDiff::eval(), casadi::Scpgen::eval_exp(), casadi::Scpgen::eval_mat(), casadi::Scpgen::eval_res(), casadi::CallSX::eval_sx(), casadi::Scpgen::eval_vec(), casadi::SXFunction::ExtendedAlgEl::ExtendedAlgEl(), casadi::External::factory(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::FunctionInternal::forward(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::FunctionInternal::get_n_in(), casadi::FiniteDiff::get_n_in(), casadi::FunctionInternal::get_n_out(), casadi::FiniteDiff::get_n_out(), casadi::Switch::get_n_out(), casadi::FunctionInternal::get_name_in(), casadi::FiniteDiff::get_name_in(), casadi::FunctionInternal::get_sparsity_in(), casadi::FiniteDiff::get_sparsity_in(), casadi::Onnx::import_symbolic(), casadi::Integrator::init(), casadi::Nlpsol::init(), casadi::Rootfinder::init(), casadi::RuntimeIntegrator::init(), casadi::BonminInterface::init(), casadi::GurobiInterface::init(), casadi::IpoptInterface::init(), casadi::Feasiblesqpmethod::init(), casadi::Sqpmethod::init(), casadi::BonminInterface::intermediate_callback(), casadi::IpoptInterface::intermediate_callback(), jac_sparsity(), casadi::FunctionInternal::jacobian(), casadi::Onnx::load(), map(), mapaccum(), casadi::MapSum::MapSum(), casadi::SymbolicQr::nfact(), casadi::Call::nout(), casadi::SXFunction::print(), casadi::qpsol_nlp(), rev(), casadi::FunctionInternal::reverse(), casadi::simpleIntegrator(), casadi::simpleIRK(), casadi::simpleRK(), casadi::WorhpInterface::solve(), casadi::Scpgen::solve(), casadi::SymbolicQr::solve(), casadi::Sqpmethod::solve_ela_QP(), casadi::Feasiblesqpmethod::solve_LP(), casadi::Feasiblesqpmethod::solve_QP(), casadi::Qrsqp::solve_QP(), casadi::Scpgen::solve_qp(), casadi::Sqpmethod::solve_QP(), and casadi::ThreadsWork().

◆ name()

const std::string & casadi::Function::name ( ) const

>>> Function("f", [SX.sym("x")], [SX(0)]).name()
'f'

>> Function('f', {SX.sym('x')}, {SX(0)}).name()
f

julia> ca.name(ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]))
"f"

See also
check_name

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

Definition at line 1504 of file function.cpp.

1504  {
1505  if (is_null()) {
1506  static std::string null = "null";
1507  return null;
1508  } else {
1509  return (*this)->name_;
1510  }
1511  }

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

Referenced by casadi::CodeGenerator::add(), casadi::DaeBuilderInternal::add_fun(), casadi::Integrator::augmented_dae(), bspline(), casadi::Call::Call(), check_name(), conditional(), casadi::Callback::construct(), construct(), casadi::construct_nlpsol(), casadi::MapSum::create(), casadi::Map::create(), casadi::FixedStepIntegrator::create_advanced(), casadi::Call::disp(), casadi::Switch::disp_more(), expand(), factory(), find_function(), fix_name(), fold(), Function(), casadi::FunctionInternal::FunctionInternal(), generate(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::Callback::get_factory(), casadi::Callback::get_forward(), casadi::MapSum::get_forward(), casadi::MXFunction::get_function(), casadi::SXFunction::get_function(), get_function(), casadi::Callback::get_jacobian(), casadi::FunctionInternal::get_n_in(), casadi::FunctionInternal::get_n_out(), casadi::FunctionInternal::get_name_in(), casadi::FunctionInternal::get_name_out(), casadi::Callback::get_reverse(), casadi::MapSum::get_reverse(), casadi::FunctionInternal::get_sparsity_in(), casadi::FunctionInternal::get_sparsity_out(), casadi::GraphBuilder::GraphBuilder(), has_in(), has_out(), hessian_old(), if_else(), index_in(), index_out(), casadi::FunctionInternal::init(), casadi::ImplicitFixedStepIntegrator::init(), casadi::Rootfinder::init(), casadi::SundialsInterface::init(), casadi::FunctionInternal::jac_is_symm(), jacobian_old(), jit(), casadi::Onnx::load(), casadi::FunctionInternal::map(), map(), mapaccum(), casadi::SXFunction::print(), casadi::SXNode::print_compact(), print_option(), casadi::OptiNode::scale_helper(), casadi::OracleFunction::set_function(), casadi::RungeKutta::setup_step(), slice(), casadi::FunctionInternal::tocache(), casadi::FunctionInternal::tocache_if_missing(), transform(), wrap(), and wrap_as_needed().

◆ name_in() [1/2]

const std::vector< std::string > & casadi::Function::name_in ( ) const

Names come from the constructor; when none were given they are i0, i1, ... Solver objects have fixed schemes, e.g. x0, p, lbx, ubx, lbg, ubg, lam_x0, lam_g0 for nlpsol.

>>> x = SX.sym("x"); y = SX.sym("y")
>>> Function("f", [x, y], [x+y]).name_in()
['i0', 'i1']
>>> f = Function("f", [x, y], [x+y], ["x", "y"], ["r"])
>>> f.name_in(), f.name_in(1), f.name_out()
(['x', 'y'], 'y', ['r'])

>> x = SX.sym('x'); y = SX.sym('y');
>> Function('f', {x, y}, {x+y}).name_in()
i0
i1
>> f = Function('f', {x, y}, {x+y}, {'x', 'y'}, {'r'});
>> f.name_in(), f.name_in(1), f.name_out()
x
y
y
r

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y");
julia> ca.name_in(ca.Function("f", [x, y], [x + y]))
2-element Vector{String}:
 "i0"
 "i1"
julia> f = ca.Function("f", [x, y], [x + y], ["x", "y"], ["r"]);
julia> ca.name_in(f), ca.name_in(f, 1), ca.name_out(f)
(["x", "y"], "y", ["r"])

See also
name_out, index_in, has_in

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

Definition at line 1113 of file function.cpp.

1113  {
1114  return (*this)->name_in_;
1115  }

Referenced by casadi::CodeGenerator::add(), assert_size_in(), casadi::OracleFunction::calc_function(), conditional(), construct(), casadi::construct_nlpsol(), casadi::DaeBuilderInternal::create(), casadi::GraphBuilderInternal::create_function(), expand(), casadi::External::factory(), fold(), Function(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::KinsolInterface::get_jtimes(), casadi::FunctionInternal::get_name_in(), casadi::FiniteDiff::get_name_in(), casadi::Rootfinder::get_name_in(), casadi::FunctionInternal::get_name_out(), casadi::Rootfinder::get_name_out(), hessian_old(), casadi::Onnx::import_symbolic(), casadi::Rootfinder::init(), jacobian_old(), jit(), casadi::DaeBuilderInternal::load_fmi_description(), map(), mapaccum(), casadi::nlpsol(), casadi::onnx_input_name(), casadi::qpsol_nlp(), casadi::OptiNode::scale_helper(), and transform().

◆ name_in() [2/2]

const std::string & casadi::Function::name_in ( casadi_int  ind) const

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

Definition at line 1151 of file function.cpp.

1151  {
1152  try {
1153  return (*this)->name_in_.at(ind);
1154  } catch(std::exception& e) {
1155  THROW_ERROR("name_in", e.what());
1156  }
1157  }

◆ name_out() [1/2]

const std::vector< std::string > & casadi::Function::name_out ( ) const

Defaults are o0, o1, ... when the constructor was given no names.

>>> x = SX.sym("x")
>>> Function("f", [x], [x, 2*x]).name_out()
['o0', 'o1']

>> x = SX.sym('x');
>> Function('f', {x}, {x, 2*x}).name_out()
o0
o1

julia> x = ca.SX.sym("x");
julia> ca.name_out(ca.Function("f", [x], [x, 2x]))
2-element Vector{String}:
 "o0"
 "o1"

See also
name_in, index_out, has_out

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

Definition at line 1117 of file function.cpp.

1117  {
1118  return (*this)->name_out_;
1119  }

Referenced by casadi::CodeGenerator::add(), assert_size_out(), assert_sparsity_out(), casadi::blazing_spline(), casadi::OracleFunction::calc_function(), call_gen(), conditional(), construct(), casadi::construct_nlpsol(), casadi::DaeBuilderInternal::create(), casadi::GraphBuilderInternal::create_function(), expand(), casadi::External::factory(), fold(), Function(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::KinsolInterface::get_jtimes(), casadi::FunctionInternal::get_name_in(), casadi::FiniteDiff::get_name_in(), casadi::FunctionInternal::get_name_out(), casadi::FiniteDiff::get_name_out(), casadi::Rootfinder::get_name_out(), hessian_old(), casadi::Onnx::import_symbolic(), casadi::Rootfinder::init(), casadi::RuntimeIntegrator::init(), jacobian_old(), jit(), casadi::DaeBuilderInternal::load_fmi_description(), map(), mapaccum(), casadi::nlpsol(), casadi::onnx_output_name(), casadi::qpsol_nlp(), casadi::OptiNode::scale_helper(), and transform().

◆ name_out() [2/2]

const std::string & casadi::Function::name_out ( casadi_int  ind) const

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

Definition at line 1159 of file function.cpp.

1159  {
1160  try {
1161  return (*this)->name_out_.at(ind);
1162  } catch(std::exception& e) {
1163  THROW_ERROR("name_out", e.what());
1164  }
1165  }

◆ nnz_in() [1/3]

casadi_int casadi::Function::nnz_in ( ) const

Without argument, the sum over all inputs. The nonzero count is what numerical evaluation reads for the input; it is smaller than numel_in for sparse inputs.

>>> f = Function("f", [SX.sym("x", 2), SX.sym("D", Sparsity.diag(3))], [SX(1)])
>>> f.nnz_in(0), f.nnz_in(1), f.nnz_in()
(2, 3, 5)
>>> f.numel_in(0), f.numel_in(1), f.numel_in()
(2, 9, 11)

>> f = Function('f', {SX.sym('x', 2), SX.sym('D', Sparsity.diag(3))}, {SX(1)});
>> fprintf('%d %d %d\n', f.nnz_in(0), f.nnz_in(1), f.nnz_in())
2 3 5
>> fprintf('%d %d %d\n', f.numel_in(0), f.numel_in(1), f.numel_in())
2 9 11

julia> D = ca.SX.sym("D", ca.Sparsity.diag(3));
julia> f = ca.Function("f", [ca.SX.sym("x", 2), D], [ca.SX(1)]);
julia> ca.nnz_in(f, 0), ca.nnz_in(f, 1), ca.nnz_in(f)
(2, 3, 5)
julia> ca.numel_in(f, 0), ca.numel_in(f, 1), ca.numel_in(f)
(2, 9, 11)

See also
nnz_out, numel_in, sparsity_in

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

Definition at line 1003 of file function.cpp.

1003  {
1004  return (*this)->nnz_in();
1005  }

Referenced by casadi::_which_depends(), activity(), casadi::SXFunction::ad_forward(), casadi::SXFunction::ad_reverse(), buf_in(), casadi::OracleFunction::calc_function(), casadi::FiniteDiff::codegen_body(), casadi::Map::codegen_body(), casadi::OmpMap::codegen_body(), casadi::ThreadMap::codegen_body(), casadi::MapSum::codegen_body(), casadi::CallSX::create(), casadi::Call::create(), casadi::FiniteDiff::eval(), casadi::OmpMap::eval(), casadi::Map::eval_gen(), casadi::MapSum::eval_gen(), casadi::CallSX::eval_sx(), casadi::SXFunction::ExtendedAlgEl::ExtendedAlgEl(), casadi::Call::generate(), generate_in(), casadi::MapSum::get_forward(), casadi::MapSum::get_reverse(), casadi::FiniteDiff::init(), casadi::Rootfinder::init(), casadi::SXFunction::init(), casadi::ImplicitToNlp::init(), casadi::QpToNlp::init(), casadi::RuntimeIntegrator::jump_function(), casadi::SXFunction::print(), casadi::SXFunction::print_arg(), casadi::SXNode::print_compact(), casadi::SXFunction::print_res(), casadi::FunctionBuffer::set_arg(), casadi::ImplicitToNlp::set_work(), casadi::ImplicitToNlp::solve(), casadi::Map::sp_reverse(), casadi::MapSum::sp_reverse(), and casadi::ThreadsWork().

◆ nnz_in() [2/3]

casadi_int casadi::Function::nnz_in ( casadi_int  ind) const

Without argument, the sum over all inputs. The nonzero count is what numerical evaluation reads for the input; it is smaller than numel_in for sparse inputs.

>>> f = Function("f", [SX.sym("x", 2), SX.sym("D", Sparsity.diag(3))], [SX(1)])
>>> f.nnz_in(0), f.nnz_in(1), f.nnz_in()
(2, 3, 5)
>>> f.numel_in(0), f.numel_in(1), f.numel_in()
(2, 9, 11)

>> f = Function('f', {SX.sym('x', 2), SX.sym('D', Sparsity.diag(3))}, {SX(1)});
>> fprintf('%d %d %d\n', f.nnz_in(0), f.nnz_in(1), f.nnz_in())
2 3 5
>> fprintf('%d %d %d\n', f.numel_in(0), f.numel_in(1), f.numel_in())
2 9 11

julia> D = ca.SX.sym("D", ca.Sparsity.diag(3));
julia> f = ca.Function("f", [ca.SX.sym("x", 2), D], [ca.SX(1)]);
julia> ca.nnz_in(f, 0), ca.nnz_in(f, 1), ca.nnz_in(f)
(2, 3, 5)
julia> ca.numel_in(f, 0), ca.numel_in(f, 1), ca.numel_in(f)
(2, 9, 11)

See also
nnz_out, numel_in, sparsity_in

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

Definition at line 1019 of file function.cpp.

1019  {
1020  return (*this)->nnz_in(ind);
1021  }

◆ nnz_in() [3/3]

casadi_int casadi::Function::nnz_in ( const std::string &  iname) const
inline

Without argument, the sum over all inputs. The nonzero count is what numerical evaluation reads for the input; it is smaller than numel_in for sparse inputs.

>>> f = Function("f", [SX.sym("x", 2), SX.sym("D", Sparsity.diag(3))], [SX(1)])
>>> f.nnz_in(0), f.nnz_in(1), f.nnz_in()
(2, 3, 5)
>>> f.numel_in(0), f.numel_in(1), f.numel_in()
(2, 9, 11)

>> f = Function('f', {SX.sym('x', 2), SX.sym('D', Sparsity.diag(3))}, {SX(1)});
>> fprintf('%d %d %d\n', f.nnz_in(0), f.nnz_in(1), f.nnz_in())
2 3 5
>> fprintf('%d %d %d\n', f.numel_in(0), f.numel_in(1), f.numel_in())
2 9 11

julia> D = ca.SX.sym("D", ca.Sparsity.diag(3));
julia> f = ca.Function("f", [ca.SX.sym("x", 2), D], [ca.SX(1)]);
julia> ca.nnz_in(f, 0), ca.nnz_in(f, 1), ca.nnz_in(f)
(2, 3, 5)
julia> ca.numel_in(f, 0), ca.numel_in(f, 1), ca.numel_in(f)
(2, 9, 11)

See also
nnz_out, numel_in, sparsity_in

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

Definition at line 963 of file function.hpp.

963 {return nnz_in(index_in(iname));}

References nnz_in().

Referenced by nnz_in().

◆ nnz_out() [1/3]

casadi_int casadi::Function::nnz_out ( ) const

Without argument, the sum over all outputs.

>>> x = SX.sym("x", 2)
>>> f = Function("f", [x], [x, diag(x), SX(1, 1)])
>>> f.nnz_out(0), f.nnz_out(1), f.nnz_out(2), f.nnz_out()
(2, 2, 0, 4)

>> x = SX.sym('x', 2);
>> f = Function('f', {x}, {x, diag(x), SX(1, 1)});
>> fprintf('%d %d %d %d\n', f.nnz_out(0), f.nnz_out(1), f.nnz_out(2), f.nnz_out())
2 2 0 4

julia> x = ca.SX.sym("x", 2);
julia> f = ca.Function("f", [x], [x, ca.diag(x), ca.SX(1, 1)]);
julia> ca.nnz_out(f, 0), ca.nnz_out(f, 1), ca.nnz_out(f, 2), ca.nnz_out(f)
(2, 2, 0, 4)

See also
nnz_in, numel_out, sparsity_out

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

Definition at line 1007 of file function.cpp.

1007  {
1008  return (*this)->nnz_out();
1009  }

Referenced by casadi::_which_depends(), activity(), casadi::SXFunction::ad_forward(), casadi::SXFunction::ad_reverse(), buf_out(), casadi::SundialsInterface::calc_daeB(), casadi::OracleFunction::calc_function(), casadi::SundialsInterface::calc_quadB(), casadi::SXElem::call(), casadi::FiniteDiff::codegen_body(), casadi::Map::codegen_body(), casadi::OmpMap::codegen_body(), casadi::ThreadMap::codegen_body(), casadi::MapSum::codegen_body(), casadi::FiniteDiff::eval(), casadi::OmpMap::eval(), casadi::Map::eval_gen(), casadi::MapSum::eval_gen(), casadi::CallSX::eval_sx(), casadi::SXFunction::ExtendedAlgEl::ExtendedAlgEl(), casadi::Call::generate(), generate_out(), casadi::FiniteDiff::init(), casadi::FixedStepIntegrator::init(), casadi::MapSum::init(), casadi::Rootfinder::init(), casadi::SXFunction::init(), casadi::SundialsInterface::init(), casadi::SuperscsInterface::init(), casadi::SymbolicQr::init_mem(), casadi::SXFunction::print(), casadi::SXFunction::print_res(), casadi::FunctionBuffer::set_res(), casadi::SundialsInterface::set_work(), casadi::SuperscsInterface::solve(), casadi::Map::sp_reverse(), casadi::MapSum::sp_reverse(), casadi::FixedStepIntegrator::stepB(), and casadi::ThreadsWork().

◆ nnz_out() [2/3]

casadi_int casadi::Function::nnz_out ( casadi_int  ind) const

Without argument, the sum over all outputs.

>>> x = SX.sym("x", 2)
>>> f = Function("f", [x], [x, diag(x), SX(1, 1)])
>>> f.nnz_out(0), f.nnz_out(1), f.nnz_out(2), f.nnz_out()
(2, 2, 0, 4)

>> x = SX.sym('x', 2);
>> f = Function('f', {x}, {x, diag(x), SX(1, 1)});
>> fprintf('%d %d %d %d\n', f.nnz_out(0), f.nnz_out(1), f.nnz_out(2), f.nnz_out())
2 2 0 4

julia> x = ca.SX.sym("x", 2);
julia> f = ca.Function("f", [x], [x, ca.diag(x), ca.SX(1, 1)]);
julia> ca.nnz_out(f, 0), ca.nnz_out(f, 1), ca.nnz_out(f, 2), ca.nnz_out(f)
(2, 2, 0, 4)

See also
nnz_in, numel_out, sparsity_out

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

Definition at line 1023 of file function.cpp.

1023  {
1024  return (*this)->nnz_out(ind);
1025  }

◆ nnz_out() [3/3]

casadi_int casadi::Function::nnz_out ( const std::string &  oname) const
inline

Without argument, the sum over all outputs.

>>> x = SX.sym("x", 2)
>>> f = Function("f", [x], [x, diag(x), SX(1, 1)])
>>> f.nnz_out(0), f.nnz_out(1), f.nnz_out(2), f.nnz_out()
(2, 2, 0, 4)

>> x = SX.sym('x', 2);
>> f = Function('f', {x}, {x, diag(x), SX(1, 1)});
>> fprintf('%d %d %d %d\n', f.nnz_out(0), f.nnz_out(1), f.nnz_out(2), f.nnz_out())
2 2 0 4

julia> x = ca.SX.sym("x", 2);
julia> f = ca.Function("f", [x], [x, ca.diag(x), ca.SX(1, 1)]);
julia> ca.nnz_out(f, 0), ca.nnz_out(f, 1), ca.nnz_out(f, 2), ca.nnz_out(f)
(2, 2, 0, 4)

See also
nnz_in, numel_out, sparsity_out

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

Definition at line 1003 of file function.hpp.

1003 {return nnz_out(index_out(oname));}

References nnz_out().

Referenced by nnz_out().

◆ nominal_in()

std::vector< double > casadi::Function::nominal_in ( casadi_int  ind) const

A list of length nnz_in(ind), all ones unless the class defines scaling.

>>> x = SX.sym("x", 2)
>>> f = Function("f", [x], [vertcat(x, 1)])
>>> f.nominal_in(0), f.nominal_out(0)
([1.0, 1.0], [1.0, 1.0, 1.0])

>> x = SX.sym('x', 2);
>> f = Function('f', {x}, {vertcat(x, 1)});
>> f.nominal_in(0), f.nominal_out(0)
1 1
1 1 1

julia> x = ca.SX.sym("x", 2);
julia> f = ca.Function("f", [x], [[x; 1]]);
julia> ca.nominal_in(f, 0), ca.nominal_out(f, 0)
([1.0, 1.0], [1.0, 1.0, 1.0])

See also
nominal_out, default_in

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

Definition at line 1689 of file function.cpp.

1689  {
1690  return (*this)->get_nominal_in(ind);
1691  }

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

◆ nominal_out()

std::vector< double > casadi::Function::nominal_out ( casadi_int  ind) const
See also
nominal_in

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

Definition at line 1693 of file function.cpp.

1693  {
1694  return (*this)->get_nominal_out(ind);
1695  }

◆ numel_in() [1/3]

casadi_int casadi::Function::numel_in ( ) const

Counts structural zeros too, unlike nnz_in.

>>> f = Function("f", [SX.sym("D", Sparsity.diag(3))], [SX(1)])
>>> f.numel_in(0), f.nnz_in(0), f.numel_in("i0")
(9, 3, 9)

>> f = Function('f', {SX.sym('D', Sparsity.diag(3))}, {SX(1)});
>> fprintf('%d %d %d\n', f.numel_in(0), f.nnz_in(0), f.numel_in('i0'))
9 3 9

julia> f = ca.Function("f", [ca.SX.sym("D", ca.Sparsity.diag(3))], [ca.SX(1)]);
julia> ca.numel_in(f, 0), ca.nnz_in(f, 0), ca.numel_in(f, "i0")
(9, 3, 9)

See also
nnz_in, numel_out

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

Definition at line 1011 of file function.cpp.

1011  {
1012  return (*this)->numel_in();
1013  }

Referenced by casadi::Integrator::init(), and casadi::RuntimeIntegrator::init().

◆ numel_in() [2/3]

casadi_int casadi::Function::numel_in ( casadi_int  ind) const

Counts structural zeros too, unlike nnz_in.

>>> f = Function("f", [SX.sym("D", Sparsity.diag(3))], [SX(1)])
>>> f.numel_in(0), f.nnz_in(0), f.numel_in("i0")
(9, 3, 9)

>> f = Function('f', {SX.sym('D', Sparsity.diag(3))}, {SX(1)});
>> fprintf('%d %d %d\n', f.numel_in(0), f.nnz_in(0), f.numel_in('i0'))
9 3 9

julia> f = ca.Function("f", [ca.SX.sym("D", ca.Sparsity.diag(3))], [ca.SX(1)]);
julia> ca.numel_in(f, 0), ca.nnz_in(f, 0), ca.numel_in(f, "i0")
(9, 3, 9)

See also
nnz_in, numel_out

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

Definition at line 1027 of file function.cpp.

1027  {
1028  return (*this)->numel_in(ind);
1029  }

◆ numel_in() [3/3]

casadi_int casadi::Function::numel_in ( const std::string &  iname) const
inline

Counts structural zeros too, unlike nnz_in.

>>> f = Function("f", [SX.sym("D", Sparsity.diag(3))], [SX(1)])
>>> f.numel_in(0), f.nnz_in(0), f.numel_in("i0")
(9, 3, 9)

>> f = Function('f', {SX.sym('D', Sparsity.diag(3))}, {SX(1)});
>> fprintf('%d %d %d\n', f.numel_in(0), f.nnz_in(0), f.numel_in('i0'))
9 3 9

julia> f = ca.Function("f", [ca.SX.sym("D", ca.Sparsity.diag(3))], [ca.SX(1)]);
julia> ca.numel_in(f, 0), ca.nnz_in(f, 0), ca.numel_in(f, "i0")
(9, 3, 9)

See also
nnz_in, numel_out

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

Definition at line 1052 of file function.hpp.

1052 {return numel_in(index_in(iname));}
casadi_int numel_in() const
Get the number of elements (rows times columns) of one input, or of all.
Definition: function.cpp:1011

References numel_in().

Referenced by numel_in().

◆ numel_out() [1/3]

casadi_int casadi::Function::numel_out ( ) const

>>> x = SX.sym("x", 2)
>>> f = Function("f", [x], [SX(2, 2), x])
>>> f.numel_out(0), f.numel_out(1), f.numel_out()
(4, 2, 6)

>> x = SX.sym('x', 2);
>> f = Function('f', {x}, {SX(2, 2), x});
>> fprintf('%d %d %d\n', f.numel_out(0), f.numel_out(1), f.numel_out())
4 2 6

julia> x = ca.SX.sym("x", 2);
julia> f = ca.Function("f", [x], [ca.SX(2, 2), x]);
julia> ca.numel_out(f, 0), ca.numel_out(f, 1), ca.numel_out(f)
(4, 2, 6)

See also
nnz_out, numel_in

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

Definition at line 1015 of file function.cpp.

1015  {
1016  return (*this)->numel_out();
1017  }

Referenced by casadi::Integrator::init(), and casadi::Nlpsol::init().

◆ numel_out() [2/3]

casadi_int casadi::Function::numel_out ( casadi_int  ind) const

>>> x = SX.sym("x", 2)
>>> f = Function("f", [x], [SX(2, 2), x])
>>> f.numel_out(0), f.numel_out(1), f.numel_out()
(4, 2, 6)

>> x = SX.sym('x', 2);
>> f = Function('f', {x}, {SX(2, 2), x});
>> fprintf('%d %d %d\n', f.numel_out(0), f.numel_out(1), f.numel_out())
4 2 6

julia> x = ca.SX.sym("x", 2);
julia> f = ca.Function("f", [x], [ca.SX(2, 2), x]);
julia> ca.numel_out(f, 0), ca.numel_out(f, 1), ca.numel_out(f)
(4, 2, 6)

See also
nnz_out, numel_in

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

Definition at line 1031 of file function.cpp.

1031  {
1032  return (*this)->numel_out(ind);
1033  }

◆ numel_out() [3/3]

casadi_int casadi::Function::numel_out ( const std::string &  oname) const
inline

>>> x = SX.sym("x", 2)
>>> f = Function("f", [x], [SX(2, 2), x])
>>> f.numel_out(0), f.numel_out(1), f.numel_out()
(4, 2, 6)

>> x = SX.sym('x', 2);
>> f = Function('f', {x}, {SX(2, 2), x});
>> fprintf('%d %d %d\n', f.numel_out(0), f.numel_out(1), f.numel_out())
4 2 6

julia> x = ca.SX.sym("x", 2);
julia> f = ca.Function("f", [x], [ca.SX(2, 2), x]);
julia> ca.numel_out(f, 0), ca.numel_out(f, 1), ca.numel_out(f)
(4, 2, 6)

See also
nnz_out, numel_in

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

Definition at line 1090 of file function.hpp.

1090 {return numel_out(index_out(oname));}
casadi_int numel_out() const
Get the number of elements (rows times columns) of one output, or of all.
Definition: function.cpp:1015

References numel_out().

Referenced by numel_out().

◆ nz_from_in()

std::vector< double > casadi::Function::nz_from_in ( const std::vector< DM > &  arg) const

nonzeros

nz_from_in flattens a list of n_in() DM arguments (shape rules as in call) into the concatenated nonzeros, in input order and column-major within each input; nz_to_in does the reverse, the list must have exactly nnz_in() entries. nz_from_out and nz_to_out do the same for the outputs with nnz_out(). This is the memory layout that generated C code and FunctionBuffer use.

>>> f = Function("f", [SX.sym("x"), SX.sym("D", Sparsity.diag(2))], [SX(0)])
>>> f.nz_from_in([1, DM([[2, 0], [0, 3]])])
[1.0, 2.0, 3.0]
>>> f.nz_to_in([1, 2, 3])
[DM(1), DM(
[[2, 00],
 [00, 3]])]
>>> try:
...   f.nz_to_in([1, 2])
... except RuntimeError as e:
...   print("Dimension mismatch. Expecting 3, got 2" in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('D', Sparsity.diag(2))}, {SX(0)});
>> f.nz_from_in({1, DM([2, 0; 0, 3])})
1 2 3
>> arg = f.nz_to_in([1, 2, 3]); disp(arg{1}), disp(arg{2})
1
[[2, 00],
 [00, 3]]
>> try, f.nz_to_in([1, 2]); catch e, disp(contains(e.message, 'Expecting 3, got 2')); end
1

julia> D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [ca.SX.sym("x"), D], [ca.SX(0)]);
julia> ca.nz_from_in(f, [1, ca.DM([2 0; 0 3])])
3-element Vector{Float64}:
 1.0
 2.0
 3.0
julia> x_in, D_in = ca.nz_to_in(f, [1, 2, 3]);
julia> x_in
DM(1)
julia> D_in
DM(
[[2, 00],
 [00, 3]])
julia> try
           ca.nz_to_in(f, [1, 2])
       catch e
           println(occursin("Dimension mismatch. Expecting 3, got 2", sprint(showerror, e)))
       end
true

See also
convert_in, generate_in, FunctionBuffer

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

Definition at line 1797 of file function.cpp.

1797  {
1798  return (*this)->nz_in(arg);
1799  }

Referenced by generate_in().

◆ nz_from_out()

std::vector< double > casadi::Function::nz_from_out ( const std::vector< DM > &  arg) const

nonzeros

nz_from_in flattens a list of n_in() DM arguments (shape rules as in call) into the concatenated nonzeros, in input order and column-major within each input; nz_to_in does the reverse, the list must have exactly nnz_in() entries. nz_from_out and nz_to_out do the same for the outputs with nnz_out(). This is the memory layout that generated C code and FunctionBuffer use.

>>> f = Function("f", [SX.sym("x"), SX.sym("D", Sparsity.diag(2))], [SX(0)])
>>> f.nz_from_in([1, DM([[2, 0], [0, 3]])])
[1.0, 2.0, 3.0]
>>> f.nz_to_in([1, 2, 3])
[DM(1), DM(
[[2, 00],
 [00, 3]])]
>>> try:
...   f.nz_to_in([1, 2])
... except RuntimeError as e:
...   print("Dimension mismatch. Expecting 3, got 2" in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('D', Sparsity.diag(2))}, {SX(0)});
>> f.nz_from_in({1, DM([2, 0; 0, 3])})
1 2 3
>> arg = f.nz_to_in([1, 2, 3]); disp(arg{1}), disp(arg{2})
1
[[2, 00],
 [00, 3]]
>> try, f.nz_to_in([1, 2]); catch e, disp(contains(e.message, 'Expecting 3, got 2')); end
1

julia> D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [ca.SX.sym("x"), D], [ca.SX(0)]);
julia> ca.nz_from_in(f, [1, ca.DM([2 0; 0 3])])
3-element Vector{Float64}:
 1.0
 2.0
 3.0
julia> x_in, D_in = ca.nz_to_in(f, [1, 2, 3]);
julia> x_in
DM(1)
julia> D_in
DM(
[[2, 00],
 [00, 3]])
julia> try
           ca.nz_to_in(f, [1, 2])
       catch e
           println(occursin("Dimension mismatch. Expecting 3, got 2", sprint(showerror, e)))
       end
true

See also
convert_in, generate_in, FunctionBuffer

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

Definition at line 1801 of file function.cpp.

1801  {
1802  return (*this)->nz_out(res);
1803  }

Referenced by generate_out().

◆ nz_to_in()

std::vector< DM > casadi::Function::nz_to_in ( const std::vector< double > &  arg) const

nonzeros

nz_from_in flattens a list of n_in() DM arguments (shape rules as in call) into the concatenated nonzeros, in input order and column-major within each input; nz_to_in does the reverse, the list must have exactly nnz_in() entries. nz_from_out and nz_to_out do the same for the outputs with nnz_out(). This is the memory layout that generated C code and FunctionBuffer use.

>>> f = Function("f", [SX.sym("x"), SX.sym("D", Sparsity.diag(2))], [SX(0)])
>>> f.nz_from_in([1, DM([[2, 0], [0, 3]])])
[1.0, 2.0, 3.0]
>>> f.nz_to_in([1, 2, 3])
[DM(1), DM(
[[2, 00],
 [00, 3]])]
>>> try:
...   f.nz_to_in([1, 2])
... except RuntimeError as e:
...   print("Dimension mismatch. Expecting 3, got 2" in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('D', Sparsity.diag(2))}, {SX(0)});
>> f.nz_from_in({1, DM([2, 0; 0, 3])})
1 2 3
>> arg = f.nz_to_in([1, 2, 3]); disp(arg{1}), disp(arg{2})
1
[[2, 00],
 [00, 3]]
>> try, f.nz_to_in([1, 2]); catch e, disp(contains(e.message, 'Expecting 3, got 2')); end
1

julia> D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [ca.SX.sym("x"), D], [ca.SX(0)]);
julia> ca.nz_from_in(f, [1, ca.DM([2 0; 0 3])])
3-element Vector{Float64}:
 1.0
 2.0
 3.0
julia> x_in, D_in = ca.nz_to_in(f, [1, 2, 3]);
julia> x_in
DM(1)
julia> D_in
DM(
[[2, 00],
 [00, 3]])
julia> try
           ca.nz_to_in(f, [1, 2])
       catch e
           println(occursin("Dimension mismatch. Expecting 3, got 2", sprint(showerror, e)))
       end
true

See also
convert_in, generate_in, FunctionBuffer

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

Definition at line 1805 of file function.cpp.

1805  {
1806  return (*this)->nz_in(arg);
1807  }

Referenced by generate_in().

◆ nz_to_out()

std::vector< DM > casadi::Function::nz_to_out ( const std::vector< double > &  arg) const

nonzeros

nz_from_in flattens a list of n_in() DM arguments (shape rules as in call) into the concatenated nonzeros, in input order and column-major within each input; nz_to_in does the reverse, the list must have exactly nnz_in() entries. nz_from_out and nz_to_out do the same for the outputs with nnz_out(). This is the memory layout that generated C code and FunctionBuffer use.

>>> f = Function("f", [SX.sym("x"), SX.sym("D", Sparsity.diag(2))], [SX(0)])
>>> f.nz_from_in([1, DM([[2, 0], [0, 3]])])
[1.0, 2.0, 3.0]
>>> f.nz_to_in([1, 2, 3])
[DM(1), DM(
[[2, 00],
 [00, 3]])]
>>> try:
...   f.nz_to_in([1, 2])
... except RuntimeError as e:
...   print("Dimension mismatch. Expecting 3, got 2" in str(e))
True

>> f = Function('f', {SX.sym('x'), SX.sym('D', Sparsity.diag(2))}, {SX(0)});
>> f.nz_from_in({1, DM([2, 0; 0, 3])})
1 2 3
>> arg = f.nz_to_in([1, 2, 3]); disp(arg{1}), disp(arg{2})
1
[[2, 00],
 [00, 3]]
>> try, f.nz_to_in([1, 2]); catch e, disp(contains(e.message, 'Expecting 3, got 2')); end
1

julia> D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [ca.SX.sym("x"), D], [ca.SX(0)]);
julia> ca.nz_from_in(f, [1, ca.DM([2 0; 0 3])])
3-element Vector{Float64}:
 1.0
 2.0
 3.0
julia> x_in, D_in = ca.nz_to_in(f, [1, 2, 3]);
julia> x_in
DM(1)
julia> D_in
DM(
[[2, 00],
 [00, 3]])
julia> try
           ca.nz_to_in(f, [1, 2])
       catch e
           println(occursin("Dimension mismatch. Expecting 3, got 2", sprint(showerror, e)))
       end
true

See also
convert_in, generate_in, FunctionBuffer

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

Definition at line 1809 of file function.cpp.

1809  {
1810  return (*this)->nz_out(res);
1811  }

Referenced by generate_out().

◆ operator()() [1/24]

int casadi::Function::operator() ( const bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t *  w,
int  mem = 0 
) const

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

Definition at line 1243 of file function.cpp.

1244  {
1245  try {
1246  return (*this)->sp_forward(arg, res, iw, w, memory(mem));
1247  } catch(std::exception& e) {
1248  THROW_ERROR("operator()", e.what());
1249  }
1250  }

References memory().

◆ operator()() [2/24]

std::vector<DM> casadi::Function::operator() ( const DM &  arg0) const
inline

Functor shorthand for evaluation, single argument (only C++)

Definition at line 2484 of file function.hpp.

2484  {
2485  return operator()(std::vector<DM>{arg0});
2486  }
std::vector< DM > operator()(const std::vector< DM > &arg) const
Definition: function.cpp:1597

◆ operator()() [3/24]

const DMDict casadi::Function::operator() ( const DMDict &  arg) const

Functor shorthand for evaluation

Definition at line 1632 of file function.cpp.

1632  {
1633  DMDict res;
1634  call(arg, res);
1635  return res;
1636  }
std::map< std::string, DM > DMDict
Definition: dm_fwd.hpp:36

References call().

◆ operator()() [4/24]

int casadi::Function::operator() ( const double **  arg,
double **  res,
casadi_int *  iw,
double *  w 
) const

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

Definition at line 1702 of file function.cpp.

1703  {
1704  scoped_checkout<Function> mem(*this);
1705  return operator()(arg, res, iw, w, mem);
1706  }

References operator()().

◆ operator()() [5/24]

int casadi::Function::operator() ( const double **  arg,
double **  res,
casadi_int *  iw,
double *  w,
int  mem 
) const

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

Definition at line 1708 of file function.cpp.

1709  {
1710  try {
1711 #ifdef WITH_EXTRA_CHECKS
1712  // Should never happen
1713  casadi_assert_dev(call_depth_>=0);
1714  call_depth_++;
1715  // For consistency check
1716  casadi_int depth = call_depth_;
1717 #endif // WITH_EXTRA_CHECKS
1718  int ret = (*this)->eval_gen(arg, res, iw, w, memory(mem), false, false);
1719 #ifdef WITH_EXTRA_CHECKS
1720  // Consitency check
1721  casadi_assert_dev(call_depth_==depth);
1722  call_depth_--;
1723 #endif // WITH_EXTRA_CHECKS
1724  return ret;
1725  } catch (KeyboardInterruptException& e) {
1726  (void)e; // unused
1727 #ifdef WITH_EXTRA_CHECKS
1728  call_depth_--;
1729 #endif // WITH_EXTRA_CHECKS
1730  throw;
1731  } catch(std::exception& e) {
1732 #ifdef WITH_EXTRA_CHECKS
1733  call_depth_--;
1734 #endif // WITH_EXTRA_CHECKS
1735  (*this)->print_in(uerr(), arg, true);
1736  THROW_ERROR("operator()", e.what());
1737  }
1738  }
std::ostream & uerr()

References memory(), casadi::uerr(), and casadi::CasadiException::what().

◆ operator()() [6/24]

std::vector<MX> casadi::Function::operator() ( const MX &  arg0) const
inline

Functor shorthand for evaluation, single argument (only C++)

Definition at line 2490 of file function.hpp.

2490  {
2491  return operator()(std::vector<MX>{arg0});
2492  }

◆ operator()() [7/24]

const MXDict casadi::Function::operator() ( const MXDict &  arg) const

Functor shorthand for evaluation

Definition at line 1644 of file function.cpp.

1644  {
1645  MXDict res;
1646  call(arg, res);
1647  return res;
1648  }
std::map< std::string, MX > MXDict
Definition: mx.hpp:5151

References call().

◆ operator()() [8/24]

std::vector< DM > casadi::Function::operator() ( const std::vector< DM > &  arg) const

Functor shorthand for evaluation

Definition at line 1597 of file function.cpp.

1597  {
1598  std::vector<DM> res;
1599  call(arg, res);
1600  return res;
1601  }

References call().

Referenced by operator()().

◆ operator()() [9/24]

std::vector< MX > casadi::Function::operator() ( const std::vector< MX > &  arg) const

Functor shorthand for evaluation

Definition at line 1609 of file function.cpp.

1609  {
1610  std::vector<MX> res;
1611  call(arg, res);
1612  return res;
1613  }

References call().

◆ operator()() [10/24]

std::vector< SX > casadi::Function::operator() ( const std::vector< SX > &  arg) const

Functor shorthand for evaluation

Definition at line 1603 of file function.cpp.

1603  {
1604  std::vector<SX> res;
1605  call(arg, res);
1606  return res;
1607  }

References call().

◆ operator()() [11/24]

std::vector<SX> casadi::Function::operator() ( const SX &  arg0) const
inline

Functor shorthand for evaluation, single argument (only C++)

Definition at line 2487 of file function.hpp.

2487  {
2488  return operator()(std::vector<SX>{arg0});
2489  }

◆ operator()() [12/24]

const SXDict casadi::Function::operator() ( const SXDict &  arg) const

Functor shorthand for evaluation

Definition at line 1638 of file function.cpp.

1638  {
1639  SXDict res;
1640  call(arg, res);
1641  return res;
1642  }
std::map< std::string, SX > SXDict
Definition: sx_fwd.hpp:40

References call().

◆ operator()() [13/24]

int casadi::Function::operator() ( const SXElem **  arg,
SXElem **  res,
casadi_int *  iw,
SXElem *  w,
int  mem = 0 
) const

Same syntax as the double version, allowing use in templated code

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

Definition at line 1740 of file function.cpp.

1741  {
1742  try {
1743  return (*this)->eval_sx(arg, res, iw, w, memory(mem), false, false);
1744  } catch(std::exception& e) {
1745  THROW_ERROR("operator()", e.what());
1746  }
1747  }

References memory().

◆ operator()() [14/24]

void casadi::Function::operator() ( MapArg  arg,
MapRes  res 
) const
inline

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

Definition at line 2477 of file function.hpp.

2477 { (*this)(buf_in(arg), buf_out(res)); }
std::vector< double * > buf_out(VecRes res) const
Supported arguments for numerical evaluation and converters.
Definition: function.cpp:547
std::vector< const double * > buf_in(VecArg arg) const
Supported arguments for numerical evaluation and converters.
Definition: function.cpp:536

◆ operator()() [15/24]

void casadi::Function::operator() ( MapArg  arg,
MPrRes  res 
) const
inline

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

Definition at line 2479 of file function.hpp.

2479 { (*this)(buf_in(arg), buf_out(res)); }

◆ operator()() [16/24]

void casadi::Function::operator() ( MapArg  arg,
VecRes  res 
) const
inline

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

Definition at line 2476 of file function.hpp.

2476 { (*this)(buf_in(arg), buf_out(res)); }

◆ operator()() [17/24]

void casadi::Function::operator() ( MapArg  arg,
VPrRes  res 
) const
inline

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

Definition at line 2478 of file function.hpp.

2478 { (*this)(buf_in(arg), buf_out(res)); }

◆ operator()() [18/24]

void casadi::Function::operator() ( std::vector< const bvec_t * >  arg,
std::vector< bvec_t * >  res 
) const

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

Definition at line 636 of file function.cpp.

636  {
637  call_gen(arg, res);
638  }

References call_gen().

◆ operator()() [19/24]

void casadi::Function::operator() ( std::vector< const double * >  arg,
std::vector< double * >  res 
) const

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

Definition at line 632 of file function.cpp.

632  {
633  call_gen(arg, res);
634  }

References call_gen().

◆ operator()() [20/24]

void casadi::Function::operator() ( std::vector< const SXElem * >  arg,
std::vector< SXElem * >  res 
) const

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

Definition at line 640 of file function.cpp.

640  {
641  call_gen(arg, res);
642  }

References call_gen().

◆ operator()() [21/24]

void casadi::Function::operator() ( VecArg  arg,
MapRes  res 
) const
inline

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

Definition at line 2472 of file function.hpp.

2472 { (*this)(buf_in(arg), buf_out(res)); }

◆ operator()() [22/24]

void casadi::Function::operator() ( VecArg  arg,
MPrRes  res 
) const
inline

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

Definition at line 2474 of file function.hpp.

2474 { (*this)(buf_in(arg), buf_out(res)); }

◆ operator()() [23/24]

void casadi::Function::operator() ( VecArg  arg,
VecRes  res 
) const
inline

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

Definition at line 2471 of file function.hpp.

2471 { (*this)(buf_in(arg), buf_out(res)); }

◆ operator()() [24/24]

void casadi::Function::operator() ( VecArg  arg,
VPrRes  res 
) const
inline

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

Definition at line 2473 of file function.hpp.

2473 { (*this)(buf_in(arg), buf_out(res)); }

◆ operator->()

FunctionInternal * casadi::Function::operator-> ( ) const

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

Definition at line 500 of file function.cpp.

500  {
501  casadi_assert_dev(!is_null());
502  return get();
503  }

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

◆ operator==()

bool casadi::Function::operator== ( const Function &  f) const

Definition at line 2128 of file function.cpp.

2128  {
2129  try {
2130  casadi_assert(!is_null(), "lhs is null");
2131  casadi_assert(!f.is_null(), "rhs is null");
2132  return get()==f.get();
2133  } catch(std::exception& e) {
2134  THROW_ERROR("operator==", e.what());
2135  }
2136  }

References get(), casadi::GenericShared< Shared, Internal >::is_null(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::is_null().

◆ oracle()

Function casadi::Function::oracle ( ) const

For nlpsol, qpsol, rootfinder and integrator objects this is the Function with the problem expressions (e.g. nlp:(x,p)->(f,g)); for other classes an error is raised.

>>> x = SX.sym("x")
>>> opts = {"qpsol": "qrqp", "print_header": False, "print_iteration": False,
...         "print_time": False, "qpsol_options": {"print_header": False}}
>>> S = nlpsol("S", "sqpmethod", {"x": x, "f": x**2}, opts)
>>> S.oracle()
Function(nlp:(x,p[])->(f,g[0]) SXFunction)
>>> try:
...   S.oracle().oracle()
... except RuntimeError as e:
...   print("'oracle' not defined for SXFunction" in str(e))
True

>> x = SX.sym('x');
>> opts = struct('qpsol', 'qrqp', 'print_header', false, 'print_iteration', false);
>> opts.print_time = false; opts.qpsol_options = struct('print_header', false);
>> S = nlpsol('S', 'sqpmethod', struct('x', x, 'f', x^2), opts);
>> S.oracle()
nlp:(x,p[])->(f,g[0]) SXFunction
>> try, S.oracle().oracle(); catch e, disp(contains(e.message, 'not defined')); end
1

julia> x = ca.SX.sym("x");
julia> opts = Dict("qpsol" => "qrqp", "print_header" => false, "print_iteration" => false,
                   "print_time" => false, "qpsol_options" => Dict("print_header" => false));
julia> S = ca.nlpsol("S", "sqpmethod", Dict("x" => x, "f" => x^2), opts);
julia> ca.oracle(S)
Function(nlp:(x,p[])->(f,g[0]) SXFunction)
julia> try
           ca.oracle(ca.oracle(S))
       catch e
           println(occursin("'oracle' not defined for SXFunction", sprint(showerror, e)))
       end
true

See also
get_function, find_functions

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

Definition at line 2104 of file function.cpp.

2104  {
2105  try {
2106  return (*this)->oracle();
2107  } catch(std::exception& e) {
2108  THROW_ERROR("oracle", e.what());
2109  }
2110  }

References casadi::FunctionInternal::oracle().

◆ order() [1/2]

std::vector< MX > casadi::Function::order ( const std::vector< MX > &  expr)
static

Definition at line 2146 of file function.cpp.

2146  {
2147  return MXFunction::order(expr);
2148  }
static std::vector< MX > order(const std::vector< MX > &expr)

References casadi::MXFunction::order().

◆ order() [2/2]

std::vector< SX > casadi::Function::order ( const std::vector< SX > &  expr)
static

Definition at line 2142 of file function.cpp.

2142  {
2143  return SXFunction::order(expr);
2144  }
static std::vector< SX > order(const std::vector< SX > &expr)

References casadi::SXFunction::order().

Referenced by casadi::SerializerBase::pack(), and which_depends().

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

◆ print_dimensions()

void casadi::Function::print_dimensions ( std::ostream &  stream = casadi::uout()) const

>>> f = Function("f", [SX.sym("x", 2), SX.sym("p")], [SX(1, 3)], ["x", "p"], ["r"])
>>> f.print_dimensions()
Number of inputs: 2
Input 0 ("x"): 2x1
Input 1 ("p"): 1x1
Number of outputs: 1
Output 0 ("r"): 1x3

>> f = Function('f', {SX.sym('x', 2), SX.sym('p')}, {SX(1, 3)}, {'x', 'p'}, {'r'});
>> f.print_dimensions()
Number of inputs: 2
Input 0 ("x"): 2x1
Input 1 ("p"): 1x1
Number of outputs: 1
Output 0 ("r"): 1x3

julia> x = ca.SX.sym("x", 2); p = ca.SX.sym("p");
julia> f = ca.Function("f", [x, p], [ca.SX(1, 3)], ["x", "p"], ["r"]);
julia> ca.print_dimensions(f)
 Number of inputs: 2
  Input 0 ("x"): 2x1
  Input 1 ("p"): 1x1
 Number of outputs: 1
  Output 0 ("r"): 1x3

See also
size_in, sparsity_in

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

Definition at line 1340 of file function.cpp.

1340  {
1341  (*this)->print_dimensions(stream);
1342  }

◆ print_option()

void casadi::Function::print_option ( const std::string &  name,
std::ostream &  stream = casadi::uout() 
) const

notice

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.print_option("verbose")
> "verbose"          [OT_BOOL]      "Verbose evaluation -- for debugging"

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> f.print_option('verbose')
> "verbose"          [OT_BOOL]      "Verbose evaluation -- for debugging"

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.print_option(f, "verbose")
> "verbose"          [OT_BOOL]      "Verbose evaluation -- for debugging"

See also
print_options, has_option

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

Definition at line 1348 of file function.cpp.

1348  {
1349  (*this)->print_option(name, stream);
1350  }

References name().

◆ print_options()

void casadi::Function::print_options ( std::ostream &  stream = casadi::uout()) const

The list depends on the class (SXFunction, MXFunction, a solver plugin, ...). Options are set at construction; see change_option for the few that can be changed afterwards.

See also
print_option, has_option

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

Definition at line 1344 of file function.cpp.

1344  {
1345  (*this)->print_options(stream);
1346  }

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

◆ proceed_to()

bool casadi::Function::proceed_to ( std::istream &  file,
const std::string &  str 
)
staticprotected

Definition at line 64 of file function.cpp.

64  {
65  // Make sure that the file is ready for reading
66  if (!file.good()) return false;
67  // Have we already wrapped around once?
68  //bool wrapped_around = false;
69  // Read line-by-line
70  std::string tmp;
71  while (true) {
72  // Read a word
73  std::streampos cur_pos = file.tellg();
74  file >> tmp;
75  if (!file.good()) return false;
76 
77  // Check if match
78  if (str==tmp) return true;
79 
80  // If comment, continue to the end of the line
81  if (tmp.at(0)=='#') {
82  file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
83  continue;
84  }
85 
86  // If mismatching name, rewind and break
87  file.seekg(cur_pos);
88  return false;
89  }
90  }

References casadi::str().

◆ release()

void casadi::Function::release ( int  mem) const

Definition at line 1974 of file function.cpp.

1974  {
1975  (*this)->release(mem);
1976  }

Referenced by casadi::QpToNlp::free_mem(), casadi::Sqpmethod::free_mem(), casadi::FunctionBuffer::operator=(), and casadi::FunctionBuffer::~FunctionBuffer().

◆ reset_dump_count()

void casadi::Function::reset_dump_count ( )

dump_out and dump_trace

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

Definition at line 1373 of file function.cpp.

1373  {
1374  try {
1375  (*this)->reset_dump_count();
1376  } catch(std::exception& e) {
1377  THROW_ERROR("reset_dump_count", e.what());
1378  }
1379  }

◆ rev() [1/2]

int casadi::Function::rev ( bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t *  w,
int  mem = 0 
) const

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

Definition at line 1252 of file function.cpp.

1252  {
1253  try {
1254  return (*this)->sp_reverse(arg, res, iw, w, memory(mem));
1255  } catch(std::exception& e) {
1256  THROW_ERROR("rev", e.what());
1257  }
1258  }

References memory().

Referenced by casadi::_which_depends(), rev(), casadi::Call::sp_reverse(), casadi::Map::sp_reverse(), casadi::MapSum::sp_reverse(), and casadi::Rootfinder::sp_reverse().

◆ rev() [2/2]

int casadi::Function::rev ( std::vector< bvec_t * >  arg,
std::vector< bvec_t * >  res 
) const

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

Definition at line 644 of file function.cpp.

644  {
645  // Input buffer
646  casadi_assert_dev(arg.size()>=n_in());
647  arg.resize(sz_arg());
648 
649  // Output buffer
650  casadi_assert_dev(res.size()>=n_out());
651  res.resize(sz_res());
652 
653  // Work vectors
654  std::vector<casadi_int> iw(sz_iw());
655  std::vector<bvec_t> w(sz_w());
656 
657  // Evaluate memoryless
658  return rev(get_ptr(arg), get_ptr(res), get_ptr(iw), get_ptr(w), 0);
659  }
int rev(bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, int mem=0) const
Propagate sparsity backward.
Definition: function.cpp:1252

References casadi::get_ptr(), n_in(), n_out(), rev(), sz_arg(), sz_iw(), sz_res(), and sz_w().

◆ reverse()

Function casadi::Function::reverse ( casadi_int  nadj) const

The result is named adj<nadj>_<name> and has n_in + n_out + n_out inputs: the original inputs, the original outputs (out_<name>) and the adjoint seeds adj_<output>, each with nadj times the columns of the output. Its n_in outputs adj_<input> are the adjoint sensitivities, nadj stacked horizontally. Falls back to the full Jacobian when the class has no reverse mode; raises when it has no derivatives at all. Results are cached while alive. nadj must be positive.

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"])
>>> R = f.reverse(1)
>>> R
Function(adj1_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],adj_r[2],adj_s)->(adj_x,adj_y[2])
SXFunction)
>>> R(1, [2, 3], 0, 0, [1, 1], 0)
(DM(5), DM([1, 1]))

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y, sin(x)}, {'x', 'y'}, {'r', 's'});
>> R = f.reverse(1); disp(R)
adj1_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],adj_r[2],adj_s)->(adj_x,adj_y[2]) SXFunction
>> [adj_x, adj_y] = R(1, [2; 3], 0, 0, [1; 1], 0); disp(adj_x), disp(adj_y)
5
[1, 1]

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y, sin(x)], ["x", "y"], ["r", "s"]);
julia> R = f.reverse(1);
julia> R
Function(adj1_f:(x,y[2],out_r[2x1,0nz],out_s[1x1,0nz],adj_r[2],adj_s)->(adj_x,adj_y[2]) SXFunction)
julia> R(1, [2, 3], 0, 0, [1, 1], 0)
(5, [1, 1])

See also
forward, jacobian, factory

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

Definition at line 1332 of file function.cpp.

1332  {
1333  try {
1334  return (*this)->reverse(nadj);
1335  } catch(std::exception& e) {
1336  THROW_ERROR("reverse", e.what());
1337  }
1338  }

References casadi::FunctionInternal::reverse().

Referenced by casadi::SXFunction::ad_reverse(), casadi::DaeBuilderInternal::export_fmu(), casadi::Conic::get_reverse(), casadi::Map::get_reverse(), casadi::MapSum::get_reverse(), casadi::Nlpsol::get_reverse(), casadi::Switch::get_reverse(), casadi::Integrator::init(), casadi::ImplicitFixedStepIntegrator::init(), casadi::RuntimeIntegrator::init(), casadi::FunctionInternal::reverse(), and casadi::RungeKutta::setup_step().

◆ save()

void casadi::Function::save ( const std::string &  fname,
const Dict &  opts = Dict() 
) const

Writes a serialization of the function to fname (conventionally with the extension .casadi). The file is portable across platforms and languages (Python, MATLAB, C++); it is compatible across CasADi versions as far as the serialization format allows.

Parameters
fnameFile name
optsSerializer options, e.g. "debug"

>>> import os
>>> x = SX.sym("x")
>>> f = Function("f", [x], [x**2])
>>> f.save("f.casadi")
>>> g = Function.load("f.casadi")
>>> g, g(3)
(Function(f:(i0)->(o0) SXFunction), DM(9))
>>> os.remove("f.casadi")

>> x = SX.sym('x');
>> f = Function('f', {x}, {x^2});
>> f.save('f.casadi'); g = Function.load('f.casadi'); disp(g), disp(g(3))
f:(i0)->(o0) SXFunction
9
>> delete('f.casadi');

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [x^2]);
julia> ca.save(f, "f.casadi")
julia> g = ca.Function.load("f.casadi");
julia> println(g); g(3)
f:(i0)->(o0) SXFunction
DM(9)
julia> rm("f.casadi")

See also
load, serialize, FileSerializer

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

Definition at line 1466 of file function.cpp.

1466  {
1467  FileSerializer fs(fname, opts);
1468  fs.pack(*this);
1469  }

References casadi::SerializerBase::pack().

◆ serialize() [1/3]

std::string casadi::Function::serialize ( const Dict &  opts = Dict()) const

Any Function can be serialized, including solvers and functions with embedded calls; a just-in-time compiled function is stored according to option "jit_serialize". The string is binary-safe text; it is also what the Python pickle protocol and MATLAB save use.

Parameters
opts"debug" (bool) adds consistency markers to the stream

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)], ["x"], ["y"])
>>> s = f.serialize()
>>> g = Function.deserialize(s)
>>> g, g(1)
(Function(f:(x)->(y) SXFunction), DM(0.841471))

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)}, {'x'}, {'y'});
>> s = f.serialize(); g = Function.deserialize(s); disp(g), disp(g(1))
f:(x)->(y) SXFunction
0.841471

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)], ["x"], ["y"]);
julia> s = ca.serialize(f);
julia> g = ca.Function.deserialize(s);
julia> println(g); g(1)
f:(x)->(y) SXFunction
DM(0.841471)

See also
deserialize, save, load

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

Definition at line 1471 of file function.cpp.

1471  {
1472  std::stringstream ss;
1473  serialize(ss, opts);
1474  return ss.str();
1475  }
void serialize(std::ostream &stream, const Dict &opts=Dict()) const
Serialize.
Definition: function.cpp:1477

References serialize().

◆ serialize() [2/3]

void casadi::Function::serialize ( SerializingStream &  s) const

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

Definition at line 1482 of file function.cpp.

1482  {
1483  if (is_null()) {
1484  s.pack("Function::null", true);
1485  } else {
1486  s.pack("Function::null", false);
1487  (*this)->serialize(s);
1488  }
1489  }

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

◆ serialize() [3/3]

void casadi::Function::serialize ( std::ostream &  stream,
const Dict &  opts = Dict() 
) const

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

Definition at line 1477 of file function.cpp.

1477  {
1478  SerializingStream s(stream, opts);
1479  serialize(s);
1480  }

Referenced by casadi::MX::cse(), and serialize().

◆ set_temp()

void casadi::Function::set_temp ( const double **  arg,
double **  res,
casadi_int *  iw,
double *  w,
int  mem = 0 
) const

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

Definition at line 1306 of file function.cpp.

1307  {
1308  try {
1309  (*this)->set_temp(memory(mem), arg, res, iw, w);
1310  } catch(std::exception& e) {
1311  THROW_ERROR("set_temp", e.what());
1312  }
1313  }

References memory().

◆ set_work()

void casadi::Function::set_work ( const double **&  arg,
double **&  res,
casadi_int *&  iw,
double *&  w,
int  mem = 0 
) const

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

Definition at line 1297 of file function.cpp.

1298  {
1299  try {
1300  (*this)->set_work(memory(mem), arg, res, iw, w);
1301  } catch(std::exception& e) {
1302  THROW_ERROR("set_work", e.what());
1303  }
1304  }

References memory().

◆ setup()

void casadi::Function::setup ( const double **  arg,
double **  res,
casadi_int *  iw,
double *  w,
int  mem = 0 
) const

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

Definition at line 1315 of file function.cpp.

1316  {
1317  try {
1318  (*this)->setup(memory(mem), arg, res, iw, w);
1319  } catch(std::exception& e) {
1320  THROW_ERROR("setup", e.what());
1321  }
1322  }

References memory().

◆ size1_in() [1/2]

casadi_int casadi::Function::size1_in ( casadi_int  ind) const

size1_in is the number of rows, size2_in the number of columns and size_in the pair (rows, columns). The input is selected by index or by name; an unknown name raises an error listing the available names, an index out of range raises an error.

>>> f = Function("f", [SX.sym("A", 2, 3), SX.sym("b", 2)], [SX(0)], ["A", "b"], ["c"])
>>> f.size_in(0), f.size1_in("A"), f.size2_in("A")
((2, 3), 2, 3)
>>> f.size_in("b")
(2, 1)
>>> try:
...   f.size_in("nope")
... except RuntimeError as e:
...   print("Available names are: [A, b]" in str(e))
True

>> f = Function('f', {SX.sym('A', 2, 3), SX.sym('b', 2)}, {SX(0)}, {'A', 'b'}, {'c'});
>> disp(f.size_in(0)), fprintf('%d %d\n', f.size1_in('A'), f.size2_in('A'))
2 3
2 3
>> f.size_in('b')
2 1
>> try, f.size_in('nope'); catch e, disp(contains(e.message, 'Available names')); end
1

julia> A = ca.SX.sym("A", 2, 3); b = ca.SX.sym("b", 2);
julia> f = ca.Function("f", [A, b], [ca.SX(0)], ["A", "b"], ["c"]);
julia> ca.size_in(f, 0), ca.size1_in(f, "A"), ca.size2_in(f, "A")
((2, 3), 2, 3)
julia> ca.size_in(f, "b")
(2, 1)
julia> try
           ca.size_in(f, "nope")
       catch e
           println(occursin("Available names are: [A, b]", sprint(showerror, e)))
       end
true

See also
size_out, sparsity_in, nnz_in, numel_in

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

Definition at line 979 of file function.cpp.

979  {
980  return (*this)->size1_in(ind);
981  }

Referenced by assert_size_in(), casadi::construct_nlpsol(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::FiniteDiff::get_sparsity_in(), and casadi::Blocksqp::init().

◆ size1_in() [2/2]

casadi_int casadi::Function::size1_in ( const std::string &  iname) const
inline

size1_in is the number of rows, size2_in the number of columns and size_in the pair (rows, columns). The input is selected by index or by name; an unknown name raises an error listing the available names, an index out of range raises an error.

>>> f = Function("f", [SX.sym("A", 2, 3), SX.sym("b", 2)], [SX(0)], ["A", "b"], ["c"])
>>> f.size_in(0), f.size1_in("A"), f.size2_in("A")
((2, 3), 2, 3)
>>> f.size_in("b")
(2, 1)
>>> try:
...   f.size_in("nope")
... except RuntimeError as e:
...   print("Available names are: [A, b]" in str(e))
True

>> f = Function('f', {SX.sym('A', 2, 3), SX.sym('b', 2)}, {SX(0)}, {'A', 'b'}, {'c'});
>> disp(f.size_in(0)), fprintf('%d %d\n', f.size1_in('A'), f.size2_in('A'))
2 3
2 3
>> f.size_in('b')
2 1
>> try, f.size_in('nope'); catch e, disp(contains(e.message, 'Available names')); end
1

julia> A = ca.SX.sym("A", 2, 3); b = ca.SX.sym("b", 2);
julia> f = ca.Function("f", [A, b], [ca.SX(0)], ["A", "b"], ["c"]);
julia> ca.size_in(f, 0), ca.size1_in(f, "A"), ca.size2_in(f, "A")
((2, 3), 2, 3)
julia> ca.size_in(f, "b")
(2, 1)
julia> try
           ca.size_in(f, "nope")
       catch e
           println(occursin("Available names are: [A, b]", sprint(showerror, e)))
       end
true

See also
size_out, sparsity_in, nnz_in, numel_in

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

Definition at line 864 of file function.hpp.

864 {return size1_in(index_in(iname));}

References size1_in().

Referenced by size1_in().

◆ size1_out() [1/2]

casadi_int casadi::Function::size1_out ( casadi_int  ind) const

Same conventions as size_in, size1_in and size2_in.

>>> x = SX.sym("x", 3)
>>> f = Function("f", [x], [x.T, SX(2, 2)])
>>> f.size_out(0), f.size_out("o1"), f.size1_out(0), f.size2_out(1)
((1, 3), (2, 2), 1, 2)

>> x = SX.sym('x', 3);
>> f = Function('f', {x}, {x', SX(2, 2)});
>> f.size_out(0), f.size_out('o1')
1 3
2 2
>> fprintf('%d %d\n', f.size1_out(0), f.size2_out(1))
1 2

julia> x = ca.SX.sym("x", 3);
julia> f = ca.Function("f", [x], [x', ca.SX(2, 2)]);
julia> ca.size_out(f, 0), ca.size_out(f, "o1"), ca.size1_out(f, 0), ca.size2_out(f, 1)
((1, 3), (2, 2), 1, 2)

See also
size_in, sparsity_out

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

Definition at line 987 of file function.cpp.

987  {
988  return (*this)->size1_out(ind);
989  }

Referenced by assert_size_out(), casadi::construct_nlpsol(), casadi::Call::create(), casadi::Blocksqp::init(), and casadi::Onnx::load().

◆ size1_out() [2/2]

casadi_int casadi::Function::size1_out ( const std::string &  oname) const
inline

Same conventions as size_in, size1_in and size2_in.

>>> x = SX.sym("x", 3)
>>> f = Function("f", [x], [x.T, SX(2, 2)])
>>> f.size_out(0), f.size_out("o1"), f.size1_out(0), f.size2_out(1)
((1, 3), (2, 2), 1, 2)

>> x = SX.sym('x', 3);
>> f = Function('f', {x}, {x', SX(2, 2)});
>> f.size_out(0), f.size_out('o1')
1 3
2 2
>> fprintf('%d %d\n', f.size1_out(0), f.size2_out(1))
1 2

julia> x = ca.SX.sym("x", 3);
julia> f = ca.Function("f", [x], [x', ca.SX(2, 2)]);
julia> ca.size_out(f, 0), ca.size_out(f, "o1"), ca.size1_out(f, 0), ca.size2_out(f, 1)
((1, 3), (2, 2), 1, 2)

See also
size_in, sparsity_out

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

Definition at line 912 of file function.hpp.

912 {return size1_out(index_out(oname));}

References size1_out().

Referenced by size1_out().

◆ size2_in() [1/2]

casadi_int casadi::Function::size2_in ( casadi_int  ind) const

size1_in is the number of rows, size2_in the number of columns and size_in the pair (rows, columns). The input is selected by index or by name; an unknown name raises an error listing the available names, an index out of range raises an error.

>>> f = Function("f", [SX.sym("A", 2, 3), SX.sym("b", 2)], [SX(0)], ["A", "b"], ["c"])
>>> f.size_in(0), f.size1_in("A"), f.size2_in("A")
((2, 3), 2, 3)
>>> f.size_in("b")
(2, 1)
>>> try:
...   f.size_in("nope")
... except RuntimeError as e:
...   print("Available names are: [A, b]" in str(e))
True

>> f = Function('f', {SX.sym('A', 2, 3), SX.sym('b', 2)}, {SX(0)}, {'A', 'b'}, {'c'});
>> disp(f.size_in(0)), fprintf('%d %d\n', f.size1_in('A'), f.size2_in('A'))
2 3
2 3
>> f.size_in('b')
2 1
>> try, f.size_in('nope'); catch e, disp(contains(e.message, 'Available names')); end
1

julia> A = ca.SX.sym("A", 2, 3); b = ca.SX.sym("b", 2);
julia> f = ca.Function("f", [A, b], [ca.SX(0)], ["A", "b"], ["c"]);
julia> ca.size_in(f, 0), ca.size1_in(f, "A"), ca.size2_in(f, "A")
((2, 3), 2, 3)
julia> ca.size_in(f, "b")
(2, 1)
julia> try
           ca.size_in(f, "nope")
       catch e
           println(occursin("Available names are: [A, b]", sprint(showerror, e)))
       end
true

See also
size_out, sparsity_in, nnz_in, numel_in

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

Definition at line 983 of file function.cpp.

983  {
984  return (*this)->size2_in(ind);
985  }

Referenced by assert_size_in(), casadi::FiniteDiff::get_sparsity_in(), map(), and mapaccum().

◆ size2_in() [2/2]

casadi_int casadi::Function::size2_in ( const std::string &  iname) const
inline

size1_in is the number of rows, size2_in the number of columns and size_in the pair (rows, columns). The input is selected by index or by name; an unknown name raises an error listing the available names, an index out of range raises an error.

>>> f = Function("f", [SX.sym("A", 2, 3), SX.sym("b", 2)], [SX(0)], ["A", "b"], ["c"])
>>> f.size_in(0), f.size1_in("A"), f.size2_in("A")
((2, 3), 2, 3)
>>> f.size_in("b")
(2, 1)
>>> try:
...   f.size_in("nope")
... except RuntimeError as e:
...   print("Available names are: [A, b]" in str(e))
True

>> f = Function('f', {SX.sym('A', 2, 3), SX.sym('b', 2)}, {SX(0)}, {'A', 'b'}, {'c'});
>> disp(f.size_in(0)), fprintf('%d %d\n', f.size1_in('A'), f.size2_in('A'))
2 3
2 3
>> f.size_in('b')
2 1
>> try, f.size_in('nope'); catch e, disp(contains(e.message, 'Available names')); end
1

julia> A = ca.SX.sym("A", 2, 3); b = ca.SX.sym("b", 2);
julia> f = ca.Function("f", [A, b], [ca.SX(0)], ["A", "b"], ["c"]);
julia> ca.size_in(f, 0), ca.size1_in(f, "A"), ca.size2_in(f, "A")
((2, 3), 2, 3)
julia> ca.size_in(f, "b")
(2, 1)
julia> try
           ca.size_in(f, "nope")
       catch e
           println(occursin("Available names are: [A, b]", sprint(showerror, e)))
       end
true

See also
size_out, sparsity_in, nnz_in, numel_in

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

Definition at line 866 of file function.hpp.

866 {return size2_in(index_in(iname));}

References size2_in().

Referenced by size2_in().

◆ size2_out() [1/2]

casadi_int casadi::Function::size2_out ( casadi_int  ind) const

Same conventions as size_in, size1_in and size2_in.

>>> x = SX.sym("x", 3)
>>> f = Function("f", [x], [x.T, SX(2, 2)])
>>> f.size_out(0), f.size_out("o1"), f.size1_out(0), f.size2_out(1)
((1, 3), (2, 2), 1, 2)

>> x = SX.sym('x', 3);
>> f = Function('f', {x}, {x', SX(2, 2)});
>> f.size_out(0), f.size_out('o1')
1 3
2 2
>> fprintf('%d %d\n', f.size1_out(0), f.size2_out(1))
1 2

julia> x = ca.SX.sym("x", 3);
julia> f = ca.Function("f", [x], [x', ca.SX(2, 2)]);
julia> ca.size_out(f, 0), ca.size_out(f, "o1"), ca.size1_out(f, 0), ca.size2_out(f, 1)
((1, 3), (2, 2), 1, 2)

See also
size_in, sparsity_out

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

Definition at line 991 of file function.cpp.

991  {
992  return (*this)->size2_out(ind);
993  }

Referenced by assert_size_out(), casadi::Call::create(), fold(), casadi::Onnx::load(), and map().

◆ size2_out() [2/2]

casadi_int casadi::Function::size2_out ( const std::string &  oname) const
inline

Same conventions as size_in, size1_in and size2_in.

>>> x = SX.sym("x", 3)
>>> f = Function("f", [x], [x.T, SX(2, 2)])
>>> f.size_out(0), f.size_out("o1"), f.size1_out(0), f.size2_out(1)
((1, 3), (2, 2), 1, 2)

>> x = SX.sym('x', 3);
>> f = Function('f', {x}, {x', SX(2, 2)});
>> f.size_out(0), f.size_out('o1')
1 3
2 2
>> fprintf('%d %d\n', f.size1_out(0), f.size2_out(1))
1 2

julia> x = ca.SX.sym("x", 3);
julia> f = ca.Function("f", [x], [x', ca.SX(2, 2)]);
julia> ca.size_out(f, 0), ca.size_out(f, "o1"), ca.size1_out(f, 0), ca.size2_out(f, 1)
((1, 3), (2, 2), 1, 2)

See also
size_in, sparsity_out

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

Definition at line 914 of file function.hpp.

914 {return size2_out(index_out(oname));}

References size2_out().

Referenced by size2_out().

◆ size_in() [1/2]

std::pair< casadi_int, casadi_int > casadi::Function::size_in ( casadi_int  ind) const

size1_in is the number of rows, size2_in the number of columns and size_in the pair (rows, columns). The input is selected by index or by name; an unknown name raises an error listing the available names, an index out of range raises an error.

>>> f = Function("f", [SX.sym("A", 2, 3), SX.sym("b", 2)], [SX(0)], ["A", "b"], ["c"])
>>> f.size_in(0), f.size1_in("A"), f.size2_in("A")
((2, 3), 2, 3)
>>> f.size_in("b")
(2, 1)
>>> try:
...   f.size_in("nope")
... except RuntimeError as e:
...   print("Available names are: [A, b]" in str(e))
True

>> f = Function('f', {SX.sym('A', 2, 3), SX.sym('b', 2)}, {SX(0)}, {'A', 'b'}, {'c'});
>> disp(f.size_in(0)), fprintf('%d %d\n', f.size1_in('A'), f.size2_in('A'))
2 3
2 3
>> f.size_in('b')
2 1
>> try, f.size_in('nope'); catch e, disp(contains(e.message, 'Available names')); end
1

julia> A = ca.SX.sym("A", 2, 3); b = ca.SX.sym("b", 2);
julia> f = ca.Function("f", [A, b], [ca.SX(0)], ["A", "b"], ["c"]);
julia> ca.size_in(f, 0), ca.size1_in(f, "A"), ca.size2_in(f, "A")
((2, 3), 2, 3)
julia> ca.size_in(f, "b")
(2, 1)
julia> try
           ca.size_in(f, "nope")
       catch e
           println(occursin("Available names are: [A, b]", sprint(showerror, e)))
       end
true

See also
size_out, sparsity_in, nnz_in, numel_in

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

Definition at line 995 of file function.cpp.

995  {
996  return (*this)->size_in(ind);
997  }

Referenced by casadi::blazing_spline(), casadi::DaeBuilderInternal::CallIO::calc_jac(), casadi::Integrator::get_forward(), casadi::Integrator::get_reverse(), and casadi::Nlpsol::init().

◆ size_in() [2/2]

std::pair<casadi_int, casadi_int> casadi::Function::size_in ( const std::string &  iname) const
inline

size1_in is the number of rows, size2_in the number of columns and size_in the pair (rows, columns). The input is selected by index or by name; an unknown name raises an error listing the available names, an index out of range raises an error.

>>> f = Function("f", [SX.sym("A", 2, 3), SX.sym("b", 2)], [SX(0)], ["A", "b"], ["c"])
>>> f.size_in(0), f.size1_in("A"), f.size2_in("A")
((2, 3), 2, 3)
>>> f.size_in("b")
(2, 1)
>>> try:
...   f.size_in("nope")
... except RuntimeError as e:
...   print("Available names are: [A, b]" in str(e))
True

>> f = Function('f', {SX.sym('A', 2, 3), SX.sym('b', 2)}, {SX(0)}, {'A', 'b'}, {'c'});
>> disp(f.size_in(0)), fprintf('%d %d\n', f.size1_in('A'), f.size2_in('A'))
2 3
2 3
>> f.size_in('b')
2 1
>> try, f.size_in('nope'); catch e, disp(contains(e.message, 'Available names')); end
1

julia> A = ca.SX.sym("A", 2, 3); b = ca.SX.sym("b", 2);
julia> f = ca.Function("f", [A, b], [ca.SX(0)], ["A", "b"], ["c"]);
julia> ca.size_in(f, 0), ca.size1_in(f, "A"), ca.size2_in(f, "A")
((2, 3), 2, 3)
julia> ca.size_in(f, "b")
(2, 1)
julia> try
           ca.size_in(f, "nope")
       catch e
           println(occursin("Available names are: [A, b]", sprint(showerror, e)))
       end
true

See also
size_out, sparsity_in, nnz_in, numel_in

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

Definition at line 868 of file function.hpp.

868  {
869  return size_in(index_in(iname));
870  }
std::pair< casadi_int, casadi_int > size_in(casadi_int ind) const
Get the shape of an input: rows, columns or both.
Definition: function.cpp:995

◆ size_out() [1/2]

std::pair< casadi_int, casadi_int > casadi::Function::size_out ( casadi_int  ind) const

Same conventions as size_in, size1_in and size2_in.

>>> x = SX.sym("x", 3)
>>> f = Function("f", [x], [x.T, SX(2, 2)])
>>> f.size_out(0), f.size_out("o1"), f.size1_out(0), f.size2_out(1)
((1, 3), (2, 2), 1, 2)

>> x = SX.sym('x', 3);
>> f = Function('f', {x}, {x', SX(2, 2)});
>> f.size_out(0), f.size_out('o1')
1 3
2 2
>> fprintf('%d %d\n', f.size1_out(0), f.size2_out(1))
1 2

julia> x = ca.SX.sym("x", 3);
julia> f = ca.Function("f", [x], [x', ca.SX(2, 2)]);
julia> ca.size_out(f, 0), ca.size_out(f, "o1"), ca.size1_out(f, 0), ca.size2_out(f, 1)
((1, 3), (2, 2), 1, 2)

See also
size_in, sparsity_out

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

Definition at line 999 of file function.cpp.

999  {
1000  return (*this)->size_out(ind);
1001  }

Referenced by casadi::DaeBuilderInternal::CallIO::calc_jac(), casadi::SqicInterface::generateNativeCode(), casadi::FunctionInternal::get_sparsity_in(), and casadi::SqicInterface::init().

◆ size_out() [2/2]

std::pair<casadi_int, casadi_int> casadi::Function::size_out ( const std::string &  oname) const
inline

Same conventions as size_in, size1_in and size2_in.

>>> x = SX.sym("x", 3)
>>> f = Function("f", [x], [x.T, SX(2, 2)])
>>> f.size_out(0), f.size_out("o1"), f.size1_out(0), f.size2_out(1)
((1, 3), (2, 2), 1, 2)

>> x = SX.sym('x', 3);
>> f = Function('f', {x}, {x', SX(2, 2)});
>> f.size_out(0), f.size_out('o1')
1 3
2 2
>> fprintf('%d %d\n', f.size1_out(0), f.size2_out(1))
1 2

julia> x = ca.SX.sym("x", 3);
julia> f = ca.Function("f", [x], [x', ca.SX(2, 2)]);
julia> ca.size_out(f, 0), ca.size_out(f, "o1"), ca.size1_out(f, 0), ca.size2_out(f, 1)
((1, 3), (2, 2), 1, 2)

See also
size_in, sparsity_out

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

Definition at line 916 of file function.hpp.

916  {
917  return size_out(index_out(oname));
918  }
std::pair< casadi_int, casadi_int > size_out(casadi_int ind) const
Get the shape of an output: rows, columns or both.
Definition: function.cpp:999

◆ slice()

Function casadi::Function::slice ( const std::string &  name,
const std::vector< casadi_int > &  order_in,
const std::vector< casadi_int > &  order_out,
const Dict &  opts = Dict() 
) const

The expressions are unchanged; only the lists of inputs and outputs are rearranged. Indices may be repeated or omitted. An omitted input that an output depends on makes the result have free variables (construction then fails unless "allow_free" is in opts). Classes other than SXFunction and MXFunction are wrapped first.

Parameters
nameName of the result
order_inIndices of the original inputs to keep, in the new order
order_outIndices of the original outputs to keep, in the new order
optsOptions for the new function

>>> x = SX.sym("x"); y = SX.sym("y")
>>> f = Function("f", [x, y], [x + y, x - y, 2*x], ["x", "y"], ["a", "b", "c"])
>>> g = f.slice("g", [1, 0], [2, 0])
>>> g, g(1, 2)
(Function(g:(y,x)->(c,a) SXFunction), (DM(4), DM(3)))
>>> f.slice("h", [0], [2])
Function(h:(x)->(c) SXFunction)

>> x = SX.sym('x'); y = SX.sym('y');
>> f = Function('f', {x, y}, {x + y, x - y, 2*x}, {'x', 'y'}, {'a', 'b', 'c'});
>> g = f.slice('g', [1, 0], [2, 0]); disp(g)
g:(y,x)->(c,a) SXFunction
>> [c, a] = g(1, 2); disp(c), disp(a)
4
3
>> f.slice('h', 0, 2)
h:(x)->(c) SXFunction

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y");
julia> f = ca.Function("f", [x, y], [x + y, x - y, 2x], ["x", "y"], ["a", "b", "c"]);
julia> g = ca.slice(f, "g", [1, 0], [2, 0]);
julia> println(g); g(1, 2)
g:(y,x)->(c,a) SXFunction
(4, 3)
julia> ca.slice(f, "h", [0], [2])
Function(h:(x)->(c) SXFunction)

See also
factory

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

Definition at line 898 of file function.cpp.

900  {
901  try {
902  return (*this)->slice(name, order_in, order_out, opts);
903  } catch(std::exception& e) {
904  THROW_ERROR("slice", e.what());
905  }
906  }

References name(), and casadi::FunctionInternal::slice().

Referenced by mapaccum(), and casadi::FunctionInternal::slice().

◆ sparsity_in() [1/2]

const Sparsity & casadi::Function::sparsity_in ( casadi_int  ind) const

Numerical arguments are projected onto this pattern before evaluation: entries outside it are dropped silently. Symbolic inputs keep the pattern of the expression passed to the constructor.

>>> f = Function("f", [SX.sym("D", Sparsity.diag(2))], [SX(0)], ["D"], ["r"])
>>> f.sparsity_in(0)
Sparsity(2x2,2nz)
>>> f.sparsity_in("D").is_diag()
True
>>> f.sparsity_out(0)
Sparsity(1x1)

>> f = Function('f', {SX.sym('D', Sparsity.diag(2))}, {SX(0)}, {'D'}, {'r'});
>> f.sparsity_in(0)
2x2,2nz
>> f.sparsity_in('D').is_diag()
1
>> f.sparsity_out(0)
1x1

julia> D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [D], [ca.SX(0)], ["D"], ["r"]);
julia> ca.sparsity_in(f, 0)
Sparsity(2x2,2nz)
julia> ca.is_diag(ca.sparsity_in(f, "D"))
true
julia> ca.sparsity_out(f, 0)
Sparsity(1x1)

See also
sparsity_out, size_in, nnz_in

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

Definition at line 1167 of file function.cpp.

1167  {
1168  try {
1169  return (*this)->sparsity_in_.at(ind);
1170  } catch(std::exception& e) {
1171  THROW_ERROR("sparsity_in", e.what());
1172  }
1173  }

Referenced by casadi::Call::Call(), casadi::Switch::codegen_body(), casadi::SXFunction::eval_mx(), casadi::Switch::eval_sx(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::Integrator::get_forward_dae(), casadi::FunctionInternal::get_sparsity_in(), casadi::FiniteDiff::get_sparsity_in(), casadi::Nlpsol::get_sparsity_in(), casadi::Switch::get_sparsity_in(), casadi::FunctionInternal::get_sparsity_out(), casadi::Nlpsol::get_sparsity_out(), casadi::Rootfinder::get_sparsity_out(), casadi::Onnx::import_symbolic(), casadi::Integrator::init(), casadi::Nlpsol::init(), casadi::Rootfinder::init(), casadi::Switch::init(), jit(), casadi::RuntimeIntegrator::jump_function(), casadi::Onnx::load(), map(), casadi::Collocation::setup_step(), casadi::RungeKutta::setup_step(), casadi::simpleIntegrator(), casadi::simpleIRK(), casadi::simpleRK(), sparsity_in(), and casadi::OnnxFunction::wrap_derivative().

◆ sparsity_in() [2/2]

const Sparsity & casadi::Function::sparsity_in ( const std::string &  iname) const

Numerical arguments are projected onto this pattern before evaluation: entries outside it are dropped silently. Symbolic inputs keep the pattern of the expression passed to the constructor.

>>> f = Function("f", [SX.sym("D", Sparsity.diag(2))], [SX(0)], ["D"], ["r"])
>>> f.sparsity_in(0)
Sparsity(2x2,2nz)
>>> f.sparsity_in("D").is_diag()
True
>>> f.sparsity_out(0)
Sparsity(1x1)

>> f = Function('f', {SX.sym('D', Sparsity.diag(2))}, {SX(0)}, {'D'}, {'r'});
>> f.sparsity_in(0)
2x2,2nz
>> f.sparsity_in('D').is_diag()
1
>> f.sparsity_out(0)
1x1

julia> D = ca.SX.sym("D", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [D], [ca.SX(0)], ["D"], ["r"]);
julia> ca.sparsity_in(f, 0)
Sparsity(2x2,2nz)
julia> ca.is_diag(ca.sparsity_in(f, "D"))
true
julia> ca.sparsity_out(f, 0)
Sparsity(1x1)

See also
sparsity_out, size_in, nnz_in

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

Definition at line 1175 of file function.cpp.

1175  {
1176  try {
1177  return sparsity_in(index_in(iname));
1178  } catch(std::exception& e) {
1179  THROW_ERROR("sparsity_in", e.what());
1180  }
1181  }

References index_in(), and sparsity_in().

◆ sparsity_jac() [1/4]

const Sparsity casadi::Function::sparsity_jac ( casadi_int  iind,
casadi_int  oind,
bool  compact = false,
bool  symmetric = false 
) const

[DEPRECATED] Sparsity of the Jacobian of output oind w.r.t. input iind; use jac_sparsity(oind, iind) (note the reversed argument order)

Definition at line 1058 of file function.cpp.

1059  {
1060  try {
1061  return (*this)->jac_sparsity(oind, iind, compact, symmetric);
1062  } catch(std::exception& e) {
1063  THROW_ERROR("sparsity_jac", e.what());
1064  }
1065  }

Referenced by casadi::Blocksqp::init(), and casadi::ConoptInterface::init().

◆ sparsity_jac() [2/4]

const Sparsity casadi::Function::sparsity_jac ( casadi_int  iind,
const std::string &  oind,
bool  compact = false,
bool  symmetric = false 
) const
inline

[DEPRECATED] Sparsity of the Jacobian of output oind w.r.t. input iind; use jac_sparsity(oind, iind) (note the reversed argument order)

Definition at line 2143 of file function.hpp.

2144  {
2145  return sparsity_jac(iind, index_out(oind), compact, symmetric);
2146  }
const Sparsity sparsity_jac(casadi_int iind, casadi_int oind, bool compact=false, bool symmetric=false) const
Definition: function.cpp:1059

◆ sparsity_jac() [3/4]

const Sparsity casadi::Function::sparsity_jac ( const std::string &  iind,
casadi_int  oind = 0,
bool  compact = false,
bool  symmetric = false 
) const
inline

[DEPRECATED] Sparsity of the Jacobian of output oind w.r.t. input iind; use jac_sparsity(oind, iind) (note the reversed argument order)

Definition at line 2139 of file function.hpp.

2140  {
2141  return sparsity_jac(index_in(iind), oind, compact, symmetric);
2142  }

◆ sparsity_jac() [4/4]

const Sparsity casadi::Function::sparsity_jac ( const std::string &  iind,
const std::string &  oind,
bool  compact = false,
bool  symmetric = false 
) const
inline

[DEPRECATED] Sparsity of the Jacobian of output oind w.r.t. input iind; use jac_sparsity(oind, iind) (note the reversed argument order)

Definition at line 2147 of file function.hpp.

2148  {
2149  return sparsity_jac(index_in(iind), index_out(oind), compact, symmetric);
2150  }

◆ sparsity_out() [1/2]

const Sparsity & casadi::Function::sparsity_out ( casadi_int  ind) const

Results of a numerical call are DM objects with exactly this pattern.

See also
sparsity_in, size_out, nnz_out

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

Definition at line 1183 of file function.cpp.

1183  {
1184  try {
1185  return (*this)->sparsity_out_.at(ind);
1186  } catch(std::exception& e) {
1187  THROW_ERROR("sparsity_out", e.what());
1188  }
1189  }

Referenced by assert_sparsity_out(), casadi::OracleFunction::calc_function(), casadi::Switch::codegen_body(), conditional(), casadi::Switch::eval_sx(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::Integrator::get_forward_dae(), casadi::FunctionInternal::get_sparsity_in(), casadi::FiniteDiff::get_sparsity_in(), casadi::FunctionInternal::get_sparsity_out(), casadi::FiniteDiff::get_sparsity_out(), casadi::Nlpsol::get_sparsity_out(), casadi::Rootfinder::get_sparsity_out(), casadi::Switch::get_sparsity_out(), casadi::Integrator::init(), casadi::Nlpsol::init(), casadi::Rootfinder::init(), casadi::RuntimeIntegrator::init(), casadi::Switch::init(), casadi::ConoptInterface::init(), casadi::KnitroInterface::init(), casadi::SnoptInterface::init(), casadi::SundialsInterface::init(), casadi::SuperscsInterface::init(), casadi::UnoInterface::init(), casadi::Qrsqp::init(), casadi::Scpgen::init(), casadi::SuperscsInterface::init_mem(), jac_sparsity(), jit(), casadi::Onnx::load(), casadi::IdasInterface::psetupF(), casadi::Call::sparsity(), sparsity_out(), and casadi::OnnxFunction::wrap_derivative().

◆ sparsity_out() [2/2]

const Sparsity & casadi::Function::sparsity_out ( const std::string &  iname) const

Results of a numerical call are DM objects with exactly this pattern.

See also
sparsity_in, size_out, nnz_out

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

Definition at line 1191 of file function.cpp.

1191  {
1192  try {
1193  return sparsity_out(index_out(iname));
1194  } catch(std::exception& e) {
1195  THROW_ERROR("sparsity_out", e.what());
1196  }
1197  }

References index_out(), and sparsity_out().

◆ stats()

Dict casadi::Function::stats ( int  mem = 0) const

The content depends on the class: solvers report e.g. "success", "return_status", "iter_count"; with option "record_time" every function reports "t_wall_total", "t_proc_total" and "n_call_total". Raises an error when the function has not been evaluated numerically yet.

Parameters
memMemory object (from checkout) whose statistics to return; 0 is the memory used by ordinary calls

>>> x = SX.sym("x")
>>> f = Function("f", [x], [x**2], {"record_time": True})
>>> try:
...   f.stats()
... except RuntimeError as e:
...   print("first evaluate it numerically" in str(e))
True
>>> r = f(2)
>>> sorted(f.stats().keys())
['n_call_total', 't_proc_total', 't_wall_total']

>> x = SX.sym('x');
>> f = Function('f', {x}, {x^2}, struct('record_time', true));
>> try, f.stats(); catch e, disp(contains(e.message, 'first evaluate it numerically')); end
1
>> r = f(2); disp(strjoin(sort(fieldnames(f.stats()))', ' '))
n_call_total t_proc_total t_wall_total

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [x^2], Dict("record_time" => true));
julia> try
           ca.stats(f)
       catch e
           println(occursin("first evaluate it numerically", sprint(showerror, e)))
       end
true
julia> r = f(2);
julia> sort(collect(keys(ca.stats(f))))
3-element Vector{String}:
 "n_call_total"
 "t_proc_total"
 "t_wall_total"

See also
checkout

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

Definition at line 1080 of file function.cpp.

1080  {
1081  if (!(*this)->has_memory(mem)) {
1082  THROW_ERROR("stats",
1083  "No stats available: Function/solver was not yet numerically evaluated.");
1084  }
1085  try {
1086  return (*this)->get_stats(memory(mem));
1087  } catch(std::exception& e) {
1088  THROW_ERROR("stats", e.what());
1089  }
1090  }

References memory().

Referenced by casadi::DaeBuilder::get(), casadi::MXFunction::get_stats(), casadi::ImplicitToNlp::get_stats(), casadi::FunctionBuffer::stats(), and casadi::OptiNode::stats().

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

◆ sx_in() [1/3]

const std::vector< SX > casadi::Function::sx_in ( ) const

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

Definition at line 1765 of file function.cpp.

1765  {
1766  try {
1767  return (*this)->sx_in();
1768  } catch(std::exception& e) {
1769  THROW_ERROR("sx_in", e.what());
1770  }
1771  }

Referenced by expand(), and sym_in().

◆ sx_in() [2/3]

const SX casadi::Function::sx_in ( casadi_int  iind) const

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

Definition at line 1749 of file function.cpp.

1749  {
1750  try {
1751  return (*this)->sx_in(iind);
1752  } catch(std::exception& e) {
1753  THROW_ERROR("sx_in", e.what());
1754  }
1755  }

Referenced by casadi::Matrix< Scalar >::get_input(), casadi::AmplInterface::init(), casadi::qpsol_nlp(), and transform().

◆ sx_in() [3/3]

const SX casadi::Function::sx_in ( const std::string &  iname) const
inline

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

Definition at line 3934 of file function.hpp.

3934  {
3935  return sx_in(index_in(iname));
3936  }

◆ sx_out() [1/3]

const std::vector< SX > casadi::Function::sx_out ( ) const

Useful as adjoint seeds or placeholders; see sx_in.

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

Definition at line 1773 of file function.cpp.

1773  {
1774  try {
1775  return (*this)->sx_out();
1776  } catch(std::exception& e) {
1777  THROW_ERROR("sx_out", e.what());
1778  }
1779  }

◆ sx_out() [2/3]

const SX casadi::Function::sx_out ( casadi_int  oind) const

Useful as adjoint seeds or placeholders; see sx_in.

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

Definition at line 1757 of file function.cpp.

1757  {
1758  try {
1759  return (*this)->sx_out(oind);
1760  } catch(std::exception& e) {
1761  THROW_ERROR("sx_out", e.what());
1762  }
1763  }

◆ sx_out() [3/3]

const SX casadi::Function::sx_out ( const std::string &  oname) const
inline

Useful as adjoint seeds or placeholders; see sx_in.

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

Definition at line 3962 of file function.hpp.

3962  {
3963  return sx_out(index_out(oname));
3964  }
const std::vector< SX > sx_out() const
Create fresh symbols with the names and sparsity patterns of the outputs.
Definition: function.cpp:1773

◆ sym_in() [1/5]

template<>
const std::vector< MX > CASADI_EXPORT casadi::Function::sym_in ( ) const

Definition at line 2246 of file function.cpp.

2246  {
2247  return sx_in();
2248  }

References sx_in().

◆ sym_in() [2/5]

template<typename T >
const std::vector<T> casadi::Function::sym_in ( ) const

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

◆ sym_in() [3/5]

template<>
const MX CASADI_EXPORT casadi::Function::sym_in ( casadi_int  iind) const

Definition at line 2237 of file function.cpp.

2237  {
2238  return sx_in(iind);
2239  }

References sx_in().

◆ sym_in() [4/5]

template<typename T >
const T casadi::Function::sym_in ( casadi_int  iind) const

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

References casadi::T.

Referenced by casadi::construct_nlpsol().

◆ sym_in() [5/5]

template<typename T >
const T casadi::Function::sym_in ( const std::string &  iname) const
inline

Convenient for calling the function symbolically or for building a wrapper: f(f.mx_in()) is an MX expression of the outputs. Each call creates new symbols; they are not the symbols the function was constructed from. All inputs (no argument), one by index, or one by name.

>>> f = Function("f", [SX.sym("a"), SX.sym("B", Sparsity.diag(2))], [SX(0)],
...              ["a", "B"], ["r"])
>>> f.sx_in()
[SX(a), SX(
[[B_0, 00],
 [00, B_1]])]
>>> f.mx_in(1), f.mx_in("a").shape
(MX(B), (1, 1))
>>> f.sx_out(), f.mx_out(0)
([SX(r)], MX(r))

>> a = SX.sym('a'); B = SX.sym('B', Sparsity.diag(2));
>> f = Function('f', {a, B}, {SX(0)}, {'a', 'B'}, {'r'});
>> in = f.sx_in(); disp(in{1}), disp(in{2})
a
[[B_0, 00],
 [00, B_1]]
>> f.mx_in(1), size(f.mx_in('a'))
B
1 1
>> out = f.sx_out(); disp(out{1}), disp(f.mx_out(0))
r
r

julia> a = ca.SX.sym("a"); B = ca.SX.sym("B", ca.Sparsity.diag(2));
julia> f = ca.Function("f", [a, B], [ca.SX(0)], ["a", "B"], ["r"]);
julia> a_in, B_in = ca.sx_in(f);
julia> a_in
SX(a)
julia> B_in
SX(
[[B_0, 00],
 [00, B_1]])
julia> ca.mx_in(f, 1), size(ca.mx_in(f, "a"))
(B, (1, 1))
julia> ca.sx_out(f), ca.mx_out(f, 0)
(SX[r], r)

See also
sx_out, mx_out, sparsity_in

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

Definition at line 3947 of file function.hpp.

3947  {
3948  return sym_in<T>(index_in(iname));
3949  }

References casadi::T.

◆ sz_arg()

size_t casadi::Function::sz_arg ( ) const

sz_arg, sz_res, sz_iw and sz_w are the sizes of the arg, res, iw and w arrays of the low-level evaluation interface used by generated code and FunctionBuffer.

>>> f = Function("f", [SX.sym("x"), SX.sym("y")], [SX(0)])
>>> f.sz_arg(), f.sz_res(), f.sz_iw(), f.sz_w()
(2, 1, 0, 1)

>> f = Function('f', {SX.sym('x'), SX.sym('y')}, {SX(0)});
>> fprintf('%d %d %d %d\n', f.sz_arg(), f.sz_res(), f.sz_iw(), f.sz_w())
2 1 0 1

julia> f = ca.Function("f", [ca.SX.sym("x"), ca.SX.sym("y")], [ca.SX(0)]);
julia> ca.sz_arg(f), ca.sz_res(f), ca.sz_iw(f), ca.sz_w(f)
(2, 1, 0, 1)

See also
sz_res, sz_iw, sz_w, FunctionBuffer

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

Definition at line 1235 of file function.cpp.

1235 { return (*this)->sz_arg();}

Referenced by activity(), casadi::SymbolicQrMemory::alloc(), buf_in(), call_gen(), casadi::Nlpsol::codegen_setup_constants(), casadi::Blocksqp::feasibilityRestorationPhase(), casadi::FunctionBuffer::FunctionBuffer(), casadi::Map::init(), casadi::OmpMap::init(), casadi::ThreadMap::init(), casadi::MapSum::init(), casadi::SXFunction::init(), casadi::BSplineInterpolant::init(), casadi::GurobiInterface::init_mem(), rev(), casadi::MX::simplify_const_folding(), casadi::Call::sz_arg(), and sz_work().

◆ sz_iw()

size_t casadi::Function::sz_iw ( ) const

◆ sz_res()

size_t casadi::Function::sz_res ( ) const

◆ sz_w()

size_t casadi::Function::sz_w ( ) const

◆ sz_work()

void casadi::Function::sz_work ( size_t &  sz_arg,
size_t &  sz_res,
size_t &  sz_iw,
size_t &  sz_w 
) const

◆ test_cast()

bool casadi::Function::test_cast ( const SharedObjectInternal *  ptr)
static

Definition at line 1076 of file function.cpp.

1076  {
1077  return dynamic_cast<const FunctionInternal*>(ptr)!=nullptr;
1078  }

◆ transform() [1/4]

Function casadi::Function::transform ( const Dict &  opts = Dict()) const

Only defined for SXFunction and MXFunction. The result has the same signature, names and options; only the expression graph differs.

The dict form runs a single "simplify" pass whose tasks are selected with boolean options, all defaulting to on except combine_terms:

  • empty_inputs: an input whose symbols do not occur in any output is replaced by an all-zero sparse matrix of the same shape (its nnz becomes 0)
  • cse: common subexpression elimination
  • ref_count: drop unreferenced nodes, repeated until a fixed point
  • const_folding: evaluate constant subexpressions
  • combine_terms: merge like terms of sums

Unknown keys raise an error.

The passes form runs an explicit list of passes in order. Each pass is a list whose first entry is the verb:

  • ["simplify", task, ...] with tasks from the list above; an integer before a task is its run count (N>0: N times, 0: until the graph stops shrinking)
  • ["expand"]: expand to an SXFunction
  • ["external", library, operation] or [..., opts]: a transform from a plugin library

Here opts accepts only "verbose"; passing the boolean task options raises an error. With "verbose": true the node and instruction counts after each pass are printed.

Parameters
fnameName of the result; defaults to the current name
passesExplicit list of passes
optsDict form: task booleans and "verbose"; passes form: "verbose" only

>>> z = MX.sym("z"); w = MX.sym("w")
>>> f = Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"])
>>> f, f.n_instructions()
(Function(f:(z,w)->(r) MXFunction), 9)
>>> g = f.transform()
>>> g, g.n_instructions()
(Function(f:(z,w[1x1,0nz])->(r) MXFunction), 6)
>>> f.transform([["simplify", "cse"]]).n_instructions()
6
>>> f.transform("fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
>>> try:
...   f.transform([["nope"]])
... except RuntimeError as e:
...   print("unknown pass verb" in str(e))
True

>> z = MX.sym('z'); w = MX.sym('w');
>> f = Function('f', {z, w}, {sin(z)*cos(z) + sin(z)*cos(z)}, {'z', 'w'}, {'r'});
>> f, f.n_instructions()
f:(z,w)->(r) MXFunction
9
>> g = f.transform(); disp(g), disp(g.n_instructions())
f:(z,w[1x1,0nz])->(r) MXFunction
6
>> f.transform({{'simplify', 'cse'}}).n_instructions()
6
>> f.transform('fe', {{'expand'}})
fe:(z,w)->(r) SXFunction
>> try, f.transform({{'nope'}}); catch e, disp(contains(e.message, 'unknown pass')); end
1

julia> z = ca.MX.sym("z"); w = ca.MX.sym("w");
julia> f = ca.Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"]);
julia> println(f); ca.n_instructions(f)
f:(z,w)->(r) MXFunction
9
julia> g = ca.transform(f);
julia> println(g); ca.n_instructions(g)
f:(z,w[1x1,0nz])->(r) MXFunction
6
julia> ca.n_instructions(ca.transform(f, [["simplify", "cse"]]))
6
julia> ca.transform(f, "fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
julia> try
           ca.transform(f, [["nope"]])
       catch e
           println(occursin("unknown pass verb", sprint(showerror, e)))
       end
true

See also
expand

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

Definition at line 359 of file function.cpp.

359  {
360  return transform(name(), opts);
361  }
Function transform(const Dict &opts=Dict()) const
Rebuild the function after graph simplification or other passes.
Definition: function.cpp:359

References name().

Referenced by transform(), and casadi::MX::transform().

◆ transform() [2/4]

Function casadi::Function::transform ( const std::string &  fname,
const Dict &  opts = Dict() 
) const

Only defined for SXFunction and MXFunction. The result has the same signature, names and options; only the expression graph differs.

The dict form runs a single "simplify" pass whose tasks are selected with boolean options, all defaulting to on except combine_terms:

  • empty_inputs: an input whose symbols do not occur in any output is replaced by an all-zero sparse matrix of the same shape (its nnz becomes 0)
  • cse: common subexpression elimination
  • ref_count: drop unreferenced nodes, repeated until a fixed point
  • const_folding: evaluate constant subexpressions
  • combine_terms: merge like terms of sums

Unknown keys raise an error.

The passes form runs an explicit list of passes in order. Each pass is a list whose first entry is the verb:

  • ["simplify", task, ...] with tasks from the list above; an integer before a task is its run count (N>0: N times, 0: until the graph stops shrinking)
  • ["expand"]: expand to an SXFunction
  • ["external", library, operation] or [..., opts]: a transform from a plugin library

Here opts accepts only "verbose"; passing the boolean task options raises an error. With "verbose": true the node and instruction counts after each pass are printed.

Parameters
fnameName of the result; defaults to the current name
passesExplicit list of passes
optsDict form: task booleans and "verbose"; passes form: "verbose" only

>>> z = MX.sym("z"); w = MX.sym("w")
>>> f = Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"])
>>> f, f.n_instructions()
(Function(f:(z,w)->(r) MXFunction), 9)
>>> g = f.transform()
>>> g, g.n_instructions()
(Function(f:(z,w[1x1,0nz])->(r) MXFunction), 6)
>>> f.transform([["simplify", "cse"]]).n_instructions()
6
>>> f.transform("fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
>>> try:
...   f.transform([["nope"]])
... except RuntimeError as e:
...   print("unknown pass verb" in str(e))
True

>> z = MX.sym('z'); w = MX.sym('w');
>> f = Function('f', {z, w}, {sin(z)*cos(z) + sin(z)*cos(z)}, {'z', 'w'}, {'r'});
>> f, f.n_instructions()
f:(z,w)->(r) MXFunction
9
>> g = f.transform(); disp(g), disp(g.n_instructions())
f:(z,w[1x1,0nz])->(r) MXFunction
6
>> f.transform({{'simplify', 'cse'}}).n_instructions()
6
>> f.transform('fe', {{'expand'}})
fe:(z,w)->(r) SXFunction
>> try, f.transform({{'nope'}}); catch e, disp(contains(e.message, 'unknown pass')); end
1

julia> z = ca.MX.sym("z"); w = ca.MX.sym("w");
julia> f = ca.Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"]);
julia> println(f); ca.n_instructions(f)
f:(z,w)->(r) MXFunction
9
julia> g = ca.transform(f);
julia> println(g); ca.n_instructions(g)
f:(z,w[1x1,0nz])->(r) MXFunction
6
julia> ca.n_instructions(ca.transform(f, [["simplify", "cse"]]))
6
julia> ca.transform(f, "fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
julia> try
           ca.transform(f, [["nope"]])
       catch e
           println(occursin("unknown pass verb", sprint(showerror, e)))
       end
true

See also
expand

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

Definition at line 363 of file function.cpp.

363  {
364  try {
365  // Boolean shorthands (defaults reproduce the meaningful default flow)
366  bool empty_inputs = true;
367  bool combine_terms = false;
368  bool cse = true;
369  bool ref_count = true;
370  bool const_folding = true;
371  bool verbose = false;
372  for (auto&& op : opts) {
373  if (op.first=="empty_inputs") {
374  empty_inputs = op.second;
375  } else if (op.first=="combine_terms") {
376  combine_terms = op.second;
377  } else if (op.first=="cse") {
378  cse = op.second;
379  } else if (op.first=="ref_count") {
380  ref_count = op.second;
381  } else if (op.first=="const_folding") {
382  const_folding = op.second;
383  } else if (op.first=="verbose") {
384  verbose = op.second;
385  } else {
386  casadi_error("transform: no such option: " + std::string(op.first) + ".\n");
387  }
388  }
389  std::vector<GenericType> simp = {std::string("simplify")};
390  if (empty_inputs) simp.push_back("empty_inputs");
391  if (combine_terms) simp.push_back("combine_terms");
392  if (cse) simp.push_back("cse");
393  if (ref_count) { simp.push_back(0); simp.push_back("ref_count"); } // 0 = fixed point
394  if (const_folding) simp.push_back("const_folding");
395  return transform(fname, std::vector<std::vector<GenericType> >{simp}, {{"verbose", verbose}});
396  } catch(std::exception& e) {
397  THROW_ERROR("transform", e.what());
398  }
399  }

References transform().

◆ transform() [3/4]

Function casadi::Function::transform ( const std::string &  fname,
const std::vector< std::vector< GenericType > > &  passes,
const Dict &  opts = Dict() 
) const

Only defined for SXFunction and MXFunction. The result has the same signature, names and options; only the expression graph differs.

The dict form runs a single "simplify" pass whose tasks are selected with boolean options, all defaulting to on except combine_terms:

  • empty_inputs: an input whose symbols do not occur in any output is replaced by an all-zero sparse matrix of the same shape (its nnz becomes 0)
  • cse: common subexpression elimination
  • ref_count: drop unreferenced nodes, repeated until a fixed point
  • const_folding: evaluate constant subexpressions
  • combine_terms: merge like terms of sums

Unknown keys raise an error.

The passes form runs an explicit list of passes in order. Each pass is a list whose first entry is the verb:

  • ["simplify", task, ...] with tasks from the list above; an integer before a task is its run count (N>0: N times, 0: until the graph stops shrinking)
  • ["expand"]: expand to an SXFunction
  • ["external", library, operation] or [..., opts]: a transform from a plugin library

Here opts accepts only "verbose"; passing the boolean task options raises an error. With "verbose": true the node and instruction counts after each pass are printed.

Parameters
fnameName of the result; defaults to the current name
passesExplicit list of passes
optsDict form: task booleans and "verbose"; passes form: "verbose" only

>>> z = MX.sym("z"); w = MX.sym("w")
>>> f = Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"])
>>> f, f.n_instructions()
(Function(f:(z,w)->(r) MXFunction), 9)
>>> g = f.transform()
>>> g, g.n_instructions()
(Function(f:(z,w[1x1,0nz])->(r) MXFunction), 6)
>>> f.transform([["simplify", "cse"]]).n_instructions()
6
>>> f.transform("fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
>>> try:
...   f.transform([["nope"]])
... except RuntimeError as e:
...   print("unknown pass verb" in str(e))
True

>> z = MX.sym('z'); w = MX.sym('w');
>> f = Function('f', {z, w}, {sin(z)*cos(z) + sin(z)*cos(z)}, {'z', 'w'}, {'r'});
>> f, f.n_instructions()
f:(z,w)->(r) MXFunction
9
>> g = f.transform(); disp(g), disp(g.n_instructions())
f:(z,w[1x1,0nz])->(r) MXFunction
6
>> f.transform({{'simplify', 'cse'}}).n_instructions()
6
>> f.transform('fe', {{'expand'}})
fe:(z,w)->(r) SXFunction
>> try, f.transform({{'nope'}}); catch e, disp(contains(e.message, 'unknown pass')); end
1

julia> z = ca.MX.sym("z"); w = ca.MX.sym("w");
julia> f = ca.Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"]);
julia> println(f); ca.n_instructions(f)
f:(z,w)->(r) MXFunction
9
julia> g = ca.transform(f);
julia> println(g); ca.n_instructions(g)
f:(z,w[1x1,0nz])->(r) MXFunction
6
julia> ca.n_instructions(ca.transform(f, [["simplify", "cse"]]))
6
julia> ca.transform(f, "fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
julia> try
           ca.transform(f, [["nope"]])
       catch e
           println(occursin("unknown pass verb", sprint(showerror, e)))
       end
true

See also
expand

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

Definition at line 406 of file function.cpp.

408  {
409  try {
410  // Only 'verbose' is accepted here; boolean simplify options belong to the
411  // dict-only overload
412  bool verbose = false;
413  for (auto&& op : opts) {
414  if (op.first=="verbose") {
415  verbose = op.second;
416  } else {
417  casadi_error("transform(passes, opts): unsupported option '" + std::string(op.first)
418  + "' (boolean simplify options are only allowed in the dict-only form).\n");
419  }
420  }
421 
422  if (verbose) {
423  uout() << "transform(" << transform_passes_str(passes) << ")" << std::endl;
424  uout() << " start: " << transform_stats(*this) << std::endl;
425  }
426 
427  // Run the pipeline
428  Function f = *this;
429  for (const auto& pass : passes) {
430  casadi_assert(!pass.empty(), "transform: each pass must be a non-empty list");
431  std::string verb = pass.front().to_string();
432  if (verb=="simplify") {
433  // Tasks are strings; an optional integer before a task sets its run
434  // count (N>0: run N times, 0: run until a fixed point). Default: 1.
435  std::vector<std::pair<std::string, casadi_int> > tasks;
436  casadi_int count = 1;
437  bool have_count = false;
438  for (size_t i=1; i<pass.size(); ++i) {
439  if (pass[i].is_int()) {
440  count = pass[i].to_int();
441  have_count = true;
442  } else {
443  tasks.push_back({pass[i].to_string(), count});
444  count = 1;
445  have_count = false;
446  }
447  }
448  casadi_assert(!have_count,
449  "transform 'simplify': trailing run count with no following task");
450  f = f->simplify_passes(tasks);
451  } else if (verb=="expand") {
452  casadi_assert(pass.size()==1, "transform: 'expand' pass takes no arguments");
453  f = f.expand();
454  } else if (verb=="external") {
455  casadi_assert(pass.size()>=3 && pass.size()<=4,
456  "transform: 'external' pass must be {\"external\", library, operation[, opts]}");
457  std::string lib = pass[1].to_string();
458  std::string op = pass[2].to_string();
459  Dict eopts = pass.size()==4 ? pass[3].to_dict() : Dict();
460  f = external_transform(lib, op, f, eopts);
461  } else {
462  casadi_error("transform: unknown pass verb '" + verb + "'");
463  }
464  if (verbose) {
465  uout() << " after " << transform_passes_str({pass}) << ": "
466  << transform_stats(f) << std::endl;
467  }
468  }
469 
470  // Optionally rename the result (type-preserving for SX/MX functions)
471  if (!fname.empty() && fname!=f.name()) {
472  Dict ropts{{"allow_free", true}, {"allow_duplicate_io_names", true}};
473  std::vector<std::string> ni = f.name_in(), no = f.name_out();
474  if (f.is_a("SXFunction", true)) {
475  std::vector<SX> arg = f.sx_in();
476  f = Function(fname, arg, f(arg), ni, no, ropts);
477  } else {
478  std::vector<MX> arg = f.mx_in();
479  f = Function(fname, arg, f(arg), ni, no, ropts);
480  }
481  }
482  return f;
483  } catch(std::exception& e) {
484  THROW_ERROR("transform", e.what());
485  }
486  }
std::string transform_stats(const Function &f)
Definition: function.cpp:352
std::string transform_passes_str(const std::vector< std::vector< GenericType > > &ps)
Definition: function.cpp:338
std::ostream & uout()

References expand(), casadi::external_transform(), Function(), is_a(), mx_in(), name(), name_in(), name_out(), casadi::FunctionInternal::simplify_passes(), sx_in(), casadi::transform_passes_str(), casadi::transform_stats(), and casadi::uout().

◆ transform() [4/4]

Function casadi::Function::transform ( const std::vector< std::vector< GenericType > > &  passes,
const Dict &  opts = Dict() 
) const

Only defined for SXFunction and MXFunction. The result has the same signature, names and options; only the expression graph differs.

The dict form runs a single "simplify" pass whose tasks are selected with boolean options, all defaulting to on except combine_terms:

  • empty_inputs: an input whose symbols do not occur in any output is replaced by an all-zero sparse matrix of the same shape (its nnz becomes 0)
  • cse: common subexpression elimination
  • ref_count: drop unreferenced nodes, repeated until a fixed point
  • const_folding: evaluate constant subexpressions
  • combine_terms: merge like terms of sums

Unknown keys raise an error.

The passes form runs an explicit list of passes in order. Each pass is a list whose first entry is the verb:

  • ["simplify", task, ...] with tasks from the list above; an integer before a task is its run count (N>0: N times, 0: until the graph stops shrinking)
  • ["expand"]: expand to an SXFunction
  • ["external", library, operation] or [..., opts]: a transform from a plugin library

Here opts accepts only "verbose"; passing the boolean task options raises an error. With "verbose": true the node and instruction counts after each pass are printed.

Parameters
fnameName of the result; defaults to the current name
passesExplicit list of passes
optsDict form: task booleans and "verbose"; passes form: "verbose" only

>>> z = MX.sym("z"); w = MX.sym("w")
>>> f = Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"])
>>> f, f.n_instructions()
(Function(f:(z,w)->(r) MXFunction), 9)
>>> g = f.transform()
>>> g, g.n_instructions()
(Function(f:(z,w[1x1,0nz])->(r) MXFunction), 6)
>>> f.transform([["simplify", "cse"]]).n_instructions()
6
>>> f.transform("fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
>>> try:
...   f.transform([["nope"]])
... except RuntimeError as e:
...   print("unknown pass verb" in str(e))
True

>> z = MX.sym('z'); w = MX.sym('w');
>> f = Function('f', {z, w}, {sin(z)*cos(z) + sin(z)*cos(z)}, {'z', 'w'}, {'r'});
>> f, f.n_instructions()
f:(z,w)->(r) MXFunction
9
>> g = f.transform(); disp(g), disp(g.n_instructions())
f:(z,w[1x1,0nz])->(r) MXFunction
6
>> f.transform({{'simplify', 'cse'}}).n_instructions()
6
>> f.transform('fe', {{'expand'}})
fe:(z,w)->(r) SXFunction
>> try, f.transform({{'nope'}}); catch e, disp(contains(e.message, 'unknown pass')); end
1

julia> z = ca.MX.sym("z"); w = ca.MX.sym("w");
julia> f = ca.Function("f", [z, w], [sin(z)*cos(z) + sin(z)*cos(z)], ["z", "w"], ["r"]);
julia> println(f); ca.n_instructions(f)
f:(z,w)->(r) MXFunction
9
julia> g = ca.transform(f);
julia> println(g); ca.n_instructions(g)
f:(z,w[1x1,0nz])->(r) MXFunction
6
julia> ca.n_instructions(ca.transform(f, [["simplify", "cse"]]))
6
julia> ca.transform(f, "fe", [["expand"]])
Function(fe:(z,w)->(r) SXFunction)
julia> try
           ca.transform(f, [["nope"]])
       catch e
           println(occursin("unknown pass verb", sprint(showerror, e)))
       end
true

See also
expand

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

Definition at line 401 of file function.cpp.

402  {
403  return transform(name(), passes, opts);
404  }

References name(), and transform().

◆ type_name()

static std::string casadi::Function::type_name ( )
inlinestatic

>>> Function.type_name()
'Function'

>> Function.type_name()
Function

julia> ca.Function.type_name()
"Function"

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

Definition at line 152 of file function.hpp.

152 {return "Function";}

◆ uses_output()

bool casadi::Function::uses_output ( ) const

The functions returned by jacobian, forward and reverse always accept the original outputs as extra inputs (out_r, ...). For most classes those inputs are ignored and this returns false; it is true for classes that reuse the outputs, for example to avoid recomputing a solver solution.

>>> f = Function("f", [SX.sym("x")], [SX(0)])
>>> f.uses_output()
False

>> f = Function('f', {SX.sym('x')}, {SX(0)});
>> f.uses_output()
0

julia> f = ca.Function("f", [ca.SX.sym("x")], [ca.SX(0)]);
julia> ca.uses_output(f)
false

See also
jacobian, forward, reverse

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

Definition at line 1035 of file function.cpp.

1035  {
1036  return (*this)->uses_output();
1037  }

◆ weak()

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

Definition at line 130 of file generic_shared_impl.hpp.

143  {
144  return (*this)->weak();
145  }

◆ which_depends()

std::vector< bool > casadi::Function::which_depends ( const std::string &  s_in,
const std::vector< std::string > &  s_out,
casadi_int  order = 1,
bool  tr = false 
) const

Returns one boolean per nonzero of input s_in: true when at least one of the outputs s_out depends on that entry (order 1) or depends on it nonlinearly (order 2). With tr true the relation is flipped: one boolean per nonzero of the vertically concatenated outputs, true when it depends on any entry of s_in. The analysis is structural (it follows the graph, not the values).

Parameters
s_inName of one input
s_outNames of the outputs to inspect
order1 (any dependence) or 2 (nonlinear dependence); other values raise
trTranspose the relation, see above

>>> x = SX.sym("x"); y = SX.sym("y", 2)
>>> f = Function("f", [x, y], [x*y[0], y[1]**2 + x, 3], ["x", "y"], ["a", "b", "c"])
>>> f.which_depends("y", ["a", "b"])
[True, True]
>>> f.which_depends("y", ["a", "b"], 2)
[False, True]
>>> f.which_depends("y", ["a", "b", "c"], 1, True)
[True, True, False]
>>> f.which_depends("x", ["a"], 2)
[False]

>> x = SX.sym('x'); y = SX.sym('y', 2);
>> f = Function('f', {x, y}, {x*y(1), y(2)^2 + x, 3}, {'x', 'y'}, {'a', 'b', 'c'});
>> f.which_depends('y', {'a', 'b'})
1 1
>> f.which_depends('y', {'a', 'b'}, 2)
0 1
>> f.which_depends('y', {'a', 'b', 'c'}, 1, true)
1 1 0
>> f.which_depends('x', {'a'}, 2)
0

julia> x = ca.SX.sym("x"); y = ca.SX.sym("y", 2);
julia> f = ca.Function("f", [x, y], [x*y[1], y[2]^2 + x, 3], ["x", "y"], ["a", "b", "c"]);
julia> ca.which_depends(f, "y", ["a", "b"])
2-element Vector{Bool}:
 1
 1
julia> ca.which_depends(f, "y", ["a", "b"], 2)
2-element Vector{Bool}:
 0
 1
julia> ca.which_depends(f, "y", ["a", "b", "c"], 1, true)
3-element Vector{Bool}:
 1
 1
 0
julia> ca.which_depends(f, "x", ["a"], 2)
1-element Vector{Bool}:
 0

See also
factory, jac_sparsity

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

Definition at line 2022 of file function.cpp.

2024  {
2025  try {
2026  return (*this)->which_depends(s_in, s_out, order, tr);
2027  } catch(std::exception& e) {
2028  THROW_ERROR("which_depends", e.what());
2029  }
2030  }
static std::vector< SX > order(const std::vector< SX > &expr)
Definition: function.cpp:2142

References order().

Referenced by casadi::BonminInterface::init(), casadi::IpoptInterface::init(), casadi::KnitroInterface::init(), and casadi::FunctionInternal::which_depends().

◆ wrap() [1/2]

Function casadi::Function::wrap ( ) const

The wrapper has the same signature and names, carries over the derivative options (ad_weight, ad_weight_sp, max_num_dir, is_diff_in/out, derivative_of) and is cached by name. Classes without their own derivative or slice implementation use it internally; it is also a way to give any function a plain MX graph.

Parameters
nameName of the wrapper; defaults to "wrap_" + name()

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)], ["x"], ["y"])
>>> w = f.wrap()
>>> w, w.n_instructions(), w.get_function()
(Function(wrap_f:(x)->(y) MXFunction), 3, ['f'])
>>> f.wrap("g").name()
'g'

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)}, {'x'}, {'y'});
>> w = f.wrap(); disp(w), disp(w.n_instructions()), disp(w.get_function())
wrap_f:(x)->(y) MXFunction
3
f
>> f.wrap('g').name()
g

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)], ["x"], ["y"]);
julia> w = ca.wrap(f);
julia> println(w); ca.n_instructions(w), ca.get_function(w)
wrap_f:(x)->(y) MXFunction
(3, ["f"])
julia> ca.name(ca.wrap(f, "g"))
"g"

See also
wrap_as_needed, expand

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

Definition at line 2112 of file function.cpp.

2112  {
2113  return (*this)->wrap();
2114  }

References casadi::FunctionInternal::wrap().

Referenced by casadi::FunctionInternal::which_depends().

◆ wrap() [2/2]

Function casadi::Function::wrap ( const std::string &  name) const

The wrapper has the same signature and names, carries over the derivative options (ad_weight, ad_weight_sp, max_num_dir, is_diff_in/out, derivative_of) and is cached by name. Classes without their own derivative or slice implementation use it internally; it is also a way to give any function a plain MX graph.

Parameters
nameName of the wrapper; defaults to "wrap_" + name()

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)], ["x"], ["y"])
>>> w = f.wrap()
>>> w, w.n_instructions(), w.get_function()
(Function(wrap_f:(x)->(y) MXFunction), 3, ['f'])
>>> f.wrap("g").name()
'g'

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)}, {'x'}, {'y'});
>> w = f.wrap(); disp(w), disp(w.n_instructions()), disp(w.get_function())
wrap_f:(x)->(y) MXFunction
3
f
>> f.wrap('g').name()
g

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)], ["x"], ["y"]);
julia> w = ca.wrap(f);
julia> println(w); ca.n_instructions(w), ca.get_function(w)
wrap_f:(x)->(y) MXFunction
(3, ["f"])
julia> ca.name(ca.wrap(f, "g"))
"g"

See also
wrap_as_needed, expand

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

Definition at line 2116 of file function.cpp.

2116  {
2117  return (*this)->wrap(name);
2118  }

References name(), and casadi::FunctionInternal::wrap().

◆ wrap_as_needed() [1/2]

Function casadi::Function::wrap_as_needed ( const Dict &  opts) const

Like wrap, but the wrapper is built with opts (merged with the derivative options of this function) and is not cached. The named overload returns this function itself when opts is empty and name equals its current name; the unnamed overload always wraps, under the name "wrap_" + name().

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)])
>>> f.wrap_as_needed("f", {}).class_name(), f.wrap_as_needed({}).class_name()
('SXFunction', 'MXFunction')
>>> f.wrap_as_needed("g", {"ad_weight": 1}).name()
'g'

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)});
>> f.wrap_as_needed('f', struct()).class_name()
SXFunction
>> f.wrap_as_needed(struct()).class_name()
MXFunction
>> f.wrap_as_needed('g', struct('ad_weight', 1)).name()
g

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)]);
julia> ca.class_name(ca.wrap_as_needed(f, "f", Dict()))
"SXFunction"
julia> ca.class_name(ca.wrap_as_needed(f, Dict()))
"MXFunction"
julia> ca.name(ca.wrap_as_needed(f, "g", Dict("ad_weight" => 1)))
"g"

See also
wrap

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

Definition at line 2120 of file function.cpp.

2120  {
2121  return (*this)->wrap_as_needed(opts);
2122  }

References casadi::FunctionInternal::wrap_as_needed().

Referenced by casadi::MapSum::create().

◆ wrap_as_needed() [2/2]

Function casadi::Function::wrap_as_needed ( const std::string &  name,
const Dict &  opts 
) const

Like wrap, but the wrapper is built with opts (merged with the derivative options of this function) and is not cached. The named overload returns this function itself when opts is empty and name equals its current name; the unnamed overload always wraps, under the name "wrap_" + name().

>>> x = SX.sym("x")
>>> f = Function("f", [x], [sin(x)])
>>> f.wrap_as_needed("f", {}).class_name(), f.wrap_as_needed({}).class_name()
('SXFunction', 'MXFunction')
>>> f.wrap_as_needed("g", {"ad_weight": 1}).name()
'g'

>> x = SX.sym('x');
>> f = Function('f', {x}, {sin(x)});
>> f.wrap_as_needed('f', struct()).class_name()
SXFunction
>> f.wrap_as_needed(struct()).class_name()
MXFunction
>> f.wrap_as_needed('g', struct('ad_weight', 1)).name()
g

julia> x = ca.SX.sym("x");
julia> f = ca.Function("f", [x], [sin(x)]);
julia> ca.class_name(ca.wrap_as_needed(f, "f", Dict()))
"SXFunction"
julia> ca.class_name(ca.wrap_as_needed(f, Dict()))
"MXFunction"
julia> ca.name(ca.wrap_as_needed(f, "g", Dict("ad_weight" => 1)))
"g"

See also
wrap

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

Definition at line 2124 of file function.cpp.

2124  {
2125  return (*this)->wrap_as_needed(name, opts);
2126  }

References name(), and casadi::FunctionInternal::wrap_as_needed().


The documentation for this class was generated from the following files: