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

User-defined Function implemented by subclassing. More...

#include <callback.hpp>

Detailed Description

A Callback is a Function whose numerical evaluation (and optionally its derivatives) is written by the user in Python, MATLAB or C++ by overriding virtual methods. It can be called like any Function, embedded in MX graphs, mapped, and used inside NLPs and integrators.

A subclass must call the base constructor and then construct(name, opts) from its own constructor; construct() queries the virtual methods below (get_n_in, get_n_out, get_sparsity_in/out, get_name_in/out) and calls init() and finalize(), so all data those methods need must be set before construct() runs. Only eval() is mandatory. Defaults: one scalar input "i0" and one scalar output "o0".

Object lifetime: the Function side holds a raw pointer to the user object and does not own it. The user must keep the Callback object alive (in Python: keep a reference) for as long as any Function, expression or solver that uses it exists; otherwise evaluation fails with "Callback object has been deleted". The same holds for objects returned from get_jacobian/get_forward/get_reverse. Callback objects cannot be copied.

Derivatives: by default a Callback is not differentiable, so jacobian(), forward/reverse sweeps and NLP solvers that need gradients fail with "Derivatives cannot be calculated". Either override has_jacobian/get_jacobian, has_forward/get_forward or has_reverse/get_reverse, or pass the option "enable_fd": True to construct() to use finite differences ("fd_method": "central" (default), "forward", "backward" or "smoothing"; "fd_options" such as {"h": 1e-6} tune the step). A user-provided Jacobian is itself differentiated with finite differences only when it is a Callback with "enable_fd"; a Function built from SX/MX gives exact second derivatives.

>>> class MyCallback(Callback):
...   def __init__(self, name, d, opts={}):
...     Callback.__init__(self)
...     self.d = d
...     self.construct(name, opts)
...   def get_n_in(self): return 1
...   def get_n_out(self): return 1
...   def eval(self, arg):
...     return [sin(self.d*arg[0])]
>>> f = MyCallback("f", 0.5)
>>> f
Callback(f:(i0)->(o0) CallbackInternal)
>>> f(2)
DM(0.8415)
>>> x = MX.sym("x")
>>> f(x)
MX(f(x){0})
>>> try:
...   jacobian(f(x), x)
... except Exception as e:
...   print("Derivatives cannot be calculated for f" in str(e))
True
>>> f = MyCallback("f", 0.5, {"enable_fd": True})
>>> J = Function("J", [x], [jacobian(f(x), x)])
>>> J(2)
DM(0.2702)

>> c = {'classdef MyCallback < casadi.Callback', 'properties', 'd', 'end', 'methods'};
>> c = [c, {'function self = MyCallback(name, d, varargin)'}];
>> c = [c, {'self@casadi.Callback(); self.d = d; construct(self, name, varargin{:});'}];
>> c = [c, {'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {sin(self.d*arg{1})};'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'MyCallback.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = MyCallback('f', 0.5); disp(f)
f:(i0)->(o0) CallbackInternal
>> f(2)
0.8415
>> x = MX.sym('x'); disp(f(x))
f(x){0}
>> try, jacobian(f(x), x); catch e, disp(contains(e.message, 'Derivatives cannot be')); end
1
>> f = MyCallback('f', 0.5, struct('enable_fd', true));
>> J = Function('J', {x}, {jacobian(f(x), x)}); J(2)
0.2702
>> rmpath(d); rmdir(d, 's');

julia> struct MyCallback <: ca.Callback
           d::Float64
       end
julia> ca.get_n_in(::MyCallback) = 1
julia> ca.get_n_out(::MyCallback) = 1
julia> ca.eval_(cb::MyCallback, arg) = [sin(cb.d * arg[1])]
julia> f = ca.callback(MyCallback(0.5), "f");
julia> ca.Function(f)
Function(f:(i0)->(o0) CallbackInternal)
julia> f(2)
DM(0.8415)
julia> x = ca.MX.sym("x");
julia> f(x)
MX(f(x){0})
julia> try
           ca.jacobian(f(x), x)
       catch e
           println(occursin("Derivatives cannot be calculated for f", sprint(showerror, e)))
       end
true
julia> f = ca.callback(MyCallback(0.5), "f", Dict("enable_fd" => true));
julia> J = ca.Function("J", [x], [ca.jacobian(f(x), x)]);
julia> J(2)
DM(0.2702)

The callback object must outlive every use of the Function:

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
>>> x = MX.sym("x")
>>> f = Sq("f")
>>> F = Function("F", [x], [f(x)])
>>> F(3)
DM(9)
>>> del f
>>> try:
...   F(3)
... except Exception as e:
...   print(str(e).splitlines()[-1])
Callback object has been deleted

>> c = {'classdef SqCb < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqCb(name)', 'self@casadi.Callback(); construct(self, name);'}];
>> c = [c, {'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqCb.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> x = MX.sym('x'); f = SqCb('f'); F = Function('F', {x}, {f(x)}); disp(F(3))
9
>> delete(f)
>> try, F(3); catch e, disp(contains(e.message, 'Callback object has been deleted')); end
...
1
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> x = ca.MX.sym("x");
julia> f = ca.callback(Sq(), "f");
julia> F = ca.Function("F", [x], [f(x)]);
julia> F(3)
DM(9)
julia> f = nothing; GC.gc()
julia> try
           F(3)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Callback object has been deleted

Use in an NLP with finite differences:

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
>>> f = Sq("f", {"enable_fd": True})
>>> opti = Opti()
>>> v = opti.variable()
>>> opti.minimize(f(v-1))
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> opti.solve().value(v)
1.0

>> c = {'classdef SqFd < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqFd(name, opts)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name, opts);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqFd.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqFd('f', struct('enable_fd', true));
>> opti = Opti(); v = opti.variable(); opti.minimize(f(v-1));
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); disp(sol.value(v))
1.0000
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> f = ca.callback(Sq(), "f", Dict("enable_fd" => true));
julia> opti = ca.Opti();
julia> v = ca.variable(opti);
julia> ca.minimize(opti, f(v - 1))
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> ca.value(ca.solve(opti), v)
1.0

See also
Function, external
Author
Joris Gillis, Joel Andersson
Date
2015

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

Examples
Function/callback.py, and misc/assertion.py.

Definition at line 266 of file casadi/core/callback.hpp.

Inheritance diagram for casadi::Callback:
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

 Callback ()
 Default constructor. More...
 
 Callback (const Callback &obj)
 Copy constructor (throws an error) More...
 
virtual ~Callback ()
 Destructor. More...
 
void construct (const std::string &name, const Dict &opts=Dict())
 Construct the internal Function object. More...
 
virtual void init ()
 Initialize the object. More...
 
virtual void finalize ()
 Finalize the object. More...
 
virtual std::vector< DM > eval (const std::vector< DM > &arg) const
 Evaluate numerically. More...
 
virtual int eval_buffer (const double **arg, const std::vector< casadi_int > &sizes_arg, double **res, const std::vector< casadi_int > &sizes_res) const
 A copy-free low level interface. More...
 
virtual bool has_eval_buffer () const
 Does the Callback class support a copy-free low level interface ? More...
 
virtual casadi_int get_n_in ()
 Get the number of inputs. More...
 
virtual casadi_int get_n_out ()
 Get the number of outputs. More...
 
virtual Sparsity get_sparsity_in (casadi_int i)
 Get the sparsity of an input. More...
 
virtual Sparsity get_sparsity_out (casadi_int i)
 Get the sparsity of an output. More...
 
virtual std::string get_name_in (casadi_int i)
 Get the name of an input. More...
 
virtual std::string get_name_out (casadi_int i)
 Get the name of an output. More...
 
virtual bool uses_output () const
 Do the derivative functions need nondifferentiated outputs? More...
 
virtual Function get_factory (const std::string &name, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const Function::AuxOut &aux, const Dict &opts) const
 Customize calls to the function factory. 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::string & name_in (casadi_int ind) const
 Get the name of input ind; out of range raises an error. More...
 
const std::vector< std::string > & name_out () const
 Get the names of all outputs, in order. 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...
 
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...
 
virtual bool has_jacobian () const
 Return Jacobian of all input elements with respect to all output elements. More...
 
virtual Function get_jacobian (const std::string &name, const std::vector< std::string > &inames, const std::vector< std::string > &onames, const Dict &opts) const
 Return Jacobian of all input elements with respect to all output elements. More...
 
virtual bool has_forward (casadi_int nfwd) const
 Return function that calculates forward derivatives. More...
 
virtual Function get_forward (casadi_int nfwd, const std::string &name, const std::vector< std::string > &inames, const std::vector< std::string > &onames, const Dict &opts) const
 Return function that calculates forward derivatives. More...
 
virtual bool has_reverse (casadi_int nadj) const
 Return function that calculates adjoint derivatives. More...
 
virtual Function get_reverse (casadi_int nadj, const std::string &name, const std::vector< std::string > &inames, const std::vector< std::string > &onames, const Dict &opts) const
 Return function that calculates adjoint derivatives. More...
 
virtual bool has_jac_sparsity (casadi_int oind, casadi_int iind) const
 Return sparsity of Jacobian of all input elements. More...
 
virtual Sparsity get_jac_sparsity (casadi_int oind, casadi_int iind, bool symmetric) const
 Return sparsity of Jacobian of all input elements. 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...
 
std::vector< bool > is_diff_in () 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_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 export_code (const std::string &lang, 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...
 
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...
 
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...
 
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...
 
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_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_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 type name. 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 deserialize (DeserializingStream &s)
 Build a function from a DeserializingStream (C++ serialization API) More...
 
static Function load (const std::string &filename)
 Read a function from a file written by save. 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
inherited

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

◆ Callback() [1/2]

casadi::Callback::Callback ( )

Creates a null Function; construct() must be called before use.

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

◆ Callback() [2/2]

casadi::Callback::Callback ( const Callback &  obj)

Callback objects cannot be copied; share the Function instead.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
>>> f = Sq("f")
>>> try:
...   Callback(f)
... except Exception as e:
...   print("Callback objects cannot be copied" in str(e))
True

>> c = {'classdef SqCopy < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqCopy(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqCopy.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqCopy('f');
>> try, Callback(f); catch e, disp(contains(e.message, 'cannot be copied')); end
1
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> f = ca.callback(Sq(), "f");
julia> try
           ca.CallbackFunction(f)
       catch e
           println(e isa MethodError)
       end
true

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

◆ ~Callback()

virtual casadi::Callback::~Callback ( )
virtual

Detaches the user object; a Function that still references it fails afterwards.

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

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
inherited

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
inherited

>>> 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
inherited

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

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

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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

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

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
inherited

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

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

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

◆ construct()

void casadi::Callback::construct ( const std::string &  name,
const Dict &  opts = Dict() 
)

The class constructor only creates a null pointer; this call creates the Function. It must be called once from the subclass constructor, after all data needed by get_n_in/get_n_out/get_sparsity_in/get_sparsity_out/get_name_in/get_name_out is set, because those methods are evaluated here. init() and finalize() are called at the end. Calling it twice raises an error.

Parameters
nameName of the Function
optsFunction options, e.g. "enable_fd", "fd_method", "fd_options", "enable_forward", "enable_reverse", "enable_jacobian"

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
>>> f = Sq("f", {"enable_fd": True, "fd_method": "forward"})
>>> f.name(), f.n_in(), f.n_out()
('f', 1, 1)
>>> try:
...   f.construct("g")
... except Exception as e:
...   print("Internal class already created" in str(e))
True

>> c = {'classdef SqOpts < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqOpts(name, opts)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name, opts);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqOpts.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqOpts('f', struct('enable_fd', true, 'fd_method', 'forward'));
>> fprintf('%s %d %d\n', f.name(), f.n_in(), f.n_out())
f 1 1
>> try, f.construct('g'); catch e, disp(contains(e.message, 'already created')); end
1
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> f = ca.callback(Sq(), "f", Dict("enable_fd" => true, "fd_method" => "forward"));
julia> ca.name(f), ca.n_in(f), ca.n_out(f)
("f", 1, 1)
julia> try
           ca.construct(f, "g")
       catch e
           println(occursin("Internal class already created", sprint(showerror, e)))
       end
true

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

◆ convert_in() [1/6]

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

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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

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

◆ deserialize() [3/3]

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

◆ disp()

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

◆ eval()

virtual std::vector<DM> casadi::Callback::eval ( const std::vector< DM > &  arg) const
virtual

The method a subclass must implement. Receives one DM per input (with the sparsity of get_sparsity_in) and must return a list with one entry per output; each entry is converted to a DM and must match the shape of get_sparsity_out, otherwise the call raises an error. Exceptions raised inside propagate to the caller. The default implementation raises an error.

This signature is not thread-safe. For guaranteed thread-safety, use eval_buffer.

Parameters
argInput values
Returns
Output values

>>> class Scale(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_n_in(self): return 2
...   def get_sparsity_in(self, i):
...     return Sparsity.dense(2, 1) if i == 0 else Sparsity.dense(1, 1)
...   def get_sparsity_out(self, i): return Sparsity.dense(2, 1)
...   def eval(self, arg):
...     return [arg[0]*arg[1]]
>>> f = Scale("f")
>>> f([1, 2], 3)
DM([3, 6])
>>> class Bad(Scale):
...   def eval(self, arg):
...     return [arg[1]]
>>> try:
...   Bad("b")([1, 2], 3)
... except Exception as e:
...   print("Shape mismatch" in str(e))
True

>> c = {'classdef Scale < casadi.Callback', 'methods'};
>> c = [c, {'function self = Scale(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function n = get_n_in(self)', 'n = 2;', 'end'}];
>> c = [c, {'function sp = get_sparsity_in(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(1, 1);'}];
>> c = [c, {'if i == 0, sp = casadi.Sparsity.dense(2, 1); end', 'end'}];
>> c = [c, {'function sp = get_sparsity_out(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(2, 1);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}*arg{2}};'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'Scale.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = Scale('f'); disp(f([1; 2], 3))
[3, 6]
>> c = {'classdef BadScale < Scale', 'methods', 'function self = BadScale(name)'};
>> c = [c, {'self@Scale(name);', 'end', 'function r = eval(self, arg)', 'r = {arg{2}};'}];
>> c = [c, {'end', 'end', 'end'}]; fid = fopen(fullfile(d, 'BadScale.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid); g = BadScale('b');
>> try, g([1; 2], 3); catch e, disp(contains(e.message, 'Shape mismatch')); end
1
>> rmpath(d); rmdir(d, 's');

julia> abstract type AbstractScale <: ca.Callback end
julia> struct Scale <: AbstractScale end
julia> ca.get_n_in(::AbstractScale) = 2
julia> ca.get_sparsity_in(::AbstractScale, i) = ca.Sparsity.dense(i == 0 ? 2 : 1, 1)
julia> ca.get_sparsity_out(::AbstractScale, i) = ca.Sparsity.dense(2, 1)
julia> ca.eval_(::Scale, arg) = [arg[1] * arg[2]]
julia> f = ca.callback(Scale(), "f");
julia> f([1, 2], 3)
DM([3, 6])
julia> struct Bad <: AbstractScale end
julia> ca.eval_(::Bad, arg) = [arg[2]]
julia> try
           ca.callback(Bad(), "b")([1, 2], 3)
       catch e
           println(occursin("Shape mismatch", sprint(showerror, e)))
       end
true

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

◆ eval_buffer()

virtual int casadi::Callback::eval_buffer ( const double **  arg,
const std::vector< casadi_int > &  sizes_arg,
double **  res,
const std::vector< casadi_int > &  sizes_res 
) const
virtual

Alternative to eval() that works on the raw nonzero buffers, avoiding DM allocation. Override has_eval_buffer() to return true to activate it. In Python the method receives two tuples of memoryview objects (inputs and outputs), each holding only the structural nonzeros of the corresponding input or output in column-major order; write the result into the output buffers and return 0.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_sparsity_in(self, i): return Sparsity.dense(3, 1)
...   def get_sparsity_out(self, i): return Sparsity.dense(3, 1)
...   def has_eval_buffer(self): return True
...   def eval_buffer(self, arg, res):
...     a = np.frombuffer(arg[0], dtype=np.float64)
...     r = np.frombuffer(res[0], dtype=np.float64)
...     r[:] = a**2
...     return 0
>>> f = Sq("f")
>>> f([1, 2, 3])
DM([1, 4, 9])

julia> struct Sq <: ca.Callback end
julia> ca.get_sparsity_in(::Sq, i) = ca.Sparsity.dense(3, 1)
julia> ca.get_sparsity_out(::Sq, i) = ca.Sparsity.dense(3, 1)
julia> ca.has_eval_buffer(::Sq) = true
julia> ca.eval_buffer(::Sq, arg, res) = (res[1] .= arg[1] .^ 2; 0)
julia> f = ca.callback(Sq(), "f");
julia> f([1, 2, 3])
DM([1, 4, 9])

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

◆ expand() [1/2]

Function casadi::Function::expand ( ) const
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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

◆ finalize()

virtual void casadi::Callback::finalize ( )
inlinevirtual

Called from construct() after init(), as the last step before the Function can be evaluated. The default does nothing.

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

Definition at line 479 of file casadi/core/callback.hpp.

◆ find_function()

Function casadi::Function::find_function ( const std::string &  name,
casadi_int  max_depth = -1 
) const
inherited
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
inherited

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

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
inherited

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
inherited

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
inherited

>>> 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
inherited

◆ generate() [1/2]

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

◆ generate() [2/2]

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

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
inherited

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

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

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
inherited

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

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

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

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

Called when a derived function is requested by name through Function::factory; the default delegates to the standard factory.

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

◆ get_forward()

virtual Function casadi::Callback::get_forward ( casadi_int  nfwd,
const std::string &  name,
const std::vector< std::string > &  inames,
const std::vector< std::string > &  onames,
const Dict &  opts 
) const
virtual

Override has_forward(nfwd) to return true for the numbers of directions you support (nfwd==1 is enough; CasADi then loops) and get_forward() to return a Function with inputs [nominal inputs, nominal outputs, one forward seed per input] and one forward sensitivity per output. For nfwd>1 the seeds and sensitivities are horizontally stacked (n-by-nfwd*m). forward(nfwd) on the Function caches the result.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
...   def has_forward(self, nfwd): return nfwd == 1
...   def get_forward(self, nfwd, name, inames, onames, opts):
...     print(nfwd, name, inames, onames)
...     x, y, xd = SX.sym("x"), SX.sym("y", Sparsity(1, 1)), SX.sym("xd")
...     return Function(name, [x, y, xd], [2*x*xd], inames, onames, opts)
>>> f = Sq("f")
>>> x = MX.sym("x")
>>> J = Function("J", [x], [jacobian(f(x), x)])
1 fwd1_f ['i0', 'out_o0', 'fwd_i0'] ['fwd_o0']
>>> J(3)
DM(6)

>> c = {'classdef SqFwd < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqFwd(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end'}];
>> c = [c, {'function b = has_forward(self, nfwd)', 'b = nfwd == 1;', 'end'}];
>> c = [c, {'function F = get_forward(self, nfwd, name, inames, onames, opts)'}];
>> c = [c, {'disp(nfwd); disp(name); disp(inames); disp(onames);'}];
>> c = [c, {'x = casadi.SX.sym(''x''); y = casadi.SX.sym(''y'', casadi.Sparsity(1, 1));'}];
>> c = [c, {'xd = casadi.SX.sym(''xd'');'}];
>> c = [c, {'F = casadi.Function(name, {x, y, xd}, {2*x*xd}, inames, onames, opts);'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqFwd.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqFwd('f'); x = MX.sym('x'); J = Function('J', {x}, {jacobian(f(x), x)});
1
fwd1_f
i0
out_o0
fwd_i0
fwd_o0
>> J(3)
6
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> ca.has_forward(::Sq, nfwd) = nfwd == 1
julia> function ca.get_forward(::Sq, nfwd, name, inames, onames, opts)
           println(nfwd, " ", name, " ", inames, " ", onames)
           x = ca.SX.sym("x"); y = ca.SX.sym("y", ca.Sparsity(1, 1)); xd = ca.SX.sym("xd")
           ca.Function(name, [x, y, xd], [2x*xd], inames, onames, opts)
       end
julia> f = ca.callback(Sq(), "f");
julia> x = ca.MX.sym("x");
julia> J = ca.Function("J", [x], [ca.jacobian(f(x), x)]);
1 fwd1_f ["i0", "out_o0", "fwd_i0"] ["fwd_o0"]
julia> J(3)
DM(6)

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

◆ get_free()

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

◆ get_function() [1/2]

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

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
inherited

◆ get_jac_sparsity()

virtual Sparsity casadi::Callback::get_jac_sparsity ( casadi_int  oind,
casadi_int  iind,
bool  symmetric 
) const
inlinevirtual

with respect to all output elements. Override has_jac_sparsity(oind, iind) to return true and get_jac_sparsity() to return the pattern of the Jacobian block of output oind with respect to input iind. Without it the block is assumed dense. Finite differencing exploits the pattern (fewer evaluations) and the result of jacobian() carries it.

>>> class Diag(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_sparsity_in(self, i): return Sparsity.dense(3, 1)
...   def get_sparsity_out(self, i): return Sparsity.dense(3, 1)
...   def eval(self, arg):
...     return [arg[0]**2]
...   def has_jac_sparsity(self, oind, iind): return True
...   def get_jac_sparsity(self, oind, iind, symmetric): return Sparsity.diag(3)
>>> f = Diag("f", {"enable_fd": True})
>>> x = MX.sym("x", 3)
>>> J = jacobian(f(x), x)
>>> J.sparsity()
Sparsity(3x3,3nz)
>>> Function("J", [x], [J])([1, 2, 3])
DM(
[[2, 00, 00],
 [00, 4, 00],
 [00, 00, 6]])

>> c = {'classdef DiagCb < casadi.Callback', 'methods'};
>> c = [c, {'function self = DiagCb(name, opts)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name, opts);', 'end'}];
>> c = [c, {'function sp = get_sparsity_in(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(3, 1);', 'end'}];
>> c = [c, {'function sp = get_sparsity_out(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(3, 1);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}.^2};', 'end'}];
>> c = [c, {'function b = has_jac_sparsity(self, oind, iind)', 'b = true;', 'end'}];
>> c = [c, {'function sp = get_jac_sparsity(self, oind, iind, symmetric)'}];
>> c = [c, {'sp = casadi.Sparsity.diag(3);', 'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'DiagCb.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = DiagCb('f', struct('enable_fd', true)); x = MX.sym('x', 3); J = jacobian(f(x), x);
>> J.sparsity()
3x3,3nz
>> JF = Function('J', {x}, {J}); disp(JF([1; 2; 3]))
[[2, 00, 00],
 [00, 4, 00],
 [00, 00, 6]]
>> rmpath(d); rmdir(d, 's');

julia> struct Diag <: ca.Callback end
julia> ca.get_sparsity_in(::Diag, i) = ca.Sparsity.dense(3, 1)
julia> ca.get_sparsity_out(::Diag, i) = ca.Sparsity.dense(3, 1)
julia> ca.eval_(::Diag, arg) = [arg[1] .^ 2]
julia> ca.has_jac_sparsity(::Diag, oind, iind) = true
julia> ca.get_jac_sparsity(::Diag, oind, iind, symmetric) = ca.Sparsity.diag(3)
julia> f = ca.callback(Diag(), "f", Dict("enable_fd" => true));
julia> x = ca.MX.sym("x", 3);
julia> J = ca.jacobian(f(x), x);
julia> ca.sparsity(J)
Sparsity(3x3,3nz)
julia> ca.Function("J", [x], [J])([1, 2, 3])
DM(
[[2, 00, 00],
 [00, 4, 00],
 [00, 00, 6]])

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

Definition at line 1267 of file casadi/core/callback.hpp.

◆ get_jacobian()

virtual Function casadi::Callback::get_jacobian ( const std::string &  name,
const std::vector< std::string > &  inames,
const std::vector< std::string > &  onames,
const Dict &  opts 
) const
virtual

Override has_jacobian() to return true and get_jacobian() to return a Function with inputs [all nominal inputs, all nominal outputs] and one output per (output, input) pair, each the dense or sparse Jacobian block of that output with respect to that input (row-major over the pairs). Use the inames, onames and opts passed in: they carry the expected names and the "derivative_of" option. The returned Function may be an SX/MX Function (then higher derivatives are exact) or another Callback (keep a reference to it).

>>> class F43(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_sparsity_in(self, i): return Sparsity.dense(4, 1)
...   def get_sparsity_out(self, i): return Sparsity.dense(3, 1)
...   def eval(self, arg):
...     a, b, c, d = vertsplit(arg[0])
...     return [vertcat(sin(c)*d+d**2, 2*a+c, b**2+5*c)]
...   def has_jacobian(self): return True
...   def get_jacobian(self, name, inames, onames, opts):
...     print(name, inames, onames)
...     x = SX.sym("x", 4)
...     y = SX.sym("y", Sparsity(3, 1))
...     a, b, c, d = vertsplit(x)
...     J = blockcat([[0, 0, d*cos(c), sin(c)+2*d], [2, 0, 1, 0], [0, 2*b, 5, 0]])
...     return Function(name, [x, y], [J], inames, onames, opts)
>>> f = F43("f")
>>> x = MX.sym("x", 4)
>>> J = Function("J", [x], [jacobian(f(x), x)])
jac_f ['i0', 'out_o0'] ['jac_o0_i0']
>>> J([1, 2, 0, 3])
DM(
[[0, 0, 3, 6],
 [2, 0, 1, 0],
 [0, 4, 5, 0]])

>> c = {'classdef F43 < casadi.Callback', 'methods'};
>> c = [c, {'function self = F43(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function sp = get_sparsity_in(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(4, 1);', 'end'}];
>> c = [c, {'function sp = get_sparsity_out(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(3, 1);', 'end'}];
>> c = [c, {'function r = eval(self, arg)'}];
>> c = [c, {'v = arg{1}; a = v(1); b = v(2); c = v(3); d = v(4);'}];
>> c = [c, {'r = {[sin(c)*d+d^2; 2*a+c; b^2+5*c]};', 'end'}];
>> c = [c, {'function b = has_jacobian(self)', 'b = true;', 'end'}];
>> c = [c, {'function J = get_jacobian(self, name, inames, onames, opts)'}];
>> c = [c, {'disp(name); disp(inames); disp(onames);'}];
>> c = [c, {'x = casadi.SX.sym(''x'', 4); a = x(1); b = x(2); c = x(3); d = x(4);'}];
>> c = [c, {'y = casadi.SX.sym(''y'', casadi.Sparsity(3, 1));'}];
>> c = [c, {'Jm = [0, 0, d*cos(c), sin(c)+2*d; 2, 0, 1, 0; 0, 2*b, 5, 0];'}];
>> c = [c, {'J = casadi.Function(name, {x, y}, {Jm}, inames, onames, opts);'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'F43.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = F43('f'); x = MX.sym('x', 4); J = Function('J', {x}, {jacobian(f(x), x)});
jac_f
i0
out_o0
jac_o0_i0
>> J([1; 2; 0; 3])
[[0, 0, 3, 6],
 [2, 0, 1, 0],
 [0, 4, 5, 0]]
>> rmpath(d); rmdir(d, 's');

julia> struct F43 <: ca.Callback end
julia> ca.get_sparsity_in(::F43, i) = ca.Sparsity.dense(4, 1)
julia> ca.get_sparsity_out(::F43, i) = ca.Sparsity.dense(3, 1)
julia> function ca.eval_(::F43, arg)
           a, b, c, d = arg[1][1], arg[1][2], arg[1][3], arg[1][4]
           [[sin(c)*d + d^2; 2a + c; b^2 + 5c]]
       end
julia> ca.has_jacobian(::F43) = true
julia> function ca.get_jacobian(::F43, name, inames, onames, opts)
           println(name, " ", inames, " ", onames)
           x = ca.SX.sym("x", 4); y = ca.SX.sym("y", ca.Sparsity(3, 1))
           a, b, c, d = x[1], x[2], x[3], x[4]
           J = [0 0 d*cos(c) sin(c)+2d; 2 0 1 0; 0 2b 5 0]
           ca.Function(name, [x, y], [J], inames, onames, opts)
       end
julia> f = ca.callback(F43(), "f");
julia> x = ca.MX.sym("x", 4);
julia> J = ca.Function("J", [x], [ca.jacobian(f(x), x)]);
jac_f ["i0", "out_o0"] ["jac_o0_i0"]
julia> J([1, 2, 0, 3])
DM(
[[0, 0, 3, 6],
 [2, 0, 1, 0],
 [0, 4, 5, 0]])

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

◆ get_n_in()

virtual casadi_int casadi::Callback::get_n_in ( )
virtual

Called during construct(). Default: 1.

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

◆ get_n_out()

virtual casadi_int casadi::Callback::get_n_out ( )
virtual

Called during construct(). Default: 1.

>>> class Split(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_n_in(self): return 1
...   def get_n_out(self): return 2
...   def eval(self, arg):
...     return [arg[0]**2, -arg[0]]
>>> f = Split("f")
>>> f(3)
(DM(9), DM(-3))

>> c = {'classdef SplitCb < casadi.Callback', 'methods'};
>> c = [c, {'function self = SplitCb(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function n = get_n_out(self)', 'n = 2;', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2, -arg{1}};'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SplitCb.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SplitCb('f'); [a, b] = f(3); disp(a), disp(b)
9
-3
>> rmpath(d); rmdir(d, 's');

julia> struct Split <: ca.Callback end
julia> ca.get_n_in(::Split) = 1
julia> ca.get_n_out(::Split) = 2
julia> ca.eval_(::Split, arg) = [arg[1]^2, -arg[1]]
julia> f = ca.callback(Split(), "f");
julia> f(3)
(9, -3)

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

◆ get_name_in()

virtual std::string casadi::Callback::get_name_in ( casadi_int  i)
virtual

Called during construct(). Default: "i0", "i1", ... Names allow calling the Function with keyword arguments.

>>> class Lin(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_n_in(self): return 2
...   def get_name_in(self, i): return ["x", "a"][i]
...   def get_name_out(self, i): return "y"
...   def eval(self, arg):
...     return [arg[1]*arg[0]]
>>> f = Lin("f")
>>> f
Callback(f:(x,a)->(y) CallbackInternal)
>>> f(x=2, a=3)
{'y': DM(6)}

>> c = {'classdef Lin < casadi.Callback', 'methods'};
>> c = [c, {'function self = Lin(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function n = get_n_in(self)', 'n = 2;', 'end'}];
>> c = [c, {'function s = get_name_in(self, i)'}];
>> c = [c, {'names = {''x'', ''a''}; s = names{i+1};', 'end'}];
>> c = [c, {'function s = get_name_out(self, i)', 's = ''y'';', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{2}*arg{1}};'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'Lin.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = Lin('f'); disp(f)
f:(x,a)->(y) CallbackInternal
>> r = f('x', 2, 'a', 3); disp(r.y)
6
>> rmpath(d); rmdir(d, 's');

julia> struct Lin <: ca.Callback end
julia> ca.get_n_in(::Lin) = 2
julia> ca.get_name_in(::Lin, i) = ["x", "a"][i + 1]
julia> ca.get_name_out(::Lin, i) = "y"
julia> ca.eval_(::Lin, arg) = [arg[2] * arg[1]]
julia> f = ca.callback(Lin(), "f");
julia> ca.Function(f)
Function(f:(x,a)->(y) CallbackInternal)
julia> f(x=2, a=3)
Dict{String, DM} with 1 entry:
  "y" => 6

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

◆ get_name_out()

virtual std::string casadi::Callback::get_name_out ( casadi_int  i)
virtual

Called during construct(). Default: "o0", "o1", ...

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

◆ get_reverse()

virtual Function casadi::Callback::get_reverse ( casadi_int  nadj,
const std::string &  name,
const std::vector< std::string > &  inames,
const std::vector< std::string > &  onames,
const Dict &  opts 
) const
virtual

Override has_reverse(nadj) to return true for the numbers of directions you support and get_reverse() to return a Function with inputs [nominal inputs, nominal outputs, one adjoint seed per output] and one adjoint sensitivity per input. For nadj>1 the seeds and sensitivities are horizontally stacked. Reverse mode is what gradient-based NLP solvers use for the objective gradient. reverse(nadj) caches the result.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
...   def has_reverse(self, nadj): return nadj == 1
...   def get_reverse(self, nadj, name, inames, onames, opts):
...     print(nadj, name, inames, onames)
...     x, y, yb = SX.sym("x"), SX.sym("y", Sparsity(1, 1)), SX.sym("yb")
...     return Function(name, [x, y, yb], [2*x*yb], inames, onames, opts)
>>> f = Sq("f")
>>> x = MX.sym("x")
>>> G = Function("G", [x], [gradient(f(x), x)])
1 adj1_f ['i0', 'out_o0', 'adj_o0'] ['adj_i0']
>>> G(3)
DM(6)

>> c = {'classdef SqAdj < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqAdj(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end'}];
>> c = [c, {'function b = has_reverse(self, nadj)', 'b = nadj == 1;', 'end'}];
>> c = [c, {'function F = get_reverse(self, nadj, name, inames, onames, opts)'}];
>> c = [c, {'disp(nadj); disp(name); disp(inames); disp(onames);'}];
>> c = [c, {'x = casadi.SX.sym(''x''); y = casadi.SX.sym(''y'', casadi.Sparsity(1, 1));'}];
>> c = [c, {'yb = casadi.SX.sym(''yb'');'}];
>> c = [c, {'F = casadi.Function(name, {x, y, yb}, {2*x*yb}, inames, onames, opts);'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqAdj.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqAdj('f'); x = MX.sym('x'); G = Function('G', {x}, {gradient(f(x), x)});
1
adj1_f
i0
out_o0
adj_o0
adj_i0
>> G(3)
6
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> ca.has_reverse(::Sq, nadj) = nadj == 1
julia> function ca.get_reverse(::Sq, nadj, name, inames, onames, opts)
           println(nadj, " ", name, " ", inames, " ", onames)
           x = ca.SX.sym("x"); y = ca.SX.sym("y", ca.Sparsity(1, 1)); yb = ca.SX.sym("yb")
           ca.Function(name, [x, y, yb], [2x*yb], inames, onames, opts)
       end
julia> f = ca.callback(Sq(), "f");
julia> x = ca.MX.sym("x");
julia> G = ca.Function("G", [x], [ca.gradient(f(x), x)]);
1 adj1_f ["i0", "out_o0", "adj_o0"] ["adj_i0"]
julia> G(3)
DM(6)

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

◆ get_sparsity_in()

virtual Sparsity casadi::Callback::get_sparsity_in ( casadi_int  i)
virtual

Called during construct() for i in 0..n_in-1. Default: scalar (1-by-1 dense). Inputs are padded or projected to this pattern when the Function is called.

>>> class Trace(Callback):
...   def __init__(self, name, n, opts={}):
...     Callback.__init__(self)
...     self.n = n
...     self.construct(name, opts)
...   def get_sparsity_in(self, i): return Sparsity.diag(self.n)
...   def eval(self, arg):
...     return [sum1(diag(arg[0]))]
>>> f = Trace("f", 3)
>>> f.sparsity_in(0), f(DM.ones(3, 3))
(Sparsity(3x3,3nz), DM(3))

>> c = {'classdef TraceCb < casadi.Callback', 'properties', 'n', 'end', 'methods'};
>> c = [c, {'function self = TraceCb(name, n)'}];
>> c = [c, {'self@casadi.Callback(); self.n = n; construct(self, name);', 'end'}];
>> c = [c, {'function sp = get_sparsity_in(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.diag(self.n);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {sum1(diag(arg{1}))};'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'TraceCb.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = TraceCb('f', 3); disp(f.sparsity_in(0)), disp(f(DM.ones(3, 3)))
3x3,3nz
3
>> rmpath(d); rmdir(d, 's');

julia> struct Trace <: ca.Callback
           n::Int
       end
julia> ca.get_sparsity_in(cb::Trace, i) = ca.Sparsity.diag(cb.n)
julia> ca.eval_(::Trace, arg) = [ca.sum1(ca.diag(arg[1]))]
julia> f = ca.callback(Trace(3), "f");
julia> ca.sparsity_in(f, 0), f(ca.DM.ones(3, 3))
(3x3,3nz, 3)

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

◆ get_sparsity_out()

virtual Sparsity casadi::Callback::get_sparsity_out ( casadi_int  i)
virtual

Called during construct() for i in 0..n_out-1. Default: scalar (1-by-1 dense). The value returned by eval() for output i must have this shape.

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

◆ get_str()

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

Definition at line 91 of file shared_object.hpp.

◆ has_eval_buffer()

virtual bool casadi::Callback::has_eval_buffer ( ) const
virtual

Return true to have eval_buffer() called instead of eval(). Default: false.

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

◆ has_forward()

virtual bool casadi::Callback::has_forward ( casadi_int  nfwd) const
virtual

Override has_forward(nfwd) to return true for the numbers of directions you support (nfwd==1 is enough; CasADi then loops) and get_forward() to return a Function with inputs [nominal inputs, nominal outputs, one forward seed per input] and one forward sensitivity per output. For nfwd>1 the seeds and sensitivities are horizontally stacked (n-by-nfwd*m). forward(nfwd) on the Function caches the result.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
...   def has_forward(self, nfwd): return nfwd == 1
...   def get_forward(self, nfwd, name, inames, onames, opts):
...     print(nfwd, name, inames, onames)
...     x, y, xd = SX.sym("x"), SX.sym("y", Sparsity(1, 1)), SX.sym("xd")
...     return Function(name, [x, y, xd], [2*x*xd], inames, onames, opts)
>>> f = Sq("f")
>>> x = MX.sym("x")
>>> J = Function("J", [x], [jacobian(f(x), x)])
1 fwd1_f ['i0', 'out_o0', 'fwd_i0'] ['fwd_o0']
>>> J(3)
DM(6)

>> c = {'classdef SqFwd < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqFwd(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end'}];
>> c = [c, {'function b = has_forward(self, nfwd)', 'b = nfwd == 1;', 'end'}];
>> c = [c, {'function F = get_forward(self, nfwd, name, inames, onames, opts)'}];
>> c = [c, {'disp(nfwd); disp(name); disp(inames); disp(onames);'}];
>> c = [c, {'x = casadi.SX.sym(''x''); y = casadi.SX.sym(''y'', casadi.Sparsity(1, 1));'}];
>> c = [c, {'xd = casadi.SX.sym(''xd'');'}];
>> c = [c, {'F = casadi.Function(name, {x, y, xd}, {2*x*xd}, inames, onames, opts);'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqFwd.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqFwd('f'); x = MX.sym('x'); J = Function('J', {x}, {jacobian(f(x), x)});
1
fwd1_f
i0
out_o0
fwd_i0
fwd_o0
>> J(3)
6
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> ca.has_forward(::Sq, nfwd) = nfwd == 1
julia> function ca.get_forward(::Sq, nfwd, name, inames, onames, opts)
           println(nfwd, " ", name, " ", inames, " ", onames)
           x = ca.SX.sym("x"); y = ca.SX.sym("y", ca.Sparsity(1, 1)); xd = ca.SX.sym("xd")
           ca.Function(name, [x, y, xd], [2x*xd], inames, onames, opts)
       end
julia> f = ca.callback(Sq(), "f");
julia> x = ca.MX.sym("x");
julia> J = ca.Function("J", [x], [ca.jacobian(f(x), x)]);
1 fwd1_f ["i0", "out_o0", "fwd_i0"] ["fwd_o0"]
julia> J(3)
DM(6)

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

◆ has_free()

bool casadi::Function::has_free ( ) const
inherited

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
inherited

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
inherited

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

virtual bool casadi::Callback::has_jac_sparsity ( casadi_int  oind,
casadi_int  iind 
) const
inlinevirtual

with respect to all output elements. Override has_jac_sparsity(oind, iind) to return true and get_jac_sparsity() to return the pattern of the Jacobian block of output oind with respect to input iind. Without it the block is assumed dense. Finite differencing exploits the pattern (fewer evaluations) and the result of jacobian() carries it.

>>> class Diag(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_sparsity_in(self, i): return Sparsity.dense(3, 1)
...   def get_sparsity_out(self, i): return Sparsity.dense(3, 1)
...   def eval(self, arg):
...     return [arg[0]**2]
...   def has_jac_sparsity(self, oind, iind): return True
...   def get_jac_sparsity(self, oind, iind, symmetric): return Sparsity.diag(3)
>>> f = Diag("f", {"enable_fd": True})
>>> x = MX.sym("x", 3)
>>> J = jacobian(f(x), x)
>>> J.sparsity()
Sparsity(3x3,3nz)
>>> Function("J", [x], [J])([1, 2, 3])
DM(
[[2, 00, 00],
 [00, 4, 00],
 [00, 00, 6]])

>> c = {'classdef DiagCb < casadi.Callback', 'methods'};
>> c = [c, {'function self = DiagCb(name, opts)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name, opts);', 'end'}];
>> c = [c, {'function sp = get_sparsity_in(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(3, 1);', 'end'}];
>> c = [c, {'function sp = get_sparsity_out(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(3, 1);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}.^2};', 'end'}];
>> c = [c, {'function b = has_jac_sparsity(self, oind, iind)', 'b = true;', 'end'}];
>> c = [c, {'function sp = get_jac_sparsity(self, oind, iind, symmetric)'}];
>> c = [c, {'sp = casadi.Sparsity.diag(3);', 'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'DiagCb.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = DiagCb('f', struct('enable_fd', true)); x = MX.sym('x', 3); J = jacobian(f(x), x);
>> J.sparsity()
3x3,3nz
>> JF = Function('J', {x}, {J}); disp(JF([1; 2; 3]))
[[2, 00, 00],
 [00, 4, 00],
 [00, 00, 6]]
>> rmpath(d); rmdir(d, 's');

julia> struct Diag <: ca.Callback end
julia> ca.get_sparsity_in(::Diag, i) = ca.Sparsity.dense(3, 1)
julia> ca.get_sparsity_out(::Diag, i) = ca.Sparsity.dense(3, 1)
julia> ca.eval_(::Diag, arg) = [arg[1] .^ 2]
julia> ca.has_jac_sparsity(::Diag, oind, iind) = true
julia> ca.get_jac_sparsity(::Diag, oind, iind, symmetric) = ca.Sparsity.diag(3)
julia> f = ca.callback(Diag(), "f", Dict("enable_fd" => true));
julia> x = ca.MX.sym("x", 3);
julia> J = ca.jacobian(f(x), x);
julia> ca.sparsity(J)
Sparsity(3x3,3nz)
julia> ca.Function("J", [x], [J])([1, 2, 3])
DM(
[[2, 00, 00],
 [00, 4, 00],
 [00, 00, 6]])

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

Definition at line 1266 of file casadi/core/callback.hpp.

◆ has_jacobian()

virtual bool casadi::Callback::has_jacobian ( ) const
virtual

Override has_jacobian() to return true and get_jacobian() to return a Function with inputs [all nominal inputs, all nominal outputs] and one output per (output, input) pair, each the dense or sparse Jacobian block of that output with respect to that input (row-major over the pairs). Use the inames, onames and opts passed in: they carry the expected names and the "derivative_of" option. The returned Function may be an SX/MX Function (then higher derivatives are exact) or another Callback (keep a reference to it).

>>> class F43(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def get_sparsity_in(self, i): return Sparsity.dense(4, 1)
...   def get_sparsity_out(self, i): return Sparsity.dense(3, 1)
...   def eval(self, arg):
...     a, b, c, d = vertsplit(arg[0])
...     return [vertcat(sin(c)*d+d**2, 2*a+c, b**2+5*c)]
...   def has_jacobian(self): return True
...   def get_jacobian(self, name, inames, onames, opts):
...     print(name, inames, onames)
...     x = SX.sym("x", 4)
...     y = SX.sym("y", Sparsity(3, 1))
...     a, b, c, d = vertsplit(x)
...     J = blockcat([[0, 0, d*cos(c), sin(c)+2*d], [2, 0, 1, 0], [0, 2*b, 5, 0]])
...     return Function(name, [x, y], [J], inames, onames, opts)
>>> f = F43("f")
>>> x = MX.sym("x", 4)
>>> J = Function("J", [x], [jacobian(f(x), x)])
jac_f ['i0', 'out_o0'] ['jac_o0_i0']
>>> J([1, 2, 0, 3])
DM(
[[0, 0, 3, 6],
 [2, 0, 1, 0],
 [0, 4, 5, 0]])

>> c = {'classdef F43 < casadi.Callback', 'methods'};
>> c = [c, {'function self = F43(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function sp = get_sparsity_in(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(4, 1);', 'end'}];
>> c = [c, {'function sp = get_sparsity_out(self, i)'}];
>> c = [c, {'sp = casadi.Sparsity.dense(3, 1);', 'end'}];
>> c = [c, {'function r = eval(self, arg)'}];
>> c = [c, {'v = arg{1}; a = v(1); b = v(2); c = v(3); d = v(4);'}];
>> c = [c, {'r = {[sin(c)*d+d^2; 2*a+c; b^2+5*c]};', 'end'}];
>> c = [c, {'function b = has_jacobian(self)', 'b = true;', 'end'}];
>> c = [c, {'function J = get_jacobian(self, name, inames, onames, opts)'}];
>> c = [c, {'disp(name); disp(inames); disp(onames);'}];
>> c = [c, {'x = casadi.SX.sym(''x'', 4); a = x(1); b = x(2); c = x(3); d = x(4);'}];
>> c = [c, {'y = casadi.SX.sym(''y'', casadi.Sparsity(3, 1));'}];
>> c = [c, {'Jm = [0, 0, d*cos(c), sin(c)+2*d; 2, 0, 1, 0; 0, 2*b, 5, 0];'}];
>> c = [c, {'J = casadi.Function(name, {x, y}, {Jm}, inames, onames, opts);'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'F43.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = F43('f'); x = MX.sym('x', 4); J = Function('J', {x}, {jacobian(f(x), x)});
jac_f
i0
out_o0
jac_o0_i0
>> J([1; 2; 0; 3])
[[0, 0, 3, 6],
 [2, 0, 1, 0],
 [0, 4, 5, 0]]
>> rmpath(d); rmdir(d, 's');

julia> struct F43 <: ca.Callback end
julia> ca.get_sparsity_in(::F43, i) = ca.Sparsity.dense(4, 1)
julia> ca.get_sparsity_out(::F43, i) = ca.Sparsity.dense(3, 1)
julia> function ca.eval_(::F43, arg)
           a, b, c, d = arg[1][1], arg[1][2], arg[1][3], arg[1][4]
           [[sin(c)*d + d^2; 2a + c; b^2 + 5c]]
       end
julia> ca.has_jacobian(::F43) = true
julia> function ca.get_jacobian(::F43, name, inames, onames, opts)
           println(name, " ", inames, " ", onames)
           x = ca.SX.sym("x", 4); y = ca.SX.sym("y", ca.Sparsity(3, 1))
           a, b, c, d = x[1], x[2], x[3], x[4]
           J = [0 0 d*cos(c) sin(c)+2d; 2 0 1 0; 0 2b 5 0]
           ca.Function(name, [x, y], [J], inames, onames, opts)
       end
julia> f = ca.callback(F43(), "f");
julia> x = ca.MX.sym("x", 4);
julia> J = ca.Function("J", [x], [ca.jacobian(f(x), x)]);
jac_f ["i0", "out_o0"] ["jac_o0_i0"]
julia> J([1, 2, 0, 3])
DM(
[[0, 0, 3, 6],
 [2, 0, 1, 0],
 [0, 4, 5, 0]])

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

◆ has_option()

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

>>> 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
inherited

◆ has_reverse()

virtual bool casadi::Callback::has_reverse ( casadi_int  nadj) const
virtual

Override has_reverse(nadj) to return true for the numbers of directions you support and get_reverse() to return a Function with inputs [nominal inputs, nominal outputs, one adjoint seed per output] and one adjoint sensitivity per input. For nadj>1 the seeds and sensitivities are horizontally stacked. Reverse mode is what gradient-based NLP solvers use for the objective gradient. reverse(nadj) caches the result.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
...   def has_reverse(self, nadj): return nadj == 1
...   def get_reverse(self, nadj, name, inames, onames, opts):
...     print(nadj, name, inames, onames)
...     x, y, yb = SX.sym("x"), SX.sym("y", Sparsity(1, 1)), SX.sym("yb")
...     return Function(name, [x, y, yb], [2*x*yb], inames, onames, opts)
>>> f = Sq("f")
>>> x = MX.sym("x")
>>> G = Function("G", [x], [gradient(f(x), x)])
1 adj1_f ['i0', 'out_o0', 'adj_o0'] ['adj_i0']
>>> G(3)
DM(6)

>> c = {'classdef SqAdj < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqAdj(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end'}];
>> c = [c, {'function b = has_reverse(self, nadj)', 'b = nadj == 1;', 'end'}];
>> c = [c, {'function F = get_reverse(self, nadj, name, inames, onames, opts)'}];
>> c = [c, {'disp(nadj); disp(name); disp(inames); disp(onames);'}];
>> c = [c, {'x = casadi.SX.sym(''x''); y = casadi.SX.sym(''y'', casadi.Sparsity(1, 1));'}];
>> c = [c, {'yb = casadi.SX.sym(''yb'');'}];
>> c = [c, {'F = casadi.Function(name, {x, y, yb}, {2*x*yb}, inames, onames, opts);'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqAdj.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqAdj('f'); x = MX.sym('x'); G = Function('G', {x}, {gradient(f(x), x)});
1
adj1_f
i0
out_o0
adj_o0
adj_i0
>> G(3)
6
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> ca.has_reverse(::Sq, nadj) = nadj == 1
julia> function ca.get_reverse(::Sq, nadj, name, inames, onames, opts)
           println(nadj, " ", name, " ", inames, " ", onames)
           x = ca.SX.sym("x"); y = ca.SX.sym("y", ca.Sparsity(1, 1)); yb = ca.SX.sym("yb")
           ca.Function(name, [x, y, yb], [2x*yb], inames, onames, opts)
       end
julia> f = ca.callback(Sq(), "f");
julia> x = ca.MX.sym("x");
julia> G = ca.Function("G", [x], [ca.gradient(f(x), x)]);
1 adj1_f ["i0", "out_o0", "adj_o0"] ["adj_i0"]
julia> G(3)
DM(6)

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

◆ has_spfwd()

bool casadi::Function::has_spfwd ( ) const
inherited

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
inherited

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
inherited

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

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
inherited

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
inherited

◆ info()

Dict casadi::Function::info ( ) const
inherited

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

◆ init()

virtual void casadi::Callback::init ( )
inlinevirtual

Called from construct() after the inputs and outputs are known and the options are processed, before finalize(). Override to allocate data; the default does nothing.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     print("before construct")
...     self.construct(name, opts)
...     print("after construct")
...   def init(self): print("init", self.n_in())
...   def finalize(self): print("finalize")
...   def eval(self, arg):
...     return [arg[0]**2]
>>> f = Sq("f")
before construct
init 1
finalize
after construct

>> c = {'classdef SqInit < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqInit(name)'}];
>> c = [c, {'self@casadi.Callback(); disp(''before construct'');'}];
>> c = [c, {'construct(self, name); disp(''after construct'');', 'end'}];
>> c = [c, {'function init(self)', 'fprintf(''init %d\n'', self.n_in());', 'end'}];
>> c = [c, {'function finalize(self)', 'disp(''finalize'');', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqInit.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqInit('f');
before construct
init 1
finalize
after construct
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.init(::Sq) = println("init")
julia> ca.finalize(::Sq) = println("finalize")
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> begin
           println("before construct")
           f = ca.callback(Sq(), "f")
           println("after construct")
       end
before construct
init
finalize
after construct

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

Definition at line 471 of file casadi/core/callback.hpp.

◆ instruction_constant()

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

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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

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

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

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
inherited

◆ map() [2/5]

Function casadi::Function::map ( casadi_int  n,
const std::string &  parallelization = "serial" 
) const
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

◆ mx_in() [1/3]

const std::vector<MX> casadi::Function::mx_in ( ) const
inherited

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
inherited

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
inlineinherited

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
inherited

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
inherited

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
inlineinherited

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
inherited

>>> 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
inherited

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
inherited

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
inherited

>>> 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
inherited

>>> 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
inherited

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
inherited

◆ name_out() [1/2]

const std::vector<std::string>& casadi::Function::name_out ( ) const
inherited

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
inherited

◆ nnz_in() [1/3]

casadi_int casadi::Function::nnz_in ( ) const
inherited

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
inherited

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
inlineinherited

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
inherited

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
inherited

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
inlineinherited

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
inherited

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
inherited

◆ numel_in() [1/3]

casadi_int casadi::Function::numel_in ( ) const
inherited

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
inherited

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
inlineinherited

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
inherited

>>> 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
inherited

>>> 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
inlineinherited

>>> 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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

>>> 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
inherited

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
inherited

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
inherited

◆ reset_dump_count()

void casadi::Function::reset_dump_count ( )
inherited

dump_out and dump_trace

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

◆ reverse()

Function casadi::Function::reverse ( casadi_int  nadj) const
inherited

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
inherited

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
inherited

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
inherited

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
inlineinherited

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
inherited

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
inlineinherited

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
inherited

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
inlineinherited

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
inherited

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
inlineinherited

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
inherited

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
inlineinherited

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
inherited

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
inlineinherited

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
inherited

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
inherited

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
inherited

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
inherited

[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
inlineinherited

[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
inlineinherited

[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
inlineinherited

[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
inherited

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
inherited

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
inherited

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
inherited

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
inherited

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
inlineinherited

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
inherited

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
inherited

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
inlineinherited

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
inherited

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
inherited

◆ sz_res()

size_t casadi::Function::sz_res ( ) const
inherited

◆ sz_w()

size_t casadi::Function::sz_w ( ) const
inherited

◆ transform() [1/4]

Function casadi::Function::transform ( const Dict &  opts = Dict()) const
inherited

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
inherited

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
inherited

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
inherited

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::Callback::type_name ( )
inlinestatic

◆ uses_output()

virtual bool casadi::Callback::uses_output ( ) const
virtual

Derivative functions obtained from get_jacobian/get_forward/get_reverse receive the nominal outputs as extra inputs. When this returns false (default) those inputs are passed as empty (all-zero sparsity) placeholders; return true to receive the actual output values, e.g. to reuse them in the derivative computation.

>>> class Sq(Callback):
...   def __init__(self, name, opts={}):
...     Callback.__init__(self)
...     self.construct(name, opts)
...   def eval(self, arg):
...     return [arg[0]**2]
...   def has_jacobian(self): return True
...   def get_jacobian(self, name, inames, onames, opts):
...     x = SX.sym("x")
...     y = SX.sym("y", self.sparsity_out(0) if self.uses_output() else Sparsity(1, 1))
...     return Function(name, [x, y], [2*x], inames, onames, opts)
>>> class SqU(Sq):
...   def uses_output(self): return True
>>> Sq("f").jacobian().sparsity_in(1), SqU("f").jacobian().sparsity_in(1)
(Sparsity(1x1,0nz), Sparsity(1x1))

>> c = {'classdef SqJac < casadi.Callback', 'methods'};
>> c = [c, {'function self = SqJac(name)'}];
>> c = [c, {'self@casadi.Callback(); construct(self, name);', 'end'}];
>> c = [c, {'function r = eval(self, arg)', 'r = {arg{1}^2};', 'end'}];
>> c = [c, {'function b = has_jacobian(self)', 'b = true;', 'end'}];
>> c = [c, {'function J = get_jacobian(self, name, inames, onames, opts)'}];
>> c = [c, {'x = casadi.SX.sym(''x''); y = casadi.SX.sym(''y'', casadi.Sparsity(1, 1));'}];
>> c = [c, {'if self.uses_output(), y = casadi.SX.sym(''y'', self.sparsity_out(0)); end'}];
>> c = [c, {'J = casadi.Function(name, {x, y}, {2*x}, inames, onames, opts);'}];
>> c = [c, {'end', 'end', 'end'}];
>> d = tempname; mkdir(d); addpath(d); fid = fopen(fullfile(d, 'SqJac.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> c = {'classdef SqJacU < SqJac', 'methods', 'function self = SqJacU(name)'};
>> c = [c, {'self@SqJac(name);', 'end', 'function b = uses_output(self)', 'b = true;'}];
>> c = [c, {'end', 'end', 'end'}]; fid = fopen(fullfile(d, 'SqJacU.m'), 'w');
>> fprintf(fid, '%s\n', c{:}); fclose(fid);
>> f = SqJac('f'); J = f.jacobian(); disp(J.sparsity_in(1))
1x1,0nz
>> g = SqJacU('g'); J = g.jacobian(); disp(J.sparsity_in(1))
1x1
>> rmpath(d); rmdir(d, 's');

julia> struct Sq <: ca.Callback end
julia> ca.eval_(::Sq, arg) = [arg[1]^2]
julia> ca.has_jacobian(::Sq) = true
julia> function ca.get_jacobian(::Sq, name, inames, onames, opts)
           x = ca.SX.sym("x"); y = ca.SX.sym("y", ca.Sparsity(1, 1))
           ca.Function(name, [x, y], [2x], inames, onames, opts)
       end
julia> ca.sparsity_in(ca.jacobian(ca.callback(Sq(), "f")), 1)
Sparsity(1x1,0nz)

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

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

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
inherited

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
inherited

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
inherited

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
inherited

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: