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

'blocksqp' plugin for Nlpsol More...

#include <blocksqp.hpp>

Detailed Description

This is a modified version of blockSQP by Janka et al.

Author
Dennis Janka, Joel Andersson
Date
2012-2015, 2016

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


List of available options
IdTypeDescription
block_hessOT_INTBlockwise Hessian approximation?
col_epsOT_DOUBLEEpsilon for COL scaling strategy
col_tau1OT_DOUBLEtau1 for COL scaling strategy
col_tau2OT_DOUBLEtau2 for COL scaling strategy
conv_strategyOT_INTConvexification strategy
deltaOT_DOUBLEFilter line search parameter, cf. IPOPT paper
delta_h0OT_DOUBLEFilter line search parameter, cf. IPOPT paper
epsOT_DOUBLEValues smaller than this are regarded as numerically zero
etaOT_DOUBLEFilter line search parameter, cf. IPOPT paper
fallback_scalingOT_INTIf indefinite update is used, the type of fallback strategy
fallback_updateOT_INTIf indefinite update is used, the type of fallback strategy
gamma_fOT_DOUBLEFilter line search parameter, cf. IPOPT paper
gamma_thetaOT_DOUBLEFilter line search parameter, cf. IPOPT paper
globalizationOT_BOOLEnable globalization
hess_dampOT_INTActivate Powell damping for BFGS
hess_damp_facOT_DOUBLEDamping factor for BFGS Powell modification
hess_lim_memOT_INTFull or limited memory
hess_memsizeOT_INTMemory size for L-BFGS updates
hess_scalingOT_INTScaling strategy for Hessian approximation
hess_updateOT_INTType of Hessian approximation
ini_hess_diagOT_DOUBLEInitial Hessian guess: diagonal matrix diag(iniHessDiag)
kappa_fOT_DOUBLEFilter line search parameter, cf. IPOPT paper
kappa_minusOT_DOUBLEFilter line search parameter, cf. IPOPT paper
kappa_plusOT_DOUBLEFilter line search parameter, cf. IPOPT paper
kappa_plus_maxOT_DOUBLEFilter line search parameter, cf. IPOPT paper
kappa_socOT_DOUBLEFilter line search parameter, cf. IPOPT paper
linsolOT_STRINGThe linear solver to be used by the QP method
max_consec_reduced_stepsOT_INTMaximum number of consecutive reduced steps
max_consec_skipped_updatesOT_INTMaximum number of consecutive skipped updates
max_conv_qpOT_INTHow many additional QPs may be solved for convexification per iteration?
max_it_qpOT_INTMaximum number of QP iterations per SQP iteration
max_iterOT_INTMaximum number of SQP iterations
max_line_searchOT_INTMaximum number of steps in line search
max_soc_iterOT_INTMaximum number of SOC line search iterations
max_time_qpOT_DOUBLEMaximum number of time in seconds per QP solve per SQP iteration
nlinfeastolOT_DOUBLENonlinear feasibility tolerance
obj_loOT_DOUBLELower bound on objective function [-inf]
obj_upOT_DOUBLEUpper bound on objective function [inf]
opttolOT_DOUBLEOptimality tolerance
print_headerOT_BOOLPrint solver header at startup
print_iterationOT_BOOLPrint SQP iterations
print_maxit_reachedOT_BOOLPrint error when maximum number of SQP iterations reached
qp_initOT_BOOLUse warmstarting
qpsolOT_STRINGThe QP solver to be used by the SQP method
qpsol_optionsOT_DICTOptions to be passed to the QP solver
restore_feasOT_BOOLUse feasibility restoration phase
rhoOT_DOUBLEFeasibility restoration phase parameter
s_fOT_DOUBLEFilter line search parameter, cf. IPOPT paper
s_thetaOT_DOUBLEFilter line search parameter, cf. IPOPT paper
schurOT_BOOLUse qpOASES Schur compliment approach
skip_first_globalizationOT_BOOLNo globalization strategy in first iteration
theta_maxOT_DOUBLEFilter line search parameter, cf. IPOPT paper
theta_minOT_DOUBLEFilter line search parameter, cf. IPOPT paper
warmstartOT_BOOLUse warmstarting
which_second_dervOT_INTFor which block should second derivatives be provided by the user
zetaOT_DOUBLEFeasibility restoration phase parameter


List of available options
IdTypeDescriptionUsed in
ad_weightOT_DOUBLEWeighting factor for derivative calculation.When there is an option of either using forward or reverse mode directional derivatives, the condition ad_weight*nf<=(1-ad_weight)*na is used where nf and na are estimates of the number of forward/reverse mode directional derivatives needed. By default, ad_weight is calculated automatically, but this can be overridden by setting this option. In particular, 0 means forcing forward mode and 1 forcing reverse mode. Leave unset for (class specific) heuristics.casadi::FunctionInternal
ad_weight_spOT_DOUBLEWeighting factor for sparsity pattern calculation calculation.Overrides default behavior. Set to 0 and 1 to force forward and reverse mode respectively. Cf. option "ad_weight". When set to -1, sparsity is completely ignored and dense matrices are used.casadi::FunctionInternal
always_inlineOT_BOOLForce inlining.casadi::FunctionInternal
block_hessOT_INTBlockwise Hessian approximation?casadi::Blocksqp
bound_consistencyOT_BOOLEnsure that primal-dual solution is consistent with the boundscasadi::Nlpsol
cacheOT_DICTPrepopulate the function cache. Default: emptycasadi::FunctionInternal
calc_fOT_BOOLCalculate 'f' in the Nlpsol base classcasadi::Nlpsol
calc_gOT_BOOLCalculate 'g' in the Nlpsol base classcasadi::Nlpsol
calc_lam_pOT_BOOLCalculate 'lam_p' in the Nlpsol base classcasadi::Nlpsol
calc_lam_xOT_BOOLCalculate 'lam_x' in the Nlpsol base classcasadi::Nlpsol
calc_multipliersOT_BOOLCalculate Lagrange multipliers in the Nlpsol base classcasadi::Nlpsol
col_epsOT_DOUBLEEpsilon for COL scaling strategycasadi::Blocksqp
col_tau1OT_DOUBLEtau1 for COL scaling strategycasadi::Blocksqp
col_tau2OT_DOUBLEtau2 for COL scaling strategycasadi::Blocksqp
common_optionsOT_DICTOptions for auto-generated functionscasadi::OracleFunction
compilerOT_STRINGJust-in-time compiler plugin to be used.casadi::FunctionInternal
conv_strategyOT_INTConvexification strategycasadi::Blocksqp
custom_jacobianOT_FUNCTIONOverride CasADi's AD. Use together with 'jac_penalty': 0. Note: Highly experimental. Syntax may break often.casadi::FunctionInternal
deltaOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
delta_h0OT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
der_optionsOT_DICTDefault options to be used to populate forward_options, reverse_options, and jacobian_options before those options are merged in.casadi::FunctionInternal
derivative_ofOT_FUNCTIONThe function is a derivative of another function. The type of derivative (directional derivative, Jacobian) is inferred from the function name.casadi::FunctionInternal
detect_simple_boundsOT_BOOLAutomatically detect simple bounds (lbx/ubx) (default false). This is hopefully beneficial to speed and robustness but may also have adverse affects: 1) Subtleties in heuristics and stopping criteria may change the solution, 2) IPOPT may lie about multipliers of simple equality bounds unless 'fixed_variable_treatment' is set to 'relax_bounds'.casadi::Nlpsol
detect_simple_bounds_is_simpleOT_BOOLVECTORFor internal use only.casadi::Nlpsol
detect_simple_bounds_partsOT_FUNCTIONFor internal use only.casadi::Nlpsol
detect_simple_bounds_target_xOT_INTVECTORFor internal use only.casadi::Nlpsol
discreteOT_BOOLVECTORIndicates which of the variables are discrete, i.e. integer-valuedcasadi::Nlpsol
dumpOT_BOOLDump function to file upon first evaluation. [false]casadi::FunctionInternal
dump_dirOT_STRINGDirectory to dump inputs/outputs to. Make sure the directory exists [.]casadi::FunctionInternal
dump_formatOT_STRINGChoose file format to dump matrices. See DM.from_file [mtx]casadi::FunctionInternal
dump_inOT_BOOLDump numerical values of inputs to file (readable with DM.from_file) [default: false] A counter is used to generate unique names. The counter may be reset using reset_dump_count.casadi::FunctionInternal
dump_outOT_BOOLDump numerical values of outputs to file (readable with DM.from_file) [default: false] A counter is used to generate unique names. The counter may be reset using reset_dump_count.casadi::FunctionInternal
enable_fdOT_BOOLEnable derivative calculation by finite differencing. [default: false]]casadi::FunctionInternal
enable_forwardOT_BOOLEnable derivative calculation using generated functions for Jacobian-times-vector products - typically using forward mode AD - if available. [default: true]casadi::FunctionInternal
enable_jacobianOT_BOOLEnable derivative calculation using generated functions for Jacobians of all differentiable outputs with respect to all differentiable inputs - if available. [default: true]casadi::FunctionInternal
enable_reverseOT_BOOLEnable derivative calculation using generated functions for transposed Jacobian-times-vector products - typically using reverse mode AD - if available. [default: true]casadi::FunctionInternal
epsOT_DOUBLEValues smaller than this are regarded as numerically zerocasadi::Blocksqp
equalityOT_BOOLVECTORIndicate an upfront hint which of the constraints are equalities. Some solvers may be able to exploit this knowledge. When true, the corresponding lower and upper bounds are assumed equal. When false, the corresponding bounds may be equal or different.casadi::Nlpsol
error_on_failOT_BOOLThrow exceptions when function evaluation fails (default true).casadi::ProtoFunction
etaOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
eval_errors_fatalOT_BOOLWhen errors occur during evaluation of f,g,...,stop the iterationscasadi::Nlpsol
expandOT_BOOLReplace MX with SX expressions in problem formulation [false] This happens before creating derivatives unless indicated by postpone_expandcasadi::OracleFunction
external_transformOT_VECTORVECTORList of external_transform instruction arguments. Default: emptycasadi::FunctionInternal
fallback_scalingOT_INTIf indefinite update is used, the type of fallback strategycasadi::Blocksqp
fallback_updateOT_INTIf indefinite update is used, the type of fallback strategycasadi::Blocksqp
fd_methodOT_STRINGMethod for finite differencing [default 'central']casadi::FunctionInternal
fd_optionsOT_DICTOptions to be passed to the finite difference instancecasadi::FunctionInternal
forward_optionsOT_DICTOptions to be passed to a forward mode constructorcasadi::FunctionInternal
gamma_fOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
gamma_thetaOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
gather_statsOT_BOOLDeprecated option (ignored): Statistics are now always collected.casadi::FunctionInternal
globalizationOT_BOOLEnable globalizationcasadi::Blocksqp
hess_dampOT_INTActivate Powell damping for BFGScasadi::Blocksqp
hess_damp_facOT_DOUBLEDamping factor for BFGS Powell modificationcasadi::Blocksqp
hess_lim_memOT_INTFull or limited memorycasadi::Blocksqp
hess_memsizeOT_INTMemory size for L-BFGS updatescasadi::Blocksqp
hess_scalingOT_INTScaling strategy for Hessian approximationcasadi::Blocksqp
hess_updateOT_INTType of Hessian approximationcasadi::Blocksqp
ignore_check_vecOT_BOOLIf set to true, the input shape of F will not be checked.casadi::Nlpsol
ini_hess_diagOT_DOUBLEInitial Hessian guess: diagonal matrix diag(iniHessDiag)casadi::Blocksqp
inputs_checkOT_BOOLThrow exceptions when the numerical values of the inputs don't make sensecasadi::FunctionInternal
is_diff_inOT_BOOLVECTORIndicate for each input if it should be differentiable.casadi::FunctionInternal
is_diff_outOT_BOOLVECTORIndicate for each output if it should be differentiable.casadi::FunctionInternal
iteration_callbackOT_FUNCTIONA function that will be called at each iteration with the solver as input. Check documentation of Callback.casadi::Nlpsol
iteration_callback_ignore_errorsOT_BOOLIf set to true, errors thrown by iteration_callback will be ignored.casadi::Nlpsol
iteration_callback_stepOT_INTOnly call the callback function every few iterations.casadi::Nlpsol
jac_penaltyOT_DOUBLEWhen requested for a number of forward/reverse directions, it may be cheaper to compute first the full jacobian and then multiply with seeds, rather than obtain the requested directions in a straightforward manner. Casadi uses a heuristic to decide which is cheaper. A high value of 'jac_penalty' makes it less likely for the heurstic to chose the full Jacobian strategy. The special value -1 indicates never to use the full Jacobian strategycasadi::FunctionInternal
jacobian_optionsOT_DICTOptions to be passed to a Jacobian constructorcasadi::FunctionInternal
jitOT_BOOLUse just-in-time compiler to speed up the evaluationcasadi::FunctionInternal
jit_cleanupOT_BOOLCleanup up the temporary source file that jit creates. Default: truecasadi::FunctionInternal
jit_nameOT_STRINGThe file name used to write out code. The actual file names used depend on 'jit_temp_suffix' and include extensions. Default: 'jit_tmp'casadi::FunctionInternal
jit_optionsOT_DICTOptions to be passed to the jit compiler.casadi::FunctionInternal
jit_serializeOT_STRINGSpecify behaviour when serializing a jitted function: SOURCE|link|embed.casadi::FunctionInternal
jit_temp_suffixOT_BOOLUse a temporary (seemingly random) filename suffix for generated code and libraries. This is desired for thread-safety. This behaviour may defeat caching compiler wrappers. Default: truecasadi::FunctionInternal
kappa_fOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
kappa_minusOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
kappa_plusOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
kappa_plus_maxOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
kappa_socOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
linsolOT_STRINGThe linear solver to be used by the QP methodcasadi::Blocksqp
max_consec_reduced_stepsOT_INTMaximum number of consecutive reduced stepscasadi::Blocksqp
max_consec_skipped_updatesOT_INTMaximum number of consecutive skipped updatescasadi::Blocksqp
max_conv_qpOT_INTHow many additional QPs may be solved for convexification per iteration?casadi::Blocksqp
max_ioOT_INTAcceptable number of inputs and outputs. Warn if exceeded.casadi::FunctionInternal
max_it_qpOT_INTMaximum number of QP iterations per SQP iterationcasadi::Blocksqp
max_iterOT_INTMaximum number of SQP iterationscasadi::Blocksqp
max_line_searchOT_INTMaximum number of steps in line searchcasadi::Blocksqp
max_num_dirOT_INTSpecify the maximum number of directions for derivative functions. Overrules the builtin optimized_num_dir.casadi::FunctionInternal
max_soc_iterOT_INTMaximum number of SOC line search iterationscasadi::Blocksqp
max_time_qpOT_DOUBLEMaximum number of time in seconds per QP solve per SQP iterationcasadi::Blocksqp
min_lamOT_DOUBLEMinimum allowed multiplier valuecasadi::Nlpsol
monitorOT_STRINGVECTORSet of user problem functions to be monitoredcasadi::OracleFunction
never_inlineOT_BOOLForbid inlining.casadi::FunctionInternal
nlinfeastolOT_DOUBLENonlinear feasibility tolerancecasadi::Blocksqp
no_nlp_gradOT_BOOLPrevent the creation of the 'nlp_grad' functioncasadi::Nlpsol
obj_loOT_DOUBLELower bound on objective function [-inf]casadi::Blocksqp
obj_upOT_DOUBLEUpper bound on objective function [inf]casadi::Blocksqp
opttolOT_DOUBLEOptimality tolerancecasadi::Blocksqp
oracle_optionsOT_DICTOptions to be passed to the oracle functioncasadi::Nlpsol
post_expandOT_BOOLAfter construction, expand this Function. Default: Falsecasadi::FunctionInternal
post_expand_optionsOT_DICTOptions to be passed to post-construction expansion. Default: emptycasadi::FunctionInternal
postpone_expandOT_BOOLWhen expand is active, postpone it until after creation of derivatives. Default: Falsecasadi::OracleFunction
print_canonicalOT_BOOLWhen printing numerical matrices, use a format that is exact and reproducible in generated C code.casadi::FunctionInternal
print_headerOT_BOOLPrint solver header at startupcasadi::Blocksqp
print_inOT_BOOLPrint numerical values of inputs [default: false]casadi::FunctionInternal
print_iterationOT_BOOLPrint SQP iterationscasadi::Blocksqp
print_maxit_reachedOT_BOOLPrint error when maximum number of SQP iterations reachedcasadi::Blocksqp
print_outOT_BOOLPrint numerical values of outputs [default: false]casadi::FunctionInternal
print_timeOT_BOOLprint information about execution time. Implies record_time.casadi::ProtoFunction
qp_initOT_BOOLUse warmstartingcasadi::Blocksqp
qpsolOT_STRINGThe QP solver to be used by the SQP methodcasadi::Blocksqp
qpsol_optionsOT_DICTOptions to be passed to the QP solvercasadi::Blocksqp
record_timeOT_BOOLrecord information about execution time, for retrieval with stats().casadi::ProtoFunction
regularity_checkOT_BOOLThrow exceptions when NaN or Inf appears during evaluationcasadi::ProtoFunction
restore_feasOT_BOOLUse feasibility restoration phasecasadi::Blocksqp
reverse_optionsOT_DICTOptions to be passed to a reverse mode constructorcasadi::FunctionInternal
rhoOT_DOUBLEFeasibility restoration phase parametercasadi::Blocksqp
s_fOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
s_thetaOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
schurOT_BOOLUse qpOASES Schur compliment approachcasadi::Blocksqp
sens_linsolOT_STRINGLinear solver used for parametric sensitivities (default 'qr').casadi::Nlpsol
sens_linsol_optionsOT_DICTLinear solver options used for parametric sensitivities.casadi::Nlpsol
show_eval_warningsOT_BOOLShow warnings generated from function evaluations [true]casadi::OracleFunction
skip_first_globalizationOT_BOOLNo globalization strategy in first iterationcasadi::Blocksqp
specific_optionsOT_DICTOptions for specific auto-generated functions, overwriting the defaults from common_options. Nested dictionary.casadi::OracleFunction
theta_maxOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
theta_minOT_DOUBLEFilter line search parameter, cf. IPOPT papercasadi::Blocksqp
user_dataOT_VOIDPTRA user-defined field that can be used to identify the function or pass additional informationcasadi::FunctionInternal
verboseOT_BOOLVerbose evaluation – for debuggingcasadi::ProtoFunction
verbose_initOT_BOOLPrint out timing information about the different stages of initializationcasadi::Nlpsol
warmstartOT_BOOLUse warmstartingcasadi::Blocksqp
warn_initial_boundsOT_BOOLWarn if the initial guess does not satisfy LBX and UBXcasadi::Nlpsol
which_second_dervOT_INTFor which block should second derivatives be provided by the usercasadi::Blocksqp
zetaOT_DOUBLEFeasibility restoration phase parametercasadi::Blocksqp

Definition at line 151 of file blocksqp.hpp.

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

Public Types

typedef Nlpsol *(* Creator) (const std::string &name, const Function &oracle)
 
using weak_ref_type = WeakRefInternal
 
typedef int(* RegFcn) (Plugin *plugin)
 

Public Member Functions

 Blocksqp (const std::string &name, const Function &nlp)
 
 ~Blocksqp () override
 
const char * plugin_name () const override
 
std::string class_name () const override
 Get type name. More...
 
void init (const Dict &opts) override
 Initialize. More...
 
void * alloc_mem () const override
 Create memory block. More...
 
int init_mem (void *mem) const override
 Initalize memory block. More...
 
void free_mem (void *mem) const override
 Free memory block. More...
 
void set_work (void *mem, const double **&arg, double **&res, casadi_int *&iw, double *&w) const override
 Set the (persistent) work vectors. More...
 
int solve (void *mem) const override
 
casadi_int run (BlocksqpMemory *m, casadi_int maxIt, casadi_int warmStart=0) const
 Main Loop of SQP method. More...
 
void calcLagrangeGradient (BlocksqpMemory *m, const double *lam_x, const double *lam_g, const double *grad_f, const double *jacNz, double *grad_lag, casadi_int flag) const
 Compute gradient of Lagrangian function (sparse version) More...
 
void calcLagrangeGradient (BlocksqpMemory *m, double *grad_lag, casadi_int flag) const
 Overloaded function for convenience, uses current variables of SQPiterate vars. More...
 
void printInfo (BlocksqpMemory *m) const
 Print information about the SQP method. More...
 
bool calcOptTol (BlocksqpMemory *m) const
 Update optimization tolerance (similar to SNOPT) in current iterate. More...
 
void updateStepBounds (BlocksqpMemory *m, bool soc) const
 
casadi_int solveQP (BlocksqpMemory *m, double *deltaXi, double *lambdaQP, bool matricesChanged=true) const
 
void computeNextHessian (BlocksqpMemory *m, casadi_int idx, casadi_int maxQP) const
 
casadi_int fullstep (BlocksqpMemory *m) const
 No globalization strategy. More...
 
void acceptStep (BlocksqpMemory *m, const double *deltaXi, const double *lambdaQP, double alpha, casadi_int nSOCS) const
 Set new primal dual iterate. More...
 
void acceptStep (BlocksqpMemory *m, double alpha) const
 
void reduceStepsize (BlocksqpMemory *m, double *alpha) const
 
casadi_int filterLineSearch (BlocksqpMemory *m) const
 
void initializeFilter (BlocksqpMemory *m) const
 
bool pairInFilter (BlocksqpMemory *m, double cNorm, double obj) const
 
void augmentFilter (BlocksqpMemory *m, double cNorm, double obj) const
 
bool secondOrderCorrection (BlocksqpMemory *m, double cNorm, double cNormTrial, double dfTdeltaXi, bool swCond, casadi_int it) const
 
void reduceSOCStepsize (BlocksqpMemory *m, double *alphaSOC) const
 
casadi_int feasibilityRestorationHeuristic (BlocksqpMemory *m) const
 
casadi_int feasibilityRestorationPhase (BlocksqpMemory *m) const
 
casadi_int kktErrorReduction (BlocksqpMemory *m) const
 
void calcInitialHessian (BlocksqpMemory *m) const
 
void calcInitialHessian (BlocksqpMemory *m, casadi_int b) const
 
void resetHessian (BlocksqpMemory *m) const
 
void resetHessian (BlocksqpMemory *m, casadi_int b) const
 
void calcHessianUpdate (BlocksqpMemory *m, casadi_int updateType, casadi_int hessScaling) const
 
void calcHessianUpdateLimitedMemory (BlocksqpMemory *m, casadi_int updateType, casadi_int hessScaling) const
 
void calcHessianUpdateExact (BlocksqpMemory *m) const
 
void calcSR1 (BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b) const
 
void calcBFGS (BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b) const
 
void updateDeltaGamma (BlocksqpMemory *m) const
 
void sizeInitialHessian (BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b, casadi_int option) const
 
void sizeHessianCOL (BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b) const
 
void initStats (BlocksqpMemory *m) const
 
void updateStats (BlocksqpMemory *m) const
 
void printProgress (BlocksqpMemory *m) const
 Print one line of output to stdout about the current iteration. More...
 
void reset_sqp (BlocksqpMemory *m) const
 Reset variables that any SQP code needs. More...
 
void convertHessian (BlocksqpMemory *m) const
 Convert *hess to column compressed sparse format. More...
 
void initIterate (BlocksqpMemory *m) const
 Set initial filter, objective function, tolerances etc. More...
 
casadi_int evaluate (BlocksqpMemory *m, double *f, double *g, double *grad_f, double *jac_g) const
 Evaluate objective and constraints, including derivatives. More...
 
casadi_int evaluate (BlocksqpMemory *m, const double *xk, double *f, double *g) const
 Evaluate objective and constraints, no derivatives. More...
 
casadi_int evaluate (BlocksqpMemory *m, double *exact_hess_lag) const
 Evaluate exact hessian of Lagrangian. More...
 
double lInfConstraintNorm (BlocksqpMemory *m, const double *xk, const double *g) const
 
void serialize_body (SerializingStream &s) const override
 Serialize an object without type information. More...
 
void serialize_type (SerializingStream &s) const override
 Serialize type information. More...
 
std::string serialize_base_function () const override
 String used to identify the immediate FunctionInternal subclass. More...
 
void disp_more (std::ostream &stream) const override
 Print description. More...
 
virtual void check_inputs (void *mem) const
 Check if the inputs correspond to a well-posed problem. More...
 
double get_default_in (casadi_int ind) const override
 Get default input value. More...
 
virtual bool integer_support () const
 Can discrete variables be treated. More...
 
int eval (const double **arg, double **res, casadi_int *iw, double *w, void *mem) const final
 Evaluate numerically. More...
 
void codegen_declarations (CodeGenerator &g) const override
 Generate code for the declarations of the C function. More...
 
void codegen_body_enter (CodeGenerator &g) const override
 Generate code for the function body. More...
 
void codegen_body_exit (CodeGenerator &g) const override
 Generate code for the function body. More...
 
void codegen_setup_constants (CodeGenerator &g, const std::string &d_nlp, const std::string &p_nlp, const std::string &d_oracle) const
 
void codegen_setup_per_call (CodeGenerator &g, const std::string &d_nlp) const
 
void codegen_post_solve (CodeGenerator &g, const std::string &d_nlp) const
 
bool uses_output () const override
 Do the derivative functions need nondifferentiated outputs? More...
 
Dict get_stats (void *mem) const override
 Get all statistics. More...
 
int callback (NlpsolMemory *m) const
 
Function kkt () const
 
bool is_a (const std::string &type, bool recursive) const override
 Check if the function is of a particular type. More...
 
virtual DM getReducedHessian ()
 
virtual void setOptionsFromFile (const std::string &file)
 Read options from parameter xml. More...
 
void finalize () override
 Finalize initialization. More...
 
void join_results (OracleMemory *m) const
 Combine results from different threads. More...
 
const Functionoracle () const override
 Get oracle. More...
 
void expand ()
 
Function create_function (const Function &oracle, const std::string &fname, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const Function::AuxOut &aux=Function::AuxOut(), const Dict &opts=Dict())
 
Function create_function (const std::string &fname, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const Function::AuxOut &aux=Function::AuxOut(), const Dict &opts=Dict())
 
Function create_function (const std::string &fname, const std::vector< MX > &e_in, const std::vector< MX > &e_out, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const Dict &opts=Dict())
 
Function create_forward (const std::string &fname, casadi_int nfwd)
 
void set_function (const Function &fcn, const std::string &fname, bool jit=false)
 
void set_function (const Function &fcn)
 
int calc_function (OracleMemory *m, const std::string &fcn, const double *const *arg=nullptr, int thread_id=0) const
 
int calc_sp_forward (const std::string &fcn, const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w) const
 
int calc_sp_reverse (const std::string &fcn, bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w) const
 
std::vector< std::string > get_function () const override
 Get list of dependency functions. More...
 
const Functionget_function (const std::string &name) const override
 
void find (std::map< FunctionInternal *, std::pair< Function, size_t > > &all_fun, casadi_int max_depth) const override
 
virtual bool monitored (const std::string &name) const
 
bool has_function (const std::string &fname) const override
 
std::string generate_dependencies (const std::string &fname, const Dict &opts) const override
 Export / Generate C code for the generated functions. More...
 
void jit_dependencies (const std::string &fname) override
 JIT for dependencies. More...
 
int local_init_mem (void *mem) const
 Initalize memory block. More...
 
void set_temp (void *mem, const double **arg, double **res, casadi_int *iw, double *w) const override
 Set the work vectors. More...
 
virtual std::string getAdaptorSolverName () const
 Obtain solver name from Adaptor. More...
 
Dict generate_options (const std::string &target) const override
 Reconstruct options dict. More...
 
void change_option (const std::string &option_name, const GenericType &option_value) override
 Change option after object creation for debugging. More...
 
void reset_dump_count ()
 Reset the counter used to name dump files. More...
 
Function self () const
 Get a public class instance. More...
 
virtual Function 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
 
void add_embedded (std::map< FunctionInternal *, std::pair< Function, size_t > > &all_fun, const Function &dep, casadi_int max_depth) const
 
virtual std::vector< bool > which_depends (const std::string &s_in, const std::vector< std::string > &s_out, casadi_int order, bool tr=false) const
 Which variables enter with some order. More...
 
virtual Function simplify_passes (const std::vector< std::pair< std::string, casadi_int > > &tasks) const
 Apply an ordered list of simplify passes (used by transform) More...
 
virtual int eval_sx (const SXElem **arg, SXElem **res, casadi_int *iw, SXElem *w, void *mem, bool always_inline, bool never_inline) const
 Evaluate with symbolic scalars. More...
 
virtual void eval_mx (const MXVector &arg, MXVector &res, bool always_inline, bool never_inline) const
 Evaluate with symbolic matrices. More...
 
template<typename M >
void call (const std::vector< M > &arg, std::vector< M > &res, bool always_inline, bool never_inline) const
 Call a function, templated. More...
 
template<typename M >
bool matching_arg (const std::vector< M > &arg, casadi_int &npar) const
 Check if input arguments that needs to be replaced. More...
 
template<typename M >
bool matching_res (const std::vector< M > &arg, casadi_int &npar) const
 Check if output arguments that needs to be replaced. More...
 
template<typename M >
std::vector< M > replace_arg (const std::vector< M > &arg, casadi_int npar) const
 Replace 0-by-0 inputs. More...
 
template<typename M >
std::vector< M > project_arg (const std::vector< M > &arg, casadi_int npar) const
 Project sparsities. More...
 
template<typename M >
std::vector< M > project_res (const std::vector< M > &arg, casadi_int npar) const
 Project sparsities. More...
 
template<typename M >
std::vector< M > replace_res (const std::vector< M > &res, casadi_int npar) const
 Replace 0-by-0 outputs. More...
 
template<typename M >
std::vector< std::vector< M > > replace_fseed (const std::vector< std::vector< M >> &fseed, casadi_int npar) const
 Replace 0-by-0 forward seeds. More...
 
template<typename M >
std::vector< std::vector< M > > replace_fseed (const std::vector< std::vector< M > > &fseed, casadi_int npar) const
 
template<typename M >
std::vector< std::vector< M > > replace_aseed (const std::vector< std::vector< M >> &aseed, casadi_int npar) const
 Replace 0-by-0 reverse seeds. More...
 
template<typename M >
std::vector< std::vector< M > > replace_aseed (const std::vector< std::vector< M > > &aseed, casadi_int npar) const
 
std::vector< MXmapsum_mx (const std::vector< MX > &arg, const std::string &parallelization)
 Parallel evaluation. More...
 
std::string diff_prefix (const std::string &prefix) const
 Determine prefix for differentiated functions. More...
 
virtual Function slice (const std::string &name, const std::vector< casadi_int > &order_in, const std::vector< casadi_int > &order_out, const Dict &opts) const
 returns a new function with a selection of inputs/outputs of the original More...
 
bool has_derivative () const
 Can derivatives be calculated in any way? More...
 
virtual double ad_weight () const
 Weighting factor for chosing forward/reverse mode. More...
 
virtual double sp_weight () const
 Weighting factor for chosing forward/reverse mode,. More...
 
virtual std::vector< MXfree_mx () const
 Get free variables (MX) More...
 
virtual std::vector< SXfree_sx () const
 Get free variables (SX) More...
 
virtual bool has_free () const
 Does the function have free variables. More...
 
virtual void generate_lifted (Function &vdef_fcn, Function &vinit_fcn) const
 Extract the functions needed for the Lifted Newton method. More...
 
virtual casadi_int n_instructions () const
 Get the number of atomic operations. More...
 
virtual casadi_int instruction_id (casadi_int k) const
 Get an atomic operation operator index. More...
 
virtual std::vector< casadi_int > instruction_input (casadi_int k) const
 Get the (integer) input arguments of an atomic operation. More...
 
virtual double instruction_constant (casadi_int k) const
 Get the floating point output argument of an atomic operation. More...
 
virtual std::vector< casadi_int > instruction_output (casadi_int k) const
 Get the (integer) output argument of an atomic operation. More...
 
virtual casadi_int n_nodes () const
 Number of nodes in the algorithm. More...
 
virtual MX instruction_MX (casadi_int k) const
 get MX expression associated with instruction More...
 
virtual SX instructions_sx () const
 get SX expression associated with instructions More...
 
Dict cache () const
 Get all functions in the cache. More...
 
bool incache (const std::string &fname, Function &f, const std::string &suffix="") const
 Get function in cache. More...
 
void tocache (const Function &f, const std::string &suffix="") const
 Save function to cache. More...
 
void tocache_if_missing (Function &f, const std::string &suffix="") const
 Save function to cache, only if missing. More...
 
void codegen (CodeGenerator &g, const std::string &fname) const
 Generate code the function. More...
 
void codegen_meta (CodeGenerator &g) const
 Generate meta-information allowing a user to evaluate a generated function. More...
 
void codegen_sparsities (CodeGenerator &g) const
 Codegen sparsities. More...
 
virtual std::string codegen_name (const CodeGenerator &g, bool ns=true) const
 Get name in codegen. More...
 
std::string codegen_mem (CodeGenerator &g, const std::string &index="mem") const
 Get thread-local memory object. More...
 
virtual void codegen_incref (CodeGenerator &g) const
 Codegen incref for dependencies. More...
 
virtual void codegen_decref (CodeGenerator &g) const
 Codegen decref for dependencies. More...
 
virtual void codegen_alloc_mem (CodeGenerator &g) const
 Codegen decref for alloc_mem. More...
 
virtual void codegen_init_mem (CodeGenerator &g) const
 Codegen decref for init_mem. More...
 
virtual void codegen_free_mem (CodeGenerator &g) const
 Codegen for free_mem. More...
 
virtual void codegen_checkout (CodeGenerator &g) const
 Codegen for checkout. More...
 
virtual void codegen_release (CodeGenerator &g) const
 Codegen for release. More...
 
std::string signature (const std::string &fname) const
 Code generate the function. More...
 
std::string signature_unrolled (const std::string &fname) const
 Code generate the function. More...
 
virtual void codegen_body (CodeGenerator &g) const
 Generate code for the function body. More...
 
virtual std::string codegen_mem_type () const
 Thread-local memory object type. More...
 
virtual bool codegen_needs_mem () const
 Is thread-local memory object needed? More...
 
virtual bool codegen_mem_is_opaque () const
 Is thread-local memory object managed by checkout/release. More...
 
virtual bool has_codegen () const
 Is codegen supported? More...
 
virtual void export_code (const std::string &lang, std::ostream &stream, const Dict &options) const
 Export function in a specific language. More...
 
void disp (std::ostream &stream, bool more) const override
 Display object. More...
 
std::string definition () const
 Get function signature: name:(inputs)->(outputs) More...
 
void print_dimensions (std::ostream &stream) const
 Print dimensions of inputs and outputs. More...
 
virtual std::vector< std::string > get_free () const
 Print free variables. More...
 
void get_partition (casadi_int iind, casadi_int oind, Sparsity &D1, Sparsity &D2, bool compact, bool symmetric, bool allow_forward, bool allow_reverse) const
 Get the unidirectional or bidirectional partition. More...
 
virtual double get_max_in (casadi_int ind) const
 Get largest input value. More...
 
virtual double get_min_in (casadi_int ind) const
 Get smallest input value. More...
 
virtual std::vector< double > get_nominal_in (casadi_int ind) const
 
virtual std::vector< double > get_nominal_out (casadi_int ind) const
 
virtual double get_reltol () const
 Get relative tolerance. More...
 
virtual double get_abstol () const
 Get absolute tolerance. More...
 
virtual bool get_diff_in (casadi_int i)
 Which inputs are differentiable. More...
 
virtual bool get_diff_out (casadi_int i)
 Which outputs are differentiable. More...
 
casadi_int index_in (const std::string &name) const
 Get input scheme index by name. More...
 
casadi_int index_out (const std::string &name) const
 Get output scheme index by name. More...
 
virtual int sp_forward (const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, void *mem) const
 Propagate sparsity forward. More...
 
virtual int eval_activity (const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, void *mem) const
 Propagate signal activity forward. More...
 
virtual int sp_forward_block (const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, void *mem, casadi_int oind, casadi_int iind) const
 Propagate sparsity forward, specific block. More...
 
virtual int sp_reverse (bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, void *mem) const
 Propagate sparsity backwards. More...
 
void sz_work (size_t &sz_arg, size_t &sz_res, size_t &sz_iw, size_t &sz_w) const
 Get number of temporary variables needed. More...
 
size_t sz_arg () const
 Get required length of arg field. More...
 
size_t sz_res () const
 Get required length of res field. More...
 
size_t sz_iw () const
 Get required length of iw field. More...
 
size_t sz_w () const
 Get required length of w field. More...
 
void alloc_arg (size_t sz_arg, bool persistent=false)
 Ensure required length of arg field. More...
 
void alloc_res (size_t sz_res, bool persistent=false)
 Ensure required length of res field. More...
 
void alloc_iw (size_t sz_iw, bool persistent=false)
 Ensure required length of iw field. More...
 
void alloc_w (size_t sz_w, bool persistent=false)
 Ensure required length of w field. More...
 
void alloc (const Function &f, bool persistent=false, int num_threads=1)
 Ensure work vectors long enough to evaluate function. More...
 
void setup (void *mem, const double **arg, double **res, casadi_int *iw, double *w) const
 Set the (persistent and temporary) work vectors. More...
 
virtual Dict info () const
 
Function map (casadi_int n, const std::string &parallelization) const
 Generate/retrieve cached serial map. More...
 
void generate_in (const std::string &fname, const double **arg) const
 Export an input file that can be passed to generate C code with a main. More...
 
void generate_out (const std::string &fname, double **res) const
 
virtual void merge (const std::vector< MX > &arg, std::vector< MX > &subs_from, std::vector< MX > &subs_to) const
 List merge opportunitities. More...
 
template<typename MatType >
std::vector< std::vector< MatType > > fwd_seed (casadi_int nfwd) const
 Symbolic expressions for the forward seeds. More...
 
template<typename MatType >
std::vector< std::vector< MatType > > symbolicAdjSeed (casadi_int nadj, const std::vector< MatType > &v) const
 Symbolic expressions for the adjoint seeds. More...
 
void print_in (std::ostream &stream, const double **arg, bool truncate) const
 Print inputs. More...
 
void print_out (std::ostream &stream, double **res, bool truncate) const
 Print outputs. More...
 
void construct (const Dict &opts)
 Construct. More...
 
void print_options (std::ostream &stream) const
 Print list of options. More...
 
void print_option (const std::string &name, std::ostream &stream) const
 Print all information there is to know about a certain option. More...
 
bool has_option (const std::string &option_name) const
 Does a particular option exist. More...
 
int checkout () const
 Checkout a memory object. More...
 
void release (int mem) const
 Release a memory object. More...
 
void * memory (int ind) const
 Memory objects. More...
 
bool has_memory (int ind) const
 Check for existance of memory object. More...
 
virtual void check_mem_count (casadi_int n) const
 Check for validatity of memory object count. More...
 
void clear_mem ()
 Clear all memory (called from destructor) More...
 
void print (const char *fmt,...) const
 C-style formatted printing during evaluation. More...
 
void sprint (char *buf, size_t buf_sz, const char *fmt,...) const
 C-style formatted printing to string. More...
 
void format_time (char *buffer, double time) const
 Format time in a fixed width 8 format. More...
 
void print_time (const std::map< std::string, FStats > &fstats) const
 Print timing statistics. More...
 
void serialize (SerializingStream &s) const
 Serialize an object. More...
 
casadi_int getCount () const
 Get the reference count. More...
 
std::string debug_repr (const SharedObjectInternal *) const
 
GenericWeakRef< SharedObject, SharedObjectInternal > * weak ()
 Get a weak reference to the object. More...
 
virtual void deps_version_check (const std::string &stage) const
 
size_t get_n_in () override
 Number of function inputs and outputs. More...
 
size_t get_n_out () override
 Number of function inputs and outputs. More...
 
Sparsity get_sparsity_in (casadi_int i) override
 Sparsities of function inputs and outputs. More...
 
Sparsity get_sparsity_out (casadi_int i) override
 Sparsities of function inputs and outputs. More...
 
std::string get_name_in (casadi_int i) override
 Names of function input and outputs. More...
 
std::string get_name_out (casadi_int i) override
 Names of function input and outputs. More...
 
bool has_forward (casadi_int nfwd) const override
 Generate a function that calculates forward mode derivatives. More...
 
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 override
 Generate a function that calculates forward mode derivatives. More...
 
bool has_reverse (casadi_int nadj) const override
 Generate a function that calculates reverse mode derivatives. More...
 
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 override
 Generate a function that calculates reverse mode derivatives. More...
 
virtual bool has_spfwd () const
 Is the class able to propagate seeds through the algorithm? More...
 
virtual bool has_sprev () const
 Is the class able to propagate seeds through the algorithm? More...
 
int eval_gen (const double **arg, double **res, casadi_int *iw, double *w, void *mem, bool always_inline, bool never_inline) const
 Evaluate numerically. More...
 
int eval_gen (const SXElem **arg, SXElem **res, casadi_int *iw, SXElem *w, void *mem, bool always_inline, bool never_inline) const
 Evaluate a function, overloaded. More...
 
int eval_gen (const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, void *mem, bool always_inline, bool never_inline) const
 Evaluate a function, overloaded. More...
 
virtual std::vector< DMeval_dm (const std::vector< DM > &arg) const
 Evaluate with DM matrices. More...
 
virtual bool has_eval_dm () const
 Evaluate with DM matrices. More...
 
void call_gen (const MXVector &arg, MXVector &res, casadi_int npar, bool always_inline, bool never_inline) const
 Call a function, overloaded. More...
 
template<typename D >
void call_gen (const std::vector< Matrix< D > > &arg, std::vector< Matrix< D > > &res, casadi_int npar, bool always_inline, bool never_inline) const
 Call a function, overloaded. More...
 
template<typename M >
void check_arg (const std::vector< M > &arg, casadi_int &npar) const
 Check if input arguments have correct length and dimensions. More...
 
template<typename M >
void check_res (const std::vector< M > &res, casadi_int &npar) const
 Check if output arguments have correct length and dimensions. More...
 
template<typename M >
std::map< std::string, M > convert_arg (const std::vector< M > &arg) const
 Convert from/to input/output lists/map. More...
 
template<typename M >
std::vector< M > convert_arg (const std::map< std::string, M > &arg) const
 Convert from/to input/output lists/map. More...
 
template<typename M >
std::map< std::string, M > convert_res (const std::vector< M > &res) const
 Convert from/to input/output lists/map. More...
 
template<typename M >
std::vector< M > convert_res (const std::map< std::string, M > &res) const
 Convert from/to input/output lists/map. More...
 
std::vector< double > nz_in (const std::vector< DM > &arg) const
 Convert from/to flat vector of input/output nonzeros. More...
 
std::vector< DMnz_in (const std::vector< double > &arg) const
 Convert from/to flat vector of input/output nonzeros. More...
 
std::vector< double > nz_out (const std::vector< DM > &res) const
 Convert from/to flat vector of input/output nonzeros. More...
 
std::vector< DMnz_out (const std::vector< double > &res) const
 Convert from/to flat vector of input/output nonzeros. More...
 
virtual void call_forward (const std::vector< MX > &arg, const std::vector< MX > &res, const std::vector< std::vector< MX > > &fseed, std::vector< std::vector< MX > > &fsens, bool always_inline, bool never_inline) const
 Forward mode AD, virtual functions overloaded in derived classes. More...
 
virtual void call_forward (const std::vector< SX > &arg, const std::vector< SX > &res, const std::vector< std::vector< SX > > &fseed, std::vector< std::vector< SX > > &fsens, bool always_inline, bool never_inline) const
 Forward mode AD, virtual functions overloaded in derived classes. More...
 
virtual void call_reverse (const std::vector< MX > &arg, const std::vector< MX > &res, const std::vector< std::vector< MX > > &aseed, std::vector< std::vector< MX > > &asens, bool always_inline, bool never_inline) const
 Reverse mode, virtual functions overloaded in derived classes. More...
 
virtual void call_reverse (const std::vector< SX > &arg, const std::vector< SX > &res, const std::vector< std::vector< SX > > &aseed, std::vector< std::vector< SX > > &asens, bool always_inline, bool never_inline) const
 Reverse mode, virtual functions overloaded in derived classes. More...
 
Function jacobian () const
 Return Jacobian of all input elements with respect to all output elements. 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...
 
Sparsityjac_sparsity (casadi_int oind, casadi_int iind, bool compact, bool symmetric) const
 Get Jacobian sparsity. More...
 
virtual bool has_jac_sparsity (casadi_int oind, casadi_int iind) const
 Get Jacobian sparsity. More...
 
virtual Sparsity get_jac_sparsity (casadi_int oind, casadi_int iind, bool symmetric) const
 Get Jacobian sparsity. More...
 
Function forward (casadi_int nfwd) const
 Return function that calculates forward derivatives. More...
 
Function reverse (casadi_int nadj) const
 Return function that calculates adjoint derivatives. More...
 
virtual const SX sx_in (casadi_int ind) const
 Get function input(s) and output(s) More...
 
virtual const std::vector< SXsx_in () const
 Get function input(s) and output(s) More...
 
virtual const SX sx_out (casadi_int ind) const
 Get function input(s) and output(s) More...
 
virtual const std::vector< SXsx_out () const
 Get function input(s) and output(s) More...
 
virtual const MX mx_in (casadi_int ind) const
 Get function input(s) and output(s) More...
 
virtual const std::vector< MXmx_in () const
 Get function input(s) and output(s) More...
 
virtual const MX mx_out (casadi_int ind) const
 Get function input(s) and output(s) More...
 
virtual const std::vector< MXmx_out () const
 Get function input(s) and output(s) More...
 
const DM dm_in (casadi_int ind) const
 Get function input(s) and output(s) More...
 
const std::vector< DMdm_in () const
 Get function input(s) and output(s) More...
 
const DM dm_out (casadi_int ind) const
 Get function input(s) and output(s) More...
 
const std::vector< DMdm_out () const
 Get function input(s) and output(s) More...
 
Function wrap (const std::string &name) const
 Wrap in an Function instance consisting of only one MX call. More...
 
Function wrap () const
 Wrap in an Function instance consisting of only one MX call. More...
 
Function wrap_as_needed (const std::string &name, const Dict &opts) const
 Wrap in an Function instance consisting of only one MX call. More...
 
Function wrap_as_needed (const Dict &opts) const
 Wrap in an Function instance consisting of only one MX call. More...
 
casadi_int nnz_in () const
 Number of input/output nonzeros. More...
 
casadi_int nnz_in (casadi_int ind) const
 Number of input/output nonzeros. More...
 
casadi_int nnz_out () const
 Number of input/output nonzeros. More...
 
casadi_int nnz_out (casadi_int ind) const
 Number of input/output nonzeros. More...
 
casadi_int numel_in () const
 Number of input/output elements. More...
 
casadi_int numel_in (casadi_int ind) const
 Number of input/output elements. More...
 
casadi_int numel_out (casadi_int ind) const
 Number of input/output elements. More...
 
casadi_int numel_out () const
 Number of input/output elements. More...
 
casadi_int size1_in (casadi_int ind) const
 Input/output dimensions. More...
 
casadi_int size2_in (casadi_int ind) const
 Input/output dimensions. More...
 
casadi_int size1_out (casadi_int ind) const
 Input/output dimensions. More...
 
casadi_int size2_out (casadi_int ind) const
 Input/output dimensions. More...
 
std::pair< casadi_int, casadi_int > size_in (casadi_int ind) const
 Input/output dimensions. More...
 
std::pair< casadi_int, casadi_int > size_out (casadi_int ind) const
 Input/output dimensions. More...
 
const Sparsitysparsity_in (casadi_int ind) const
 Input/output sparsity. More...
 
const Sparsitysparsity_out (casadi_int ind) const
 Input/output sparsity. More...
 
bool all_scalar () const
 Are all inputs and outputs scalar. More...
 
virtual bool jac_is_symm (casadi_int oind, casadi_int iind) const
 Is a Jacobian block known to be symmetric a priori? More...
 
Sparsity to_compact (casadi_int oind, casadi_int iind, const Sparsity &sp) const
 Convert to compact Jacobian sparsity pattern. More...
 
Sparsity from_compact (casadi_int oind, casadi_int iind, const Sparsity &sp) const
 Convert from compact Jacobian sparsity pattern. More...
 
template<bool fwd>
Sparsity get_jac_sparsity_gen (casadi_int oind, casadi_int iind) const
 Get the sparsity pattern via sparsity seed propagation. More...
 
Sparsity get_jac_sparsity_hierarchical (casadi_int oind, casadi_int iind) const
 A flavor of get_jac_sparsity_gen that does hierarchical block structure recognition. More...
 
Sparsity get_jac_sparsity_hierarchical_symm (casadi_int oind, casadi_int iind) const
 
virtual std::vector< MXsymbolic_output (const std::vector< MX > &arg) const
 Get a vector of symbolic variables corresponding to the outputs. More...
 
virtual size_t codegen_sz_arg (const CodeGenerator &g) const
 Get required lengths, for codegen. More...
 
virtual size_t codegen_sz_res (const CodeGenerator &g) const
 Get required lengths, for codegen. More...
 
virtual size_t codegen_sz_iw (const CodeGenerator &g) const
 Get required lengths, for codegen. More...
 
virtual size_t codegen_sz_w (const CodeGenerator &g) const
 Get required lengths, for codegen. More...
 
virtual bool fwdViaJac (casadi_int nfwd) const
 Calculate derivatives by multiplying the full Jacobian and multiplying. More...
 
virtual bool adjViaJac (casadi_int nadj) const
 Calculate derivatives by multiplying the full Jacobian and multiplying. More...
 

Static Public Member Functions

static Nlpsolcreator (const std::string &name, const Function &nlp)
 Create a new NLP Solver. More...
 
static ProtoFunctiondeserialize (DeserializingStream &s)
 Deserialize into MX. More...
 
static void bound_consistency (casadi_int n, double *z, double *lam, const double *lbz, const double *ubz)
 
static std::string shortname ()
 Short name. More...
 
template<typename Type >
static void append_to_vec (GenericType &t, Type el)
 WORKAROUND: Add an element to an std::vector stored in a GenericType: More...
 
template<typename XType >
static Function create_oracle (const std::map< std::string, XType > &d, const Dict &opts)
 Convert dictionary to Problem. More...
 
static std::string forward_name (const std::string &fcn, casadi_int nfwd)
 Helper function: Get name of forward derivative function. More...
 
static std::string reverse_name (const std::string &fcn, casadi_int nadj)
 Helper function: Get name of adjoint derivative function. More...
 
template<typename MatType >
static MatType ensure_stacked (const MatType &v, const Sparsity &sp, casadi_int n)
 Ensure that a matrix's sparsity is a horizontal multiple of another, or empty. More...
 
static std::string get_jit_directory (const Dict &jit_options)
 Get JIT directory from options. More...
 
template<typename MatType >
static bool purgable (const std::vector< MatType > &seed)
 Can a derivative direction be skipped. More...
 
static std::string string_from_UnifiedReturnStatus (UnifiedReturnStatus status)
 
static void print_canonical (std::ostream &stream, const Sparsity &sp, const double *nz)
 Print canonical representation of a numeric matrix. More...
 
static void print_canonical (std::ostream &stream, casadi_int sz, const double *nz)
 Print canonical representation of a numeric vector. More...
 
static void print_canonical (std::ostream &stream, double a)
 Print canonical representation of a number. More...
 
static bool has_plugin (const std::string &pname, bool verbose=false)
 Check if a plugin is available or can be loaded. More...
 
static const Optionsplugin_options (const std::string &pname)
 Get the plugin options. More...
 
static Deserialize plugin_deserialize (const std::string &pname)
 Get the plugin deserialize_map. More...
 
static Plugin pluginFromRegFcn (RegFcn regfcn)
 Instantiate a Plugin struct from a factory function. More...
 
static Plugin load_plugin (const std::string &pname, bool register_plugin=true, bool needs_lock=true)
 Load a plugin dynamically. More...
 
static handle_t load_library (const std::string &libname, std::string &resultpath, bool global)
 Load a library dynamically. More...
 
static void registerPlugin (const Plugin &plugin, bool needs_lock=true)
 Register an integrator in the factory. More...
 
static void registerPlugin (RegFcn regfcn, bool needs_lock=true)
 Register an integrator in the factory. More...
 
static Plugin & getPlugin (const std::string &pname)
 Load and get the creator function. More...
 
static Nlpsolinstantiate (const std::string &fname, const std::string &pname, Problem problem)
 
static bool check_mat (const Sparsity &arg, const Sparsity &inp, casadi_int &npar)
 

Public Attributes

casadi_int nblocks_
 
std::vector< casadi_int > blocks_
 
std::vector< casadi_int > dim_
 
casadi_int nnz_H_
 
Sparsity Asp_
 
Sparsity Hsp_
 
Sparsity exact_hess_lag_sp_
 
std::string linsol_plugin_
 QP solver for the subproblems. More...
 
bool print_header_
 
bool print_iteration_
 
double eps_
 
double opttol_
 
double nlinfeastol_
 
bool schur_
 
bool globalization_
 
bool restore_feas_
 
casadi_int max_line_search_
 
casadi_int max_consec_reduced_steps_
 
casadi_int max_consec_skipped_updates_
 
casadi_int max_it_qp_
 
casadi_int max_iter_
 
bool warmstart_
 
bool qp_init_
 
bool block_hess_
 
casadi_int hess_scaling_
 
casadi_int fallback_scaling_
 
double max_time_qp_
 
double ini_hess_diag_
 
double col_eps_
 
double col_tau1_
 
double col_tau2_
 
casadi_int hess_damp_
 
double hess_damp_fac_
 
casadi_int hess_update_
 
casadi_int fallback_update_
 
casadi_int hess_lim_mem_
 
casadi_int hess_memsize_
 
casadi_int which_second_derv_
 
bool skip_first_globalization_
 
casadi_int conv_strategy_
 
casadi_int max_conv_qp_
 
casadi_int max_soc_iter_
 
double gamma_theta_
 
double gamma_f_
 
double kappa_soc_
 
double kappa_f_
 
double theta_max_
 
double theta_min_
 
double delta_
 
double s_theta_
 
double s_f_
 
double kappa_minus_
 
double kappa_plus_
 
double kappa_plus_max_
 
double delta_h0_
 
double eta_
 
double obj_lo_
 
double obj_up_
 
double rho_
 
double zeta_
 
Function rp_solver_
 
bool print_maxit_reached_
 
casadi_nlpsol_prob< double > p_nlp_
 
casadi_int nx_
 Number of variables. More...
 
casadi_int ng_
 Number of constraints. More...
 
casadi_int np_
 Number of parameters. More...
 
Function fcallback_
 callback function, executed at each iteration More...
 
casadi_int callback_step_
 Execute the callback function only after this amount of iterations. More...
 
std::string sens_linsol_
 Linear solver and options. More...
 
Dict sens_linsol_options_
 
std::vector< char > detect_simple_bounds_is_simple_
 
Function detect_simple_bounds_parts_
 
std::vector< casadi_int > detect_simple_bounds_target_x_
 
std::vector< casadi_int > detect_simple_bounds_target_g_
 
bool mi_
 
WeakRef kkt_
 Cache for KKT function. More...
 
bool always_inline_
 
bool never_inline_
 
size_t n_in_
 Number of inputs and outputs. More...
 
size_t n_out_
 
std::vector< bool > is_diff_in_
 Are inputs and outputs differentiable? More...
 
std::vector< bool > is_diff_out_
 
std::vector< Sparsitysparsity_in_
 Input and output sparsity. More...
 
std::vector< Sparsitysparsity_out_
 
std::vector< std::string > name_in_
 Input and output scheme. More...
 
std::vector< std::string > name_out_
 
bool jit_
 Use just-in-time compiler. More...
 
bool jit_cleanup_
 Cleanup jit source file. More...
 
std::string jit_serialize_
 Serialize behaviour. More...
 
std::string jit_name_
 Name if jit source file. More...
 
std::string jit_directory_
 
std::string jit_base_name_
 
bool jit_temp_suffix_
 Use a temporary name. More...
 
eval_t eval_
 Numerical evaluation redirected to a C function. More...
 
casadi_checkout_t checkout_
 Checkout redirected to a C function. More...
 
casadi_release_t release_
 Release redirected to a C function. More...
 
signal_t incref_
 Incref/decref redirected to C functions. More...
 
signal_t decref_
 
Dict stats_
 Dict of statistics (resulting from evaluate) More...
 
bool has_refcount_
 Reference counting in codegen? More...
 
bool has_refcount_in_deps_
 Reference counting in dependent functions. More...
 
Dict cache_init_
 Values to prepopulate the function cache with. More...
 
WeakCache< std::string, Functioncache_
 Function cache. More...
 
std::vector< Sparsityjac_sparsity_ [2]
 Cache for sparsities of the Jacobian blocks. More...
 
Function derivative_of_
 If the function is the derivative of another function. More...
 
void * user_data_
 User-set field. More...
 
std::string compiler_plugin_
 Just-in-time compiler. More...
 
Importer compiler_
 
Dict jit_options_
 
double jac_penalty_
 Penalty factor for using a complete Jacobian to calculate directional derivatives. More...
 
bool enable_forward_
 
bool enable_reverse_
 
bool enable_jacobian_
 
bool enable_fd_
 
bool enable_forward_op_
 
bool enable_reverse_op_
 
bool enable_jacobian_op_
 
bool enable_fd_op_
 
double ad_weight_
 Weighting factor for derivative calculation and sparsity pattern calculation. More...
 
double ad_weight_sp_
 
casadi_int max_num_dir_
 Maximum number of sensitivity directions. More...
 
bool inputs_check_
 Errors are thrown if numerical values of inputs look bad. More...
 
Dict fd_options_
 
double fd_step_
 
std::string fd_method_
 
bool print_in_
 
bool print_out_
 
bool print_canonical_
 
casadi_int max_io_
 
bool dump_in_
 
bool dump_out_
 
bool dump_
 
std::string dump_dir_
 
std::string dump_format_
 
Dict forward_options_
 
Dict reverse_options_
 
Dict jacobian_options_
 
Dict der_options_
 
Function custom_jacobian_
 
std::vector< Functionregistered_functions_
 
casadi_int dump_count_
 
std::string name_
 Name. More...
 
bool verbose_
 Verbose printout. More...
 
bool print_time_
 
bool record_time_
 
bool regularity_check_
 Errors are thrown when NaN is produced. More...
 
bool error_on_fail_
 Throw an exception on failure? More...
 
bool eval_errors_fatal_
 Options. More...
 
bool warn_initial_bounds_
 Options. More...
 
bool iteration_callback_ignore_errors_
 Options. More...
 
bool calc_multipliers_
 Options. More...
 
bool calc_lam_x_
 Options. More...
 
bool calc_lam_p_
 Options. More...
 
bool calc_f_
 Options. More...
 
bool calc_g_
 Options. More...
 
bool bound_consistency_
 Options. More...
 
double min_lam_
 Options. More...
 
bool no_nlp_grad_
 Options. More...
 
std::vector< bool > discrete_
 Options. More...
 
std::vector< bool > equality_
 Options. More...
 

Static Public Attributes

static const std::string meta_doc
 A documentation string. More...
 
static std::map< std::string, Plugin > solvers_
 Collection of solvers. More...
 
static const std::string infix_ = "nlpsol"
 Infix. More...
 
static std::map< std::string, ProtoFunction *(*)(DeserializingStream &)> deserialize_map
 

Protected Member Functions

 Blocksqp (DeserializingStream &s)
 Deserializing constructor. More...
 
void set_jac_sparsity (casadi_int oind, casadi_int iind, const Sparsity &sp)
 Populate jac_sparsity_ and jac_sparsity_compact_ during initialization. More...
 
void initSingleton ()
 
void destroySingleton ()
 
shared_from_this ()
 Get a shared object from the current internal object. More...
 
const B shared_from_this () const
 Get a shared object from the current internal object. More...
 

Protected Attributes

Function oracle_
 Oracle: Used to generate other functions. More...
 
Dict common_options_
 Options for creating functions. More...
 
Dict specific_options_
 
bool show_eval_warnings_
 Show evaluation warnings. More...
 
int max_num_threads_
 
std::map< std::string, RegFunall_functions_
 
std::vector< std::string > monitor_
 
size_t stride_arg_
 
size_t stride_res_
 
size_t stride_iw_
 
size_t stride_w_
 
bool post_expand_
 
static const Options options_
 Options. More...
 
const Optionsget_options () const override
 Options. More...
 

Member Typedef Documentation

◆ Creator

typedef Nlpsol*(* casadi::Nlpsol::Creator) (const std::string &name, const Function &oracle)
inherited

Definition at line 296 of file nlpsol_impl.hpp.

◆ RegFcn

typedef int(* casadi::PluginInterface< Nlpsol >::RegFcn) (Plugin *plugin)
inherited

Definition at line 73 of file plugin_interface.hpp.

◆ weak_ref_type

Definition at line 152 of file shared_object.hpp.

Constructor & Destructor Documentation

◆ Blocksqp() [1/2]

casadi::Blocksqp::Blocksqp ( const std::string &  name,
const Function nlp 
)
explicit

Definition at line 49 of file blocksqp.cpp.

50  : Nlpsol(name, nlp) {
51  }
Nlpsol(const std::string &name, const Function &oracle)
Constructor.
Definition: nlpsol.cpp:346

◆ ~Blocksqp()

casadi::Blocksqp::~Blocksqp ( )
override

Definition at line 54 of file blocksqp.cpp.

54  {
55  clear_mem();
56  }
void clear_mem()
Clear all memory (called from destructor)

References casadi::ProtoFunction::clear_mem().

◆ Blocksqp() [2/2]

casadi::Blocksqp::Blocksqp ( DeserializingStream s)
explicitprotected

Definition at line 2848 of file blocksqp.cpp.

2848  : Nlpsol(s) {
2849  s.version("Blocksqp", 1);
2850  s.unpack("Blocksqp::nblocks", nblocks_);
2851  s.unpack("Blocksqp::blocks", blocks_);
2852  s.unpack("Blocksqp::dim", dim_);
2853  s.unpack("Blocksqp::nnz_H", nnz_H_);
2854  s.unpack("Blocksqp::Asp", Asp_);
2855  s.unpack("Blocksqp::Hsp", Hsp_);
2856  s.unpack("Blocksqp::exact_hess_lag_sp_", exact_hess_lag_sp_);
2857  s.unpack("Blocksqp::linsol_plugin", linsol_plugin_);
2858  s.unpack("Blocksqp::print_header", print_header_);
2859  s.unpack("Blocksqp::print_iteration", print_iteration_);
2860  s.unpack("Blocksqp::eps", eps_);
2861  s.unpack("Blocksqp::opttol", opttol_);
2862  s.unpack("Blocksqp::nlinfeastol", nlinfeastol_);
2863  s.unpack("Blocksqp::schur", schur_);
2864  s.unpack("Blocksqp::globalization", globalization_);
2865  s.unpack("Blocksqp::restore_feas", restore_feas_);
2866  s.unpack("Blocksqp::max_line_search", max_line_search_);
2867  s.unpack("Blocksqp::max_consec_reduced_steps", max_consec_reduced_steps_);
2868  s.unpack("Blocksqp::max_consec_skipped_updates", max_consec_skipped_updates_);
2869  s.unpack("Blocksqp::max_it_qp", max_it_qp_);
2870  s.unpack("Blocksqp::max_iter", max_iter_);
2871  s.unpack("Blocksqp::warmstart", warmstart_);
2872  s.unpack("Blocksqp::qp_init", qp_init_);
2873  s.unpack("Blocksqp::block_hess", block_hess_);
2874  s.unpack("Blocksqp::hess_scaling", hess_scaling_);
2875  s.unpack("Blocksqp::fallback_scaling", fallback_scaling_);
2876  s.unpack("Blocksqp::max_time_qp", max_time_qp_);
2877  s.unpack("Blocksqp::ini_hess_diag", ini_hess_diag_);
2878  s.unpack("Blocksqp::col_eps", col_eps_);
2879  s.unpack("Blocksqp::col_tau1", col_tau1_);
2880  s.unpack("Blocksqp::col_tau2", col_tau2_);
2881  s.unpack("Blocksqp::hess_damp", hess_damp_);
2882  s.unpack("Blocksqp::hess_damp_fac", hess_damp_fac_);
2883  s.unpack("Blocksqp::hess_update", hess_update_);
2884  s.unpack("Blocksqp::fallback_update", fallback_update_);
2885  s.unpack("Blocksqp::hess_lim_mem", hess_lim_mem_);
2886  s.unpack("Blocksqp::hess_memsize", hess_memsize_);
2887  s.unpack("Blocksqp::which_second_derv", which_second_derv_);
2888  s.unpack("Blocksqp::skip_first_globalization", skip_first_globalization_);
2889  s.unpack("Blocksqp::conv_strategy", conv_strategy_);
2890  s.unpack("Blocksqp::max_conv_qp", max_conv_qp_);
2891  s.unpack("Blocksqp::max_soc_iter", max_soc_iter_);
2892  s.unpack("Blocksqp::gamma_theta", gamma_theta_);
2893  s.unpack("Blocksqp::gamma_f", gamma_f_);
2894  s.unpack("Blocksqp::kappa_soc", kappa_soc_);
2895  s.unpack("Blocksqp::kappa_f", kappa_f_);
2896  s.unpack("Blocksqp::theta_max", theta_max_);
2897  s.unpack("Blocksqp::theta_min", theta_min_);
2898  s.unpack("Blocksqp::delta", delta_);
2899  s.unpack("Blocksqp::s_theta", s_theta_);
2900  s.unpack("Blocksqp::s_f", s_f_);
2901  s.unpack("Blocksqp::kappa_minus", kappa_minus_);
2902  s.unpack("Blocksqp::kappa_plus", kappa_plus_);
2903  s.unpack("Blocksqp::kappa_plus_max", kappa_plus_max_);
2904  s.unpack("Blocksqp::delta_h0", delta_h0_);
2905  s.unpack("Blocksqp::eta", eta_);
2906  s.unpack("Blocksqp::obj_lo", obj_lo_);
2907  s.unpack("Blocksqp::obj_up", obj_up_);
2908  s.unpack("Blocksqp::rho", rho_);
2909  s.unpack("Blocksqp::zeta", zeta_);
2910  s.unpack("Blocksqp::rp_solver", rp_solver_);
2911  s.unpack("Blocksqp::print_maxit_reached", print_maxit_reached_);
2912 
2913  }
casadi_int nblocks_
Definition: blocksqp.hpp:196
casadi_int hess_scaling_
Definition: blocksqp.hpp:357
casadi_int hess_lim_mem_
Definition: blocksqp.hpp:368
casadi_int conv_strategy_
Definition: blocksqp.hpp:373
double nlinfeastol_
Definition: blocksqp.hpp:343
casadi_int hess_update_
Definition: blocksqp.hpp:366
double kappa_plus_
Definition: blocksqp.hpp:389
double kappa_plus_max_
Definition: blocksqp.hpp:390
double kappa_minus_
Definition: blocksqp.hpp:388
casadi_int fallback_update_
Definition: blocksqp.hpp:367
casadi_int fallback_scaling_
Definition: blocksqp.hpp:358
casadi_int max_soc_iter_
Definition: blocksqp.hpp:378
casadi_int hess_memsize_
Definition: blocksqp.hpp:369
std::string linsol_plugin_
QP solver for the subproblems.
Definition: blocksqp.hpp:336
std::vector< casadi_int > dim_
Definition: blocksqp.hpp:198
double max_time_qp_
Definition: blocksqp.hpp:359
casadi_int max_it_qp_
Definition: blocksqp.hpp:352
casadi_int max_consec_skipped_updates_
Definition: blocksqp.hpp:351
Function rp_solver_
Definition: blocksqp.hpp:399
bool print_maxit_reached_
Definition: blocksqp.hpp:400
double hess_damp_fac_
Definition: blocksqp.hpp:365
double ini_hess_diag_
Definition: blocksqp.hpp:360
casadi_int which_second_derv_
Definition: blocksqp.hpp:370
casadi_int max_consec_reduced_steps_
Definition: blocksqp.hpp:350
std::vector< casadi_int > blocks_
Definition: blocksqp.hpp:197
casadi_int max_line_search_
Definition: blocksqp.hpp:349
bool skip_first_globalization_
Definition: blocksqp.hpp:372
casadi_int hess_damp_
Definition: blocksqp.hpp:364
casadi_int max_iter_
Definition: blocksqp.hpp:353
casadi_int max_conv_qp_
Definition: blocksqp.hpp:374
Sparsity exact_hess_lag_sp_
Definition: blocksqp.hpp:203
casadi_int nnz_H_
Definition: blocksqp.hpp:199
double gamma_theta_
Definition: blocksqp.hpp:379

References Asp_, block_hess_, blocks_, col_eps_, col_tau1_, col_tau2_, conv_strategy_, delta_, delta_h0_, dim_, eps_, eta_, exact_hess_lag_sp_, fallback_scaling_, fallback_update_, gamma_f_, gamma_theta_, globalization_, hess_damp_, hess_damp_fac_, hess_lim_mem_, hess_memsize_, hess_scaling_, hess_update_, Hsp_, ini_hess_diag_, kappa_f_, kappa_minus_, kappa_plus_, kappa_plus_max_, kappa_soc_, linsol_plugin_, max_consec_reduced_steps_, max_consec_skipped_updates_, max_conv_qp_, max_it_qp_, max_iter_, max_line_search_, max_soc_iter_, max_time_qp_, nblocks_, nlinfeastol_, nnz_H_, obj_lo_, obj_up_, opttol_, print_header_, print_iteration_, print_maxit_reached_, qp_init_, restore_feas_, rho_, rp_solver_, s_f_, s_theta_, schur_, skip_first_globalization_, theta_max_, theta_min_, casadi::DeserializingStream::unpack(), casadi::DeserializingStream::version(), warmstart_, which_second_derv_, and zeta_.

Member Function Documentation

◆ acceptStep() [1/2]

void casadi::Blocksqp::acceptStep ( BlocksqpMemory m,
const double *  deltaXi,
const double *  lambdaQP,
double  alpha,
casadi_int  nSOCS 
) const

Definition at line 1107 of file blocksqp.cpp.

1109  {
1110  auto d_nlp = &m->d_nlp;
1111  double lStpNorm;
1112 
1113  // Current alpha
1114  m->alpha = alpha;
1115  m->nSOCS = nSOCS;
1116 
1117  // Set new x by accepting the current trial step
1118  for (casadi_int k=0; k<nx_; k++) {
1119  d_nlp->z[k] = m->trial_xk[k];
1120  m->dxk[k] = alpha * deltaXi[k];
1121  }
1122 
1123  // Store the infinity norm of the multiplier step
1124  m->lambdaStepNorm = 0.0;
1125  for (casadi_int k=0; k<nx_; k++)
1126  if ((lStpNorm = fabs(alpha*lambdaQP[k] - alpha*m->lam_xk[k])) > m->lambdaStepNorm)
1127  m->lambdaStepNorm = lStpNorm;
1128  for (casadi_int k=0; k<ng_; k++)
1129  if ((lStpNorm = fabs(alpha*lambdaQP[nx_+k] - alpha*m->lam_gk[k])) > m->lambdaStepNorm)
1130  m->lambdaStepNorm = lStpNorm;
1131 
1132  // Set new multipliers
1133  for (casadi_int k=0; k<nx_; k++)
1134  m->lam_xk[k] = (1.0 - alpha)*m->lam_xk[k] + alpha*lambdaQP[k];
1135  for (casadi_int k=0; k<ng_; k++)
1136  m->lam_gk[k] = (1.0 - alpha)*m->lam_gk[k] + alpha*lambdaQP[nx_+k];
1137 
1138  // Count consecutive reduced steps
1139  if (m->alpha < 1.0)
1140  m->reducedStepCount++;
1141  else
1142  m->reducedStepCount = 0;
1143  }
casadi_int ng_
Number of constraints.
Definition: nlpsol_impl.hpp:69
casadi_int nx_
Number of variables.
Definition: nlpsol_impl.hpp:66

References casadi::BlocksqpMemory::alpha, casadi::NlpsolMemory::d_nlp, casadi::BlocksqpMemory::dxk, casadi::BlocksqpMemory::lam_gk, casadi::BlocksqpMemory::lam_xk, casadi::BlocksqpMemory::lambdaStepNorm, casadi::Nlpsol::ng_, casadi::BlocksqpMemory::nSOCS, casadi::Nlpsol::nx_, casadi::BlocksqpMemory::reducedStepCount, and casadi::BlocksqpMemory::trial_xk.

Referenced by acceptStep(), filterLineSearch(), fullstep(), kktErrorReduction(), and secondOrderCorrection().

◆ acceptStep() [2/2]

void casadi::Blocksqp::acceptStep ( BlocksqpMemory m,
double  alpha 
) const

Definition at line 1102 of file blocksqp.cpp.

1103  {
1104  acceptStep(m, m->dxk, m->lam_qp, alpha, 0);
1105  }
void acceptStep(BlocksqpMemory *m, const double *deltaXi, const double *lambdaQP, double alpha, casadi_int nSOCS) const
Set new primal dual iterate.
Definition: blocksqp.cpp:1108

References acceptStep(), casadi::BlocksqpMemory::dxk, and casadi::BlocksqpMemory::lam_qp.

◆ ad_weight()

double casadi::FunctionInternal::ad_weight ( ) const
virtualinherited

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

Definition at line 3464 of file function_internal.cpp.

3464  {
3465  // If reverse mode derivatives unavailable, use forward
3466  if (!enable_reverse_) return 0;
3467 
3468  // If forward mode derivatives unavailable, use reverse
3469  if (!enable_forward_ && !enable_fd_) return 1;
3470 
3471  // Use the (potentially user set) option
3472  return ad_weight_;
3473  }
double ad_weight_
Weighting factor for derivative calculation and sparsity pattern calculation.

References casadi::FunctionInternal::ad_weight_, casadi::FunctionInternal::enable_fd_, casadi::FunctionInternal::enable_forward_, and casadi::FunctionInternal::enable_reverse_.

Referenced by casadi::FunctionInternal::adjViaJac(), casadi::FunctionInternal::fwdViaJac(), casadi::FunctionInternal::get_partition(), casadi::FunctionInternal::wrap(), and casadi::FunctionInternal::wrap_as_needed().

◆ add_embedded()

void casadi::FunctionInternal::add_embedded ( std::map< FunctionInternal *, std::pair< Function, size_t > > &  all_fun,
const Function dep,
casadi_int  max_depth 
) const
inherited

Definition at line 3906 of file function_internal.cpp.

3908  {
3909  // Add, if not already in graph and not null
3910  if (!dep.is_null() && all_fun.find(dep.get()) == all_fun.end()) {
3911  // Add to map
3912  all_fun[dep.get()] = std::make_pair(dep, all_fun.size());
3913  // Also add its dependencies
3914  if (max_depth > 0) dep->find(all_fun, max_depth - 1);
3915  }
3916  }

References casadi::FunctionInternal::find(), casadi::Function::get(), and casadi::GenericShared< Shared, Internal >::is_null().

Referenced by casadi::FunctionInternal::find(), casadi::Map::find(), casadi::MapSum::find(), casadi::MXFunction::find(), casadi::OracleFunction::find(), casadi::Switch::find(), casadi::SXFunction::find(), and casadi::BSplineInterpolant::find().

◆ adjViaJac()

bool casadi::FunctionInternal::adjViaJac ( casadi_int  nadj) const
virtualinherited

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

Definition at line 3197 of file function_internal.cpp.

3197  {
3198  if (!enable_reverse_) return true;
3199  if (jac_penalty_==-1) return false;
3200 
3201  // Heuristic 1: Jac calculated via reverse mode likely cheaper
3202  if (jac_penalty_*static_cast<double>(nnz_out())<nadj) return true;
3203 
3204  // Heuristic 2: Jac calculated via forward mode likely cheaper
3205  double w = ad_weight();
3206  if ((enable_forward_ || enable_fd_) &&
3207  jac_penalty_*w*static_cast<double>(nnz_in())<(1-w)*static_cast<double>(nadj))
3208  return true; // NOLINT
3209 
3210  return false;
3211  }
double jac_penalty_
Penalty factor for using a complete Jacobian to calculate directional derivatives.
virtual double ad_weight() const
Weighting factor for chosing forward/reverse mode.
casadi_int nnz_in() const
Number of input/output nonzeros.
casadi_int nnz_out() const
Number of input/output nonzeros.

References casadi::FunctionInternal::ad_weight(), casadi::FunctionInternal::enable_fd_, casadi::FunctionInternal::enable_forward_, casadi::FunctionInternal::enable_reverse_, casadi::FunctionInternal::jac_penalty_, casadi::FunctionInternal::nnz_in(), and casadi::FunctionInternal::nnz_out().

Referenced by casadi::FunctionInternal::call_reverse().

◆ all_scalar()

bool casadi::FunctionInternal::all_scalar ( ) const
inherited

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

Definition at line 3951 of file function_internal.cpp.

3951  {
3952  // Check inputs
3953  for (casadi_int i=0; i<n_in_; ++i) {
3954  if (!sparsity_in_[i].is_scalar()) return false;
3955  }
3956  // Check outputs
3957  for (casadi_int i=0; i<n_out_; ++i) {
3958  if (!sparsity_out_[i].is_scalar()) return false;
3959  }
3960  // All are scalar
3961  return true;
3962  }
std::vector< Sparsity > sparsity_in_
Input and output sparsity.
size_t n_in_
Number of inputs and outputs.
std::vector< Sparsity > sparsity_out_

References casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::FunctionInternal::sparsity_in_, and casadi::FunctionInternal::sparsity_out_.

Referenced by casadi::FunctionInternal::call().

◆ alloc()

void casadi::FunctionInternal::alloc ( const Function f,
bool  persistent = false,
int  num_threads = 1 
)
inherited

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

Definition at line 3145 of file function_internal.cpp.

3145  {
3146  if (f.is_null()) return;
3147  size_t sz_arg, sz_res, sz_iw, sz_w;
3148  f.sz_work(sz_arg, sz_res, sz_iw, sz_w);
3149  alloc_arg(sz_arg*num_threads, persistent);
3150  alloc_res(sz_res*num_threads, persistent);
3151  alloc_iw(sz_iw*num_threads, persistent);
3152  alloc_w(sz_w*num_threads, persistent);
3153  registered_functions_.push_back(f);
3154  }
void alloc_iw(size_t sz_iw, bool persistent=false)
Ensure required length of iw field.
void alloc_res(size_t sz_res, bool persistent=false)
Ensure required length of res field.
void alloc_arg(size_t sz_arg, bool persistent=false)
Ensure required length of arg field.
std::vector< Function > registered_functions_
size_t sz_res() const
Get required length of res field.
size_t sz_w() const
Get required length of w field.
void alloc_w(size_t sz_w, bool persistent=false)
Ensure required length of w field.
size_t sz_arg() const
Get required length of arg field.
size_t sz_iw() const
Get required length of iw field.

References casadi::FunctionInternal::alloc_arg(), casadi::FunctionInternal::alloc_iw(), casadi::FunctionInternal::alloc_res(), casadi::FunctionInternal::alloc_w(), casadi::GenericShared< Shared, Internal >::is_null(), casadi::FunctionInternal::registered_functions_, casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), casadi::FunctionInternal::sz_w(), and casadi::Function::sz_work().

Referenced by casadi::OracleFunction::finalize(), casadi::KinsolInterface::get_jtimes(), casadi::FiniteDiff::init(), casadi::Nlpsol::init(), casadi::Rootfinder::init(), casadi::Switch::init(), casadi::Feasiblesqpmethod::init(), casadi::ImplicitToNlp::init(), casadi::QpToNlp::init(), casadi::Qrsqp::init(), casadi::Scpgen::init(), and casadi::Sqpmethod::init().

◆ alloc_arg()

void casadi::FunctionInternal::alloc_arg ( size_t  sz_arg,
bool  persistent = false 
)
inherited

◆ alloc_iw()

void casadi::FunctionInternal::alloc_iw ( size_t  sz_iw,
bool  persistent = false 
)
inherited

◆ alloc_mem()

void* casadi::Blocksqp::alloc_mem ( ) const
inlineoverridevirtual

Reimplemented from casadi::Nlpsol.

Definition at line 177 of file blocksqp.hpp.

177 { return new BlocksqpMemory();}

◆ alloc_res()

void casadi::FunctionInternal::alloc_res ( size_t  sz_res,
bool  persistent = false 
)
inherited

◆ alloc_w()

void casadi::FunctionInternal::alloc_w ( size_t  sz_w,
bool  persistent = false 
)
inherited

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

Definition at line 3137 of file function_internal.cpp.

3137  {
3138  if (persistent) {
3139  sz_w_per_ += sz_w;
3140  } else {
3141  sz_w_tmp_ = std::max(sz_w_tmp_, sz_w);
3142  }
3143  }

References casadi::FunctionInternal::sz_w().

Referenced by casadi::FunctionInternal::alloc(), casadi::BlazingSplineFunction::init(), casadi::External::init(), casadi::FiniteDiff::init(), casadi::FmuFunction::init(), casadi::Integrator::init(), casadi::FixedStepIntegrator::init(), casadi::Interpolant::init(), casadi::JitFunction::init(), casadi::Map::init(), casadi::OmpMap::init(), casadi::ThreadMap::init(), casadi::MapSum::init(), casadi::MXFunction::init(), casadi::Nlpsol::init(), casadi::Rootfinder::init(), casadi::Switch::init(), casadi::SXFunction::init(), init(), casadi::BonminInterface::init(), casadi::CbcInterface::init(), casadi::MadmpecInterface::init(), casadi::ClarabelInterface::init(), casadi::ClpInterface::init(), casadi::CplexInterface::init(), casadi::DaqpInterface::init(), casadi::FatropConicInterface::init(), casadi::FatropInterface::init(), casadi::GurobiInterface::init(), casadi::HighsInterface::init(), casadi::HpipmInterface::init(), casadi::IpoptInterface::init(), casadi::KnitroInterface::init(), casadi::MadnlpInterface::init(), casadi::MosekInterface::init(), casadi::OoqpInterface::init(), casadi::OsqpInterface::init(), casadi::PiqpInterface::init(), casadi::ProxqpInterface::init(), casadi::QpoasesInterface::init(), casadi::SLEQPInterface::init(), casadi::SlicotDple::init(), casadi::SlicotExpm::init(), casadi::SnoptInterface::init(), casadi::CvodesInterface::init(), casadi::IdasInterface::init(), casadi::KinsolInterface::init(), casadi::SundialsInterface::init(), casadi::SuperscsInterface::init(), casadi::WorhpInterface::init(), casadi::XpressInterface::init(), casadi::BSplineInterpolant::init(), casadi::FastNewton::init(), casadi::Feasiblesqpmethod::init(), casadi::ImplicitToNlp::init(), casadi::Ipqp::init(), casadi::LinearInterpolant::init(), casadi::LinearInterpolantJac::init(), casadi::Newton::init(), casadi::QpToNlp::init(), casadi::Qrqp::init(), casadi::Qrsqp::init(), casadi::Scpgen::init(), and casadi::Sqpmethod::init().

◆ append_to_vec()

template<typename Type >
static void casadi::Nlpsol::append_to_vec ( GenericType t,
Type  el 
)
inlinestaticinherited

Definition at line 331 of file nlpsol_impl.hpp.

331  {
332  std::vector<Type> v = t;
333  v.push_back(el);
334  t = v;
335  }

◆ augmentFilter()

void casadi::Blocksqp::augmentFilter ( BlocksqpMemory m,
double  cNorm,
double  obj 
) const

Augment the filter: F_k+1 = F_k U { (c,f) | c > (1-gammaTheta)cNorm and f > obj-gammaF*c

Definition at line 1741 of file blocksqp.cpp.

1742  {
1743  std::pair<double, double> entry((1-gamma_theta_)*cNorm,
1744  obj-gamma_f_*cNorm);
1745 
1746  // Augment filter by current element
1747  m->filter.insert(entry);
1748 
1749  // Remove dominated elements
1750  auto iter=m->filter.begin();
1751  while (iter != m->filter.end()) {
1752  if (iter->first > entry.first && iter->second > entry.second) {
1753  auto iterToRemove = iter;
1754  iter++;
1755  m->filter.erase(iterToRemove);
1756  } else {
1757  iter++;
1758  }
1759  }
1760  }

References casadi::BlocksqpMemory::filter, gamma_f_, and gamma_theta_.

Referenced by filterLineSearch().

◆ bound_consistency()

void casadi::Nlpsol::bound_consistency ( casadi_int  n,
double *  z,
double *  lam,
const double *  lbz,
const double *  ubz 
)
staticinherited

Definition at line 767 of file nlpsol.cpp.

768  {
769  casadi_assert_dev(z!=nullptr);
770  casadi_assert_dev(lam!=nullptr);
771  casadi_assert_dev(lbz!=nullptr);
772  casadi_assert_dev(ubz!=nullptr);
773  // Local variables
774  casadi_int i;
775  // Loop over variables
776  for (i=0; i<n; ++i) {
777  // Make sure bounds are respected
778  z[i] = std::fmin(std::fmax(z[i], lbz[i]), ubz[i]);
779  // Adjust multipliers
780  if (std::isinf(lbz[i]) && std::isinf(ubz[i])) {
781  // Both multipliers are infinite
782  lam[i] = 0.;
783  } else if (std::isinf(lbz[i]) || z[i] - lbz[i] > ubz[i] - z[i]) {
784  // Infinite lower bound or closer to upper bound than lower bound
785  lam[i] = std::fmax(0., lam[i]);
786  } else if (std::isinf(ubz[i]) || z[i] - lbz[i] < ubz[i] - z[i]) {
787  // Infinite upper bound or closer to lower bound than upper bound
788  lam[i] = std::fmin(0., lam[i]);
789  }
790  }
791  }

Referenced by casadi::Nlpsol::eval().

◆ cache()

Dict casadi::FunctionInternal::cache ( ) const
inherited

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

Definition at line 1105 of file function_internal.cpp.

1105  {
1106  // Return value
1107  Dict ret;
1108 
1109  // Retrieve all Function instances that haven't been deleted
1110  std::vector<std::string> keys;
1111  std::vector<Function> entries;
1112  cache_.cache(keys, entries);
1113 
1114  for (size_t i=0; i<keys.size(); ++i) {
1115  // Get the name of the key
1116  std::string s = keys[i];
1117  casadi_assert_dev(s.size() > 0);
1118  // Replace ':' with '_'
1119  std::replace(s.begin(), s.end(), ':', '_');
1120  // Remove trailing underscore, if any
1121  if (s.back() == '_') s.resize(s.size() - 1);
1122  // Add entry to function return
1123  ret[s] = entries[i];
1124  }
1125 
1126  return ret;
1127  }
WeakCache< std::string, Function > cache_
Function cache.
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.

References casadi::FunctionInternal::cache_.

◆ calc_function()

int casadi::OracleFunction::calc_function ( OracleMemory m,
const std::string &  fcn,
const double *const *  arg = nullptr,
int  thread_id = 0 
) const
inherited

Definition at line 302 of file oracle_function.cpp.

304  {
305  auto *ml = m->thread_local_mem.at(thread_id);
306  // Is the function monitored?
307  bool monitored = this->monitored(fcn);
308 
309  // Print progress
310  if (monitored) casadi_message("Calling \"" + fcn + "\"");
311 
312  // Respond to a possible Crl+C signals
313  // Python interrupt checker needs the GIL.
314  // We may not have access to it in a multi-threaded context
315  // See issue #2955
317 
318  // Get function
319  const Function& f = get_function(fcn);
320 
321  // Get statistics structure
322  FStats& fstats = ml->fstats.at(fcn);
323 
324  // Number of inputs and outputs
325  casadi_int n_in = f.n_in(), n_out = f.n_out();
326 
327  // Prepare stats, start timer
328  ScopedTiming tic(fstats);
329 
330  // Input buffers
331  if (arg) {
332  std::fill_n(ml->arg, n_in, nullptr);
333  for (casadi_int i=0; i<n_in; ++i) ml->arg[i] = *arg++;
334  }
335 
336  // Print inputs nonzeros
337  if (monitored) {
338  std::stringstream s;
339  s << fcn << " input nonzeros:\n";
340  for (casadi_int i=0; i<n_in; ++i) {
341  s << " " << i << " (" << f.name_in(i) << "): ";
342  if (ml->arg[i]) {
343  // Print nonzeros
344  s << "[";
345  for (casadi_int k=0; k<f.nnz_in(i); ++k) {
346  if (k!=0) s << ", ";
347  DM::print_scalar(s, ml->arg[i][k]);
348  }
349  s << "]\n";
350  } else {
351  // All zero input
352  s << "0\n";
353  }
354  }
355  casadi_message(s.str());
356  }
357 
358  // Evaluate memory-less
359  try {
360  if (f(ml->arg, ml->res, ml->iw, ml->w)) {
361  // Recoverable error
362  if (monitored) casadi_message(name_ + ":" + fcn + " failed");
363  return 1;
364  }
365  } catch(std::exception& ex) {
366  // Fatal error: Generate stack trace
367  casadi_error("Error in " + name_ + ":" + fcn + ":" + std::string(ex.what()));
368  }
369 
370  // Print output nonzeros
371  if (monitored) {
372  std::stringstream s;
373  s << fcn << " output nonzeros:\n";
374  for (casadi_int i=0; i<n_out; ++i) {
375  s << " " << i << " (" << f.name_out(i) << "): ";
376  if (ml->res[i]) {
377  // Print nonzeros
378  s << "[";
379  for (casadi_int k=0; k<f.nnz_out(i); ++k) {
380  if (k!=0) s << ", ";
381  DM::print_scalar(s, ml->res[i][k]);
382  }
383  s << "]\n";
384  } else {
385  // Ignored output
386  s << " N/A\n";
387  }
388  }
389  casadi_message(s.str());
390  }
391 
392  // Make sure not NaN or Inf
393  for (casadi_int i=0; i<n_out; ++i) {
394  if (!ml->res[i]) continue;
395  if (!std::all_of(ml->res[i], ml->res[i]+f.nnz_out(i), [](double v) { return isfinite(v);})) {
396  std::stringstream ss;
397 
398  auto *it = std::find_if(ml->res[i], ml->res[i] + f.nnz_out(i),
399  [](double v) { return !isfinite(v);});
400  casadi_int k = std::distance(ml->res[i], it);
401  bool is_nan = isnan(ml->res[i][k]);
402  ss << name_ << ":" << fcn << " failed: " << (is_nan? "NaN" : "Inf") <<
403  " detected for output " << f.name_out(i) << ", at " << f.sparsity_out(i).repr_el(k) << ".";
404 
405  if (regularity_check_) {
406  casadi_error(ss.str());
407  } else {
408  if (show_eval_warnings_) casadi_warning(ss.str());
409  }
410  return -1;
411  }
412  }
413 
414  // Success
415  return 0;
416 }
static void check()
Raises an error if an interrupt was captured.
void print_scalar(std::ostream &stream) const
Print scalar.
std::vector< std::string > get_function() const override
Get list of dependency functions.
virtual bool monitored(const std::string &name) const
bool show_eval_warnings_
Show evaluation warnings.
bool regularity_check_
Errors are thrown when NaN is produced.

References casadi::InterruptHandler::check(), casadi::OracleFunction::get_function(), casadi::OracleFunction::max_num_threads_, casadi::OracleFunction::monitored(), casadi::Function::n_in(), casadi::Function::n_out(), casadi::ProtoFunction::name_, casadi::Function::name_in(), casadi::Function::name_out(), casadi::Function::nnz_in(), casadi::Function::nnz_out(), casadi::Matrix< double >::print_scalar(), casadi::ProtoFunction::regularity_check_, casadi::Sparsity::repr_el(), casadi::OracleFunction::show_eval_warnings_, casadi::Function::sparsity_out(), and casadi::OracleMemory::thread_local_mem.

Referenced by casadi::KinsolInterface::bjac(), casadi::SundialsInterface::calc_daeB(), casadi::SundialsInterface::calc_daeF(), casadi::Integrator::calc_edot(), casadi::calc_function(), casadi::SundialsInterface::calc_jacF(), casadi::SundialsInterface::calc_jtimesF(), casadi::SundialsInterface::calc_quadB(), casadi::SundialsInterface::calc_quadF(), casadi::casadi_func_cons_jac(), casadi::casadi_func_cons_val(), casadi::casadi_func_hess_prod(), casadi::casadi_func_obj_grad(), casadi::casadi_func_obj_val(), casadi::KinsolInterface::djac(), casadi::Nlpsol::eval(), casadi::AlpaqaProblem::eval_f(), casadi::BonminUserClass::eval_f(), casadi::IpoptUserClass::eval_f(), casadi::AlpaqaProblem::eval_f_grad_f(), casadi::AlpaqaProblem::eval_g(), casadi::BonminUserClass::eval_g(), casadi::IpoptUserClass::eval_g(), casadi::BonminUserClass::eval_grad_f(), casadi::IpoptUserClass::eval_grad_f(), casadi::AlpaqaProblem::eval_grad_L(), casadi::BonminUserClass::eval_h(), casadi::IpoptUserClass::eval_h(), casadi::AlpaqaProblem::eval_hess_L(), casadi::AlpaqaProblem::eval_hess_L_prod(), casadi::AlpaqaProblem::eval_hess_ψ(), casadi::AlpaqaProblem::eval_hess_ψ_prod(), casadi::AlpaqaProblem::eval_jac_g(), casadi::BonminUserClass::eval_jac_g(), casadi::IpoptUserClass::eval_jac_g(), casadi::AlpaqaProblem::eval_ψ(), casadi::AlpaqaProblem::eval_ψ_grad_ψ(), evaluate(), casadi::Feasiblesqpmethod::feasibility_iterations(), casadi::KinsolInterface::psetup(), casadi::KnitroInterface::solve(), casadi::SnoptInterface::solve(), casadi::WorhpInterface::solve(), casadi::Feasiblesqpmethod::solve(), casadi::Newton::solve(), casadi::Qrsqp::solve(), casadi::Sqpmethod::solve(), casadi::FixedStepIntegrator::stepB(), casadi::FixedStepIntegrator::stepF(), casadi::Integrator::trigger_event(), and casadi::SnoptInterface::userfun().

◆ calc_sp_forward()

int casadi::OracleFunction::calc_sp_forward ( const std::string &  fcn,
const bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t w 
) const
inherited

◆ calc_sp_reverse()

int casadi::OracleFunction::calc_sp_reverse ( const std::string &  fcn,
bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t w 
) const
inherited

◆ calcBFGS()

void casadi::Blocksqp::calcBFGS ( BlocksqpMemory m,
const double *  gamma,
const double *  delta,
casadi_int  b 
) const

Definition at line 2133 of file blocksqp.cpp.

2135  {
2136  casadi_int dim = dim_[b];
2137  double h1 = 0.0;
2138  double h2 = 0.0;
2139  double thetaPowell = 0.0;
2140  casadi_int damped;
2141 
2142  /* Work with a local copy of gamma because damping may need to change gamma.
2143  * Note that m->gamma needs to remain unchanged!
2144  * This may be important in a limited memory context:
2145  * When information is "forgotten", B_i-1 is different and the
2146  * original gamma might lead to an undamped update with the new B_i-1! */
2147  std::vector<double> gamma2(gamma, gamma+dim);
2148 
2149  double *B = m->hess[b];
2150 
2151  // Bdelta = B*delta (if sizing is enabled, B is the sized B!)
2152  // h1 = delta^T * B * delta
2153  // h2 = delta^T * gamma
2154  std::vector<double> Bdelta(dim, 0.0);
2155  for (casadi_int i=0; i<dim; i++) {
2156  for (casadi_int k=0; k<dim; k++)
2157  Bdelta[i] += B[i+k*dim] * delta[k];
2158 
2159  h1 += delta[i] * Bdelta[i];
2160  //h2 += delta[i] * gamma[i];
2161  }
2162  h2 = m->delta_gamma[b];
2163 
2164  /* Powell's damping strategy to maintain pos. def. (Nocedal/Wright p.537; SNOPT paper)
2165  * Interpolates between current approximation and unmodified BFGS */
2166  damped = 0;
2167  if (hess_damp_)
2168  if (h2 < hess_damp_fac_ * h1 / m->alpha && fabs(h1 - h2) > 1.0e-12) {
2169  // At the first iteration h1 and h2 are equal due to COL scaling
2170 
2171  thetaPowell = (1.0 - hess_damp_fac_)*h1 / (h1 - h2);
2172 
2173  // Redefine gamma and h2 = delta^T * gamma
2174  h2 = 0.0;
2175  for (casadi_int i=0; i<dim; i++) {
2176  gamma2[i] = thetaPowell*gamma2[i] + (1.0 - thetaPowell)*Bdelta[i];
2177  h2 += delta[i] * gamma2[i];
2178  }
2179 
2180  // Also redefine deltaGamma for computation of sizing factor in the next iteration
2181  m->delta_gamma[b] = h2;
2182 
2183  damped = 1;
2184  }
2185 
2186  // For statistics: count number of damped blocks
2187  m->hessDamped += damped;
2188 
2189  // B_k+1 = B_k - Bdelta * (Bdelta)^T / h1 + gamma * gamma^T / h2
2190  double myEps = 1.0e2 * eps_;
2191  if (fabs(h1) < myEps || fabs(h2) < myEps) {
2192  // don't perform update because of bad condition, might introduce negative eigenvalues
2193  m->noUpdateCounter[b]++;
2194  m->hessDamped -= damped;
2195  m->hessSkipped++;
2196  m->nTotalSkippedUpdates++;
2197  } else {
2198  for (casadi_int i=0; i<dim; i++)
2199  for (casadi_int j=0; j<dim; j++)
2200  B[i+j*dim] += - Bdelta[i]*Bdelta[j]/h1 + gamma2[i]*gamma2[j]/h2;
2201 
2202  m->noUpdateCounter[b] = 0;
2203  }
2204  }

References casadi::BlocksqpMemory::delta_gamma, dim_, eps_, casadi::BlocksqpMemory::hess, hess_damp_, hess_damp_fac_, casadi::BlocksqpMemory::hessDamped, casadi::BlocksqpMemory::hessSkipped, casadi::BlocksqpMemory::noUpdateCounter, and casadi::BlocksqpMemory::nTotalSkippedUpdates.

Referenced by calcHessianUpdate(), and calcHessianUpdateLimitedMemory().

◆ calcHessianUpdate()

void casadi::Blocksqp::calcHessianUpdate ( BlocksqpMemory m,
casadi_int  updateType,
casadi_int  hessScaling 
) const

Apply BFGS or SR1 update blockwise and size blocks

Definition at line 1923 of file blocksqp.cpp.

1924  {
1925  casadi_int nBlocks;
1926  bool firstIter;
1927 
1928  //if objective derv is computed exactly, don't set the last block!
1929  if (which_second_derv_ == 1 && block_hess_)
1930  nBlocks = nblocks_ - 1;
1931  else
1932  nBlocks = nblocks_;
1933 
1934  // Statistics: how often is damping active, what is the average COL sizing factor?
1935  m->hessDamped = 0;
1936  m->averageSizingFactor = 0.0;
1937 
1938  for (casadi_int b=0; b<nBlocks; b++) {
1939  casadi_int dim = dim_[b];
1940 
1941  // smallGamma and smallDelta are subvectors of gamma and delta,
1942  // corresponding to partially separability
1943  double* smallGamma = m->gammaMat + blocks_[b];
1944  double* smallDelta = m->deltaMat + blocks_[b];
1945 
1946  // Is this the first iteration or the first after a Hessian reset?
1947  firstIter = (m->noUpdateCounter[b] == -1);
1948 
1949  // Update sTs, sTs_ and sTy, sTy_
1950  m->delta_norm_old[b] = m->delta_norm[b];
1951  m->delta_gamma_old[b] = m->delta_gamma[b];
1952  m->delta_norm[b] = casadi_dot(dim, smallDelta, smallDelta);
1953  m->delta_gamma[b] = casadi_dot(dim, smallDelta, smallGamma);
1954 
1955  // Sizing before the update
1956  if (hessScaling < 4 && firstIter)
1957  sizeInitialHessian(m, smallGamma, smallDelta, b, hessScaling);
1958  else if (hessScaling == 4)
1959  sizeHessianCOL(m, smallGamma, smallDelta, b);
1960 
1961  // Compute the new update
1962  if (updateType == 1) {
1963  calcSR1(m, smallGamma, smallDelta, b);
1964 
1965  // Prepare to compute fallback update as well
1966  m->hess = m->hess2;
1967 
1968  // Sizing the fallback update
1969  if (fallback_scaling_ < 4 && firstIter)
1970  sizeInitialHessian(m, smallGamma, smallDelta, b, fallback_scaling_);
1971  else if (fallback_scaling_ == 4)
1972  sizeHessianCOL(m, smallGamma, smallDelta, b);
1973 
1974  // Compute fallback update
1975  if (fallback_update_ == 2)
1976  calcBFGS(m, smallGamma, smallDelta, b);
1977 
1978  // Reset pointer
1979  m->hess = m->hess1;
1980  } else if (updateType == 2) {
1981  calcBFGS(m, smallGamma, smallDelta, b);
1982  }
1983 
1984  // If an update is skipped to often, reset Hessian block
1985  if (m->noUpdateCounter[b] > max_consec_skipped_updates_) {
1986  resetHessian(m, b);
1987  }
1988  }
1989 
1990  // statistics: average sizing factor
1991  m->averageSizingFactor /= nBlocks;
1992  }
void resetHessian(BlocksqpMemory *m) const
Definition: blocksqp.cpp:1794
void sizeHessianCOL(BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b) const
Definition: blocksqp.cpp:1874
void sizeInitialHessian(BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b, casadi_int option) const
Definition: blocksqp.cpp:1835
void calcBFGS(BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b) const
Definition: blocksqp.cpp:2134
void calcSR1(BlocksqpMemory *m, const double *gamma, const double *delta, casadi_int b) const
Definition: blocksqp.cpp:2208
T1 casadi_dot(casadi_int n, const T1 *x, const T1 *y)
Inner product.

References casadi::BlocksqpMemory::averageSizingFactor, block_hess_, blocks_, calcBFGS(), calcSR1(), casadi::casadi_dot(), casadi::BlocksqpMemory::delta_gamma, casadi::BlocksqpMemory::delta_gamma_old, casadi::BlocksqpMemory::delta_norm, casadi::BlocksqpMemory::delta_norm_old, casadi::BlocksqpMemory::deltaMat, dim_, fallback_scaling_, fallback_update_, casadi::BlocksqpMemory::gammaMat, casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hess1, casadi::BlocksqpMemory::hess2, casadi::BlocksqpMemory::hessDamped, max_consec_skipped_updates_, nblocks_, casadi::BlocksqpMemory::noUpdateCounter, resetHessian(), sizeHessianCOL(), sizeInitialHessian(), and which_second_derv_.

Referenced by calcHessianUpdateExact(), and run().

◆ calcHessianUpdateExact()

void casadi::Blocksqp::calcHessianUpdateExact ( BlocksqpMemory m) const

Definition at line 2096 of file blocksqp.cpp.

2097  {
2098  // compute exact hessian
2099  (void)evaluate(m, m->exact_hess_lag);
2100 
2101  // assign exact hessian to blocks
2102  const casadi_int* col = exact_hess_lag_sp_.colind();
2103  const casadi_int* row = exact_hess_lag_sp_.row();
2104  casadi_int s, dim;
2105 
2106  for (casadi_int k=0; k<nblocks_; k++) {
2107  s = blocks_[k];
2108  dim = dim_[k];
2109  for (casadi_int i=0; i<dim; i++)
2110  // Set diagonal to 0 (may have been 1 because of CalcInitialHessian)
2111  m->hess[k][i + i*dim] = 0.0;
2112  for (casadi_int j=0; j<dim; j++) {
2113  for (casadi_int i=col[j+s]; i<col[j+1+s]; i++) {
2114  m->hess[k][row[i]-row[col[s]] + j*dim] = m->exact_hess_lag[i];
2115  if (row[i]-row[col[s]] < j)
2116  m->hess[k][j + (row[i]-row[col[s]])*dim] = m->exact_hess_lag[i];
2117  }
2118  }
2119  }
2120 
2121  // Prepare to compute fallback update as well
2122  m->hess = m->hess2;
2123  if (fallback_update_ == 2 && !hess_lim_mem_)
2125  else if (fallback_update_ == 0)
2126  calcInitialHessian(m); // Set fallback as Identity
2127 
2128  // Reset pointer
2129  m->hess = m->hess1;
2130  }
void calcInitialHessian(BlocksqpMemory *m) const
Definition: blocksqp.cpp:1765
casadi_int evaluate(BlocksqpMemory *m, double *f, double *g, double *grad_f, double *jac_g) const
Evaluate objective and constraints, including derivatives.
Definition: blocksqp.cpp:2783
void calcHessianUpdate(BlocksqpMemory *m, casadi_int updateType, casadi_int hessScaling) const
Definition: blocksqp.cpp:1924
const casadi_int * row() const
Get a reference to row-vector,.
Definition: sparsity.cpp:164
const casadi_int * colind() const
Get a reference to the colindex of all column element (see class description)
Definition: sparsity.cpp:168

References blocks_, calcHessianUpdate(), calcInitialHessian(), casadi::Sparsity::colind(), dim_, evaluate(), casadi::BlocksqpMemory::exact_hess_lag, exact_hess_lag_sp_, fallback_scaling_, fallback_update_, casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hess1, casadi::BlocksqpMemory::hess2, hess_lim_mem_, nblocks_, and casadi::Sparsity::row().

Referenced by run().

◆ calcHessianUpdateLimitedMemory()

void casadi::Blocksqp::calcHessianUpdateLimitedMemory ( BlocksqpMemory m,
casadi_int  updateType,
casadi_int  hessScaling 
) const

Definition at line 1995 of file blocksqp.cpp.

1997  {
1998  casadi_int nBlocks;
1999  casadi_int m2, pos, posOldest, posNewest;
2000  casadi_int hessDamped, hessSkipped;
2001  double averageSizingFactor;
2002 
2003  //if objective derv is computed exactly, don't set the last block!
2004  if (which_second_derv_ == 1 && block_hess_) {
2005  nBlocks = nblocks_ - 1;
2006  } else {
2007  nBlocks = nblocks_;
2008  }
2009 
2010  // Statistics: how often is damping active, what is the average COL sizing factor?
2011  m->hessDamped = 0;
2012  m->hessSkipped = 0;
2013  m->averageSizingFactor = 0.0;
2014 
2015  for (casadi_int b=0; b<nBlocks; b++) {
2016  casadi_int dim = dim_[b];
2017 
2018  // smallGamma and smallDelta are submatrices of gammaMat, deltaMat,
2019  // i.e. subvectors of gamma and delta from m prev. iterations
2020  double *smallGamma = m->gammaMat + blocks_[b];
2021  double *smallDelta = m->deltaMat + blocks_[b];
2022 
2023  // Memory structure
2024  if (m->itCount > hess_memsize_) {
2025  m2 = hess_memsize_;
2026  posOldest = m->itCount % m2;
2027  posNewest = (m->itCount-1) % m2;
2028  } else {
2029  m2 = m->itCount;
2030  posOldest = 0;
2031  posNewest = m2-1;
2032  }
2033 
2034  // Set B_0 (pretend it's the first step)
2035  calcInitialHessian(m, b);
2036  m->delta_norm[b] = 1.0;
2037  m->delta_norm_old[b] = 1.0;
2038  m->delta_gamma[b] = 0.0;
2039  m->delta_gamma_old[b] = 0.0;
2040  m->noUpdateCounter[b] = -1;
2041 
2042  // Size the initial update, but with the most recent delta/gamma-pair
2043  double *gammai = smallGamma + nx_*posNewest;
2044  double *deltai = smallDelta + nx_*posNewest;
2045  sizeInitialHessian(m, gammai, deltai, b, hessScaling);
2046 
2047  for (casadi_int i=0; i<m2; i++) {
2048  pos = (posOldest+i) % m2;
2049 
2050  // Get new vector from list
2051  gammai = smallGamma + nx_*pos;
2052  deltai = smallDelta + nx_*pos;
2053 
2054  // Update sTs, sTs_ and sTy, sTy_
2055  m->delta_norm_old[b] = m->delta_norm[b];
2056  m->delta_gamma_old[b] = m->delta_gamma[b];
2057  m->delta_norm[b] = casadi_dot(dim, deltai, deltai);
2058  m->delta_gamma[b] = casadi_dot(dim, gammai, deltai);
2059 
2060  // Save statistics, we want to record them only for the most recent update
2061  averageSizingFactor = m->averageSizingFactor;
2062  hessDamped = m->hessDamped;
2063  hessSkipped = m->hessSkipped;
2064 
2065  // Selective sizing before the update
2066  if (hessScaling == 4) sizeHessianCOL(m, gammai, deltai, b);
2067 
2068  // Compute the new update
2069  if (updateType == 1) {
2070  calcSR1(m, gammai, deltai, b);
2071  } else if (updateType == 2) {
2072  calcBFGS(m, gammai, deltai, b);
2073  }
2074 
2075  m->nTotalUpdates++;
2076 
2077  // Count damping statistics only for the most recent update
2078  if (pos != posNewest) {
2079  m->hessDamped = hessDamped;
2080  m->hessSkipped = hessSkipped;
2081  if (hessScaling == 4)
2082  m->averageSizingFactor = averageSizingFactor;
2083  }
2084  }
2085 
2086  // If an update is skipped to often, reset Hessian block
2087  if (m->noUpdateCounter[b] > max_consec_skipped_updates_) {
2088  resetHessian(m, b);
2089  }
2090  }
2091  //blocks
2092  m->averageSizingFactor /= nBlocks;
2093  }

References casadi::BlocksqpMemory::averageSizingFactor, block_hess_, blocks_, calcBFGS(), calcInitialHessian(), calcSR1(), casadi::casadi_dot(), casadi::BlocksqpMemory::delta_gamma, casadi::BlocksqpMemory::delta_gamma_old, casadi::BlocksqpMemory::delta_norm, casadi::BlocksqpMemory::delta_norm_old, casadi::BlocksqpMemory::deltaMat, dim_, casadi::BlocksqpMemory::gammaMat, hess_memsize_, casadi::BlocksqpMemory::hessDamped, casadi::BlocksqpMemory::hessSkipped, casadi::BlocksqpMemory::itCount, max_consec_skipped_updates_, nblocks_, casadi::BlocksqpMemory::noUpdateCounter, casadi::BlocksqpMemory::nTotalUpdates, casadi::Nlpsol::nx_, resetHessian(), sizeHessianCOL(), sizeInitialHessian(), and which_second_derv_.

Referenced by computeNextHessian(), and run().

◆ calcInitialHessian() [1/2]

void casadi::Blocksqp::calcInitialHessian ( BlocksqpMemory m) const

Initial Hessian: Identity matrix

Definition at line 1765 of file blocksqp.cpp.

1765  {
1766  for (casadi_int b=0; b<nblocks_; b++)
1767  //if objective derv is computed exactly, don't set the last block!
1768  if (!(which_second_derv_ == 1 && block_hess_
1769  && b == nblocks_-1))
1770  calcInitialHessian(m, b);
1771  }

References block_hess_, nblocks_, and which_second_derv_.

Referenced by calcHessianUpdateExact(), calcHessianUpdateLimitedMemory(), resetHessian(), and run().

◆ calcInitialHessian() [2/2]

void casadi::Blocksqp::calcInitialHessian ( BlocksqpMemory m,
casadi_int  b 
) const

Initial Hessian for one block: Identity matrix

Definition at line 1777 of file blocksqp.cpp.

1777  {
1778  casadi_int dim = dim_[b];
1779  casadi_fill(m->hess[b], dim*dim, 0.);
1780 
1781  // Each block is a diagonal matrix
1782  for (casadi_int i=0; i<dim; i++)
1783  m->hess[b][i+i*dim] = ini_hess_diag_;
1784 
1785  // If we maintain 2 Hessians, also reset the second one
1786  if (m->hess2 != nullptr) {
1787  casadi_fill(m->hess2[b], dim*dim, 0.);
1788  for (casadi_int i=0; i<dim; i++)
1789  m->hess2[b][i+i*dim] = ini_hess_diag_;
1790  }
1791  }
void casadi_fill(T1 *x, casadi_int n, T1 alpha)
FILL: x <- alpha.

References casadi::casadi_fill(), dim_, casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hess2, and ini_hess_diag_.

◆ calcLagrangeGradient() [1/2]

void casadi::Blocksqp::calcLagrangeGradient ( BlocksqpMemory m,
const double *  lam_x,
const double *  lam_g,
const double *  grad_f,
const double *  jacNz,
double *  grad_lag,
casadi_int  flag 
) const

Compute gradient of Lagrangian or difference of Lagrangian gradients (sparse version)

flag == 0: output dL(xk, lambda) flag == 1: output dL(xi_k+1, lambda_k+1) - L(xi_k, lambda_k+1) flag == 2: output dL(xi_k+1, lambda_k+1) - df(xi)

Definition at line 952 of file blocksqp.cpp.

956  {
957 
958  // Objective gradient
959  if (flag == 0) {
960  casadi_copy(grad_f, nx_, grad_lag);
961  } else if (flag == 1) {
962  casadi_scal(nx_, -1., grad_lag);
963  casadi_axpy(nx_, 1., grad_f, grad_lag);
964  } else {
965  casadi_fill(grad_lag, nx_, 0.);
966  }
967 
968  // - lambdaT * constrJac
969  const casadi_int* jacIndRow = Asp_.row();
970  const casadi_int* jacIndCol = Asp_.colind();
971  for (casadi_int iVar=0; iVar<nx_; iVar++) {
972  for (casadi_int iCon=jacIndCol[iVar]; iCon<jacIndCol[iVar+1]; iCon++) {
973  grad_lag[iVar] -= lam_g[jacIndRow[iCon]] * jacNz[iCon];
974  }
975  }
976 
977  // - lambdaT * simpleBounds
978  casadi_axpy(nx_, -1., lam_x, grad_lag);
979  }
void casadi_copy(const T1 *x, casadi_int n, T1 *y)
COPY: y <-x.
void casadi_scal(casadi_int n, T1 alpha, T1 *x)
SCAL: x <- alpha*x.
void casadi_axpy(casadi_int n, T1 alpha, const T1 *x, T1 *y)
AXPY: y <- a*x + y.

References Asp_, casadi::casadi_axpy(), casadi::casadi_copy(), casadi::casadi_fill(), casadi::casadi_scal(), casadi::Sparsity::colind(), casadi::Nlpsol::nx_, and casadi::Sparsity::row().

Referenced by calcLagrangeGradient(), calcOptTol(), kktErrorReduction(), and run().

◆ calcLagrangeGradient() [2/2]

void casadi::Blocksqp::calcLagrangeGradient ( BlocksqpMemory m,
double *  grad_lag,
casadi_int  flag 
) const

Wrapper if called with standard arguments

Definition at line 984 of file blocksqp.cpp.

985  {
986  calcLagrangeGradient(m, m->lam_xk, m->lam_gk, m->grad_fk, m->jac_g,
987  grad_lag, flag);
988  }
void calcLagrangeGradient(BlocksqpMemory *m, const double *lam_x, const double *lam_g, const double *grad_f, const double *jacNz, double *grad_lag, casadi_int flag) const
Compute gradient of Lagrangian function (sparse version)
Definition: blocksqp.cpp:953

References calcLagrangeGradient(), casadi::BlocksqpMemory::grad_fk, casadi::BlocksqpMemory::jac_g, casadi::BlocksqpMemory::lam_gk, and casadi::BlocksqpMemory::lam_xk.

◆ calcOptTol()

bool casadi::Blocksqp::calcOptTol ( BlocksqpMemory m) const

Compute optimality conditions: ||grad_lag(xk,lambda)||_infty / (1 + ||lambda||_infty) <= TOL and ||constrViolation||_infty / (1 + ||xi||_infty) <= TOL

Definition at line 997 of file blocksqp.cpp.

997  {
998  auto d_nlp = &m->d_nlp;
999  // scaled norm of Lagrangian gradient
1000  calcLagrangeGradient(m, m->grad_lagk, 0);
1001  m->gradNorm = casadi_norm_inf(nx_, m->grad_lagk);
1002  m->tol = m->gradNorm/(1.0+fmax(casadi_norm_inf(nx_, m->lam_xk),
1003  casadi_norm_inf(ng_, m->lam_gk)));
1004 
1005  // norm of constraint violation
1006  m->cNorm = lInfConstraintNorm(m, d_nlp->z, m->gk);
1007  m->cNormS = m->cNorm /(1.0 + casadi_norm_inf(nx_, d_nlp->z));
1008 
1009  return m->tol <= opttol_ && m->cNormS <= nlinfeastol_;
1010  }
double lInfConstraintNorm(BlocksqpMemory *m, const double *xk, const double *g) const
Definition: blocksqp.cpp:2841
T1 casadi_norm_inf(casadi_int n, const T1 *x)

References calcLagrangeGradient(), casadi::casadi_norm_inf(), casadi::BlocksqpMemory::cNorm, casadi::BlocksqpMemory::cNormS, casadi::NlpsolMemory::d_nlp, casadi::BlocksqpMemory::gk, casadi::BlocksqpMemory::grad_lagk, casadi::BlocksqpMemory::gradNorm, casadi::BlocksqpMemory::lam_gk, casadi::BlocksqpMemory::lam_xk, lInfConstraintNorm(), casadi::Nlpsol::ng_, nlinfeastol_, casadi::Nlpsol::nx_, opttol_, and casadi::BlocksqpMemory::tol.

Referenced by run().

◆ calcSR1()

void casadi::Blocksqp::calcSR1 ( BlocksqpMemory m,
const double *  gamma,
const double *  delta,
casadi_int  b 
) const

Definition at line 2207 of file blocksqp.cpp.

2209  {
2210  casadi_int dim = dim_[b];
2211  double *B = m->hess[b];
2212  double myEps = 1.0e2 * eps_;
2213  double r = 1.0e-8;
2214  double h = 0.0;
2215 
2216  // gmBdelta = gamma - B*delta
2217  // h = (gamma - B*delta)^T * delta
2218  std::vector<double> gmBdelta(dim);
2219  for (casadi_int i=0; i<dim; i++) {
2220  gmBdelta[i] = gamma[i];
2221  for (casadi_int k=0; k<dim; k++)
2222  gmBdelta[i] -= B[i+k*dim] * delta[k];
2223 
2224  h += (gmBdelta[i] * delta[i]);
2225  }
2226 
2227  // B_k+1 = B_k + gmBdelta * gmBdelta^T / h
2228  if (fabs(h) < r * casadi_norm_2(dim, delta)
2229  *casadi_norm_2(dim, get_ptr(gmBdelta)) || fabs(h) < myEps) {
2230  // Skip update if denominator is too small
2231  m->noUpdateCounter[b]++;
2232  m->hessSkipped++;
2233  m->nTotalSkippedUpdates++;
2234  } else {
2235  for (casadi_int i=0; i<dim; i++)
2236  for (casadi_int j=0; j<dim; j++)
2237  B[i+j*dim] += gmBdelta[i]*gmBdelta[j]/h;
2238  m->noUpdateCounter[b] = 0;
2239  }
2240  }
T1 casadi_norm_2(casadi_int n, const T1 *x)
NORM_2: ||x||_2 -> return.
T * get_ptr(std::vector< T > &v)
Get a pointer to the data contained in the vector.

References casadi::casadi_norm_2(), dim_, eps_, casadi::get_ptr(), casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hessSkipped, casadi::BlocksqpMemory::noUpdateCounter, and casadi::BlocksqpMemory::nTotalSkippedUpdates.

Referenced by calcHessianUpdate(), and calcHessianUpdateLimitedMemory().

◆ call()

template<typename M >
void casadi::FunctionInternal::call ( const std::vector< M > &  arg,
std::vector< M > &  res,
bool  always_inline,
bool  never_inline 
) const
inherited

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

Definition at line 1615 of file function_internal.hpp.

1616  {
1617  // If all inputs are scalar ...
1618  if (all_scalar()) {
1619  // ... and some arguments are matrix-valued with matching dimensions ...
1620  bool matrix_call = false;
1621  std::pair<casadi_int, casadi_int> sz;
1622  for (auto&& a : arg) {
1623  if (!a.is_scalar() && !a.is_empty()) {
1624  if (!matrix_call) {
1625  // Matrix call
1626  matrix_call = true;
1627  sz = a.size();
1628  } else if (a.size()!=sz) {
1629  // Not same dimensions
1630  matrix_call = false;
1631  break;
1632  }
1633  }
1634  }
1635 
1636  // ... then, call multiple times
1637  if (matrix_call) {
1638  // Start with zeros
1639  res.resize(n_out_);
1640  M z = M::zeros(sz);
1641  for (auto&& a : res) a = z;
1642  // Call multiple times
1643  std::vector<M> arg1 = arg, res1;
1644  for (casadi_int c=0; c<sz.second; ++c) {
1645  for (casadi_int r=0; r<sz.first; ++r) {
1646  // Get scalar arguments
1647  for (casadi_int i=0; i<arg.size(); ++i) {
1648  if (arg[i].size()==sz) arg1[i] = arg[i](r, c);
1649  }
1650  // Call recursively with scalar arguments
1651  call(arg1, res1, always_inline, never_inline);
1652  // Get results
1653  casadi_assert_dev(res.size() == res1.size());
1654  for (casadi_int i=0; i<res.size(); ++i) res[i](r, c) = res1[i];
1655  }
1656  }
1657  // All elements assigned
1658  return;
1659  }
1660  }
1661 
1662  // Check if inputs need to be replaced
1663  casadi_int npar = 1;
1664  if (!matching_arg(arg, npar)) {
1665  return call(replace_arg(arg, npar), res, always_inline, never_inline);
1666  }
1667 
1668  // Call the type-specific method
1669  call_gen(arg, res, npar, always_inline, never_inline);
1670  }
void call_gen(const MXVector &arg, MXVector &res, casadi_int npar, bool always_inline, bool never_inline) const
Call a function, overloaded.
std::vector< M > replace_arg(const std::vector< M > &arg, casadi_int npar) const
Replace 0-by-0 inputs.
bool matching_arg(const std::vector< M > &arg, casadi_int &npar) const
Check if input arguments that needs to be replaced.
void call(const std::vector< M > &arg, std::vector< M > &res, bool always_inline, bool never_inline) const
Call a function, templated.
bool all_scalar() const
Are all inputs and outputs scalar.

References casadi::FunctionInternal::all_scalar(), casadi::FunctionInternal::call_gen(), casadi::FunctionInternal::matching_arg(), casadi::FunctionInternal::n_out_, and casadi::FunctionInternal::replace_arg().

◆ call_forward() [1/2]

void casadi::FunctionInternal::call_forward ( const std::vector< MX > &  arg,
const std::vector< MX > &  res,
const std::vector< std::vector< MX > > &  fseed,
std::vector< std::vector< MX > > &  fsens,
bool  always_inline,
bool  never_inline 
) const
virtualinherited

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

Definition at line 3217 of file function_internal.cpp.

3221  {
3222  casadi_assert(!(always_inline && never_inline), "Inconsistent options");
3223  casadi_assert(!always_inline, "Class " + class_name() +
3224  " cannot be inlined in an MX expression");
3225 
3226  // Derivative information must be available
3227  casadi_assert(has_derivative(),
3228  "Derivatives cannot be calculated for " + name_);
3229 
3230  // Number of directional derivatives
3231  casadi_int nfwd = fseed.size();
3232  fsens.resize(nfwd);
3233 
3234  // Quick return if no seeds
3235  if (nfwd==0) return;
3236 
3237  // Check if seeds need to have dimensions corrected
3238  casadi_int npar = 1;
3239  for (auto&& r : fseed) {
3240  if (!matching_arg(r, npar)) {
3241  FunctionInternal::call_forward(arg, res, replace_fseed(fseed, npar),
3242  fsens, always_inline, never_inline);
3243  return;
3244  }
3245  }
3246 
3247  // Calculating full Jacobian and then multiplying
3248  if (fwdViaJac(nfwd)) {
3249  // Multiply the Jacobian from the right
3250  std::vector<MX> darg = arg;
3251  darg.insert(darg.end(), res.begin(), res.end());
3252  std::vector<MX> J = jacobian()(darg);
3253  // Join forward seeds
3254  std::vector<MX> v(nfwd), all_fseed(n_in_);
3255  for (size_t i = 0; i < n_in_; ++i) {
3256  for (size_t d = 0; d < nfwd; ++d) v[d] = vec(fseed.at(d).at(i));
3257  all_fseed[i] = horzcat(v);
3258  }
3259  // Calculate forward sensitivities
3260  std::vector<MX> all_fsens(n_out_);
3261  std::vector<MX>::const_iterator J_it = J.begin();
3262  for (size_t oind = 0; oind < n_out_; ++oind) {
3263  for (size_t iind = 0; iind < n_in_; ++iind) {
3264  // Add contribution
3265  MX a = mtimes(*J_it++, all_fseed[iind]);
3266  all_fsens[oind] = all_fsens[oind].is_empty(true) ? a : all_fsens[oind] + a;
3267  }
3268  }
3269  // Split forward sensitivities
3270  for (size_t d = 0; d < nfwd; ++d) fsens[d].resize(n_out_);
3271  for (size_t i = 0; i < n_out_; ++i) {
3272  v = horzsplit(all_fsens[i]);
3273  casadi_assert_dev(v.size() == nfwd);
3274  for (size_t d = 0; d < nfwd; ++d) fsens[d][i] = reshape(v[d], size_out(i));
3275  }
3276  } else {
3277  // Evaluate in batches
3278  casadi_assert_dev(enable_forward_ || enable_fd_);
3279  casadi_int max_nfwd = max_num_dir_;
3280  if (!enable_fd_) {
3281  while (!has_forward(max_nfwd)) max_nfwd/=2;
3282  }
3283  casadi_int offset = 0;
3284  while (offset<nfwd) {
3285  // Number of derivatives, in this batch
3286  casadi_int nfwd_batch = std::min(nfwd-offset, max_nfwd);
3287 
3288  // All inputs and seeds
3289  std::vector<MX> darg;
3290  darg.reserve(n_in_ + n_out_ + n_in_);
3291  darg.insert(darg.end(), arg.begin(), arg.end());
3292  darg.insert(darg.end(), res.begin(), res.end());
3293  std::vector<MX> v(nfwd_batch);
3294  for (casadi_int i=0; i<n_in_; ++i) {
3295  for (casadi_int d=0; d<nfwd_batch; ++d) v[d] = fseed[offset+d][i];
3296  darg.push_back(horzcat(v));
3297  }
3298 
3299  // Create the evaluation node
3300  Function dfcn = self().forward(nfwd_batch);
3301  std::vector<MX> x = dfcn(darg);
3302 
3303  casadi_assert_dev(x.size()==n_out_);
3304 
3305  // Retrieve sensitivities
3306  for (casadi_int d=0; d<nfwd_batch; ++d) fsens[offset+d].resize(n_out_);
3307  for (casadi_int i=0; i<n_out_; ++i) {
3308  if (size2_out(i)>0) {
3309  v = horzsplit(x[i], size2_out(i));
3310  casadi_assert_dev(v.size()==nfwd_batch);
3311  } else {
3312  v = std::vector<MX>(nfwd_batch, MX(size_out(i)));
3313  }
3314  for (casadi_int d=0; d<nfwd_batch; ++d) fsens[offset+d][i] = v[d];
3315  }
3316 
3317  // Update offset
3318  offset += nfwd_batch;
3319  }
3320  }
3321  }
virtual void call_forward(const std::vector< MX > &arg, const std::vector< MX > &res, const std::vector< std::vector< MX > > &fseed, std::vector< std::vector< MX > > &fsens, bool always_inline, bool never_inline) const
Forward mode AD, virtual functions overloaded in derived classes.
Function forward(casadi_int nfwd) const
Return function that calculates forward derivatives.
virtual bool has_forward(casadi_int nfwd) const
Return function that calculates forward derivatives.
std::vector< std::vector< M > > replace_fseed(const std::vector< std::vector< M >> &fseed, casadi_int npar) const
Replace 0-by-0 forward seeds.
bool has_derivative() const
Can derivatives be calculated in any way?
casadi_int size2_out(casadi_int ind) const
Input/output dimensions.
std::pair< casadi_int, casadi_int > size_out(casadi_int ind) const
Input/output dimensions.
casadi_int max_num_dir_
Maximum number of sensitivity directions.
virtual bool fwdViaJac(casadi_int nfwd) const
Calculate derivatives by multiplying the full Jacobian and multiplying.
Function jacobian() const
Return Jacobian of all input elements with respect to all output elements.
virtual std::string class_name() const =0
Readable name of the internal class.

References casadi::SharedObjectInternal::class_name(), casadi::FunctionInternal::enable_fd_, casadi::FunctionInternal::enable_forward_, casadi::FunctionInternal::forward(), casadi::FunctionInternal::fwdViaJac(), casadi::FunctionInternal::has_derivative(), casadi::FunctionInternal::has_forward(), casadi::FunctionInternal::jacobian(), casadi::FunctionInternal::matching_arg(), casadi::FunctionInternal::max_num_dir_, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::replace_fseed(), casadi::FunctionInternal::size2_out(), and casadi::FunctionInternal::size_out().

Referenced by casadi::Rootfinder::ad_forward(), casadi::Call::ad_forward(), casadi::MXFunction::ad_forward(), casadi::XFunction< DerivedType, MatType, NodeType >::call_forward(), casadi::MX::forward(), casadi::Integrator::get_forward_dae(), and casadi::Scpgen::init().

◆ call_forward() [2/2]

void casadi::FunctionInternal::call_forward ( const std::vector< SX > &  arg,
const std::vector< SX > &  res,
const std::vector< std::vector< SX > > &  fseed,
std::vector< std::vector< SX > > &  fsens,
bool  always_inline,
bool  never_inline 
) const
virtualinherited

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

Definition at line 3438 of file function_internal.cpp.

3442  {
3443  casadi_assert(!(always_inline && never_inline), "Inconsistent options");
3444  if (fseed.empty()) { // Quick return if no seeds
3445  fsens.clear();
3446  return;
3447  }
3448  casadi_error("'forward' (SX) not defined for " + class_name());
3449  }

References casadi::SharedObjectInternal::class_name().

◆ call_gen() [1/2]

void casadi::FunctionInternal::call_gen ( const MXVector arg,
MXVector res,
casadi_int  npar,
bool  always_inline,
bool  never_inline 
) const
inherited

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

Definition at line 4125 of file function_internal.cpp.

4127  {
4128  if (npar==1) {
4129  eval_mx(arg, res, always_inline, never_inline);
4130  } else {
4131  // Split it up arguments
4132  std::vector<std::vector<MX>> v(npar, arg);
4133  std::vector<MX> t;
4134  for (int i=0; i<n_in_; ++i) {
4135  if (arg[i].size2()!=size2_in(i)) {
4136  t = horzsplit(arg[i], size2_in(i));
4137  casadi_assert_dev(t.size()==npar);
4138  for (int p=0; p<npar; ++p) v[p][i] = t[p];
4139  }
4140  }
4141  // Unroll the loop
4142  for (int p=0; p<npar; ++p) {
4143  eval_mx(v[p], t, always_inline, never_inline);
4144  v[p] = t;
4145  }
4146  // Concatenate results
4147  t.resize(npar);
4148  res.resize(n_out_);
4149  for (int i=0; i<n_out_; ++i) {
4150  for (int p=0; p<npar; ++p) t[p] = v[p][i];
4151  res[i] = horzcat(t);
4152  }
4153  }
4154  }
virtual void eval_mx(const MXVector &arg, MXVector &res, bool always_inline, bool never_inline) const
Evaluate with symbolic matrices.
casadi_int size2_in(casadi_int ind) const
Input/output dimensions.

References casadi::FunctionInternal::eval_mx(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, and casadi::FunctionInternal::size2_in().

Referenced by casadi::FunctionInternal::call().

◆ call_gen() [2/2]

template<typename D >
void casadi::FunctionInternal::call_gen ( const std::vector< Matrix< D > > &  arg,
std::vector< Matrix< D > > &  res,
casadi_int  npar,
bool  always_inline,
bool  never_inline 
) const
inherited

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

Definition at line 1719 of file function_internal.hpp.

1721  {
1722  std::vector< Matrix<D> > arg2 = project_arg(arg, npar);
1723 
1724  // Which arguments require mapped evaluation
1725  std::vector<bool> mapped(n_in_);
1726  for (casadi_int i=0; i<n_in_; ++i) {
1727  mapped[i] = arg[i].size2()!=size2_in(i);
1728  }
1729 
1730  // Allocate results
1731  res.resize(n_out_);
1732  for (casadi_int i=0; i<n_out_; ++i) {
1733  if (!res[i].sparsity().is_stacked(sparsity_out(i), npar)) {
1734  res[i] = Matrix<D>::zeros(repmat(sparsity_out(i), 1, npar));
1735  }
1736  }
1737 
1738  // Allocate temporary memory if needed
1739  std::vector<casadi_int> iw_tmp(sz_iw());
1740  std::vector<D> w_tmp(sz_w());
1741 
1742  // Get pointers to input arguments
1743  std::vector<const D*> argp(sz_arg());
1744  for (casadi_int i=0; i<n_in_; ++i) argp[i]=get_ptr(arg2[i]);
1745 
1746  // Get pointers to output arguments
1747  std::vector<D*> resp(sz_res());
1748  for (casadi_int i=0; i<n_out_; ++i) resp[i]=get_ptr(res[i]);
1749 
1750  // For all parallel calls
1751  for (casadi_int p=0; p<npar; ++p) {
1752  // Call memory-less
1753  if (eval_gen(get_ptr(argp), get_ptr(resp),
1754  get_ptr(iw_tmp), get_ptr(w_tmp), memory(0),
1755  always_inline, never_inline)) {
1756  if (error_on_fail_) casadi_error("Evaluation failed");
1757  }
1758  // Update offsets
1759  if (p==npar-1) break;
1760  for (casadi_int i=0; i<n_in_; ++i) if (mapped[i]) argp[i] += nnz_in(i);
1761  for (casadi_int i=0; i<n_out_; ++i) resp[i] += nnz_out(i);
1762  }
1763  }
std::vector< M > project_arg(const std::vector< M > &arg, casadi_int npar) const
Project sparsities.
const Sparsity & sparsity_out(casadi_int ind) const
Input/output sparsity.
int eval_gen(const double **arg, double **res, casadi_int *iw, double *w, void *mem, bool always_inline, bool never_inline) const
Evaluate numerically.
static Matrix< Scalar > zeros(casadi_int nrow=1, casadi_int ncol=1)
Create a dense matrix or a matrix with specified sparsity with all entries zero.
bool error_on_fail_
Throw an exception on failure?
void * memory(int ind) const
Memory objects.

References casadi::ProtoFunction::error_on_fail_, casadi::FunctionInternal::eval_gen(), casadi::get_ptr(), casadi::ProtoFunction::memory(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::project_arg(), casadi::FunctionInternal::size2_in(), casadi::FunctionInternal::sparsity_out(), casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), casadi::FunctionInternal::sz_w(), and casadi::GenericMatrix< Matrix< Scalar > >::zeros().

◆ call_reverse() [1/2]

void casadi::FunctionInternal::call_reverse ( const std::vector< MX > &  arg,
const std::vector< MX > &  res,
const std::vector< std::vector< MX > > &  aseed,
std::vector< std::vector< MX > > &  asens,
bool  always_inline,
bool  never_inline 
) const
virtualinherited

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

Definition at line 3323 of file function_internal.cpp.

3327  {
3328  casadi_assert(!(always_inline && never_inline), "Inconsistent options");
3329  casadi_assert(!always_inline, "Class " + class_name() +
3330  " cannot be inlined in an MX expression");
3331 
3332  // Derivative information must be available
3333  casadi_assert(has_derivative(),
3334  "Derivatives cannot be calculated for " + name_);
3335 
3336  // Number of directional derivatives
3337  casadi_int nadj = aseed.size();
3338  asens.resize(nadj);
3339 
3340  // Quick return if no seeds
3341  if (nadj==0) return;
3342 
3343  // Check if seeds need to have dimensions corrected
3344  casadi_int npar = 1;
3345  for (auto&& r : aseed) {
3346  if (!matching_res(r, npar)) {
3347  FunctionInternal::call_reverse(arg, res, replace_aseed(aseed, npar),
3348  asens, always_inline, never_inline);
3349  return;
3350  }
3351  }
3352 
3353  // Calculating full Jacobian and then multiplying likely cheaper
3354  if (adjViaJac(nadj)) {
3355  // Multiply the transposed Jacobian from the right
3356  std::vector<MX> darg = arg;
3357  darg.insert(darg.end(), res.begin(), res.end());
3358  std::vector<MX> J = jacobian()(darg);
3359  // Join adjoint seeds
3360  std::vector<MX> v(nadj), all_aseed(n_out_);
3361  for (size_t i = 0; i < n_out_; ++i) {
3362  for (size_t d = 0; d < nadj; ++d) v[d] = vec(aseed.at(d).at(i));
3363  all_aseed[i] = horzcat(v);
3364  }
3365  // Calculate adjoint sensitivities
3366  std::vector<MX> all_asens(n_in_);
3367  std::vector<MX>::const_iterator J_it = J.begin();
3368  for (size_t oind = 0; oind < n_out_; ++oind) {
3369  for (size_t iind = 0; iind < n_in_; ++iind) {
3370  // Add contribution
3371  MX a = mtimes((*J_it++).T(), all_aseed[oind]);
3372  all_asens[iind] = all_asens[iind].is_empty(true) ? a : all_asens[iind] + a;
3373  }
3374  }
3375  // Split adjoint sensitivities
3376  for (size_t d = 0; d < nadj; ++d) asens[d].resize(n_in_);
3377  for (size_t i = 0; i < n_in_; ++i) {
3378  v = horzsplit(all_asens[i]);
3379  casadi_assert_dev(v.size() == nadj);
3380  for (size_t d = 0; d < nadj; ++d) {
3381  if (asens[d][i].is_empty(true)) {
3382  asens[d][i] = reshape(v[d], size_in(i));
3383  } else {
3384  asens[d][i] += reshape(v[d], size_in(i));
3385  }
3386  }
3387  }
3388  } else {
3389  // Evaluate in batches
3390  casadi_assert_dev(enable_reverse_);
3391  casadi_int max_nadj = max_num_dir_;
3392 
3393  while (!has_reverse(max_nadj)) max_nadj/=2;
3394  casadi_int offset = 0;
3395  while (offset<nadj) {
3396  // Number of derivatives, in this batch
3397  casadi_int nadj_batch = std::min(nadj-offset, max_nadj);
3398 
3399  // All inputs and seeds
3400  std::vector<MX> darg;
3401  darg.reserve(n_in_ + n_out_ + n_out_);
3402  darg.insert(darg.end(), arg.begin(), arg.end());
3403  darg.insert(darg.end(), res.begin(), res.end());
3404  std::vector<MX> v(nadj_batch);
3405  for (casadi_int i=0; i<n_out_; ++i) {
3406  for (casadi_int d=0; d<nadj_batch; ++d) v[d] = aseed[offset+d][i];
3407  darg.push_back(horzcat(v));
3408  }
3409 
3410  // Create the evaluation node
3411  Function dfcn = self().reverse(nadj_batch);
3412  std::vector<MX> x = dfcn(darg);
3413  casadi_assert_dev(x.size()==n_in_);
3414 
3415  // Retrieve sensitivities
3416  for (casadi_int d=0; d<nadj_batch; ++d) asens[offset+d].resize(n_in_);
3417  for (casadi_int i=0; i<n_in_; ++i) {
3418  if (size2_in(i)>0) {
3419  v = horzsplit(x[i], size2_in(i));
3420  casadi_assert_dev(v.size()==nadj_batch);
3421  } else {
3422  v = std::vector<MX>(nadj_batch, MX(size_in(i)));
3423  }
3424  for (casadi_int d=0; d<nadj_batch; ++d) {
3425  if (asens[offset+d][i].is_empty(true)) {
3426  asens[offset+d][i] = v[d];
3427  } else {
3428  asens[offset+d][i] += v[d];
3429  }
3430  }
3431  }
3432  // Update offset
3433  offset += nadj_batch;
3434  }
3435  }
3436  }
virtual bool adjViaJac(casadi_int nadj) const
Calculate derivatives by multiplying the full Jacobian and multiplying.
std::pair< casadi_int, casadi_int > size_in(casadi_int ind) const
Input/output dimensions.
virtual void call_reverse(const std::vector< MX > &arg, const std::vector< MX > &res, const std::vector< std::vector< MX > > &aseed, std::vector< std::vector< MX > > &asens, bool always_inline, bool never_inline) const
Reverse mode, virtual functions overloaded in derived classes.
Function reverse(casadi_int nadj) const
Return function that calculates adjoint derivatives.
bool matching_res(const std::vector< M > &arg, casadi_int &npar) const
Check if output arguments that needs to be replaced.
virtual bool has_reverse(casadi_int nadj) const
Return function that calculates adjoint derivatives.
std::vector< std::vector< M > > replace_aseed(const std::vector< std::vector< M >> &aseed, casadi_int npar) const
Replace 0-by-0 reverse seeds.

References casadi::FunctionInternal::adjViaJac(), casadi::SharedObjectInternal::class_name(), casadi::FunctionInternal::enable_reverse_, casadi::FunctionInternal::has_derivative(), casadi::FunctionInternal::has_reverse(), casadi::FunctionInternal::jacobian(), casadi::FunctionInternal::matching_res(), casadi::FunctionInternal::max_num_dir_, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::replace_aseed(), casadi::FunctionInternal::reverse(), casadi::FunctionInternal::size2_in(), casadi::FunctionInternal::size_in(), and casadi::T.

Referenced by casadi::Rootfinder::ad_reverse(), casadi::MXFunction::ad_reverse(), casadi::Call::ad_reverse(), casadi::XFunction< DerivedType, MatType, NodeType >::call_reverse(), casadi::Scpgen::init(), and casadi::MX::reverse().

◆ call_reverse() [2/2]

void casadi::FunctionInternal::call_reverse ( const std::vector< SX > &  arg,
const std::vector< SX > &  res,
const std::vector< std::vector< SX > > &  aseed,
std::vector< std::vector< SX > > &  asens,
bool  always_inline,
bool  never_inline 
) const
virtualinherited

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

Definition at line 3451 of file function_internal.cpp.

3455  {
3456  casadi_assert(!(always_inline && never_inline), "Inconsistent options");
3457  if (aseed.empty()) { // Quick return if no seeds
3458  asens.clear();
3459  return;
3460  }
3461  casadi_error("'reverse' (SX) not defined for " + class_name());
3462  }

References casadi::SharedObjectInternal::class_name().

◆ callback()

int casadi::Nlpsol::callback ( NlpsolMemory m) const
inherited

Definition at line 1210 of file nlpsol.cpp.

1210  {
1211  // Quick return if no callback function
1212  if (fcallback_.is_null()) return 0;
1213  // Callback inputs
1214  std::fill_n(m->arg, fcallback_.n_in(), nullptr);
1215 
1216  auto *d_nlp = &m->d_nlp;
1217 
1218  m->arg[NLPSOL_X] = d_nlp->z;
1219  m->arg[NLPSOL_F] = &d_nlp->objective;
1220  m->arg[NLPSOL_G] = d_nlp->z + nx_;
1221  m->arg[NLPSOL_LAM_G] = d_nlp->lam + nx_;
1222  m->arg[NLPSOL_LAM_X] = d_nlp->lam;
1223 
1224  // Callback outputs
1225  std::fill_n(m->res, fcallback_.n_out(), nullptr);
1226  double ret = 0;
1227  m->res[0] = &ret;
1228 
1229  // Start timer
1230  m->fstats.at("callback_fun").tic();
1231  try {
1232  // Evaluate
1233  fcallback_(m->arg, m->res, m->iw, m->w, 0);
1234  } catch(KeyboardInterruptException& ex) {
1235  (void)ex; // unused
1236  throw;
1237  } catch(std::exception& ex) {
1238  print("WARNING: intermediate_callback error: %s\n", ex.what());
1240  }
1241 
1242  // User user interruption?
1243  if (static_cast<casadi_int>(ret)) return 1;
1244 
1245  // Stop timer
1246  m->fstats.at("callback_fun").toc();
1247 
1248  return 0;
1249  }
casadi_int n_out() const
Get the number of function outputs.
Definition: function.cpp:975
casadi_int n_in() const
Get the number of function inputs.
Definition: function.cpp:971
bool is_null() const
Is a null pointer?
bool iteration_callback_ignore_errors_
Options.
Definition: nlpsol_impl.hpp:95
Function fcallback_
callback function, executed at each iteration
Definition: nlpsol_impl.hpp:75
void print(const char *fmt,...) const
C-style formatted printing during evaluation.
@ NLPSOL_G
Constraints function at the optimal solution (ng x 1)
Definition: nlpsol.hpp:221
@ NLPSOL_X
Decision variables at the optimal solution (nx x 1)
Definition: nlpsol.hpp:217
@ NLPSOL_F
Cost function value at the optimal solution (1 x 1)
Definition: nlpsol.hpp:219
@ NLPSOL_LAM_G
Lagrange multipliers for bounds on G at the solution (ng x 1)
Definition: nlpsol.hpp:225
@ NLPSOL_LAM_X
Lagrange multipliers for bounds on X at the solution (nx x 1)
Definition: nlpsol.hpp:223

References casadi::OracleMemory::arg, casadi::NlpsolMemory::d_nlp, casadi::Nlpsol::fcallback_, casadi::ProtoFunctionMemory::fstats, casadi::GenericShared< Shared, Internal >::is_null(), casadi::Nlpsol::iteration_callback_ignore_errors_, casadi::OracleMemory::iw, casadi::Function::n_in(), casadi::Function::n_out(), casadi::NLPSOL_F, casadi::NLPSOL_G, casadi::NLPSOL_LAM_G, casadi::NLPSOL_LAM_X, casadi::NLPSOL_X, casadi::Nlpsol::nx_, casadi::ProtoFunction::print(), casadi::OracleMemory::res, casadi::OracleMemory::w, and casadi::CasadiException::what().

Referenced by casadi::Feasiblesqpmethod::solve(), casadi::Qrsqp::solve(), and casadi::Sqpmethod::solve().

◆ change_option()

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

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

Reimplemented from casadi::ProtoFunction.

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 443 of file function_internal.cpp.

444  {
445  if (option_name == "print_in") {
446  print_in_ = option_value;
447  } else if (option_name == "print_out") {
448  print_out_ = option_value;
449  } else if (option_name == "print_canonical") {
450  print_canonical_ = option_value;
451  } else if (option_name=="ad_weight") {
452  ad_weight_ = option_value;
453  } else if (option_name=="ad_weight_sp") {
454  ad_weight_sp_ = option_value;
455  } else if (option_name=="dump") {
456  dump_ = option_value;
457  } else if (option_name=="dump_in") {
458  dump_in_ = option_value;
459  } else if (option_name=="dump_out") {
460  dump_out_ = option_value;
461  } else if (option_name=="dump_dir") {
462  dump_dir_ = option_value.to_string();
463  } else if (option_name=="dump_format") {
464  dump_format_ = option_value.to_string();
465  } else {
466  // Option not found - continue to base classes
467  ProtoFunction::change_option(option_name, option_value);
468  }
469  }
virtual void change_option(const std::string &option_name, const GenericType &option_value)
Change option after object creation for debugging.

References casadi::FunctionInternal::ad_weight_, casadi::FunctionInternal::ad_weight_sp_, casadi::ProtoFunction::change_option(), casadi::FunctionInternal::dump_, casadi::FunctionInternal::dump_dir_, casadi::FunctionInternal::dump_format_, casadi::FunctionInternal::dump_in_, casadi::FunctionInternal::dump_out_, casadi::FunctionInternal::print_canonical_, casadi::FunctionInternal::print_in_, casadi::FunctionInternal::print_out_, and casadi::GenericType::to_string().

Referenced by casadi::FmuFunction::change_option(), casadi::MXFunction::change_option(), and casadi::SXFunction::change_option().

◆ check_arg()

template<typename M >
void casadi::FunctionInternal::check_arg ( const std::vector< M > &  arg,
casadi_int &  npar 
) const
inherited

Raises errors.

Parameters
npar[in]normal usage: 1, disallow pararallel calls: -1
[out]nparmax number of horizontal repetitions across all arguments (or -1)

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

Definition at line 1766 of file function_internal.hpp.

1766  {
1767  casadi_assert(arg.size()==n_in_, "Incorrect number of inputs: Expected "
1768  + str(n_in_) + ", got " + str(arg.size()));
1769  for (casadi_int i=0; i<n_in_; ++i) {
1770  if (!check_mat(arg[i].sparsity(), sparsity_in(i), npar)) {
1771  // Dimensions
1772  std::string d_arg = str(arg[i].size1()) + "-by-" + str(arg[i].size2());
1773  std::string d_in = str(size1_in(i)) + "-by-" + str(size2_in(i));
1774  std::string e = "Input " + str(i) + " (" + name_in_[i] + ") has mismatching shape. "
1775  "Got " + d_arg + ". Allowed dimensions, in general, are:\n"
1776  " - The input dimension N-by-M (here " + d_in + ")\n"
1777  " - A scalar, i.e. 1-by-1\n"
1778  " - M-by-N if N=1 or M=1 (i.e. a transposed vector)\n"
1779  " - N-by-M1 if K*M1=M for some K (argument repeated horizontally)\n";
1780  if (npar!=-1) {
1781  e += " - N-by-P*M, indicating evaluation with multiple arguments (P must be a "
1782  "multiple of " + str(npar) + " for consistency with previous inputs)";
1783  }
1784  casadi_error(e);
1785  }
1786  }
1787  }
casadi_int size1_in(casadi_int ind) const
Input/output dimensions.
const Sparsity & sparsity_in(casadi_int ind) const
Input/output sparsity.
static bool check_mat(const Sparsity &arg, const Sparsity &inp, casadi_int &npar)
std::vector< std::string > name_in_
Input and output scheme.
std::string str(const T &v)
String representation, any type.

References casadi::FunctionInternal::check_mat(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::size1_in(), casadi::FunctionInternal::size2_in(), casadi::FunctionInternal::sparsity_in(), and casadi::str().

Referenced by casadi::FunctionInternal::mapsum_mx(), and casadi::FunctionInternal::matching_arg().

◆ check_inputs()

void casadi::Nlpsol::check_inputs ( void *  mem) const
virtualinherited

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

Definition at line 702 of file nlpsol.cpp.

702  {
703  auto *m = static_cast<NlpsolMemory*>(mem);
704  auto *d_nlp = &m->d_nlp;
705 
706  // Skip check?
707  if (!inputs_check_) return;
708 
709  const double inf = std::numeric_limits<double>::infinity();
710 
711  // Number of equality constraints
712  casadi_int n_eq = 0;
713 
714  // Detect ill-posed problems (simple bounds)
715  for (casadi_int i=0; i<nx_; ++i) {
716  double lb = d_nlp->lbx ? d_nlp->lbx[i] : get_default_in(NLPSOL_LBX);
717  double ub = d_nlp->ubx ? d_nlp->ubx[i] : get_default_in(NLPSOL_UBX);
718  double x0 = d_nlp->x0 ? d_nlp->x0[i] : get_default_in(NLPSOL_X0);
719  casadi_assert(lb <= ub && lb!=inf && ub!=-inf,
720  "Ill-posed problem detected: "
721  "LBX[" + str(i) + "] <= UBX[" + str(i) + "] was violated. "
722  "Got LBX[" + str(i) + "]=" + str(lb) + " and UBX[" + str(i) + "] = " + str(ub) + ".");
723  if (warn_initial_bounds_ && (x0>ub || x0<lb)) {
724  casadi_warning("Nlpsol: The initial guess does not satisfy LBX and UBX. "
725  "Option 'warn_initial_bounds' controls this warning.");
726  break;
727  }
728  if (lb==ub) n_eq++;
729  }
730 
731  // Detect ill-posed problems (nonlinear bounds)
732  for (casadi_int i=0; i<nnz_out(NLPSOL_G); ++i) {
733  double lb = d_nlp->lbg ? d_nlp->lbg[i] : get_default_in(NLPSOL_LBG);
734  double ub = d_nlp->ubg ? d_nlp->ubg[i] : get_default_in(NLPSOL_UBG);
735  casadi_assert(lb <= ub && lb!=inf && ub!=-inf,
736  "Ill-posed problem detected: "
737  "LBG[" + str(i) + "] <= UBG[" + str(i) + "] was violated. "
738  "Got LBG[" + str(i) + "] = " + str(lb) + " and UBG[" + str(i) + "] = " + str(ub) + ".");
739  if (lb==ub) n_eq++;
740  }
741 
742  // Make sure enough degrees of freedom
743  using casadi::str; // Workaround, MingGW bug, cf. CasADi issue #890
744  if (n_eq> nx_) {
745  casadi_warning("NLP is overconstrained: There are " + str(n_eq) +
746  " equality constraints but only " + str(nx_) + " variables.");
747  }
748  }
bool inputs_check_
Errors are thrown if numerical values of inputs look bad.
bool warn_initial_bounds_
Options.
Definition: nlpsol_impl.hpp:94
double get_default_in(casadi_int ind) const override
Get default input value.
@ NLPSOL_UBX
Decision variables upper bound (nx x 1), default +inf.
Definition: nlpsol.hpp:202
@ NLPSOL_X0
Decision variables, initial guess (nx x 1)
Definition: nlpsol.hpp:196
@ NLPSOL_UBG
Constraints upper bound (ng x 1), default +inf.
Definition: nlpsol.hpp:206
@ NLPSOL_LBG
Constraints lower bound (ng x 1), default -inf.
Definition: nlpsol.hpp:204
@ NLPSOL_LBX
Decision variables lower bound (nx x 1), default -inf.
Definition: nlpsol.hpp:200
const double inf
infinity
Definition: calculus.hpp:50

References casadi::NlpsolMemory::d_nlp, casadi::Nlpsol::get_default_in(), casadi::inf, casadi::FunctionInternal::inputs_check_, casadi::NLPSOL_G, casadi::NLPSOL_LBG, casadi::NLPSOL_LBX, casadi::NLPSOL_UBG, casadi::NLPSOL_UBX, casadi::NLPSOL_X0, casadi::FunctionInternal::nnz_out(), casadi::Nlpsol::nx_, casadi::str(), and casadi::Nlpsol::warn_initial_bounds_.

Referenced by casadi::Nlpsol::eval(), casadi::AlpaqaInterface::set_work(), and casadi::SLEQPInterface::set_work().

◆ check_mat()

bool casadi::FunctionInternal::check_mat ( const Sparsity arg,
const Sparsity inp,
casadi_int &  npar 
)
staticinherited

Helper function

Parameters
npar[in]normal usage: 1, disallow pararallel calls: -1
npar[out]required number of parallel calls (or -1)

Definition at line 3649 of file function_internal.cpp.

3649  {
3650  // Matching dimensions
3651  if (arg.size()==inp.size()) return true;
3652  // Calling with a scalar - set all
3653  if (arg.is_scalar()) return true;
3654  // Vectors that are transposes of each other
3655  if (arg.is_vector() && inp.size()==std::make_pair(arg.size2(), arg.size1())) return true;
3656  // Horizontal repmat
3657  if (arg.size1()==inp.size1() && arg.size2()>0 && inp.size2()>0
3658  && inp.size2()%arg.size2()==0) return true;
3659  // Evaluate with multiple arguments
3660  if (npar!=-1 && arg.size1()==inp.size1() && arg.size2()>0 && inp.size2()>0
3661  && arg.size2()%(npar*inp.size2())==0) {
3662  npar *= arg.size2()/(npar*inp.size2());
3663  return true;
3664  }
3665  // Calling with empty matrix - set all to zero (after the structured branches above,
3666  // so that a 0-by-N argument can still be recognised as a parallel/repmat call)
3667  if (arg.is_empty()) return true;
3668  // No match
3669  return false;
3670  }

References casadi::Sparsity::is_empty(), casadi::Sparsity::is_scalar(), casadi::Sparsity::is_vector(), casadi::Sparsity::size(), casadi::Sparsity::size1(), and casadi::Sparsity::size2().

Referenced by casadi::FunctionInternal::check_arg(), casadi::FunctionInternal::check_res(), and casadi::FunctionInternal::mapsum_mx().

◆ check_mem_count()

virtual void casadi::ProtoFunction::check_mem_count ( casadi_int  n) const
inlinevirtualinherited

Purpose if to allow more helpful error messages

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

Reimplemented in casadi::FmuFunction.

Definition at line 179 of file function_internal.hpp.

179 { }

Referenced by casadi::ProtoFunction::checkout().

◆ check_res()

template<typename M >
void casadi::FunctionInternal::check_res ( const std::vector< M > &  res,
casadi_int &  npar 
) const
inherited

Raises errors.

Parameters
npar[in]normal usage: 1, disallow pararallel calls: -1
[out]nparmax number of horizontal repetitions across all arguments (or -1)

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

Definition at line 1790 of file function_internal.hpp.

1790  {
1791  casadi_assert(res.size()==n_out_, "Incorrect number of outputs: Expected "
1792  + str(n_out_) + ", got " + str(res.size()));
1793  for (casadi_int i=0; i<n_out_; ++i) {
1794  casadi_assert(check_mat(res[i].sparsity(), sparsity_out(i), npar),
1795  "Output " + str(i) + " (" + name_out_[i] + ") has mismatching shape. "
1796  "Expected " + str(size_out(i)) + ", got " + str(res[i].size()));
1797  }
1798  }
std::vector< std::string > name_out_

References casadi::FunctionInternal::check_mat(), casadi::FunctionInternal::n_out_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::size_out(), casadi::FunctionInternal::sparsity_out(), and casadi::str().

Referenced by casadi::FunctionInternal::matching_res().

◆ checkout()

int casadi::ProtoFunction::checkout ( ) const
inherited

Definition at line 3858 of file function_internal.cpp.

3858  {
3859 #ifdef CASADI_WITH_THREAD
3860  std::lock_guard<std::mutex> lock(mtx_);
3861 #endif //CASADI_WITH_THREAD
3862  if (unused_.empty()) {
3863  check_mem_count(mem_.size()+1);
3864  // Allocate a new memory object
3865  void* m = alloc_mem();
3866  mem_.push_back(m);
3867  if (init_mem(m)) {
3868  casadi_error("Failed to create or initialize memory object");
3869  }
3870  return static_cast<int>(mem_.size()) - 1;
3871  } else {
3872  // Use an unused memory object
3873  int m = unused_.top();
3874  unused_.pop();
3875  return m;
3876  }
3877  }
virtual int init_mem(void *mem) const
Initalize memory block.
virtual void * alloc_mem() const
Create memory block.
virtual void check_mem_count(casadi_int n) const
Check for validatity of memory object count.

References casadi::ProtoFunction::alloc_mem(), casadi::ProtoFunction::check_mem_count(), and casadi::ProtoFunction::init_mem().

Referenced by casadi::FunctionInternal::codegen_meta(), casadi::ProtoFunction::finalize(), and casadi::Sqpmethod::init_mem().

◆ class_name()

std::string casadi::Blocksqp::class_name ( ) const
inlineoverridevirtual

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

Reimplemented from casadi::Nlpsol.

Definition at line 160 of file blocksqp.hpp.

160 { return "Blocksqp";}

◆ clear_mem()

void casadi::ProtoFunction::clear_mem ( )
inherited

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

Definition at line 3746 of file function_internal.cpp.

3746  {
3747  for (auto&& i : mem_) {
3748  if (i!=nullptr) free_mem(i);
3749  }
3750  mem_.clear();
3751  }
virtual void free_mem(void *mem) const
Free memory block.

References casadi::ProtoFunction::free_mem().

Referenced by casadi::AlpaqaInterface::~AlpaqaInterface(), casadi::AmplInterface::~AmplInterface(), casadi::BlazingSplineFunction::~BlazingSplineFunction(), ~Blocksqp(), casadi::BonminInterface::~BonminInterface(), casadi::BSplineInterpolant::~BSplineInterpolant(), casadi::CallbackInternal::~CallbackInternal(), casadi::CbcInterface::~CbcInterface(), casadi::ClarabelInterface::~ClarabelInterface(), casadi::ClpInterface::~ClpInterface(), casadi::CplexInterface::~CplexInterface(), casadi::CsparseInterface::~CsparseInterface(), casadi::CvodesInterface::~CvodesInterface(), casadi::DaqpInterface::~DaqpInterface(), casadi::External::~External(), casadi::FastNewton::~FastNewton(), casadi::FatropConicInterface::~FatropConicInterface(), casadi::FatropInterface::~FatropInterface(), casadi::Feasiblesqpmethod::~Feasiblesqpmethod(), casadi::FiniteDiff::~FiniteDiff(), casadi::FixedStepIntegrator::~FixedStepIntegrator(), casadi::FmuFunction::~FmuFunction(), casadi::GurobiInterface::~GurobiInterface(), casadi::HighsInterface::~HighsInterface(), casadi::HpipmInterface::~HpipmInterface(), casadi::HpmpcInterface::~HpmpcInterface(), casadi::IdasInterface::~IdasInterface(), casadi::ImplicitToNlp::~ImplicitToNlp(), casadi::IpoptInterface::~IpoptInterface(), casadi::Ipqp::~Ipqp(), casadi::JitFunction::~JitFunction(), casadi::KinsolInterface::~KinsolInterface(), casadi::KnitroInterface::~KnitroInterface(), casadi::LapackLu::~LapackLu(), casadi::LapackQr::~LapackQr(), casadi::LinearInterpolant::~LinearInterpolant(), casadi::LinearInterpolantJac::~LinearInterpolantJac(), casadi::LinsolLdl::~LinsolLdl(), casadi::LinsolQr::~LinsolQr(), casadi::LinsolTridiag::~LinsolTridiag(), casadi::Lsqr::~Lsqr(), casadi::Ma27Interface::~Ma27Interface(), casadi::MadmpecInterface::~MadmpecInterface(), casadi::MadnlpInterface::~MadnlpInterface(), casadi::Map::~Map(), casadi::MapSum::~MapSum(), casadi::MosekInterface::~MosekInterface(), casadi::MumpsInterface::~MumpsInterface(), casadi::MXFunction::~MXFunction(), casadi::Newton::~Newton(), casadi::Nlpsol::~Nlpsol(), casadi::OmpMap::~OmpMap(), casadi::OnnxFunction::~OnnxFunction(), casadi::OnnxRuntimeInterface::~OnnxRuntimeInterface(), casadi::OoqpInterface::~OoqpInterface(), casadi::OsqpInterface::~OsqpInterface(), casadi::PiqpInterface::~PiqpInterface(), casadi::ProxqpInterface::~ProxqpInterface(), casadi::QpoasesInterface::~QpoasesInterface(), casadi::QpToNlp::~QpToNlp(), casadi::Qrqp::~Qrqp(), casadi::Qrsqp::~Qrsqp(), casadi::Scpgen::~Scpgen(), casadi::SLEQPInterface::~SLEQPInterface(), casadi::SlicotDple::~SlicotDple(), casadi::SlicotExpm::~SlicotExpm(), casadi::SnoptInterface::~SnoptInterface(), casadi::Sqpmethod::~Sqpmethod(), casadi::SuperscsInterface::~SuperscsInterface(), casadi::Switch::~Switch(), casadi::SXFunction::~SXFunction(), casadi::SymbolicQr::~SymbolicQr(), casadi::ThreadMap::~ThreadMap(), casadi::UnoInterface::~UnoInterface(), casadi::WorhpInterface::~WorhpInterface(), and casadi::XpressInterface::~XpressInterface().

◆ codegen()

void casadi::FunctionInternal::codegen ( CodeGenerator g,
const std::string &  fname 
) const
inherited

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

Definition at line 2452 of file function_internal.cpp.

2452  {
2453  // Define function
2454  g << "/* " << definition() << " */\n";
2455  g << "static " << signature(fname) << " {\n";
2456 
2457  // Reset local variables, flush buffer
2458  g.flush(g.body);
2459 
2460  g.scope_enter();
2461 
2462  if (dump_in_ || dump_out_) {
2463  Function F = shared_from_this<Function>();
2464  std::string cg_name = codegen_name(g, false);
2465  std::string dump_counter = g.shorthand(cg_name + "_dump_counter");
2466  g.auxiliaries << "static int " << dump_counter << " = 0;\n";
2467  if (g.thread_safe()) {
2468  g.define_local_mutex(F, cg_name + "_dump_mutex");
2469  std::string dump_mutex = g.local_mutex(F, cg_name + "_dump_mutex");
2470  g << "CASADI_MUTEX_LOCK(&" << dump_mutex << ");\n";
2471  g << "int dump_id_local = " << dump_counter << "++;\n";
2472  g << "CASADI_MUTEX_UNLOCK(&" << dump_mutex << ");\n";
2473  } else {
2474  g << "int dump_id_local = " << dump_counter << "++;\n";
2475  }
2476  }
2477 
2478  if (dump_in_) g.generate_dump(shared_from_this<Function>(), "arg", true);
2479  if (print_in_) g.generate_print(shared_from_this<Function>(), "arg", true);
2480 
2481  // Generate function body (to buffer)
2482  codegen_body(g);
2483 
2484  if (dump_out_) g.generate_dump(shared_from_this<Function>(), "res", false);
2485  if (print_out_) g.generate_print(shared_from_this<Function>(), "res", false);
2486 
2487  g.scope_exit();
2488 
2489  // Finalize the function
2490  g << "return 0;\n";
2491  g << "}\n\n";
2492 
2493  // Flush to function body
2494  g.flush(g.body);
2495  }
std::string definition() const
Get function signature: name:(inputs)->(outputs)
virtual std::string codegen_name(const CodeGenerator &g, bool ns=true) const
Get name in codegen.
virtual void codegen_body(CodeGenerator &g) const
Generate code for the function body.
std::string signature(const std::string &fname) const
Code generate the function.

References casadi::CodeGenerator::auxiliaries, casadi::CodeGenerator::body, casadi::FunctionInternal::codegen_body(), casadi::FunctionInternal::codegen_name(), casadi::CodeGenerator::define_local_mutex(), casadi::FunctionInternal::definition(), casadi::FunctionInternal::dump_in_, casadi::FunctionInternal::dump_out_, casadi::CodeGenerator::flush(), casadi::CodeGenerator::generate_dump(), casadi::CodeGenerator::generate_print(), casadi::CodeGenerator::local_mutex(), casadi::FunctionInternal::print_in_, casadi::FunctionInternal::print_out_, casadi::CodeGenerator::scope_enter(), casadi::CodeGenerator::scope_exit(), casadi::CodeGenerator::shorthand(), casadi::FunctionInternal::signature(), and casadi::CodeGenerator::thread_safe().

Referenced by casadi::CodeGenerator::add_dependency().

◆ codegen_alloc_mem()

void casadi::FunctionInternal::codegen_alloc_mem ( CodeGenerator g) const
virtualinherited

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

Reimplemented in casadi::External.

Definition at line 2596 of file function_internal.cpp.

2596  {
2597  bool needs_mem = codegen_needs_mem();
2598  if (needs_mem) {
2599  std::string name = codegen_name(g, false);
2600  std::string mem_counter = g.shorthand(name + "_mem_counter");
2601  g << "return " + mem_counter + "++;\n";
2602  }
2603  }
virtual bool codegen_needs_mem() const
Is thread-local memory object needed?

References casadi::FunctionInternal::codegen_name(), casadi::FunctionInternal::codegen_needs_mem(), and casadi::CodeGenerator::shorthand().

Referenced by casadi::CodeGenerator::add_dependency().

◆ codegen_body()

void casadi::FunctionInternal::codegen_body ( CodeGenerator g) const
virtualinherited

◆ codegen_body_enter()

void casadi::Nlpsol::codegen_body_enter ( CodeGenerator g) const
overridevirtualinherited

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

Reimplemented from casadi::OracleFunction.

Definition at line 1268 of file nlpsol.cpp.

1268  {
1270  g.local("d_nlp", "struct casadi_nlpsol_data");
1271  g.local("p_nlp", "struct casadi_nlpsol_prob");
1272  codegen_setup_constants(g, "d_nlp", "p_nlp", "d_oracle");
1273  codegen_setup_per_call(g, "d_nlp");
1274  }
void codegen_setup_per_call(CodeGenerator &g, const std::string &d_nlp) const
Definition: nlpsol.cpp:1313
void codegen_setup_constants(CodeGenerator &g, const std::string &d_nlp, const std::string &p_nlp, const std::string &d_oracle) const
Definition: nlpsol.cpp:1281
virtual void codegen_body_enter(CodeGenerator &g) const
Generate code for the function body.

References casadi::OracleFunction::codegen_body_enter(), casadi::Nlpsol::codegen_setup_constants(), casadi::Nlpsol::codegen_setup_per_call(), and casadi::CodeGenerator::local().

Referenced by casadi::MadmpecInterface::codegen_body(), casadi::FatropInterface::codegen_body(), casadi::IpoptInterface::codegen_body(), casadi::MadnlpInterface::codegen_body(), casadi::Feasiblesqpmethod::codegen_body(), and casadi::Sqpmethod::codegen_body().

◆ codegen_body_exit()

void casadi::Nlpsol::codegen_body_exit ( CodeGenerator g) const
overridevirtualinherited

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

Reimplemented from casadi::OracleFunction.

Definition at line 1368 of file nlpsol.cpp.

1368  {
1369  codegen_post_solve(g, "d_nlp");
1371  }
void codegen_post_solve(CodeGenerator &g, const std::string &d_nlp) const
Definition: nlpsol.cpp:1373
virtual void codegen_body_exit(CodeGenerator &g) const
Generate code for the function body.

References casadi::OracleFunction::codegen_body_exit(), and casadi::Nlpsol::codegen_post_solve().

Referenced by casadi::MadmpecInterface::codegen_body(), casadi::FatropInterface::codegen_body(), casadi::IpoptInterface::codegen_body(), casadi::MadnlpInterface::codegen_body(), and casadi::Sqpmethod::codegen_body().

◆ codegen_checkout()

void casadi::FunctionInternal::codegen_checkout ( CodeGenerator g) const
virtualinherited

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

Reimplemented in casadi::External.

Definition at line 2605 of file function_internal.cpp.

2605  {
2606  std::string name = codegen_name(g, false);
2607  std::string stack_counter = g.shorthand(name + "_unused_stack_counter");
2608  std::string stack = g.shorthand(name + "_unused_stack");
2609  std::string mem_counter = g.shorthand(name + "_mem_counter");
2610  std::string mem_array = g.shorthand(name + "_mem");
2611  std::string alloc_mem = g.shorthand(name + "_alloc_mem");
2612  std::string init_mem = g.shorthand(name + "_init_mem");
2613 
2614 
2615  g.auxiliaries << "static int " << mem_counter << " = 0;\n";
2616  g.auxiliaries << "static int " << stack_counter << " = -1;\n";
2617  g.auxiliaries << "static int " << stack << "[CASADI_MAX_NUM_THREADS];\n";
2618  g.auxiliaries << "static " << codegen_mem_type() <<
2619  " " << mem_array << "[CASADI_MAX_NUM_THREADS];\n\n";
2620 
2621  if (g.thread_safe()) {
2622  Function F = shared_from_this<Function>();
2623  g.define_local_mutex(F, name + "_mem_mutex");
2624  std::string mem_mutex = g.local_mutex(F, name + "_mem_mutex");
2625  g << "CASADI_MUTEX_LOCK(&" << mem_mutex << ");\n";
2626  g.scope_add_cleanup("CASADI_MUTEX_UNLOCK(&" + mem_mutex + ");\n");
2627  }
2628 
2629  g.local("mid", "int");
2630 
2631  g << "if (" << stack_counter << ">=0) {\n";
2632  g.scope_return(stack + "[" + stack_counter + "--]");
2633  g << "} else {\n";
2634  g << "if (" << mem_counter << "==CASADI_MAX_NUM_THREADS) {\n";
2635  g.scope_return("-1");
2636  g << "}\n";
2637  g << "mid = " << alloc_mem << "();\n";
2638  g << "if (mid<0) {\n";
2639  g.scope_return("-1");
2640  g << "}\n";
2641  g << "if (" << init_mem << "(mid)) {\n";
2642  g.scope_return("-1");
2643  g << "}\n";
2644  g.scope_return("mid");
2645  g << "}\n";
2646  }
virtual std::string codegen_mem_type() const
Thread-local memory object type.
void * alloc_mem() const override
Create memory block.

References casadi::FunctionInternal::alloc_mem(), casadi::CodeGenerator::auxiliaries, casadi::FunctionInternal::codegen_mem_type(), casadi::FunctionInternal::codegen_name(), casadi::CodeGenerator::define_local_mutex(), casadi::ProtoFunction::init_mem(), casadi::CodeGenerator::local(), casadi::CodeGenerator::local_mutex(), casadi::CodeGenerator::scope_add_cleanup(), casadi::CodeGenerator::scope_return(), casadi::CodeGenerator::shorthand(), and casadi::CodeGenerator::thread_safe().

Referenced by casadi::CodeGenerator::add_dependency().

◆ codegen_declarations()

void casadi::Nlpsol::codegen_declarations ( CodeGenerator g) const
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Reimplemented in casadi::Sqpmethod, casadi::Feasiblesqpmethod, casadi::UnoInterface, casadi::MadnlpInterface, casadi::IpoptInterface, casadi::FatropInterface, and casadi::MadmpecInterface.

Definition at line 1348 of file nlpsol.cpp.

1348  {
1349  g.add_auxiliary(CodeGenerator::AUX_FILL);
1350  g.add_auxiliary(CodeGenerator::AUX_INF);
1351  if (calc_f_ || calc_g_ || calc_lam_x_ || calc_lam_p_)
1352  g.add_dependency(get_function("nlp_grad"));
1353 
1354  if (detect_simple_bounds_is_simple_.size()) {
1355  g.add_dependency(detect_simple_bounds_parts_);
1356  std::string w =
1357  g.shorthand(g.wrapper(detect_simple_bounds_parts_, "detect_simple_bounds_wrapper"));
1358 
1359  g << "int " << w
1360  << "(const casadi_real** arg, casadi_real** res, "
1361  << "casadi_int* iw, casadi_real* w, void* callback_data) {\n";
1362  std::string flag = g(detect_simple_bounds_parts_, "arg", "res", "iw", "w");
1363  g << "return " + flag + ";\n";
1364  g << "}\n";
1365  }
1366  }
bool calc_lam_p_
Options.
Definition: nlpsol_impl.hpp:97
Function detect_simple_bounds_parts_
Definition: nlpsol_impl.hpp:85
bool calc_f_
Options.
Definition: nlpsol_impl.hpp:97
bool calc_g_
Options.
Definition: nlpsol_impl.hpp:97
std::vector< char > detect_simple_bounds_is_simple_
Definition: nlpsol_impl.hpp:84
bool calc_lam_x_
Options.
Definition: nlpsol_impl.hpp:97

References casadi::CodeGenerator::add_auxiliary(), casadi::CodeGenerator::add_dependency(), casadi::CodeGenerator::AUX_FILL, casadi::CodeGenerator::AUX_INF, casadi::Nlpsol::calc_f_, casadi::Nlpsol::calc_g_, casadi::Nlpsol::calc_lam_p_, casadi::Nlpsol::calc_lam_x_, casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::Nlpsol::detect_simple_bounds_parts_, casadi::OracleFunction::get_function(), casadi::CodeGenerator::shorthand(), and casadi::CodeGenerator::wrapper().

Referenced by casadi::MadmpecInterface::codegen_declarations(), casadi::FatropInterface::codegen_declarations(), casadi::IpoptInterface::codegen_declarations(), casadi::MadnlpInterface::codegen_declarations(), casadi::UnoInterface::codegen_declarations(), casadi::Feasiblesqpmethod::codegen_declarations(), and casadi::Sqpmethod::codegen_declarations().

◆ codegen_decref()

void casadi::FunctionInternal::codegen_decref ( CodeGenerator g) const
virtualinherited

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

Reimplemented in casadi::MXFunction, and casadi::External.

Definition at line 2551 of file function_internal.cpp.

2551  {
2552 
2553  // Treat dependent functions
2554  std::set<void*> added;
2555  Function F = shared_from_this<Function>();
2556  for (const Function& f : F.find_functions(0)) {
2557  if (f->has_refcount_in_deps_) {
2558  std::string cg_name = f->codegen_name(g, false);
2559  auto i = added.insert(f.get());
2560  if (i.second) { // prevent duplicate calls
2561  std::string decref = g.shorthand(cg_name + "_decref");
2562  g << decref << "();\n";
2563  }
2564  }
2565  }
2566 
2567  if (has_refcount_) {
2568  std::string name = codegen_name(g, false);
2569  std::string ref_counter = g.shorthand(name + "_ref_counter");
2570  std::string mem_counter = g.shorthand(name + "_mem_counter");
2571  std::string free_mem = g.shorthand(name + "_free_mem");
2572  g << ref_counter << "--;\n";
2573  g << "if (" << ref_counter << "==0) {\n";
2574  if (codegen_needs_mem()) {
2575  g << "while (" << mem_counter << ">0) {\n";
2576  g << free_mem << "(--" << mem_counter << ");\n";
2577  g << "}\n";
2578  }
2579  if (g.thread_safe()) {
2580  Function F = shared_from_this<Function>();
2581  for (const auto& m : g.local_mutexes(F)) {
2582  std::string mtx = g.local_mutex(F, m);
2583  g << "#if CASADI_MUTEX_USE_STATIC_INIT == 0\n";
2584  g << "CASADI_MUTEX_DESTROY(&" << mtx << ");\n";
2585  g << "#endif\n";
2586  }
2587  }
2588  g << "}\n";
2589  }
2590  }
bool has_refcount_
Reference counting in codegen?
void free_mem(void *mem) const override
Free memory block.

References casadi::FunctionInternal::codegen_name(), casadi::FunctionInternal::codegen_needs_mem(), casadi::Function::find_functions(), casadi::FunctionInternal::free_mem(), casadi::FunctionInternal::has_refcount_, casadi::CodeGenerator::local_mutex(), casadi::CodeGenerator::local_mutexes(), casadi::CodeGenerator::shorthand(), and casadi::CodeGenerator::thread_safe().

Referenced by casadi::CodeGenerator::add_dependency(), and casadi::MXFunction::codegen_decref().

◆ codegen_free_mem()

virtual void casadi::FunctionInternal::codegen_free_mem ( CodeGenerator g) const
inlinevirtualinherited

◆ codegen_incref()

void casadi::FunctionInternal::codegen_incref ( CodeGenerator g) const
virtualinherited

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

Reimplemented in casadi::MXFunction, and casadi::External.

Definition at line 2518 of file function_internal.cpp.

2518  {
2519  if (has_refcount_) {
2520  std::string name = codegen_name(g, false);
2521  std::string ref_counter = g.shorthand(name + "_ref_counter");
2522  g.auxiliaries << "static int " << ref_counter << " = 0;\n";
2523 
2524  Function F = shared_from_this<Function>();
2525  if (g.thread_safe()) {
2526  for (const auto& m : g.local_mutexes(F)) {
2527  std::string mtx = g.local_mutex(F, m);
2528  g << "#if CASADI_MUTEX_USE_STATIC_INIT == 0\n";
2529  g << "if (" << ref_counter << "==0) CASADI_MUTEX_INIT(&" << mtx << ");\n";
2530  g << "#endif\n";
2531  }
2532  }
2533  g << ref_counter << "++;\n";
2534  }
2535 
2536  // Treat dependent functions
2537  std::set<void*> added;
2538  Function F = shared_from_this<Function>();
2539  for (const Function& f : F.find_functions(0)) {
2540  if (f->has_refcount_in_deps_) {
2541  std::string cg_name = f->codegen_name(g, false);
2542  auto i = added.insert(f.get());
2543  if (i.second) { // prevent duplicate calls
2544  std::string incref = g.shorthand(cg_name + "_incref");
2545  g << incref << "();\n";
2546  }
2547  }
2548  }
2549  }

References casadi::CodeGenerator::auxiliaries, casadi::FunctionInternal::codegen_name(), casadi::Function::find_functions(), casadi::FunctionInternal::has_refcount_, casadi::CodeGenerator::local_mutex(), casadi::CodeGenerator::local_mutexes(), casadi::CodeGenerator::shorthand(), and casadi::CodeGenerator::thread_safe().

Referenced by casadi::CodeGenerator::add_dependency(), and casadi::MXFunction::codegen_incref().

◆ codegen_init_mem()

void casadi::FunctionInternal::codegen_init_mem ( CodeGenerator g) const
virtualinherited

◆ codegen_mem()

std::string casadi::FunctionInternal::codegen_mem ( CodeGenerator g,
const std::string &  index = "mem" 
) const
inherited

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

Definition at line 2993 of file function_internal.cpp.

2993  {
2994  std::string name = codegen_name(g, false);
2995  std::string mem_array = g.shorthand(name + "_mem");
2996  return mem_array+"[" + index + "]";
2997  }

References casadi::FunctionInternal::codegen_name(), and casadi::CodeGenerator::shorthand().

Referenced by casadi::MadmpecInterface::codegen_body(), casadi::ClarabelInterface::codegen_body(), casadi::DaqpInterface::codegen_body(), casadi::FatropInterface::codegen_body(), casadi::HighsInterface::codegen_body(), casadi::IpoptInterface::codegen_body(), casadi::MadnlpInterface::codegen_body(), casadi::MosekInterface::codegen_body(), casadi::OsqpInterface::codegen_body(), casadi::UnoInterface::codegen_body(), casadi::XpressInterface::codegen_body(), casadi::Sqpmethod::codegen_body(), casadi::MadmpecInterface::codegen_free_mem(), casadi::ClarabelInterface::codegen_free_mem(), casadi::DaqpInterface::codegen_free_mem(), casadi::FatropInterface::codegen_free_mem(), casadi::HighsInterface::codegen_free_mem(), casadi::IpoptInterface::codegen_free_mem(), casadi::MadnlpInterface::codegen_free_mem(), casadi::MosekInterface::codegen_free_mem(), casadi::OsqpInterface::codegen_free_mem(), casadi::UnoInterface::codegen_free_mem(), casadi::XpressInterface::codegen_free_mem(), casadi::MadmpecInterface::codegen_init_mem(), casadi::ClarabelInterface::codegen_init_mem(), casadi::DaqpInterface::codegen_init_mem(), casadi::FatropInterface::codegen_init_mem(), casadi::HighsInterface::codegen_init_mem(), casadi::IpoptInterface::codegen_init_mem(), casadi::MadnlpInterface::codegen_init_mem(), casadi::MosekInterface::codegen_init_mem(), casadi::OsqpInterface::codegen_init_mem(), casadi::UnoInterface::codegen_init_mem(), casadi::XpressInterface::codegen_init_mem(), and casadi::MadmpecInterface::codegen_options().

◆ codegen_mem_is_opaque()

virtual bool casadi::FunctionInternal::codegen_mem_is_opaque ( ) const
inlinevirtualinherited

without a need for alloc_mem, init_mem, free_mem?

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

Reimplemented in casadi::External.

Definition at line 932 of file function_internal.hpp.

932 { return false; }

Referenced by casadi::CodeGenerator::add_dependency().

◆ codegen_mem_type()

virtual std::string casadi::FunctionInternal::codegen_mem_type ( ) const
inlinevirtualinherited

◆ codegen_meta()

void casadi::FunctionInternal::codegen_meta ( CodeGenerator g) const
inherited

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

Definition at line 2668 of file function_internal.cpp.

2668  {
2669  bool needs_mem = codegen_needs_mem();
2670  std::string name = codegen_name(g, false);
2671 
2672  // Checkout/release routines
2673  g << g.declare("int " + name_ + "_checkout(void)") << " {\n";
2674  if (needs_mem) {
2675  std::string checkout = g.shorthand(name + "_checkout");
2676  g << "return " << checkout << "();\n";
2677  } else {
2678  g << "return 0;\n";
2679  }
2680  g << "}\n\n";
2681 
2682  if (needs_mem) {
2683  g << g.declare("void " + name_ + "_release(int mem)") << " {\n";
2684  std::string release = g.shorthand(name + "_release");
2685  g << release << "(mem);\n";
2686  } else {
2687  g << g.declare("void " + name_ + "_release(int mem)") << " {\n";
2688  }
2689  g << "}\n\n";
2690 
2691  // Reference counter routines
2692  g << g.declare("void " + name_ + "_incref(void)") << " {\n";
2693  if (has_refcount_in_deps_) {
2694  std::string incref = g.shorthand(name + "_incref");
2695  g << incref << "();\n";
2696  }
2697  g << "}\n\n"
2698  << g.declare("void " + name_ + "_decref(void)") << " {\n";
2699  if (has_refcount_in_deps_) {
2700  std::string decref = g.shorthand(name + "_decref");
2701  g << decref << "();\n";
2702  }
2703  g << "}\n\n";
2704 
2705  // Number of inputs and outptus
2706  g << g.declare("casadi_int " + name_ + "_n_in(void)")
2707  << " { return " << n_in_ << ";}\n\n"
2708  << g.declare("casadi_int " + name_ + "_n_out(void)")
2709  << " { return " << n_out_ << ";}\n\n";
2710 
2711  // Default inputs
2712  g << g.declare("casadi_real " + name_ + "_default_in(casadi_int i)") << " {\n"
2713  << "switch (i) {\n";
2714  for (casadi_int i=0; i<n_in_; ++i) {
2715  double def = get_default_in(i);
2716  if (def!=0) g << "case " << i << ": return " << g.constant(def) << ";\n";
2717  }
2718  g << "default: return 0;\n}\n"
2719  << "}\n\n";
2720 
2721  // Input names
2722  g << g.declare("const char* " + name_ + "_name_in(casadi_int i)") << " {\n"
2723  << "switch (i) {\n";
2724  for (casadi_int i=0; i<n_in_; ++i) {
2725  g << "case " << i << ": return \"" << name_in_[i] << "\";\n";
2726  }
2727  g << "default: return 0;\n}\n"
2728  << "}\n\n";
2729 
2730  // Output names
2731  g << g.declare("const char* " + name_ + "_name_out(casadi_int i)") << " {\n"
2732  << "switch (i) {\n";
2733  for (casadi_int i=0; i<n_out_; ++i) {
2734  g << "case " << i << ": return \"" << name_out_[i] << "\";\n";
2735  }
2736  g << "default: return 0;\n}\n"
2737  << "}\n\n";
2738 
2739  // Codegen sparsities
2740  codegen_sparsities(g);
2741 
2742  // Function that returns work vector lengths
2743  g << g.declare(
2744  "int " + name_ + "_work(casadi_int *sz_arg, casadi_int* sz_res, "
2745  "casadi_int *sz_iw, casadi_int *sz_w)")
2746  << " {\n"
2747  << "if (sz_arg) *sz_arg = " << codegen_sz_arg(g) << ";\n"
2748  << "if (sz_res) *sz_res = " << codegen_sz_res(g) << ";\n"
2749  << "if (sz_iw) *sz_iw = " << codegen_sz_iw(g) << ";\n"
2750  << "if (sz_w) *sz_w = " << codegen_sz_w(g) << ";\n"
2751  << "return 0;\n"
2752  << "}\n\n";
2753 
2754  // Function that returns work vector lengths in bytes
2755  g << g.declare(
2756  "int " + name_ + "_work_bytes(casadi_int *sz_arg, casadi_int* sz_res, "
2757  "casadi_int *sz_iw, casadi_int *sz_w)")
2758  << " {\n"
2759  << "if (sz_arg) *sz_arg = " << codegen_sz_arg(g) << "*sizeof(const casadi_real*);\n"
2760  << "if (sz_res) *sz_res = " << codegen_sz_res(g) << "*sizeof(casadi_real*);\n"
2761  << "if (sz_iw) *sz_iw = " << codegen_sz_iw(g) << "*sizeof(casadi_int);\n"
2762  << "if (sz_w) *sz_w = " << codegen_sz_w(g) << "*sizeof(casadi_real);\n"
2763  << "return 0;\n"
2764  << "}\n\n";
2765 
2766  // Also add to header file to allow getting
2767  if (g.with_header) {
2768  g.header
2769  << "#define " << name_ << "_SZ_ARG " << codegen_sz_arg(g) << "\n"
2770  << "#define " << name_ << "_SZ_RES " << codegen_sz_res(g) << "\n"
2771  << "#define " << name_ << "_SZ_IW " << codegen_sz_iw(g) << "\n"
2772  << "#define " << name_ << "_SZ_W " << codegen_sz_w(g) << "\n";
2773  }
2774 
2775  // Which inputs are differentiable
2776  if (!all(is_diff_in_)) {
2777  g << g.declare("int " + name_ + "_diff_in(casadi_int i)") << " {\n"
2778  << "switch (i) {\n";
2779  for (casadi_int i=0; i<n_in_; ++i) {
2780  g << "case " << i << ": return " << is_diff_in_[i] << ";\n";
2781  }
2782  g << "default: return -1;\n}\n"
2783  << "}\n\n";
2784  }
2785 
2786  // Which outputs are differentiable
2787  if (!all(is_diff_out_)) {
2788  g << g.declare("int " + name_ + "_diff_out(casadi_int i)") << " {\n"
2789  << "switch (i) {\n";
2790  for (casadi_int i=0; i<n_out_; ++i) {
2791  g << "case " << i << ": return " << is_diff_out_[i] << ";\n";
2792  }
2793  g << "default: return -1;\n}\n"
2794  << "}\n\n";
2795  }
2796 
2797  // Generate mex gateway for the function
2798  if (g.mex) {
2799  // Begin conditional compilation
2800  g << "#ifdef MATLAB_MEX_FILE\n";
2801 
2802  // Declare wrapper
2803  g << "void mex_" << name_
2804  << "(int resc, mxArray *resv[], int argc, const mxArray *argv[]) {\n"
2805  << "casadi_int i;\n";
2806  g << "int mem;\n";
2807  // Work vectors, including input and output buffers
2808  casadi_int i_nnz = nnz_in(), o_nnz = nnz_out();
2809  size_t sz_w = this->sz_w();
2810  for (casadi_int i=0; i<n_in_; ++i) {
2811  const Sparsity& s = sparsity_in_[i];
2812  sz_w = std::max(sz_w, static_cast<size_t>(s.size1())); // To be able to copy a column
2813  sz_w = std::max(sz_w, static_cast<size_t>(s.size2())); // To be able to copy a row
2814  }
2815  sz_w += i_nnz + o_nnz;
2816  g << CodeGenerator::array("casadi_real", "w", sz_w);
2817  g << CodeGenerator::array("casadi_int", "iw", sz_iw());
2818  std::string fw = "w+" + str(i_nnz + o_nnz);
2819 
2820  // Copy inputs to buffers
2821  casadi_int offset=0;
2822  g << CodeGenerator::array("const casadi_real*", "arg", sz_arg(), "{0}");
2823 
2824  // Allocate output buffers
2825  g << "casadi_real* res[" << sz_res() << "] = {0};\n";
2826 
2827  // Check arguments
2828  g << "if (argc>" << n_in_ << ") mexErrMsgIdAndTxt(\"Casadi:RuntimeError\","
2829  << "\"Evaluation of \\\"" << name_ << "\\\" failed. Too many input arguments "
2830  << "(%d, max " << n_in_ << ")\", argc);\n";
2831 
2832  g << "if (resc>" << n_out_ << ") mexErrMsgIdAndTxt(\"Casadi:RuntimeError\","
2833  << "\"Evaluation of \\\"" << name_ << "\\\" failed. "
2834  << "Too many output arguments (%d, max " << n_out_ << ")\", resc);\n";
2835 
2836  for (casadi_int i=0; i<n_in_; ++i) {
2837  std::string p = "argv[" + str(i) + "]";
2838  g << "if (--argc>=0) arg[" << i << "] = "
2839  << g.from_mex(p, "w", offset, sparsity_in_[i], fw) << "\n";
2840  offset += nnz_in(i);
2841  }
2842 
2843  for (casadi_int i=0; i<n_out_; ++i) {
2844  if (i==0) {
2845  // if i==0, always store output (possibly ans output)
2846  g << "--resc;\n";
2847  } else {
2848  // Store output, if it exists
2849  g << "if (--resc>=0) ";
2850  }
2851  // Create and get pointer
2852  g << g.res(i) << " = w+" << str(offset) << ";\n";
2853  offset += nnz_out(i);
2854  }
2855  g << name_ << "_incref();\n";
2856  g << "mem = " << name_ << "_checkout();\n";
2857 
2858  // Call the function
2859  g << "i = " << name_ << "(arg, res, iw, " << fw << ", mem);\n"
2860  << "if (i) mexErrMsgIdAndTxt(\"Casadi:RuntimeError\",\"Evaluation of \\\"" << name_
2861  << "\\\" failed.\");\n";
2862  g << name_ << "_release(mem);\n";
2863  g << name_ << "_decref();\n";
2864 
2865  // Save results
2866  for (casadi_int i=0; i<n_out_; ++i) {
2867  g << "if (" << g.res(i) << ") resv[" << i << "] = "
2868  << g.to_mex(sparsity_out_[i], g.res(i)) << "\n";
2869  }
2870 
2871  // End conditional compilation and function
2872  g << "}\n"
2873  << "#endif\n\n";
2874  }
2875 
2876  if (g.main) {
2877  // Declare wrapper
2878  g << "casadi_int main_" << name_ << "(casadi_int argc, char* argv[]) {\n";
2879 
2880  g << "casadi_int j;\n";
2881  g << "casadi_real* a;\n";
2882  g << "const casadi_real* r;\n";
2883  g << "casadi_int flag;\n";
2884  if (needs_mem) g << "int mem;\n";
2885 
2886 
2887 
2888  // Work vectors and input and output buffers
2889  size_t nr = sz_w() + nnz_in() + nnz_out();
2890  g << CodeGenerator::array("casadi_int", "iw", sz_iw())
2891  << CodeGenerator::array("casadi_real", "w", nr);
2892 
2893  // Input buffers
2894  g << "const casadi_real* arg[" << sz_arg() << "];\n";
2895 
2896  // Output buffers
2897  g << "casadi_real* res[" << sz_res() << "];\n";
2898 
2899  casadi_int off=0;
2900  for (casadi_int i=0; i<n_in_; ++i) {
2901  g << "arg[" << i << "] = w+" << off << ";\n";
2902  off += nnz_in(i);
2903  }
2904  for (casadi_int i=0; i<n_out_; ++i) {
2905  g << "res[" << i << "] = w+" << off << ";\n";
2906  off += nnz_out(i);
2907  }
2908 
2909  // TODO(@jaeandersson): Read inputs from file. For now; read from stdin
2910  g << "a = w;\n"
2911  << "for (j=0; j<" << nnz_in() << "; ++j) "
2912  << "if (scanf(\"%lg\", a++)<=0) return 2;\n";
2913 
2914  if (has_refcount_in_deps_) {
2915  g << name_ << "_incref();\n";
2916  }
2917 
2918  if (needs_mem) {
2919  g << "mem = " << name_ << "_checkout();\n";
2920  }
2921 
2922  // Call the function
2923  g << "flag = " << name_ << "(arg, res, iw, w+" << off << ", ";
2924  if (needs_mem) {
2925  g << "mem";
2926  } else {
2927  g << "0";
2928  }
2929  g << ");\n";
2930  if (needs_mem) {
2931  g << name_ << "_release(mem);\n";
2932  }
2933 
2934  if (has_refcount_in_deps_) {
2935  g << name_ << "_decref();\n";
2936  }
2937 
2938  g << "if (flag) return flag;\n";
2939 
2940  // TODO(@jaeandersson): Write outputs to file. For now: print to stdout
2941  g << "r = w+" << nnz_in() << ";\n"
2942  << "for (j=0; j<" << nnz_out() << "; ++j) "
2943  << g.printf("%.16e ", "*r++") << "\n";
2944 
2945  // End with newline
2946  g << g.printf("\\n") << "\n";
2947 
2948  // Finalize function
2949  g << "return 0;\n"
2950  << "}\n\n";
2951  }
2952 
2953  if (g.with_mem) {
2954  // Allocate memory
2955  g << g.declare("casadi_functions* " + name_ + "_functions(void)") << " {\n"
2956  << "static casadi_functions fun = {\n"
2957  << name_ << "_incref,\n"
2958  << name_ << "_decref,\n"
2959  << name_ << "_checkout,\n"
2960  << name_ << "_release,\n"
2961  << name_ << "_default_in,\n"
2962  << name_ << "_n_in,\n"
2963  << name_ << "_n_out,\n"
2964  << name_ << "_name_in,\n"
2965  << name_ << "_name_out,\n"
2966  << name_ << "_sparsity_in,\n"
2967  << name_ << "_sparsity_out,\n"
2968  << name_ << "_work,\n"
2969  << name_ << "\n"
2970  << "};\n"
2971  << "return &fun;\n"
2972  << "}\n";
2973  }
2974  // Flush
2975  g.flush(g.body);
2976  }
static std::string array(const std::string &type, const std::string &name, casadi_int len, const std::string &def=std::string())
virtual size_t codegen_sz_res(const CodeGenerator &g) const
Get required lengths, for codegen.
virtual size_t codegen_sz_arg(const CodeGenerator &g) const
Get required lengths, for codegen.
std::vector< bool > is_diff_out_
virtual size_t codegen_sz_iw(const CodeGenerator &g) const
Get required lengths, for codegen.
virtual size_t codegen_sz_w(const CodeGenerator &g) const
Get required lengths, for codegen.
bool has_refcount_in_deps_
Reference counting in dependent functions.
std::vector< bool > is_diff_in_
Are inputs and outputs differentiable?
void codegen_sparsities(CodeGenerator &g) const
Codegen sparsities.
virtual double get_default_in(casadi_int ind) const
Get default input value.
int checkout() const
Checkout a memory object.
void release(int mem) const
Release a memory object.
bool all(const std::vector< bool > &v)
Check if all arguments are true.
Definition: casadi_misc.cpp:81

References casadi::all(), casadi::CodeGenerator::array(), casadi::CodeGenerator::body, casadi::ProtoFunction::checkout(), casadi::FunctionInternal::codegen_name(), casadi::FunctionInternal::codegen_needs_mem(), casadi::FunctionInternal::codegen_sparsities(), casadi::FunctionInternal::codegen_sz_arg(), casadi::FunctionInternal::codegen_sz_iw(), casadi::FunctionInternal::codegen_sz_res(), casadi::FunctionInternal::codegen_sz_w(), casadi::CodeGenerator::constant(), casadi::CodeGenerator::declare(), casadi::CodeGenerator::flush(), casadi::CodeGenerator::from_mex(), casadi::FunctionInternal::get_default_in(), casadi::FunctionInternal::has_refcount_in_deps_, casadi::CodeGenerator::header, casadi::FunctionInternal::is_diff_in_, casadi::FunctionInternal::is_diff_out_, casadi::CodeGenerator::main, casadi::CodeGenerator::mex, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::CodeGenerator::printf(), casadi::ProtoFunction::release(), casadi::CodeGenerator::res(), casadi::CodeGenerator::shorthand(), casadi::Sparsity::size1(), casadi::Sparsity::size2(), casadi::FunctionInternal::sparsity_in_, casadi::FunctionInternal::sparsity_out_, casadi::str(), casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), casadi::FunctionInternal::sz_w(), casadi::CodeGenerator::to_mex(), casadi::CodeGenerator::with_header, and casadi::CodeGenerator::with_mem.

Referenced by casadi::CodeGenerator::add().

◆ codegen_name()

std::string casadi::FunctionInternal::codegen_name ( const CodeGenerator g,
bool  ns = true 
) const
virtualinherited

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

Definition at line 2978 of file function_internal.cpp.

2978  {
2979  if (ns) {
2980  // Get the index of the function
2981  for (auto&& e : g.added_functions_) {
2982  if (e.f.get()==this) return e.codegen_name;
2983  }
2984  } else {
2985  for (casadi_int i=0;i<g.added_functions_.size();++i) {
2986  const auto & e = g.added_functions_[i];
2987  if (e.f.get()==this) return "f" + str(i);
2988  }
2989  }
2990  casadi_error("Function '" + name_ + "' not found");
2991  }

References casadi::CodeGenerator::added_functions_, casadi::ProtoFunction::name_, and casadi::str().

Referenced by casadi::FunctionInternal::codegen(), casadi::FunctionInternal::codegen_alloc_mem(), casadi::FatropInterface::codegen_body(), casadi::FunctionInternal::codegen_checkout(), casadi::FunctionInternal::codegen_decref(), casadi::FunctionInternal::codegen_incref(), casadi::FunctionInternal::codegen_mem(), casadi::FunctionInternal::codegen_meta(), casadi::FunctionInternal::codegen_release(), casadi::CodeGenerator::mem(), and casadi::CodeGenerator::operator()().

◆ codegen_needs_mem()

virtual bool casadi::FunctionInternal::codegen_needs_mem ( ) const
inlinevirtualinherited

◆ codegen_post_solve()

void casadi::Nlpsol::codegen_post_solve ( CodeGenerator g,
const std::string &  d_nlp 
) const
inherited

Definition at line 1373 of file nlpsol.cpp.

1373  {
1374  if (calc_f_ || calc_g_ || calc_lam_x_ || calc_lam_p_) {
1375  g.local("one", "const casadi_real");
1376  g.init_local("one", "1");
1377  g << "d->arg[0] = " << d_nlp << ".z;\n";
1378  g << "d->arg[1] = " << d_nlp << ".p;\n";
1379  g << "d->arg[2] = &one;\n";
1380  g << "d->arg[3] = " << d_nlp << ".lam+" << str(nx_) << ";\n";
1381  g << "d->res[0] = " << (calc_f_ ? "&" + d_nlp + ".objective" : "0") << ";\n";
1382  g << "d->res[1] = " << (calc_g_ ? d_nlp + ".z+" + str(nx_) : "0") << ";\n";
1383  g << "d->res[2] = " << (calc_lam_x_ ? d_nlp + ".lam+" + str(nx_) : "0") << ";\n";
1384  g << "d->res[3] = " << (calc_lam_p_ ? d_nlp + ".lam_p" : "0") << ";\n";
1385  std::string nlp_grad = g(get_function("nlp_grad"), "d->arg", "d->res", "d->iw", "d->w");
1386  g << "if (" << nlp_grad << ") return 1;\n";
1387  if (calc_lam_x_) g << g.scal(nx_, "-1.0", d_nlp + ".lam") << "\n";
1388  if (calc_lam_p_) g << g.scal(np_, "-1.0", d_nlp + ".lam_p") << "\n";
1389  }
1390  if (bound_consistency_) {
1391  g << g.bound_consistency(nx_+ng_, d_nlp + ".z", d_nlp + ".lam",
1392  d_nlp + ".lbz", d_nlp + ".ubz") << ";\n";
1393  }
1394 
1395  g << g.copy(d_nlp + ".z", nx_, d_nlp + ".x") << "\n";
1396 
1397  if (detect_simple_bounds_is_simple_.empty()) {
1398  g << g.copy(d_nlp + ".z + " + str(nx_), ng_, d_nlp + ".g") << "\n";
1399  g << g.copy(d_nlp + ".lam", nx_, d_nlp + ".lam_x") << "\n";
1400  g << g.copy(d_nlp + ".lam + " + str(nx_), ng_, d_nlp + ".lam_g") << "\n";
1401  } else {
1402  g << "if (casadi_nlpsol_detect_bounds_after(&" << d_nlp << ")) return 1;\n";
1403  }
1404 
1405  g.copy_check("&" + d_nlp + ".objective", 1, d_nlp + ".f", false, true);
1406  g.copy_check(d_nlp + ".lam_p", np_, d_nlp + ".lam_p", false, true);
1407  }
casadi_int np_
Number of parameters.
Definition: nlpsol_impl.hpp:72
bool bound_consistency_
Options.
Definition: nlpsol_impl.hpp:98

References casadi::CodeGenerator::bound_consistency(), casadi::Nlpsol::bound_consistency_, casadi::Nlpsol::calc_f_, casadi::Nlpsol::calc_g_, casadi::Nlpsol::calc_lam_p_, casadi::Nlpsol::calc_lam_x_, casadi::CodeGenerator::copy(), casadi::CodeGenerator::copy_check(), casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::OracleFunction::get_function(), casadi::CodeGenerator::init_local(), casadi::CodeGenerator::local(), casadi::Nlpsol::ng_, casadi::Nlpsol::np_, casadi::Nlpsol::nx_, casadi::CodeGenerator::scal(), and casadi::str().

Referenced by casadi::UnoInterface::codegen_body(), and casadi::Nlpsol::codegen_body_exit().

◆ codegen_release()

void casadi::FunctionInternal::codegen_release ( CodeGenerator g) const
virtualinherited

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

Reimplemented in casadi::External.

Definition at line 2648 of file function_internal.cpp.

2648  {
2649  std::string name = codegen_name(g, false);
2650  std::string stack_counter = g.shorthand(name + "_unused_stack_counter");
2651  std::string stack = g.shorthand(name + "_unused_stack");
2652 
2653  if (g.thread_safe()) {
2654  Function F = shared_from_this<Function>();
2655  std::string mem_mutex = g.local_mutex(F, name + "_mem_mutex");
2656  g << "CASADI_MUTEX_LOCK(&" << mem_mutex << ");\n";
2657  g.scope_add_cleanup("CASADI_MUTEX_UNLOCK(&" + mem_mutex + ");\n");
2658  }
2659 
2660  g << stack << "[++" << stack_counter << "] = mem;\n";
2661  g.scope_return();
2662  }

References casadi::FunctionInternal::codegen_name(), casadi::CodeGenerator::local_mutex(), casadi::CodeGenerator::scope_add_cleanup(), casadi::CodeGenerator::scope_return(), casadi::CodeGenerator::shorthand(), and casadi::CodeGenerator::thread_safe().

Referenced by casadi::CodeGenerator::add_dependency().

◆ codegen_setup_constants()

void casadi::Nlpsol::codegen_setup_constants ( CodeGenerator g,
const std::string &  d_nlp,
const std::string &  p_nlp,
const std::string &  d_oracle 
) const
inherited

Definition at line 1281 of file nlpsol.cpp.

1283  {
1284  g << d_nlp << ".oracle = &" << d_oracle << ";\n";
1285  g << d_nlp << ".prob = &" << p_nlp << ";\n";
1286  g << p_nlp << ".nx = " << nx_ << ";\n";
1287  g << p_nlp << ".ng = " << ng_ << ";\n";
1288  g << p_nlp << ".np = " << np_ << ";\n";
1289  g << p_nlp << ".detect_bounds.ng = " << detect_simple_bounds_is_simple_.size() << ";\n";
1290  if (detect_simple_bounds_is_simple_.size()) {
1291  g << p_nlp << ".detect_bounds.sz_arg = " << detect_simple_bounds_parts_.sz_arg() << ";\n";
1292  g << p_nlp << ".detect_bounds.sz_res = " << detect_simple_bounds_parts_.sz_res() << ";\n";
1293  g << p_nlp << ".detect_bounds.sz_iw = " << detect_simple_bounds_parts_.sz_iw() << ";\n";
1294  g << p_nlp << ".detect_bounds.sz_w = " << detect_simple_bounds_parts_.sz_w() << ";\n";
1295 
1296  g << p_nlp << ".detect_bounds.nb = " << detect_simple_bounds_target_x_.size() << ";\n";
1297  g << p_nlp << ".detect_bounds.target_x = "
1298  << g.constant(detect_simple_bounds_target_x_) << ";\n";
1299  g << p_nlp << ".detect_bounds.target_g = "
1300  << g.constant(detect_simple_bounds_target_g_) << ";\n";
1301  g << p_nlp << ".detect_bounds.is_simple = "
1302  << g.constant(detect_simple_bounds_is_simple_) << ";\n";
1303  std::string w =
1304  g.shorthand(g.wrapper(detect_simple_bounds_parts_, "detect_simple_bounds_wrapper"));
1305  g << p_nlp << ".detect_bounds.callback = " << w << ";\n";
1306  g << p_nlp << ".detect_bounds.callback_data = 0;\n";
1307  }
1308  }
size_t sz_res() const
Get required length of res field.
Definition: function.cpp:1237
size_t sz_iw() const
Get required length of iw field.
Definition: function.cpp:1239
size_t sz_w() const
Get required length of w field.
Definition: function.cpp:1241
size_t sz_arg() const
Get required length of arg field.
Definition: function.cpp:1235
std::vector< casadi_int > detect_simple_bounds_target_g_
Definition: nlpsol_impl.hpp:87
std::vector< casadi_int > detect_simple_bounds_target_x_
Definition: nlpsol_impl.hpp:86

References casadi::CodeGenerator::constant(), casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::Nlpsol::detect_simple_bounds_parts_, casadi::Nlpsol::detect_simple_bounds_target_g_, casadi::Nlpsol::detect_simple_bounds_target_x_, casadi::Nlpsol::ng_, casadi::Nlpsol::np_, casadi::Nlpsol::nx_, casadi::CodeGenerator::shorthand(), casadi::Function::sz_arg(), casadi::Function::sz_iw(), casadi::Function::sz_res(), casadi::Function::sz_w(), and casadi::CodeGenerator::wrapper().

Referenced by casadi::Nlpsol::codegen_body_enter(), and casadi::UnoInterface::codegen_init_mem().

◆ codegen_setup_per_call()

void casadi::Nlpsol::codegen_setup_per_call ( CodeGenerator g,
const std::string &  d_nlp 
) const
inherited

Definition at line 1313 of file nlpsol.cpp.

1313  {
1314  g << d_nlp << ".p = arg[" << NLPSOL_P << "];\n";
1315  g << d_nlp << ".lbx = arg[" << NLPSOL_LBX << "];\n";
1316  g << d_nlp << ".ubx = arg[" << NLPSOL_UBX << "];\n";
1317  g << d_nlp << ".lbg = arg[" << NLPSOL_LBG << "];\n";
1318  g << d_nlp << ".ubg = arg[" << NLPSOL_UBG << "];\n";
1319  g << d_nlp << ".x0 = arg[" << NLPSOL_X0 << "];\n";
1320  g << d_nlp << ".lam_x0 = arg[" << NLPSOL_LAM_X0 << "];\n";
1321  g << d_nlp << ".lam_g0 = arg[" << NLPSOL_LAM_G0 << "];\n";
1322  g << "arg += " << NLPSOL_NUM_IN << ";\n";
1323 
1324  g << d_nlp << ".x = res[" << NLPSOL_X << "];\n";
1325  g << d_nlp << ".f = res[" << NLPSOL_F << "];\n";
1326  g << d_nlp << ".g = res[" << NLPSOL_G << "];\n";
1327  g << d_nlp << ".lam_x = res[" << NLPSOL_LAM_X << "];\n";
1328  g << d_nlp << ".lam_g = res[" << NLPSOL_LAM_G << "];\n";
1329  g << d_nlp << ".lam_p = res[" << NLPSOL_LAM_P << "];\n";
1330  g << "res += " << NLPSOL_NUM_OUT << ";\n";
1331 
1332  g << "casadi_nlpsol_set_work(&" << d_nlp << ", &arg, &res, &iw, &w);\n";
1333 
1334  g.copy_default(d_nlp + ".x0", nx_, d_nlp + ".z", "0", false);
1335  g.copy_default(d_nlp + ".lbx", nx_, d_nlp + ".lbz", "-casadi_inf", false);
1336  g.copy_default(d_nlp + ".ubx", nx_, d_nlp + ".ubz", "casadi_inf", false);
1337  g.copy_default(d_nlp + ".lam_x0", nx_, d_nlp + ".lam", "0", false);
1338 
1339  if (detect_simple_bounds_is_simple_.empty()) {
1340  g.copy_default(d_nlp + ".lbg", ng_, d_nlp + ".lbz+" + str(nx_), "-casadi_inf", false);
1341  g.copy_default(d_nlp + ".ubg", ng_, d_nlp + ".ubz+" + str(nx_), "casadi_inf", false);
1342  g.copy_default(d_nlp + ".lam_g0", ng_, d_nlp + ".lam+" + str(nx_), "0", false);
1343  } else {
1344  g << "if (casadi_nlpsol_detect_bounds_before(&" << d_nlp << ")) return 1;\n";
1345  }
1346  }
@ NLPSOL_P
Value of fixed parameters (np x 1)
Definition: nlpsol.hpp:198
@ NLPSOL_LAM_G0
Lagrange multipliers for bounds on G, initial guess (ng x 1)
Definition: nlpsol.hpp:210
@ NLPSOL_LAM_X0
Lagrange multipliers for bounds on X, initial guess (nx x 1)
Definition: nlpsol.hpp:208
@ NLPSOL_NUM_IN
Definition: nlpsol.hpp:211
@ NLPSOL_NUM_OUT
Definition: nlpsol.hpp:228
@ NLPSOL_LAM_P
Lagrange multipliers for bounds on P at the solution (np x 1)
Definition: nlpsol.hpp:227

References casadi::CodeGenerator::copy_default(), casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::Nlpsol::ng_, casadi::NLPSOL_F, casadi::NLPSOL_G, casadi::NLPSOL_LAM_G, casadi::NLPSOL_LAM_G0, casadi::NLPSOL_LAM_P, casadi::NLPSOL_LAM_X, casadi::NLPSOL_LAM_X0, casadi::NLPSOL_LBG, casadi::NLPSOL_LBX, casadi::NLPSOL_NUM_IN, casadi::NLPSOL_NUM_OUT, casadi::NLPSOL_P, casadi::NLPSOL_UBG, casadi::NLPSOL_UBX, casadi::NLPSOL_X, casadi::NLPSOL_X0, casadi::Nlpsol::nx_, and casadi::str().

Referenced by casadi::UnoInterface::codegen_body(), and casadi::Nlpsol::codegen_body_enter().

◆ codegen_sparsities()

void casadi::FunctionInternal::codegen_sparsities ( CodeGenerator g) const
inherited

◆ codegen_sz_arg()

size_t casadi::FunctionInternal::codegen_sz_arg ( const CodeGenerator g) const
virtualinherited

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

Definition at line 3100 of file function_internal.cpp.

3100  {
3101  return sz_arg();
3102  }

References casadi::FunctionInternal::sz_arg().

Referenced by casadi::FunctionInternal::codegen_meta().

◆ codegen_sz_iw()

size_t casadi::FunctionInternal::codegen_sz_iw ( const CodeGenerator g) const
virtualinherited

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

Definition at line 3106 of file function_internal.cpp.

3106  {
3107  return sz_iw();
3108  }

References casadi::FunctionInternal::sz_iw().

Referenced by casadi::FunctionInternal::codegen_meta().

◆ codegen_sz_res()

size_t casadi::FunctionInternal::codegen_sz_res ( const CodeGenerator g) const
virtualinherited

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

Definition at line 3103 of file function_internal.cpp.

3103  {
3104  return sz_res();
3105  }

References casadi::FunctionInternal::sz_res().

Referenced by casadi::FunctionInternal::codegen_meta().

◆ codegen_sz_w()

size_t casadi::FunctionInternal::codegen_sz_w ( const CodeGenerator g) const
virtualinherited

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

Reimplemented in casadi::SXFunction.

Definition at line 3109 of file function_internal.cpp.

3109  {
3110  return sz_w();
3111  }

References casadi::FunctionInternal::sz_w().

Referenced by casadi::FunctionInternal::codegen_meta().

◆ computeNextHessian()

void casadi::Blocksqp::computeNextHessian ( BlocksqpMemory m,
casadi_int  idx,
casadi_int  maxQP 
) const

Definition at line 2254 of file blocksqp.cpp.

2255  {
2256  // Compute fallback update only once
2257  if (idx == 1) {
2258  // Switch storage
2259  m->hess = m->hess2;
2260 
2261  // If last block contains exact Hessian, we need to copy it
2262  if (which_second_derv_ == 1) {
2263  casadi_int dim = dim_[nblocks_-1];
2264  casadi_copy(m->hess1[nblocks_-1], dim*dim, m->hess2[nblocks_-1]);
2265  }
2266 
2267  // Limited memory: compute fallback update only when needed
2268  if (hess_lim_mem_) {
2269  m->itCount--;
2270  casadi_int hessDampSave = hess_damp_;
2271  const_cast<Blocksqp*>(this)->hess_damp_ = 1;
2273  const_cast<Blocksqp*>(this)->hess_damp_ = hessDampSave;
2274  m->itCount++;
2275  }
2276  /* Full memory: both updates must be computed in every iteration
2277  * so switching storage is enough */
2278  }
2279 
2280  // 'Nontrivial' convex combinations
2281  if (maxQP > 2) {
2282  /* Convexification parameter: mu_l = l / (maxQP-1).
2283  * Compute it only in the first iteration, afterwards update
2284  * by recursion: mu_l/mu_(l-1) */
2285  double idxF = idx;
2286  double mu = (idx==1) ? 1.0 / (maxQP-1) : idxF / (idxF - 1.0);
2287  double mu1 = 1.0 - mu;
2288  for (casadi_int b=0; b<nblocks_; b++) {
2289  casadi_int dim = dim_[b];
2290  for (casadi_int i=0; i<dim; i++) {
2291  for (casadi_int j=0; j<dim; j++) {
2292  m->hess2[b][i+j*dim] *= mu;
2293  m->hess2[b][i+j*dim] += mu1 * m->hess1[b][i+j*dim];
2294  }
2295  }
2296  }
2297  }
2298  }
void calcHessianUpdateLimitedMemory(BlocksqpMemory *m, casadi_int updateType, casadi_int hessScaling) const
Definition: blocksqp.cpp:1996
Blocksqp(const std::string &name, const Function &nlp)
Definition: blocksqp.cpp:49

References calcHessianUpdateLimitedMemory(), casadi::casadi_copy(), dim_, fallback_scaling_, fallback_update_, casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hess1, casadi::BlocksqpMemory::hess2, hess_damp_, hess_lim_mem_, casadi::BlocksqpMemory::itCount, nblocks_, and which_second_derv_.

Referenced by solveQP().

◆ construct()

void casadi::ProtoFunction::construct ( const Dict opts)
inherited

Prepares the function for evaluation

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

Definition at line 141 of file function_internal.cpp.

141  {
142  // Sanitize dictionary is needed
143  if (!Options::is_sane(opts)) {
144  // Call recursively
146  return;
147  }
148 
149  // Make sure all options exist
150  get_options().check(opts);
151 
152  // Initialize the class hierarchy
153  try {
154  init(opts);
155  } catch(std::exception& e) {
156  casadi_error("Error calling " + class_name() + "::init for '" + name_ + "':\n"
157  + std::string(e.what()));
158  }
159 
160  // Revisit class hierarchy in reverse order
161  try {
162  finalize();
163  } catch(std::exception& e) {
164  casadi_error("Error calling " + class_name() + "::finalize for '" + name_ + "':\n"
165  + std::string(e.what()));
166  }
167  }
void construct(const Dict &opts)
Construct.
virtual const Options & get_options() const
Options.
virtual void init(const Dict &opts)
Initialize.
virtual void finalize()
Finalize the object creation.
static bool is_sane(const Dict &opts)
Is the dictionary sane.
Definition: options.cpp:169
static Dict sanitize(const Dict &opts, bool top_level=true)
Sanitize a options dictionary.
Definition: options.cpp:173
void check(const Dict &opts) const
Check if options exist.
Definition: options.cpp:240

References casadi::Options::check(), casadi::SharedObjectInternal::class_name(), casadi::ProtoFunction::finalize(), casadi::ProtoFunction::get_options(), casadi::ProtoFunction::init(), casadi::Options::is_sane(), casadi::ProtoFunction::name_, and casadi::Options::sanitize().

Referenced by casadi::Function::create(), casadi::FmuFunction::factory(), casadi::FmuFunction::get_forward(), casadi::FmuFunction::get_jacobian(), casadi::LinearInterpolant::get_jacobian(), and casadi::FmuFunction::get_reverse().

◆ convert_arg() [1/2]

template<typename M >
std::vector< M > casadi::FunctionInternal::convert_arg ( const std::map< std::string, M > &  arg) const
inherited

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

Definition at line 1892 of file function_internal.hpp.

1893  {
1894  // Get default inputs
1895  std::vector<M> arg_v(n_in_);
1896  for (casadi_int i=0; i<arg_v.size(); ++i) {
1897  arg_v[i] = get_default_in(i);
1898  }
1899 
1900  // Assign provided inputs
1901  for (auto&& e : arg) {
1902  arg_v.at(index_in(e.first)) = e.second;
1903  }
1904 
1905  return arg_v;
1906  }
casadi_int index_in(const std::string &name) const
Get input scheme index by name.

References casadi::FunctionInternal::get_default_in(), casadi::FunctionInternal::index_in(), and casadi::FunctionInternal::n_in_.

◆ convert_arg() [2/2]

template<typename M >
std::map< std::string, M > casadi::FunctionInternal::convert_arg ( const std::vector< M > &  arg) const
inherited

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

Definition at line 1880 of file function_internal.hpp.

1881  {
1882  casadi_assert(arg.size()==n_in_, "Incorrect number of inputs: Expected "
1883  + str(n_in_) + ", got " + str(arg.size()));
1884  std::map<std::string, M> ret;
1885  for (casadi_int i=0;i<n_in_;++i) {
1886  ret[name_in_[i]] = arg[i];
1887  }
1888  return ret;
1889  }

References casadi::FunctionInternal::n_in_, casadi::FunctionInternal::name_in_, and casadi::str().

◆ convert_res() [1/2]

template<typename M >
std::vector< M > casadi::FunctionInternal::convert_res ( const std::map< std::string, M > &  res) const
inherited

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

Definition at line 1921 of file function_internal.hpp.

1922  {
1923  // Get default inputs
1924  std::vector<M> res_v(n_out_);
1925  for (casadi_int i=0; i<res_v.size(); ++i) {
1926  res_v[i] = std::numeric_limits<double>::quiet_NaN();
1927  }
1928 
1929  // Assign provided inputs
1930  for (auto&& e : res) {
1931  M a = e.second;
1932  res_v.at(index_out(e.first)) = a;
1933  }
1934  return res_v;
1935  }
casadi_int index_out(const std::string &name) const
Get output scheme index by name.

References casadi::FunctionInternal::index_out(), and casadi::FunctionInternal::n_out_.

◆ convert_res() [2/2]

template<typename M >
std::map< std::string, M > casadi::FunctionInternal::convert_res ( const std::vector< M > &  res) const
inherited

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

Definition at line 1909 of file function_internal.hpp.

1910  {
1911  casadi_assert(res.size()==n_out_, "Incorrect number of outputs: Expected "
1912  + str(n_out_) + ", got " + str(res.size()));
1913  std::map<std::string, M> ret;
1914  for (casadi_int i=0;i<n_out_;++i) {
1915  ret[name_out_[i]] = res[i];
1916  }
1917  return ret;
1918  }

References casadi::FunctionInternal::n_out_, casadi::FunctionInternal::name_out_, and casadi::str().

◆ convertHessian()

void casadi::Blocksqp::convertHessian ( BlocksqpMemory m) const

Convert array *hess to a single symmetric sparse matrix in Harwell-Boeing format (as used by qpOASES)

Definition at line 2712 of file blocksqp.cpp.

2713  {
2714  casadi_int count, colCountTotal, rowOffset;
2715  casadi_int nnz;
2716 
2717  // 1) count nonzero elements
2718  nnz = 0;
2719  for (casadi_int b=0; b<nblocks_; b++) {
2720  casadi_int dim = dim_[b];
2721  for (casadi_int i=0; i<dim; i++) {
2722  for (casadi_int j=0; j<dim; j++) {
2723  if (fabs(m->hess[b][i+j*dim]) > eps_) {
2724  nnz++;
2725  }
2726  }
2727  }
2728  }
2729 
2730  m->hessIndCol = m->hessIndRow + nnz;
2731  m->hessIndLo = m->hessIndCol + (nx_+1);
2732 
2733  // 2) store matrix entries columnwise in hessNz
2734  count = 0; // runs over all nonzero elements
2735  colCountTotal = 0; // keep track of position in large matrix
2736  rowOffset = 0;
2737  for (casadi_int b=0; b<nblocks_; b++) {
2738  casadi_int dim = dim_[b];
2739 
2740  for (casadi_int i=0; i<dim; i++) {
2741  // column 'colCountTotal' starts at element 'count'
2742  m->hessIndCol[colCountTotal] = count;
2743 
2744  for (casadi_int j=0; j<dim; j++) {
2745  if (fabs(m->hess[b][i+j*dim]) > eps_) {
2746  m->hess_lag[count] = m->hess[b][i+j*dim];
2747  m->hessIndRow[count] = j + rowOffset;
2748  count++;
2749  }
2750  }
2751  colCountTotal++;
2752  }
2753  rowOffset += dim;
2754  }
2755  m->hessIndCol[colCountTotal] = count;
2756 
2757  // 3) Set reference to lower triangular matrix
2758  for (casadi_int j=0; j<nx_; j++) {
2759  casadi_int i;
2760  for (i=m->hessIndCol[j]; i<m->hessIndCol[j+1] && m->hessIndRow[i]<j; i++) {}
2761  m->hessIndLo[j] = i;
2762  }
2763 
2764  if (count != nnz)
2765  print("***WARNING: Error in convertHessian: %i elements processed, "
2766  "should be %i elements!\n", count, nnz);
2767  }

References dim_, eps_, casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hess_lag, casadi::BlocksqpMemory::hessIndCol, casadi::BlocksqpMemory::hessIndLo, casadi::BlocksqpMemory::hessIndRow, nblocks_, casadi::Nlpsol::nx_, and casadi::ProtoFunction::print().

Referenced by solveQP().

◆ create_forward()

Function casadi::OracleFunction::create_forward ( const std::string &  fname,
casadi_int  nfwd 
)
inherited

Create an oracle function as a forward derivative of a different function

Definition at line 278 of file oracle_function.cpp.

278  {
279  // Create derivative
280  Function ret = get_function(fname).forward(nfwd);
281  std::string fwd_name = forward_name(fname, nfwd); // may be different from ret.name()
282  if (!has_function(fwd_name)) set_function(ret, fwd_name, true);
283  return ret;
284 }
static std::string forward_name(const std::string &fcn, casadi_int nfwd)
Helper function: Get name of forward derivative function.
void set_function(const Function &fcn, const std::string &fname, bool jit=false)
bool has_function(const std::string &fname) const override

References casadi::FunctionInternal::forward_name(), casadi::OracleFunction::get_function(), casadi::OracleFunction::has_function(), and casadi::OracleFunction::set_function().

Referenced by casadi::Integrator::init(), casadi::ImplicitFixedStepIntegrator::init(), casadi::SLEQPInterface::init(), casadi::SundialsInterface::init(), casadi::UnoInterface::init(), and casadi::RungeKutta::setup_step().

◆ create_function() [1/3]

Function casadi::OracleFunction::create_function ( const Function oracle,
const std::string &  fname,
const std::vector< std::string > &  s_in,
const std::vector< std::string > &  s_out,
const Function::AuxOut aux = Function::AuxOut(),
const Dict opts = Dict() 
)
inherited

Create an oracle function, using a different oracle function Temporary addition to allow transition from one oracle formulation to another.

Definition at line 235 of file oracle_function.cpp.

239  {
240  // Print progress
241  if (verbose_) {
242  casadi_message(name_ + "::create_function " + fname + ":" + str(s_in) + "->" + str(s_out));
243  }
244 
245  // Check if function is already in cache
246  Function ret;
247  if (incache(fname, ret)) {
248  // Consistency checks
249  casadi_assert(ret.n_in() == s_in.size(), fname + " has wrong number of inputs");
250  casadi_assert(ret.n_out() == s_out.size(), fname + " has wrong number of outputs");
251  } else {
252  // Retrieve specific set of options if available
253  Dict specific_options;
254  auto it = specific_options_.find(fname);
255  if (it!=specific_options_.end()) specific_options = it->second;
256 
257  // Combine specific and common options
258  Dict opt = combine(specific_options, common_options_);
259  opt = combine(opts, opt);
260 
261  // Generate the function
262  ret = oracle.factory(fname, s_in, s_out, aux, opt);
263 
264  // Make sure that it's sound
265  if (ret.has_free()) {
266  casadi_error("Cannot create '" + fname + "' since " + str(ret.get_free()) + " are free.");
267  }
268 
269  // Add to cache
270  tocache_if_missing(ret);
271  }
272 
273  // Save and return
274  set_function(ret, fname, true);
275  return ret;
276 }
void tocache_if_missing(Function &f, const std::string &suffix="") const
Save function to cache, only if missing.
bool incache(const std::string &fname, Function &f, const std::string &suffix="") const
Get function in cache.
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
Definition: function.cpp:2009
Dict common_options_
Options for creating functions.
const Function & oracle() const override
Get oracle.
bool verbose_
Verbose printout.
Dict combine(const Dict &first, const Dict &second, bool recurse)
Combine two dicts. First has priority.

References casadi::combine(), casadi::OracleFunction::common_options_, casadi::Function::factory(), casadi::Function::get_free(), casadi::Function::has_free(), casadi::FunctionInternal::incache(), casadi::Function::n_in(), casadi::Function::n_out(), casadi::ProtoFunction::name_, casadi::OracleFunction::oracle(), casadi::OracleFunction::set_function(), casadi::OracleFunction::specific_options_, casadi::str(), casadi::FunctionInternal::tocache_if_missing(), and casadi::ProtoFunction::verbose_.

Referenced by casadi::OracleFunction::create_function(), casadi::Integrator::init(), casadi::Nlpsol::init(), casadi::AlpaqaInterface::init(), init(), casadi::BonminInterface::init(), casadi::MadmpecInterface::init(), casadi::FatropInterface::init(), casadi::IpoptInterface::init(), casadi::KnitroInterface::init(), casadi::MadnlpInterface::init(), casadi::SLEQPInterface::init(), casadi::SnoptInterface::init(), casadi::SundialsInterface::init(), casadi::UnoInterface::init(), casadi::WorhpInterface::init(), casadi::Feasiblesqpmethod::init(), casadi::Qrsqp::init(), and casadi::Sqpmethod::init().

◆ create_function() [2/3]

Function casadi::OracleFunction::create_function ( const std::string &  fname,
const std::vector< MX > &  e_in,
const std::vector< MX > &  e_out,
const std::vector< std::string > &  s_in,
const std::vector< std::string > &  s_out,
const Dict opts = Dict() 
)
inherited

Create an oracle function from MX

Definition at line 187 of file oracle_function.cpp.

192  {
193 
194  // Print progress
195  if (verbose_) {
196  casadi_message(name_ + "::create_function " + fname + ":" + str(s_in) + "->" + str(s_out));
197  }
198 
199  // Check if function is already in cache
200  Function ret;
201  if (incache(fname, ret)) {
202  // Consistency checks
203  casadi_assert(ret.n_in() == s_in.size(), fname + " has wrong number of inputs");
204  casadi_assert(ret.n_out() == s_out.size(), fname + " has wrong number of outputs");
205  } else {
206  // Retrieve specific set of options if available
207  Dict specific_options;
208  auto it = specific_options_.find(fname);
209  if (it!=specific_options_.end()) specific_options = it->second;
210 
211  // Combine specific and common options
212  Dict opt = combine(specific_options, common_options_);
213  opt = combine(opts, opt);
214 
215  // Generate the function
216  ret = Function(fname, e_in, e_out, s_in, s_out, opt);
217 
218  // Make sure that it's sound
219  if (ret.has_free()) {
220  casadi_error("Cannot create '" + fname + "' since " + str(ret.get_free()) + " are free.");
221  }
222 
223  // TODO(jgillis) Conditionally convert to SX
224 
225  // Add to cache
226  tocache_if_missing(ret);
227  }
228 
229  // Save and return
230  set_function(ret, fname, true);
231  return ret;
232 
233 }

References casadi::combine(), casadi::OracleFunction::common_options_, casadi::FunctionInternal::Function, casadi::Function::get_free(), casadi::Function::has_free(), casadi::FunctionInternal::incache(), casadi::Function::n_in(), casadi::Function::n_out(), casadi::ProtoFunction::name_, casadi::OracleFunction::set_function(), casadi::OracleFunction::specific_options_, casadi::str(), casadi::FunctionInternal::tocache_if_missing(), and casadi::ProtoFunction::verbose_.

◆ create_function() [3/3]

Function casadi::OracleFunction::create_function ( const std::string &  fname,
const std::vector< std::string > &  s_in,
const std::vector< std::string > &  s_out,
const Function::AuxOut aux = Function::AuxOut(),
const Dict opts = Dict() 
)
inherited

Create an oracle function

Definition at line 179 of file oracle_function.cpp.

183  {
184  return create_function(oracle_, fname, s_in, s_out, aux, opts);
185 }
Function oracle_
Oracle: Used to generate other functions.
Function create_function(const Function &oracle, const std::string &fname, const std::vector< std::string > &s_in, const std::vector< std::string > &s_out, const Function::AuxOut &aux=Function::AuxOut(), const Dict &opts=Dict())

References casadi::OracleFunction::create_function(), and casadi::OracleFunction::oracle_.

◆ create_oracle()

template<typename XType >
Function casadi::Nlpsol::create_oracle ( const std::map< std::string, XType > &  d,
const Dict opts 
)
staticinherited

Definition at line 206 of file nlpsol.cpp.

207  {
208  std::vector<XType> nl_in(NL_NUM_IN), nl_out(NL_NUM_OUT);
209  for (auto&& i : d) {
210  if (i.first=="x") {
211  nl_in[NL_X]=i.second;
212  } else if (i.first=="p") {
213  nl_in[NL_P]=i.second;
214  } else if (i.first=="f") {
215  nl_out[NL_F]=i.second;
216  } else if (i.first=="g") {
217  nl_out[NL_G]=i.second;
218  } else {
219  casadi_error("No such field: " + i.first);
220  }
221  }
222  if (nl_out[NL_F].is_empty()) nl_out[NL_F] = 0;
223  if (nl_out[NL_G].is_empty()) nl_out[NL_G] = XType(0, 1);
224 
225  // Options for the oracle
226  Dict oracle_options;
227  Dict::const_iterator it = opts.find("oracle_options");
228  if (it != opts.end()) {
229  // "oracle_options" has been set
230  oracle_options = it->second;
231  } else {
232  // Propagate selected options from Nlpsol to oracle by default
233  for (const char* op : {"verbose", "regularity_check"}) {
234  it = opts.find(op);
235  if (it != opts.end()) {
236  oracle_options[op] = it->second;
237  }
238  }
239  }
240 
241  // Create oracle
242  return Function("nlp", nl_in, nl_out, NL_INPUTS, NL_OUTPUTS, oracle_options);
243  }
@ NL_X
Decision variable.
Definition: nlpsol.hpp:170
@ NL_P
Fixed parameter.
Definition: nlpsol.hpp:172
@ NL_NUM_IN
Number of NLP inputs.
Definition: nlpsol.hpp:174
@ NL_F
Objective function.
Definition: nlpsol.hpp:183
@ NL_G
Constraint function.
Definition: nlpsol.hpp:185
@ NL_NUM_OUT
Number of NLP outputs.
Definition: nlpsol.hpp:187
const std::vector< std::string > NL_INPUTS
Shortname for onput arguments of an NLP function.
Definition: nlpsol.hpp:178
const std::vector< std::string > NL_OUTPUTS
Shortname for output arguments of an NLP function.
Definition: nlpsol.hpp:191

References casadi::FunctionInternal::Function, casadi::NL_F, casadi::NL_G, casadi::NL_INPUTS, casadi::NL_NUM_IN, casadi::NL_NUM_OUT, casadi::NL_OUTPUTS, casadi::NL_P, and casadi::NL_X.

Referenced by casadi::construct_nlpsol().

◆ creator()

static Nlpsol* casadi::Blocksqp::creator ( const std::string &  name,
const Function nlp 
)
inlinestatic

Definition at line 163 of file blocksqp.hpp.

163  {
164  return new Blocksqp(name, nlp);
165  }

Referenced by casadi::casadi_register_nlpsol_blocksqp().

◆ debug_repr()

std::string casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::debug_repr ( const Internal *  i) const
inherited

Definition at line 62 of file generic_shared_internal.hpp.

175  {
176  // Note: i != this because of something something multiple inheritance
177  return str( (casadi_int)(i)) + "/" + static_cast<const Internal*>(this)->class_name();
178  }

◆ definition()

std::string casadi::FunctionInternal::definition ( ) const
inherited

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

Definition at line 1076 of file function_internal.cpp.

1076  {
1077  std::stringstream s;
1078 
1079  // Print name
1080  s << name_ << ":(";
1081  // Print input arguments
1082  for (casadi_int i=0; i<n_in_; ++i) {
1083  if (!is_diff_in_.empty() && !is_diff_in_[i]) s << "#";
1084  s << name_in_[i] << sparsity_in_[i].postfix_dim() << (i==n_in_-1 ? "" : ",");
1085  }
1086  s << ")->(";
1087  // Print output arguments
1088  for (casadi_int i=0; i<n_out_; ++i) {
1089  if (!is_diff_out_.empty() && !is_diff_out_[i]) s << "#";
1090  s << name_out_[i] << sparsity_out_[i].postfix_dim() << (i==n_out_-1 ? "" : ",");
1091  }
1092  s << ")";
1093 
1094  return s.str();
1095  }

References casadi::FunctionInternal::is_diff_in_, casadi::FunctionInternal::is_diff_out_, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::sparsity_in_, and casadi::FunctionInternal::sparsity_out_.

Referenced by casadi::FunctionInternal::codegen(), casadi::FunctionInternal::disp(), casadi::MXFunction::should_inline(), and casadi::SXFunction::should_inline().

◆ deps_version_check()

virtual void casadi::PluginInterface< Nlpsol >::deps_version_check ( const std::string &  stage) const
inlinevirtualinherited

Definition at line 112 of file plugin_interface.hpp.

112 {}

◆ deserialize()

static ProtoFunction* casadi::Blocksqp::deserialize ( DeserializingStream s)
inlinestatic

Definition at line 406 of file blocksqp.hpp.

406 { return new Blocksqp(s); }

Referenced by casadi::casadi_register_nlpsol_blocksqp().

◆ destroySingleton()

void casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::destroySingleton ( )
inlineprotectedinherited

Called in the destructor of singletons

Definition at line 77 of file generic_shared_internal.hpp.

77  {
78  static_cast<Internal*>(this)->count--;
79  }

◆ diff_prefix()

std::string casadi::FunctionInternal::diff_prefix ( const std::string &  prefix) const
inherited

Definition at line 2184 of file function_internal.cpp.

2184  {
2185  // Highest index found in current inputs and outputs
2186  casadi_int highest_index = 0;
2187  // Loop over both input names and output names
2188  for (const std::vector<std::string>& name_io : {name_in_, name_out_}) {
2189  for (const std::string& n : name_io) {
2190  // Find end of prefix, skip if no prefix
2191  size_t end = n.find('_');
2192  if (end >= n.size()) continue;
2193  // Skip if too short
2194  if (end < prefix.size()) continue;
2195  // Skip if wrong prefix
2196  if (n.compare(0, prefix.size(), prefix) != 0) continue;
2197  // Beginning of index
2198  size_t begin = prefix.size();
2199  // Check if any index
2200  casadi_int this_index;
2201  if (begin == end) {
2202  // No prefix, implicitly 1
2203  this_index = 1;
2204  } else {
2205  // Read index from string
2206  this_index = std::stoi(n.substr(begin, end - begin));
2207  }
2208  // Find the highest index
2209  if (this_index > highest_index) highest_index = this_index;
2210  }
2211  }
2212  // Return one higher index
2213  if (highest_index == 0) {
2214  return prefix + "_";
2215  } else {
2216  return prefix + std::to_string(highest_index + 1) + "_";
2217  }
2218  }

References casadi::FunctionInternal::name_in_, and casadi::FunctionInternal::name_out_.

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

◆ disp()

void casadi::FunctionInternal::disp ( std::ostream &  stream,
bool  more 
) const
overridevirtualinherited

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

Implements casadi::SharedObjectInternal.

Definition at line 1097 of file function_internal.cpp.

1097  {
1098  stream << definition() << " " << class_name();
1099  if (more) {
1100  stream << std::endl;
1101  disp_more(stream);
1102  }
1103  }
virtual void disp_more(std::ostream &stream) const
Print more.

References casadi::SharedObjectInternal::class_name(), casadi::FunctionInternal::definition(), and casadi::FunctionInternal::disp_more().

Referenced by casadi::MXFunction::eval(), and casadi::SXFunction::eval().

◆ disp_more()

void casadi::Nlpsol::disp_more ( std::ostream &  stream) const
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 931 of file nlpsol.cpp.

931  {
932  stream << "minimize f(x;p) subject to lbx<=x<=ubx, lbg<=g(x;p)<=ubg defined by:\n";
933  oracle_.disp(stream, true);
934  }
void disp(std::ostream &stream, bool more=false) const
Print a description of the object.

References casadi::SharedObject::disp(), and casadi::OracleFunction::oracle_.

◆ dm_in() [1/2]

const std::vector< DM > casadi::FunctionInternal::dm_in ( ) const
inherited

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

Definition at line 3518 of file function_internal.cpp.

3518  {
3519  std::vector<DM> ret(n_in_);
3520  for (casadi_int i=0; i<ret.size(); ++i) {
3521  ret[i] = dm_in(i);
3522  }
3523  return ret;
3524  }
const std::vector< DM > dm_in() const
Get function input(s) and output(s)

References casadi::FunctionInternal::n_in_.

Referenced by casadi::FunctionInternal::nz_in().

◆ dm_in() [2/2]

const DM casadi::FunctionInternal::dm_in ( casadi_int  ind) const
inherited

◆ dm_out() [1/2]

const std::vector< DM > casadi::FunctionInternal::dm_out ( ) const
inherited

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

Definition at line 3526 of file function_internal.cpp.

3526  {
3527  std::vector<DM> ret(n_out_);
3528  for (casadi_int i=0; i<ret.size(); ++i) {
3529  ret[i] = dm_out(i);
3530  }
3531  return ret;
3532  }
const std::vector< DM > dm_out() const
Get function input(s) and output(s)

References casadi::FunctionInternal::n_out_.

Referenced by casadi::FunctionInternal::nz_out().

◆ dm_out() [2/2]

const DM casadi::FunctionInternal::dm_out ( casadi_int  ind) const
inherited

◆ ensure_stacked()

template<typename MatType >
MatType casadi::FunctionInternal::ensure_stacked ( const MatType &  v,
const Sparsity sp,
casadi_int  n 
)
staticinherited

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

Definition at line 1938 of file function_internal.hpp.

1938  {
1939  // Check dimensions
1940  if (v.size1() == sp.size1() && v.size2() == n * sp.size2()) {
1941  // Ensure that sparsity is a horizontal multiple of original input, or has no entries
1942  if (v.nnz() != 0 && !v.sparsity().is_stacked(sp, n)) {
1943  return project(v, repmat(sp, 1, n));
1944  }
1945  } else {
1946  // Correct empty sparsity
1947  casadi_assert_dev(v.is_empty());
1948  return MatType(sp.size1(), sp.size2() * n);
1949  }
1950  // No correction needed
1951  return v;
1952  }

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

◆ eval()

int casadi::Nlpsol::eval ( const double **  arg,
double **  res,
casadi_int *  iw,
double *  w,
void *  mem 
) const
finalvirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 793 of file nlpsol.cpp.

793  {
794  auto *m = static_cast<NlpsolMemory*>(mem);
795 
796  auto *d_nlp = &m->d_nlp;
797 
798  // Reset the solver, prepare for solution
799  setup(m, arg, res, iw, w);
800  const auto *p_nlp = d_nlp->prob;
801 
802  // Set initial guess
803  casadi_copy(d_nlp->x0, nx_, d_nlp->z);
804 
805  // Read simple bounds and multiplier guesses
806  casadi_copy(d_nlp->lbx, nx_, d_nlp->lbz);
807  casadi_copy(d_nlp->ubx, nx_, d_nlp->ubz);
808  casadi_copy(d_nlp->lam_x0, nx_, d_nlp->lam);
809 
810  if (p_nlp->detect_bounds.ng==0) {
811  // Read constraint bounds and multiplier guesses
812  casadi_copy(d_nlp->lbg, ng_, d_nlp->lbz+nx_);
813  casadi_copy(d_nlp->ubg, ng_, d_nlp->ubz+nx_);
814  casadi_copy(d_nlp->lam_g0, ng_, d_nlp->lam+nx_);
815  } else {
816  if (casadi_nlpsol_detect_bounds_before(d_nlp)) return 1;
817  }
818 
819  // Set multipliers to nan
820  casadi_fill(d_nlp->lam_p, np_, nan);
821 
822  // Reset f, g
823  d_nlp->objective = nan;
824  casadi_fill(d_nlp->z + nx_, ng_, nan);
825 
826  // Check the provided inputs
827  check_inputs(m);
828 
829  // Solve the NLP
830  int flag = solve(m);
831 
832  // Join statistics (introduced for parallel oracle facilities)
833  join_results(m);
834 
835  // Calculate multiplers
836  if ((calc_f_ || calc_g_ || calc_lam_x_ || calc_lam_p_) && !flag) {
837  const double lam_f = 1.;
838  m->arg[0] = d_nlp->z;
839  m->arg[1] = d_nlp->p;
840  m->arg[2] = &lam_f;
841  m->arg[3] = d_nlp->lam + nx_;
842  m->res[0] = calc_f_ ? &d_nlp->objective : nullptr;
843  m->res[1] = calc_g_ ? d_nlp->z + nx_ : nullptr;
844  m->res[2] = calc_lam_x_ ? d_nlp->lam : nullptr;
845  m->res[3] = calc_lam_p_ ? d_nlp->lam_p : nullptr;
846  if (calc_function(m, "nlp_grad")) {
847  casadi_warning("Failed to calculate multipliers");
848  }
849  if (calc_lam_x_) casadi_scal(nx_, -1., d_nlp->lam);
850  if (calc_lam_p_) casadi_scal(np_, -1., d_nlp->lam_p);
851  }
852 
853  // Make sure that an optimal solution is consistant with bounds
854  if (bound_consistency_ && !flag) {
855  bound_consistency(nx_+ng_, d_nlp->z, d_nlp->lam, d_nlp->lbz, d_nlp->ubz);
856  }
857 
858  // Get optimal solution
859  casadi_copy(d_nlp->z, nx_, d_nlp->x);
860 
861  if (p_nlp->detect_bounds.ng==0) {
862  casadi_copy(d_nlp->z + nx_, ng_, d_nlp->g);
863  casadi_copy(d_nlp->lam, nx_, d_nlp->lam_x);
864  casadi_copy(d_nlp->lam + nx_, ng_, d_nlp->lam_g);
865  } else {
866  if (casadi_nlpsol_detect_bounds_after(d_nlp)) return 1;
867  }
868 
869  casadi_copy(d_nlp->lam_p, np_, d_nlp->lam_p);
870  casadi_copy(&d_nlp->objective, 1, d_nlp->f);
871 
872  if (m->success) m->unified_return_status = SOLVER_RET_SUCCESS;
873 
874  if (error_on_fail_ && !m->success)
875  casadi_error("nlpsol process failed. "
876  "Set 'error_on_fail' option to false to ignore this error.");
877 
878  if (m->unified_return_status==SOLVER_RET_EXCEPTION) {
879  casadi_error("An exception was raised in the solver.");
880  }
881  return flag;
882  }
void setup(void *mem, const double **arg, double **res, casadi_int *iw, double *w) const
Set the (persistent and temporary) work vectors.
virtual void check_inputs(void *mem) const
Check if the inputs correspond to a well-posed problem.
Definition: nlpsol.cpp:702
static void bound_consistency(casadi_int n, double *z, double *lam, const double *lbz, const double *ubz)
Definition: nlpsol.cpp:767
virtual int solve(void *mem) const =0
void join_results(OracleMemory *m) const
Combine results from different threads.
int calc_function(OracleMemory *m, const std::string &fcn, const double *const *arg=nullptr, int thread_id=0) const
const double nan
Not a number.
Definition: calculus.hpp:53
@ SOLVER_RET_SUCCESS
@ SOLVER_RET_EXCEPTION

References casadi::Nlpsol::bound_consistency(), casadi::Nlpsol::bound_consistency_, casadi::Nlpsol::calc_f_, casadi::OracleFunction::calc_function(), casadi::Nlpsol::calc_g_, casadi::Nlpsol::calc_lam_p_, casadi::Nlpsol::calc_lam_x_, casadi::casadi_copy(), casadi::casadi_fill(), casadi::casadi_scal(), casadi::Nlpsol::check_inputs(), casadi::NlpsolMemory::d_nlp, casadi::ProtoFunction::error_on_fail_, casadi::OracleFunction::join_results(), casadi::nan, casadi::Nlpsol::ng_, casadi::Nlpsol::np_, casadi::Nlpsol::nx_, casadi::FunctionInternal::setup(), casadi::Nlpsol::solve(), casadi::SOLVER_RET_EXCEPTION, and casadi::SOLVER_RET_SUCCESS.

◆ eval_activity()

int casadi::FunctionInternal::eval_activity ( const bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t w,
void *  mem 
) const
virtualinherited

bvec bit set = active (possibly nonzero), clear = inactive (definitely zero). Unlike sp_forward (a dependency analysis), this respects multiplicative annihilation and nonzero constants. Default is the sound fallback: all active.

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 3015 of file function_internal.cpp.

3016  {
3017  // Sound fallback: we cannot prove any output zero, so mark everything active
3018  for (casadi_int oind=0; oind<n_out_; ++oind) {
3019  if (res[oind]==nullptr) continue;
3020  std::fill_n(res[oind], nnz_out(oind), ~static_cast<bvec_t>(0));
3021  }
3022  return 0;
3023  }
unsigned long long bvec_t

References casadi::FunctionInternal::n_out_, and casadi::FunctionInternal::nnz_out().

◆ eval_dm()

std::vector< DM > casadi::FunctionInternal::eval_dm ( const std::vector< DM > &  arg) const
virtualinherited

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

Reimplemented in casadi::CallbackInternal.

Definition at line 2167 of file function_internal.cpp.

2167  {
2168  casadi_error("'eval_dm' not defined for " + class_name());
2169  }

References casadi::SharedObjectInternal::class_name().

Referenced by casadi::FunctionInternal::eval().

◆ eval_gen() [1/3]

int casadi::FunctionInternal::eval_gen ( const bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t w,
void *  mem,
bool  always_inline,
bool  never_inline 
) const
inlineinherited

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

Definition at line 445 of file function_internal.hpp.

446  {
447  return sp_forward(arg, res, iw, w, mem);
448  }
virtual int sp_forward(const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, void *mem) const
Propagate sparsity forward.

◆ eval_gen() [2/3]

int casadi::FunctionInternal::eval_gen ( const double **  arg,
double **  res,
casadi_int *  iw,
double *  w,
void *  mem,
bool  always_inline,
bool  never_inline 
) const
inherited

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

Definition at line 965 of file function_internal.cpp.

967  {
968  casadi_int dump_id = (dump_in_ || dump_out_ || dump_) ? get_dump_id() : 0;
969  if (dump_in_) dump_in(dump_id, arg);
970  if (dump_ && dump_id==0) dump();
971  if (print_in_) print_in(uout(), arg, false);
972  auto *m = static_cast<ProtoFunctionMemory*>(mem);
973 
974  // Avoid memory corruption
975  for (casadi_int i=0;i<n_in_;++i) {
976  casadi_assert(arg[i]==nullptr || arg[i]+nnz_in(i)<=w || arg[i]>=w+sz_w(),
977  "Memory corruption detected for input " + name_in_[i] + ".\n"+
978  "arg[" + str(i) + "] " + str(arg[i]) + "-" + str(arg[i]+nnz_in(i)) +
979  " intersects with w " + str(w)+"-"+str(w+sz_w())+".");
980  }
981  for (casadi_int i=0;i<n_out_;++i) {
982  casadi_assert(res[i]==nullptr || res[i]+nnz_out(i)<=w || res[i]>=w+sz_w(),
983  "Memory corruption detected for output " + name_out_[i]);
984  }
985  // Reset statistics
986  for (auto&& s : m->fstats) s.second.reset();
987  if (m->t_total) m->t_total->tic();
988  int ret;
989  if (eval_) {
990  auto *m = static_cast<FunctionMemory*>(mem);
991  m->stats_available = true;
992  int mem_ = 0;
993  if (checkout_) {
994 #ifdef CASADI_WITH_THREAD
995  std::lock_guard<std::mutex> lock(mtx_);
996 #endif //CASADI_WITH_THREAD
997  mem_ = checkout_();
998  }
999  ret = eval_(arg, res, iw, w, mem_);
1000  if (release_) {
1001 #ifdef CASADI_WITH_THREAD
1002  std::lock_guard<std::mutex> lock(mtx_);
1003 #endif //CASADI_WITH_THREAD
1004  release_(mem_);
1005  }
1006  } else {
1007  ret = eval(arg, res, iw, w, mem);
1008  }
1009  if (m->t_total) m->t_total->toc();
1010  // Show statistics
1011  print_time(m->fstats);
1012 
1013  if (dump_out_) dump_out(dump_id, res);
1014  if (print_out_) print_out(uout(), res, false);
1015  // Check all outputs for NaNs
1016  if (regularity_check_) {
1017  for (casadi_int i = 0; i < n_out_; ++i) {
1018  // Skip of not calculated
1019  if (!res[i]) continue;
1020  // Loop over nonzeros
1021  casadi_int nnz = this->nnz_out(i);
1022  for (casadi_int nz = 0; nz < nnz; ++nz) {
1023  if (isnan(res[i][nz]) || isinf(res[i][nz])) {
1024  // Throw readable error message
1025  casadi_error(str(res[i][nz]) + " detected for output " + name_out_[i] + " at "
1026  + sparsity_out(i).repr_el(nz));
1027  }
1028  }
1029  }
1030  }
1031  return ret;
1032  }
void print_in(std::ostream &stream, const double **arg, bool truncate) const
Print inputs.
casadi_release_t release_
Release redirected to a C function.
virtual int eval(const double **arg, double **res, casadi_int *iw, double *w, void *mem) const
Evaluate numerically.
eval_t eval_
Numerical evaluation redirected to a C function.
casadi_checkout_t checkout_
Checkout redirected to a C function.
void print_out(std::ostream &stream, double **res, bool truncate) const
Print outputs.
void print_time(const std::map< std::string, FStats > &fstats) const
Print timing statistics.
std::ostream & uout()

References casadi::FunctionInternal::checkout_, casadi::FunctionInternal::dump_, casadi::FunctionInternal::dump_in_, casadi::FunctionInternal::dump_out_, casadi::FunctionInternal::eval(), casadi::FunctionInternal::eval_, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::print_in(), casadi::FunctionInternal::print_in_, casadi::FunctionInternal::print_out(), casadi::FunctionInternal::print_out_, casadi::ProtoFunction::print_time(), casadi::ProtoFunction::regularity_check_, casadi::FunctionInternal::release_, casadi::FunctionInternal::sparsity_out(), casadi::FunctionMemory::stats_available, casadi::str(), casadi::FunctionInternal::sz_w(), and casadi::uout().

Referenced by casadi::FunctionInternal::call_gen().

◆ eval_gen() [3/3]

int casadi::FunctionInternal::eval_gen ( const SXElem **  arg,
SXElem **  res,
casadi_int *  iw,
SXElem w,
void *  mem,
bool  always_inline,
bool  never_inline 
) const
inlineinherited

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

Definition at line 441 of file function_internal.hpp.

442  {
443  return eval_sx(arg, res, iw, w, mem, always_inline, never_inline);
444  }
virtual int eval_sx(const SXElem **arg, SXElem **res, casadi_int *iw, SXElem *w, void *mem, bool always_inline, bool never_inline) const
Evaluate with symbolic scalars.

◆ eval_mx()

void casadi::FunctionInternal::eval_mx ( const MXVector arg,
MXVector res,
bool  always_inline,
bool  never_inline 
) const
virtualinherited

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 2386 of file function_internal.cpp.

2387  {
2388 
2389  always_inline = always_inline || always_inline_;
2390  never_inline = never_inline || never_inline_;
2391 
2392  // The code below creates a call node, to inline, wrap in an MXFunction
2393  if (always_inline) {
2394  casadi_assert(!never_inline, "Inconsistent options for " + str(name_));
2395  wrap().call(arg, res, true);
2396  return;
2397  }
2398 
2399  // Create a call-node
2400  res = Call::create(self(), arg);
2401  }
static std::vector< MX > create(const Function &fcn, const std::vector< MX > &arg)
Create function call node.
Function wrap() const
Wrap in an Function instance consisting of only one MX call.
void call(const std::vector< DM > &arg, std::vector< DM > &res, bool always_inline=false, bool never_inline=false) const
Evaluate the function symbolically or numerically.
Definition: function.cpp:509

References casadi::FunctionInternal::always_inline_, casadi::Function::call(), casadi::Call::create(), casadi::ProtoFunction::name_, casadi::FunctionInternal::never_inline_, casadi::str(), and casadi::FunctionInternal::wrap().

Referenced by casadi::FunctionInternal::call_gen(), casadi::MXFunction::eval_mx(), and casadi::SXFunction::eval_mx().

◆ eval_sx()

int casadi::FunctionInternal::eval_sx ( const SXElem **  arg,
SXElem **  res,
casadi_int *  iw,
SXElem w,
void *  mem,
bool  always_inline,
bool  never_inline 
) const
virtualinherited

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

Reimplemented in casadi::SXFunction, casadi::Switch, casadi::MXFunction, casadi::MapSum, and casadi::Map.

Definition at line 2171 of file function_internal.cpp.

2173  {
2174 
2175  always_inline = always_inline || always_inline_;
2176  never_inline = never_inline || never_inline_;
2177 
2178  casadi_assert(!always_inline, "'eval_sx' not defined for " + class_name() +
2179  " in combination with always_inline true");
2180 
2181  return CallSX::eval_sx(self(), arg, res);
2182  }
static int eval_sx(const Function &f, const SXElem **arg, SXElem **res)
Definition: call_sx.hpp:63

References casadi::FunctionInternal::always_inline_, casadi::SharedObjectInternal::class_name(), casadi::CallSX::eval_sx(), and casadi::FunctionInternal::never_inline_.

Referenced by casadi::MXFunction::eval_sx(), and casadi::SXFunction::eval_sx().

◆ evaluate() [1/3]

casadi_int casadi::Blocksqp::evaluate ( BlocksqpMemory m,
const double *  xk,
double *  f,
double *  g 
) const

Definition at line 2796 of file blocksqp.cpp.

2798  {
2799  auto d_nlp = &m->d_nlp;
2800  m->arg[0] = xk; // x
2801  m->arg[1] = d_nlp->p; // p
2802  m->res[0] = f; // f
2803  m->res[1] = g; // g
2804  return calc_function(m, "nlp_fg");
2805  }

References casadi::OracleMemory::arg, casadi::OracleFunction::calc_function(), casadi::NlpsolMemory::d_nlp, and casadi::OracleMemory::res.

◆ evaluate() [2/3]

casadi_int casadi::Blocksqp::evaluate ( BlocksqpMemory m,
double *  exact_hess_lag 
) const

Definition at line 2807 of file blocksqp.cpp.

2809  {
2810  auto d_nlp = &m->d_nlp;
2811  static std::vector<double> ones;
2812  ones.resize(nx_);
2813  for (casadi_int i=0; i<nx_; ++i) ones[i] = 1.0;
2814  static std::vector<double> minus_lam_gk;
2815  minus_lam_gk.resize(ng_);
2816  // Langrange function in blocksqp is L = f - lambdaT * g, whereas + in casadi
2817  for (casadi_int i=0; i<ng_; ++i) minus_lam_gk[i] = -m->lam_gk[i];
2818  m->arg[0] = d_nlp->z; // x
2819  m->arg[1] = d_nlp->p; // p
2820  m->arg[2] = get_ptr(ones); // lam:f
2821  m->arg[3] = get_ptr(minus_lam_gk); // lam:g
2822  m->res[0] = exact_hess_lag; // hess:gamma:x:x
2823  return calc_function(m, "nlp_hess_l");;
2824  }

References casadi::OracleMemory::arg, casadi::OracleFunction::calc_function(), casadi::NlpsolMemory::d_nlp, casadi::get_ptr(), casadi::BlocksqpMemory::lam_gk, casadi::Nlpsol::ng_, casadi::Nlpsol::nx_, and casadi::OracleMemory::res.

◆ evaluate() [3/3]

casadi_int casadi::Blocksqp::evaluate ( BlocksqpMemory m,
double *  f,
double *  g,
double *  grad_f,
double *  jac_g 
) const

Definition at line 2782 of file blocksqp.cpp.

2785  {
2786  auto d_nlp = &m->d_nlp;
2787  m->arg[0] = d_nlp->z; // x
2788  m->arg[1] = d_nlp->p; // p
2789  m->res[0] = f; // f
2790  m->res[1] = g; // g
2791  m->res[2] = grad_f; // grad:f:x
2792  m->res[3] = jac_g; // jac:g:x
2793  return calc_function(m, "nlp_gf_jg");
2794  }

References casadi::OracleMemory::arg, casadi::OracleFunction::calc_function(), casadi::NlpsolMemory::d_nlp, and casadi::OracleMemory::res.

Referenced by calcHessianUpdateExact(), feasibilityRestorationPhase(), filterLineSearch(), fullstep(), kktErrorReduction(), run(), and secondOrderCorrection().

◆ expand()

void casadi::OracleFunction::expand ( )
inherited

Definition at line 455 of file oracle_function.cpp.

455  {
456  oracle_ = oracle_.expand();
457 }
Function expand() const
Expand a function to SX.
Definition: function.cpp:312

References casadi::Function::expand(), and casadi::OracleFunction::oracle_.

Referenced by casadi::Nlpsol::init(), and casadi::OracleFunction::init().

◆ export_code()

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

◆ factory()

Function casadi::FunctionInternal::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
virtualinherited

◆ feasibilityRestorationHeuristic()

casadi_int casadi::Blocksqp::feasibilityRestorationHeuristic ( BlocksqpMemory m) const

Try to (partly) improve constraint violation by satisfying the (pseudo) continuity constraints, i.e. do a single shooting iteration with the current controls and measurement weights q and w

Definition at line 1636 of file blocksqp.cpp.

1636  {
1637  auto d_nlp = &m->d_nlp;
1638  m->nRestHeurCalls++;
1639 
1640  // Call problem specific heuristic to reduce constraint violation.
1641  // For shooting methods that means setting consistent values for
1642  // shooting nodes by one forward integration.
1643  for (casadi_int k=0; k<nx_; k++) // input: last successful step
1644  m->trial_xk[k] = d_nlp->z[k];
1645 
1646  // FIXME(@jaeandersson) Not implemented
1647  return -1;
1648  }

References casadi::NlpsolMemory::d_nlp, casadi::BlocksqpMemory::nRestHeurCalls, casadi::Nlpsol::nx_, and casadi::BlocksqpMemory::trial_xk.

Referenced by run().

◆ feasibilityRestorationPhase()

casadi_int casadi::Blocksqp::feasibilityRestorationPhase ( BlocksqpMemory m) const

Minimize constraint violation by solving an NLP with minimum norm objective

"The dreaded restoration phase" – Nick Gould

Definition at line 1434 of file blocksqp.cpp.

1434  {
1435  auto d_nlp = &m->d_nlp;
1436  // No Feasibility restoration phase
1437  if (!restore_feas_) return -1;
1438 
1439  m->nRestPhaseCalls++;
1440 
1441  casadi_int ret, info;
1442  casadi_int maxRestIt = 100;
1443  casadi_int warmStart;
1444  double cNormTrial, objTrial, lStpNorm;
1445 
1446 
1447  // Create Input for the minimum norm NLP
1448  DMDict solver_in;
1449 
1450  // The reference point is the starting value for the restoration phase
1451  std::vector<double> in_x0(d_nlp->z, d_nlp->z+nx_);
1452 
1453  // Initialize slack variables such that the constraints are feasible
1454  for (casadi_int i=0; i<ng_; i++) {
1455  if (m->gk[i] <= d_nlp->lbz[i+nx_])
1456  in_x0.push_back(m->gk[i] - d_nlp->lbz[i+nx_]);
1457  else if (m->gk[i] > d_nlp->ubz[i+nx_])
1458  in_x0.push_back(m->gk[i] - d_nlp->ubz[i+nx_]);
1459  else
1460  in_x0.push_back(0.0);
1461  }
1462 
1463  // Add current iterate xk to parameter p
1464  std::vector<double> in_p(d_nlp->p, d_nlp->p+np_);
1465  std::vector<double> in_p2(d_nlp->z, d_nlp->z+nx_);
1466  in_p.insert(in_p.end(), in_p2.begin(), in_p2.end());
1467 
1468  // Set bounds for variables
1469  std::vector<double> in_lbx(d_nlp->lbz, d_nlp->lbz+nx_);
1470  std::vector<double> in_ubx(d_nlp->ubz, d_nlp->ubz+nx_);
1471  for (casadi_int i=0; i<ng_; i++) {
1472  in_lbx.push_back(-inf);
1473  in_ubx.push_back(inf);
1474  }
1475 
1476  // Set bounds for constraints
1477  std::vector<double> in_lbg(d_nlp->lbz+nx_, d_nlp->lbz+nx_+ng_);
1478  std::vector<double> in_ubg(d_nlp->ubz+nx_, d_nlp->ubz+nx_+ng_);
1479 
1480  solver_in["x0"] = in_x0;
1481  solver_in["p"] = in_p;
1482  solver_in["lbx"] = in_lbx;
1483  solver_in["ubx"] = in_ubx;
1484  solver_in["lbg"] = in_lbg;
1485  solver_in["ubg"] = in_ubg;
1486 
1487  /*
1488 
1489  Consider the following simple call:
1490  auto solver_out = rp_solver_(solver_in);
1491 
1492  This call in fact allocates memory,
1493  calls a memory-less eval(),
1494  and clears up the memory again.
1495 
1496  Since we want to access the memory later on,
1497  we need to unravel the simple call into its parts,
1498  and avoid the memory cleanup
1499 
1500  */
1501 
1502  // perform first iteration for the minimum norm NLP
1503 
1504  // Get the number of inputs and outputs
1505  int n_in = rp_solver_.n_in();
1506  int n_out = rp_solver_.n_out();
1507 
1508  // Get default inputs
1509  std::vector<DM> arg_v(n_in);
1510  for (casadi_int i=0; i<arg_v.size(); i++)
1511  arg_v[i] = DM::repmat(rp_solver_.default_in(i), rp_solver_.size1_in(i), 1);
1512 
1513  // Assign provided inputs
1514  for (auto&& e : solver_in) arg_v.at(rp_solver_.index_in(e.first)) = e.second;
1515 
1516  // Check sparsities
1517  for (casadi_int i=0; i<arg_v.size(); i++)
1518  casadi_assert_dev(arg_v[i].sparsity()==rp_solver_.sparsity_in(i));
1519 
1520  // Allocate results
1521  std::vector<DM> res(n_out);
1522  for (casadi_int i=0; i<n_out; i++) {
1523  if (res[i].sparsity()!=rp_solver_.sparsity_out(i))
1524  res[i] = DM::zeros(rp_solver_.sparsity_out(i));
1525  }
1526 
1527  // Allocate temporary memory if needed
1528  std::vector<casadi_int> iw_tmp(rp_solver_.sz_iw());
1529  std::vector<double> w_tmp(rp_solver_.sz_w());
1530 
1531  // Get pointers to input arguments
1532  std::vector<const double*> argp(rp_solver_.sz_arg());
1533  for (casadi_int i=0; i<n_in; ++i) argp[i] = get_ptr(arg_v[i]);
1534 
1535  // Get pointers to output arguments
1536  std::vector<double*> resp(rp_solver_.sz_res());
1537  for (casadi_int i=0; i<n_out; i++) resp[i] = get_ptr(res[i]);
1538 
1539  void* mem2 = rp_solver_.memory(0);
1540 
1541  // perform The m
1542  rp_solver_->eval(get_ptr(argp), get_ptr(resp), get_ptr(iw_tmp), get_ptr(w_tmp), mem2);
1543 
1544  // Get BlocksqpMemory and Blocksqp from restoration phase
1545  auto m2 = static_cast<BlocksqpMemory*>(mem2);
1546  const Blocksqp* bp = static_cast<const Blocksqp*>(rp_solver_.get());
1547  ret = m2->ret_;
1548 
1549  warmStart = 1;
1550  for (casadi_int it=0; it<maxRestIt; it++) {
1551  // One iteration for minimum norm NLP
1552  if (it > 0)
1553  ret = bp->run(m2, 1, warmStart);
1554 
1555  // If restMethod yields error, stop restoration phase
1556  if (ret == -1)
1557  break;
1558 
1559  // Get new xi from the restoration phase
1560  for (casadi_int i=0; i<nx_; i++)
1561  m->trial_xk[i] = m2->d_nlp.z[i];
1562 
1563  // Compute objective at trial point
1564  info = evaluate(m, m->trial_xk, &objTrial, m->gk);
1565  m->nFunCalls++;
1566  cNormTrial = lInfConstraintNorm(m, m->trial_xk, m->gk);
1567  if ( info != 0 || objTrial < obj_lo_ || objTrial > obj_up_ ||
1568  !(objTrial == objTrial) || !(cNormTrial == cNormTrial) )
1569  continue;
1570 
1571  // Is this iterate acceptable for the filter?
1572  if (!pairInFilter(m, cNormTrial, objTrial)) {
1573  // success
1574  print("Found a point acceptable for the filter.\n");
1575  ret = 0;
1576  break;
1577  }
1578 
1579  // If minimum norm NLP has converged, declare local infeasibility
1580  if (m2->tol < opttol_ && m2->cNormS < nlinfeastol_) {
1581  ret = 1;
1582  break;
1583  }
1584  }
1585 
1586  // Success or locally infeasible
1587  if (ret == 0 || ret == 1) {
1588  // Store the infinity norm of the multiplier step
1589  m->lambdaStepNorm = 0.0;
1590  // Compute restoration step
1591  for (casadi_int k=0; k<nx_; k++) {
1592  m->dxk[k] = d_nlp->z[k];
1593 
1594  d_nlp->z[k] = m->trial_xk[k];
1595 
1596  // Store lInf norm of dual step
1597  if ((lStpNorm = fabs(m2->lam_xk[k] - m->lam_xk[k])) > m->lambdaStepNorm)
1598  m->lambdaStepNorm = lStpNorm;
1599  m->lam_xk[k] = m2->lam_xk[k];
1600  m->lam_qp[k] = m2->lam_qp[k];
1601 
1602  m->dxk[k] -= d_nlp->z[k];
1603  }
1604  for (casadi_int k=0; k<ng_; k++) {
1605  // skip the dual variables for the slack variables in the restoration problem
1606  if ((lStpNorm = fabs(m2->lam_gk[k] - m->lam_gk[k])) > m->lambdaStepNorm)
1607  m->lambdaStepNorm = lStpNorm;
1608  m->lam_gk[k] = m2->lam_gk[k];
1609  m->lam_qp[k] = m2->lam_qp[nx_+ng_+k];
1610  }
1611  m->alpha = 1.0;
1612  m->nSOCS = 0;
1613 
1614  // reset reduced step counter
1615  m->reducedStepCount = 0;
1616 
1617  // reset Hessian and limited memory information
1618  resetHessian(m);
1619  }
1620 
1621  if (ret == 1) {
1623  updateStats(m);
1624  print("The problem seems to be locally infeasible. Infeasibilities minimized.\n");
1625  }
1626 
1627  return ret;
1628  }
void printProgress(BlocksqpMemory *m) const
Print one line of output to stdout about the current iteration.
Definition: blocksqp.cpp:2555
bool pairInFilter(BlocksqpMemory *m, double cNorm, double obj) const
Definition: blocksqp.cpp:1698
void updateStats(BlocksqpMemory *m) const
Definition: blocksqp.cpp:2617
const Sparsity & sparsity_out(casadi_int ind) const
Get sparsity of a given output.
Definition: function.cpp:1183
FunctionInternal * get() const
Definition: function.cpp:505
casadi_int size1_in(casadi_int ind) const
Get input dimension.
Definition: function.cpp:979
casadi_int index_in(const std::string &name) const
Find the index for a string describing a particular entry of an input scheme.
Definition: function.cpp:1121
const Sparsity & sparsity_in(casadi_int ind) const
Get sparsity of a given input.
Definition: function.cpp:1167
void * memory(int ind) const
Get memory object.
Definition: function.cpp:1978
double default_in(casadi_int ind) const
Get default input value.
Definition: function.cpp:1677
static MatType repmat(const MatType &x, casadi_int n, casadi_int m=1)
std::map< std::string, DM > DMDict
Definition: dm_fwd.hpp:36

References casadi::BlocksqpMemory::alpha, casadi::NlpsolMemory::d_nlp, casadi::Function::default_in(), casadi::BlocksqpMemory::dxk, casadi::FunctionInternal::eval(), evaluate(), casadi::Function::get(), casadi::get_ptr(), casadi::BlocksqpMemory::gk, casadi::Function::index_in(), casadi::inf, casadi::FunctionInternal::info(), casadi::BlocksqpMemory::lam_gk, casadi::BlocksqpMemory::lam_qp, casadi::BlocksqpMemory::lam_xk, casadi::BlocksqpMemory::lambdaStepNorm, lInfConstraintNorm(), casadi::Function::memory(), casadi::Function::n_in(), casadi::Function::n_out(), casadi::BlocksqpMemory::nFunCalls, casadi::Nlpsol::ng_, nlinfeastol_, casadi::Nlpsol::np_, casadi::BlocksqpMemory::nRestPhaseCalls, casadi::BlocksqpMemory::nSOCS, casadi::Nlpsol::nx_, obj_up_, opttol_, pairInFilter(), casadi::ProtoFunction::print(), print_iteration_, printProgress(), casadi::BlocksqpMemory::reducedStepCount, casadi::SparsityInterface< MatType >::repmat(), resetHessian(), restore_feas_, rp_solver_, run(), casadi::Function::size1_in(), casadi::Function::sparsity_in(), casadi::Function::sparsity_out(), casadi::Function::sz_arg(), casadi::Function::sz_iw(), casadi::Function::sz_res(), casadi::Function::sz_w(), casadi::BlocksqpMemory::trial_xk, updateStats(), and casadi::GenericMatrix< MatType >::zeros().

Referenced by run().

◆ filterLineSearch()

casadi_int casadi::Blocksqp::filterLineSearch ( BlocksqpMemory m) const

Backtracking line search based on a filter as described in Ipopt paper (Waechter 2006)

Definition at line 1217 of file blocksqp.cpp.

1217  {
1218  auto d_nlp = &m->d_nlp;
1219  double alpha = 1.0;
1220  double cNormTrial=0, objTrial, dfTdeltaXi=0;
1221 
1222  // Compute ||constr(xi)|| at old point
1223  double cNorm = lInfConstraintNorm(m, d_nlp->z, m->gk);
1224 
1225  // Backtracking line search
1226  casadi_int k;
1227  for (k=0; k<max_line_search_; k++) {
1228  // Compute new trial point
1229  for (casadi_int i=0; i<nx_; i++)
1230  m->trial_xk[i] = d_nlp->z[i] + alpha * m->dxk[i];
1231 
1232  // Compute grad(f)^T * deltaXi
1233  dfTdeltaXi = 0.0;
1234  for (casadi_int i=0; i<nx_; i++)
1235  dfTdeltaXi += m->grad_fk[i] * m->dxk[i];
1236 
1237  // Compute objective and at ||constr(trial_xk)||_1 at trial point
1238  casadi_int info = evaluate(m, m->trial_xk, &objTrial, m->gk);
1239  m->nFunCalls++;
1240  cNormTrial = lInfConstraintNorm(m, m->trial_xk, m->gk);
1241  // Reduce step if evaluation fails, if lower bound is violated or if objective is NaN
1242  if (info != 0 || objTrial < obj_lo_ || objTrial > obj_up_
1243  || !(objTrial == objTrial) || !(cNormTrial == cNormTrial)) {
1244  // evaluation error, reduce stepsize
1245  reduceStepsize(m, &alpha);
1246  continue;
1247  }
1248 
1249  // Check acceptability to the filter
1250  if (pairInFilter(m, cNormTrial, objTrial)) {
1251  // Trial point is in the prohibited region defined by
1252  // the filter, try second order correction
1253  if (secondOrderCorrection(m, cNorm, cNormTrial, dfTdeltaXi, 0, k)) {
1254  break; // SOC yielded suitable alpha, stop
1255  } else {
1256  reduceStepsize(m, &alpha);
1257  continue;
1258  }
1259  }
1260 
1261  // Check sufficient decrease, case I:
1262  // If we are (almost) feasible and a "switching condition" is satisfied
1263  // require sufficient progress in the objective instead of bi-objective condition
1264  if (cNorm <= theta_min_) {
1265  // Switching condition, part 1: grad(f)^T * deltaXi < 0 ?
1266  if (dfTdeltaXi < 0)
1267  // Switching condition, part 2: alpha * (- grad(f)^T * deltaXi)**sF
1268  // > delta * cNorm**sTheta ?
1269  if (alpha * pow((-dfTdeltaXi), s_f_)
1270  > delta_ * pow(cNorm, s_theta_)) {
1271  // Switching conditions hold: Require satisfaction of Armijo condition for objective
1272  if (objTrial > m->obj + eta_*alpha*dfTdeltaXi) {
1273  // Armijo condition violated, try second order correction
1274  if (secondOrderCorrection(m, cNorm, cNormTrial, dfTdeltaXi, 1, k)) {
1275  break; // SOC yielded suitable alpha, stop
1276  } else {
1277  reduceStepsize(m, &alpha);
1278  continue;
1279  }
1280  } else {
1281  // found suitable alpha, stop
1282  acceptStep(m, alpha);
1283  break;
1284  }
1285  }
1286  }
1287 
1288  // Check sufficient decrease, case II:
1289  // Bi-objective (filter) condition
1290  if (cNormTrial < (1.0 - gamma_theta_) * cNorm
1291  || objTrial < m->obj - gamma_f_ * cNorm) {
1292  // found suitable alpha, stop
1293  acceptStep(m, alpha);
1294  break;
1295  } else {
1296  // Trial point is dominated by current point, try second order correction
1297  if (secondOrderCorrection(m, cNorm, cNormTrial, dfTdeltaXi, 0, k)) {
1298  break; // SOC yielded suitable alpha, stop
1299  } else {
1300  reduceStepsize(m, &alpha);
1301  continue;
1302  }
1303  }
1304  }
1305 
1306  // No step could be found by the line search
1307  if (k == max_line_search_) return 1;
1308 
1309  // Augment the filter if switching condition or Armijo condition does not hold
1310  if (dfTdeltaXi >= 0) {
1311  augmentFilter(m, cNormTrial, objTrial);
1312  } else if (alpha * pow((-dfTdeltaXi), s_f_) > delta_ * pow(cNorm, s_theta_)) {
1313  // careful with neg. exponents!
1314  augmentFilter(m, cNormTrial, objTrial);
1315  } else if (objTrial <= m->obj + eta_*alpha*dfTdeltaXi) {
1316  augmentFilter(m, cNormTrial, objTrial);
1317  }
1318 
1319  return 0;
1320  }
void reduceStepsize(BlocksqpMemory *m, double *alpha) const
Definition: blocksqp.cpp:1146
bool secondOrderCorrection(BlocksqpMemory *m, double cNorm, double cNormTrial, double dfTdeltaXi, bool swCond, casadi_int it) const
Definition: blocksqp.cpp:1332
void augmentFilter(BlocksqpMemory *m, double cNorm, double obj) const
Definition: blocksqp.cpp:1742

References acceptStep(), augmentFilter(), casadi::NlpsolMemory::d_nlp, delta_, casadi::BlocksqpMemory::dxk, eta_, evaluate(), gamma_f_, gamma_theta_, casadi::BlocksqpMemory::gk, casadi::BlocksqpMemory::grad_fk, casadi::FunctionInternal::info(), lInfConstraintNorm(), max_line_search_, casadi::BlocksqpMemory::nFunCalls, casadi::Nlpsol::nx_, casadi::BlocksqpMemory::obj, obj_up_, pairInFilter(), reduceStepsize(), s_f_, s_theta_, secondOrderCorrection(), theta_min_, and casadi::BlocksqpMemory::trial_xk.

Referenced by run().

◆ finalize()

void casadi::OracleFunction::finalize ( )
overridevirtualinherited

Reimplemented from casadi::FunctionInternal.

Definition at line 122 of file oracle_function.cpp.

122  {
123  if (post_expand_) {
124  for (auto&& e : all_functions_) {
125  Function& fcn = e.second.f;
126  fcn = fcn.expand();
127  }
128  }
129 
130  // Allocate space for (parallel) evaluations
131  // Lifted from set_function as max_num_threads_ is not known yet in that method
132  for (auto&& e : all_functions_) {
133  Function& fcn = e.second.f;
134  // Compute strides for multi threading
135  size_t sz_arg, sz_res, sz_iw, sz_w;
136  fcn.sz_work(sz_arg, sz_res, sz_iw, sz_w);
137  stride_arg_ = std::max(stride_arg_, sz_arg);
138  stride_res_ = std::max(stride_res_, sz_res);
139  stride_iw_ = std::max(stride_iw_, sz_iw);
140  stride_w_ = std::max(stride_w_, sz_w);
141  bool persistent = false;
142  alloc(fcn, persistent, max_num_threads_);
143  }
144 
145  // Set corresponding monitors
146  for (const std::string& fname : monitor_) {
147  auto it = all_functions_.find(fname);
148  if (it==all_functions_.end()) {
149  casadi_warning("Ignoring monitor '" + fname + "'."
150  " Available functions: " + join(get_function()) + ".");
151  } else {
152  if (it->second.monitored) casadi_warning("Duplicate monitor " + fname);
153  it->second.monitored = true;
154  }
155  }
156 
157  // Check specific options
158  for (auto&& i : specific_options_) {
159  if (all_functions_.find(i.first)==all_functions_.end())
160  casadi_warning("Ignoring specific_options entry '" + i.first+"'."
161  " Available functions: " + join(get_function()) + ".");
162  }
163 
164  // Recursive call
166 }
void finalize() override
Finalize the object creation.
void alloc(const Function &f, bool persistent=false, int num_threads=1)
Ensure work vectors long enough to evaluate function.
std::map< std::string, RegFun > all_functions_
std::vector< std::string > monitor_
std::string join(const std::vector< std::string > &l, const std::string &delim)

References casadi::OracleFunction::all_functions_, casadi::FunctionInternal::alloc(), casadi::Function::expand(), casadi::FunctionInternal::finalize(), casadi::OracleFunction::get_function(), casadi::join(), casadi::OracleFunction::max_num_threads_, casadi::OracleFunction::monitor_, casadi::OracleFunction::post_expand_, casadi::OracleFunction::specific_options_, casadi::OracleFunction::stride_arg_, casadi::OracleFunction::stride_iw_, casadi::OracleFunction::stride_res_, casadi::OracleFunction::stride_w_, casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), casadi::FunctionInternal::sz_w(), and casadi::Function::sz_work().

◆ find()

void casadi::OracleFunction::find ( std::map< FunctionInternal *, std::pair< Function, size_t > > &  all_fun,
casadi_int  max_depth 
) const
overridevirtualinherited

Reimplemented from casadi::FunctionInternal.

Definition at line 548 of file oracle_function.cpp.

549  {
550  // Call to base class
551  FunctionInternal::find(all_fun, max_depth);
552  for (auto&& e : all_functions_) {
553  add_embedded(all_fun, e.second.f, max_depth);
554  }
555 }
void add_embedded(std::map< FunctionInternal *, std::pair< Function, size_t > > &all_fun, const Function &dep, casadi_int max_depth) const
virtual void find(std::map< FunctionInternal *, std::pair< Function, size_t > > &all_fun, casadi_int max_depth) const

References casadi::FunctionInternal::add_embedded(), casadi::OracleFunction::all_functions_, and casadi::FunctionInternal::find().

◆ format_time()

void casadi::ProtoFunction::format_time ( char *  buffer,
double  time 
) const
inherited

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

Definition at line 4059 of file function_internal.cpp.

4059  {
4060  // Always of width 8
4061  casadi_assert_dev(time>=0);
4062  double log_time = log10(time);
4063  int magn = static_cast<int>(floor(log_time));
4064  int iprefix = static_cast<int>(floor(log_time/3));
4065  if (iprefix<-4) {
4066  sprint(buffer, 10, " 0");
4067  return;
4068  }
4069  if (iprefix>=5) {
4070  sprint(buffer, 10, " inf");
4071  return;
4072  }
4073  char prefixes[] = "TGMk munp";
4074  char prefix = prefixes[4-iprefix];
4075 
4076  int rem = magn-3*iprefix;
4077  double time_normalized = time/pow(10, 3*iprefix);
4078 
4079  if (rem==0) {
4080  sprint(buffer, 10, " %1.2f%cs", time_normalized, prefix);
4081  } else if (rem==1) {
4082  sprint(buffer, 10, " %2.2f%cs", time_normalized, prefix);
4083  } else {
4084  sprint(buffer, 10, "%3.2f%cs", time_normalized, prefix);
4085  }
4086  }
void sprint(char *buf, size_t buf_sz, const char *fmt,...) const
C-style formatted printing to string.

References casadi::ProtoFunction::sprint().

Referenced by casadi::ProtoFunction::print_time().

◆ forward()

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

forward(nfwd) returns a cached instance if available, and calls Function get_forward(casadi_int nfwd) if no cached version is available.

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

Definition at line 2220 of file function_internal.cpp.

2220  {
2221  casadi_assert_dev(nfwd>=0);
2222  // Used wrapped function if forward not available
2223  if (!enable_forward_ && !enable_fd_) {
2224  // Derivative information must be available
2225  casadi_assert(has_derivative(), "Derivatives cannot be calculated for " + name_);
2226  return wrap().forward(nfwd);
2227  }
2228  // Retrieve/generate cached
2229  Function f;
2230  std::string fname = forward_name(name_, nfwd);
2231  if (!incache(fname, f)) {
2232  casadi_int i;
2233  // Prefix to be used for forward seeds, sensitivities
2234  std::string pref = diff_prefix("fwd");
2235  // Names of inputs
2236  std::vector<std::string> inames;
2237  for (i=0; i<n_in_; ++i) inames.push_back(name_in_[i]);
2238  for (i=0; i<n_out_; ++i) inames.push_back("out_" + name_out_[i]);
2239  for (i=0; i<n_in_; ++i) inames.push_back(pref + name_in_[i]);
2240  // Names of outputs
2241  std::vector<std::string> onames;
2242  for (i=0; i<n_out_; ++i) onames.push_back(pref + name_out_[i]);
2243  // Options
2245  if (enable_forward_) {
2246  opts = combine(opts, generate_options("forward"));
2247  } else {
2248  opts = combine(opts, FunctionInternal::generate_options("forward"));
2249  }
2250  opts["derivative_of"] = self();
2251  // Generate derivative function
2252  casadi_assert_dev(enable_forward_ || enable_fd_);
2253  if (enable_forward_) {
2254  f = get_forward(nfwd, fname, inames, onames, opts);
2255  } else {
2256  opts = combine(opts, fd_options_);
2257  // Get FD method
2258  if (fd_method_.empty() || fd_method_=="central") {
2259  f = Function::create(new CentralDiff(fname, nfwd), opts);
2260  } else if (fd_method_=="forward") {
2261  f = Function::create(new ForwardDiff(fname, nfwd), opts);
2262  } else if (fd_method_=="backward") {
2263  f = Function::create(new BackwardDiff(fname, nfwd), opts);
2264  } else if (fd_method_=="smoothing") {
2265  f = Function::create(new Smoothing(fname, nfwd), opts);
2266  } else {
2267  casadi_error("Unknown 'fd_method': " + fd_method_);
2268  }
2269  }
2270  // Consistency check for inputs
2271  casadi_assert_dev(f.n_in()==n_in_ + n_out_ + n_in_);
2272  casadi_int ind=0;
2273  for (i=0; i<n_in_; ++i) f.assert_size_in(ind++, size1_in(i), size2_in(i));
2274  for (i=0; i<n_out_; ++i) f.assert_size_in(ind++, size1_out(i), size2_out(i));
2275  for (i=0; i<n_in_; ++i) f.assert_size_in(ind++, size1_in(i), nfwd*size2_in(i));
2276  // Consistency check for outputs
2277  casadi_assert_dev(f.n_out()==n_out_);
2278  for (i=0; i<n_out_; ++i) f.assert_sparsity_out(i, sparsity_out(i), nfwd);
2279  // Save to cache
2280  tocache_if_missing(f);
2281  }
2282  return f;
2283  }
std::string diff_prefix(const std::string &prefix) const
Determine prefix for differentiated functions.
casadi_int size1_out(casadi_int ind) const
Input/output dimensions.
Dict generate_options(const std::string &target) const override
Reconstruct options dict.
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.
Function forward(casadi_int nfwd) const
Get a function that calculates nfwd forward derivatives.
Definition: function.cpp:1324
static Function create(FunctionInternal *node)
Create from node.
Definition: function.cpp:488

References casadi::Function::assert_size_in(), casadi::Function::assert_sparsity_out(), casadi::combine(), casadi::Function::create(), casadi::FunctionInternal::der_options_, casadi::FunctionInternal::diff_prefix(), casadi::FunctionInternal::enable_fd_, casadi::FunctionInternal::enable_forward_, casadi::FunctionInternal::fd_method_, casadi::FunctionInternal::fd_options_, casadi::Function::forward(), casadi::FunctionInternal::forward_name(), casadi::FunctionInternal::forward_options_, casadi::FunctionInternal::generate_options(), casadi::FunctionInternal::get_forward(), casadi::FunctionInternal::has_derivative(), casadi::FunctionInternal::incache(), casadi::Function::n_in(), casadi::FunctionInternal::n_in_, casadi::Function::n_out(), casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::size1_in(), casadi::FunctionInternal::size1_out(), casadi::FunctionInternal::size2_in(), casadi::FunctionInternal::size2_out(), casadi::FunctionInternal::sparsity_out(), casadi::FunctionInternal::tocache_if_missing(), and casadi::FunctionInternal::wrap().

Referenced by casadi::FunctionInternal::call_forward(), and casadi::Function::forward().

◆ forward_name()

static std::string casadi::FunctionInternal::forward_name ( const std::string &  fcn,
casadi_int  nfwd 
)
inlinestaticinherited

◆ free_mem()

void casadi::Blocksqp::free_mem ( void *  mem) const
inlineoverridevirtual

Reimplemented from casadi::Nlpsol.

Definition at line 183 of file blocksqp.hpp.

183 { delete static_cast<BlocksqpMemory*>(mem);}

◆ free_mx()

std::vector< MX > casadi::FunctionInternal::free_mx ( ) const
virtualinherited

Reimplemented in casadi::MXFunction.

Definition at line 3566 of file function_internal.cpp.

3566  {
3567  casadi_error("'free_mx' only defined for 'MXFunction'");
3568  }

◆ free_sx()

std::vector< SX > casadi::FunctionInternal::free_sx ( ) const
virtualinherited

Reimplemented in casadi::SXFunction.

Definition at line 3570 of file function_internal.cpp.

3570  {
3571  casadi_error("'free_sx' only defined for 'SXFunction'");
3572  }

◆ from_compact()

Sparsity casadi::FunctionInternal::from_compact ( casadi_int  oind,
casadi_int  iind,
const Sparsity sp 
) const
inherited

Definition at line 1985 of file function_internal.cpp.

1986  {
1987  // Return value
1988  Sparsity r = sp;
1989  // Insert rows if sparse output
1990  if (numel_out(oind) != r.size1()) {
1991  casadi_assert_dev(r.size1() == nnz_out(oind));
1992  r.enlargeRows(numel_out(oind), sparsity_out(oind).find());
1993  }
1994  // Insert columns if sparse input
1995  if (numel_in(iind) != r.size2()) {
1996  casadi_assert_dev(r.size2() == nnz_in(iind));
1997  r.enlargeColumns(numel_in(iind), sparsity_in(iind).find());
1998  }
1999  // Return non-compact pattern
2000  return r;
2001  }
casadi_int numel_out() const
Number of input/output elements.
casadi_int numel_in() const
Number of input/output elements.

References casadi::Sparsity::enlargeColumns(), casadi::Sparsity::enlargeRows(), casadi::FunctionInternal::find(), casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::numel_in(), casadi::FunctionInternal::numel_out(), casadi::Sparsity::size1(), casadi::Sparsity::size2(), casadi::FunctionInternal::sparsity_in(), and casadi::FunctionInternal::sparsity_out().

Referenced by casadi::FunctionInternal::jac_sparsity().

◆ fullstep()

casadi_int casadi::Blocksqp::fullstep ( BlocksqpMemory m) const

Take a full Quasi-Newton step, except when integrator fails: xk = xk + deltaXi lambda = lambdaQP

Definition at line 1179 of file blocksqp.cpp.

1179  {
1180  auto d_nlp = &m->d_nlp;
1181  double alpha;
1182  double objTrial, cNormTrial;
1183 
1184  // Backtracking line search
1185  alpha = 1.0;
1186  for (casadi_int k=0; k<10; k++) {
1187  // Compute new trial point
1188  for (casadi_int i=0; i<nx_; i++)
1189  m->trial_xk[i] = d_nlp->z[i] + alpha * m->dxk[i];
1190 
1191  // Compute problem functions at trial point
1192  casadi_int info = evaluate(m, m->trial_xk, &objTrial, m->gk);
1193  m->nFunCalls++;
1194  cNormTrial = lInfConstraintNorm(m, m->trial_xk, m->gk);
1195  // Reduce step if evaluation fails, if lower bound is violated
1196  // or if objective or a constraint is NaN
1197  if (info != 0 || objTrial < obj_lo_ || objTrial > obj_up_
1198  || !(objTrial == objTrial) || !(cNormTrial == cNormTrial)) {
1199  print("info=%i, objTrial=%g\n", info, objTrial);
1200  // evaluation error, reduce stepsize
1201  reduceStepsize(m, &alpha);
1202  continue;
1203  } else {
1204  acceptStep(m, alpha);
1205  return 0;
1206  }
1207  }
1208  return 1;
1209  }

References acceptStep(), casadi::NlpsolMemory::d_nlp, casadi::BlocksqpMemory::dxk, evaluate(), casadi::BlocksqpMemory::gk, casadi::FunctionInternal::info(), lInfConstraintNorm(), casadi::BlocksqpMemory::nFunCalls, casadi::Nlpsol::nx_, obj_up_, casadi::ProtoFunction::print(), reduceStepsize(), and casadi::BlocksqpMemory::trial_xk.

Referenced by run().

◆ fwd_seed()

template<typename MatType >
std::vector< std::vector< MatType > > casadi::FunctionInternal::fwd_seed ( casadi_int  nfwd) const
inherited

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

Definition at line 1575 of file function_internal.hpp.

1576  {
1577  std::vector<std::vector<MatType>> fseed(nfwd);
1578  for (casadi_int dir=0; dir<nfwd; ++dir) {
1579  fseed[dir].resize(n_in_);
1580  for (casadi_int iind=0; iind<n_in_; ++iind) {
1581  std::string n = "f" + str(dir) + "_" + name_in_[iind];
1582  Sparsity sp = is_diff_in_[iind] ? sparsity_in(iind) : Sparsity(size_in(iind));
1583  fseed[dir][iind] = MatType::sym(n, sp);
1584  }
1585  }
1586  return fseed;
1587  }

References casadi::FunctionInternal::is_diff_in_, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::size_in(), casadi::FunctionInternal::sparsity_in(), and casadi::str().

◆ fwdViaJac()

bool casadi::FunctionInternal::fwdViaJac ( casadi_int  nfwd) const
virtualinherited

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

Definition at line 3181 of file function_internal.cpp.

3181  {
3182  if (!enable_forward_ && !enable_fd_) return true;
3183  if (jac_penalty_==-1) return false;
3184 
3185  // Heuristic 1: Jac calculated via forward mode likely cheaper
3186  if (jac_penalty_*static_cast<double>(nnz_in())<nfwd) return true;
3187 
3188  // Heuristic 2: Jac calculated via reverse mode likely cheaper
3189  double w = ad_weight();
3190  if (enable_reverse_ &&
3191  jac_penalty_*(1-w)*static_cast<double>(nnz_out())<w*static_cast<double>(nfwd))
3192  return true; // NOLINT
3193 
3194  return false;
3195  }

References casadi::FunctionInternal::ad_weight(), casadi::FunctionInternal::enable_fd_, casadi::FunctionInternal::enable_forward_, casadi::FunctionInternal::enable_reverse_, casadi::FunctionInternal::jac_penalty_, casadi::FunctionInternal::nnz_in(), and casadi::FunctionInternal::nnz_out().

Referenced by casadi::FunctionInternal::call_forward().

◆ generate_dependencies()

std::string casadi::OracleFunction::generate_dependencies ( const std::string &  fname,
const Dict opts 
) const
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 428 of file oracle_function.cpp.

429  {
430  CodeGenerator gen(fname, opts);
431  gen.add(oracle_);
432  for (auto&& e : all_functions_) {
433  if (e.second.jit) gen.add(e.second.f);
434  }
435  return gen.generate();
436 }

References casadi::CodeGenerator::add(), casadi::OracleFunction::all_functions_, casadi::CodeGenerator::generate(), and casadi::OracleFunction::oracle_.

Referenced by casadi::OracleFunction::jit_dependencies().

◆ generate_in()

void casadi::FunctionInternal::generate_in ( const std::string &  fname,
const double **  arg 
) const
inherited

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

Definition at line 794 of file function_internal.cpp.

794  {
795  // Set up output stream
796  auto of_ptr = Filesystem::ofstream_ptr(fname);
797  std::ostream& of = *of_ptr;
798  normalized_setup(of);
799 
800  // Encode each input
801  for (casadi_int i=0; i<n_in_; ++i) {
802  const double* v = arg[i];
803  for (casadi_int k=0;k<nnz_in(i);++k) {
804  normalized_out(of, v ? v[k] : 0);
805  of << std::endl;
806  }
807  }
808  }
static std::unique_ptr< std::ostream > ofstream_ptr(const std::string &path, std::ios_base::openmode mode=std::ios_base::out)
Definition: filesystem.cpp:115
void normalized_setup(std::istream &stream)
void normalized_out(std::ostream &stream, double val)

References casadi::FunctionInternal::n_in_, casadi::FunctionInternal::nnz_in(), casadi::normalized_out(), casadi::normalized_setup(), and casadi::Filesystem::ofstream_ptr().

◆ generate_lifted()

void casadi::FunctionInternal::generate_lifted ( Function vdef_fcn,
Function vinit_fcn 
) const
virtualinherited

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

Reimplemented in casadi::MXFunction.

Definition at line 3574 of file function_internal.cpp.

3575  {
3576  casadi_error("'generate_lifted' only defined for 'MXFunction'");
3577  }

◆ generate_options()

Dict casadi::FunctionInternal::generate_options ( const std::string &  target) const
overridevirtualinherited

Reimplemented from casadi::ProtoFunction.

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 389 of file function_internal.cpp.

389  {
390  Dict opts = ProtoFunction::generate_options(target);
391  opts["jac_penalty"] = jac_penalty_;
392  opts["user_data"] = user_data_;
393  opts["inputs_check"] = inputs_check_;
394  if (target!="tmp") opts["jit"] = jit_;
395  opts["jit_cleanup"] = jit_cleanup_;
396  opts["jit_serialize"] = jit_serialize_;
397  opts["compiler"] = compiler_plugin_;
398  opts["jit_options"] = jit_options_;
399  opts["jit_name"] = jit_base_name_;
400  opts["jit_temp_suffix"] = jit_temp_suffix_;
401  opts["ad_weight"] = ad_weight_;
402  opts["ad_weight_sp"] = ad_weight_sp_;
403  opts["always_inline"] = always_inline_;
404  opts["never_inline"] = never_inline_;
405  opts["max_num_dir"] = max_num_dir_;
406  if (target=="clone" || target=="tmp") {
407  opts["enable_forward"] = enable_forward_op_;
408  opts["enable_reverse"] = enable_reverse_op_;
409  opts["enable_jacobian"] = enable_jacobian_op_;
410  opts["enable_fd"] = enable_fd_op_;
411  opts["reverse_options"] = reverse_options_;
412  opts["forward_options"] = forward_options_;
413  opts["jacobian_options"] = jacobian_options_;
414  opts["der_options"] = der_options_;
415  opts["derivative_of"] = derivative_of_;
416  }
417  opts["fd_options"] = fd_options_;
418  opts["fd_method"] = fd_method_;
419  opts["print_in"] = print_in_;
420  opts["print_out"] = print_out_;
421  opts["print_canonical"] = print_canonical_;
422  opts["max_io"] = max_io_;
423  opts["dump_in"] = dump_in_;
424  opts["dump_out"] = dump_out_;
425  opts["dump_dir"] = dump_dir_;
426  opts["dump_format"] = dump_format_;
427  opts["dump"] = dump_;
428  if (target=="clone") {
429  opts["is_diff_in"] = is_diff_in_;
430  opts["is_diff_out"] = is_diff_out_;
431  }
432  if (target=="forward") {
433  opts["is_diff_in"] = join(is_diff_in_, is_diff_out_, is_diff_in_);
434  opts["is_diff_out"] = is_diff_out_;
435  }
436  if (target=="reverse") {
437  opts["is_diff_in"] = join(is_diff_in_, is_diff_out_, is_diff_out_);
438  opts["is_diff_out"] = is_diff_in_;
439  }
440  return opts;
441  }
std::string jit_serialize_
Serialize behaviour.
std::string compiler_plugin_
Just-in-time compiler.
void * user_data_
User-set field.
bool jit_
Use just-in-time compiler.
bool jit_temp_suffix_
Use a temporary name.
bool jit_cleanup_
Cleanup jit source file.
Function derivative_of_
If the function is the derivative of another function.
virtual Dict generate_options(const std::string &target) const
Reconstruct options dict.

References casadi::FunctionInternal::ad_weight_, casadi::FunctionInternal::ad_weight_sp_, casadi::FunctionInternal::always_inline_, casadi::FunctionInternal::compiler_plugin_, casadi::FunctionInternal::der_options_, casadi::FunctionInternal::derivative_of_, casadi::FunctionInternal::dump_, casadi::FunctionInternal::dump_dir_, casadi::FunctionInternal::dump_format_, casadi::FunctionInternal::dump_in_, casadi::FunctionInternal::dump_out_, casadi::FunctionInternal::enable_fd_op_, casadi::FunctionInternal::enable_forward_op_, casadi::FunctionInternal::enable_jacobian_op_, casadi::FunctionInternal::enable_reverse_op_, casadi::FunctionInternal::fd_method_, casadi::FunctionInternal::fd_options_, casadi::FunctionInternal::forward_options_, casadi::ProtoFunction::generate_options(), casadi::FunctionInternal::inputs_check_, casadi::FunctionInternal::is_diff_in_, casadi::FunctionInternal::is_diff_out_, casadi::FunctionInternal::jac_penalty_, casadi::FunctionInternal::jacobian_options_, casadi::FunctionInternal::jit_, casadi::FunctionInternal::jit_base_name_, casadi::FunctionInternal::jit_cleanup_, casadi::FunctionInternal::jit_options_, casadi::FunctionInternal::jit_serialize_, casadi::FunctionInternal::jit_temp_suffix_, casadi::join(), casadi::FunctionInternal::max_io_, casadi::FunctionInternal::max_num_dir_, casadi::FunctionInternal::never_inline_, casadi::FunctionInternal::print_canonical_, casadi::FunctionInternal::print_in_, casadi::FunctionInternal::print_out_, casadi::FunctionInternal::reverse_options_, and casadi::FunctionInternal::user_data_.

Referenced by casadi::Function::expand(), casadi::FunctionInternal::forward(), casadi::MXFunction::generate_options(), casadi::SXFunction::generate_options(), casadi::BlazingSplineFunction::get_jacobian(), and casadi::FunctionInternal::reverse().

◆ generate_out()

void casadi::FunctionInternal::generate_out ( const std::string &  fname,
double **  res 
) const
inherited

Definition at line 810 of file function_internal.cpp.

810  {
811  // Set up output stream
812  auto of_ptr = Filesystem::ofstream_ptr(fname);
813  std::ostream& of = *of_ptr;
814  normalized_setup(of);
815 
816  // Encode each input
817  for (casadi_int i=0; i<n_out_; ++i) {
818  const double* v = res[i];
819  for (casadi_int k=0;k<nnz_out(i);++k) {
820  normalized_out(of, v ? v[k] : std::numeric_limits<double>::quiet_NaN());
821  of << std::endl;
822  }
823  }
824  }

References casadi::FunctionInternal::n_out_, casadi::FunctionInternal::nnz_out(), casadi::normalized_out(), casadi::normalized_setup(), and casadi::Filesystem::ofstream_ptr().

◆ get_abstol()

virtual double casadi::FunctionInternal::get_abstol ( ) const
inlinevirtualinherited

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

Reimplemented in casadi::SundialsInterface, casadi::Smoothing, casadi::CentralDiff, and casadi::ForwardDiff.

Definition at line 1132 of file function_internal.hpp.

1132  {
1133  return eps;
1134  }
const double eps
Machine epsilon.
Definition: calculus.hpp:56

References casadi::eps.

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

◆ get_default_in()

double casadi::Nlpsol::get_default_in ( casadi_int  ind) const
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 204 of file nlpsol_impl.hpp.

204 { return nlpsol_default_in(ind);}
double nlpsol_default_in(casadi_int ind)
Default input for an NLP solver.
Definition: nlpsol.cpp:291

References casadi::nlpsol_default_in().

Referenced by casadi::Nlpsol::check_inputs().

◆ get_diff_in()

virtual bool casadi::FunctionInternal::get_diff_in ( casadi_int  i)
inlinevirtualinherited

◆ get_diff_out()

virtual bool casadi::FunctionInternal::get_diff_out ( casadi_int  i)
inlinevirtualinherited

◆ get_forward()

Function casadi::Nlpsol::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
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 957 of file nlpsol.cpp.

961  {
962  casadi_assert(detect_simple_bounds_is_simple_.empty(),
963  "Simple bound detection not compatible with get_forward");
964 
965  // Symbolic expression for the input
966  std::vector<MX> arg = mx_in(), res = mx_out();
967 
968  // Initial guesses not used for derivative calculations
970  std::string name = arg[i].is_symbolic() ? arg[i].name() : "tmp_get_forward";
971  arg[i] = MX::sym(name, Sparsity(arg[i].size()));
972  }
973 
974  // Optimal solution
975  MX x = res[NLPSOL_X];
976  MX lam_g = res[NLPSOL_LAM_G];
977  MX lam_x = res[NLPSOL_LAM_X];
978  MX lam_p = res[NLPSOL_LAM_P];
979  MX f = res[NLPSOL_F];
980  MX g = res[NLPSOL_G];
981 
982  // Inputs used
983  MX lbx = arg[NLPSOL_LBX];
984  MX ubx = arg[NLPSOL_UBX];
985  MX lbg = arg[NLPSOL_LBG];
986  MX ubg = arg[NLPSOL_UBG];
987  MX p = arg[NLPSOL_P];
988 
989  // Get KKT function
990  Function kkt = this->kkt();
991 
992  // Hessian of the Lagrangian, Jacobian of the constraints
993  std::vector<MX> HJ_res = kkt({x, p, 1, lam_g});
994  MX JG = HJ_res.at(0);
995  MX HL = HJ_res.at(1);
996 
997  // Active set (assumed known and given by the multiplier signs)
998  MX ubIx = lam_x > min_lam_;
999  MX lbIx = lam_x < -min_lam_;
1000  MX bIx = ubIx + lbIx;
1001  MX iIx = 1-bIx;
1002  MX ubIg = lam_g > min_lam_;
1003  MX lbIg = lam_g < -min_lam_;
1004  MX bIg = ubIg + lbIg;
1005  MX iIg = 1-bIg;
1006 
1007  // KKT matrix
1008  MX H_11 = mtimes(diag(iIx), HL) + diag(bIx);
1009  MX H_12 = mtimes(diag(iIx), JG.T());
1010  MX H_21 = mtimes(diag(bIg), JG);
1011  MX H_22 = diag(-iIg);
1012  MX H = MX::blockcat({{H_11, H_12}, {H_21, H_22}});
1013 
1014  // Sensitivity inputs
1015  std::vector<MX> fseed(NLPSOL_NUM_IN);
1016  MX fwd_lbx = fseed[NLPSOL_LBX] = MX::sym("fwd_lbx", repmat(x.sparsity(), 1, nfwd));
1017  MX fwd_ubx = fseed[NLPSOL_UBX] = MX::sym("fwd_ubx", repmat(x.sparsity(), 1, nfwd));
1018  MX fwd_lbg = fseed[NLPSOL_LBG] = MX::sym("fwd_lbg", repmat(g.sparsity(), 1, nfwd));
1019  MX fwd_ubg = fseed[NLPSOL_UBG] = MX::sym("fwd_ubg", repmat(g.sparsity(), 1, nfwd));
1020  MX fwd_p = fseed[NLPSOL_P] = MX::sym("fwd_p", repmat(p.sparsity(), 1, nfwd));
1021 
1022  // Guesses are unused
1024  fseed[i] = MX(repmat(Sparsity(arg[i].size()), 1, nfwd));
1025  }
1026 
1027  // nlp_grad has the signature
1028  // (x, p, lam_f, lam_g) -> (f, g, grad_x, grad_p)
1029  // with lam_f=1 and lam_g=lam_g, grad_x = -lam_x, grad_p=-lam_p
1030  Function nlp_grad = get_function("nlp_grad");
1031 
1032  // fwd_nlp_grad has the signature
1033  // (x, p, lam_f, lam_g, f, g, grad_x, grad_p,
1034  // fwd_x, fwd_p, fwd_lam_f, fwd_lam_g)
1035  // -> (fwd_f, fwd_g, fwd_grad_x, fwd_grad_p)
1036  Function fwd_nlp_grad = nlp_grad.forward(nfwd);
1037 
1038  // Calculate sensitivities from fwd_p
1039  std::vector<MX> vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p, 0., fwd_p, 0., 0.};
1040  vv = fwd_nlp_grad(vv);
1041  MX fwd_g_p = vv.at(1);
1042  MX fwd_gL_p = vv.at(2);
1043 
1044  // Propagate forward seeds
1045  MX fwd_alpha_x = (if_else(lbIx, fwd_lbx, 0) + if_else(ubIx, fwd_ubx, 0))
1046  - if_else(iIx, fwd_gL_p, 0);
1047  MX fwd_alpha_g = (if_else(ubIg, fwd_ubg, 0) + if_else(lbIg, fwd_lbg, 0))
1048  - if_else(bIg, fwd_g_p, 0);
1049  MX v = MX::vertcat({fwd_alpha_x, fwd_alpha_g});
1050 
1051  // Solve
1053 
1054  // Extract sensitivities in x, lam_x and lam_g
1055  std::vector<MX> v_split = vertsplit(v, {0, nx_, nx_+ng_});
1056  MX fwd_x = v_split.at(0);
1057  MX fwd_lam_g = v_split.at(1);
1058 
1059  // Calculate sensitivities in lam_x, lam_g
1060  vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p,
1061  fwd_x, fwd_p, 0, fwd_lam_g};
1062  vv = fwd_nlp_grad(vv);
1063  MX fwd_f = vv.at(0);
1064  MX fwd_g = vv.at(1);
1065  MX fwd_lam_x = -vv.at(2);
1066  MX fwd_lam_p = -vv.at(3);
1067 
1068  // Forward sensitivities
1069  std::vector<MX> fsens(NLPSOL_NUM_OUT);
1070  fsens[NLPSOL_X] = fwd_x;
1071  fsens[NLPSOL_F] = fwd_f;
1072  fsens[NLPSOL_G] = fwd_g;
1073  fsens[NLPSOL_LAM_X] = fwd_lam_x;
1074  fsens[NLPSOL_LAM_G] = fwd_lam_g;
1075  fsens[NLPSOL_LAM_P] = fwd_lam_p;
1076 
1077  // Gather return values
1078  arg.insert(arg.end(), res.begin(), res.end());
1079  arg.insert(arg.end(), fseed.begin(), fseed.end());
1080  res = fsens;
1081 
1082  Dict options = opts;
1083  options["allow_duplicate_io_names"] = true;
1084 
1085  return Function(name, arg, res, inames, onames, options);
1086  }
virtual const std::vector< MX > mx_in() const
Get function input(s) and output(s)
virtual const std::vector< MX > mx_out() const
Get function input(s) and output(s)
static MX sym(const std::string &name, casadi_int nrow=1, casadi_int ncol=1)
Create an nrow-by-ncol symbolic primitive.
static MX blockcat(const std::vector< std::vector< MX > > &v)
Definition: mx.cpp:1263
static MX solve(const MX &a, const MX &b)
Definition: mx.cpp:2115
static MX vertcat(const std::vector< MX > &x)
Definition: mx.cpp:1165
Function kkt() const
Definition: nlpsol.cpp:936
Dict sens_linsol_options_
Definition: nlpsol_impl.hpp:82
double min_lam_
Options.
Definition: nlpsol_impl.hpp:99
std::string sens_linsol_
Linear solver and options.
Definition: nlpsol_impl.hpp:81
NlpsolInput
Input arguments of an NLP Solver.
Definition: nlpsol.hpp:194
double if_else(double x, double y, double z)
Definition: calculus.hpp:296

References casadi::MX::blockcat(), casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::Function::forward(), casadi::FunctionInternal::Function, casadi::OracleFunction::get_function(), casadi::if_else(), casadi::Nlpsol::kkt(), casadi::Nlpsol::min_lam_, casadi::FunctionInternal::mx_in(), casadi::FunctionInternal::mx_out(), casadi::Nlpsol::ng_, casadi::NLPSOL_F, casadi::NLPSOL_G, casadi::NLPSOL_LAM_G, casadi::NLPSOL_LAM_G0, casadi::NLPSOL_LAM_P, casadi::NLPSOL_LAM_X, casadi::NLPSOL_LAM_X0, casadi::NLPSOL_LBG, casadi::NLPSOL_LBX, casadi::NLPSOL_NUM_IN, casadi::NLPSOL_NUM_OUT, casadi::NLPSOL_P, casadi::NLPSOL_UBG, casadi::NLPSOL_UBX, casadi::NLPSOL_X, casadi::NLPSOL_X0, casadi::Nlpsol::nx_, casadi::Nlpsol::sens_linsol_, casadi::Nlpsol::sens_linsol_options_, casadi::MX::solve(), casadi::MX::sparsity(), casadi::GenericMatrix< MX >::sym(), and casadi::MX::vertcat().

◆ get_free()

std::vector< std::string > casadi::FunctionInternal::get_free ( ) const
virtualinherited

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 1071 of file function_internal.cpp.

1071  {
1072  casadi_assert_dev(!has_free());
1073  return std::vector<std::string>();
1074  }
virtual bool has_free() const
Does the function have free variables.

References casadi::FunctionInternal::has_free().

◆ get_function() [1/2]

std::vector< std::string > casadi::OracleFunction::get_function ( ) const
overridevirtualinherited

-1 Indicates irregularity

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

Reimplemented from casadi::FunctionInternal.

Definition at line 531 of file oracle_function.cpp.

531  {
532  std::vector<std::string> ret;
533  ret.reserve(all_functions_.size());
534  for (auto&& e : all_functions_) {
535  ret.push_back(e.first);
536  }
537  return ret;
538 }

References casadi::OracleFunction::all_functions_.

Referenced by casadi::Rootfinder::ad_forward(), casadi::Rootfinder::ad_reverse(), casadi::SundialsInterface::calc_daeB(), casadi::OracleFunction::calc_function(), casadi::SundialsInterface::calc_quadB(), casadi::OracleFunction::calc_sp_forward(), casadi::OracleFunction::calc_sp_reverse(), casadi::FastNewton::codegen_body(), casadi::Feasiblesqpmethod::codegen_body(), casadi::Sqpmethod::codegen_body(), casadi::Nlpsol::codegen_declarations(), casadi::MadmpecInterface::codegen_declarations(), casadi::FatropInterface::codegen_declarations(), casadi::IpoptInterface::codegen_declarations(), casadi::MadnlpInterface::codegen_declarations(), casadi::UnoInterface::codegen_declarations(), casadi::FastNewton::codegen_declarations(), casadi::Feasiblesqpmethod::codegen_declarations(), casadi::Sqpmethod::codegen_declarations(), casadi::Feasiblesqpmethod::codegen_feasibility_iterations(), casadi::Nlpsol::codegen_post_solve(), casadi::FixedStepIntegrator::create_advanced(), casadi::OracleFunction::create_forward(), casadi::AlpaqaProblem::eval_hess_L(), casadi::AlpaqaProblem::eval_hess_ψ(), casadi::OracleFunction::finalize(), casadi::Nlpsol::get_forward(), casadi::OracleFunction::get_function(), casadi::AlpaqaProblem::get_hess_L_num_nonzeros(), casadi::AlpaqaProblem::get_hess_ψ_num_nonzeros(), casadi::Nlpsol::get_reverse(), casadi::FixedStepIntegrator::init(), casadi::ImplicitFixedStepIntegrator::init(), init(), casadi::BonminInterface::init(), casadi::MadmpecInterface::init(), casadi::FatropInterface::init(), casadi::IpoptInterface::init(), casadi::MadnlpInterface::init(), casadi::SLEQPInterface::init(), casadi::SundialsInterface::init(), casadi::FastNewton::init(), casadi::Feasiblesqpmethod::init(), casadi::Sqpmethod::init(), casadi::OracleFunction::monitored(), casadi::MadmpecInterface::set_ccopt_prob(), casadi::FatropInterface::set_fatrop_prob(), casadi::IpoptInterface::set_ipopt_prob(), casadi::MadnlpInterface::set_madnlp_prob(), casadi::SundialsInterface::set_work(), casadi::Collocation::setup_step(), casadi::RungeKutta::setup_step(), casadi::Integrator::sp_jac_dae(), casadi::Integrator::sp_jac_rdae(), and casadi::FixedStepIntegrator::stepB().

◆ get_function() [2/2]

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

Reimplemented from casadi::FunctionInternal.

Definition at line 540 of file oracle_function.cpp.

540  {
541  auto it = all_functions_.find(name);
542  casadi_assert(it!=all_functions_.end(),
543  "No function \"" + name + "\" in " + name_ + ". " +
544  "Available functions: " + join(get_function()) + ".");
545  return it->second.f;
546 }

References casadi::OracleFunction::all_functions_, casadi::OracleFunction::get_function(), casadi::join(), and casadi::ProtoFunction::name_.

◆ get_jac_sparsity()

Sparsity casadi::FunctionInternal::get_jac_sparsity ( casadi_int  oind,
casadi_int  iind,
bool  symmetric 
) const
virtualinherited

Extra doc: https://github.com/casadi/casadi/wiki/L_kz Get, if necessary generate, the sparsity of a Jacobian block

Reimplemented in casadi::FmuFunction, casadi::GenericExternal, casadi::Expm, and casadi::CallbackInternal.

Definition at line 1928 of file function_internal.cpp.

1929  {
1930  if (symmetric) {
1931  casadi_assert(sparsity_out_[oind].is_dense(),
1932  "Symmetry exploitation in Jacobian assumes dense expression. "
1933  "A potential workaround is to apply densify().");
1934  }
1935  // Check if we are able to propagate dependencies through the function
1936  if (has_spfwd() || has_sprev()) {
1937  // Get weighting factor
1938  double w = sp_weight();
1939 
1940  // Skip generation, assume dense
1941  if (w == -1) return Sparsity();
1942 
1943  Sparsity sp;
1944  if (nnz_in(iind) > 3*bvec_size && nnz_out(oind) > 3*bvec_size &&
1946  if (symmetric) {
1947  sp = get_jac_sparsity_hierarchical_symm(oind, iind);
1948  } else {
1949  sp = get_jac_sparsity_hierarchical(oind, iind);
1950  }
1951  } else {
1952  // Number of nonzero inputs and outputs
1953  casadi_int nz_in = nnz_in(iind);
1954  casadi_int nz_out = nnz_out(oind);
1955 
1956  // Number of forward sweeps we must make
1957  casadi_int nsweep_fwd = nz_in/bvec_size;
1958  if (nz_in%bvec_size) nsweep_fwd++;
1959 
1960  // Number of adjoint sweeps we must make
1961  casadi_int nsweep_adj = nz_out/bvec_size;
1962  if (nz_out%bvec_size) nsweep_adj++;
1963 
1964  // Use forward mode?
1965  if (w*static_cast<double>(nsweep_fwd) <= (1-w)*static_cast<double>(nsweep_adj)) {
1966  sp = get_jac_sparsity_gen<true>(oind, iind);
1967  } else {
1968  sp = get_jac_sparsity_gen<false>(oind, iind);
1969  }
1970  }
1971  return sp;
1972  } else {
1973  // Not calculated
1974  return Sparsity();
1975  }
1976  }
virtual bool has_sprev() const
Is the class able to propagate seeds through the algorithm?
Sparsity get_jac_sparsity_hierarchical_symm(casadi_int oind, casadi_int iind) const
virtual double sp_weight() const
Weighting factor for chosing forward/reverse mode,.
Sparsity get_jac_sparsity_hierarchical(casadi_int oind, casadi_int iind) const
A flavor of get_jac_sparsity_gen that does hierarchical block structure recognition.
std::vector< double > nz_in(const std::vector< DM > &arg) const
Convert from/to flat vector of input/output nonzeros.
std::vector< double > nz_out(const std::vector< DM > &res) const
Convert from/to flat vector of input/output nonzeros.
virtual bool has_spfwd() const
Is the class able to propagate seeds through the algorithm?
static bool hierarchical_sparsity
const int bvec_size

References casadi::bvec_size, casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::FunctionInternal::has_spfwd(), casadi::FunctionInternal::has_sprev(), casadi::GlobalOptions::hierarchical_sparsity, casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::nz_in(), casadi::FunctionInternal::nz_out(), casadi::FunctionInternal::sp_weight(), and casadi::FunctionInternal::sparsity_out_.

Referenced by casadi::Expm::get_jac_sparsity(), casadi::GenericExternal::get_jac_sparsity(), and casadi::FunctionInternal::jac_sparsity().

◆ get_jac_sparsity_gen()

template<bool fwd>
Sparsity casadi::FunctionInternal::get_jac_sparsity_gen ( casadi_int  oind,
casadi_int  iind 
) const
inherited

Definition at line 1273 of file function_internal.cpp.

1273  {
1274  // Number of nonzero inputs and outputs
1275  casadi_int nz_in = nnz_in(iind);
1276  casadi_int nz_out = nnz_out(oind);
1277 
1278  // Evaluation buffers
1279  std::vector<typename JacSparsityTraits<fwd>::arg_t> arg(sz_arg(), nullptr);
1280  std::vector<bvec_t*> res(sz_res(), nullptr);
1281  std::vector<casadi_int> iw(sz_iw());
1282  std::vector<bvec_t> w(sz_w(), 0);
1283 
1284  // Seeds and sensitivities
1285  std::vector<bvec_t> seed(nz_in, 0);
1286  arg[iind] = get_ptr(seed);
1287  std::vector<bvec_t> sens(nz_out, 0);
1288  res[oind] = get_ptr(sens);
1289  if (!fwd) std::swap(seed, sens);
1290 
1291  // Number of forward sweeps we must make
1292  casadi_int nsweep = seed.size() / bvec_size;
1293  if (seed.size() % bvec_size) nsweep++;
1294 
1295  // Print
1296  if (verbose_) {
1297  casadi_message(str(nsweep) + std::string(fwd ? " forward" : " reverse") + " sweeps "
1298  "needed for " + str(seed.size()) + " directions");
1299  }
1300 
1301  // Progress
1302  casadi_int progress = -10;
1303 
1304  // Temporary vectors
1305  std::vector<casadi_int> jcol, jrow;
1306 
1307  // Loop over the variables, bvec_size variables at a time
1308  for (casadi_int s=0; s<nsweep; ++s) {
1309 
1310  // Print progress
1311  if (verbose_) {
1312  casadi_int progress_new = (s*100)/nsweep;
1313  // Print when entering a new decade
1314  if (progress_new / 10 > progress / 10) {
1315  progress = progress_new;
1316  casadi_message(str(progress) + " %");
1317  }
1318  }
1319 
1320  // Nonzero offset
1321  casadi_int offset = s*bvec_size;
1322 
1323  // Number of local seed directions
1324  casadi_int ndir_local = seed.size()-offset;
1325  ndir_local = std::min(static_cast<casadi_int>(bvec_size), ndir_local);
1326 
1327  for (casadi_int i=0; i<ndir_local; ++i) {
1328  seed[offset+i] |= bvec_t(1)<<i;
1329  }
1330 
1331  // Propagate the dependencies
1332  JacSparsityTraits<fwd>::sp(this, get_ptr(arg), get_ptr(res),
1333  get_ptr(iw), get_ptr(w), memory(0));
1334 
1335  // Loop over the nonzeros of the output
1336  for (casadi_int el=0; el<sens.size(); ++el) {
1337 
1338  // Get the sparsity sensitivity
1339  bvec_t spsens = sens[el];
1340 
1341  if (!fwd) {
1342  // Clear the sensitivities for the next sweep
1343  sens[el] = 0;
1344  }
1345 
1346  // If there is a dependency in any of the directions
1347  if (spsens!=0) {
1348 
1349  // Loop over seed directions
1350  for (casadi_int i=0; i<ndir_local; ++i) {
1351 
1352  // If dependents on the variable
1353  if ((bvec_t(1) << i) & spsens) {
1354  // Add to pattern
1355  jcol.push_back(el);
1356  jrow.push_back(i+offset);
1357  }
1358  }
1359  }
1360  }
1361 
1362  // Remove the seeds
1363  for (casadi_int i=0; i<ndir_local; ++i) {
1364  seed[offset+i] = 0;
1365  }
1366  }
1367 
1368  // Construct sparsity pattern and return
1369  if (!fwd) swap(jrow, jcol);
1370  Sparsity ret = Sparsity::triplet(nz_out, nz_in, jcol, jrow);
1371  if (verbose_) {
1372  casadi_message("Formed Jacobian sparsity pattern (dimension " + str(ret.size()) + ", "
1373  + str(ret.nnz()) + " (" + str(ret.density()) + " %) nonzeros.");
1374  }
1375  return ret;
1376  }
static Sparsity triplet(casadi_int nrow, casadi_int ncol, const std::vector< casadi_int > &row, const std::vector< casadi_int > &col, std::vector< casadi_int > &mapping, bool invert_mapping)
Create a sparsity pattern given the nonzeros in sparse triplet form *.
Definition: sparsity.cpp:1143

References casadi::bvec_size, casadi::Sparsity::density(), casadi::get_ptr(), casadi::ProtoFunction::memory(), casadi::Sparsity::nnz(), casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::nz_in(), casadi::FunctionInternal::nz_out(), casadi::Sparsity::size(), casadi::str(), casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), casadi::FunctionInternal::sz_w(), casadi::Sparsity::triplet(), and casadi::ProtoFunction::verbose_.

◆ get_jac_sparsity_hierarchical()

Sparsity casadi::FunctionInternal::get_jac_sparsity_hierarchical ( casadi_int  oind,
casadi_int  iind 
) const
inherited

Decide which ad_mode to take

Definition at line 1613 of file function_internal.cpp.

1613  {
1614  // Number of nonzero inputs
1615  casadi_int nz_in = nnz_in(iind);
1616 
1617  // Number of nonzero outputs
1618  casadi_int nz_out = nnz_out(oind);
1619 
1620  // Seeds and sensitivities
1621  std::vector<bvec_t> s_in(nz_in, 0);
1622  std::vector<bvec_t> s_out(nz_out, 0);
1623 
1624  // Evaluation buffers
1625  std::vector<const bvec_t*> arg_fwd(sz_arg(), nullptr);
1626  std::vector<bvec_t*> arg_adj(sz_arg(), nullptr);
1627  arg_fwd[iind] = arg_adj[iind] = get_ptr(s_in);
1628  std::vector<bvec_t*> res(sz_res(), nullptr);
1629  res[oind] = get_ptr(s_out);
1630  std::vector<casadi_int> iw(sz_iw());
1631  std::vector<bvec_t> w(sz_w());
1632 
1633  // Sparsity triplet accumulator
1634  std::vector<casadi_int> jcol, jrow;
1635 
1636  // Cols of the coarse blocks
1637  std::vector<casadi_int> coarse_col(2, 0); coarse_col[1] = nz_out;
1638  // Rows of the coarse blocks
1639  std::vector<casadi_int> coarse_row(2, 0); coarse_row[1] = nz_in;
1640 
1641  // Cols of the fine blocks
1642  std::vector<casadi_int> fine_col;
1643 
1644  // Rows of the fine blocks
1645  std::vector<casadi_int> fine_row;
1646 
1647  // In each iteration, subdivide each coarse block in this many fine blocks
1648  casadi_int subdivision = bvec_size;
1649 
1650  Sparsity r = Sparsity::dense(1, 1);
1651 
1652  // The size of a block
1653  casadi_int granularity_row = nz_in;
1654  casadi_int granularity_col = nz_out;
1655 
1656  bool use_fwd = true;
1657 
1658  casadi_int nsweeps = 0;
1659 
1660  bool hasrun = false;
1661 
1662  // Get weighting factor
1663  double sp_w = sp_weight();
1664 
1665  // Lookup table for bvec_t
1666  std::vector<bvec_t> bvec_lookup;
1667  bvec_lookup.reserve(bvec_size);
1668  for (casadi_int i=0;i<bvec_size;++i) {
1669  bvec_lookup.push_back(bvec_t(1) << i);
1670  }
1671 
1672  while (!hasrun || coarse_col.size()!=nz_out+1 || coarse_row.size()!=nz_in+1) {
1673  if (verbose_) {
1674  casadi_message("Block size: " + str(granularity_col) + " x " + str(granularity_row));
1675  }
1676 
1677  // Clear the sparsity triplet acccumulator
1678  jcol.clear();
1679  jrow.clear();
1680 
1681  // Clear the fine block structure
1682  fine_row.clear();
1683  fine_col.clear();
1684 
1685  // r transpose will be needed in the algorithm
1686  Sparsity rT = r.T();
1687 
1690  // Forward mode
1691  Sparsity D1 = rT.uni_coloring(r);
1692  // Adjoint mode
1693  Sparsity D2 = r.uni_coloring(rT);
1694  if (verbose_) {
1695  casadi_message("Coloring on " + str(r.dim()) + " (fwd seeps: " + str(D1.size2()) +
1696  " , adj sweeps: " + str(D2.size1()) + ")");
1697  }
1698 
1699  // Use whatever required less colors if we tried both (with preference to forward mode)
1700  double fwd_cost = static_cast<double>(use_fwd ? granularity_row : granularity_col) *
1701  sp_w*static_cast<double>(D1.size2());
1702  double adj_cost = static_cast<double>(use_fwd ? granularity_col : granularity_row) *
1703  (1-sp_w)*static_cast<double>(D2.size2());
1704  use_fwd = fwd_cost <= adj_cost;
1705  if (verbose_) {
1706  casadi_message(std::string(use_fwd ? "Forward" : "Reverse") + " mode chosen "
1707  "(fwd cost: " + str(fwd_cost) + ", adj cost: " + str(adj_cost) + ")");
1708  }
1709 
1710  // Get seeds and sensitivities
1711  bvec_t* seed_v = use_fwd ? get_ptr(s_in) : get_ptr(s_out);
1712  bvec_t* sens_v = use_fwd ? get_ptr(s_out) : get_ptr(s_in);
1713 
1714  // The number of zeros in the seed and sensitivity directions
1715  casadi_int nz_seed = use_fwd ? nz_in : nz_out;
1716  casadi_int nz_sens = use_fwd ? nz_out : nz_in;
1717 
1718  // Clear the seeds
1719  for (casadi_int i=0; i<nz_seed; ++i) seed_v[i]=0;
1720 
1721  // Choose the active jacobian coloring scheme
1722  Sparsity D = use_fwd ? D1 : D2;
1723 
1724  // Adjoint mode amounts to swapping
1725  if (!use_fwd) {
1726  std::swap(coarse_col, coarse_row);
1727  std::swap(granularity_col, granularity_row);
1728  std::swap(r, rT);
1729  }
1730 
1731  // Subdivide the coarse block cols
1732  for (casadi_int k=0;k<coarse_col.size()-1;++k) {
1733  casadi_int diff = coarse_col[k+1]-coarse_col[k];
1734  casadi_int new_diff = diff/subdivision;
1735  if (diff%subdivision>0) new_diff++;
1736  std::vector<casadi_int> temp = range(coarse_col[k], coarse_col[k+1], new_diff);
1737  fine_col.insert(fine_col.end(), temp.begin(), temp.end());
1738  }
1739  // Subdivide the coarse block rows
1740  for (casadi_int k=0;k<coarse_row.size()-1;++k) {
1741  casadi_int diff = coarse_row[k+1]-coarse_row[k];
1742  casadi_int new_diff = diff/subdivision;
1743  if (diff%subdivision>0) new_diff++;
1744  std::vector<casadi_int> temp = range(coarse_row[k], coarse_row[k+1], new_diff);
1745  fine_row.insert(fine_row.end(), temp.begin(), temp.end());
1746  }
1747  if (fine_row.back()!=coarse_row.back()) fine_row.push_back(coarse_row.back());
1748  if (fine_col.back()!=coarse_col.back()) fine_col.push_back(coarse_col.back());
1749 
1750  granularity_col = fine_col[1] - fine_col[0];
1751  granularity_row = fine_row[1] - fine_row[0];
1752 
1753  // The index into the bvec bit vector
1754  casadi_int bvec_i = 0;
1755 
1756  // Create lookup tables for the fine blocks
1757  std::vector<casadi_int> fine_col_lookup = lookupvector(fine_col, nz_sens+1);
1758  std::vector<casadi_int> fine_row_lookup = lookupvector(fine_row, nz_seed+1);
1759 
1760  // Triplet data used as a lookup table
1761  std::vector<casadi_int> lookup_col;
1762  std::vector<casadi_int> lookup_row;
1763  std::vector<casadi_int> lookup_value;
1764 
1765 
1766  // The maximum number of fine blocks contained in one coarse block
1767  casadi_int n_fine_blocks_max = 0;
1768  for (casadi_int i=0;i<coarse_row.size()-1;++i) {
1769  casadi_int del = fine_row_lookup[coarse_row[i+1]]-fine_row_lookup[coarse_row[i]];
1770  n_fine_blocks_max = std::max(n_fine_blocks_max, del);
1771  }
1772 
1773  // Loop over all coarse seed directions from the coloring
1774  for (casadi_int csd=0; csd<D.size2(); ++csd) {
1775 
1776  casadi_int fci_offset = 0;
1777  casadi_int fci_cap = bvec_size-bvec_i;
1778 
1779  // Flag to indicate if all fine blocks have been handled
1780  bool f_finished = false;
1781 
1782  // Loop while not finished
1783  while (!f_finished) {
1784 
1785  // Loop over all coarse rows that are found in the coloring for this coarse seed direction
1786  for (casadi_int k=D.colind(csd); k<D.colind(csd+1); ++k) {
1787  casadi_int cci = D.row(k);
1788 
1789  // The first and last rows of the fine block
1790  casadi_int fci_start = fine_row_lookup[coarse_row[cci]];
1791  casadi_int fci_end = fine_row_lookup[coarse_row[cci+1]];
1792 
1793  // Local counter that modifies index into bvec
1794  casadi_int bvec_i_mod = 0;
1795 
1796  casadi_int value = -bvec_i + fci_offset + fci_start;
1797 
1798  // Loop over the rows of the fine block
1799  for (casadi_int fci = fci_offset; fci < std::min(fci_end-fci_start, fci_cap); ++fci) {
1800 
1801  // Loop over the coarse block cols that appear in the coloring
1802  // for the current coarse seed direction
1803  for (casadi_int cri=rT.colind(cci);cri<rT.colind(cci+1);++cri) {
1804  lookup_col.push_back(rT.row(cri));
1805  lookup_row.push_back(bvec_i+bvec_i_mod);
1806  lookup_value.push_back(value);
1807  }
1808 
1809  // Toggle on seeds
1810  bvec_toggle(seed_v, fine_row[fci+fci_start], fine_row[fci+fci_start+1],
1811  bvec_i+bvec_i_mod);
1812  bvec_i_mod++;
1813  }
1814  }
1815 
1816  // Bump bvec_i for next major coarse direction
1817  bvec_i+= std::min(n_fine_blocks_max, fci_cap);
1818 
1819  // Check if bvec buffer is full
1820  if (bvec_i==bvec_size || csd==D.size2()-1) {
1821  // Calculate sparsity for bvec_size directions at once
1822 
1823  // Statistics
1824  nsweeps+=1;
1825 
1826  // Construct lookup table
1827  IM lookup = IM::triplet(lookup_row, lookup_col, lookup_value, bvec_size,
1828  coarse_col.size());
1829 
1830  // Propagate the dependencies
1831  if (use_fwd) {
1832  JacSparsityTraits<true>::sp(this, get_ptr(arg_fwd), get_ptr(res),
1833  get_ptr(iw), get_ptr(w), memory(0));
1834  } else {
1835  std::fill(w.begin(), w.end(), 0);
1836  JacSparsityTraits<false>::sp(this, get_ptr(arg_adj), get_ptr(res),
1837  get_ptr(iw), get_ptr(w), memory(0));
1838  }
1839 
1840  // Temporary bit work vector
1841  bvec_t spsens;
1842 
1843  // Loop over the cols of coarse blocks
1844  for (casadi_int cri=0;cri<coarse_col.size()-1;++cri) {
1845 
1846  // Loop over the cols of fine blocks within the current coarse block
1847  for (casadi_int fri=fine_col_lookup[coarse_col[cri]];
1848  fri<fine_col_lookup[coarse_col[cri+1]];++fri) {
1849  // Lump individual sensitivities together into fine block
1850  bvec_or(sens_v, spsens, fine_col[fri], fine_col[fri+1]);
1851 
1852  // Next iteration if no sparsity
1853  if (!spsens) continue;
1854 
1855  // Loop over all bvec_bits
1856  for (casadi_int bvec_i=0;bvec_i<bvec_size;++bvec_i) {
1857  if (spsens & bvec_lookup[bvec_i]) {
1858  // if dependency is found, add it to the new sparsity pattern
1859  casadi_int ind = lookup.sparsity().get_nz(bvec_i, cri);
1860  if (ind==-1) continue;
1861  jrow.push_back(bvec_i+lookup->at(ind));
1862  jcol.push_back(fri);
1863  }
1864  }
1865  }
1866  }
1867 
1868  // Clear the forward seeds/adjoint sensitivities, ready for next bvec sweep
1869  std::fill(s_in.begin(), s_in.end(), 0);
1870 
1871  // Clear the adjoint seeds/forward sensitivities, ready for next bvec sweep
1872  std::fill(s_out.begin(), s_out.end(), 0);
1873 
1874  // Clean lookup table
1875  lookup_col.clear();
1876  lookup_row.clear();
1877  lookup_value.clear();
1878  }
1879 
1880  if (n_fine_blocks_max>fci_cap) {
1881  fci_offset += std::min(n_fine_blocks_max, fci_cap);
1882  bvec_i = 0;
1883  fci_cap = bvec_size;
1884  } else {
1885  f_finished = true;
1886  }
1887 
1888  }
1889 
1890  }
1891 
1892  // Swap results if adjoint mode was used
1893  if (use_fwd) {
1894  // Construct fine sparsity pattern
1895  r = Sparsity::triplet(fine_row.size()-1, fine_col.size()-1, jrow, jcol);
1896  coarse_col = fine_col;
1897  coarse_row = fine_row;
1898  } else {
1899  // Construct fine sparsity pattern
1900  r = Sparsity::triplet(fine_col.size()-1, fine_row.size()-1, jcol, jrow);
1901  coarse_col = fine_row;
1902  coarse_row = fine_col;
1903  }
1904  hasrun = true;
1905  }
1906  if (verbose_) {
1907  casadi_message("Number of sweeps: " + str(nsweeps));
1908  casadi_message("Formed Jacobian sparsity pattern (dimension " + str(r.size()) + ", " +
1909  str(r.nnz()) + " (" + str(r.density()) + " %) nonzeros.");
1910  }
1911 
1912  return r.T();
1913  }
static Matrix< casadi_int > triplet(const std::vector< casadi_int > &row, const std::vector< casadi_int > &col, const Matrix< casadi_int > &d)
Construct a sparse matrix from triplet form.
static Sparsity dense(casadi_int nrow, casadi_int ncol=1)
Create a dense rectangular sparsity pattern *.
Definition: sparsity.cpp:1028
std::vector< casadi_int > range(casadi_int start, casadi_int stop, casadi_int step, casadi_int len)
Range function.
std::vector< casadi_int > lookupvector(const std::vector< casadi_int > &v, casadi_int size)
Returns a vector for quickly looking up entries of supplied list.
Matrix< casadi_int > IM
Definition: im_fwd.hpp:31
std::vector< T > diff(const std::vector< T > &values)
diff
bvec_t bvec_or(const bvec_t *arg, casadi_int n)
Bit-wise or operation on bvec_t array.
void bvec_toggle(bvec_t *s, casadi_int begin, casadi_int end, casadi_int j)

References casadi::bvec_or(), casadi::bvec_size, casadi::bvec_toggle(), casadi::Sparsity::colind(), casadi::D, casadi::Sparsity::dense(), casadi::Sparsity::density(), casadi::diff(), casadi::Sparsity::dim(), casadi::Sparsity::get_nz(), casadi::get_ptr(), casadi::lookupvector(), casadi::ProtoFunction::memory(), casadi::Sparsity::nnz(), casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::nz_in(), casadi::FunctionInternal::nz_out(), casadi::range(), casadi::Sparsity::row(), casadi::Sparsity::size(), casadi::Sparsity::size1(), casadi::Sparsity::size2(), casadi::FunctionInternal::sp_weight(), casadi::Matrix< Scalar >::sparsity(), casadi::str(), casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), casadi::FunctionInternal::sz_w(), casadi::Sparsity::T(), casadi::Sparsity::triplet(), casadi::Matrix< casadi_int >::triplet(), casadi::Sparsity::uni_coloring(), and casadi::ProtoFunction::verbose_.

Referenced by casadi::FunctionInternal::get_jac_sparsity().

◆ get_jac_sparsity_hierarchical_symm()

Sparsity casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm ( casadi_int  oind,
casadi_int  iind 
) const
inherited

A flavor of get_jac_sparsity_gen that does hierarchical block structure recognition for symmetric Jacobians

Definition at line 1378 of file function_internal.cpp.

1379  {
1380  casadi_assert_dev(has_spfwd());
1381 
1382  // Number of nonzero inputs
1383  casadi_int nz = nnz_in(iind);
1384  casadi_assert_dev(nz==nnz_out(oind));
1385 
1386  // Evaluation buffers
1387  std::vector<const bvec_t*> arg(sz_arg(), nullptr);
1388  std::vector<bvec_t*> res(sz_res(), nullptr);
1389  std::vector<casadi_int> iw(sz_iw());
1390  std::vector<bvec_t> w(sz_w());
1391 
1392  // Seeds
1393  std::vector<bvec_t> seed(nz, 0);
1394  arg[iind] = get_ptr(seed);
1395 
1396  // Sensitivities
1397  std::vector<bvec_t> sens(nz, 0);
1398  res[oind] = get_ptr(sens);
1399 
1400  // Sparsity triplet accumulator
1401  std::vector<casadi_int> jcol, jrow;
1402 
1403  // Cols/rows of the coarse blocks
1404  std::vector<casadi_int> coarse(2, 0); coarse[1] = nz;
1405 
1406  // Cols/rows of the fine blocks
1407  std::vector<casadi_int> fine;
1408 
1409  // In each iteration, subdivide each coarse block in this many fine blocks
1410  casadi_int subdivision = bvec_size;
1411 
1412  Sparsity r = Sparsity::dense(1, 1);
1413 
1414  // The size of a block
1415  casadi_int granularity = nz;
1416 
1417  casadi_int nsweeps = 0;
1418 
1419  bool hasrun = false;
1420 
1421  while (!hasrun || coarse.size()!=nz+1) {
1422  if (verbose_) casadi_message("Block size: " + str(granularity));
1423 
1424  // Clear the sparsity triplet acccumulator
1425  jcol.clear();
1426  jrow.clear();
1427 
1428  // Clear the fine block structure
1429  fine.clear();
1430 
1431  Sparsity D = r.star_coloring();
1432 
1433  if (verbose_) {
1434  casadi_message("Star coloring on " + str(r.dim()) + ": "
1435  + str(D.size2()) + " <-> " + str(D.size1()));
1436  }
1437 
1438  // Clear the seeds
1439  std::fill(seed.begin(), seed.end(), 0);
1440 
1441  // Subdivide the coarse block
1442  for (casadi_int k=0; k<coarse.size()-1; ++k) {
1443  casadi_int diff = coarse[k+1]-coarse[k];
1444  casadi_int new_diff = diff/subdivision;
1445  if (diff%subdivision>0) new_diff++;
1446  std::vector<casadi_int> temp = range(coarse[k], coarse[k+1], new_diff);
1447  fine.insert(fine.end(), temp.begin(), temp.end());
1448  }
1449  if (fine.back()!=coarse.back()) fine.push_back(coarse.back());
1450 
1451  granularity = fine[1] - fine[0];
1452 
1453  // The index into the bvec bit vector
1454  casadi_int bvec_i = 0;
1455 
1456  // Create lookup tables for the fine blocks
1457  std::vector<casadi_int> fine_lookup = lookupvector(fine, nz+1);
1458 
1459  // Triplet data used as a lookup table
1460  std::vector<casadi_int> lookup_col;
1461  std::vector<casadi_int> lookup_row;
1462  std::vector<casadi_int> lookup_value;
1463 
1464  // The maximum number of fine blocks contained in one coarse block
1465  casadi_int n_fine_blocks_max = 0;
1466  for (casadi_int i=0;i<coarse.size()-1;++i) {
1467  casadi_int del = fine_lookup[coarse[i+1]]-fine_lookup[coarse[i]];
1468  n_fine_blocks_max = std::max(n_fine_blocks_max, del);
1469  }
1470 
1471  // Loop over all coarse seed directions from the coloring
1472  for (casadi_int csd=0; csd<D.size2(); ++csd) {
1473 
1474 
1475  casadi_int fci_offset = 0;
1476  casadi_int fci_cap = bvec_size-bvec_i;
1477 
1478  // Flag to indicate if all fine blocks have been handled
1479  bool f_finished = false;
1480 
1481  // Loop while not finished
1482  while (!f_finished) {
1483 
1484  // Loop over all coarse rows that are found in the coloring for this coarse seed direction
1485  for (casadi_int k=D.colind(csd); k<D.colind(csd+1); ++k) {
1486  casadi_int cci = D.row(k);
1487 
1488  // The first and last rows of the fine block
1489  casadi_int fci_start = fine_lookup[coarse[cci]];
1490  casadi_int fci_end = fine_lookup[coarse[cci+1]];
1491 
1492  // Local counter that modifies index into bvec
1493  casadi_int bvec_i_mod = 0;
1494 
1495  casadi_int value = -bvec_i + fci_offset + fci_start;
1496 
1497  //casadi_assert_dev(value>=0);
1498 
1499  // Loop over the rows of the fine block
1500  for (casadi_int fci = fci_offset; fci<std::min(fci_end-fci_start, fci_cap); ++fci) {
1501 
1502  // Loop over the coarse block cols that appear in the
1503  // coloring for the current coarse seed direction
1504  for (casadi_int cri=r.colind(cci);cri<r.colind(cci+1);++cri) {
1505  lookup_col.push_back(r.row(cri));
1506  lookup_row.push_back(bvec_i+bvec_i_mod);
1507  lookup_value.push_back(value);
1508  }
1509 
1510  // Toggle on seeds
1511  bvec_toggle(get_ptr(seed), fine[fci+fci_start], fine[fci+fci_start+1],
1512  bvec_i+bvec_i_mod);
1513  bvec_i_mod++;
1514  }
1515  }
1516 
1517  // Bump bvec_i for next major coarse direction
1518  bvec_i += std::min(n_fine_blocks_max, fci_cap);
1519 
1520  // Check if bvec buffer is full
1521  if (bvec_i==bvec_size || csd==D.size2()-1) {
1522  // Calculate sparsity for bvec_size directions at once
1523 
1524  // Statistics
1525  nsweeps+=1;
1526 
1527  // Construct lookup table
1528  IM lookup = IM::triplet(lookup_row, lookup_col, lookup_value,
1529  bvec_size, coarse.size());
1530 
1531  std::reverse(lookup_col.begin(), lookup_col.end());
1532  std::reverse(lookup_row.begin(), lookup_row.end());
1533  std::reverse(lookup_value.begin(), lookup_value.end());
1534  IM duplicates =
1535  IM::triplet(lookup_row, lookup_col, lookup_value, bvec_size, coarse.size())
1536  - lookup;
1537  duplicates = sparsify(duplicates);
1538  lookup(duplicates.sparsity()) = -bvec_size;
1539 
1540  // Propagate the dependencies
1541  JacSparsityTraits<true>::sp(this, get_ptr(arg), get_ptr(res),
1542  get_ptr(iw), get_ptr(w), nullptr);
1543 
1544  // Temporary bit work vector
1545  bvec_t spsens;
1546 
1547  // Loop over the cols of coarse blocks
1548  for (casadi_int cri=0; cri<coarse.size()-1; ++cri) {
1549 
1550  // Loop over the cols of fine blocks within the current coarse block
1551  for (casadi_int fri=fine_lookup[coarse[cri]];fri<fine_lookup[coarse[cri+1]];++fri) {
1552  // Lump individual sensitivities together into fine block
1553  bvec_or(get_ptr(sens), spsens, fine[fri], fine[fri+1]);
1554 
1555  // Loop over all bvec_bits
1556  for (casadi_int bvec_i=0;bvec_i<bvec_size;++bvec_i) {
1557  if (spsens & (bvec_t(1) << bvec_i)) {
1558  // if dependency is found, add it to the new sparsity pattern
1559  casadi_int ind = lookup.sparsity().get_nz(bvec_i, cri);
1560  if (ind==-1) continue;
1561  casadi_int lk = lookup->at(ind);
1562  if (lk>-bvec_size) {
1563  jrow.push_back(bvec_i+lk);
1564  jcol.push_back(fri);
1565  jrow.push_back(fri);
1566  jcol.push_back(bvec_i+lk);
1567  }
1568  }
1569  }
1570  }
1571  }
1572 
1573  // Clear the forward seeds/adjoint sensitivities, ready for next bvec sweep
1574  std::fill(seed.begin(), seed.end(), 0);
1575 
1576  // Clean lookup table
1577  lookup_col.clear();
1578  lookup_row.clear();
1579  lookup_value.clear();
1580  }
1581 
1582  if (n_fine_blocks_max>fci_cap) {
1583  fci_offset += std::min(n_fine_blocks_max, fci_cap);
1584  bvec_i = 0;
1585  fci_cap = bvec_size;
1586  } else {
1587  f_finished = true;
1588  }
1589  }
1590  }
1591 
1592  // Construct fine sparsity pattern
1593  r = Sparsity::triplet(fine.size()-1, fine.size()-1, jrow, jcol);
1594 
1595  // There may be false positives here that are not present
1596  // in the reverse mode that precedes it.
1597  // This can lead to an assymetrical result
1598  // cf. #1522
1599  r=r*r.T();
1600 
1601  coarse = fine;
1602  hasrun = true;
1603  }
1604  if (verbose_) {
1605  casadi_message("Number of sweeps: " + str(nsweeps));
1606  casadi_message("Formed Jacobian sparsity pattern (dimension " + str(r.size()) +
1607  ", " + str(r.nnz()) + " (" + str(r.density()) + " %) nonzeros.");
1608  }
1609 
1610  return r.T();
1611  }

References casadi::bvec_or(), casadi::bvec_size, casadi::bvec_toggle(), casadi::Sparsity::colind(), casadi::D, casadi::Sparsity::dense(), casadi::Sparsity::density(), casadi::diff(), casadi::Sparsity::dim(), casadi::Sparsity::get_nz(), casadi::get_ptr(), casadi::FunctionInternal::has_spfwd(), casadi::lookupvector(), casadi::Sparsity::nnz(), casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::range(), casadi::Sparsity::row(), casadi::Sparsity::size(), casadi::Matrix< Scalar >::sparsity(), casadi::Sparsity::star_coloring(), casadi::str(), casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), casadi::FunctionInternal::sz_w(), casadi::Sparsity::T(), casadi::Sparsity::triplet(), casadi::Matrix< casadi_int >::triplet(), and casadi::ProtoFunction::verbose_.

Referenced by casadi::FunctionInternal::get_jac_sparsity().

◆ get_jacobian()

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

◆ get_jit_directory()

std::string casadi::FunctionInternal::get_jit_directory ( const Dict jit_options)
staticinherited

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

Definition at line 710 of file function_internal.cpp.

710  {
711  // Start with default temp work dir
712  std::string jit_directory = GlobalOptions::getTempWorkDir();
713 
714  // Get user-specified directory
715  std::string directory;
716  directory = get_from_dict(jit_options, "directory", std::string(""));
717 
718  // What if directory itself is absolute?
719  if (Filesystem::is_absolute(directory)) {
720  // Override
721  jit_directory = directory;
722  } else {
723  jit_directory = jit_directory + directory;
724  if (Filesystem::is_enabled()) {
725  jit_directory = Filesystem::absolute(jit_directory);
726  }
727  }
728 
729  return Filesystem::ensure_trailing_slash(jit_directory);
730  }
static std::string absolute(const std::string &path)
Definition: filesystem.cpp:78
static bool is_absolute(const std::string &path)
Definition: filesystem.cpp:162
static std::string ensure_trailing_slash(const std::string &path)
Definition: filesystem.cpp:155
static bool is_enabled()
Definition: filesystem.cpp:83
static std::string getTempWorkDir()
T get_from_dict(const std::map< std::string, T > &d, const std::string &key, const T &default_value)

References casadi::Filesystem::absolute(), casadi::Filesystem::ensure_trailing_slash(), casadi::get_from_dict(), casadi::GlobalOptions::getTempWorkDir(), casadi::Filesystem::is_absolute(), and casadi::Filesystem::is_enabled().

Referenced by casadi::FunctionInternal::finalize(), and casadi::ShellCompiler::init().

◆ get_max_in()

virtual double casadi::FunctionInternal::get_max_in ( casadi_int  ind) const
inlinevirtualinherited

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

Definition at line 1103 of file function_internal.hpp.

1103  {
1104  return inf;
1105  }

References casadi::inf.

◆ get_min_in()

virtual double casadi::FunctionInternal::get_min_in ( casadi_int  ind) const
inlinevirtualinherited

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

Definition at line 1110 of file function_internal.hpp.

1110  {
1111  return -inf;
1112  }

References casadi::inf.

◆ get_n_in()

size_t casadi::Nlpsol::get_n_in ( )
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 145 of file nlpsol_impl.hpp.

145 { return NLPSOL_NUM_IN;}

References casadi::NLPSOL_NUM_IN.

◆ get_n_out()

size_t casadi::Nlpsol::get_n_out ( )
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 146 of file nlpsol_impl.hpp.

146 { return NLPSOL_NUM_OUT;}

References casadi::NLPSOL_NUM_OUT.

◆ get_name_in()

std::string casadi::Nlpsol::get_name_in ( casadi_int  i)
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 161 of file nlpsol_impl.hpp.

161 { return nlpsol_in(i);}
std::vector< std::string > nlpsol_in()
Get input scheme of NLP solvers.
Definition: nlpsol.cpp:279

References casadi::nlpsol_in().

◆ get_name_out()

std::string casadi::Nlpsol::get_name_out ( casadi_int  i)
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 162 of file nlpsol_impl.hpp.

162 { return nlpsol_out(i);}
std::vector< std::string > nlpsol_out()
Get NLP solver output scheme of NLP solvers.
Definition: nlpsol.cpp:285

References casadi::nlpsol_out().

◆ get_nominal_in()

virtual std::vector<double> casadi::FunctionInternal::get_nominal_in ( casadi_int  ind) const
inlinevirtualinherited

Reimplemented in casadi::FmuFunction.

Definition at line 1114 of file function_internal.hpp.

1114  {
1115  return std::vector<double>(nnz_in(ind), 1.);
1116  }

Referenced by casadi::FmuFunction::get_nominal_in().

◆ get_nominal_out()

virtual std::vector<double> casadi::FunctionInternal::get_nominal_out ( casadi_int  ind) const
inlinevirtualinherited

Reimplemented in casadi::FmuFunction.

Definition at line 1118 of file function_internal.hpp.

1118  {
1119  return std::vector<double>(nnz_out(ind), 1.);
1120  }

Referenced by casadi::FmuFunction::get_nominal_out().

◆ get_options()

const Options& casadi::Blocksqp::get_options ( ) const
inlineoverridevirtual

Reimplemented from casadi::Nlpsol.

Definition at line 170 of file blocksqp.hpp.

170 { return options_;}
static const Options options_
Options.
Definition: blocksqp.hpp:169

◆ get_partition()

void casadi::FunctionInternal::get_partition ( casadi_int  iind,
casadi_int  oind,
Sparsity D1,
Sparsity D2,
bool  compact,
bool  symmetric,
bool  allow_forward,
bool  allow_reverse 
) const
inherited

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

Definition at line 2068 of file function_internal.cpp.

2070  {
2071  if (verbose_) casadi_message(name_ + "::get_partition");
2072  casadi_assert(allow_forward || allow_reverse, "Inconsistent options");
2073 
2074  // Sparsity pattern with transpose
2075  Sparsity &AT = jac_sparsity(oind, iind, compact, symmetric);
2076  Sparsity A = symmetric ? AT : AT.T();
2077 
2078  // Get seed matrices by graph coloring
2079  if (symmetric) {
2080  casadi_assert_dev(enable_forward_ || enable_fd_);
2081  casadi_assert_dev(allow_forward);
2082 
2083  // Star coloring if symmetric
2084  if (verbose_) casadi_message("FunctionInternal::getPartition star_coloring");
2085  D1 = A.star_coloring();
2086  if (verbose_) {
2087  casadi_message("Star coloring completed: " + str(D1.size2())
2088  + " directional derivatives needed ("
2089  + str(A.size1()) + " without coloring).");
2090  }
2091 
2092  } else {
2093  casadi_assert_dev(enable_forward_ || enable_fd_ || enable_reverse_);
2094  // Get weighting factor
2095  double w = ad_weight();
2096 
2097  // Which AD mode?
2098  if (w==1) allow_forward = false;
2099  if (w==0) allow_reverse = false;
2100  casadi_assert(allow_forward || allow_reverse, "Conflicting ad weights");
2101 
2102  // Best coloring encountered so far (relatively tight upper bound)
2103  double best_coloring = std::numeric_limits<double>::infinity();
2104 
2105  // Test forward mode first?
2106  bool test_fwd_first = allow_forward && w*static_cast<double>(A.size1()) <=
2107  (1-w)*static_cast<double>(A.size2());
2108  casadi_int mode_fwd = test_fwd_first ? 0 : 1;
2109 
2110  // Test both coloring modes
2111  for (casadi_int mode=0; mode<2; ++mode) {
2112  // Is this the forward mode?
2113  bool fwd = mode==mode_fwd;
2114 
2115  // Skip?
2116  if (!allow_forward && fwd) continue;
2117  if (!allow_reverse && !fwd) continue;
2118 
2119  // Perform the coloring
2120  if (fwd) {
2121  if (verbose_) casadi_message("Unidirectional coloring (forward mode)");
2122  bool d = best_coloring>=w*static_cast<double>(A.size1());
2123  casadi_int max_colorings_to_test =
2124  d ? A.size1() : static_cast<casadi_int>(floor(best_coloring/w));
2125  D1 = AT.uni_coloring(A, max_colorings_to_test);
2126  if (D1.is_null()) {
2127  if (verbose_) {
2128  casadi_message("Forward mode coloring interrupted (more than "
2129  + str(max_colorings_to_test) + " needed).");
2130  }
2131  } else {
2132  if (verbose_) {
2133  casadi_message("Forward mode coloring completed: "
2134  + str(D1.size2()) + " directional derivatives needed ("
2135  + str(A.size1()) + " without coloring).");
2136  }
2137  D2 = Sparsity();
2138  best_coloring = w*static_cast<double>(D1.size2());
2139  }
2140  } else {
2141  if (verbose_) casadi_message("Unidirectional coloring (adjoint mode)");
2142  bool d = best_coloring>=(1-w)*static_cast<double>(A.size2());
2143  casadi_int max_colorings_to_test =
2144  d ? A.size2() : static_cast<casadi_int>(floor(best_coloring/(1-w)));
2145 
2146  D2 = A.uni_coloring(AT, max_colorings_to_test);
2147  if (D2.is_null()) {
2148  if (verbose_) {
2149  casadi_message("Adjoint mode coloring interrupted (more than "
2150  + str(max_colorings_to_test) + " needed).");
2151  }
2152  } else {
2153  if (verbose_) {
2154  casadi_message("Adjoint mode coloring completed: "
2155  + str(D2.size2()) + " directional derivatives needed ("
2156  + str(A.size2()) + " without coloring).");
2157  }
2158  D1 = Sparsity();
2159  best_coloring = (1-w)*static_cast<double>(D2.size2());
2160  }
2161  }
2162  }
2163 
2164  }
2165  }
Sparsity & jac_sparsity(casadi_int oind, casadi_int iind, bool compact, bool symmetric) const
Get Jacobian sparsity.

References casadi::FunctionInternal::ad_weight(), casadi::FunctionInternal::enable_fd_, casadi::FunctionInternal::enable_forward_, casadi::FunctionInternal::enable_reverse_, casadi::GenericShared< Shared, Internal >::is_null(), casadi::FunctionInternal::jac_sparsity(), casadi::ProtoFunction::name_, casadi::Sparsity::size1(), casadi::Sparsity::size2(), casadi::Sparsity::star_coloring(), casadi::str(), casadi::Sparsity::T(), casadi::Sparsity::uni_coloring(), and casadi::ProtoFunction::verbose_.

◆ get_reltol()

virtual double casadi::FunctionInternal::get_reltol ( ) const
inlinevirtualinherited

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

Reimplemented in casadi::SundialsInterface.

Definition at line 1125 of file function_internal.hpp.

1125  {
1126  return eps;
1127  }

References casadi::eps.

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

◆ get_reverse()

Function casadi::Nlpsol::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
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 1088 of file nlpsol.cpp.

1092  {
1093  casadi_assert(detect_simple_bounds_is_simple_.empty(),
1094  "Simple bound detection not compatible with get_reverse");
1095 
1096  // Symbolic expression for the input
1097  std::vector<MX> arg = mx_in(), res = mx_out();
1098 
1099  // Initial guesses not used for derivative calculations
1101  std::string name = arg[i].is_symbolic() ? arg[i].name() : "tmp_get_reverse";
1102  arg[i] = MX::sym(name, Sparsity(arg[i].size()));
1103  }
1104 
1105  // Optimal solution
1106  MX x = res[NLPSOL_X];
1107  MX lam_g = res[NLPSOL_LAM_G];
1108  MX lam_x = res[NLPSOL_LAM_X];
1109  MX lam_p = res[NLPSOL_LAM_P];
1110  MX f = res[NLPSOL_F];
1111  MX g = res[NLPSOL_G];
1112 
1113  // Inputs used
1114  MX lbx = arg[NLPSOL_LBX];
1115  MX ubx = arg[NLPSOL_UBX];
1116  MX lbg = arg[NLPSOL_LBG];
1117  MX ubg = arg[NLPSOL_UBG];
1118  MX p = arg[NLPSOL_P];
1119 
1120  // Get KKT function
1121  Function kkt = this->kkt();
1122 
1123  // Hessian of the Lagrangian, Jacobian of the constraints
1124  std::vector<MX> HJ_res = kkt({x, p, 1, lam_g});
1125  MX JG = HJ_res.at(0);
1126  MX HL = HJ_res.at(1);
1127 
1128  // Active set (assumed known and given by the multiplier signs)
1129  MX ubIx = lam_x > min_lam_;
1130  MX lbIx = lam_x < -min_lam_;
1131  MX bIx = ubIx + lbIx;
1132  MX iIx = 1-bIx;
1133  MX ubIg = lam_g > min_lam_;
1134  MX lbIg = lam_g < -min_lam_;
1135  MX bIg = ubIg + lbIg;
1136  MX iIg = 1-bIg;
1137 
1138  // KKT matrix
1139  MX H_11 = mtimes(diag(iIx), HL) + diag(bIx);
1140  MX H_12 = mtimes(diag(iIx), JG.T());
1141  MX H_21 = mtimes(diag(bIg), JG);
1142  MX H_22 = diag(-iIg);
1143  MX H = MX::blockcat({{H_11, H_12}, {H_21, H_22}});
1144 
1145  // Sensitivity inputs
1146  std::vector<MX> aseed(NLPSOL_NUM_OUT);
1147  MX adj_x = aseed[NLPSOL_X] = MX::sym("adj_x", repmat(x.sparsity(), 1, nadj));
1148  MX adj_lam_g = aseed[NLPSOL_LAM_G] = MX::sym("adj_lam_g", repmat(g.sparsity(), 1, nadj));
1149  MX adj_lam_x = aseed[NLPSOL_LAM_X] = MX::sym("adj_lam_x", repmat(x.sparsity(), 1, nadj));
1150  MX adj_lam_p = aseed[NLPSOL_LAM_P] = MX::sym("adj_lam_p", repmat(p.sparsity(), 1, nadj));
1151  MX adj_f = aseed[NLPSOL_F] = MX::sym("adj_f", Sparsity::dense(1, nadj));
1152  MX adj_g = aseed[NLPSOL_G] = MX::sym("adj_g", repmat(g.sparsity(), 1, nadj));
1153 
1154  // nlp_grad has the signature
1155  // (x, p, lam_f, lam_g) -> (f, g, grad_x, grad_p)
1156  // with lam_f=1 and lam_g=lam_g, grad_x = -lam_x, grad_p=-lam_p
1157  Function nlp_grad = get_function("nlp_grad");
1158 
1159  // rev_nlp_grad has the signature
1160  // (x, p, lam_f, lam_g, f, g, grad_x, grad_p,
1161  // adj_f, adj_g, adj_grad_x, adj_grad_p)
1162  // -> (adj_x, adj_p, adj_lam_f, adj_lam_g)
1163  Function rev_nlp_grad = nlp_grad.reverse(nadj);
1164 
1165  // Calculate sensitivities from f, g and lam_x
1166  std::vector<MX> vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p,
1167  adj_f, adj_g, -adj_lam_x, -adj_lam_p};
1168  vv = rev_nlp_grad(vv);
1169  MX adj_x0 = vv.at(0);
1170  MX adj_p0 = vv.at(1);
1171  MX adj_lam_g0 = vv.at(3);
1172 
1173  // Solve to get beta_x_bar, beta_g_bar
1174  MX v = MX::vertcat({adj_x + adj_x0, adj_lam_g + adj_lam_g0});
1176  std::vector<MX> v_split = vertsplit(v, {0, nx_, nx_+ng_});
1177  MX beta_x_bar = v_split.at(0);
1178  MX beta_g_bar = v_split.at(1);
1179 
1180  // Calculate sensitivities in p
1181  vv = {x, p, 1, lam_g, f, g, -lam_x, -lam_p,
1182  0, bIg*beta_g_bar, iIx*beta_x_bar, 0};
1183  vv = rev_nlp_grad(vv);
1184  MX adj_p = vv.at(1);
1185 
1186  // Reverse sensitivities
1187  std::vector<MX> asens(NLPSOL_NUM_IN);
1188  asens[NLPSOL_UBX] = if_else(ubIx, beta_x_bar, 0);
1189  asens[NLPSOL_LBX] = if_else(lbIx, beta_x_bar, 0);
1190  asens[NLPSOL_UBG] = if_else(ubIg, beta_g_bar, 0);
1191  asens[NLPSOL_LBG] = if_else(lbIg, beta_g_bar, 0);
1192  asens[NLPSOL_P] = adj_p0 - adj_p;
1193 
1194  // Guesses are unused
1196  asens[i] = MX(repmat(Sparsity(arg[i].size()), 1, nadj));
1197  }
1198 
1199  // Gather return values
1200  arg.insert(arg.end(), res.begin(), res.end());
1201  arg.insert(arg.end(), aseed.begin(), aseed.end());
1202  res = asens;
1203 
1204  Dict options = opts;
1205  options["allow_duplicate_io_names"] = true;
1206 
1207  return Function(name, arg, res, inames, onames, options);
1208  }

References casadi::MX::blockcat(), casadi::Sparsity::dense(), casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::FunctionInternal::Function, casadi::OracleFunction::get_function(), casadi::if_else(), casadi::Nlpsol::kkt(), casadi::Nlpsol::min_lam_, casadi::FunctionInternal::mx_in(), casadi::FunctionInternal::mx_out(), casadi::Nlpsol::ng_, casadi::NLPSOL_F, casadi::NLPSOL_G, casadi::NLPSOL_LAM_G, casadi::NLPSOL_LAM_G0, casadi::NLPSOL_LAM_P, casadi::NLPSOL_LAM_X, casadi::NLPSOL_LAM_X0, casadi::NLPSOL_LBG, casadi::NLPSOL_LBX, casadi::NLPSOL_NUM_IN, casadi::NLPSOL_NUM_OUT, casadi::NLPSOL_P, casadi::NLPSOL_UBG, casadi::NLPSOL_UBX, casadi::NLPSOL_X, casadi::NLPSOL_X0, casadi::Nlpsol::nx_, casadi::Function::reverse(), casadi::Nlpsol::sens_linsol_, casadi::Nlpsol::sens_linsol_options_, casadi::MX::solve(), casadi::MX::sparsity(), casadi::GenericMatrix< MX >::sym(), casadi::MX::T(), and casadi::MX::vertcat().

◆ get_sparsity_in()

Sparsity casadi::Nlpsol::get_sparsity_in ( casadi_int  i)
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 373 of file nlpsol.cpp.

373  {
374  switch (static_cast<NlpsolInput>(i)) {
375  case NLPSOL_X0:
376  case NLPSOL_LBX:
377  case NLPSOL_UBX:
378  case NLPSOL_LAM_X0:
379  return get_sparsity_out(NLPSOL_X);
380  case NLPSOL_LBG:
381  case NLPSOL_UBG:
382  case NLPSOL_LAM_G0:
383  return get_sparsity_out(NLPSOL_G);
384  case NLPSOL_P:
385  return oracle_.sparsity_in(NL_P);
386  case NLPSOL_NUM_IN: break;
387  }
388  return Sparsity();
389  }
Sparsity get_sparsity_out(casadi_int i) override
Sparsities of function inputs and outputs.
Definition: nlpsol.cpp:391

References casadi::Nlpsol::get_sparsity_out(), casadi::NL_P, casadi::NLPSOL_G, casadi::NLPSOL_LAM_G0, casadi::NLPSOL_LAM_X0, casadi::NLPSOL_LBG, casadi::NLPSOL_LBX, casadi::NLPSOL_NUM_IN, casadi::NLPSOL_P, casadi::NLPSOL_UBG, casadi::NLPSOL_UBX, casadi::NLPSOL_X, casadi::NLPSOL_X0, casadi::OracleFunction::oracle_, and casadi::Function::sparsity_in().

Referenced by casadi::Nlpsol::get_sparsity_out().

◆ get_sparsity_out()

Sparsity casadi::Nlpsol::get_sparsity_out ( casadi_int  i)
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 391 of file nlpsol.cpp.

391  {
392  switch (static_cast<NlpsolOutput>(i)) {
393  case NLPSOL_F:
394  return oracle_.sparsity_out(NL_F);
395  case NLPSOL_X:
396  case NLPSOL_LAM_X:
397  return oracle_.sparsity_in(NL_X);
398  case NLPSOL_LAM_G:
399  case NLPSOL_G:
400  if (detect_simple_bounds_is_simple_.empty()) {
401  return oracle_.sparsity_out(NL_G);
402  } else {
404  }
405  case NLPSOL_LAM_P:
406  return get_sparsity_in(NLPSOL_P);
407  case NLPSOL_NUM_OUT: break;
408  }
409  return Sparsity();
410  }
Sparsity get_sparsity_in(casadi_int i) override
Sparsities of function inputs and outputs.
Definition: nlpsol.cpp:373
NlpsolOutput
Output arguments of an NLP Solver.
Definition: nlpsol.hpp:215

References casadi::Sparsity::dense(), casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::Nlpsol::get_sparsity_in(), casadi::NL_F, casadi::NL_G, casadi::NL_X, casadi::NLPSOL_F, casadi::NLPSOL_G, casadi::NLPSOL_LAM_G, casadi::NLPSOL_LAM_P, casadi::NLPSOL_LAM_X, casadi::NLPSOL_NUM_OUT, casadi::NLPSOL_P, casadi::NLPSOL_X, casadi::OracleFunction::oracle_, casadi::Function::sparsity_in(), and casadi::Function::sparsity_out().

Referenced by casadi::Nlpsol::get_sparsity_in().

◆ get_stats()

Dict casadi::Nlpsol::get_stats ( void *  mem) const
overridevirtualinherited

Reimplemented from casadi::FunctionInternal.

Reimplemented in casadi::Sqpmethod, casadi::Scpgen, casadi::Qrsqp, casadi::Feasiblesqpmethod, casadi::WorhpInterface, casadi::UnoInterface, casadi::SnoptInterface, casadi::SLEQPInterface, casadi::MadnlpInterface, casadi::KnitroInterface, casadi::IpoptInterface, casadi::FatropInterface, casadi::MadmpecInterface, casadi::BonminInterface, and casadi::AlpaqaInterface.

Definition at line 1251 of file nlpsol.cpp.

1251  {
1252  Dict stats = OracleFunction::get_stats(mem);
1253  auto *m = static_cast<NlpsolMemory*>(mem);
1254  casadi_assert(m->d_nlp.prob,
1255  "No stats available: nlp Solver instance has not yet been called with numerical arguments.");
1256  auto *d_nlp = &m->d_nlp;
1257  stats["success"] = m->success;
1258  stats["unified_return_status"] = string_from_UnifiedReturnStatus(m->unified_return_status);
1259  if (d_nlp->prob && d_nlp->prob->detect_bounds.ng) {
1260  std::vector<bool> is_simple;
1262  stats["detect_simple_bounds_is_simple"] = is_simple;
1263  stats["detect_simple_bounds_target_x"] = detect_simple_bounds_target_x_;
1264  }
1265  return stats;
1266  }
static std::string string_from_UnifiedReturnStatus(UnifiedReturnStatus status)
Dict get_stats(void *mem) const override
Get all statistics.
void assign_vector(const std::vector< S > &s, std::vector< D > &d)

References casadi::assign_vector(), casadi::Nlpsol::detect_simple_bounds_is_simple_, casadi::Nlpsol::detect_simple_bounds_target_x_, casadi::OracleFunction::get_stats(), and casadi::FunctionInternal::string_from_UnifiedReturnStatus().

Referenced by casadi::AlpaqaInterface::get_stats(), casadi::BonminInterface::get_stats(), casadi::MadmpecInterface::get_stats(), casadi::FatropInterface::get_stats(), casadi::IpoptInterface::get_stats(), casadi::KnitroInterface::get_stats(), casadi::MadnlpInterface::get_stats(), casadi::SLEQPInterface::get_stats(), casadi::SnoptInterface::get_stats(), casadi::UnoInterface::get_stats(), casadi::WorhpInterface::get_stats(), casadi::Feasiblesqpmethod::get_stats(), casadi::Qrsqp::get_stats(), casadi::Scpgen::get_stats(), and casadi::Sqpmethod::get_stats().

◆ getAdaptorSolverName()

virtual std::string casadi::FunctionInternal::getAdaptorSolverName ( ) const
inlinevirtualinherited

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

Definition at line 304 of file function_internal.hpp.

304 { return ""; }

◆ getCount()

Definition at line 60 of file generic_shared_internal.hpp.

205  {
206  return static_cast<const Internal*>(this)->count;
207  }

◆ getPlugin()

PluginInterface< Nlpsol >::Plugin & casadi::PluginInterface< Nlpsol >::getPlugin ( const std::string &  pname)
staticinherited

Definition at line 102 of file plugin_interface.hpp.

295  {
296 
297 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
298  std::lock_guard<std::mutex> lock(Derived::mutex_solvers_);
299 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
300 
301  // Check if the solver has been loaded
302  auto it=Derived::solvers_.find(pname);
303 
304  // Load the solver if needed
305  if (it==Derived::solvers_.end()) {
306  load_plugin(pname, true, false);
307  it=Derived::solvers_.find(pname);
308  }
309  casadi_assert_dev(it!=Derived::solvers_.end());
310  return it->second;
311  }
static Plugin load_plugin(const std::string &pname, bool register_plugin=true, bool needs_lock=true)
Load a plugin dynamically.

◆ getReducedHessian()

DM casadi::Nlpsol::getReducedHessian ( )
virtualinherited

Definition at line 758 of file nlpsol.cpp.

758  {
759  casadi_error("getReducedHessian not defined for class " + class_name());
760  return DM();
761  }
std::string class_name() const override
Get type name.
Matrix< double > DM
Definition: dm_fwd.hpp:33

References casadi::Nlpsol::class_name().

◆ has_codegen()

virtual bool casadi::FunctionInternal::has_codegen ( ) const
inlinevirtualinherited

◆ has_derivative()

bool casadi::FunctionInternal::has_derivative ( ) const
inherited

◆ has_eval_dm()

virtual bool casadi::FunctionInternal::has_eval_dm ( ) const
inlinevirtualinherited

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

Reimplemented in casadi::CallbackInternal.

Definition at line 434 of file function_internal.hpp.

434 { return false;}

Referenced by casadi::FunctionInternal::eval().

◆ has_forward()

bool casadi::Nlpsol::has_forward ( casadi_int  nfwd) const
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 267 of file nlpsol_impl.hpp.

267 { return true;}

◆ has_free()

virtual bool casadi::FunctionInternal::has_free ( ) const
inlinevirtualinherited

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 753 of file function_internal.hpp.

753 { return false;}

Referenced by casadi::FunctionInternal::get_free().

◆ has_function()

bool casadi::OracleFunction::has_function ( const std::string &  fname) const
overridevirtualinherited

◆ has_jac_sparsity()

virtual bool casadi::FunctionInternal::has_jac_sparsity ( casadi_int  oind,
casadi_int  iind 
) const
inlinevirtualinherited

◆ has_jacobian()

virtual bool casadi::FunctionInternal::has_jacobian ( ) const
inlinevirtualinherited

◆ has_memory()

bool casadi::ProtoFunction::has_memory ( int  ind) const
inherited

Definition at line 3854 of file function_internal.cpp.

3854  {
3855  return ind<mem_.size();
3856  }

◆ has_option()

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

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

Definition at line 1055 of file function_internal.cpp.

1055  {
1056  return get_options().find(option_name) != nullptr;
1057  }
const Options::Entry * find(const std::string &name) const
Definition: options.cpp:32

References casadi::Options::find(), and casadi::ProtoFunction::get_options().

◆ has_plugin()

bool casadi::PluginInterface< Nlpsol >::has_plugin ( const std::string &  pname,
bool  verbose = false 
)
staticinherited

Definition at line 76 of file plugin_interface.hpp.

134  {
135 
136 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
137  std::lock_guard<std::mutex> lock(Derived::mutex_solvers_);
138 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
139 
140  // Quick return if available
141  if (Derived::solvers_.find(pname) != Derived::solvers_.end()) {
142  return true;
143  }
144 
145  // Try loading the plugin
146  try {
147  (void)load_plugin(pname, false, false);
148  return true;
149  } catch (CasadiException& ex) {
150  if (verbose) {
151  casadi_warning(ex.what());
152  }
153  return false;
154  }
155  }
std::vector< casadi_int > find(const std::vector< T > &v)
find nonzeros

◆ has_reverse()

bool casadi::Nlpsol::has_reverse ( casadi_int  nadj) const
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 278 of file nlpsol_impl.hpp.

278 { return true;}

◆ has_spfwd()

virtual bool casadi::FunctionInternal::has_spfwd ( ) const
inlinevirtualinherited

◆ has_sprev()

virtual bool casadi::FunctionInternal::has_sprev ( ) const
inlinevirtualinherited

◆ incache()

bool casadi::FunctionInternal::incache ( const std::string &  fname,
Function f,
const std::string &  suffix = "" 
) const
inherited

◆ index_in()

casadi_int casadi::FunctionInternal::index_in ( const std::string &  name) const
inlineinherited

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

Definition at line 1159 of file function_internal.hpp.

1159  {
1160  for (casadi_int i=0; i<name_in_.size(); ++i) {
1161  if (name_in_[i]==name) return i;
1162  }
1163  casadi_error("FunctionInternal::index_in: could not find entry \""
1164  + name + "\". Available names are: " + str(name_in_) + ".");
1165  return -1;
1166  }

References casadi::str().

Referenced by casadi::FunctionInternal::convert_arg().

◆ index_out()

casadi_int casadi::FunctionInternal::index_out ( const std::string &  name) const
inlineinherited

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

Definition at line 1171 of file function_internal.hpp.

1171  {
1172  for (casadi_int i=0; i<name_out_.size(); ++i) {
1173  if (name_out_[i]==name) return i;
1174  }
1175  casadi_error("FunctionInternal::index_out: could not find entry \""
1176  + name + "\". Available names are: " + str(name_out_) + ".");
1177  return -1;
1178  }

References casadi::str().

Referenced by casadi::FunctionInternal::convert_res().

◆ info()

Dict casadi::FunctionInternal::info ( ) const
virtualinherited

◆ init()

void casadi::Blocksqp::init ( const Dict opts)
overridevirtual

Reimplemented from casadi::Nlpsol.

Definition at line 231 of file blocksqp.cpp.

231  {
232  // Call the init method of the base class
233  Nlpsol::init(opts);
234 
235  // Set default options
236  //string qpsol_plugin = "qpoases";
237  //Dict qpsol_options;
238  linsol_plugin_ = "ma27";
239  print_header_ = true;
240  print_iteration_ = true;
241  eps_ = 1.0e-16;
242  opttol_ = 1.0e-6;
243  nlinfeastol_ = 1.0e-6;
244  schur_ = true;
245  globalization_ = true;
246  restore_feas_ = true;
247  max_line_search_ = 20;
250  max_iter_ = 100;
251  warmstart_ = false;
252  max_it_qp_ = 5000;
253  block_hess_ = true;
254  hess_scaling_ = 2;
255  fallback_scaling_ = 4;
256  max_time_qp_ = 10000.0;
257  ini_hess_diag_ = 1.0;
258  col_eps_ = 0.1;
259  col_tau1_ = 0.5;
260  col_tau2_ = 1.0e4;
261  hess_damp_ = 1;
262  hess_damp_fac_ = 0.2;
263  hess_update_ = 1;
264  fallback_update_ = 2;
265  hess_lim_mem_ = 1;
266  hess_memsize_ = 20;
267  which_second_derv_ = 0;
269  conv_strategy_ = 0;
270  max_conv_qp_ = 1;
271  max_soc_iter_ = 3;
272  gamma_theta_ = 1.0e-5;
273  gamma_f_ = 1.0e-5;
274  kappa_soc_ = 0.99;
275  kappa_f_ = 0.999;
276  theta_max_ = 1.0e7;
277  theta_min_ = 1.0e-5;
278  delta_ = 1.0;
279  s_theta_ = 1.1;
280  s_f_ = 2.3;
281  kappa_minus_ = 0.333;
282  kappa_plus_ = 8.0;
283  kappa_plus_max_ = 100.0;
284  delta_h0_ = 1.0e-4;
285  eta_ = 1.0e-4;
286  obj_lo_ = -inf;
287  obj_up_ = inf;
288  rho_ = 1.0e3;
289  zeta_ = 1.0e-3;
290  print_maxit_reached_ = true;
291  qp_init_ = true;
292 
293  // Read user options
294  for (auto&& op : opts) {
295  if (op.first=="qpsol") {
296  //qpsol_plugin = op.second.to_string();
297  casadi_warning("Option 'qpsol' currently not supported, ignored");
298  } else if (op.first=="qpsol_options") {
299  //qpsol_options = op.second;
300  casadi_warning("Option 'qpsol_options' currently not supported, ignored");
301  } else if (op.first=="linsol") {
302  linsol_plugin_ = std::string(op.second);
303  } else if (op.first=="print_header") {
304  print_header_ = op.second;
305  } else if (op.first=="print_iteration") {
306  print_iteration_ = op.second;
307  } else if (op.first=="eps") {
308  eps_ = op.second;
309  } else if (op.first=="opttol") {
310  opttol_ = op.second;
311  } else if (op.first=="nlinfeastol") {
312  nlinfeastol_ = op.second;
313  } else if (op.first=="schur") {
314  schur_ = op.second;
315  } else if (op.first=="globalization") {
316  globalization_ = op.second;
317  } else if (op.first=="restore_feas") {
318  restore_feas_ = op.second;
319  } else if (op.first=="max_line_search") {
320  max_line_search_ = op.second;
321  } else if (op.first=="max_consec_reduced_steps") {
322  max_consec_reduced_steps_ = op.second;
323  } else if (op.first=="max_consec_skipped_updates") {
324  max_consec_skipped_updates_ = op.second;
325  } else if (op.first=="max_iter") {
326  max_iter_ = op.second;
327  } else if (op.first=="warmstart") {
328  warmstart_ = op.second;
329  } else if (op.first=="qp_init") {
330  qp_init_ = op.second;
331  } else if (op.first=="max_it_qp") {
332  max_it_qp_ = op.second;
333  } else if (op.first=="block_hess") {
334  block_hess_ = op.second;
335  } else if (op.first=="hess_scaling") {
336  hess_scaling_ = op.second;
337  } else if (op.first=="fallback_scaling") {
338  fallback_scaling_ = op.second;
339  } else if (op.first=="max_time_qp") {
340  max_time_qp_ = op.second;
341  } else if (op.first=="ini_hess_diag") {
342  ini_hess_diag_ = op.second;
343  } else if (op.first=="col_eps") {
344  col_eps_ = op.second;
345  } else if (op.first=="col_tau1") {
346  col_tau1_ = op.second;
347  } else if (op.first=="col_tau2") {
348  col_tau2_ = op.second;
349  } else if (op.first=="hess_damp") {
350  hess_damp_ = op.second;
351  } else if (op.first=="hess_damp_fac") {
352  hess_damp_fac_ = op.second;
353  } else if (op.first=="hess_update") {
354  hess_update_ = op.second;
355  } else if (op.first=="fallback_update") {
356  fallback_update_ = op.second;
357  } else if (op.first=="hess_lim_mem") {
358  hess_lim_mem_ = op.second;
359  } else if (op.first=="hess_memsize") {
360  hess_memsize_ = op.second;
361  } else if (op.first=="which_second_derv") {
362  which_second_derv_ = op.second;
363  } else if (op.first=="skip_first_globalization") {
364  skip_first_globalization_ = op.second;
365  } else if (op.first=="conv_strategy") {
366  conv_strategy_ = op.second;
367  } else if (op.first=="max_conv_qp") {
368  max_conv_qp_ = op.second;
369  } else if (op.first=="max_soc_iter") {
370  max_soc_iter_ = op.second;
371  } else if (op.first=="gamma_theta") {
372  gamma_theta_ = op.second;
373  } else if (op.first=="gamma_f") {
374  gamma_f_ = op.second;
375  } else if (op.first=="kappa_soc") {
376  kappa_soc_ = op.second;
377  } else if (op.first=="kappa_f") {
378  kappa_f_ = op.second;
379  } else if (op.first=="theta_max") {
380  theta_max_ = op.second;
381  } else if (op.first=="theta_min") {
382  theta_min_ = op.second;
383  } else if (op.first=="delta") {
384  delta_ = op.second;
385  } else if (op.first=="s_theta") {
386  s_theta_ = op.second;
387  } else if (op.first=="s_f") {
388  s_f_ = op.second;
389  } else if (op.first=="kappa_minus") {
390  kappa_minus_ = op.second;
391  } else if (op.first=="kappa_plus") {
392  kappa_plus_ = op.second;
393  } else if (op.first=="kappa_plus_max") {
394  kappa_plus_max_ = op.second;
395  } else if (op.first=="delta_h0") {
396  delta_h0_ = op.second;
397  } else if (op.first=="eta") {
398  eta_ = op.second;
399  } else if (op.first=="obj_lo") {
400  obj_lo_ = op.second;
401  } else if (op.first=="obj_up") {
402  obj_up_ = op.second;
403  } else if (op.first=="rho") {
404  rho_ = op.second;
405  } else if (op.first=="zeta") {
406  zeta_ = op.second;
407  } else if (op.first=="print_maxit_reached") {
408  print_maxit_reached_ = op.second;
409  }
410  }
411 
412  // If we compute second constraints derivatives switch to
413  // finite differences Hessian (convenience)
414  if (which_second_derv_ == 2) {
415  hess_update_ = 4;
416  block_hess_ = true;
417  }
418 
419  // If we don't use limited memory BFGS we need to store only one vector.
420  if (!hess_lim_mem_) hess_memsize_ = 1;
421  if (!schur_ && hess_update_ == 1) {
422  print("***WARNING: SR1 update only works with qpOASES Schur complement version. "
423  "Using BFGS updates instead.\n");
424  hess_update_ = 2;
426  }
427 
428  // Setup feasibility restoration phase
429  if (restore_feas_) {
430  // get orignal nlp
431  Function nlp = oracle_;
432  std::vector<MX> resv;
433  std::vector<MX> argv = nlp.mx_in();
434 
435  // build fesibility restoration phase nlp
436  MX p = MX::sym("p", nlp.size1_in("x"));
437  MX s = MX::sym("s", nlp.size1_out("g"));
438 
439  MX d = fmin(1.0, 1.0/abs(p)) * (argv.at(0) - p);
440  MX f_rp = 0.5 * rho_ * dot(s, s) + zeta_/2.0 * dot(d, d);
441  MX g_rp = nlp(argv).at(1) - s;
442 
443  MXDict nlp_rp = {{"x", MX::vertcat({argv.at(0), s})},
444  {"p", MX::vertcat({argv.at(1), p})},
445  {"f", f_rp},
446  {"g", g_rp}};
447 
448  // Set options for the SQP method for the restoration problem
449  Dict solver_options;
450  solver_options["globalization"] = true;
451  solver_options["which_second_derv"] = 0;
452  solver_options["restore_feas"] = false;
453  solver_options["hess_update"] = 2;
454  solver_options["hess_lim_mem"] = 1;
455  solver_options["hess_scaling"] = 2;
456  solver_options["opttol"] = opttol_;
457  solver_options["nlinfeastol"] = nlinfeastol_;
458  solver_options["max_iter"] = 1;
459  solver_options["print_time"] = false;
460  solver_options["print_header"] = false;
461  solver_options["print_iteration"] = false;
462  solver_options["print_maxit_reached"] = false;
463 
464  // Create and initialize solver for the restoration problem
465  rp_solver_ = nlpsol("rpsolver", "blocksqp", nlp_rp, solver_options);
466  }
467 
468  // Setup NLP functions
469  create_function("nlp_fg", {"x", "p"}, {"f", "g"});
470  Function gf_jg = create_function("nlp_gf_jg", {"x", "p"},
471  {"f", "g", "grad:f:x", "jac:g:x"});
472  Asp_ = gf_jg.sparsity_out("jac_g_x");
473 
474  if (!block_hess_) {
475  // No block-structured Hessian
476  blocks_ = {0, nx_};
477  which_second_derv_ = 0;
479  } else {
480  // Detect block structure
481 
482  // Get the sparsity pattern for the Hessian of the Lagrangian
483  Function grad_lag = oracle_.factory("grad_lag",
484  {"x", "p", "lam:f", "lam:g"}, {"grad:gamma:x"},
485  {{"gamma", {"f", "g"}}});
486  Hsp_ = grad_lag.sparsity_jac("x", "grad_gamma_x", false, true);
487 
488  // Make sure diagonal exists
490 
491  // Find the strongly connected components of the Hessian
492  // Unlike Sparsity::scc, assume ordered
493  const casadi_int* colind = Hsp_.colind();
494  const casadi_int* row = Hsp_.row();
495  blocks_.push_back(0);
496  casadi_int ind = 0;
497  while (ind < nx_) {
498  // Find the next cutoff
499  casadi_int next=ind+1;
500  while (ind<next && ind<nx_) {
501  for (casadi_int k=colind[ind]; k<colind[ind+1]; ++k) next = std::max(next, 1+row[k]);
502  ind++;
503  }
504  blocks_.push_back(next);
505  }
506  }
507 
508  // Number of blocks
509  nblocks_ = blocks_.size()-1;
510 
511  // Blocksizes
512  dim_.resize(nblocks_);
513  casadi_int max_size = 0;
514  nnz_H_ = 0;
515  for (casadi_int i=0; i<nblocks_; ++i) {
516  dim_[i] = blocks_[i+1]-blocks_[i];
517  max_size = std::max(max_size, dim_[i]);
518  nnz_H_ += dim_[i]*dim_[i];
519  }
520 
521  create_function("nlp_hess_l", {"x", "p", "lam:f", "lam:g"},
522  {"triu:hess:gamma:x:x"}, {{"gamma", {"f", "g"}}});
523  exact_hess_lag_sp_ = get_function("nlp_hess_l").sparsity_out(0);
524 
525  if (verbose_) casadi_message(str(nblocks_) + " blocks of max size " + str(max_size) + ".");
526 
527  // Allocate a QP solver
528  //casadi_assert(!qpsol_plugin.empty(), "'qpsol' option has not been set");
529  //qpsol_ = conic("qpsol", qpsol_plugin, {{"h", Hsp_}, {"a", Asp_}},
530  // qpsol_options);
531  //alloc(qpsol_);
532 
533  // Allocate memory
534  alloc_w(Asp_.nnz(), true); // jac
535  alloc_w(nx_, true); // lam_xk
536  alloc_w(ng_, true); // lam_gk
537  alloc_w(ng_, true); // gk
538  alloc_w(nx_, true); // grad_fk
539  alloc_w(nx_, true); // grad_lagk
540  alloc_w(nx_+ng_, true); // lam_qp
541  alloc_w(nblocks_, true); // delta_norm
542  alloc_w(nblocks_, true); // delta_norm_old
543  alloc_w(nblocks_, true); // delta_gamma
544  alloc_w(nblocks_, true); // delta_gamma_old
545  alloc_w(nblocks_, true); // delta_h
546  alloc_w(nx_, true); // trial_xk
547  alloc_w(nx_, true); // lbx_qp
548  alloc_w(nx_, true); // ubx_qp
549  alloc_w(ng_, true); // lba_qp
550  alloc_w(ng_, true); // uba_qp
551  alloc_w(ng_, true); // jac_times_dxk
552  alloc_w(nx_*hess_memsize_, true); // deltaMat
553  alloc_w(nx_*hess_memsize_, true); // gammaMat
554  alloc_w(Asp_.nnz(), true); // jac_g
555  alloc_w(nnz_H_, true); // hess_lag
556  alloc_iw(nblocks_, true); // noUpdateCounter
557 
558  // Allocate block diagonal Hessian(s)
559  casadi_int n_hess = hess_update_==1 || hess_update_==4 ? 2 : 1;
560  alloc_res(nblocks_*n_hess, true);
561  alloc_w(n_hess*nnz_H_, true);
562  alloc_iw(nnz_H_ + (nx_+1) + nx_, true); // hessIndRow
563  alloc_w(exact_hess_lag_sp_.nnz(), true); // exact_hess_lag
564  }
const MX mx_in(casadi_int ind) const
Get symbolic primitives equivalent to the input expressions.
Definition: function.cpp:1781
void init(const Dict &opts) override
Initialize.
Definition: nlpsol.cpp:499
static Sparsity diag(casadi_int nrow)
Create diagonal sparsity pattern *.
Definition: sparsity.hpp:190
casadi_int nnz() const
Get the number of (structural) non-zeros.
Definition: sparsity.cpp:148
Function nlpsol(const std::string &name, const std::string &solver, const SXDict &nlp, const Dict &opts)
Definition: nlpsol.cpp:195
std::map< std::string, MX > MXDict
Definition: mx.hpp:1110
T dot(const std::vector< T > &a, const std::vector< T > &b)

References casadi::FunctionInternal::alloc_iw(), casadi::FunctionInternal::alloc_res(), casadi::FunctionInternal::alloc_w(), Asp_, block_hess_, blocks_, col_eps_, col_tau1_, col_tau2_, casadi::Sparsity::colind(), conv_strategy_, casadi::OracleFunction::create_function(), delta_, delta_h0_, casadi::Sparsity::dense(), casadi::Sparsity::diag(), dim_, casadi::dot(), eps_, eta_, exact_hess_lag_sp_, casadi::Function::factory(), fallback_scaling_, fallback_update_, gamma_f_, gamma_theta_, casadi::OracleFunction::get_function(), globalization_, hess_damp_, hess_damp_fac_, hess_lim_mem_, hess_memsize_, hess_scaling_, hess_update_, Hsp_, casadi::inf, ini_hess_diag_, casadi::Nlpsol::init(), kappa_f_, kappa_minus_, kappa_plus_, kappa_plus_max_, kappa_soc_, linsol_plugin_, max_consec_reduced_steps_, max_consec_skipped_updates_, max_conv_qp_, max_it_qp_, max_iter_, max_line_search_, max_soc_iter_, max_time_qp_, casadi::Function::mx_in(), nblocks_, casadi::Nlpsol::ng_, nlinfeastol_, casadi::nlpsol(), casadi::Sparsity::nnz(), nnz_H_, casadi::Nlpsol::nx_, obj_lo_, obj_up_, opttol_, casadi::OracleFunction::oracle_, casadi::ProtoFunction::print(), print_header_, print_iteration_, print_maxit_reached_, qp_init_, restore_feas_, rho_, casadi::Sparsity::row(), rp_solver_, s_f_, s_theta_, schur_, casadi::Function::size1_in(), casadi::Function::size1_out(), skip_first_globalization_, casadi::Function::sparsity_jac(), casadi::str(), casadi::GenericMatrix< MX >::sym(), theta_max_, theta_min_, casadi::ProtoFunction::verbose_, casadi::MX::vertcat(), warmstart_, which_second_derv_, and zeta_.

◆ init_mem()

int casadi::Blocksqp::init_mem ( void *  mem) const
overridevirtual

Reimplemented from casadi::Nlpsol.

Definition at line 566 of file blocksqp.cpp.

566  {
567  if (Nlpsol::init_mem(mem)) return 1;
568  auto m = static_cast<BlocksqpMemory*>(mem);
569 
570  // Create qpOASES memory
571  if (schur_) {
572  m->qpoases_mem = new QpoasesMemory();
573  m->qpoases_mem->linsol_plugin = linsol_plugin_;
574  }
575 
576  m->qp = nullptr;
577  m->colind.resize(Asp_.size2()+1);
578  m->row.resize(Asp_.nnz());
579  return 0;
580  }
int init_mem(void *mem) const override
Initalize memory block.
Definition: nlpsol.cpp:692
casadi_int size2() const
Get the number of columns.
Definition: sparsity.cpp:128

References Asp_, casadi::Nlpsol::init_mem(), linsol_plugin_, casadi::Sparsity::nnz(), casadi::BlocksqpMemory::qpoases_mem, schur_, and casadi::Sparsity::size2().

◆ initializeFilter()

void casadi::Blocksqp::initializeFilter ( BlocksqpMemory m) const

Definition at line 1722 of file blocksqp.cpp.

1722  {
1723  std::pair<double, double> initPair(theta_max_, obj_lo_);
1724 
1725  // Remove all elements
1726  auto iter=m->filter.begin();
1727  while (iter != m->filter.end()) {
1728  std::set< std::pair<double, double> >::iterator iterToRemove = iter;
1729  iter++;
1730  m->filter.erase(iterToRemove);
1731  }
1732 
1733  // Initialize with pair (maxConstrViolation, objLowerBound);
1734  m->filter.insert(initPair);
1735  }

References casadi::BlocksqpMemory::filter, obj_lo_, and theta_max_.

Referenced by solve().

◆ initIterate()

void casadi::Blocksqp::initIterate ( BlocksqpMemory m) const

Definition at line 2769 of file blocksqp.cpp.

2769  {
2770  m->alpha = 1.0;
2771  m->nSOCS = 0;
2772  m->reducedStepCount = 0;
2773  m->steptype = 0;
2774 
2775  m->obj = inf;
2776  m->tol = inf;
2777  m->cNorm = theta_max_;
2778  m->gradNorm = inf;
2779  m->lambdaStepNorm = 0.0;
2780  }

References casadi::BlocksqpMemory::alpha, casadi::BlocksqpMemory::cNorm, casadi::BlocksqpMemory::gradNorm, casadi::inf, casadi::BlocksqpMemory::lambdaStepNorm, casadi::BlocksqpMemory::nSOCS, casadi::BlocksqpMemory::obj, casadi::BlocksqpMemory::reducedStepCount, casadi::BlocksqpMemory::steptype, theta_max_, and casadi::BlocksqpMemory::tol.

Referenced by solve().

◆ initSingleton()

void casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::initSingleton ( )
inlineprotectedinherited

Called in the constructor of singletons to avoid that the counter reaches zero

Definition at line 71 of file generic_shared_internal.hpp.

71  {
72  casadi_assert_dev(static_cast<Internal*>(this)->count==0);
73  static_cast<Internal*>(this)->count++;
74  }

◆ initStats()

void casadi::Blocksqp::initStats ( BlocksqpMemory m) const

Definition at line 2608 of file blocksqp.cpp.

2608  {
2609  m->itCount = 0;
2610  m->qpItTotal = 0;
2611  m->qpIterations = 0;
2612  m->hessSkipped = 0;
2613  m->hessDamped = 0;
2614  m->averageSizingFactor = 0.0;
2615  }

References casadi::BlocksqpMemory::averageSizingFactor, casadi::BlocksqpMemory::hessDamped, casadi::BlocksqpMemory::hessSkipped, casadi::BlocksqpMemory::itCount, casadi::BlocksqpMemory::qpIterations, and casadi::BlocksqpMemory::qpItTotal.

Referenced by solve().

◆ instantiate()

Nlpsol * casadi::PluginInterface< Nlpsol >::instantiate ( const std::string &  fname,
const std::string &  pname,
Problem  problem 
)
staticinherited

Definition at line 106 of file plugin_interface.hpp.

317  {
318 
319  // Assert the plugin exists (needed for adaptors)
320  if (!has_plugin(pname, true)) {
321  casadi_error("Plugin '" + pname + "' is not found.");
322  }
323  return getPlugin(pname).creator(fname, problem);
324  }
static bool has_plugin(const std::string &pname, bool verbose=false)
Check if a plugin is available or can be loaded.
static Plugin & getPlugin(const std::string &pname)
Load and get the creator function.

◆ instruction_constant()

double casadi::FunctionInternal::instruction_constant ( casadi_int  k) const
virtualinherited

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

Reimplemented in casadi::SXFunction.

Definition at line 3591 of file function_internal.cpp.

3591  {
3592  casadi_error("'instruction_constant' not defined for " + class_name());
3593  }

References casadi::SharedObjectInternal::class_name().

◆ instruction_id()

casadi_int casadi::FunctionInternal::instruction_id ( casadi_int  k) const
virtualinherited

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 3583 of file function_internal.cpp.

3583  {
3584  casadi_error("'instruction_id' not defined for " + class_name());
3585  }

References casadi::SharedObjectInternal::class_name().

◆ instruction_input()

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

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 3587 of file function_internal.cpp.

3587  {
3588  casadi_error("'instruction_input' not defined for " + class_name());
3589  }

References casadi::SharedObjectInternal::class_name().

◆ instruction_MX()

MX casadi::FunctionInternal::instruction_MX ( casadi_int  k) const
virtualinherited

Reimplemented in casadi::MXFunction.

Definition at line 3599 of file function_internal.cpp.

3599  {
3600  casadi_error("'instruction_MX' not defined for " + class_name());
3601  }

References casadi::SharedObjectInternal::class_name().

◆ instruction_output()

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

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 3595 of file function_internal.cpp.

3595  {
3596  casadi_error("'instruction_output' not defined for " + class_name());
3597  }

References casadi::SharedObjectInternal::class_name().

◆ instructions_sx()

SX casadi::FunctionInternal::instructions_sx ( ) const
virtualinherited

Reimplemented in casadi::SXFunction.

Definition at line 3603 of file function_internal.cpp.

3603  {
3604  casadi_error("'instructions_sx' not defined for " + class_name());
3605  }

References casadi::SharedObjectInternal::class_name().

◆ integer_support()

virtual bool casadi::Nlpsol::integer_support ( ) const
inlinevirtualinherited

Reimplemented in casadi::KnitroInterface, and casadi::BonminInterface.

Definition at line 207 of file nlpsol_impl.hpp.

207 { return false;}

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

◆ is_a()

bool casadi::Nlpsol::is_a ( const std::string &  type,
bool  recursive 
) const
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 369 of file nlpsol.cpp.

369  {
370  return type=="Nlpsol" || (recursive && OracleFunction::is_a(type, recursive));
371  }
virtual bool is_a(const std::string &type, bool recursive) const
Check if the function is of a particular type.

References casadi::FunctionInternal::is_a().

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

◆ jac_is_symm()

bool casadi::FunctionInternal::jac_is_symm ( casadi_int  oind,
casadi_int  iind 
) const
virtualinherited

Definition at line 1915 of file function_internal.cpp.

1915  {
1916  // If derivative expression
1917  if (!derivative_of_.is_null()) {
1918  std::string n = derivative_of_.name();
1919  // Reverse move
1920  if (name_ == "adj1_" + n) {
1921  if (iind == oind) return true;
1922  }
1923  }
1924  // Not symmetric by default
1925  return false;
1926  }
const std::string & name() const
Name of the function.
Definition: function.cpp:1504

References casadi::FunctionInternal::derivative_of_, casadi::GenericShared< Shared, Internal >::is_null(), casadi::Function::name(), and casadi::ProtoFunction::name_.

◆ jac_sparsity()

Sparsity & casadi::FunctionInternal::jac_sparsity ( casadi_int  oind,
casadi_int  iind,
bool  compact,
bool  symmetric 
) const
inherited

Extra doc: https://github.com/casadi/casadi/wiki/L_kz Get, if necessary generate, the sparsity of a Jacobian block

Definition at line 2003 of file function_internal.cpp.

2004  {
2005 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
2006  // Safe access to jac_sparsity_
2007  std::lock_guard<std::mutex> lock(jac_sparsity_mtx_);
2008 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
2009  // If first call, allocate cache
2010  for (bool c : {false, true}) {
2011  if (jac_sparsity_[c].empty()) jac_sparsity_[c].resize(n_in_ * n_out_);
2012  }
2013  // Flat index
2014  casadi_int ind = iind + oind * n_in_;
2015  // Reference to the block
2016  Sparsity& jsp = jac_sparsity_[compact].at(ind);
2017  // If null, generate
2018  if (jsp.is_null()) {
2019  // Use (non)-compact pattern, if given
2020  Sparsity& jsp_other = jac_sparsity_[!compact].at(ind);
2021  if (!jsp_other.is_null()) {
2022  jsp = compact ? to_compact(oind, iind, jsp_other) : from_compact(oind, iind, jsp_other);
2023  } else {
2024  // Generate pattern
2025  Sparsity sp;
2026  bool sp_is_compact;
2027  if (!is_diff_out_.at(oind) || !is_diff_in_.at(iind)) {
2028  // All-zero sparse
2029  sp = Sparsity(nnz_out(oind), nnz_in(iind));
2030  sp_is_compact = true;
2031  } else {
2032  // Use internal routine to determine sparsity
2033  if (has_spfwd() || has_sprev() || has_jac_sparsity(oind, iind)) {
2034  sp = get_jac_sparsity(oind, iind, symmetric);
2035  }
2036  // If null, dense
2037  if (sp.is_null()) sp = Sparsity::dense(nnz_out(oind), nnz_in(iind));
2038  // Is the return the compact pattern?
2039  sp_is_compact = sp.size1() == nnz_out(oind) && sp.size2() == nnz_in(iind);
2040  }
2041  // Save to cache and convert if needed
2042  if (sp_is_compact == compact) {
2043  jsp = sp;
2044  } else {
2045  jsp_other = sp;
2046  jsp = compact ? to_compact(oind, iind, sp) : from_compact(oind, iind, sp);
2047  }
2048  }
2049  }
2050 
2051  // Make sure the Jacobian is symmetric if requested, cf. #1522, #3074, #3134
2052  if (symmetric) {
2053  if (compact) {
2054  Sparsity sp = from_compact(oind, iind, jsp);
2055  if (!sp.is_symmetric()) {
2056  sp = sp * sp.T();
2057  jsp = to_compact(oind, iind, sp);
2058  }
2059  } else {
2060  if (!jsp.is_symmetric()) jsp = jsp * jsp.T();
2061  }
2062  }
2063 
2064  // Return a reference to the block
2065  return jsp;
2066  }
std::vector< Sparsity > jac_sparsity_[2]
Cache for sparsities of the Jacobian blocks.
Sparsity to_compact(casadi_int oind, casadi_int iind, const Sparsity &sp) const
Convert to compact Jacobian sparsity pattern.
virtual bool has_jac_sparsity(casadi_int oind, casadi_int iind) const
Get Jacobian sparsity.
Sparsity from_compact(casadi_int oind, casadi_int iind, const Sparsity &sp) const
Convert from compact Jacobian sparsity pattern.
virtual Sparsity get_jac_sparsity(casadi_int oind, casadi_int iind, bool symmetric) const
Get Jacobian sparsity.

References casadi::Sparsity::dense(), casadi::FunctionInternal::from_compact(), casadi::FunctionInternal::get_jac_sparsity(), casadi::FunctionInternal::has_jac_sparsity(), casadi::FunctionInternal::has_spfwd(), casadi::FunctionInternal::has_sprev(), casadi::FunctionInternal::is_diff_in_, casadi::FunctionInternal::is_diff_out_, casadi::GenericShared< Shared, Internal >::is_null(), casadi::Sparsity::is_symmetric(), casadi::FunctionInternal::jac_sparsity_, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::Sparsity::size1(), casadi::Sparsity::size2(), casadi::Sparsity::T(), and casadi::FunctionInternal::to_compact().

Referenced by casadi::FunctionInternal::get_partition(), casadi::FunctionInternal::sp_forward_block(), and casadi::FunctionInternal::sp_reverse().

◆ jacobian()

Function casadi::FunctionInternal::jacobian ( ) const
inherited

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

Definition at line 2403 of file function_internal.cpp.

2403  {
2404  // Used wrapped function if jacobian not available
2405  if (!has_jacobian()) {
2406  // Derivative information must be available
2407  casadi_assert(has_derivative(),
2408  "Derivatives cannot be calculated for " + name_);
2409  return wrap().jacobian();
2410  }
2411  // Retrieve/generate cached
2412  Function f;
2413  std::string fname = "jac_" + name_;
2414  if (!incache(fname, f)) {
2415  // Names of inputs
2416  std::vector<std::string> inames;
2417  for (casadi_int i=0; i<n_in_; ++i) inames.push_back(name_in_[i]);
2418  for (casadi_int i=0; i<n_out_; ++i) inames.push_back("out_" + name_out_[i]);
2419  // Names of outputs
2420  std::vector<std::string> onames;
2421  onames.reserve(n_in_ * n_out_);
2422  for (size_t oind = 0; oind < n_out_; ++oind) {
2423  for (size_t iind = 0; iind < n_in_; ++iind) {
2424  onames.push_back("jac_" + name_out_[oind] + "_" + name_in_[iind]);
2425  }
2426  }
2427  // Options
2429  opts["derivative_of"] = self();
2430  // Generate derivative function
2431  casadi_assert_dev(enable_jacobian_);
2432  f = get_jacobian(fname, inames, onames, opts);
2433  // Consistency checks
2434  casadi_assert(f.n_in() == inames.size(),
2435  "Mismatching input signature, expected " + str(inames));
2436  casadi_assert(f.n_out() == onames.size(),
2437  "Mismatching output signature, expected " + str(onames));
2438  // Save to cache
2439  tocache_if_missing(f);
2440  }
2441  return f;
2442  }
virtual bool has_jacobian() const
Return Jacobian of all input elements with respect to all output elements.
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.
Function jacobian() const
Calculate all Jacobian blocks.
Definition: function.cpp:1068

References casadi::combine(), casadi::FunctionInternal::der_options_, casadi::FunctionInternal::enable_jacobian_, casadi::FunctionInternal::get_jacobian(), casadi::FunctionInternal::has_derivative(), casadi::FunctionInternal::has_jacobian(), casadi::FunctionInternal::incache(), casadi::Function::jacobian(), casadi::FunctionInternal::jacobian_options_, casadi::Function::n_in(), casadi::FunctionInternal::n_in_, casadi::Function::n_out(), casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::str(), casadi::FunctionInternal::tocache_if_missing(), and casadi::FunctionInternal::wrap().

Referenced by casadi::FunctionInternal::call_forward(), casadi::FunctionInternal::call_reverse(), and casadi::Function::jacobian().

◆ jit_dependencies()

void casadi::OracleFunction::jit_dependencies ( const std::string &  fname)
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 438 of file oracle_function.cpp.

438  {
439  if (compiler_.is_null()) {
440  if (verbose_) casadi_message("compiling to "+ fname+"'.");
441  // JIT dependent functions
442  compiler_ = Importer(generate_dependencies(fname, Dict()),
444  }
445  // Replace the Oracle functions with generated functions
446  for (auto&& e : all_functions_) {
447  if (verbose_) casadi_message("loading '" + e.second.f.name() + "' from '" + fname + "'.");
448  if (e.second.jit) {
449  e.second.f_original = e.second.f;
450  e.second.f = external(e.second.f.name(), compiler_);
451  }
452  }
453 }
std::string generate_dependencies(const std::string &fname, const Dict &opts) const override
Export / Generate C code for the generated functions.
Function external(const std::string &name, const Importer &li, const Dict &opts)
Load a just-in-time compiled external function.
Definition: external.cpp:42

References casadi::OracleFunction::all_functions_, casadi::FunctionInternal::compiler_, casadi::FunctionInternal::compiler_plugin_, casadi::external(), casadi::OracleFunction::generate_dependencies(), casadi::GenericShared< Shared, Internal >::is_null(), casadi::FunctionInternal::jit_options_, and casadi::ProtoFunction::verbose_.

◆ join_results()

void casadi::OracleFunction::join_results ( OracleMemory m) const
inherited

Definition at line 168 of file oracle_function.cpp.

168  {
169  // Combine runtime statistics
170  // Note: probably not correct to simply add wall times
171  for (int i = 0; i < max_num_threads_; ++i) {
172  auto* ml = m->thread_local_mem[i];
173  for (auto&& s : ml->fstats) {
174  m->fstats.at(s.first).join(s.second);
175  }
176  }
177 }

References casadi::ProtoFunctionMemory::fstats, casadi::OracleFunction::max_num_threads_, and casadi::OracleMemory::thread_local_mem.

Referenced by casadi::Nlpsol::eval(), and casadi::Integrator::eval().

◆ kkt()

Function casadi::Nlpsol::kkt ( ) const
inherited

Definition at line 936 of file nlpsol.cpp.

936  {
937 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
938  // Safe access to kkt_
939  std::lock_guard<std::mutex> lock(kkt_mtx_);
940 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
941  // Quick return if cached
942  SharedObject temp;
943  if (kkt_.shared_if_alive(temp)) {
944  return shared_cast<Function>(temp);
945  }
946 
947  // Generate KKT function
948  Function ret = oracle_.factory("kkt", {"x", "p", "lam:f", "lam:g"},
949  {"jac:g:x", "hess:gamma:x:x"}, {{"gamma", {"f", "g"}}});
950 
951  // Cache and return
952  kkt_ = ret;
953  return ret;
954  }
bool shared_if_alive(Shared &shared) const
Thread-safe alternative to alive()/shared()
WeakRef kkt_
Cache for KKT function.

References casadi::Function::factory(), casadi::Nlpsol::kkt_, casadi::OracleFunction::oracle_, and casadi::GenericWeakRef< Shared, Internal >::shared_if_alive().

Referenced by casadi::Nlpsol::get_forward(), and casadi::Nlpsol::get_reverse().

◆ kktErrorReduction()

casadi_int casadi::Blocksqp::kktErrorReduction ( BlocksqpMemory m) const

If the line search fails, check if the full step reduces the KKT error by a factor kappaF.

Definition at line 1654 of file blocksqp.cpp.

1654  {
1655  auto d_nlp = &m->d_nlp;
1656  casadi_int info = 0;
1657  double objTrial, cNormTrial, trialGradNorm, trialTol;
1658 
1659  // Compute new trial point
1660  for (casadi_int i=0; i<nx_; i++)
1661  m->trial_xk[i] = d_nlp->z[i] + m->dxk[i];
1662 
1663  // Compute objective and ||constr(trial_xk)|| at trial point
1664  std::vector<double> trialConstr(ng_, 0.);
1665  info = evaluate(m, m->trial_xk, &objTrial, get_ptr(trialConstr));
1666  m->nFunCalls++;
1667  cNormTrial = lInfConstraintNorm(m, m->trial_xk, get_ptr(trialConstr));
1668  if (info != 0 || objTrial < obj_lo_ || objTrial > obj_up_
1669  || !(objTrial == objTrial) || !(cNormTrial == cNormTrial)) {
1670  // evaluation error
1671  return 1;
1672  }
1673 
1674  // Compute KKT error of the new point
1675 
1676  // scaled norm of Lagrangian gradient
1677  std::vector<double> trialGradLagrange(nx_, 0.);
1678  calcLagrangeGradient(m, m->lam_qp, m->lam_qp+nx_, m->grad_fk,
1679  m->jac_g,
1680  get_ptr(trialGradLagrange), 0);
1681 
1682  trialGradNorm = casadi_norm_inf(nx_, get_ptr(trialGradLagrange));
1683  trialTol = trialGradNorm/(1.0+casadi_norm_inf(nx_+ng_, m->lam_qp));
1684 
1685  if (fmax(cNormTrial, trialTol) < kappa_f_ * fmax(m->cNorm, m->tol)) {
1686  acceptStep(m, 1.0);
1687  return 0;
1688  } else {
1689  return 1;
1690  }
1691  }

References acceptStep(), calcLagrangeGradient(), casadi::casadi_norm_inf(), casadi::BlocksqpMemory::cNorm, casadi::NlpsolMemory::d_nlp, casadi::BlocksqpMemory::dxk, evaluate(), casadi::get_ptr(), casadi::BlocksqpMemory::grad_fk, casadi::FunctionInternal::info(), casadi::BlocksqpMemory::jac_g, kappa_f_, casadi::BlocksqpMemory::lam_qp, lInfConstraintNorm(), casadi::BlocksqpMemory::nFunCalls, casadi::Nlpsol::ng_, casadi::Nlpsol::nx_, obj_up_, casadi::BlocksqpMemory::tol, and casadi::BlocksqpMemory::trial_xk.

Referenced by run().

◆ lInfConstraintNorm()

double casadi::Blocksqp::lInfConstraintNorm ( BlocksqpMemory m,
const double *  xk,
const double *  g 
) const

Definition at line 2840 of file blocksqp.cpp.

2841  {
2842  auto d_nlp = &m->d_nlp;
2843  return fmax(casadi_max_viol(nx_, xk, d_nlp->lbz, d_nlp->ubz),
2844  casadi_max_viol(ng_, g, d_nlp->lbz+nx_, d_nlp->ubz+nx_));
2845  }
T1 casadi_max_viol(casadi_int n, const T1 *x, const T1 *lb, const T1 *ub)
Largest bound violation.

References casadi::casadi_max_viol(), casadi::NlpsolMemory::d_nlp, casadi::Nlpsol::ng_, and casadi::Nlpsol::nx_.

Referenced by calcOptTol(), feasibilityRestorationPhase(), filterLineSearch(), fullstep(), kktErrorReduction(), and secondOrderCorrection().

◆ load_library()

handle_t casadi::PluginInterface< Nlpsol >::load_library ( const std::string &  libname,
std::string &  resultpath,
bool  global 
)
staticinherited

Definition at line 92 of file plugin_interface.hpp.

187  {
188 
189 #ifndef WITH_DL
190  casadi_error("WITH_DL option needed for dynamic loading");
191 #else // WITH_DL
192 
193  // Get the name of the shared library
194  std::string lib = std::string(CasadiMeta::shared_library_prefix()) + libname +
195  CasadiMeta::shared_library_suffix();
196 
197  // Build up search paths;
198  std::vector<std::string> search_paths = get_search_paths();
199  return open_shared_library(lib, search_paths, resultpath,
200  "PluginInterface::load_plugin", global);
201 
202 #endif // WITH_DL
203  }
std::vector< std::string > get_search_paths()
Definition: casadi_os.cpp:79

◆ load_plugin()

PluginInterface< Nlpsol >::Plugin casadi::PluginInterface< Nlpsol >::load_plugin ( const std::string &  pname,
bool  register_plugin = true,
bool  needs_lock = true 
)
staticinherited

Definition at line 88 of file plugin_interface.hpp.

208  {
209 
210 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
211  casadi::conditional_lock_guard<std::mutex> lock(Derived::mutex_solvers_, needs_lock);
212 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
213 
214  // Issue warning and quick return if already loaded
215  if (Derived::solvers_.find(pname) != Derived::solvers_.end()) {
216  casadi_warning("PluginInterface: Solver " + pname + " is already in use. Ignored.");
217  return Plugin();
218  }
219 
220  // Logger singletons are lazily instantiated on first uout()/uerr() calls
221  // This instantation may lead to a data race with potential instatiations in plugin
222  // To be safe, trigger instantatin before any plugin loading
223  uout();
224  uerr();
225 
226 #ifndef WITH_DL
227  casadi_error("WITH_DL option needed for dynamic loading");
228 #else // WITH_DL
229  // Retrieve the registration function
230  RegFcn reg;
231 
232  // Load the dll
233  std::string regName = "casadi_register_" + Derived::infix_ + "_" + pname;
234 
235  std::string searchpath;
236  handle_t handle = load_library("casadi_" + Derived::infix_ + "_" + pname, searchpath,
237  false);
238 
239 #ifdef _WIN32
240 
241 #if __GNUC__
242 #pragma GCC diagnostic push
243 #pragma GCC diagnostic ignored "-Wcast-function-type"
244 #endif
245  reg = reinterpret_cast<RegFcn>(GetProcAddress(handle, TEXT(regName.c_str())));
246 #if __GNUC__
247 #pragma GCC diagnostic pop
248 #endif
249 
250 #else // _WIN32
251  // Reset error
252  dlerror();
253 
254  // Load creator
255  reg = reinterpret_cast<RegFcn>(dlsym(handle, regName.c_str()));
256 #endif // _WIN32
257  casadi_assert(reg!=nullptr,
258  "PluginInterface::load_plugin: no \"" + regName + "\" found in " + searchpath + ".");
259 
260  // Create a temporary struct
261  Plugin plugin = pluginFromRegFcn(reg);
262  // Register the plugin
263  if (register_plugin) {
264  registerPlugin(plugin, false);
265  }
266 
267  return plugin;
268 
269 #endif // WITH_DL
270  }
static handle_t load_library(const std::string &libname, std::string &resultpath, bool global)
Load a library dynamically.
static Plugin pluginFromRegFcn(RegFcn regfcn)
Instantiate a Plugin struct from a factory function.
static void registerPlugin(const Plugin &plugin, bool needs_lock=true)
Register an integrator in the factory.
std::ostream & uerr()
void * handle_t
Definition: casadi_os.hpp:109

◆ local_init_mem()

int casadi::OracleFunction::local_init_mem ( void *  mem) const
inherited

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

Definition at line 465 of file oracle_function.cpp.

465  {
466  if (ProtoFunction::init_mem(mem)) return 1;
467  if (!mem) return 1;
468  auto *m = static_cast<LocalOracleMemory*>(mem);
469 
470  // Create statistics
471  for (auto&& e : all_functions_) {
472  m->add_stat(e.first);
473  }
474 
475  return 0;
476 }

References casadi::ProtoFunctionMemory::add_stat(), casadi::OracleFunction::all_functions_, and casadi::ProtoFunction::init_mem().

Referenced by casadi::OracleFunction::init_mem().

◆ map()

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

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

Definition at line 1142 of file function_internal.cpp.

1142  {
1143  Function f;
1144  if (parallelization=="serial") {
1145  // Serial maps are cached
1146  std::string fname = "map" + str(n) + "_" + name_;
1147  if (!incache(fname, f)) {
1148  // Create new serial map
1149  f = Map::create(parallelization, self(), n);
1150  casadi_assert_dev(f.name()==fname);
1151  // Save in cache
1152  tocache_if_missing(f);
1153  }
1154  } else {
1155  // Non-serial maps are not cached
1156  f = Map::create(parallelization, self(), n);
1157  }
1158  return f;
1159  }
static Function create(const std::string &parallelization, const Function &f, casadi_int n)
Definition: map.cpp:39

References casadi::Map::create(), casadi::FunctionInternal::incache(), casadi::Function::name(), casadi::ProtoFunction::name_, casadi::str(), and casadi::FunctionInternal::tocache_if_missing().

Referenced by casadi::Dple::get_forward(), casadi::Dple::get_reverse(), and casadi::FunctionInternal::mapsum_mx().

◆ mapsum_mx()

std::vector< MX > casadi::FunctionInternal::mapsum_mx ( const std::vector< MX > &  arg,
const std::string &  parallelization 
)
inherited

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

Definition at line 3612 of file function_internal.cpp.

3613  {
3614  if (x.empty()) return x;
3615  // Check number of arguments
3616  casadi_assert(x.size()==n_in_, "mapsum_mx: Wrong number_i of arguments");
3617  // Number of parallel calls
3618  casadi_int npar = 1;
3619  // Check/replace arguments
3620  std::vector<MX> x_mod(x.size());
3621  for (casadi_int i=0; i<n_in_; ++i) {
3622  if (check_mat(x[i].sparsity(), sparsity_in_[i], npar)) {
3623  x_mod[i] = replace_mat(x[i], sparsity_in_[i], npar);
3624  } else {
3625  // Mismatching sparsity: The following will throw an error message
3626  npar = 0;
3627  check_arg(x, npar);
3628  }
3629  }
3630 
3631  casadi_int n = 1;
3632  for (casadi_int i=0; i<x_mod.size(); ++i) {
3633  n = std::max(x_mod[i].size2() / size2_in(i), n);
3634  }
3635 
3636  std::vector<casadi_int> reduce_in;
3637  for (casadi_int i=0; i<x_mod.size(); ++i) {
3638  if (x_mod[i].size2()/size2_in(i)!=n) {
3639  reduce_in.push_back(i);
3640  }
3641  }
3642 
3643  Function ms = self().map("mapsum", parallelization, n, reduce_in, range(n_out_));
3644 
3645  // Call the internal function
3646  return ms(x_mod);
3647  }
Function map(casadi_int n, const std::string &parallelization) const
Generate/retrieve cached serial map.
void check_arg(const std::vector< M > &arg, casadi_int &npar) const
Check if input arguments have correct length and dimensions.
M replace_mat(const M &arg, const Sparsity &inp, casadi_int npar)

References casadi::FunctionInternal::check_arg(), casadi::FunctionInternal::check_mat(), casadi::FunctionInternal::map(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::range(), casadi::replace_mat(), casadi::FunctionInternal::size2_in(), and casadi::FunctionInternal::sparsity_in_.

◆ matching_arg()

template<typename M >
bool casadi::FunctionInternal::matching_arg ( const std::vector< M > &  arg,
casadi_int &  npar 
) const
inherited

Raises errors

Parameters
npar[in]normal usage: 1, disallow pararallel calls: -1
[out]nparmax number of horizontal repetitions across all arguments (or -1)

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

Definition at line 1801 of file function_internal.hpp.

1801  {
1802  check_arg(arg, npar);
1803  for (casadi_int i=0; i<n_in_; ++i) {
1804  if (arg.at(i).size1()!=size1_in(i)) return false;
1805  if (arg.at(i).size2()!=size2_in(i) && arg.at(i).size2()!=npar*size2_in(i)) return false;
1806  }
1807  return true;
1808  }

References casadi::FunctionInternal::check_arg(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::size1_in(), and casadi::FunctionInternal::size2_in().

Referenced by casadi::MXFunction::ad_forward(), casadi::SXFunction::ad_forward(), casadi::FunctionInternal::call(), casadi::FunctionInternal::call_forward(), and casadi::FunctionInternal::nz_in().

◆ matching_res()

template<typename M >
bool casadi::FunctionInternal::matching_res ( const std::vector< M > &  arg,
casadi_int &  npar 
) const
inherited

Raises errors

Parameters
npar[in]normal usage: 1, disallow pararallel calls: -1
[out]nparmax number of horizontal repetitions across all arguments (or -1)

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

Definition at line 1811 of file function_internal.hpp.

1811  {
1812  check_res(res, npar);
1813  for (casadi_int i=0; i<n_out_; ++i) {
1814  if (res.at(i).size1()!=size1_out(i)) return false;
1815  if (res.at(i).size2()!=size2_out(i) && res.at(i).size2()!=npar*size2_out(i)) return false;
1816  }
1817  return true;
1818  }
void check_res(const std::vector< M > &res, casadi_int &npar) const
Check if output arguments have correct length and dimensions.

References casadi::FunctionInternal::check_res(), casadi::FunctionInternal::n_out_, casadi::FunctionInternal::size1_out(), and casadi::FunctionInternal::size2_out().

Referenced by casadi::MXFunction::ad_reverse(), casadi::SXFunction::ad_reverse(), casadi::FunctionInternal::call_reverse(), and casadi::FunctionInternal::nz_out().

◆ memory()

void * casadi::ProtoFunction::memory ( int  ind) const
inherited

Definition at line 3847 of file function_internal.cpp.

3847  {
3848 #ifdef CASADI_WITH_THREAD
3849  std::lock_guard<std::mutex> lock(mtx_);
3850 #endif //CASADI_WITH_THREAD
3851  return mem_.at(ind);
3852  }

Referenced by casadi::FunctionInternal::call_gen(), casadi::FunctionInternal::get_jac_sparsity_gen(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::Sqpmethod::solve_ela_QP(), and casadi::Sqpmethod::solve_QP().

◆ merge()

void casadi::FunctionInternal::merge ( const std::vector< MX > &  arg,
std::vector< MX > &  subs_from,
std::vector< MX > &  subs_to 
) const
virtualinherited

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

Reimplemented in casadi::BlazingSplineFunction.

Definition at line 3562 of file function_internal.cpp.

3563  {
3564  }

◆ monitored()

bool casadi::OracleFunction::monitored ( const std::string &  name) const
virtualinherited

Definition at line 557 of file oracle_function.cpp.

557  {
558  auto it = all_functions_.find(name);
559  casadi_assert(it!=all_functions_.end(),
560  "No function \"" + name + "\" in " + name_+ ". " +
561  "Available functions: " + join(get_function()) + ".");
562  return it->second.monitored;
563 }

References casadi::OracleFunction::all_functions_, casadi::OracleFunction::get_function(), casadi::join(), and casadi::ProtoFunction::name_.

Referenced by casadi::OracleFunction::calc_function().

◆ mx_in() [1/2]

const std::vector< MX > casadi::FunctionInternal::mx_in ( ) const
virtualinherited

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

Reimplemented in casadi::MXFunction.

Definition at line 3542 of file function_internal.cpp.

3542  {
3543  std::vector<MX> ret(n_in_);
3544  for (casadi_int i=0; i<ret.size(); ++i) {
3545  ret[i] = mx_in(i);
3546  }
3547  return ret;
3548  }

References casadi::FunctionInternal::n_in_.

Referenced by casadi::Nlpsol::get_forward(), casadi::LinearInterpolantJac::get_jacobian(), casadi::Nlpsol::get_reverse(), casadi::FunctionInternal::wrap(), and casadi::FunctionInternal::wrap_as_needed().

◆ mx_in() [2/2]

const MX casadi::FunctionInternal::mx_in ( casadi_int  ind) const
virtualinherited

◆ mx_out() [1/2]

const std::vector< MX > casadi::FunctionInternal::mx_out ( ) const
virtualinherited

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

Definition at line 3550 of file function_internal.cpp.

3550  {
3551  std::vector<MX> ret(n_out_);
3552  for (casadi_int i=0; i<ret.size(); ++i) {
3553  ret[i] = mx_out(i);
3554  }
3555  return ret;
3556  }

References casadi::FunctionInternal::n_out_.

Referenced by casadi::Nlpsol::get_forward(), and casadi::Nlpsol::get_reverse().

◆ mx_out() [2/2]

const MX casadi::FunctionInternal::mx_out ( casadi_int  ind) const
virtualinherited

◆ n_instructions()

casadi_int casadi::FunctionInternal::n_instructions ( ) const
virtualinherited

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 3579 of file function_internal.cpp.

3579  {
3580  casadi_error("'n_instructions' not defined for " + class_name());
3581  }

References casadi::SharedObjectInternal::class_name().

◆ n_nodes()

casadi_int casadi::FunctionInternal::n_nodes ( ) const
virtualinherited

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

Reimplemented in casadi::SXFunction, and casadi::MXFunction.

Definition at line 3607 of file function_internal.cpp.

3607  {
3608  casadi_error("'n_nodes' not defined for " + class_name());
3609  }

References casadi::SharedObjectInternal::class_name().

◆ nnz_in() [1/2]

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

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

Definition at line 2362 of file function_internal.cpp.

2362  {
2363  casadi_int ret=0;
2364  for (casadi_int iind=0; iind<n_in_; ++iind) ret += nnz_in(iind);
2365  return ret;
2366  }

References casadi::FunctionInternal::n_in_.

Referenced by casadi::FunctionInternal::adjViaJac(), casadi::FunctionInternal::call_gen(), casadi::JitFunction::codegen_body(), casadi::FunctionInternal::codegen_meta(), casadi::FunctionInternal::eval_gen(), casadi::CallbackInternal::finalize(), casadi::FunctionInternal::from_compact(), casadi::FunctionInternal::fwdViaJac(), casadi::FunctionInternal::generate_in(), casadi::FunctionInternal::get_jac_sparsity(), casadi::Expm::get_jac_sparsity(), casadi::FmuFunction::get_jac_sparsity(), casadi::FunctionInternal::get_jac_sparsity_gen(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::JitFunction::init(), casadi::Nlpsol::init(), casadi::CbcInterface::init(), casadi::ClpInterface::init(), casadi::CplexInterface::init(), casadi::OoqpInterface::init(), casadi::ProxqpInterface::init(), casadi::QpoasesInterface::init(), casadi::ImplicitToNlp::init(), casadi::FunctionInternal::jac_sparsity(), casadi::FunctionInternal::nz_in(), casadi::ImplicitToNlp::set_work(), casadi::CbcInterface::solve(), casadi::ClpInterface::solve(), casadi::CplexInterface::solve(), casadi::OoqpInterface::solve(), casadi::PiqpInterface::solve(), casadi::ProxqpInterface::solve(), casadi::QpToNlp::solve(), casadi::KinsolInterface::solve(), casadi::FunctionInternal::sp_forward(), and casadi::FunctionInternal::sp_reverse().

◆ nnz_in() [2/2]

casadi_int casadi::FunctionInternal::nnz_in ( casadi_int  ind) const
inlineinherited

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

Definition at line 1007 of file function_internal.hpp.

1007 { return sparsity_in(ind).nnz(); }

◆ nnz_out() [1/2]

casadi_int casadi::FunctionInternal::nnz_out ( ) const
inherited

◆ nnz_out() [2/2]

casadi_int casadi::FunctionInternal::nnz_out ( casadi_int  ind) const
inlineinherited

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

Definition at line 1009 of file function_internal.hpp.

1009 { return sparsity_out(ind).nnz(); }

◆ numel_in() [1/2]

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

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

Definition at line 2374 of file function_internal.cpp.

2374  {
2375  casadi_int ret=0;
2376  for (casadi_int iind=0; iind<n_in_; ++iind) ret += numel_in(iind);
2377  return ret;
2378  }

References casadi::FunctionInternal::n_in_.

Referenced by casadi::FunctionInternal::from_compact(), and casadi::Integrator::get_reverse().

◆ numel_in() [2/2]

casadi_int casadi::FunctionInternal::numel_in ( casadi_int  ind) const
inlineinherited

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

Definition at line 1017 of file function_internal.hpp.

1017 { return sparsity_in(ind).numel(); }
casadi_int numel() const
The total number of elements, including structural zeros, i.e. size2()*size1()
Definition: sparsity.cpp:132

◆ numel_out() [1/2]

casadi_int casadi::FunctionInternal::numel_out ( ) const
inherited

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

Definition at line 2380 of file function_internal.cpp.

2380  {
2381  casadi_int ret=0;
2382  for (casadi_int oind=0; oind<n_out_; ++oind) ret += numel_out(oind);
2383  return ret;
2384  }

References casadi::FunctionInternal::n_out_.

Referenced by casadi::FunctionInternal::from_compact(), and casadi::Integrator::get_reverse().

◆ numel_out() [2/2]

casadi_int casadi::FunctionInternal::numel_out ( casadi_int  ind) const
inlineinherited

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

Definition at line 1018 of file function_internal.hpp.

1018 { return sparsity_out(ind).numel(); }

◆ nz_in() [1/2]

std::vector< double > casadi::FunctionInternal::nz_in ( const std::vector< DM > &  arg) const
inherited

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

Definition at line 3702 of file function_internal.cpp.

3702  {
3703  // Disallow parallel inputs
3704  casadi_int npar = -1;
3705  if (!matching_arg(arg, npar)) {
3706  return nz_in(replace_arg(arg, npar));
3707  }
3708 
3709  std::vector<DM> arg2 = project_arg(arg, 1);
3710  std::vector<double> ret(nnz_in());
3711  casadi_int offset = 0;
3712  for (casadi_int i=0;i<n_in_;++i) {
3713  const double* e = arg2.at(i).ptr();
3714  std::copy(e, e+nnz_in(i), ret.begin()+offset);
3715  offset+= nnz_in(i);
3716  }
3717  return ret;
3718  }

References casadi::FunctionInternal::matching_arg(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::project_arg(), and casadi::FunctionInternal::replace_arg().

Referenced by casadi::SXFunction::call_activity(), casadi::SXFunction::call_fwd(), casadi::SXFunction::call_rev(), casadi::SXFunction::call_setup(), casadi::FunctionInternal::get_jac_sparsity(), casadi::FunctionInternal::get_jac_sparsity_gen(), and casadi::FunctionInternal::get_jac_sparsity_hierarchical().

◆ nz_in() [2/2]

std::vector< DM > casadi::FunctionInternal::nz_in ( const std::vector< double > &  arg) const
inherited

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

Definition at line 3672 of file function_internal.cpp.

3672  {
3673  casadi_assert(nnz_in()==arg.size(),
3674  "Dimension mismatch. Expecting " + str(nnz_in()) +
3675  ", got " + str(arg.size()) + " instead.");
3676 
3677  std::vector<DM> ret = dm_in();
3678  casadi_int offset = 0;
3679  for (casadi_int i=0;i<n_in_;++i) {
3680  DM& r = ret.at(i);
3681  std::copy(arg.begin()+offset, arg.begin()+offset+nnz_in(i), r.ptr());
3682  offset+= nnz_in(i);
3683  }
3684  return ret;
3685  }

References casadi::FunctionInternal::dm_in(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::nnz_in(), casadi::Matrix< Scalar >::ptr(), and casadi::str().

◆ nz_out() [1/2]

std::vector< double > casadi::FunctionInternal::nz_out ( const std::vector< DM > &  res) const
inherited

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

Definition at line 3720 of file function_internal.cpp.

3720  {
3721  // Disallow parallel inputs
3722  casadi_int npar = -1;
3723  if (!matching_res(res, npar)) {
3724  return nz_out(replace_res(res, npar));
3725  }
3726 
3727  std::vector<DM> res2 = project_res(res, 1);
3728  std::vector<double> ret(nnz_out());
3729  casadi_int offset = 0;
3730  for (casadi_int i=0;i<n_out_;++i) {
3731  const double* e = res2.at(i).ptr();
3732  std::copy(e, e+nnz_out(i), ret.begin()+offset);
3733  offset+= nnz_out(i);
3734  }
3735  return ret;
3736  }
std::vector< M > project_res(const std::vector< M > &arg, casadi_int npar) const
Project sparsities.
std::vector< M > replace_res(const std::vector< M > &res, casadi_int npar) const
Replace 0-by-0 outputs.

References casadi::FunctionInternal::matching_res(), casadi::FunctionInternal::n_out_, casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::project_res(), and casadi::FunctionInternal::replace_res().

Referenced by casadi::SXFunction::call_activity(), casadi::SXFunction::call_fwd(), casadi::SXFunction::call_rev(), casadi::SXFunction::call_setup(), casadi::FunctionInternal::get_jac_sparsity(), casadi::FunctionInternal::get_jac_sparsity_gen(), and casadi::FunctionInternal::get_jac_sparsity_hierarchical().

◆ nz_out() [2/2]

std::vector< DM > casadi::FunctionInternal::nz_out ( const std::vector< double > &  res) const
inherited

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

Definition at line 3687 of file function_internal.cpp.

3687  {
3688  casadi_assert(nnz_out()==res.size(),
3689  "Dimension mismatch. Expecting " + str(nnz_out()) +
3690  ", got " + str(res.size()) + " instead.");
3691 
3692  std::vector<DM> ret = dm_out();
3693  casadi_int offset = 0;
3694  for (casadi_int i=0;i<n_out_;++i) {
3695  DM& r = ret.at(i);
3696  std::copy(res.begin()+offset, res.begin()+offset+nnz_out(i), r.ptr());
3697  offset+= nnz_out(i);
3698  }
3699  return ret;
3700  }

References casadi::FunctionInternal::dm_out(), casadi::FunctionInternal::n_out_, casadi::FunctionInternal::nnz_out(), casadi::Matrix< Scalar >::ptr(), and casadi::str().

◆ oracle()

const Function& casadi::OracleFunction::oracle ( ) const
inlineoverridevirtualinherited

◆ pairInFilter()

bool casadi::Blocksqp::pairInFilter ( BlocksqpMemory m,
double  cNorm,
double  obj 
) const

Check if current entry is accepted to the filter: (cNorm, obj) in F_k

Definition at line 1697 of file blocksqp.cpp.

1698  {
1699  /*
1700  * A pair is in the filter if:
1701  * - it increases the objective and
1702  * - it also increases the constraint violation
1703  * The second expression in the if-clause states that we exclude
1704  * entries that are within the feasibility tolerance, e.g.
1705  * if an entry improves the constraint violation from 1e-16 to 1e-17,
1706  * but increases the objective considerably we also think of this entry
1707  * as dominated
1708  */
1709 
1710  for (auto&& f : m->filter) {
1711  if ((cNorm >= (1.0 - gamma_theta_) * f.first ||
1712  (cNorm < 0.01 * nlinfeastol_ && f.first < 0.01 * nlinfeastol_)) &&
1713  obj >= f.second - gamma_f_ * f.first) {
1714  return 1;
1715  }
1716  }
1717 
1718  return 0;
1719  }

References casadi::BlocksqpMemory::filter, gamma_f_, gamma_theta_, and nlinfeastol_.

Referenced by feasibilityRestorationPhase(), filterLineSearch(), and secondOrderCorrection().

◆ plugin_deserialize()

Deserialize casadi::PluginInterface< Nlpsol >::plugin_deserialize ( const std::string &  pname)
staticinherited

Definition at line 82 of file plugin_interface.hpp.

165  {
166  Deserialize m = getPlugin(pname).deserialize;
167  casadi_assert(m, "Plugin \"" + pname + "\" does not support deserialize");
168  return m;
169  }
ProtoFunction *(* Deserialize)(DeserializingStream &)

◆ plugin_name()

const char* casadi::Blocksqp::plugin_name ( ) const
inlineoverridevirtual

Implements casadi::PluginInterface< Nlpsol >.

Definition at line 157 of file blocksqp.hpp.

157 { return "blocksqp";}

◆ plugin_options()

const Options & casadi::PluginInterface< Nlpsol >::plugin_options ( const std::string &  pname)
staticinherited

Definition at line 79 of file plugin_interface.hpp.

158  {
159  const Options *op = getPlugin(pname).options;
160  casadi_assert(op!=nullptr, "Plugin \"" + pname + "\" does not support options");
161  return *op;
162  }

◆ pluginFromRegFcn()

PluginInterface< Nlpsol >::Plugin casadi::PluginInterface< Nlpsol >::pluginFromRegFcn ( RegFcn  regfcn)
staticinherited

Definition at line 85 of file plugin_interface.hpp.

173  {
174  // Create a temporary struct
175  Plugin plugin;
176 
177  // Set the fields
178  int flag = regfcn(&plugin);
179  casadi_assert(flag==0, "Registration of plugin failed.");
180 
181  return plugin;
182  }

◆ print()

void casadi::ProtoFunction::print ( const char *  fmt,
  ... 
) const
inherited

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

Definition at line 4100 of file function_internal.cpp.

4100  {
4101  // Variable number of arguments
4102  va_list args;
4103  va_start(args, fmt);
4104  // Static & dynamic buffers
4105  char buf[256];
4106  size_t buf_sz = sizeof(buf);
4107  char* buf_dyn = nullptr;
4108  // Try to print with a small buffer
4109  casadi_int n = vsnprintf(buf, buf_sz, fmt, args);
4110  // Need a larger buffer?
4111  if (n>static_cast<casadi_int>(buf_sz)) {
4112  buf_sz = static_cast<size_t>(n+1);
4113  buf_dyn = new char[buf_sz];
4114  n = vsnprintf(buf_dyn, buf_sz, fmt, args);
4115  }
4116  // Print buffer content
4117  if (n>=0) uout() << (buf_dyn ? buf_dyn : buf) << std::flush;
4118  // Cleanup
4119  delete[] buf_dyn;
4120  va_end(args);
4121  // Throw error if failure
4122  casadi_assert(n>=0, "Print failure while processing '" + std::string(fmt) + "'");
4123  }

References casadi::uout().

Referenced by casadi::Feasiblesqpmethod::anderson_acc_step_update(), casadi::Nlpsol::callback(), convertHessian(), casadi::FmuFunction::eval_task(), casadi::Feasiblesqpmethod::feasibility_iterations(), feasibilityRestorationPhase(), fullstep(), init(), casadi::Feasiblesqpmethod::init(), casadi::Ipqp::init(), casadi::Qrqp::init(), casadi::Qrsqp::init(), casadi::Sqpmethod::init(), casadi::LinsolQr::nfact(), casadi::Feasiblesqpmethod::print_iteration(), casadi::Qrsqp::print_iteration(), casadi::Sqpmethod::print_iteration(), casadi::SundialsInterface::print_stats(), casadi::ProtoFunction::print_time(), printInfo(), printProgress(), run(), solve(), casadi::Feasiblesqpmethod::solve(), casadi::Qrsqp::solve(), casadi::Sqpmethod::solve(), casadi::Sqpmethod::solve_ela_QP(), casadi::Feasiblesqpmethod::solve_LP(), casadi::Feasiblesqpmethod::solve_QP(), casadi::Qrsqp::solve_QP(), casadi::Sqpmethod::solve_QP(), and solveQP().

◆ print_canonical() [1/3]

void casadi::FunctionInternal::print_canonical ( std::ostream &  stream,
casadi_int  sz,
const double *  nz 
)
staticinherited

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

Definition at line 909 of file function_internal.cpp.

909  {
910  StreamStateGuard backup(stream);
911  normalized_setup(stream);
912  if (nz) {
913  stream << "[";
914  for (casadi_int i=0; i<sz; ++i) {
915  if (i>0) stream << ", ";
916  normalized_out(stream, nz[i]);
917  }
918  stream << "]";
919  } else {
920  stream << "NULL";
921  }
922  }

References casadi::normalized_out(), and casadi::normalized_setup().

◆ print_canonical() [2/3]

void casadi::FunctionInternal::print_canonical ( std::ostream &  stream,
const Sparsity sp,
const double *  nz 
)
staticinherited

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

Definition at line 924 of file function_internal.cpp.

925  {
926  StreamStateGuard backup(stream);
927  normalized_setup(stream);
928  if (nz) {
929  if (!sp.is_scalar(true)) {
930  stream << sp.dim(false) << ": ";
931  stream << "[";
932  }
933  for (casadi_int i=0; i<sp.nnz(); ++i) {
934  if (i>0) stream << ", ";
935  normalized_out(stream, nz[i]);
936  }
937  if (!sp.is_scalar(true)) {
938  stream << "]";
939  if (!sp.is_dense()) {
940  stream << ", colind: [";
941  for (casadi_int i=0; i<sp.size2()+1; ++i) {
942  if (i>0) stream << ", ";
943  stream << sp.colind()[i];
944  }
945  stream << "]";
946  stream << ", row: [";
947  for (casadi_int i=0; i<sp.nnz(); ++i) {
948  if (i>0) stream << ", ";
949  stream << sp.row()[i];
950  }
951  stream << "]";
952  }
953  }
954  } else {
955  stream << "NULL";
956  }
957  }

References casadi::Sparsity::colind(), casadi::Sparsity::dim(), casadi::Sparsity::is_dense(), casadi::Sparsity::is_scalar(), casadi::Sparsity::nnz(), casadi::normalized_out(), casadi::normalized_setup(), casadi::Sparsity::row(), and casadi::Sparsity::size2().

Referenced by casadi::Monitor::eval(), casadi::MXFunction::print_arg(), casadi::SXFunction::print_arg(), casadi::FunctionInternal::print_in(), casadi::FunctionInternal::print_out(), casadi::MXFunction::print_res(), and casadi::SXFunction::print_res().

◆ print_canonical() [3/3]

void casadi::FunctionInternal::print_canonical ( std::ostream &  stream,
double  a 
)
staticinherited

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

Definition at line 959 of file function_internal.cpp.

959  {
960  StreamStateGuard backup(stream);
961  normalized_setup(stream);
962  normalized_out(stream, a);
963  }

References casadi::normalized_out(), and casadi::normalized_setup().

◆ print_dimensions()

void casadi::FunctionInternal::print_dimensions ( std::ostream &  stream) const
inherited

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

Definition at line 1034 of file function_internal.cpp.

1034  {
1035  stream << " Number of inputs: " << n_in_ << std::endl;
1036  for (casadi_int i=0; i<n_in_; ++i) {
1037  stream << " Input " << i << " (\"" << name_in_[i] << "\"): "
1038  << sparsity_in_[i].dim() << std::endl;
1039  }
1040  stream << " Number of outputs: " << n_out_ << std::endl;
1041  for (casadi_int i=0; i<n_out_; ++i) {
1042  stream << " Output " << i << " (\"" << name_out_[i] << "\"): "
1043  << sparsity_out_[i].dim() << std::endl;
1044  }
1045  }

References casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::sparsity_in_, and casadi::FunctionInternal::sparsity_out_.

◆ print_in()

void casadi::FunctionInternal::print_in ( std::ostream &  stream,
const double **  arg,
bool  truncate 
) const
inherited

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

Definition at line 875 of file function_internal.cpp.

875  {
876  stream << "Function " << name_ << " (" << this << ")" << std::endl;
877  for (casadi_int i=0; i<n_in_; ++i) {
878  stream << "Input " << i << " (" << name_in_[i] << "): ";
879  if (arg[i]) {
880  if (print_canonical_) {
881  print_canonical(stream, sparsity_in_[i], arg[i]);
882  } else {
883  DM::print_default(stream, sparsity_in_[i], arg[i], truncate);
884  }
885  stream << std::endl;
886  } else {
887  stream << "NULL" << std::endl;
888  }
889  }
890  }
static void print_canonical(std::ostream &stream, const Sparsity &sp, const double *nz)
Print canonical representation of a numeric matrix.
static void print_default(std::ostream &stream, const Sparsity &sp, const double *nonzeros, bool truncate=true)
Print default style.

References casadi::FunctionInternal::n_in_, casadi::ProtoFunction::name_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::print_canonical(), casadi::FunctionInternal::print_canonical_, casadi::Matrix< double >::print_default(), and casadi::FunctionInternal::sparsity_in_.

Referenced by casadi::FunctionInternal::eval_gen().

◆ print_option()

void casadi::ProtoFunction::print_option ( const std::string &  name,
std::ostream &  stream 
) const
inherited

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

Definition at line 1051 of file function_internal.cpp.

1051  {
1052  get_options().print_one(name, stream);
1053  }
void print_one(const std::string &name, std::ostream &stream) const
Print all information there is to know about a certain option.
Definition: options.cpp:274

References casadi::ProtoFunction::get_options(), and casadi::Options::print_one().

◆ print_options()

void casadi::ProtoFunction::print_options ( std::ostream &  stream) const
inherited

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

Definition at line 1047 of file function_internal.cpp.

1047  {
1048  get_options().print_all(stream);
1049  }
void print_all(std::ostream &stream) const
Print list of options.
Definition: options.cpp:268

References casadi::ProtoFunction::get_options(), and casadi::Options::print_all().

◆ print_out()

void casadi::FunctionInternal::print_out ( std::ostream &  stream,
double **  res,
bool  truncate 
) const
inherited

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

Definition at line 892 of file function_internal.cpp.

892  {
893  stream << "Function " << name_ << " (" << this << ")" << std::endl;
894  for (casadi_int i=0; i<n_out_; ++i) {
895  stream << "Output " << i << " (" << name_out_[i] << "): ";
896  if (res[i]) {
897  if (print_canonical_) {
898  print_canonical(stream, sparsity_out_[i], res[i]);
899  } else {
900  DM::print_default(stream, sparsity_out_[i], res[i], truncate);
901  }
902  stream << std::endl;
903  } else {
904  stream << "NULL" << std::endl;
905  }
906  }
907  }

References casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::print_canonical(), casadi::FunctionInternal::print_canonical_, casadi::Matrix< double >::print_default(), and casadi::FunctionInternal::sparsity_out_.

Referenced by casadi::FunctionInternal::eval_gen().

◆ print_time()

void casadi::ProtoFunction::print_time ( const std::map< std::string, FStats > &  fstats) const
inherited

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

Definition at line 4020 of file function_internal.cpp.

4020  {
4021  if (!print_time_) return;
4022  // Length of the name being printed
4023  size_t name_len=0;
4024  for (auto &&s : fstats) {
4025  name_len = std::max(s.first.size(), name_len);
4026  }
4027  name_len = std::max(name_.size(), name_len);
4028 
4029  // Print name with a given length. Format: "%NNs "
4030  char namefmt[10];
4031  sprint(namefmt, sizeof(namefmt), "%%%ds ", static_cast<casadi_int>(name_len));
4032 
4033  // Print header
4034  print(namefmt, name_.c_str());
4035 
4036  print(" : %8s %10s %8s %10s %9s\n", "t_proc", "(avg)", "t_wall", "(avg)", "n_eval");
4037 
4038 
4039  char buffer_proc[10];
4040  char buffer_wall[10];
4041  char buffer_proc_avg[10];
4042  char buffer_wall_avg[10];
4043 
4044  // Print keys
4045  for (const auto &s : fstats) {
4046  if (s.second.n_call!=0) {
4047  print(namefmt, s.first.c_str());
4048  format_time(buffer_proc, s.second.t_proc);
4049  format_time(buffer_wall, s.second.t_wall);
4050  format_time(buffer_proc_avg, s.second.t_proc/s.second.n_call);
4051  format_time(buffer_wall_avg, s.second.t_wall/s.second.n_call);
4052  print(" | %s (%s) %s (%s) %9d\n",
4053  buffer_proc, buffer_proc_avg,
4054  buffer_wall, buffer_wall_avg, s.second.n_call);
4055  }
4056  }
4057  }
void format_time(char *buffer, double time) const
Format time in a fixed width 8 format.

References casadi::ProtoFunction::format_time(), casadi::ProtoFunction::name_, casadi::ProtoFunction::print(), casadi::ProtoFunction::print_time_, and casadi::ProtoFunction::sprint().

Referenced by casadi::FunctionInternal::eval_gen().

◆ printInfo()

void casadi::Blocksqp::printInfo ( BlocksqpMemory m) const

Definition at line 1012 of file blocksqp.cpp.

1012  {
1013  char hessString1[100];
1014  char hessString2[100];
1015  char globString[100];
1016  char qpString[100];
1017 
1018  /* QP Solver */
1019  if (schur_)
1020  strcpy(qpString, "sparse, Schur complement approach");
1021  else
1022  strcpy(qpString, "sparse, reduced Hessian factorization");
1023 
1024  /* Globalization */
1025  if (globalization_) {
1026  strcpy(globString, "filter line search");
1027  } else {
1028  strcpy(globString, "none (full step)");
1029  }
1030 
1031  /* Hessian approximation */
1032  if (block_hess_ && (hess_update_ == 1 || hess_update_ == 2))
1033  strcpy(hessString1, "block ");
1034  else
1035  strcpy(hessString1, "");
1036 
1037  if (hess_lim_mem_ && (hess_update_ == 1 || hess_update_ == 2))
1038  strcat(hessString1, "L-");
1039 
1040  /* Fallback Hessian */
1041  if (hess_update_ == 1 || hess_update_ == 4
1042  || (hess_update_ == 2 && !hess_damp_)) {
1043  strcpy(hessString2, hessString1);
1044 
1045  /* Fallback Hessian update type */
1046  if (fallback_update_ == 0) {
1047  strcat(hessString2, "Id");
1048  } else if (fallback_update_ == 1) {
1049  strcat(hessString2, "SR1");
1050  } else if (fallback_update_ == 2) {
1051  strcat(hessString2, "BFGS");
1052  } else if (fallback_update_ == 4) {
1053  strcat(hessString2, "Finite differences");
1054  }
1055 
1056  /* Fallback Hessian scaling */
1057  if (fallback_scaling_ == 1) {
1058  strcat(hessString2, ", SP");
1059  } else if (fallback_scaling_ == 2) {
1060  strcat(hessString2, ", OL");
1061  } else if (fallback_scaling_ == 3) {
1062  strcat(hessString2, ", mean");
1063  } else if (fallback_scaling_ == 4) {
1064  strcat(hessString2, ", selective sizing");
1065  }
1066  } else {
1067  strcpy(hessString2, "-");
1068  }
1069 
1070  /* First Hessian update type */
1071  if (hess_update_ == 0) {
1072  strcat(hessString1, "Id");
1073  } else if (hess_update_ == 1) {
1074  strcat(hessString1, "SR1");
1075  } else if (hess_update_ == 2) {
1076  strcat(hessString1, "BFGS");
1077  } else if (hess_update_ == 4) {
1078  strcat(hessString1, "Finite differences");
1079  }
1080 
1081  /* First Hessian scaling */
1082  if (hess_scaling_ == 1) {
1083  strcat(hessString1, ", SP");
1084  } else if (hess_scaling_ == 2) {
1085  strcat(hessString1, ", OL");
1086  } else if (hess_scaling_ == 3) {
1087  strcat(hessString1, ", mean");
1088  } else if (hess_scaling_ == 4) {
1089  strcat(hessString1, ", selective sizing");
1090  }
1091 
1092  print("\n+---------------------------------------------------------------+\n");
1093  print("| Starting blockSQP with the following algorithmic settings: |\n");
1094  print("+---------------------------------------------------------------+\n");
1095  print("| qpOASES flavor | %-34s|\n", qpString);
1096  print("| Globalization | %-34s|\n", globString);
1097  print("| 1st Hessian approximation | %-34s|\n", hessString1);
1098  print("| 2nd Hessian approximation | %-34s|\n", hessString2);
1099  print("+---------------------------------------------------------------+\n\n");
1100  }

References block_hess_, fallback_scaling_, fallback_update_, globalization_, hess_damp_, hess_lim_mem_, hess_scaling_, hess_update_, casadi::ProtoFunction::print(), and schur_.

Referenced by solve().

◆ printProgress()

void casadi::Blocksqp::printProgress ( BlocksqpMemory m) const

Definition at line 2555 of file blocksqp.cpp.

2555  {
2556  /*
2557  * m->steptype:
2558  *-1: full step was accepted because it reduces the KKT error although line search failed
2559  * 0: standard line search step
2560  * 1: Hessian has been reset to identity
2561  * 2: feasibility restoration heuristic has been called
2562  * 3: feasibility restoration phase has been called
2563  */
2564 
2565  // Print headline every twenty iterations
2566  if (m->itCount % 20 == 0) {
2567  print("%-8s", " it");
2568  print("%-21s", " qpIt");
2569  print("%-9s", "obj");
2570  print("%-11s", "feas");
2571  print("%-7s", "opt");
2572  print("%-11s", "|lgrd|");
2573  print("%-9s", "|stp|");
2574  print("%-10s", "|lstp|");
2575  print("%-8s", "alpha");
2576  print("%-6s", "nSOCS");
2577  print("%-18s", "sk, da, sca");
2578  print("%-6s", "QPr,mu");
2579  print("\n");
2580  }
2581 
2582  if (m->itCount == 0) {
2583  // Values for first iteration
2584  print("%5i ", m->itCount);
2585  print("%11i ", 0);
2586  print("% 10e ", m->obj);
2587  print("%-10.2e", m->cNormS);
2588  print("%-10.2e", m->tol);
2589  print("\n");
2590  } else {
2591  // All values
2592  print("%5i ", m->itCount);
2593  print("%5i+%5i ", m->qpIterations, m->qpIterations2);
2594  print("% 10e ", m->obj);
2595  print("%-10.2e", m->cNormS);
2596  print("%-10.2e", m->tol);
2597  print("%-10.2e", m->gradNorm);
2598  print("%-10.2e", casadi_norm_inf(nx_, m->dxk));
2599  print("%-10.2e", m->lambdaStepNorm);
2600  print("%-9.1e", m->alpha);
2601  print("%5i", m->nSOCS);
2602  print("%3i, %3i, %-9.1e", m->hessSkipped, m->hessDamped, m->averageSizingFactor);
2603  print("%i, %-9.1e", m->qpResolve, casadi_norm_1(nblocks_, m->delta_h)/nblocks_);
2604  print("\n");
2605  }
2606  }
T1 casadi_norm_1(casadi_int n, const T1 *x)
NORM_1: ||x||_1 -> return.

References casadi::BlocksqpMemory::alpha, casadi::BlocksqpMemory::averageSizingFactor, casadi::casadi_norm_1(), casadi::casadi_norm_inf(), casadi::BlocksqpMemory::cNormS, casadi::BlocksqpMemory::delta_h, casadi::BlocksqpMemory::dxk, casadi::BlocksqpMemory::gradNorm, casadi::BlocksqpMemory::hessDamped, casadi::BlocksqpMemory::hessSkipped, casadi::BlocksqpMemory::itCount, casadi::BlocksqpMemory::lambdaStepNorm, nblocks_, casadi::BlocksqpMemory::nSOCS, casadi::Nlpsol::nx_, casadi::BlocksqpMemory::obj, casadi::ProtoFunction::print(), casadi::BlocksqpMemory::qpIterations, casadi::BlocksqpMemory::qpIterations2, casadi::BlocksqpMemory::qpResolve, and casadi::BlocksqpMemory::tol.

Referenced by feasibilityRestorationPhase(), and run().

◆ project_arg()

template<typename M >
std::vector< M > casadi::FunctionInternal::project_arg ( const std::vector< M > &  arg,
casadi_int  npar 
) const
inherited

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

Definition at line 1673 of file function_internal.hpp.

1674  {
1675  casadi_assert_dev(arg.size()==n_in_);
1676 
1677  // Which arguments require mapped evaluation
1678  std::vector<bool> mapped(n_in_);
1679  for (casadi_int i=0; i<n_in_; ++i) {
1680  mapped[i] = arg[i].size2()!=size2_in(i);
1681  }
1682 
1683  // Check if matching input sparsity
1684  std::vector<bool> matching(n_in_);
1685  bool any_mismatch = false;
1686  for (casadi_int i=0; i<n_in_; ++i) {
1687  if (mapped[i]) {
1688  matching[i] = arg[i].sparsity().is_stacked(sparsity_in(i), npar);
1689  } else {
1690  matching[i] = arg[i].sparsity()==sparsity_in(i);
1691  }
1692  any_mismatch = any_mismatch || !matching[i];
1693  }
1694 
1695  // Correct input sparsity
1696  if (any_mismatch) {
1697  std::vector<M> arg2(arg);
1698  for (casadi_int i=0; i<n_in_; ++i) {
1699  if (!matching[i]) {
1700  if (mapped[i]) {
1701  arg2[i] = project(arg2[i], repmat(sparsity_in(i), 1, npar));
1702  } else {
1703  arg2[i] = project(arg2[i], sparsity_in(i));
1704  }
1705  }
1706  }
1707  return arg2;
1708  }
1709  return arg;
1710  }

References casadi::FunctionInternal::n_in_, casadi::FunctionInternal::size2_in(), and casadi::FunctionInternal::sparsity_in().

Referenced by casadi::FunctionInternal::call_gen(), and casadi::FunctionInternal::nz_in().

◆ project_res()

template<typename M >
std::vector< M > casadi::FunctionInternal::project_res ( const std::vector< M > &  arg,
casadi_int  npar 
) const
inherited

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

Definition at line 1713 of file function_internal.hpp.

1714  {
1715  return arg;
1716  }

Referenced by casadi::FunctionInternal::nz_out().

◆ purgable()

template<typename MatType >
bool casadi::FunctionInternal::purgable ( const std::vector< MatType > &  seed)
staticinherited

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

Definition at line 1566 of file function_internal.hpp.

1566  {
1567  for (auto i=v.begin(); i!=v.end(); ++i) {
1568  if (!i->is_zero()) return false;
1569  }
1570  return true;
1571  }

Referenced by casadi::MXFunction::ad_forward(), and casadi::MXFunction::ad_reverse().

◆ reduceSOCStepsize()

void casadi::Blocksqp::reduceSOCStepsize ( BlocksqpMemory m,
double *  alphaSOC 
) const

Definition at line 1150 of file blocksqp.cpp.

1151  {
1152  auto d_nlp = &m->d_nlp;
1153  // Update bounds on linearized constraints for the next SOC QP:
1154  // That is different from the update for the first SOC QP!
1155  for (casadi_int i=0; i<ng_; i++) {
1156  double lbg = d_nlp->lbz[i + nx_];
1157  double ubg = d_nlp->ubz[i + nx_];
1158  if (lbg != inf) {
1159  m->lba_qp[i] = *alphaSOC * m->lba_qp[i] - m->gk[i];
1160  } else {
1161  m->lba_qp[i] = inf;
1162  }
1163 
1164  if (ubg != inf) {
1165  m->uba_qp[i] = *alphaSOC * m->uba_qp[i] - m->gk[i];
1166  } else {
1167  m->uba_qp[i] = inf;
1168  }
1169  }
1170 
1171  *alphaSOC *= 0.5;
1172  }

References casadi::NlpsolMemory::d_nlp, casadi::BlocksqpMemory::gk, casadi::inf, casadi::BlocksqpMemory::lba_qp, casadi_nlpsol_data< T1 >::lbz, casadi::Nlpsol::ng_, casadi::Nlpsol::nx_, and casadi::BlocksqpMemory::uba_qp.

◆ reduceStepsize()

void casadi::Blocksqp::reduceStepsize ( BlocksqpMemory m,
double *  alpha 
) const

Definition at line 1145 of file blocksqp.cpp.

1146  {
1147  *alpha = (*alpha) * 0.5;
1148  }

Referenced by filterLineSearch(), and fullstep().

◆ registerPlugin() [1/2]

void casadi::PluginInterface< Nlpsol >::registerPlugin ( const Plugin &  plugin,
bool  needs_lock = true 
)
staticinherited

Definition at line 96 of file plugin_interface.hpp.

278  {
279 
280 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
281  casadi::conditional_lock_guard<std::mutex> lock(Derived::mutex_solvers_, needs_lock);
282 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
283 
284  // Check if the solver name is in use
285  typename std::map<std::string, Plugin>::iterator it=Derived::solvers_.find(plugin.name);
286  casadi_assert(it==Derived::solvers_.end(),
287  "Solver " + str(plugin.name) + " is already in use");
288 
289  // Add to list of solvers
290  Derived::solvers_[plugin.name] = plugin;
291  }

◆ registerPlugin() [2/2]

void casadi::PluginInterface< Nlpsol >::registerPlugin ( RegFcn  regfcn,
bool  needs_lock = true 
)
staticinherited

Definition at line 99 of file plugin_interface.hpp.

273  {
274  registerPlugin(pluginFromRegFcn(regfcn), needs_lock);
275  }

◆ release()

void casadi::ProtoFunction::release ( int  mem) const
inherited

Definition at line 3879 of file function_internal.cpp.

3879  {
3880 #ifdef CASADI_WITH_THREAD
3881  std::lock_guard<std::mutex> lock(mtx_);
3882 #endif //CASADI_WITH_THREAD
3883  unused_.push(mem);
3884  }

Referenced by casadi::FunctionInternal::codegen_meta().

◆ replace_arg()

template<typename M >
std::vector< M > casadi::FunctionInternal::replace_arg ( const std::vector< M > &  arg,
casadi_int  npar 
) const
inherited

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

Definition at line 1848 of file function_internal.hpp.

1849  {
1850  std::vector<M> r(arg.size());
1851  for (casadi_int i=0; i<r.size(); ++i) r[i] = replace_mat(arg[i], sparsity_in(i), npar);
1852  return r;
1853  }

References casadi::replace_mat(), and casadi::FunctionInternal::sparsity_in().

Referenced by casadi::FunctionInternal::call(), casadi::FunctionInternal::nz_in(), and casadi::FunctionInternal::replace_fseed().

◆ replace_aseed() [1/2]

template<typename M >
std::vector<std::vector<M> > casadi::FunctionInternal::replace_aseed ( const std::vector< std::vector< M > > &  aseed,
casadi_int  npar 
) const
inherited

Definition at line 1872 of file function_internal.hpp.

1873  {
1874  std::vector<std::vector<M> > r(aseed.size());
1875  for (casadi_int d=0; d<r.size(); ++d) r[d] = replace_res(aseed[d], npar);
1876  return r;
1877  }

References casadi::FunctionInternal::replace_res().

◆ replace_aseed() [2/2]

template<typename M >
std::vector<std::vector<M> > casadi::FunctionInternal::replace_aseed ( const std::vector< std::vector< M >> &  aseed,
casadi_int  npar 
) const
inherited

◆ replace_fseed() [1/2]

template<typename M >
std::vector<std::vector<M> > casadi::FunctionInternal::replace_fseed ( const std::vector< std::vector< M > > &  fseed,
casadi_int  npar 
) const
inherited

Definition at line 1864 of file function_internal.hpp.

1865  {
1866  std::vector<std::vector<M> > r(fseed.size());
1867  for (casadi_int d=0; d<r.size(); ++d) r[d] = replace_arg(fseed[d], npar);
1868  return r;
1869  }

References casadi::FunctionInternal::replace_arg().

◆ replace_fseed() [2/2]

template<typename M >
std::vector<std::vector<M> > casadi::FunctionInternal::replace_fseed ( const std::vector< std::vector< M >> &  fseed,
casadi_int  npar 
) const
inherited

◆ replace_res()

template<typename M >
std::vector< M > casadi::FunctionInternal::replace_res ( const std::vector< M > &  res,
casadi_int  npar 
) const
inherited

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

Definition at line 1856 of file function_internal.hpp.

1857  {
1858  std::vector<M> r(res.size());
1859  for (casadi_int i=0; i<r.size(); ++i) r[i] = replace_mat(res[i], sparsity_out(i), npar);
1860  return r;
1861  }

References casadi::replace_mat(), and casadi::FunctionInternal::sparsity_out().

Referenced by casadi::FunctionInternal::nz_out(), and casadi::FunctionInternal::replace_aseed().

◆ reset_dump_count()

void casadi::FunctionInternal::reset_dump_count ( )
inherited

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

Definition at line 471 of file function_internal.cpp.

471  {
472  dump_count_ = 0;
473  }

References casadi::FunctionInternal::dump_count_.

◆ reset_sqp()

void casadi::Blocksqp::reset_sqp ( BlocksqpMemory m) const

Allocate memory for variables required by all optimization algorithms except for the Jacobian

Definition at line 2637 of file blocksqp.cpp.

2637  {
2638  // dual variables (for general constraints and variable bounds)
2639  casadi_fill(m->lam_xk, nx_, 0.);
2640  casadi_fill(m->lam_gk, ng_, 0.);
2641 
2642  // constraint vector with lower and upper bounds
2643  // (Box constraints are not included in the constraint list)
2644  casadi_fill(m->gk, ng_, 0.);
2645 
2646  // gradient of objective
2647  casadi_fill(m->grad_fk, nx_, 0.);
2648 
2649  // gradient of Lagrangian
2650  casadi_fill(m->grad_lagk, nx_, 0.);
2651 
2652  // current step
2653  casadi_fill(m->deltaMat, nx_*hess_memsize_, 0.);
2654  m->dxk = m->deltaMat;
2655 
2656  // trial step (temporary variable, for line search)
2657  casadi_fill(m->trial_xk, nx_, 0.);
2658 
2659  // bounds for step (QP subproblem)
2660  casadi_fill(m->lbx_qp, nx_, 0.);
2661  casadi_fill(m->ubx_qp, nx_, 0.);
2662  casadi_fill(m->lba_qp, ng_, 0.);
2663  casadi_fill(m->uba_qp, ng_, 0.);
2664 
2665  // product of constraint Jacobian with step (deltaXi)
2666  casadi_fill(m->jac_times_dxk, ng_, 0.);
2667 
2668  // dual variables of QP (simple bounds and general constraints)
2669  casadi_fill(m->lam_qp, nx_+ng_, 0.);
2670 
2671  // line search parameters
2672  casadi_fill(m->delta_h, nblocks_, 0.);
2673 
2674  // filter as a set of pairs
2675  m->filter.clear();
2676 
2677  // difference of Lagrangian gradients
2678  casadi_fill(m->gammaMat, nx_*hess_memsize_, 0.);
2679  m->gamma = m->gammaMat;
2680 
2681  // Scalars that are used in various Hessian update procedures
2682  casadi_fill(m->noUpdateCounter, nblocks_, casadi_int(-1));
2683 
2684  // For selective sizing: for each block save sTs, sTs_, sTy, sTy_
2685  casadi_fill(m->delta_norm, nblocks_, 1.);
2686  casadi_fill(m->delta_norm_old, nblocks_, 1.);
2687  casadi_fill(m->delta_gamma, nblocks_, 0.);
2688  casadi_fill(m->delta_gamma_old, nblocks_, 0.);
2689 
2690  // Create one Matrix for one diagonal block in the Hessian
2691  for (casadi_int b=0; b<nblocks_; b++) {
2692  casadi_int dim = dim_[b];
2693  casadi_fill(m->hess1[b], dim*dim, 0.);
2694  }
2695 
2696  // For SR1 or finite differences, maintain two Hessians
2697  if (hess_update_ == 1 || hess_update_ == 4) {
2698  for (casadi_int b=0; b<nblocks_; b++) {
2699  casadi_int dim = dim_[b];
2700  casadi_fill(m->hess2[b], dim*dim, 0.);
2701  }
2702  }
2703 
2704  // Set Hessian pointer
2705  m->hess = m->hess1;
2706  }

References casadi::casadi_fill(), casadi::BlocksqpMemory::delta_gamma, casadi::BlocksqpMemory::delta_gamma_old, casadi::BlocksqpMemory::delta_h, casadi::BlocksqpMemory::delta_norm, casadi::BlocksqpMemory::delta_norm_old, casadi::BlocksqpMemory::deltaMat, dim_, casadi::BlocksqpMemory::dxk, casadi::BlocksqpMemory::filter, casadi::BlocksqpMemory::gamma, casadi::BlocksqpMemory::gammaMat, casadi::BlocksqpMemory::gk, casadi::BlocksqpMemory::grad_fk, casadi::BlocksqpMemory::grad_lagk, casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hess1, casadi::BlocksqpMemory::hess2, hess_memsize_, hess_update_, casadi::BlocksqpMemory::jac_times_dxk, casadi::BlocksqpMemory::lam_gk, casadi::BlocksqpMemory::lam_qp, casadi::BlocksqpMemory::lam_xk, casadi::BlocksqpMemory::lba_qp, casadi::BlocksqpMemory::lbx_qp, nblocks_, casadi::Nlpsol::ng_, casadi::BlocksqpMemory::noUpdateCounter, casadi::Nlpsol::nx_, casadi::BlocksqpMemory::trial_xk, casadi::BlocksqpMemory::uba_qp, and casadi::BlocksqpMemory::ubx_qp.

Referenced by solve().

◆ resetHessian() [1/2]

void casadi::Blocksqp::resetHessian ( BlocksqpMemory m) const

Definition at line 1794 of file blocksqp.cpp.

1794  {
1795  for (casadi_int b=0; b<nblocks_; b++) {
1796  if (!(which_second_derv_ == 1 && block_hess_ && b == nblocks_ - 1)) {
1797  // if objective derv is computed exactly, don't set the last block!
1798  resetHessian(m, b);
1799  }
1800  }
1801  }

References block_hess_, nblocks_, and which_second_derv_.

Referenced by calcHessianUpdate(), calcHessianUpdateLimitedMemory(), feasibilityRestorationPhase(), and run().

◆ resetHessian() [2/2]

void casadi::Blocksqp::resetHessian ( BlocksqpMemory m,
casadi_int  b 
) const

Definition at line 1804 of file blocksqp.cpp.

1804  {
1805  casadi_int dim = dim_[b];
1806 
1807  // smallGamma and smallDelta are either subvectors of gamma and delta
1808  // or submatrices of gammaMat, deltaMat, i.e. subvectors of gamma and delta
1809  // from m prev. iterations (for L-BFGS)
1810  double *smallGamma = m->gammaMat + blocks_[b];
1811  double *smallDelta = m->deltaMat + blocks_[b];
1812 
1813  for (casadi_int i=0; i<hess_memsize_; ++i) {
1814  // Remove past information on Lagrangian gradient difference
1815  casadi_fill(smallGamma, dim, 0.);
1816  smallGamma += nx_;
1817 
1818  // Remove past information on steps
1819  smallDelta += nx_;
1820  casadi_fill(smallDelta, dim, 0.);
1821  }
1822 
1823  // Remove information on old scalars (used for COL sizing)
1824  m->delta_norm[b] = 1.0;
1825  m->delta_gamma[b] = 0.0;
1826  m->delta_norm_old[b] = 1.0;
1827  m->delta_gamma_old[b] = 0.0;
1828 
1829  m->noUpdateCounter[b] = -1;
1830 
1831  calcInitialHessian(m, b);
1832  }

References blocks_, calcInitialHessian(), casadi::casadi_fill(), casadi::BlocksqpMemory::delta_gamma, casadi::BlocksqpMemory::delta_gamma_old, casadi::BlocksqpMemory::delta_norm, casadi::BlocksqpMemory::delta_norm_old, casadi::BlocksqpMemory::deltaMat, dim_, casadi::BlocksqpMemory::gammaMat, hess_memsize_, casadi::BlocksqpMemory::noUpdateCounter, and casadi::Nlpsol::nx_.

◆ reverse()

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

reverse(nadj) returns a cached instance if available, and calls Function get_reverse(casadi_int nadj) if no cached version is available.

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

Definition at line 2285 of file function_internal.cpp.

2285  {
2286  casadi_assert_dev(nadj>=0);
2287  // Used wrapped function if reverse not available
2288  if (!enable_reverse_) {
2289  // Derivative information must be available
2290  casadi_assert(has_derivative(), "Derivatives cannot be calculated for " + name_);
2291  return wrap().reverse(nadj);
2292  }
2293  // Retrieve/generate cached
2294  Function f;
2295  std::string fname = reverse_name(name_, nadj);
2296  if (!incache(fname, f)) {
2297  casadi_int i;
2298  // Prefix to be used for adjoint seeds, sensitivities
2299  std::string pref = diff_prefix("adj");
2300  // Names of inputs
2301  std::vector<std::string> inames;
2302  for (i=0; i<n_in_; ++i) inames.push_back(name_in_[i]);
2303  for (i=0; i<n_out_; ++i) inames.push_back("out_" + name_out_[i]);
2304  for (i=0; i<n_out_; ++i) inames.push_back(pref + name_out_[i]);
2305  // Names of outputs
2306  std::vector<std::string> onames;
2307  for (casadi_int i=0; i<n_in_; ++i) onames.push_back(pref + name_in_[i]);
2308  // Options
2310  opts = combine(opts, generate_options("reverse"));
2311  opts["derivative_of"] = self();
2312  // Generate derivative function
2313  casadi_assert_dev(enable_reverse_);
2314  f = get_reverse(nadj, fname, inames, onames, opts);
2315  // Consistency check for inputs
2316  casadi_assert_dev(f.n_in()==n_in_ + n_out_ + n_out_);
2317  casadi_int ind=0;
2318  for (i=0; i<n_in_; ++i) f.assert_size_in(ind++, size1_in(i), size2_in(i));
2319  for (i=0; i<n_out_; ++i) f.assert_size_in(ind++, size1_out(i), size2_out(i));
2320  for (i=0; i<n_out_; ++i) f.assert_size_in(ind++, size1_out(i), nadj*size2_out(i));
2321  // Consistency check for outputs
2322  casadi_assert_dev(f.n_out()==n_in_);
2323  for (i=0; i<n_in_; ++i) f.assert_sparsity_out(i, sparsity_in(i), nadj);
2324  // Save to cache
2325  tocache_if_missing(f);
2326  }
2327  return f;
2328  }
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.
static std::string reverse_name(const std::string &fcn, casadi_int nadj)
Helper function: Get name of adjoint derivative function.
Function reverse(casadi_int nadj) const
Get a function that calculates nadj adjoint derivatives.
Definition: function.cpp:1332

References casadi::Function::assert_size_in(), casadi::Function::assert_sparsity_out(), casadi::combine(), casadi::FunctionInternal::der_options_, casadi::FunctionInternal::diff_prefix(), casadi::FunctionInternal::enable_reverse_, casadi::FunctionInternal::generate_options(), casadi::FunctionInternal::get_reverse(), casadi::FunctionInternal::has_derivative(), casadi::FunctionInternal::incache(), casadi::Function::n_in(), casadi::FunctionInternal::n_in_, casadi::Function::n_out(), casadi::FunctionInternal::n_out_, casadi::ProtoFunction::name_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::Function::reverse(), casadi::FunctionInternal::reverse_name(), casadi::FunctionInternal::reverse_options_, casadi::FunctionInternal::size1_in(), casadi::FunctionInternal::size1_out(), casadi::FunctionInternal::size2_in(), casadi::FunctionInternal::size2_out(), casadi::FunctionInternal::sparsity_in(), casadi::FunctionInternal::tocache_if_missing(), and casadi::FunctionInternal::wrap().

Referenced by casadi::FunctionInternal::call_reverse(), and casadi::Function::reverse().

◆ reverse_name()

static std::string casadi::FunctionInternal::reverse_name ( const std::string &  fcn,
casadi_int  nadj 
)
inlinestaticinherited

Definition at line 672 of file function_internal.hpp.

672  {
673  return "adj" + str(nadj) + "_" + fcn;
674  }

References casadi::str().

Referenced by casadi::FunctionInternal::reverse(), and casadi::FixedStepIntegrator::stepB().

◆ run()

casadi_int casadi::Blocksqp::run ( BlocksqpMemory m,
casadi_int  maxIt,
casadi_int  warmStart = 0 
) const

Set initial Hessian approximation

Evaluate all functions and gradients for xk_0

Check if converged

Solve QP subproblem with qpOASES or QPOPT

Determine steplength alpha

Calculate "old" Lagrange gradient: gamma = dL(xi_k, lambda_k+1)

Evaluate functions and gradients at the new xk

Check if converged

Print one line of output for the current iteration

Calculate difference of old and new Lagrange gradient:

Revise Hessian approximation

Definition at line 740 of file blocksqp.cpp.

740  {
741  casadi_int it, infoQP = 0;
742  bool skipLineSearch = false;
743  bool hasConverged = false;
744 
745  if (warmStart == 0 || m->itCount == 0) {
746  // SQP iteration 0
747 
750 
752  switch (evaluate(m, &m->obj, m->gk, m->grad_fk, m->jac_g)) {
753  case -1:
754  m->unified_return_status = SOLVER_RET_NAN;
755  return -1;
756  case 0:
757  break;
758  default:
759  return 1;
760  }
761  m->nDerCalls++;
762 
764  hasConverged = calcOptTol(m);
766  updateStats(m);
767  if (hasConverged) {
768  if (print_iteration_ && m->steptype < 2) {
769  print("\n***CONVERGENCE ACHIEVED!***\n");
770  }
771  return 0;
772  }
773  m->itCount++;
774  }
775 
776  /*
777  * SQP Loop: during first iteration, m->itCount = 1
778  */
779  for (it=0; it<maxIt; it++) {
781  updateStepBounds(m, 0);
782  infoQP = solveQP(m, m->dxk, m->lam_qp);
783 
784  if (infoQP == 1) {
785  // 1.) Maximum number of iterations reached
786  print("***WARNING: Maximum number of QP iterations exceeded.***\n");
787  } else if (infoQP == 2 || infoQP > 3) {
788  // 2.) QP error (e.g., unbounded), solve again with pos.def. diagonal matrix (identity)
789  print("***WARNING: QP error. Solve again with identity matrix.***\n");
790  resetHessian(m);
791  infoQP = solveQP(m, m->dxk, m->lam_qp);
792  if (infoQP) {
793  // If there is still an error, terminate.
794  print("***WARNING: QP error. Stop.***\n");
795  return -1;
796  } else {
797  m->steptype = 1;
798  }
799  } else if (infoQP == 3) {
800  // 3.) QP infeasible, try to restore feasibility
801  bool qpError = true;
802  skipLineSearch = true; // don't do line search with restoration step
803 
804  // Try to reduce constraint violation by heuristic
805  if (m->steptype < 2) {
806  print("***WARNING: QP infeasible. Trying to reduce constraint violation ...");
807  qpError = feasibilityRestorationHeuristic(m);
808  if (!qpError) {
809  m->steptype = 2;
810  print("Success.***\n");
811  } else {
812  print("Failure.***\n");
813  }
814  }
815 
816  // Invoke feasibility restoration phase
817  //if (qpError && m->steptype < 3 && restore_feas_)
818  if (qpError && restore_feas_ && m->cNorm > 0.01 * nlinfeastol_) {
819  print("***Start feasibility restoration phase.***\n");
820  m->steptype = 3;
821  qpError = feasibilityRestorationPhase(m);
822  }
823 
824  // If everything failed, abort.
825  if (qpError) {
826  print("***WARNING: QP error. Stop.\n");
827  return -1;
828  }
829  }
830 
832  if (!globalization_ || (skip_first_globalization_ && m->itCount == 1)) {
833  // No globalization strategy, but reduce step if function cannot be evaluated
834  if (fullstep(m)) {
835  print("***WARNING: Constraint or objective could "
836  "not be evaluated at new point. Stop.***\n");
837  return -1;
838  }
839  m->steptype = 0;
840  } else if (globalization_ && !skipLineSearch) {
841  // Filter line search based on Waechter et al., 2006 (Ipopt paper)
842  if (filterLineSearch(m) || m->reducedStepCount > max_consec_reduced_steps_) {
843  // Filter line search did not produce a step. Now there are a few things we can try ...
844  bool lsError = true;
845 
846  // Heuristic 1: Check if the full step reduces the KKT error by at
847  // least kappaF, if so, accept the step.
848  lsError = kktErrorReduction(m);
849  if (!lsError)
850  m->steptype = -1;
851 
852  // Heuristic 2: Try to reduce constraint violation by closing
853  // continuity gaps to produce an admissable iterate
854  if (lsError && m->cNorm > 0.01 * nlinfeastol_ && m->steptype < 2) {
855  // Don't do this twice in a row!
856  print("***WARNING: Steplength too short. "
857  "Trying to reduce constraint violation...");
858 
859  // Integration over whole time interval
860  lsError = feasibilityRestorationHeuristic(m);
861  if (!lsError) {
862  m->steptype = 2;
863  print("Success.***\n");
864  } else {
865  print("***WARNING: Failed.***\n");
866  }
867  }
868 
869  // Heuristic 3: Recompute step with a diagonal Hessian
870  if (lsError && m->steptype != 1 && m->steptype != 2) {
871  // After closing continuity gaps, we already take a step with initial Hessian.
872  // If this step is not accepted then this will cause an infinite loop!
873 
874  print("***WARNING: Steplength too short. "
875  "Trying to find a new step with identity Hessian.***\n");
876  m->steptype = 1;
877 
878  resetHessian(m);
879  continue;
880  }
881 
882  // If this does not yield a successful step, start restoration phase
883  if (lsError && m->cNorm > 0.01 * nlinfeastol_ && restore_feas_) {
884  print("***WARNING: Steplength too short. "
885  "Start feasibility restoration phase.***\n");
886  m->steptype = 3;
887 
888  // Solve NLP with minimum norm objective
889  lsError = feasibilityRestorationPhase(m);
890  }
891 
892  // If everything failed, abort.
893  if (lsError) {
894  print("***WARNING: Line search error. Stop.***\n");
895  return -1;
896  }
897  } else {
898  m->steptype = 0;
899  }
900  }
901 
903  calcLagrangeGradient(m, m->gamma, 0);
904 
906  (void)evaluate(m, &m->obj, m->gk, m->grad_fk, m->jac_g);
907  m->nDerCalls++;
908 
910  hasConverged = calcOptTol(m);
911 
914  updateStats(m);
915  if (hasConverged && m->steptype < 2) {
916  if (print_iteration_) print("\n***CONVERGENCE ACHIEVED!***\n");
917  m->itCount++;
918  return 0; //Convergence achieved!
919  }
920 
922  // gamma = -gamma + dL(xi_k+1, lambda_k+1)
923  calcLagrangeGradient(m, m->gamma, 1);
924 
926  if (hess_update_ < 4 && !hess_lim_mem_) {
928  } else if (hess_update_ < 4 && hess_lim_mem_) {
930  } else if (hess_update_ == 4) {
932  }
933 
934  // If limited memory updates are used, set pointers deltaXi and
935  // gamma to the next column in deltaMat and gammaMat
936  updateDeltaGamma(m);
937 
938  m->itCount++;
939  skipLineSearch = false;
940  }
941 
942  return 1;
943  }
void updateDeltaGamma(BlocksqpMemory *m) const
Definition: blocksqp.cpp:2247
casadi_int filterLineSearch(BlocksqpMemory *m) const
Definition: blocksqp.cpp:1217
casadi_int feasibilityRestorationHeuristic(BlocksqpMemory *m) const
Definition: blocksqp.cpp:1636
casadi_int solveQP(BlocksqpMemory *m, double *deltaXi, double *lambdaQP, bool matricesChanged=true) const
Definition: blocksqp.cpp:2306
casadi_int fullstep(BlocksqpMemory *m) const
No globalization strategy.
Definition: blocksqp.cpp:1179
void calcHessianUpdateExact(BlocksqpMemory *m) const
Definition: blocksqp.cpp:2097
bool calcOptTol(BlocksqpMemory *m) const
Update optimization tolerance (similar to SNOPT) in current iterate.
Definition: blocksqp.cpp:997
casadi_int kktErrorReduction(BlocksqpMemory *m) const
Definition: blocksqp.cpp:1654
void updateStepBounds(BlocksqpMemory *m, bool soc) const
Definition: blocksqp.cpp:2516
casadi_int feasibilityRestorationPhase(BlocksqpMemory *m) const
Definition: blocksqp.cpp:1434
@ SOLVER_RET_NAN

References calcHessianUpdate(), calcHessianUpdateExact(), calcHessianUpdateLimitedMemory(), calcInitialHessian(), calcLagrangeGradient(), calcOptTol(), casadi::BlocksqpMemory::cNorm, casadi::BlocksqpMemory::dxk, evaluate(), feasibilityRestorationHeuristic(), feasibilityRestorationPhase(), filterLineSearch(), fullstep(), casadi::BlocksqpMemory::gamma, casadi::BlocksqpMemory::gk, globalization_, casadi::BlocksqpMemory::grad_fk, hess_lim_mem_, hess_scaling_, hess_update_, casadi::BlocksqpMemory::itCount, casadi::BlocksqpMemory::jac_g, kktErrorReduction(), casadi::BlocksqpMemory::lam_qp, max_consec_reduced_steps_, casadi::BlocksqpMemory::nDerCalls, nlinfeastol_, casadi::BlocksqpMemory::obj, casadi::ProtoFunction::print(), print_iteration_, printProgress(), casadi::BlocksqpMemory::reducedStepCount, resetHessian(), restore_feas_, skip_first_globalization_, solveQP(), casadi::SOLVER_RET_NAN, casadi::BlocksqpMemory::steptype, casadi::NlpsolMemory::unified_return_status, updateDeltaGamma(), updateStats(), and updateStepBounds().

Referenced by feasibilityRestorationPhase(), and solve().

◆ secondOrderCorrection()

bool casadi::Blocksqp::secondOrderCorrection ( BlocksqpMemory m,
double  cNorm,
double  cNormTrial,
double  dfTdeltaXi,
bool  swCond,
casadi_int  it 
) const

Perform a second order correction step, i.e. solve the QP:

min_d d^TBd + d^T grad_fk s.t. bl <= A^Td + constr(xi+alpha*deltaXi) - A^TdeltaXi <= bu

Definition at line 1331 of file blocksqp.cpp.

1333  {
1334  auto d_nlp = &m->d_nlp;
1335 
1336  // Perform SOC only on the first iteration of backtracking line search
1337  if (it > 0) return false;
1338  // If constraint violation of the trialstep is lower than the current one skip SOC
1339  if (cNormTrial < cNorm) return false;
1340 
1341  casadi_int nSOCS = 0;
1342  double cNormTrialSOC, cNormOld, objTrialSOC;
1343 
1344  // m->gk contains result at first trial point: c(xi+deltaXi)
1345  // m->jac_times_dxk and m->grad_fk are unchanged so far.
1346 
1347  // First SOC step
1348  std::vector<double> deltaXiSOC(nx_, 0.);
1349  std::vector<double> lambdaQPSOC(nx_+ng_, 0.);
1350 
1351  // Second order correction loop
1352  cNormOld = cNorm;
1353  for (casadi_int k=0; k<max_soc_iter_; k++) {
1354  nSOCS++;
1355 
1356  // Update bounds for SOC QP
1357  updateStepBounds(m, 1);
1358 
1359  // Solve SOC QP to obtain new, corrected deltaXi
1360  // (store in separate vector to avoid conflict with original deltaXi
1361  // -> need it in linesearch!)
1362  casadi_int info = solveQP(m, get_ptr(deltaXiSOC), get_ptr(lambdaQPSOC), false);
1363  if (info != 0) return false; // Could not solve QP, abort SOC
1364 
1365  // Set new SOC trial point
1366  for (casadi_int i=0; i<nx_; i++) {
1367  m->trial_xk[i] = d_nlp->z[i] + deltaXiSOC[i];
1368  }
1369 
1370  // Compute objective and ||constr(trialXiSOC)||_1 at SOC trial point
1371  info = evaluate(m, m->trial_xk, &objTrialSOC, m->gk);
1372  m->nFunCalls++;
1373  cNormTrialSOC = lInfConstraintNorm(m, m->trial_xk, m->gk);
1374  if (info != 0 || objTrialSOC < obj_lo_ || objTrialSOC > obj_up_
1375  || !(objTrialSOC == objTrialSOC) || !(cNormTrialSOC == cNormTrialSOC)) {
1376  return false; // evaluation error, abort SOC
1377  }
1378 
1379  // Check acceptability to the filter (in SOC)
1380  if (pairInFilter(m, cNormTrialSOC, objTrialSOC)) {
1381  // Trial point is in the prohibited region defined by the filter, abort SOC
1382  return false;
1383  }
1384 
1385  // Check sufficient decrease, case I (in SOC)
1386  // (Almost feasible and switching condition holds for line search alpha)
1387  if (cNorm <= theta_min_ && swCond) {
1388  if (objTrialSOC > m->obj + eta_*dfTdeltaXi) {
1389  // Armijo condition does not hold for SOC step, next SOC step
1390 
1391  // If constraint violation gets worse by SOC, abort
1392  if (cNormTrialSOC > kappa_soc_ * cNormOld) {
1393  return false;
1394  } else {
1395  cNormOld = cNormTrialSOC;
1396  }
1397  continue;
1398  } else {
1399  // found suitable alpha during SOC, stop
1400  acceptStep(m, get_ptr(deltaXiSOC), get_ptr(lambdaQPSOC), 1.0, nSOCS);
1401  return true;
1402  }
1403  }
1404 
1405  // Check sufficient decrease, case II (in SOC)
1406  if (cNorm > theta_min_ || !swCond) {
1407  if (cNormTrialSOC < (1.0 - gamma_theta_) * cNorm
1408  || objTrialSOC < m->obj - gamma_f_ * cNorm) {
1409  // found suitable alpha during SOC, stop
1410  acceptStep(m, get_ptr(deltaXiSOC), get_ptr(lambdaQPSOC), 1.0, nSOCS);
1411  return true;
1412  } else {
1413  // Trial point is dominated by current point, next SOC step
1414 
1415  // If constraint violation gets worse by SOC, abort
1416  if (cNormTrialSOC > kappa_soc_ * cNormOld) {
1417  return false;
1418  } else {
1419  cNormOld = cNormTrialSOC;
1420  }
1421  continue;
1422  }
1423  }
1424  }
1425 
1426  return false;
1427  }

References acceptStep(), casadi::NlpsolMemory::d_nlp, eta_, evaluate(), gamma_f_, gamma_theta_, casadi::get_ptr(), casadi::BlocksqpMemory::gk, casadi::FunctionInternal::info(), kappa_soc_, lInfConstraintNorm(), max_soc_iter_, casadi::BlocksqpMemory::nFunCalls, casadi::Nlpsol::ng_, casadi::Nlpsol::nx_, casadi::BlocksqpMemory::obj, obj_up_, pairInFilter(), solveQP(), theta_min_, casadi::BlocksqpMemory::trial_xk, and updateStepBounds().

Referenced by filterLineSearch().

◆ self()

Function casadi::FunctionInternal::self ( ) const
inlineinherited

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

Definition at line 353 of file function_internal.hpp.

353 { return shared_from_this<Function>();}

Referenced by casadi::casadi_uno_term_cb_cpp().

◆ serialize()

void casadi::ProtoFunction::serialize ( SerializingStream s) const
inherited

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

Definition at line 4393 of file function_internal.cpp.

4393  {
4394  serialize_type(s);
4395  serialize_body(s);
4396  }
virtual void serialize_type(SerializingStream &s) const
Serialize type information.
virtual void serialize_body(SerializingStream &s) const
Serialize an object without type information.

References casadi::ProtoFunction::serialize_body(), and casadi::ProtoFunction::serialize_type().

◆ serialize_base_function()

std::string casadi::Nlpsol::serialize_base_function ( ) const
inlineoverridevirtualinherited

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

Reimplemented from casadi::ProtoFunction.

Definition at line 133 of file nlpsol_impl.hpp.

133 { return "Nlpsol"; }

◆ serialize_body()

void casadi::Blocksqp::serialize_body ( SerializingStream s) const
overridevirtual

Reimplemented from casadi::Nlpsol.

Definition at line 2915 of file blocksqp.cpp.

2915  {
2917  s.version("Blocksqp", 1);
2918  s.pack("Blocksqp::nblocks", nblocks_);
2919  s.pack("Blocksqp::blocks", blocks_);
2920  s.pack("Blocksqp::dim", dim_);
2921  s.pack("Blocksqp::nnz_H", nnz_H_);
2922  s.pack("Blocksqp::Asp", Asp_);
2923  s.pack("Blocksqp::Hsp", Hsp_);
2924  s.pack("Blocksqp::exact_hess_lag_sp_", exact_hess_lag_sp_);
2925  s.pack("Blocksqp::linsol_plugin", linsol_plugin_);
2926  s.pack("Blocksqp::print_header", print_header_);
2927  s.pack("Blocksqp::print_iteration", print_iteration_);
2928  s.pack("Blocksqp::eps", eps_);
2929  s.pack("Blocksqp::opttol", opttol_);
2930  s.pack("Blocksqp::nlinfeastol", nlinfeastol_);
2931  s.pack("Blocksqp::schur", schur_);
2932  s.pack("Blocksqp::globalization", globalization_);
2933  s.pack("Blocksqp::restore_feas", restore_feas_);
2934  s.pack("Blocksqp::max_line_search", max_line_search_);
2935  s.pack("Blocksqp::max_consec_reduced_steps", max_consec_reduced_steps_);
2936  s.pack("Blocksqp::max_consec_skipped_updates", max_consec_skipped_updates_);
2937  s.pack("Blocksqp::max_it_qp", max_it_qp_);
2938  s.pack("Blocksqp::max_iter", max_iter_);
2939  s.pack("Blocksqp::warmstart", warmstart_);
2940  s.pack("Blocksqp::qp_init", qp_init_);
2941  s.pack("Blocksqp::block_hess", block_hess_);
2942  s.pack("Blocksqp::hess_scaling", hess_scaling_);
2943  s.pack("Blocksqp::fallback_scaling", fallback_scaling_);
2944  s.pack("Blocksqp::max_time_qp", max_time_qp_);
2945  s.pack("Blocksqp::ini_hess_diag", ini_hess_diag_);
2946  s.pack("Blocksqp::col_eps", col_eps_);
2947  s.pack("Blocksqp::col_tau1", col_tau1_);
2948  s.pack("Blocksqp::col_tau2", col_tau2_);
2949  s.pack("Blocksqp::hess_damp", hess_damp_);
2950  s.pack("Blocksqp::hess_damp_fac", hess_damp_fac_);
2951  s.pack("Blocksqp::hess_update", hess_update_);
2952  s.pack("Blocksqp::fallback_update", fallback_update_);
2953  s.pack("Blocksqp::hess_lim_mem", hess_lim_mem_);
2954  s.pack("Blocksqp::hess_memsize", hess_memsize_);
2955  s.pack("Blocksqp::which_second_derv", which_second_derv_);
2956  s.pack("Blocksqp::skip_first_globalization", skip_first_globalization_);
2957  s.pack("Blocksqp::conv_strategy", conv_strategy_);
2958  s.pack("Blocksqp::max_conv_qp", max_conv_qp_);
2959  s.pack("Blocksqp::max_soc_iter", max_soc_iter_);
2960  s.pack("Blocksqp::gamma_theta", gamma_theta_);
2961  s.pack("Blocksqp::gamma_f", gamma_f_);
2962  s.pack("Blocksqp::kappa_soc", kappa_soc_);
2963  s.pack("Blocksqp::kappa_f", kappa_f_);
2964  s.pack("Blocksqp::theta_max", theta_max_);
2965  s.pack("Blocksqp::theta_min", theta_min_);
2966  s.pack("Blocksqp::delta", delta_);
2967  s.pack("Blocksqp::s_theta", s_theta_);
2968  s.pack("Blocksqp::s_f", s_f_);
2969  s.pack("Blocksqp::kappa_minus", kappa_minus_);
2970  s.pack("Blocksqp::kappa_plus", kappa_plus_);
2971  s.pack("Blocksqp::kappa_plus_max", kappa_plus_max_);
2972  s.pack("Blocksqp::delta_h0", delta_h0_);
2973  s.pack("Blocksqp::eta", eta_);
2974  s.pack("Blocksqp::obj_lo", obj_lo_);
2975  s.pack("Blocksqp::obj_up", obj_up_);
2976  s.pack("Blocksqp::rho", rho_);
2977  s.pack("Blocksqp::zeta", zeta_);
2978  s.pack("Blocksqp::rp_solver", rp_solver_);
2979  s.pack("Blocksqp::print_maxit_reached", print_maxit_reached_);
2980  }
void serialize_body(SerializingStream &s) const override
Serialize an object without type information.
Definition: nlpsol.cpp:1409

References Asp_, block_hess_, blocks_, col_eps_, col_tau1_, col_tau2_, conv_strategy_, delta_, delta_h0_, dim_, eps_, eta_, exact_hess_lag_sp_, fallback_scaling_, fallback_update_, gamma_f_, gamma_theta_, globalization_, hess_damp_, hess_damp_fac_, hess_lim_mem_, hess_memsize_, hess_scaling_, hess_update_, Hsp_, ini_hess_diag_, kappa_f_, kappa_minus_, kappa_plus_, kappa_plus_max_, kappa_soc_, linsol_plugin_, max_consec_reduced_steps_, max_consec_skipped_updates_, max_conv_qp_, max_it_qp_, max_iter_, max_line_search_, max_soc_iter_, max_time_qp_, nblocks_, nlinfeastol_, nnz_H_, obj_lo_, obj_up_, opttol_, casadi::SerializingStream::pack(), print_header_, print_iteration_, print_maxit_reached_, qp_init_, restore_feas_, rho_, rp_solver_, s_f_, s_theta_, schur_, casadi::Nlpsol::serialize_body(), skip_first_globalization_, theta_max_, theta_min_, casadi::SerializingStream::version(), warmstart_, which_second_derv_, and zeta_.

◆ serialize_type()

void casadi::Nlpsol::serialize_type ( SerializingStream s) const
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 1439 of file nlpsol.cpp.

1439  {
1442  }
void serialize_type(SerializingStream &s) const override
Serialize type information.
void serialize_type(SerializingStream &s) const
Serialize type information.

References casadi::PluginInterface< Derived >::serialize_type(), and casadi::FunctionInternal::serialize_type().

◆ set_function() [1/2]

void casadi::OracleFunction::set_function ( const Function fcn)
inlineinherited

Register the function for evaluation and statistics gathering

Definition at line 183 of file oracle_function.hpp.

183 { set_function(fcn, fcn.name()); }

References casadi::Function::name(), and casadi::OracleFunction::set_function().

Referenced by casadi::OracleFunction::set_function().

◆ set_function() [2/2]

void casadi::OracleFunction::set_function ( const Function fcn,
const std::string &  fname,
bool  jit = false 
)
inherited

◆ set_jac_sparsity()

void casadi::FunctionInternal::set_jac_sparsity ( casadi_int  oind,
casadi_int  iind,
const Sparsity sp 
)
protectedinherited

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

Definition at line 3964 of file function_internal.cpp.

3964  {
3965 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
3966  // Safe access to jac_sparsity_
3967  std::lock_guard<std::mutex> lock(jac_sparsity_mtx_);
3968 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
3969  casadi_int ind = iind + oind * n_in_;
3970  jac_sparsity_[false].resize(n_in_ * n_out_);
3971  jac_sparsity_[false].at(ind) = sp;
3972  jac_sparsity_[true].resize(n_in_ * n_out_);
3973  jac_sparsity_[true].at(ind) = to_compact(oind, iind, sp);
3974  }

References casadi::FunctionInternal::jac_sparsity_, casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, and casadi::FunctionInternal::to_compact().

◆ set_temp()

void casadi::OracleFunction::set_temp ( void *  mem,
const double **  arg,
double **  res,
casadi_int *  iw,
double *  w 
) const
overridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 505 of file oracle_function.cpp.

506  {
507 
508  auto *m = static_cast<OracleMemory*>(mem);
509  m->arg = arg;
510  m->res = res;
511  m->iw = iw;
512  m->w = w;
513  m->d_oracle.arg = arg;
514  m->d_oracle.res = res;
515  m->d_oracle.iw = iw;
516  m->d_oracle.w = w;
517  for (int i = 0; i < max_num_threads_; ++i) {
518  auto* ml = m->thread_local_mem[i];
519  for (auto&& s : ml->fstats) s.second.reset();
520  ml->arg = arg;
521  ml->res = res;
522  ml->iw = iw;
523  ml->w = w;
524  arg += stride_arg_;
525  res += stride_res_;
526  iw += stride_iw_;
527  w += stride_w_;
528  }
529 }

References casadi::OracleMemory::arg, casadi::OracleFunction::max_num_threads_, casadi::OracleFunction::stride_arg_, casadi::OracleFunction::stride_iw_, casadi::OracleFunction::stride_res_, and casadi::OracleFunction::stride_w_.

◆ set_work()

void casadi::Blocksqp::set_work ( void *  mem,
const double **&  arg,
double **&  res,
casadi_int *&  iw,
double *&  w 
) const
overridevirtual

Reimplemented from casadi::Nlpsol.

Definition at line 582 of file blocksqp.cpp.

583  {
584  auto m = static_cast<BlocksqpMemory*>(mem);
585 
586  // Set work in base classes
587  Nlpsol::set_work(mem, arg, res, iw, w);
588 
589  // Temporary memory
590  m->jac = w; w += Asp_.nnz();
591  m->lam_xk = w; w += nx_;
592  m->lam_gk = w; w += ng_;
593  m->gk = w; w += ng_;
594  m->grad_fk = w; w += nx_;
595  m->grad_lagk = w; w += nx_;
596  m->lam_qp = w; w += nx_+ng_;
597  m->delta_norm = w; w += nblocks_;
598  m->delta_norm_old = w; w += nblocks_;
599  m->delta_gamma = w; w += nblocks_;
600  m->delta_gamma_old = w; w += nblocks_;
601  m->delta_h = w; w += nblocks_;
602  m->trial_xk = w; w += nx_;
603  m->lbx_qp = w; w += nx_;
604  m->ubx_qp = w; w += nx_;
605  m->lba_qp = w; w += ng_;
606  m->uba_qp = w; w += ng_;
607  m->jac_times_dxk = w; w += ng_;
608  m->deltaMat = w; w += nx_*hess_memsize_;
609  m->gammaMat = w; w += nx_*hess_memsize_;
610  m->jac_g = w; w += Asp_.nnz();
611  m->hess_lag = w; w += nnz_H_;
612  m->hessIndRow = reinterpret_cast<int*>(iw); iw += nnz_H_ + (nx_+1) + nx_;
613  m->noUpdateCounter = iw; iw += nblocks_;
614 
615  // First Hessian
616  m->hess1 = res; res += nblocks_;
617  for (casadi_int b=0; b<nblocks_; b++) {
618  m->hess1[b] = w; w += dim_[b]*dim_[b];
619  }
620 
621  // Second Hessian, for SR1 or finite differences
622  if (hess_update_ == 1 || hess_update_ == 4) {
623  m->hess2 = res; res += nblocks_;
624  for (casadi_int b=0; b<nblocks_; b++) {
625  m->hess2[b] = w; w += dim_[b]*dim_[b];
626  }
627  } else {
628  m->hess2 = nullptr;
629  }
630 
631  m->exact_hess_lag = w; w += exact_hess_lag_sp_.nnz();
632  }
void set_work(void *mem, const double **&arg, double **&res, casadi_int *&iw, double *&w) const override
Set the (persistent) work vectors.
Definition: nlpsol.cpp:884

References Asp_, dim_, exact_hess_lag_sp_, hess_memsize_, hess_update_, nblocks_, casadi::Nlpsol::ng_, casadi::Sparsity::nnz(), nnz_H_, casadi::Nlpsol::nx_, and casadi::Nlpsol::set_work().

◆ setOptionsFromFile()

void casadi::Nlpsol::setOptionsFromFile ( const std::string &  file)
virtualinherited

Definition at line 763 of file nlpsol.cpp.

763  {
764  casadi_error("setOptionsFromFile not defined for class " + class_name());
765  }

References casadi::Nlpsol::class_name().

◆ setup()

void casadi::FunctionInternal::setup ( void *  mem,
const double **  arg,
double **  res,
casadi_int *  iw,
double *  w 
) const
inherited

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

Definition at line 3738 of file function_internal.cpp.

3739  {
3740  set_work(mem, arg, res, iw, w);
3741  set_temp(mem, arg, res, iw, w);
3742  auto *m = static_cast<FunctionMemory*>(mem);
3743  m->stats_available = true;
3744  }
virtual void set_work(void *mem, const double **&arg, double **&res, casadi_int *&iw, double *&w) const
Set the (persistent) work vectors.
virtual void set_temp(void *mem, const double **arg, double **res, casadi_int *iw, double *w) const
Set the (temporary) work vectors.

References casadi::FunctionInternal::set_temp(), casadi::FunctionInternal::set_work(), and casadi::FunctionMemory::stats_available.

Referenced by casadi::Conic::eval(), casadi::Nlpsol::eval(), casadi::CallbackInternal::eval(), casadi::FiniteDiff::eval(), casadi::FmuFunction::eval(), casadi::Integrator::eval(), casadi::Map::eval(), casadi::OmpMap::eval(), casadi::ThreadMap::eval(), casadi::MapSum::eval(), casadi::MXFunction::eval(), casadi::Rootfinder::eval(), casadi::Switch::eval(), casadi::SXFunction::eval(), casadi::SlicotDple::eval(), casadi::SlicotExpm::eval(), casadi::BSplineInterpolant::eval(), and casadi::LinearInterpolant::eval().

◆ shared_from_this() [1/2]

B casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::shared_from_this ( )
inlineprotectedinherited

Definition at line 83 of file generic_shared_internal.hpp.

83  {
84  casadi_assert_dev(B::test_cast(static_cast<Internal*>(this)));
85  B ret;
86  ret.own(static_cast<Internal*>(this));
87  return ret;
88  }

◆ shared_from_this() [2/2]

const B casadi::GenericSharedInternal< SharedObject , SharedObjectInternal >::shared_from_this ( ) const
inlineprotectedinherited

Definition at line 92 of file generic_shared_internal.hpp.

92  {
93  casadi_assert_dev(B::test_cast(static_cast<const Internal*>(this)));
94  B ret;
95  ret.own(const_cast<Internal*>(static_cast<const Internal*>(this)));
96  return ret;
97  }

◆ shortname()

static std::string casadi::Nlpsol::shortname ( )
inlinestaticinherited

Definition at line 312 of file nlpsol_impl.hpp.

312 { return "nlpsol";}

◆ signature()

std::string casadi::FunctionInternal::signature ( const std::string &  fname) const
inherited

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

Definition at line 2497 of file function_internal.cpp.

2497  {
2498  return "int " + fname + "(const casadi_real** arg, casadi_real** res, "
2499  "casadi_int* iw, casadi_real* w, int mem)";
2500  }

Referenced by casadi::CodeGenerator::add(), casadi::FunctionInternal::codegen(), and casadi::External::codegen_declarations().

◆ signature_unrolled()

std::string casadi::FunctionInternal::signature_unrolled ( const std::string &  fname) const
inherited

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

Definition at line 2502 of file function_internal.cpp.

2502  {
2503  std::vector<std::string> args;
2504  for (auto e : name_in_) {
2505  args.push_back("const casadi_real* " + str(e));
2506  }
2507  for (auto e : name_out_) {
2508  args.push_back("casadi_real* " + str(e));
2509  }
2510  args.push_back("const casadi_real** arg");
2511  args.push_back("casadi_real** res");
2512  args.push_back("casadi_int* iw");
2513  args.push_back("casadi_real* w");
2514  args.push_back("int mem");
2515  return "int " + fname + "_unrolled(" + join(args, ", ") + ")";
2516  }

References casadi::join(), casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, and casadi::str().

Referenced by casadi::CodeGenerator::add().

◆ simplify_passes()

Function casadi::FunctionInternal::simplify_passes ( const std::vector< std::pair< std::string, casadi_int > > &  tasks) const
virtualinherited

Each pass is a (task, count) pair; count>0 runs the task that many times, count==0 runs it until a fixed point.

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

Reimplemented in casadi::XFunction< DerivedType, MatType, NodeType >, casadi::XFunction< MXFunction, MX, MXNode >, and casadi::XFunction< SXFunction, Matrix< SXElem >, SXNode >.

Definition at line 3933 of file function_internal.cpp.

3934  {
3935  casadi_assert(tasks.empty(), "simplify passes not supported for " + class_name());
3936  return self();
3937  }

References casadi::SharedObjectInternal::class_name().

Referenced by casadi::Function::transform().

◆ size1_in()

casadi_int casadi::FunctionInternal::size1_in ( casadi_int  ind) const
inlineinherited

◆ size1_out()

casadi_int casadi::FunctionInternal::size1_out ( casadi_int  ind) const
inlineinherited

◆ size2_in()

casadi_int casadi::FunctionInternal::size2_in ( casadi_int  ind) const
inlineinherited

◆ size2_out()

casadi_int casadi::FunctionInternal::size2_out ( casadi_int  ind) const
inlineinherited

◆ size_in()

std::pair<casadi_int, casadi_int> casadi::FunctionInternal::size_in ( casadi_int  ind) const
inlineinherited

◆ size_out()

std::pair<casadi_int, casadi_int> casadi::FunctionInternal::size_out ( casadi_int  ind) const
inlineinherited

◆ sizeHessianCOL()

void casadi::Blocksqp::sizeHessianCOL ( BlocksqpMemory m,
const double *  gamma,
const double *  delta,
casadi_int  b 
) const

Definition at line 1873 of file blocksqp.cpp.

1875  {
1876  casadi_int dim = dim_[b];
1877  double theta, scale, myEps = 1.0e3 * eps_;
1878  double deltaNorm, deltaNormOld, deltaGamma, deltaGammaOld, deltaBdelta;
1879 
1880  // Get sTs, sTs_, sTy, sTy_, sTBs
1881  deltaNorm = m->delta_norm[b];
1882  deltaGamma = m->delta_gamma[b];
1883  deltaNormOld = m->delta_norm_old[b];
1884  deltaGammaOld = m->delta_gamma_old[b];
1885  deltaBdelta = 0.0;
1886  for (casadi_int i=0; i<dim; i++)
1887  for (casadi_int j=0; j<dim; j++)
1888  deltaBdelta += delta[i] * m->hess[b][i+j*dim] * delta[j];
1889 
1890  // Centered Oren-Luenberger factor
1891  if (m->noUpdateCounter[b] == -1) {
1892  // in the first iteration, this should equal the OL factor
1893  theta = 1.0;
1894  } else {
1895  theta = fmin(col_tau1_, col_tau2_ * deltaNorm);
1896  }
1897  if (deltaNorm > myEps && deltaNormOld > myEps) {
1898  scale = (1.0 - theta)*deltaGammaOld / deltaNormOld + theta*deltaBdelta / deltaNorm;
1899  if (scale > eps_)
1900  scale = ((1.0 - theta)*deltaGammaOld / deltaNormOld + theta*deltaGamma / deltaNorm) / scale;
1901  } else {
1902  scale = 1.0;
1903  }
1904 
1905  // Size only if factor is between zero and one
1906  if (scale < 1.0 && scale > 0.0) {
1907  scale = fmax(col_eps_, scale);
1908  //print("Sizing value (COL) block %i = %g\n", b, scale);
1909  for (casadi_int i=0; i<dim; i++)
1910  for (casadi_int j=0; j<dim; j++)
1911  m->hess[b][i+j*dim] *= scale;
1912 
1913  // statistics: average sizing factor
1914  m->averageSizingFactor += scale;
1915  } else {
1916  m->averageSizingFactor += 1.0;
1917  }
1918  }

References casadi::BlocksqpMemory::averageSizingFactor, col_eps_, col_tau1_, col_tau2_, casadi::BlocksqpMemory::delta_gamma, casadi::BlocksqpMemory::delta_gamma_old, casadi::BlocksqpMemory::delta_norm, casadi::BlocksqpMemory::delta_norm_old, dim_, eps_, casadi::BlocksqpMemory::hess, and casadi::BlocksqpMemory::noUpdateCounter.

Referenced by calcHessianUpdate(), and calcHessianUpdateLimitedMemory().

◆ sizeInitialHessian()

void casadi::Blocksqp::sizeInitialHessian ( BlocksqpMemory m,
const double *  gamma,
const double *  delta,
casadi_int  b,
casadi_int  option 
) const

Definition at line 1834 of file blocksqp.cpp.

1836  {
1837  casadi_int dim = dim_[b];
1838  double scale;
1839  double myEps = 1.0e3 * eps_;
1840 
1841  if (option == 1) {
1842  // Shanno-Phua
1843  scale = casadi_dot(dim, gamma, gamma)
1844  / fmax(casadi_dot(dim, delta, gamma), myEps);
1845  } else if (option == 2) {
1846  // Oren-Luenberger
1847  scale = casadi_dot(dim, delta, gamma)
1848  / fmax(casadi_dot(dim, delta, delta), myEps);
1849  scale = fmin(scale, 1.0);
1850  } else if (option == 3) {
1851  // Geometric mean of 1 and 2
1852  scale = sqrt(casadi_dot(dim, gamma, gamma)
1853  / fmax(casadi_dot(dim, delta, delta), myEps));
1854  } else {
1855  // Invalid option, ignore
1856  return;
1857  }
1858 
1859  if (scale > 0.0) {
1860  scale = fmax(scale, myEps);
1861  for (casadi_int i=0; i<dim; i++)
1862  for (casadi_int j=0; j<dim; j++)
1863  m->hess[b][i+j*dim] *= scale;
1864  } else {
1865  scale = 1.0;
1866  }
1867 
1868  // statistics: average sizing factor
1869  m->averageSizingFactor += scale;
1870  }

References casadi::BlocksqpMemory::averageSizingFactor, casadi::casadi_dot(), dim_, eps_, and casadi::BlocksqpMemory::hess.

Referenced by calcHessianUpdate(), and calcHessianUpdateLimitedMemory().

◆ slice()

Function casadi::FunctionInternal::slice ( const std::string &  name,
const std::vector< casadi_int > &  order_in,
const std::vector< casadi_int > &  order_out,
const Dict opts 
) const
virtualinherited

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

Reimplemented in casadi::XFunction< DerivedType, MatType, NodeType >, casadi::XFunction< MXFunction, MX, MXNode >, and casadi::XFunction< SXFunction, Matrix< SXElem >, SXNode >.

Definition at line 3945 of file function_internal.cpp.

3947  {
3948  return wrap().slice(name, order_in, order_out, opts);
3949  }
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
returns a new function with a selection of inputs/outputs of the original
Definition: function.cpp:899

References casadi::Function::slice(), and casadi::FunctionInternal::wrap().

Referenced by casadi::Function::slice().

◆ solve()

int casadi::Blocksqp::solve ( void *  mem) const
overridevirtual

Implements casadi::Nlpsol.

Definition at line 634 of file blocksqp.cpp.

634  {
635  auto m = static_cast<BlocksqpMemory*>(mem);
636  auto d_nlp = &m->d_nlp;
637 
638  casadi_int ret = 0;
639 
640  // Create problem evaluation object
641  std::vector<casadi_int> blocks = blocks_;
642 
643  /*-------------------------------------------------*/
644  /* Create blockSQP method object and run algorithm */
645  /*-------------------------------------------------*/
646  m->itCount = 0;
647  m->qpItTotal = 0;
648  m->qpIterations = 0;
649  m->qpIterations2 = 0;
650  m->qpResolve = 0;
651  m->rejectedSR1 = 0;
652  m->hessSkipped = 0;
653  m->hessDamped = 0;
654  m->averageSizingFactor = 0.0;
655  m->nFunCalls = 0;
656  m->nDerCalls = 0;
657  m->nRestHeurCalls = 0;
658  m->nRestPhaseCalls = 0;
659 
660  m->nTotalUpdates = 0;
661  m->nTotalSkippedUpdates = 0;
662 
663  casadi_int maxblocksize = 1;
664 
665  for (casadi_int k=0; k<nblocks_+1; k++) {
666  if (k > 0)
667  if (blocks_[k] - blocks_[k-1] > maxblocksize)
668  maxblocksize = blocks_[k] - blocks_[k-1];
669  }
670 
671  if (hess_lim_mem_ && hess_memsize_ == 0)
672  const_cast<Blocksqp*>(this)->hess_memsize_ = maxblocksize;
673 
674  // Reset the SQP metod
675  reset_sqp(m);
676 
677  // Free existing memory, if any
678  if (qp_init_) {
679  delete m->qp;
680  m->qp = nullptr;
681  }
682  if (!m->qp) {
683  if (schur_) {
684  m->qp = new qpOASES::SQProblemSchur(nx_, ng_, qpOASES::HST_UNKNOWN, 50,
685  m->qpoases_mem,
690  } else {
691  m->qp = new qpOASES::SQProblem(nx_, ng_);
692  }
693  }
694 
695  // Print header and information about the algorithmic parameters
696  if (print_header_) printInfo(m);
697 
698  // Open output files
699  initStats(m);
700  initIterate(m);
701 
702  // Initialize filter with pair (maxConstrViolation, objLowerBound)
703  initializeFilter(m);
704 
705  // Primal-dual initial guess
706  casadi_copy(d_nlp->lam, nx_, m->lam_xk);
707  casadi_scal(nx_, -1., m->lam_xk);
708  casadi_copy(d_nlp->lam + nx_, ng_, m->lam_gk);
709  casadi_scal(ng_, -1., m->lam_gk);
710 
711  casadi_copy(m->lam_xk, nx_, m->lam_qp);
712  casadi_copy(m->lam_gk, ng_, m->lam_qp+nx_);
713 
714  ret = run(m, max_iter_, warmstart_);
715 
716  m->success = ret==0;
717  m->ret_ = ret;
718 
719  if (ret==1) {
720  if (print_maxit_reached_) print("***WARNING: Maximum number of iterations reached\n");
721  m->unified_return_status = SOLVER_RET_LIMITED;
722  }
723 
724 
725  // Get optimal cost
726  d_nlp->objective = m->obj;
727  // Get constraints at solution
728  casadi_copy(m->gk, ng_, d_nlp->z + nx_);
729  // Get dual solution (simple bounds)
730  if (d_nlp->lam) {
731  casadi_copy(m->lam_xk, nx_, d_nlp->lam);
732  casadi_scal(nx_, -1., d_nlp->lam);
733  }
734  // Get dual solution (nonlinear bounds)
735  casadi_copy(m->lam_gk, ng_, d_nlp->lam + nx_);
736  casadi_scal(ng_, -1., d_nlp->lam + nx_);
737  return 0;
738  }
void reset_sqp(BlocksqpMemory *m) const
Reset variables that any SQP code needs.
Definition: blocksqp.cpp:2637
void initializeFilter(BlocksqpMemory *m) const
Definition: blocksqp.cpp:1722
void printInfo(BlocksqpMemory *m) const
Print information about the SQP method.
Definition: blocksqp.cpp:1012
casadi_int run(BlocksqpMemory *m, casadi_int maxIt, casadi_int warmStart=0) const
Main Loop of SQP method.
Definition: blocksqp.cpp:740
void initStats(BlocksqpMemory *m) const
Definition: blocksqp.cpp:2608
void initIterate(BlocksqpMemory *m) const
Set initial filter, objective function, tolerances etc.
Definition: blocksqp.cpp:2769
static int qpoases_init(void *mem, int dim, int nnz, const int *row, const int *col)
qpOASES linear solver initialization
static int qpoases_solve(void *mem, int nrhs, double *rhs)
qpOASES linear solver solve
static int qpoases_sfact(void *mem, const double *vals)
qpOASES linear solver symbolical factorization
static int qpoases_nfact(void *mem, const double *vals, int *neig, int *rank)
qpOASES linear solver numerical factorization
@ SOLVER_RET_LIMITED

References blocks_, casadi::casadi_copy(), casadi::casadi_scal(), casadi::NlpsolMemory::d_nlp, hess_lim_mem_, hess_memsize_, initializeFilter(), initIterate(), initStats(), max_iter_, nblocks_, casadi::Nlpsol::ng_, casadi::Nlpsol::nx_, casadi::ProtoFunction::print(), print_header_, print_maxit_reached_, printInfo(), qp_init_, casadi::QpoasesInterface::qpoases_init(), casadi::QpoasesInterface::qpoases_nfact(), casadi::QpoasesInterface::qpoases_sfact(), casadi::QpoasesInterface::qpoases_solve(), reset_sqp(), run(), schur_, casadi::SOLVER_RET_LIMITED, and warmstart_.

◆ solveQP()

casadi_int casadi::Blocksqp::solveQP ( BlocksqpMemory m,
double *  deltaXi,
double *  lambdaQP,
bool  matricesChanged = true 
) const

Inner loop of SQP algorithm: Solve a sequence of QPs until pos. def. assumption (G3*) is satisfied.

Definition at line 2305 of file blocksqp.cpp.

2307  {
2308  casadi_int maxQP, l;
2309  if (globalization_ &&
2310  (hess_update_ == 1 || hess_update_ == 4) &&
2311  matricesChanged &&
2312  m->itCount > 1) {
2313  maxQP = max_conv_qp_ + 1;
2314  } else {
2315  maxQP = 1;
2316  }
2317 
2318  /*
2319  * Prepare for qpOASES
2320  */
2321 
2322  // Setup QProblem data
2323  if (matricesChanged) {
2324  delete m->A;
2325  m->A = nullptr;
2326  copy_vector(Asp_.colind(), m->colind);
2327  copy_vector(Asp_.row(), m->row);
2328  int* jacIndRow = get_ptr(m->row);
2329  int* jacIndCol = get_ptr(m->colind);
2330  m->A = new qpOASES::SparseMatrix(ng_, nx_,
2331  jacIndRow, jacIndCol, m->jac_g);
2332  }
2333  double *g = m->grad_fk;
2334  double *lb = m->lbx_qp;
2335  double *lu = m->ubx_qp;
2336  double *lbA = m->lba_qp;
2337  double *luA = m->uba_qp;
2338 
2339  // qpOASES options
2340  qpOASES::Options opts;
2341  if (matricesChanged && maxQP > 1)
2342  opts.enableInertiaCorrection = qpOASES::BT_FALSE;
2343  else
2344  opts.enableInertiaCorrection = qpOASES::BT_TRUE;
2345  opts.enableEqualities = qpOASES::BT_TRUE;
2346  opts.initialStatusBounds = qpOASES::ST_INACTIVE;
2347  opts.printLevel = qpOASES::PL_NONE;
2348  opts.numRefinementSteps = 2;
2349  opts.epsLITests = 2.2204e-08;
2350  m->qp->setOptions(opts);
2351 
2352  // Other variables for qpOASES
2353  double cpuTime = matricesChanged ? max_time_qp_ : 0.1*max_time_qp_;
2354  int maxIt = matricesChanged ? max_it_qp_ : static_cast<int>(0.1*max_it_qp_);
2355  qpOASES::SolutionAnalysis solAna;
2356  qpOASES::returnValue ret = qpOASES::RET_INFO_UNDEFINED;
2357 
2358  /*
2359  * QP solving loop for convex combinations (sequential)
2360  */
2361  for (l=0; l<maxQP; l++) {
2362  /*
2363  * Compute a new Hessian
2364  */
2365  if (l > 0) {
2366  // If the solution of the first QP was rejected, consider second Hessian
2367  m->qpResolve++;
2368  computeNextHessian(m, l, maxQP);
2369  }
2370 
2371  if (l == maxQP-1) {
2372  // Enable inertia correction for supposedly convex QPs, just in case
2373  opts.enableInertiaCorrection = qpOASES::BT_TRUE;
2374  m->qp->setOptions(opts);
2375  }
2376 
2377  /*
2378  * Prepare the current Hessian for qpOASES
2379  */
2380  if (matricesChanged) {
2381  // Convert block-Hessian to sparse format
2382  convertHessian(m);
2383  delete m->H;
2384  m->H = nullptr;
2385  m->H = new qpOASES::SymSparseMat(nx_, nx_,
2386  m->hessIndRow, m->hessIndCol,
2387  m->hess_lag);
2388  m->H->createDiagInfo();
2389  }
2390 
2391  /*
2392  * Call qpOASES
2393  */
2394  if (matricesChanged) {
2395  maxIt = max_it_qp_;
2396  cpuTime = max_time_qp_;
2397  if (m->qp->getStatus() == qpOASES::QPS_HOMOTOPYQPSOLVED ||
2398  m->qp->getStatus() == qpOASES::QPS_SOLVED) {
2399  ret = m->qp->hotstart(m->H, g, m->A, lb, lu, lbA, luA, maxIt, &cpuTime);
2400  } else {
2401  if (warmstart_) {
2402  ret = m->qp->init(m->H, g, m->A, lb, lu, lbA, luA, maxIt, &cpuTime,
2403  deltaXi, lambdaQP);
2404  } else {
2405  ret = m->qp->init(m->H, g, m->A, lb, lu, lbA, luA, maxIt, &cpuTime);
2406  }
2407  }
2408  } else {
2409  // Second order correction: H and A do not change
2410  maxIt = static_cast<int>(0.1*max_it_qp_);
2411  cpuTime = 0.1*max_time_qp_;
2412  ret = m->qp->hotstart(g, lb, lu, lbA, luA, maxIt, &cpuTime);
2413  }
2414 
2415  /*
2416  * Check assumption (G3*) if nonconvex QP was solved
2417  */
2418  if (l < maxQP-1 && matricesChanged) {
2419  if (ret == qpOASES::SUCCESSFUL_RETURN) {
2420  if (schur_) {
2421  ret = solAna.checkCurvatureOnStronglyActiveConstraints(
2422  dynamic_cast<qpOASES::SQProblemSchur*>(m->qp));
2423  } else {
2424  ret = solAna.checkCurvatureOnStronglyActiveConstraints(m->qp);
2425  }
2426  }
2427 
2428  if (ret == qpOASES::SUCCESSFUL_RETURN) {
2429  // QP was solved successfully and curvature is positive after removing bounds
2430  m->qpIterations = maxIt + 1;
2431  break; // Success!
2432  } else {
2433  // QP solution is rejected, save statistics
2434  if (ret == qpOASES::RET_SETUP_AUXILIARYQP_FAILED)
2435  m->qpIterations2++;
2436  else
2437  m->qpIterations2 += maxIt + 1;
2438  m->rejectedSR1++;
2439  }
2440  } else {
2441  // Convex QP was solved, no need to check assumption (G3*)
2442  m->qpIterations += maxIt + 1;
2443  }
2444 
2445  } // End of QP solving loop
2446 
2447  /*
2448  * Post-processing
2449  */
2450 
2451  // Get solution from qpOASES
2452  m->qp->getPrimalSolution(deltaXi);
2453  m->qp->getDualSolution(lambdaQP);
2454  m->qpObj = m->qp->getObjVal();
2455 
2456  // Compute constrJac*deltaXi, need this for second order correction step
2457  casadi_fill(m->jac_times_dxk, ng_, 0.);
2458  casadi_mv(m->jac_g, Asp_, deltaXi, m->jac_times_dxk, 0);
2459 
2460  // Print qpOASES error code, if any
2461  if (ret != qpOASES::SUCCESSFUL_RETURN && matricesChanged)
2462  print("***WARNING: qpOASES error message: \"%s\"\n",
2463  qpOASES::MessageHandling::getErrorCodeMessage(ret));
2464 
2465  // Point Hessian again to the first Hessian
2466  m->hess = m->hess1;
2467 
2468  /* For full-memory Hessian: Restore fallback Hessian if convex combinations
2469  * were used during the loop */
2470  if (!hess_lim_mem_ && maxQP > 2 && matricesChanged) {
2471  double mu = 1.0 / l;
2472  double mu1 = 1.0 - mu;
2473  casadi_int nBlocks = (which_second_derv_ == 1) ? nblocks_-1 : nblocks_;
2474  for (casadi_int b=0; b<nBlocks; b++) {
2475  casadi_int dim = dim_[b];
2476  for (casadi_int i=0; i<dim; i++) {
2477  for (casadi_int j=0; j<dim; j++) {
2478  m->hess2[b][i+j*dim] *= mu;
2479  m->hess2[b][i+j*dim] += mu1 * m->hess1[b][i+j*dim];
2480  }
2481  }
2482  }
2483  }
2484 
2485  /* Return code depending on qpOASES returnvalue
2486  * 0: Success
2487  * 1: Maximum number of iterations reached
2488  * 2: Unbounded
2489  * 3: Infeasible
2490  * 4: Other error */
2491  switch (ret) {
2492  case qpOASES::SUCCESSFUL_RETURN:
2493  return 0;
2494  case qpOASES::RET_MAX_NWSR_REACHED:
2495  return 1;
2496  case qpOASES::RET_HESSIAN_NOT_SPD:
2497  case qpOASES::RET_HESSIAN_INDEFINITE:
2498  case qpOASES::RET_INIT_FAILED_UNBOUNDEDNESS:
2499  case qpOASES::RET_QP_UNBOUNDED:
2500  case qpOASES::RET_HOTSTART_STOPPED_UNBOUNDEDNESS:
2501  return 2;
2502  case qpOASES::RET_INIT_FAILED_INFEASIBILITY:
2503  case qpOASES::RET_QP_INFEASIBLE:
2504  case qpOASES::RET_HOTSTART_STOPPED_INFEASIBILITY:
2505  return 3;
2506  default:
2507  return 4;
2508  }
2509  }
void computeNextHessian(BlocksqpMemory *m, casadi_int idx, casadi_int maxQP) const
Definition: blocksqp.cpp:2255
void convertHessian(BlocksqpMemory *m) const
Convert *hess to column compressed sparse format.
Definition: blocksqp.cpp:2713
void copy_vector(const std::vector< S > &s, std::vector< D > &d)
void casadi_mv(const T1 *x, const casadi_int *sp_x, const T1 *y, T1 *z, casadi_int tr)
Sparse matrix-vector multiplication: z <- z + x*y.

References casadi::BlocksqpMemory::A, Asp_, casadi::casadi_fill(), casadi::casadi_mv(), casadi::Sparsity::colind(), casadi::BlocksqpMemory::colind, computeNextHessian(), convertHessian(), casadi::copy_vector(), dim_, casadi::get_ptr(), globalization_, casadi::BlocksqpMemory::grad_fk, casadi::BlocksqpMemory::H, casadi::BlocksqpMemory::hess, casadi::BlocksqpMemory::hess1, casadi::BlocksqpMemory::hess2, casadi::BlocksqpMemory::hess_lag, hess_lim_mem_, hess_update_, casadi::BlocksqpMemory::hessIndCol, casadi::BlocksqpMemory::hessIndRow, casadi::BlocksqpMemory::itCount, casadi::BlocksqpMemory::jac_g, casadi::BlocksqpMemory::jac_times_dxk, casadi::BlocksqpMemory::lba_qp, casadi::BlocksqpMemory::lbx_qp, max_conv_qp_, max_it_qp_, max_time_qp_, nblocks_, casadi::Nlpsol::ng_, casadi::Nlpsol::nx_, casadi::ProtoFunction::print(), casadi::BlocksqpMemory::qp, casadi::BlocksqpMemory::qpIterations, casadi::BlocksqpMemory::qpIterations2, casadi::BlocksqpMemory::qpObj, casadi::BlocksqpMemory::qpResolve, casadi::BlocksqpMemory::rejectedSR1, casadi::Sparsity::row(), casadi::BlocksqpMemory::row, schur_, casadi::BlocksqpMemory::uba_qp, casadi::BlocksqpMemory::ubx_qp, warmstart_, and which_second_derv_.

Referenced by run(), and secondOrderCorrection().

◆ sp_forward()

int casadi::FunctionInternal::sp_forward ( const bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t w,
void *  mem 
) const
virtualinherited

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

Reimplemented in casadi::BSplineInterpolant, casadi::SXFunction, casadi::Rootfinder, casadi::MXFunction, casadi::MapSum, casadi::Map, and casadi::Integrator.

Definition at line 3025 of file function_internal.cpp.

3026  {
3027  // Loop over outputs
3028  for (casadi_int oind=0; oind<n_out_; ++oind) {
3029  // Skip if nothing to assign
3030  if (res[oind]==nullptr || nnz_out(oind)==0) continue;
3031  // Clear result
3032  casadi_clear(res[oind], nnz_out(oind));
3033  // Loop over inputs
3034  for (casadi_int iind=0; iind<n_in_; ++iind) {
3035  // Skip if no seeds
3036  if (arg[iind]==nullptr || nnz_in(iind)==0) continue;
3037  // Propagate sparsity for the specific block
3038  if (sp_forward_block(arg, res, iw, w, mem, oind, iind)) return 1;
3039  }
3040  }
3041  return 0;
3042  }
virtual int sp_forward_block(const bvec_t **arg, bvec_t **res, casadi_int *iw, bvec_t *w, void *mem, casadi_int oind, casadi_int iind) const
Propagate sparsity forward, specific block.
void casadi_clear(T1 *x, casadi_int n)
CLEAR: x <- 0.

References casadi::casadi_clear(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), and casadi::FunctionInternal::sp_forward_block().

Referenced by casadi::MXFunction::sp_forward(), casadi::SXFunction::sp_forward(), and casadi::BSplineInterpolant::sp_forward().

◆ sp_forward_block()

int casadi::FunctionInternal::sp_forward_block ( const bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t w,
void *  mem,
casadi_int  oind,
casadi_int  iind 
) const
virtualinherited

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

Definition at line 3044 of file function_internal.cpp.

3045  {
3046  // Get the sparsity of the Jacobian block
3047  Sparsity sp = jac_sparsity(oind, iind, true, false);
3048  if (sp.is_null() || sp.nnz() == 0) return 0; // Skip if zero
3049  // Carry out the sparse matrix-vector multiplication
3050  casadi_int d1 = sp.size2();
3051  const casadi_int *colind = sp.colind(), *row = sp.row();
3052  for (casadi_int cc=0; cc<d1; ++cc) {
3053  for (casadi_int el = colind[cc]; el < colind[cc+1]; ++el) {
3054  res[oind][row[el]] |= arg[iind][cc];
3055  }
3056  }
3057  return 0;
3058  }

References casadi::Sparsity::colind(), casadi::GenericShared< Shared, Internal >::is_null(), casadi::FunctionInternal::jac_sparsity(), casadi::Sparsity::nnz(), casadi::Sparsity::row(), and casadi::Sparsity::size2().

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

◆ sp_reverse()

int casadi::FunctionInternal::sp_reverse ( bvec_t **  arg,
bvec_t **  res,
casadi_int *  iw,
bvec_t w,
void *  mem 
) const
virtualinherited

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

Reimplemented in casadi::BSplineInterpolant, casadi::SXFunction, casadi::Rootfinder, casadi::MXFunction, casadi::MapSum, casadi::Map, and casadi::Integrator.

Definition at line 3060 of file function_internal.cpp.

3061  {
3062  // Loop over outputs
3063  for (casadi_int oind=0; oind<n_out_; ++oind) {
3064  // Skip if nothing to assign
3065  if (res[oind]==nullptr || nnz_out(oind)==0) continue;
3066 
3067  // Loop over inputs
3068  for (casadi_int iind=0; iind<n_in_; ++iind) {
3069  // Skip if no seeds
3070  if (arg[iind]==nullptr || nnz_in(iind)==0) continue;
3071 
3072  // Get the sparsity of the Jacobian block
3073  Sparsity sp = jac_sparsity(oind, iind, true, false);
3074  if (sp.is_null() || sp.nnz() == 0) continue; // Skip if zero
3075 
3076  // Carry out the sparse matrix-vector multiplication
3077  casadi_int d1 = sp.size2();
3078  const casadi_int *colind = sp.colind(), *row = sp.row();
3079  for (casadi_int cc=0; cc<d1; ++cc) {
3080  for (casadi_int el = colind[cc]; el < colind[cc+1]; ++el) {
3081  arg[iind][cc] |= res[oind][row[el]];
3082  }
3083  }
3084  }
3085 
3086  // Clear seeds
3087  casadi_clear(res[oind], nnz_out(oind));
3088  }
3089  return 0;
3090  }

References casadi::casadi_clear(), casadi::Sparsity::colind(), casadi::GenericShared< Shared, Internal >::is_null(), casadi::FunctionInternal::jac_sparsity(), casadi::FunctionInternal::n_in_, casadi::FunctionInternal::n_out_, casadi::Sparsity::nnz(), casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::nnz_out(), casadi::Sparsity::row(), and casadi::Sparsity::size2().

Referenced by casadi::MXFunction::sp_reverse(), casadi::SXFunction::sp_reverse(), and casadi::BSplineInterpolant::sp_reverse().

◆ sp_weight()

double casadi::FunctionInternal::sp_weight ( ) const
virtualinherited

sparsity propagation

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

Definition at line 3475 of file function_internal.cpp.

3475  {
3476  // If reverse mode propagation unavailable, use forward
3477  if (!has_sprev()) return 0;
3478 
3479  // If forward mode propagation unavailable, use reverse
3480  if (!has_spfwd()) return 1;
3481 
3482  // Use the (potentially user set) option
3483  return ad_weight_sp_;
3484  }

References casadi::FunctionInternal::ad_weight_sp_, casadi::FunctionInternal::has_spfwd(), and casadi::FunctionInternal::has_sprev().

Referenced by casadi::FunctionInternal::get_jac_sparsity(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::MXFunction::sp_forward(), casadi::SXFunction::sp_forward(), casadi::MXFunction::sp_reverse(), casadi::SXFunction::sp_reverse(), casadi::FunctionInternal::wrap(), and casadi::FunctionInternal::wrap_as_needed().

◆ sparsity_in()

const Sparsity& casadi::FunctionInternal::sparsity_in ( casadi_int  ind) const
inlineinherited

◆ sparsity_out()

const Sparsity& casadi::FunctionInternal::sparsity_out ( casadi_int  ind) const
inlineinherited

◆ sprint()

void casadi::ProtoFunction::sprint ( char *  buf,
size_t  buf_sz,
const char *  fmt,
  ... 
) const
inherited

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

Definition at line 4088 of file function_internal.cpp.

4088  {
4089  // Variable number of arguments
4090  va_list args;
4091  va_start(args, fmt);
4092  // Print to buffer
4093  casadi_int n = vsnprintf(buf, buf_sz, fmt, args);
4094  // Cleanup
4095  va_end(args);
4096  // Throw error if failure
4097  casadi_assert(n>=0 && n<buf_sz, "Print failure while processing '" + std::string(fmt) + "'");
4098  }

Referenced by casadi::ProtoFunction::format_time(), and casadi::ProtoFunction::print_time().

◆ string_from_UnifiedReturnStatus()

std::string casadi::FunctionInternal::string_from_UnifiedReturnStatus ( UnifiedReturnStatus  status)
staticinherited

Definition at line 4156 of file function_internal.cpp.

4156  {
4157  switch (status) {
4158  case SOLVER_RET_LIMITED: return "SOLVER_RET_LIMITED";
4159  case SOLVER_RET_NAN: return "SOLVER_RET_NAN";
4160  case SOLVER_RET_SUCCESS: return "SOLVER_RET_SUCCESS";
4161  default: return "SOLVER_RET_UNKNOWN";
4162  }
4163  }

References casadi::SOLVER_RET_LIMITED, casadi::SOLVER_RET_NAN, and casadi::SOLVER_RET_SUCCESS.

Referenced by casadi::Conic::get_stats(), casadi::Nlpsol::get_stats(), and casadi::Rootfinder::get_stats().

◆ sx_in() [1/2]

const std::vector< SX > casadi::FunctionInternal::sx_in ( ) const
virtualinherited

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

Reimplemented in casadi::SXFunction.

Definition at line 3502 of file function_internal.cpp.

3502  {
3503  std::vector<SX> ret(n_in_);
3504  for (casadi_int i=0; i<ret.size(); ++i) {
3505  ret[i] = sx_in(i);
3506  }
3507  return ret;
3508  }
virtual const std::vector< SX > sx_in() const
Get function input(s) and output(s)

References casadi::FunctionInternal::n_in_.

◆ sx_in() [2/2]

const SX casadi::FunctionInternal::sx_in ( casadi_int  ind) const
virtualinherited

◆ sx_out() [1/2]

const std::vector< SX > casadi::FunctionInternal::sx_out ( ) const
virtualinherited

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

Definition at line 3510 of file function_internal.cpp.

3510  {
3511  std::vector<SX> ret(n_out_);
3512  for (casadi_int i=0; i<ret.size(); ++i) {
3513  ret[i] = sx_out(i);
3514  }
3515  return ret;
3516  }
virtual const std::vector< SX > sx_out() const
Get function input(s) and output(s)

References casadi::FunctionInternal::n_out_.

◆ sx_out() [2/2]

const SX casadi::FunctionInternal::sx_out ( casadi_int  ind) const
virtualinherited

◆ symbolic_output()

std::vector< MX > casadi::FunctionInternal::symbolic_output ( const std::vector< MX > &  arg) const
virtualinherited

Reimplemented in casadi::MXFunction.

Definition at line 1207 of file function_internal.cpp.

1207  {
1208  return self()(arg);
1209  }

Referenced by casadi::MXFunction::symbolic_output().

◆ symbolicAdjSeed()

template<typename MatType >
std::vector< std::vector< MatType > > casadi::FunctionInternal::symbolicAdjSeed ( casadi_int  nadj,
const std::vector< MatType > &  v 
) const
inherited

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

Definition at line 1591 of file function_internal.hpp.

1592  {
1593  std::vector<std::vector<MatType> > aseed(nadj, v);
1594  for (casadi_int dir=0; dir<nadj; ++dir) {
1595  // Replace symbolic inputs
1596  casadi_int oind=0;
1597  for (typename std::vector<MatType>::iterator i=aseed[dir].begin();
1598  i!=aseed[dir].end();
1599  ++i, ++oind) {
1600  // Name of the adjoint seed
1601  std::stringstream ss;
1602  ss << "a";
1603  if (nadj>1) ss << dir << "_";
1604  ss << oind;
1605 
1606  // Save to matrix
1607  *i = MatType::sym(ss.str(), is_diff_out_[oind] ? i->sparsity() : Sparsity(i->size()));
1608 
1609  }
1610  }
1611  return aseed;
1612  }

References casadi::FunctionInternal::is_diff_out_.

◆ sz_arg()

size_t casadi::FunctionInternal::sz_arg ( ) const
inlineinherited

◆ sz_iw()

size_t casadi::FunctionInternal::sz_iw ( ) const
inlineinherited

◆ sz_res()

size_t casadi::FunctionInternal::sz_res ( ) const
inlineinherited

◆ sz_w()

size_t casadi::FunctionInternal::sz_w ( ) const
inlineinherited

◆ sz_work()

void casadi::FunctionInternal::sz_work ( size_t &  sz_arg,
size_t &  sz_res,
size_t &  sz_iw,
size_t &  sz_w 
) const
inherited

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

Definition at line 3092 of file function_internal.cpp.

3093  {
3094  sz_arg = this->sz_arg();
3095  sz_res = this->sz_res();
3096  sz_iw = this->sz_iw();
3097  sz_w = this->sz_w();
3098  }

References casadi::FunctionInternal::sz_arg(), casadi::FunctionInternal::sz_iw(), casadi::FunctionInternal::sz_res(), and casadi::FunctionInternal::sz_w().

◆ to_compact()

Sparsity casadi::FunctionInternal::to_compact ( casadi_int  oind,
casadi_int  iind,
const Sparsity sp 
) const
inherited

Definition at line 1978 of file function_internal.cpp.

1979  {
1980  // Strip rows and columns
1981  std::vector<casadi_int> mapping;
1982  return sp.sub(sparsity_out(oind).find(), sparsity_in(iind).find(), mapping);
1983  }

References casadi::FunctionInternal::find(), casadi::FunctionInternal::sparsity_in(), casadi::FunctionInternal::sparsity_out(), and casadi::Sparsity::sub().

Referenced by casadi::FunctionInternal::jac_sparsity(), and casadi::FunctionInternal::set_jac_sparsity().

◆ tocache()

void casadi::FunctionInternal::tocache ( const Function f,
const std::string &  suffix = "" 
) const
inherited

◆ tocache_if_missing()

void casadi::FunctionInternal::tocache_if_missing ( Function f,
const std::string &  suffix = "" 
) const
inherited

◆ updateDeltaGamma()

void casadi::Blocksqp::updateDeltaGamma ( BlocksqpMemory m) const

Set deltaXi and gamma as a column in the matrix containing the m most recent delta and gamma

Definition at line 2247 of file blocksqp.cpp.

2247  {
2248  if (hess_memsize_ == 1) return;
2249 
2250  m->dxk = m->deltaMat + nx_*(m->itCount % hess_memsize_);
2251  m->gamma = m->gammaMat + nx_*(m->itCount % hess_memsize_);
2252  }

References casadi::BlocksqpMemory::deltaMat, casadi::BlocksqpMemory::dxk, casadi::BlocksqpMemory::gamma, casadi::BlocksqpMemory::gammaMat, hess_memsize_, casadi::BlocksqpMemory::itCount, and casadi::Nlpsol::nx_.

Referenced by run().

◆ updateStats()

void casadi::Blocksqp::updateStats ( BlocksqpMemory m) const

Definition at line 2617 of file blocksqp.cpp.

2617  {
2618  // Do not accidentally print hessSkipped in the next iteration
2619  m->hessSkipped = 0;
2620  m->hessDamped = 0;
2621 
2622  // qpIterations = number of iterations for the QP that determines the step,
2623  // can be a resolve (+SOC)
2624  // qpIterations2 = number of iterations for a QP which solution was discarded
2625  m->qpItTotal += m->qpIterations;
2626  m->qpItTotal += m->qpIterations2;
2627  m->qpIterations = 0;
2628  m->qpIterations2 = 0;
2629  m->qpResolve = 0;
2630  }

References casadi::BlocksqpMemory::hessDamped, casadi::BlocksqpMemory::hessSkipped, casadi::BlocksqpMemory::qpIterations, casadi::BlocksqpMemory::qpIterations2, casadi::BlocksqpMemory::qpItTotal, and casadi::BlocksqpMemory::qpResolve.

Referenced by feasibilityRestorationPhase(), and run().

◆ updateStepBounds()

void casadi::Blocksqp::updateStepBounds ( BlocksqpMemory m,
bool  soc 
) const

Set bounds on the step (in the QP), either according to variable bounds in the NLP or according to trust region box radius

Definition at line 2516 of file blocksqp.cpp.

2516  {
2517  auto d_nlp = &m->d_nlp;
2518  // Bounds on step
2519  for (casadi_int i=0; i<nx_; i++) {
2520  double lbx = d_nlp->lbz[i];
2521  if (lbx != inf) {
2522  m->lbx_qp[i] = lbx - d_nlp->z[i];
2523  } else {
2524  m->lbx_qp[i] = inf;
2525  }
2526 
2527  double ubx = d_nlp->ubz[i];
2528  if (ubx != inf) {
2529  m->ubx_qp[i] = ubx - d_nlp->z[i];
2530  } else {
2531  m->ubx_qp[i] = inf;
2532  }
2533  }
2534 
2535  // Bounds on linearized constraints
2536  for (casadi_int i=0; i<ng_; i++) {
2537  double lbg = d_nlp->lbz[i+nx_];
2538  if (lbg != inf) {
2539  m->lba_qp[i] = lbg - m->gk[i];
2540  if (soc) m->lba_qp[i] += m->jac_times_dxk[i];
2541  } else {
2542  m->lba_qp[i] = inf;
2543  }
2544 
2545  double ubg = d_nlp->ubz[i+nx_];
2546  if (ubg != inf) {
2547  m->uba_qp[i] = ubg - m->gk[i];
2548  if (soc) m->uba_qp[i] += m->jac_times_dxk[i];
2549  } else {
2550  m->uba_qp[i] = inf;
2551  }
2552  }
2553  }

References casadi::NlpsolMemory::d_nlp, casadi::BlocksqpMemory::gk, casadi::inf, casadi::BlocksqpMemory::jac_times_dxk, casadi::BlocksqpMemory::lba_qp, casadi::BlocksqpMemory::lbx_qp, casadi_nlpsol_data< T1 >::lbz, casadi::Nlpsol::ng_, casadi::Nlpsol::nx_, casadi::BlocksqpMemory::uba_qp, and casadi::BlocksqpMemory::ubx_qp.

Referenced by run(), and secondOrderCorrection().

◆ uses_output()

bool casadi::Nlpsol::uses_output ( ) const
inlineoverridevirtualinherited

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

Reimplemented from casadi::FunctionInternal.

Definition at line 258 of file nlpsol_impl.hpp.

258 {return true;}

◆ weak()

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

Definition at line 67 of file generic_shared_internal.hpp.

210  {
211 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
212  auto* w = weak_ref_.load(std::memory_order_acquire);
213  if (!w) {
214  auto* nw = new GenericWeakRef<Shared, Internal>(static_cast<Internal*>(this));
215  GenericWeakRef<Shared, Internal>* expected = nullptr;
216  if (weak_ref_.compare_exchange_strong(
217  expected, nw, std::memory_order_release, std::memory_order_acquire)) {
218  w = nw;
219  } else {
220  delete nw; // lost the race; another thread published first
221  w = expected;
222  }
223  }
224  return w;
225 #else
226  if (weak_ref_==nullptr) {
227  weak_ref_ = new GenericWeakRef<Shared, Internal>(static_cast<Internal*>(this));
228  }
229  return weak_ref_;
230 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
231  }

◆ which_depends()

std::vector< bool > casadi::FunctionInternal::which_depends ( const std::string &  s_in,
const std::vector< std::string > &  s_out,
casadi_int  order,
bool  tr = false 
) const
virtualinherited
Parameters
[in]s_inInput name
[in]s_outOutput name(s)
[in]orderOnly 1 (linear) and 2 (nonlinear) allowed
[in]trFlip the relationship. Return which expressions contain the variables

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

Reimplemented in casadi::XFunction< DerivedType, MatType, NodeType >, casadi::XFunction< MXFunction, MX, MXNode >, and casadi::XFunction< SXFunction, Matrix< SXElem >, SXNode >.

Definition at line 3925 of file function_internal.cpp.

3927  {
3928  Function f = shared_from_this<Function>();
3929  f = f.wrap();
3930  return f.which_depends(s_in, s_out, order, tr);
3931  }

References casadi::Function::which_depends(), and casadi::Function::wrap().

◆ wrap() [1/2]

Function casadi::FunctionInternal::wrap ( ) const
inherited

◆ wrap() [2/2]

Function casadi::FunctionInternal::wrap ( const std::string &  name) const
inherited

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

Definition at line 1186 of file function_internal.cpp.

1186  {
1187  Function f;
1188  if (!incache(name, f)) {
1189  // Options
1190  Dict opts;
1191  opts["derivative_of"] = derivative_of_;
1192  opts["ad_weight"] = ad_weight();
1193  opts["ad_weight_sp"] = sp_weight();
1194  opts["max_num_dir"] = max_num_dir_;
1195  opts["is_diff_in"] = is_diff_in_;
1196  opts["is_diff_out"] = is_diff_out_;
1197  // Wrap the function
1198  std::vector<MX> arg = mx_in();
1199  std::vector<MX> res = self()(arg);
1200  f = Function(name, arg, res, name_in_, name_out_, opts);
1201  // Save in cache
1202  tocache_if_missing(f);
1203  }
1204  return f;
1205  }

References casadi::FunctionInternal::ad_weight(), casadi::FunctionInternal::derivative_of_, casadi::FunctionInternal::Function, casadi::FunctionInternal::incache(), casadi::FunctionInternal::is_diff_in_, casadi::FunctionInternal::is_diff_out_, casadi::FunctionInternal::max_num_dir_, casadi::FunctionInternal::mx_in(), casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, casadi::FunctionInternal::sp_weight(), and casadi::FunctionInternal::tocache_if_missing().

Referenced by casadi::Function::wrap().

◆ wrap_as_needed() [1/2]

Function casadi::FunctionInternal::wrap_as_needed ( const Dict opts) const
inherited

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

Definition at line 1161 of file function_internal.cpp.

1161  {
1162  return wrap_as_needed("wrap_" + name_, opts);
1163  }
Function wrap_as_needed(const std::string &name, const Dict &opts) const
Wrap in an Function instance consisting of only one MX call.

References casadi::ProtoFunction::name_, and casadi::FunctionInternal::wrap_as_needed().

◆ wrap_as_needed() [2/2]

Function casadi::FunctionInternal::wrap_as_needed ( const std::string &  name,
const Dict opts 
) const
inherited

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

Definition at line 1165 of file function_internal.cpp.

1165  {
1166  if (opts.empty() && name==name_) return shared_from_this<Function>();
1167  // Options
1168  Dict my_opts = opts;
1169  my_opts["derivative_of"] = derivative_of_;
1170  if (my_opts.find("ad_weight")==my_opts.end())
1171  my_opts["ad_weight"] = ad_weight();
1172  if (my_opts.find("ad_weight_sp")==my_opts.end())
1173  my_opts["ad_weight_sp"] = sp_weight();
1174  if (my_opts.find("max_num_dir")==my_opts.end())
1175  my_opts["max_num_dir"] = max_num_dir_;
1176  // Wrap the function
1177  std::vector<MX> arg = mx_in();
1178  std::vector<MX> res = self()(arg);
1179  return Function(name, arg, res, name_in_, name_out_, my_opts);
1180  }

References casadi::FunctionInternal::ad_weight(), casadi::FunctionInternal::derivative_of_, casadi::FunctionInternal::Function, casadi::FunctionInternal::max_num_dir_, casadi::FunctionInternal::mx_in(), casadi::ProtoFunction::name_, casadi::FunctionInternal::name_in_, casadi::FunctionInternal::name_out_, and casadi::FunctionInternal::sp_weight().

Referenced by casadi::Function::wrap_as_needed(), and casadi::FunctionInternal::wrap_as_needed().

Member Data Documentation

◆ ad_weight_

double casadi::FunctionInternal::ad_weight_
inherited

◆ ad_weight_sp_

double casadi::FunctionInternal::ad_weight_sp_
inherited

◆ all_functions_

std::map<std::string, RegFun> casadi::OracleFunction::all_functions_
protectedinherited

◆ always_inline_

bool casadi::FunctionInternal::always_inline_
inherited

◆ Asp_

Sparsity casadi::Blocksqp::Asp_

◆ block_hess_

bool casadi::Blocksqp::block_hess_

◆ blocks_

std::vector<casadi_int> casadi::Blocksqp::blocks_

◆ bound_consistency_

bool casadi::Nlpsol::bound_consistency_
inherited

◆ cache_

WeakCache<std::string, Function> casadi::FunctionInternal::cache_
mutableinherited

◆ cache_init_

Dict casadi::FunctionInternal::cache_init_
inherited

◆ calc_f_

bool casadi::Nlpsol::calc_f_
inherited

◆ calc_g_

bool casadi::Nlpsol::calc_g_
inherited

◆ calc_lam_p_

bool casadi::Nlpsol::calc_lam_p_
inherited

◆ calc_lam_x_

bool casadi::Nlpsol::calc_lam_x_
inherited

◆ calc_multipliers_

bool casadi::Nlpsol::calc_multipliers_
inherited

◆ callback_step_

casadi_int casadi::Nlpsol::callback_step_
inherited

◆ checkout_

casadi_checkout_t casadi::FunctionInternal::checkout_
inherited

◆ col_eps_

double casadi::Blocksqp::col_eps_

Definition at line 361 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and sizeHessianCOL().

◆ col_tau1_

double casadi::Blocksqp::col_tau1_

Definition at line 362 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and sizeHessianCOL().

◆ col_tau2_

double casadi::Blocksqp::col_tau2_

Definition at line 363 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and sizeHessianCOL().

◆ common_options_

Dict casadi::OracleFunction::common_options_
protectedinherited

◆ compiler_

Importer casadi::FunctionInternal::compiler_
inherited

◆ compiler_plugin_

std::string casadi::FunctionInternal::compiler_plugin_
inherited

◆ conv_strategy_

casadi_int casadi::Blocksqp::conv_strategy_

Definition at line 373 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().

◆ custom_jacobian_

Function casadi::FunctionInternal::custom_jacobian_
inherited

◆ decref_

signal_t casadi::FunctionInternal::decref_
inherited

◆ delta_

double casadi::Blocksqp::delta_

Definition at line 385 of file blocksqp.hpp.

Referenced by Blocksqp(), filterLineSearch(), init(), and serialize_body().

◆ delta_h0_

double casadi::Blocksqp::delta_h0_

Definition at line 391 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().

◆ der_options_

Dict casadi::FunctionInternal::der_options_
inherited

◆ derivative_of_

Function casadi::FunctionInternal::derivative_of_
inherited

◆ deserialize_map

std::map< std::string, ProtoFunction *(*)(DeserializingStream &)> casadi::FunctionInternal::deserialize_map
staticinherited
Initial value:
= {
{"MXFunction", MXFunction::deserialize},
{"SXFunction", SXFunction::deserialize},
{"Interpolant", Interpolant::deserialize},
{"Switch", Switch::deserialize},
{"Map", Map::deserialize},
{"MapSum", MapSum::deserialize},
{"Nlpsol", Nlpsol::deserialize},
{"Rootfinder", Rootfinder::deserialize},
{"Integrator", Integrator::deserialize},
{"External", External::deserialize},
{"Conic", Conic::deserialize},
{"FmuFunction", FmuFunction::deserialize},
{"BlazingSplineFunction", BlazingSplineFunction::deserialize},
}
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize into MX.
void deserialize(DeserializingStream &s, SDPToSOCPMem &m)
Definition: conic.cpp:744
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize into MX.
Definition: external.cpp:508
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize without type information.
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize into MX.
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize with type disambiguation.
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize with type disambiguation.
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize with type disambiguation.
Definition: mapsum.cpp:85
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize with type disambiguation.
Definition: map.cpp:110
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize into MX.
Definition: nlpsol.cpp:1444
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize into a plugin instance (dispatches on the plugin name)
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize into MX.
Definition: rootfinder.cpp:595
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize without type information.
static ProtoFunction * deserialize(DeserializingStream &s)
Deserialize without type information.
Definition: switch.hpp:150

Definition at line 1511 of file function_internal.hpp.

Referenced by casadi::FunctionInternal::deserialize().

◆ detect_simple_bounds_is_simple_

std::vector<char> casadi::Nlpsol::detect_simple_bounds_is_simple_
inherited

◆ detect_simple_bounds_parts_

Function casadi::Nlpsol::detect_simple_bounds_parts_
inherited

◆ detect_simple_bounds_target_g_

std::vector<casadi_int> casadi::Nlpsol::detect_simple_bounds_target_g_
inherited

◆ detect_simple_bounds_target_x_

std::vector<casadi_int> casadi::Nlpsol::detect_simple_bounds_target_x_
inherited

◆ dim_

std::vector<casadi_int> casadi::Blocksqp::dim_

◆ discrete_

std::vector<bool> casadi::Nlpsol::discrete_
inherited

◆ dump_

bool casadi::FunctionInternal::dump_
inherited

◆ dump_count_

casadi_int casadi::FunctionInternal::dump_count_
mutableinherited

◆ dump_dir_

std::string casadi::FunctionInternal::dump_dir_
inherited

◆ dump_format_

std::string casadi::FunctionInternal::dump_format_
inherited

◆ dump_in_

bool casadi::FunctionInternal::dump_in_
inherited

◆ dump_out_

bool casadi::FunctionInternal::dump_out_
inherited

◆ enable_fd_

bool casadi::FunctionInternal::enable_fd_
inherited

◆ enable_fd_op_

bool casadi::FunctionInternal::enable_fd_op_
inherited

◆ enable_forward_

bool casadi::FunctionInternal::enable_forward_
inherited

◆ enable_forward_op_

bool casadi::FunctionInternal::enable_forward_op_
inherited

◆ enable_jacobian_

bool casadi::FunctionInternal::enable_jacobian_
inherited

◆ enable_jacobian_op_

bool casadi::FunctionInternal::enable_jacobian_op_
inherited

◆ enable_reverse_

bool casadi::FunctionInternal::enable_reverse_
inherited

◆ enable_reverse_op_

bool casadi::FunctionInternal::enable_reverse_op_
inherited

◆ eps_

double casadi::Blocksqp::eps_

◆ equality_

std::vector<bool> casadi::Nlpsol::equality_
inherited

◆ error_on_fail_

bool casadi::ProtoFunction::error_on_fail_
inherited

◆ eta_

double casadi::Blocksqp::eta_

Definition at line 392 of file blocksqp.hpp.

Referenced by Blocksqp(), filterLineSearch(), init(), secondOrderCorrection(), and serialize_body().

◆ eval_

eval_t casadi::FunctionInternal::eval_
inherited

◆ eval_errors_fatal_

bool casadi::Nlpsol::eval_errors_fatal_
inherited

◆ exact_hess_lag_sp_

Sparsity casadi::Blocksqp::exact_hess_lag_sp_

Definition at line 203 of file blocksqp.hpp.

Referenced by Blocksqp(), calcHessianUpdateExact(), init(), serialize_body(), and set_work().

◆ fallback_scaling_

casadi_int casadi::Blocksqp::fallback_scaling_

◆ fallback_update_

casadi_int casadi::Blocksqp::fallback_update_

◆ fcallback_

Function casadi::Nlpsol::fcallback_
inherited

◆ fd_method_

std::string casadi::FunctionInternal::fd_method_
inherited

◆ fd_options_

Dict casadi::FunctionInternal::fd_options_
inherited

◆ fd_step_

double casadi::FunctionInternal::fd_step_
inherited

◆ forward_options_

Dict casadi::FunctionInternal::forward_options_
inherited

◆ gamma_f_

double casadi::Blocksqp::gamma_f_

◆ gamma_theta_

double casadi::Blocksqp::gamma_theta_

◆ globalization_

bool casadi::Blocksqp::globalization_

Definition at line 347 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), printInfo(), run(), serialize_body(), and solveQP().

◆ has_refcount_

bool casadi::FunctionInternal::has_refcount_
inherited

◆ has_refcount_in_deps_

bool casadi::FunctionInternal::has_refcount_in_deps_
inherited

◆ hess_damp_

casadi_int casadi::Blocksqp::hess_damp_

Definition at line 364 of file blocksqp.hpp.

Referenced by Blocksqp(), calcBFGS(), computeNextHessian(), init(), printInfo(), and serialize_body().

◆ hess_damp_fac_

double casadi::Blocksqp::hess_damp_fac_

Definition at line 365 of file blocksqp.hpp.

Referenced by Blocksqp(), calcBFGS(), init(), and serialize_body().

◆ hess_lim_mem_

casadi_int casadi::Blocksqp::hess_lim_mem_

◆ hess_memsize_

casadi_int casadi::Blocksqp::hess_memsize_

◆ hess_scaling_

casadi_int casadi::Blocksqp::hess_scaling_

Definition at line 357 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), printInfo(), run(), and serialize_body().

◆ hess_update_

casadi_int casadi::Blocksqp::hess_update_

Definition at line 366 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), printInfo(), reset_sqp(), run(), serialize_body(), set_work(), and solveQP().

◆ Hsp_

Sparsity casadi::Blocksqp::Hsp_

Definition at line 202 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().

◆ incref_

signal_t casadi::FunctionInternal::incref_
inherited

◆ infix_

const std::string casadi::Nlpsol::infix_ = "nlpsol"
staticinherited

Definition at line 309 of file nlpsol_impl.hpp.

◆ ini_hess_diag_

double casadi::Blocksqp::ini_hess_diag_

Definition at line 360 of file blocksqp.hpp.

Referenced by Blocksqp(), calcInitialHessian(), init(), and serialize_body().

◆ inputs_check_

bool casadi::FunctionInternal::inputs_check_
inherited

◆ is_diff_in_

std::vector<bool> casadi::FunctionInternal::is_diff_in_
inherited

◆ is_diff_out_

std::vector<bool> casadi::FunctionInternal::is_diff_out_
inherited

◆ iteration_callback_ignore_errors_

bool casadi::Nlpsol::iteration_callback_ignore_errors_
inherited

◆ jac_penalty_

double casadi::FunctionInternal::jac_penalty_
inherited

◆ jac_sparsity_

std::vector<Sparsity> casadi::FunctionInternal::jac_sparsity_[2]
mutableinherited

◆ jacobian_options_

Dict casadi::FunctionInternal::jacobian_options_
inherited

◆ jit_

bool casadi::FunctionInternal::jit_
inherited

◆ jit_base_name_

std::string casadi::FunctionInternal::jit_base_name_
inherited

◆ jit_cleanup_

bool casadi::FunctionInternal::jit_cleanup_
inherited

◆ jit_directory_

std::string casadi::FunctionInternal::jit_directory_
inherited

◆ jit_name_

std::string casadi::FunctionInternal::jit_name_
inherited

◆ jit_options_

Dict casadi::FunctionInternal::jit_options_
inherited

◆ jit_serialize_

std::string casadi::FunctionInternal::jit_serialize_
inherited

◆ jit_temp_suffix_

bool casadi::FunctionInternal::jit_temp_suffix_
inherited

◆ kappa_f_

double casadi::Blocksqp::kappa_f_

Definition at line 382 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), kktErrorReduction(), and serialize_body().

◆ kappa_minus_

double casadi::Blocksqp::kappa_minus_

Definition at line 388 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().

◆ kappa_plus_

double casadi::Blocksqp::kappa_plus_

Definition at line 389 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().

◆ kappa_plus_max_

double casadi::Blocksqp::kappa_plus_max_

Definition at line 390 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().

◆ kappa_soc_

double casadi::Blocksqp::kappa_soc_

Definition at line 381 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), secondOrderCorrection(), and serialize_body().

◆ kkt_

WeakRef casadi::Nlpsol::kkt_
mutableinherited

Definition at line 109 of file nlpsol_impl.hpp.

Referenced by casadi::Nlpsol::kkt().

◆ linsol_plugin_

std::string casadi::Blocksqp::linsol_plugin_

Definition at line 336 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), init_mem(), and serialize_body().

◆ max_consec_reduced_steps_

casadi_int casadi::Blocksqp::max_consec_reduced_steps_

Definition at line 350 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), run(), and serialize_body().

◆ max_consec_skipped_updates_

casadi_int casadi::Blocksqp::max_consec_skipped_updates_

◆ max_conv_qp_

casadi_int casadi::Blocksqp::max_conv_qp_

Definition at line 374 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and solveQP().

◆ max_io_

casadi_int casadi::FunctionInternal::max_io_
inherited

◆ max_it_qp_

casadi_int casadi::Blocksqp::max_it_qp_

Definition at line 352 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and solveQP().

◆ max_iter_

casadi_int casadi::Blocksqp::max_iter_

Definition at line 353 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and solve().

◆ max_line_search_

casadi_int casadi::Blocksqp::max_line_search_

Definition at line 349 of file blocksqp.hpp.

Referenced by Blocksqp(), filterLineSearch(), init(), and serialize_body().

◆ max_num_dir_

casadi_int casadi::FunctionInternal::max_num_dir_
inherited

◆ max_num_threads_

int casadi::OracleFunction::max_num_threads_
protectedinherited

◆ max_soc_iter_

casadi_int casadi::Blocksqp::max_soc_iter_

Definition at line 378 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), secondOrderCorrection(), and serialize_body().

◆ max_time_qp_

double casadi::Blocksqp::max_time_qp_

Definition at line 359 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and solveQP().

◆ meta_doc

const std::string casadi::Blocksqp::meta_doc
static

Definition at line 193 of file blocksqp.hpp.

Referenced by casadi::casadi_register_nlpsol_blocksqp().

◆ mi_

bool casadi::Nlpsol::mi_
inherited

◆ min_lam_

double casadi::Nlpsol::min_lam_
inherited

◆ monitor_

std::vector<std::string> casadi::OracleFunction::monitor_
protectedinherited

◆ n_in_

size_t casadi::FunctionInternal::n_in_
inherited

Definition at line 1309 of file function_internal.hpp.

Referenced by casadi::SXFunction::ad_forward(), casadi::Rootfinder::ad_reverse(), casadi::MXFunction::ad_reverse(), casadi::SXFunction::ad_reverse(), casadi::FunctionInternal::all_scalar(), casadi::KinsolInterface::bjac(), casadi::FunctionInternal::call_forward(), casadi::FunctionInternal::call_gen(), casadi::FunctionInternal::call_reverse(), casadi::SXFunction::call_setup(), casadi::FunctionInternal::check_arg(), casadi::JitFunction::codegen_body(), casadi::Map::codegen_body(), casadi::OmpMap::codegen_body(), casadi::ThreadMap::codegen_body(), casadi::MapSum::codegen_body(), casadi::MXFunction::codegen_body(), casadi::Switch::codegen_body(), casadi::SXFunction::codegen_body(), casadi::FastNewton::codegen_body(), casadi::ThreadMap::codegen_declarations(), casadi::FunctionInternal::codegen_meta(), casadi::FunctionInternal::convert_arg(), casadi::FunctionInternal::definition(), casadi::KinsolInterface::djac(), casadi::FunctionInternal::dm_in(), casadi::FunctionInternal::eval(), casadi::OmpMap::eval(), casadi::MXFunction::eval(), casadi::Switch::eval(), casadi::MXFunction::eval_activity(), casadi::FunctionInternal::eval_gen(), casadi::Map::eval_gen(), casadi::MapSum::eval_gen(), casadi::MXFunction::eval_mx(), casadi::SXFunction::eval_mx(), casadi::Switch::eval_sx(), casadi::SXFunction::export_code_body(), casadi::CallbackInternal::finalize(), casadi::FmuFunction::FmuFunction(), casadi::FunctionInternal::forward(), casadi::KinsolInterface::func(), casadi::FunctionInternal::FunctionInternal(), casadi::FunctionInternal::fwd_seed(), casadi::FunctionInternal::generate_in(), casadi::GenericExternal::get_jac_sparsity(), casadi::GenericExternal::has_jac_sparsity(), casadi::FunctionInternal::init(), casadi::MXFunction::init(), casadi::Switch::init(), casadi::SXFunction::init(), casadi::ImplicitToNlp::init(), casadi::FunctionInternal::jac_sparsity(), casadi::FunctionInternal::jacobian(), casadi::KinsolInterface::jtimes(), casadi::FunctionInternal::mapsum_mx(), casadi::FunctionInternal::matching_arg(), casadi::FunctionInternal::mx_in(), casadi::FunctionInternal::nnz_in(), casadi::FunctionInternal::numel_in(), casadi::FunctionInternal::nz_in(), casadi::SXFunction::print_arg(), casadi::FunctionInternal::print_dimensions(), casadi::FunctionInternal::print_in(), casadi::FunctionInternal::project_arg(), casadi::KinsolInterface::psetup(), casadi::FunctionInternal::reverse(), casadi::FmuFunction::serialize_body(), casadi::FunctionInternal::set_jac_sparsity(), casadi::Rootfinder::set_work(), casadi::QpToNlp::solve(), casadi::KinsolInterface::solve(), casadi::FastNewton::solve(), casadi::ImplicitToNlp::solve(), casadi::Newton::solve(), casadi::FunctionInternal::sp_forward(), casadi::Integrator::sp_forward(), casadi::MXFunction::sp_forward(), casadi::Rootfinder::sp_forward(), casadi::FunctionInternal::sp_reverse(), casadi::Integrator::sp_reverse(), casadi::Map::sp_reverse(), casadi::MapSum::sp_reverse(), casadi::MXFunction::sp_reverse(), casadi::Rootfinder::sp_reverse(), and casadi::FunctionInternal::sx_in().

◆ n_out_

size_t casadi::FunctionInternal::n_out_
inherited

Definition at line 1309 of file function_internal.hpp.

Referenced by casadi::Rootfinder::ad_forward(), casadi::MXFunction::ad_forward(), casadi::SXFunction::ad_forward(), casadi::Rootfinder::ad_reverse(), casadi::SXFunction::ad_reverse(), casadi::FunctionInternal::all_scalar(), casadi::KinsolInterface::bjac(), casadi::FunctionInternal::call(), casadi::FunctionInternal::call_forward(), casadi::FunctionInternal::call_gen(), casadi::FunctionInternal::call_reverse(), casadi::SXFunction::call_setup(), casadi::FunctionInternal::check_res(), casadi::JitFunction::codegen_body(), casadi::Map::codegen_body(), casadi::OmpMap::codegen_body(), casadi::ThreadMap::codegen_body(), casadi::MapSum::codegen_body(), casadi::MXFunction::codegen_body(), casadi::Switch::codegen_body(), casadi::SXFunction::codegen_body(), casadi::FastNewton::codegen_body(), casadi::ThreadMap::codegen_declarations(), casadi::FunctionInternal::codegen_meta(), casadi::FunctionInternal::convert_res(), casadi::FunctionInternal::definition(), casadi::KinsolInterface::djac(), casadi::FunctionInternal::dm_out(), casadi::FunctionInternal::eval(), casadi::OmpMap::eval(), casadi::MXFunction::eval(), casadi::Switch::eval(), casadi::FunctionInternal::eval_activity(), casadi::MXFunction::eval_activity(), casadi::FunctionInternal::eval_gen(), casadi::Map::eval_gen(), casadi::MapSum::eval_gen(), casadi::Switch::eval_sx(), casadi::CallbackInternal::finalize(), casadi::FmuFunction::FmuFunction(), casadi::FunctionInternal::forward(), casadi::KinsolInterface::func(), casadi::FunctionInternal::FunctionInternal(), casadi::FunctionInternal::generate_out(), casadi::LinearInterpolantJac::get_jacobian(), casadi::FunctionInternal::init(), casadi::MapSum::init(), casadi::Nlpsol::init(), casadi::Switch::init(), casadi::FunctionInternal::jac_sparsity(), casadi::FunctionInternal::jacobian(), casadi::FunctionInternal::mapsum_mx(), casadi::FunctionInternal::matching_res(), casadi::FunctionInternal::mx_out(), casadi::FunctionInternal::nnz_out(), casadi::FunctionInternal::numel_out(), casadi::FunctionInternal::nz_out(), casadi::FunctionInternal::print_dimensions(), casadi::FunctionInternal::print_out(), casadi::KinsolInterface::psetup(), casadi::FunctionInternal::reverse(), casadi::FmuFunction::serialize_body(), casadi::FunctionInternal::set_jac_sparsity(), casadi::Rootfinder::set_work(), casadi::QpToNlp::solve(), casadi::KinsolInterface::solve(), casadi::FastNewton::solve(), casadi::ImplicitToNlp::solve(), casadi::Newton::solve(), casadi::FunctionInternal::sp_forward(), casadi::Integrator::sp_forward(), casadi::MXFunction::sp_forward(), casadi::Rootfinder::sp_forward(), casadi::FunctionInternal::sp_reverse(), casadi::Integrator::sp_reverse(), casadi::Map::sp_reverse(), casadi::MapSum::sp_reverse(), casadi::MXFunction::sp_reverse(), casadi::Rootfinder::sp_reverse(), and casadi::FunctionInternal::sx_out().

◆ name_

std::string casadi::ProtoFunction::name_
inherited

Definition at line 246 of file function_internal.hpp.

Referenced by casadi::MXFunction::ad_forward(), casadi::SXFunction::ad_forward(), casadi::MXFunction::ad_reverse(), casadi::SXFunction::ad_reverse(), casadi::Integrator::augmented_dae(), casadi::OracleFunction::calc_function(), casadi::FunctionInternal::call_forward(), casadi::FunctionInternal::call_reverse(), casadi::FunctionInternal::codegen_body(), casadi::External::codegen_body(), casadi::External::codegen_checkout(), casadi::External::codegen_declarations(), casadi::MXFunction::codegen_declarations(), casadi::SXFunction::codegen_declarations(), casadi::External::codegen_decref(), casadi::External::codegen_incref(), casadi::FunctionInternal::codegen_meta(), casadi::FunctionInternal::codegen_name(), casadi::External::codegen_release(), casadi::FunctionInternal::codegen_sparsities(), casadi::ProtoFunction::construct(), casadi::OracleFunction::create_function(), casadi::FunctionInternal::definition(), casadi::FunctionInternal::eval(), casadi::MXFunction::eval(), casadi::SXFunction::eval(), casadi::FunctionInternal::eval_mx(), casadi::MXFunction::eval_mx(), casadi::SXFunction::eval_mx(), casadi::SXFunction::eval_sx(), casadi::FmuFunction::factory(), casadi::FunctionInternal::finalize(), casadi::FunctionInternal::forward(), casadi::FunctionInternal::FunctionInternal(), casadi::Integrator::get_forward(), casadi::Integrator::get_forward_dae(), casadi::Map::get_function(), casadi::MapSum::get_function(), casadi::OracleFunction::get_function(), casadi::GenericExternal::get_jac_sparsity(), casadi::BlazingSplineFunction::get_jacobian(), casadi::FunctionInternal::get_n_in(), casadi::External::get_n_in(), casadi::FunctionInternal::get_n_out(), casadi::External::get_n_out(), casadi::FunctionInternal::get_name_in(), casadi::External::get_name_in(), casadi::FunctionInternal::get_name_out(), casadi::External::get_name_out(), casadi::FunctionInternal::get_partition(), casadi::Integrator::get_reverse(), casadi::FunctionInternal::get_sparsity_in(), casadi::GenericExternal::get_sparsity_in(), casadi::FunctionInternal::get_sparsity_out(), casadi::GenericExternal::get_sparsity_out(), casadi::FunctionInternal::get_stats(), casadi::External::has_forward(), casadi::GenericExternal::has_jac_sparsity(), casadi::External::has_jacobian(), casadi::External::has_reverse(), casadi::BlazingSplineFunction::init(), casadi::External::init(), casadi::FunctionInternal::init(), casadi::MXFunction::init(), casadi::SXFunction::init(), casadi::CvodesInterface::init(), casadi::IdasInterface::init(), casadi::External::init_external(), casadi::GenericExternal::init_external(), casadi::OnnxRuntimeInterface::init_mem(), casadi::FunctionInternal::jac_is_symm(), casadi::FunctionInternal::jacobian(), casadi::FunctionInternal::map(), casadi::OracleFunction::monitored(), casadi::MXFunction::print_arg(), casadi::SXFunction::print_arg(), casadi::FunctionInternal::print_in(), casadi::FunctionInternal::print_out(), casadi::MXFunction::print_res(), casadi::SXFunction::print_res(), casadi::ProtoFunction::print_time(), casadi::ProtoFunction::ProtoFunction(), casadi::CvodesInterface::reset(), casadi::IdasInterface::reset(), casadi::IdasInterface::resetB(), casadi::FunctionInternal::reverse(), casadi::ProtoFunction::serialize_body(), casadi::GurobiInterface::solve(), casadi::SnoptInterface::solve(), casadi::Integrator::sp_forward(), casadi::Integrator::sp_reverse(), casadi::FunctionInternal::wrap(), and casadi::FunctionInternal::wrap_as_needed().

◆ name_in_

std::vector<std::string> casadi::FunctionInternal::name_in_
inherited

◆ name_out_

std::vector<std::string> casadi::FunctionInternal::name_out_
inherited

◆ nblocks_

casadi_int casadi::Blocksqp::nblocks_

◆ never_inline_

bool casadi::FunctionInternal::never_inline_
inherited

◆ ng_

casadi_int casadi::Nlpsol::ng_
inherited

Definition at line 69 of file nlpsol_impl.hpp.

Referenced by acceptStep(), casadi::AlpaqaProblem::AlpaqaProblem(), casadi::BonminUserClass::BonminUserClass(), calcOptTol(), casadi::Feasiblesqpmethod::codegen_body(), casadi::Sqpmethod::codegen_body(), casadi::Feasiblesqpmethod::codegen_feasibility_iterations(), casadi::Nlpsol::codegen_post_solve(), casadi::Sqpmethod::codegen_qp_ela_solve(), casadi::Nlpsol::codegen_setup_constants(), casadi::Nlpsol::codegen_setup_per_call(), casadi::Sqpmethod::codegen_solve_elastic_mode(), casadi::Feasiblesqpmethod::codegen_step_update(), casadi::Nlpsol::eval(), casadi::Scpgen::eval_vec(), evaluate(), casadi::Feasiblesqpmethod::feasibility_iterations(), feasibilityRestorationPhase(), casadi::IpoptUserClass::finalize_metadata(), casadi::BonminInterface::finalize_solution(), casadi::IpoptInterface::finalize_solution(), casadi::BonminInterface::get_bounds_info(), casadi::BonminUserClass::get_bounds_info(), casadi::IpoptUserClass::get_bounds_info(), casadi::IpoptInterface::get_bounds_info(), casadi::Nlpsol::get_forward(), casadi::BonminInterface::get_nlp_info(), casadi::IpoptInterface::get_nlp_info(), casadi::Nlpsol::get_reverse(), casadi::BonminInterface::get_starting_point(), casadi::BonminUserClass::get_starting_point(), casadi::IpoptUserClass::get_starting_point(), casadi::IpoptInterface::get_starting_point(), casadi::Nlpsol::init(), casadi::AlpaqaInterface::init(), casadi::AmplInterface::init(), init(), casadi::BonminInterface::init(), casadi::MadmpecInterface::init(), casadi::FatropInterface::init(), casadi::IpoptInterface::init(), casadi::KnitroInterface::init(), casadi::SLEQPInterface::init(), casadi::SnoptInterface::init(), casadi::UnoInterface::init(), casadi::Feasiblesqpmethod::init(), casadi::Qrsqp::init(), casadi::Scpgen::init(), casadi::Sqpmethod::init(), casadi::IpoptInterface::init_mem(), casadi::SnoptInterface::init_mem(), casadi::BonminInterface::intermediate_callback(), casadi::IpoptInterface::intermediate_callback(), casadi::IpoptUserClass::IpoptUserClass(), kktErrorReduction(), casadi::Scpgen::line_search(), lInfConstraintNorm(), casadi::Nlpsol::Nlpsol(), casadi::Scpgen::primalInfeasibility(), reduceSOCStepsize(), reset_sqp(), secondOrderCorrection(), casadi::Nlpsol::serialize_body(), set_work(), casadi::BonminInterface::set_work(), casadi::IpoptInterface::set_work(), casadi::KnitroInterface::set_work(), casadi::SLEQPInterface::set_work(), casadi::SnoptInterface::set_work(), casadi::WorhpInterface::set_work(), casadi::Qrsqp::set_work(), casadi::Scpgen::set_work(), casadi::AlpaqaInterface::solve(), casadi::AmplInterface::solve(), solve(), casadi::BonminInterface::solve(), casadi::IpoptInterface::solve(), casadi::KnitroInterface::solve(), casadi::SnoptInterface::solve(), casadi::WorhpInterface::solve(), casadi::Feasiblesqpmethod::solve(), casadi::Qrsqp::solve(), casadi::Scpgen::solve(), casadi::Sqpmethod::solve(), casadi::Sqpmethod::solve_ela_QP(), casadi::Sqpmethod::solve_elastic_mode(), casadi::Scpgen::solve_qp(), solveQP(), casadi::Feasiblesqpmethod::step_update(), casadi::UnoInterface::UnoInterface(), and updateStepBounds().

◆ nlinfeastol_

double casadi::Blocksqp::nlinfeastol_

◆ nnz_H_

casadi_int casadi::Blocksqp::nnz_H_

Definition at line 199 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and set_work().

◆ no_nlp_grad_

bool casadi::Nlpsol::no_nlp_grad_
inherited

◆ np_

casadi_int casadi::Nlpsol::np_
inherited

◆ nx_

casadi_int casadi::Nlpsol::nx_
inherited

Definition at line 66 of file nlpsol_impl.hpp.

Referenced by acceptStep(), casadi::AlpaqaProblem::AlpaqaProblem(), casadi::Feasiblesqpmethod::anderson_acc_init_memory(), casadi::Feasiblesqpmethod::anderson_acc_step_update(), casadi::Feasiblesqpmethod::anderson_acc_update_memory(), casadi::BonminUserClass::BonminUserClass(), casadi::Sqpmethod::calc_gamma_1(), calcHessianUpdateLimitedMemory(), calcLagrangeGradient(), calcOptTol(), casadi::Nlpsol::callback(), casadi::Nlpsol::check_inputs(), casadi::Feasiblesqpmethod::codegen_body(), casadi::Sqpmethod::codegen_body(), casadi::Sqpmethod::codegen_calc_gamma_1(), casadi::Feasiblesqpmethod::codegen_eval_m_k(), casadi::Feasiblesqpmethod::codegen_feasibility_iterations(), casadi::Nlpsol::codegen_post_solve(), casadi::Sqpmethod::codegen_qp_ela_solve(), casadi::Feasiblesqpmethod::codegen_qp_solve(), casadi::Sqpmethod::codegen_qp_solve(), casadi::Nlpsol::codegen_setup_constants(), casadi::Nlpsol::codegen_setup_per_call(), casadi::Sqpmethod::codegen_solve_elastic_mode(), casadi::Feasiblesqpmethod::codegen_step_update(), casadi::Feasiblesqpmethod::codegen_tr_update(), convertHessian(), casadi::Scpgen::dualInfeasibility(), casadi::Nlpsol::eval(), casadi::Scpgen::eval_exp(), casadi::Feasiblesqpmethod::eval_m_k(), casadi::Scpgen::eval_mat(), casadi::Scpgen::eval_res(), casadi::Scpgen::eval_vec(), evaluate(), casadi::Feasiblesqpmethod::feasibility_iterations(), feasibilityRestorationHeuristic(), feasibilityRestorationPhase(), filterLineSearch(), casadi::IpoptUserClass::finalize_metadata(), casadi::BonminInterface::finalize_solution(), casadi::IpoptInterface::finalize_solution(), fullstep(), casadi::BonminInterface::get_bounds_info(), casadi::BonminUserClass::get_bounds_info(), casadi::IpoptUserClass::get_bounds_info(), casadi::IpoptInterface::get_bounds_info(), casadi::Nlpsol::get_forward(), casadi::BonminInterface::get_nlp_info(), casadi::IpoptInterface::get_nlp_info(), casadi::Nlpsol::get_reverse(), casadi::BonminInterface::get_starting_point(), casadi::BonminUserClass::get_starting_point(), casadi::IpoptUserClass::get_starting_point(), casadi::IpoptInterface::get_starting_point(), casadi::Nlpsol::init(), casadi::AlpaqaInterface::init(), casadi::AmplInterface::init(), init(), casadi::BonminInterface::init(), casadi::MadmpecInterface::init(), casadi::FatropInterface::init(), casadi::IpoptInterface::init(), casadi::KnitroInterface::init(), casadi::SLEQPInterface::init(), casadi::SnoptInterface::init(), casadi::WorhpInterface::init(), casadi::Feasiblesqpmethod::init(), casadi::Qrsqp::init(), casadi::Scpgen::init(), casadi::Sqpmethod::init(), casadi::IpoptInterface::init_mem(), casadi::SnoptInterface::init_mem(), casadi::BonminInterface::intermediate_callback(), casadi::IpoptInterface::intermediate_callback(), casadi::IpoptUserClass::IpoptUserClass(), kktErrorReduction(), casadi::Scpgen::line_search(), lInfConstraintNorm(), casadi::Nlpsol::Nlpsol(), casadi::Scpgen::primalInfeasibility(), printProgress(), reduceSOCStepsize(), casadi::Scpgen::regularize(), reset_sqp(), resetHessian(), secondOrderCorrection(), casadi::Nlpsol::serialize_body(), set_work(), casadi::BonminInterface::set_work(), casadi::IpoptInterface::set_work(), casadi::KnitroInterface::set_work(), casadi::SLEQPInterface::set_work(), casadi::SnoptInterface::set_work(), casadi::WorhpInterface::set_work(), casadi::Qrsqp::set_work(), casadi::Scpgen::set_work(), casadi::AlpaqaInterface::solve(), casadi::AmplInterface::solve(), solve(), casadi::BonminInterface::solve(), casadi::IpoptInterface::solve(), casadi::KnitroInterface::solve(), casadi::SLEQPInterface::solve(), casadi::SnoptInterface::solve(), casadi::WorhpInterface::solve(), casadi::Feasiblesqpmethod::solve(), casadi::Qrsqp::solve(), casadi::Scpgen::solve(), casadi::Sqpmethod::solve(), casadi::Sqpmethod::solve_ela_QP(), casadi::Sqpmethod::solve_elastic_mode(), casadi::Feasiblesqpmethod::solve_LP(), casadi::Feasiblesqpmethod::solve_QP(), casadi::Qrsqp::solve_QP(), casadi::Scpgen::solve_qp(), casadi::Sqpmethod::solve_QP(), solveQP(), casadi::Feasiblesqpmethod::step_update(), casadi::Feasiblesqpmethod::tr_update(), updateDeltaGamma(), updateStepBounds(), and casadi::SnoptInterface::userfun().

◆ obj_lo_

double casadi::Blocksqp::obj_lo_

Definition at line 393 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), initializeFilter(), and serialize_body().

◆ obj_up_

double casadi::Blocksqp::obj_up_

◆ options_

const Options casadi::Blocksqp::options_
static

Definition at line 169 of file blocksqp.hpp.

Referenced by casadi::casadi_register_nlpsol_blocksqp().

◆ opttol_

double casadi::Blocksqp::opttol_

Definition at line 342 of file blocksqp.hpp.

Referenced by Blocksqp(), calcOptTol(), feasibilityRestorationPhase(), init(), and serialize_body().

◆ oracle_

Function casadi::OracleFunction::oracle_
protectedinherited

◆ p_nlp_

casadi_nlpsol_prob<double> casadi::Nlpsol::p_nlp_
inherited

◆ post_expand_

bool casadi::OracleFunction::post_expand_
protectedinherited

◆ print_canonical_

bool casadi::FunctionInternal::print_canonical_
inherited

◆ print_header_

bool casadi::Blocksqp::print_header_

Definition at line 339 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and solve().

◆ print_in_

bool casadi::FunctionInternal::print_in_
inherited

◆ print_iteration_

bool casadi::Blocksqp::print_iteration_

Definition at line 340 of file blocksqp.hpp.

Referenced by Blocksqp(), feasibilityRestorationPhase(), init(), run(), and serialize_body().

◆ print_maxit_reached_

bool casadi::Blocksqp::print_maxit_reached_

Definition at line 400 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and solve().

◆ print_out_

bool casadi::FunctionInternal::print_out_
inherited

◆ print_time_

bool casadi::ProtoFunction::print_time_
inherited

◆ qp_init_

bool casadi::Blocksqp::qp_init_

Definition at line 355 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), and solve().

◆ record_time_

bool casadi::ProtoFunction::record_time_
inherited

◆ registered_functions_

std::vector<Function> casadi::FunctionInternal::registered_functions_
inherited

◆ regularity_check_

bool casadi::ProtoFunction::regularity_check_
inherited

◆ release_

casadi_release_t casadi::FunctionInternal::release_
inherited

◆ restore_feas_

bool casadi::Blocksqp::restore_feas_

Definition at line 348 of file blocksqp.hpp.

Referenced by Blocksqp(), feasibilityRestorationPhase(), init(), run(), and serialize_body().

◆ reverse_options_

Dict casadi::FunctionInternal::reverse_options_
inherited

◆ rho_

double casadi::Blocksqp::rho_

Definition at line 397 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().

◆ rp_solver_

Function casadi::Blocksqp::rp_solver_

Definition at line 399 of file blocksqp.hpp.

Referenced by Blocksqp(), feasibilityRestorationPhase(), init(), and serialize_body().

◆ s_f_

double casadi::Blocksqp::s_f_

Definition at line 387 of file blocksqp.hpp.

Referenced by Blocksqp(), filterLineSearch(), init(), and serialize_body().

◆ s_theta_

double casadi::Blocksqp::s_theta_

Definition at line 386 of file blocksqp.hpp.

Referenced by Blocksqp(), filterLineSearch(), init(), and serialize_body().

◆ schur_

bool casadi::Blocksqp::schur_

Definition at line 346 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), init_mem(), printInfo(), serialize_body(), solve(), and solveQP().

◆ sens_linsol_

std::string casadi::Nlpsol::sens_linsol_
inherited

◆ sens_linsol_options_

Dict casadi::Nlpsol::sens_linsol_options_
inherited

◆ show_eval_warnings_

bool casadi::OracleFunction::show_eval_warnings_
protectedinherited

◆ skip_first_globalization_

bool casadi::Blocksqp::skip_first_globalization_

Definition at line 372 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), run(), and serialize_body().

◆ solvers_

std::map< std::string, Nlpsol::Plugin > casadi::Nlpsol::solvers_
staticinherited

Definition at line 302 of file nlpsol_impl.hpp.

◆ sparsity_in_

std::vector<Sparsity> casadi::FunctionInternal::sparsity_in_
inherited

◆ sparsity_out_

std::vector<Sparsity> casadi::FunctionInternal::sparsity_out_
inherited

◆ specific_options_

Dict casadi::OracleFunction::specific_options_
protectedinherited

◆ stats_

Dict casadi::FunctionInternal::stats_
inherited

◆ stride_arg_

size_t casadi::OracleFunction::stride_arg_
protectedinherited

◆ stride_iw_

size_t casadi::OracleFunction::stride_iw_
protectedinherited

◆ stride_res_

size_t casadi::OracleFunction::stride_res_
protectedinherited

◆ stride_w_

size_t casadi::OracleFunction::stride_w_
protectedinherited

◆ theta_max_

double casadi::Blocksqp::theta_max_

Definition at line 383 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), initializeFilter(), initIterate(), and serialize_body().

◆ theta_min_

double casadi::Blocksqp::theta_min_

Definition at line 384 of file blocksqp.hpp.

Referenced by Blocksqp(), filterLineSearch(), init(), secondOrderCorrection(), and serialize_body().

◆ user_data_

void* casadi::FunctionInternal::user_data_
inherited

◆ verbose_

bool casadi::ProtoFunction::verbose_
inherited

Definition at line 249 of file function_internal.hpp.

Referenced by casadi::MXFunction::ad_forward(), casadi::SXFunction::ad_forward(), casadi::MXFunction::ad_reverse(), casadi::SXFunction::ad_reverse(), casadi::Integrator::advance(), casadi::ProtoFunction::change_option(), casadi::BSplineInterpolant::construct_graph(), casadi::OracleFunction::create_function(), casadi::Integrator::eval(), casadi::MXFunction::eval(), casadi::SXFunction::eval(), casadi::MXFunction::eval_mx(), casadi::SXFunction::eval_mx(), casadi::SXFunction::eval_sx(), casadi::FmuFunction::factory(), casadi::FunctionInternal::finalize(), casadi::KinsolInterface::func(), casadi::CodeGenerator::generate_dump(), casadi::ProtoFunction::generate_options(), casadi::FmuFunction::get_forward(), casadi::Integrator::get_forward(), casadi::Integrator::get_forward_dae(), casadi::FunctionInternal::get_jac_sparsity_gen(), casadi::FunctionInternal::get_jac_sparsity_hierarchical(), casadi::FunctionInternal::get_jac_sparsity_hierarchical_symm(), casadi::FmuFunction::get_jacobian(), casadi::FunctionInternal::get_partition(), casadi::FmuFunction::get_reverse(), casadi::Integrator::get_reverse(), casadi::ProtoFunction::init(), casadi::FiniteDiff::init(), casadi::FmuFunction::init(), casadi::FunctionInternal::init(), casadi::MXFunction::init(), casadi::SXFunction::init(), init(), casadi::MadmpecInterface::init(), casadi::FatropConicInterface::init(), casadi::FatropInterface::init(), casadi::HpipmInterface::init(), casadi::HpmpcInterface::init(), casadi::IpoptInterface::init(), casadi::MadnlpInterface::init(), casadi::CvodesInterface::init(), casadi::IdasInterface::init(), casadi::Feasiblesqpmethod::init(), casadi::Scpgen::init(), casadi::Sqpmethod::init(), casadi::IpoptInterface::init_mem(), casadi::MosekInterface::init_mem(), casadi::IdasInterface::init_mem(), casadi::UnoInterface::init_mem(), casadi::SXFunction::instructions_sx(), casadi::BonminInterface::intermediate_callback(), casadi::OracleFunction::jit_dependencies(), casadi::CsparseInterface::nfact(), casadi::LapackLu::nfact(), casadi::LapackQr::nfact(), casadi::LinsolQr::nfact(), casadi::Integrator::predict_events(), casadi::ProtoFunction::ProtoFunction(), casadi::CvodesInterface::reset(), casadi::IdasInterface::reset(), casadi::IdasInterface::resetB(), casadi::ProtoFunction::serialize_body(), casadi::CbcInterface::solve(), casadi::ClpInterface::solve(), casadi::CplexInterface::solve(), casadi::GurobiInterface::solve(), casadi::HpipmInterface::solve(), casadi::QpoasesInterface::solve(), casadi::Ipqp::solve(), casadi::Qrqp::solve(), casadi::AlpaqaInterface::solve(), casadi::AmplInterface::solve(), casadi::SnoptInterface::solve(), casadi::KinsolInterface::solve(), casadi::WorhpInterface::solve(), casadi::Newton::solve(), casadi::Qrsqp::solve(), casadi::Scpgen::solve(), casadi::Sqpmethod::solve(), casadi::Sqpmethod::solve_ela_QP(), casadi::Feasiblesqpmethod::solve_LP(), casadi::Feasiblesqpmethod::solve_QP(), casadi::Qrsqp::solve_QP(), casadi::Sqpmethod::solve_QP(), casadi::Integrator::sp_forward(), casadi::Integrator::sp_reverse(), and casadi::Integrator::trigger_event().

◆ warmstart_

bool casadi::Blocksqp::warmstart_

Definition at line 354 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), serialize_body(), solve(), and solveQP().

◆ warn_initial_bounds_

bool casadi::Nlpsol::warn_initial_bounds_
inherited

◆ which_second_derv_

casadi_int casadi::Blocksqp::which_second_derv_

◆ zeta_

double casadi::Blocksqp::zeta_

Definition at line 398 of file blocksqp.hpp.

Referenced by Blocksqp(), init(), and serialize_body().


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