List of all members | Public Types | Public Member Functions | Static Public 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]

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 ()
 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...
 
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...
 
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...
 
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...
 
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...
 
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...
 
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...
 
 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 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...
 
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...
 
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...
 
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...
 
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 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 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 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())
 To resolve ambiguity on some compilers. 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())
 To resolve ambiguity on some compilers. 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

using casadi::SharedObject::internal_base_type = SharedObjectInternal
inherited

Definition at line 102 of file shared_object.hpp.

Constructor & Destructor Documentation

◆ Function() [1/7]

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

◆ Function() [2/7]

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

◆ Function() [3/7]

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

◆ Function() [4/7]

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

◆ Function() [5/7]

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

◆ Function() [6/7]

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

◆ Function() [7/7]

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

◆ ~Function()

casadi::Function::~Function ( )

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.

◆ 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

◆ 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

◆ assert_size_out()

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

◆ 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

◆ bspline()

static 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ check_name()

static 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

◆ 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

◆ class_name()

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

◆ conditional() [1/2]

static 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

◆ conditional() [2/2]

static 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ debug_repr()

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

Definition at line 112 of file generic_shared_impl.hpp.

◆ 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

◆ deserialize() [1/3]

static 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

◆ deserialize() [2/3]

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

◆ deserialize() [3/3]

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

◆ disp()

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

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

◆ 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

◆ export_code() [1/2]

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

◆ export_code() [2/2]

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ fix_name()

static 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

◆ 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

◆ 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

◆ 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

◆ free_sx()

std::vector<SX> casadi::Function::free_sx ( ) const

◆ generate() [1/2]

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

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ get_function() [2/2]

Function casadi::Function::get_function ( const std::string &  name) const

◆ get_str()

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

Definition at line 91 of file shared_object.hpp.

◆ 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

◆ 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

◆ 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

◆ 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

◆ has_out()

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

◆ 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

◆ 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

◆ 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

◆ if_else()

static 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

◆ 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

◆ index_out()

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ is_null()

bool casadi::GenericShared< SharedObject , SharedObjectInternal >::is_null
inherited

Definition at line 116 of file generic_shared_impl.hpp.

◆ 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

◆ 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

◆ 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

◆ 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

◆ jit() [1/2]

static 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

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

Create a just-in-time compiled function from a C language string

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

◆ jit() [2/2]

static 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

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

Create a just-in-time compiled function from a C language string

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

◆ load()

static 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

◆ map() [1/5]

Function casadi::Function::map ( casadi_int  n,
const std::string &  parallelization,
casadi_int  max_num_threads 
) const

◆ 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

◆ 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

◆ 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

◆ 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

◆ mapaccum() [1/5]

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

◆ mapaccum() [2/5]

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

◆ mapaccum() [3/5]

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

◆ mapaccum() [4/5]

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

◆ mapaccum() [5/5]

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

◆ 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

◆ 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

◆ min_in()

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

◆ 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

◆ 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

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

◆ 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

◆ 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

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ name_in() [2/2]

const std::string& casadi::Function::name_in ( casadi_int  ind) const

◆ 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

◆ name_out() [2/2]

const std::string& casadi::Function::name_out ( casadi_int  ind) const

◆ 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

◆ 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

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

◆ 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

◆ 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

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

◆ 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

◆ nominal_out()

std::vector<double> casadi::Function::nominal_out ( casadi_int  ind) const

◆ 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

◆ 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

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

◆ 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

◆ 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

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ release()

void casadi::Function::release ( int  mem) const

◆ reset_dump_count()

void casadi::Function::reset_dump_count ( )

dump_out and dump_trace

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

◆ 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

◆ 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

◆ serialize()

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

◆ 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

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

◆ 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

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

◆ 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

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

◆ 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

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

◆ 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

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

◆ 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

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

◆ 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

◆ 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

◆ 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

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

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

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

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

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

◆ 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

◆ 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

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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

◆ 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


The documentation for this class was generated from the following file: