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

Opti with debugging and low-level access. More...

#include <optistack.hpp>

Detailed Description

Obtained through Opti::debug or Opti::advanced; it is a deep copy of the Opti instance with the methods below added. No API stability is guaranteed for these methods. Most of them bake the problem (flatten variables and constraints) on the fly, so they also work on a copy that has not been solved.

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

Definition at line 2786 of file optistack.hpp.

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

Public Types

using internal_base_type = SharedObjectInternal
 
using base_type = SharedObject
 

Public Member Functions

 OptiAdvanced (const Opti &x)
 
 ~OptiAdvanced ()
 Destructor. More...
 
Function casadi_solver () const
 Get the underlying nlpsol/qpsol Function. More...
 
bool is_parametric (const MX &expr) const
 Check whether an expression depends on parameters only. More...
 
MetaCon canon_expr (const MX &expr) const
 Classify a constraint expression (for internal use only) More...
 
MetaVar get_meta (const MX &m) const
 Get meta-data of symbol (for internal use only) More...
 
MetaCon get_meta_con (const MX &m) const
 Get meta-data of symbol (for internal use only) More...
 
void set_meta (const MX &m, const MetaVar &meta)
 Set meta-data of an expression. More...
 
void set_meta_con (const MX &m, const MetaCon &meta)
 Set meta-data of an expression. More...
 
void assert_active_symbol (const MX &m) const
 Raise an error unless m is a symbol of this instance that appears in the problem. More...
 
std::vector< MX > active_symvar (VariableType type) const
 Get the symbols of a given type that appear in the problem. More...
 
std::vector< DM > active_values (VariableType type) const
 Initial guesses (or parameter values) of the symbols returned by active_symvar. More...
 
MX x_lookup (casadi_index i) const
 Get the variable that owns entry i of the flattened x vector. More...
 
MX g_lookup (casadi_index i) const
 Get the constraint expression that owns row i of g. More...
 
casadi_index g_index_reduce_g (casadi_index i) const
 Row of the reduced g for row i of g when "detect_simple_bounds" is active (-1 if moved) More...
 
casadi_index g_index_reduce_x (casadi_index i) const
 Index into x when row i of g was reduced to a simple bound (-1 otherwise) More...
 
casadi_index g_index_unreduce_g (casadi_index i) const
 Row of g for row i of the reduced g. More...
 
std::string x_describe (casadi_index i, const Dict &opts=Dict()) const
 Describe entry i of the flattened x vector. More...
 
std::string g_describe (casadi_index i, const Dict &opts=Dict()) const
 Describe row i of the constraint vector g. More...
 
std::string describe (const MX &x, casadi_index indent=0, const Dict &opts=Dict()) const
 Describe an expression in terms of this instance. More...
 
void show_infeasibilities (double tol=0, const Dict &opts=Dict()) const
 Print the constraints violated at the latest iterate. More...
 
void solve_prepare ()
 Prepare the solver arguments (first half of solve) More...
 
DMDict solve_actual (const DMDict &args)
 Run the solver on an argument dict (see solve_prepare) More...
 
DMDict arg () const
 Solver arguments prepared by solve_prepare (x0, p, lam_g0, lbg, ubg) More...
 
void res (const DMDict &res)
 Store a solver result dict as the latest values (marks the instance solved) More...
 
DMDict res () const
 Result dict of the latest solve (x, f, g, lam_x, lam_g, lam_p) More...
 
std::vector< MX > constraints () const
 Get the constraint expressions as passed to subject_to. More...
 
MX objective () const
 Objective expression; same as f() More...
 
OptiAdvanced baked_copy () const
 Copy of the instance with the problem baked (see bake) More...
 
void assert_empty () const
 Raise an error if an objective or constraints are present. More...
 
void bake ()
 Fix the structure of the optimization problem. More...
 
void mark_problem_dirty (bool flag=true)
 Flag that the problem structure changed since the last bake. More...
 
bool problem_dirty () const
 True when the problem must be baked again before solving. More...
 
void mark_solver_dirty (bool flag=true)
 Flag that the solver must be reconstructed (solver() was called) More...
 
bool solver_dirty () const
 True when the solver must be reconstructed. More...
 
void mark_solved (bool flag=true)
 Set or clear the solved state. More...
 
bool solved () const
 True when a solver result is available for value() More...
 
void assert_solved () const
 Raise an error unless solved() More...
 
void assert_baked () const
 Raise an error when the problem is dirty. More...
 
casadi_int instance_number () const
 Sequence number of this Opti instance in the process; prefixes the symbol names. More...
 
MX variable (casadi_int n=1, casadi_int m=1, const std::string &attribute="full")
 Create a decision variable (symbol) More...
 
MX variable (const Sparsity &sp, const std::string &attribute="full")
 Create a decision variable with a given sparsity pattern; only "full" is supported. More...
 
MX variable (const MX &symbol, const std::string &attribute="full")
 Register an existing MX symbol as a decision variable of this instance. More...
 
MX parameter (casadi_int n=1, casadi_int m=1, const std::string &attribute="full")
 Create a parameter (symbol); fixed during optimization. More...
 
MX parameter (const Sparsity &sp, const std::string &attribute="full")
 Create a parameter with a given sparsity pattern. More...
 
MX parameter (const MX &symbol, const std::string &attribute="full")
 Register an existing MX symbol as a parameter of this instance. More...
 
void minimize (const MX &f, double linear_scale=1)
 Set the objective. More...
 
void subject_to ()
 Clear all constraints. More...
 
void solver (const std::string &solver, const Dict &plugin_options=Dict(), const Dict &solver_options=Dict())
 Select the numerical solver and its options. More...
 
void set_domain (const MX &x, const std::string &domain)
 Set the domain of a decision variable. More...
 
void set_linear_scale (const MX &x, const DM &scale, const DM &offset=0)
 Set the linear scaling of a decision variable. More...
 
OptiSol solve ()
 Solve the problem. More...
 
OptiSol solve_limited ()
 Solve the problem, accepting a limit as outcome. More...
 
Dict stats () const
 Get the statistics of the last solve. More...
 
std::string return_status () const
 Get the return status of the last solve. More...
 
std::vector< MX > initial () const
 Get assignment expressions for the initial guesses. More...
 
std::vector< MX > value_variables () const
 Get assignment expressions for the latest values. More...
 
std::vector< MX > value_parameters () const
 
Function scale_helper (const Function &h) const
 Scale a helper function constructed via opti.x, opti.g, ... More...
 
MX dual (const MX &m) const
 Get the dual variable (Lagrange multiplier) of a constraint. More...
 
casadi_int nx () const
 Number of (scalarised) decision variables. More...
 
casadi_int np () const
 Number of (scalarised) parameters. More...
 
casadi_int ng () const
 Number of (scalarised) constraints. More...
 
MX x () const
 Get all (scalarised) decision variables as a symbolic column vector. More...
 
MX p () const
 Get all (scalarised) parameters as a symbolic column vector. More...
 
MX g () const
 Get all (scalarised) constraint expressions as a column vector. More...
 
MX f () const
 Get the objective expression. More...
 
MX lbg () const
 Get all (scalarised) bounds on constraints as a column vector. More...
 
MX ubg () const
 
DM x_linear_scale () const
 Per-entry scale of x (see set_linear_scale); a Python property. More...
 
DM x_linear_scale_offset () const
 Per-entry offset of x (see set_linear_scale); a Python property. More...
 
DM g_linear_scale () const
 Per-row scale of g (see subject_to); a Python property. More...
 
double f_linear_scale () const
 Scale of the objective (see minimize); a Python property. More...
 
MX lam_g () const
 Get all (scalarised) dual variables as a symbolic column vector. More...
 
OptiAdvanced debug () const
 Get a copy with advanced (debugging) functionality. More...
 
OptiAdvanced advanced () const
 Get a copy with advanced functionality. More...
 
Opti copy () const
 Get a deep copy of the Opti instance. More...
 
void update_user_dict (const MX &m, const Dict &meta)
 Add user data to a symbol or constraint. More...
 
void update_user_dict (const std::vector< MX > &m, const Dict &meta)
 
Dict user_dict (const MX &m) const
 Get the user data of a symbol or constraint. More...
 
std::string type_name () const
 Readable name of the class. More...
 
void disp (std::ostream &stream, bool more=false) const
 Print a summary of the instance. More...
 
std::string get_str (bool more=false) const
 Get string representation. More...
 
std::string class_name () const
 Get class name. More...
 
void print_ptr (std::ostream &stream=casadi::uout()) const
 
void own (SharedObjectInternal *node)
 
void assign (SharedObjectInternal *node)
 Assign the node to a node class pointer without reference counting. More...
 
SharedObjectInternal * get () const
 Get a const pointer to the node. More...
 
casadi_int getCount () const
 Get the reference count. More...
 
void swap (GenericShared &other)
 Swap content with another instance. More...
 
std::string debug_repr () const
 
bool is_null () const
 Is a null pointer? More...
 
casadi_int __hash__ () const
 Returns a number that is unique for a given Node. More...
 
GenericWeakRef< SharedObject, SharedObjectInternal > * weak ()
 Get a weak reference to the object. More...
 
std::vector< MX > symvar () const
 Get the symbols of this instance. More...
 
std::vector< MX > symvar (const MX &expr) const
 Get the symbols of this instance. More...
 
std::vector< MX > symvar (const MX &expr, VariableType type) const
 Get the symbols of this instance. More...
 
void subject_to (const MX &g, const Dict &options=Dict())
 Add constraints. More...
 
void subject_to (const std::vector< MX > &g, const Dict &options=Dict())
 Add constraints. More...
 
void subject_to (const MX &g, const DM &linear_scale, const Dict &options=Dict())
 Add constraints. More...
 
void subject_to (const std::vector< MX > &g, const DM &linear_scale, const Dict &options=Dict())
 Add constraints. More...
 
void set_initial (const MX &x, const DM &v)
 Set the initial guess of decision variables or dual variables. More...
 
void set_initial (const std::vector< MX > &assignments)
 Set the initial guess of decision variables or dual variables. More...
 
void set_value (const MX &x, const DM &v)
 Set the value of a parameter. More...
 
void set_value (const std::vector< MX > &assignments)
 Set the value of a parameter. More...
 
native_DM value (const MX &x, const std::vector< MX > &values=std::vector< MX >()) const
 Evaluate an expression at the current values. More...
 
native_DM value (const DM &x, const std::vector< MX > &values=std::vector< MX >()) const
 Evaluate an expression at the current values. More...
 
native_DM value (const SX &x, const std::vector< MX > &values=std::vector< MX >()) const
 Evaluate an expression at the current values. More...
 
Function to_function (const std::string &name, const std::vector< MX > &args, const std::vector< MX > &res, const Dict &opts=Dict())
 Create a CasADi Function from the Opti solver. More...
 
Function to_function (const std::string &name, const std::vector< MX > &args, const std::vector< MX > &res, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Create a CasADi Function from the Opti solver. More...
 
Function to_function (const std::string &name, const std::map< std::string, MX > &dict, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Same, with inputs and outputs picked by name from a dict of expressions. More...
 
void callback_class (OptiCallback *callback)
 Helper methods for callback() More...
 
void callback_class ()
 Helper methods for callback() More...
 
OptiNode * operator-> ()
 Access a member of the node. More...
 
const OptiNode * operator-> () const
 Const access a member of the node. More...
 

Static Public Member Functions

static MX bounded (const MX &lb, const MX &expr, const MX &ub)
 Construct a double inequality. More...
 
static Opti create (OptiNode *node)
 

Public Attributes

bool problem_dirty_
 
bool solver_dirty_
 
bool solved_
 

Protected Member Functions

 OptiAdvanced ()
 
void count_up ()
 
void count_down ()
 

Friends

class InternalOptiCallback
 

Member Typedef Documentation

◆ base_type

Definition at line 103 of file shared_object.hpp.

◆ internal_base_type

Definition at line 102 of file shared_object.hpp.

Constructor & Destructor Documentation

◆ OptiAdvanced() [1/2]

casadi::OptiAdvanced::OptiAdvanced ( const Opti &  x)

Definition at line 83 of file optistack.cpp.

83  : Opti(rhs) {
84 }
Opti(const std::string &problem_type="nlp")
Create an empty Opti context.
Definition: optistack.cpp:47

◆ ~OptiAdvanced()

casadi::OptiAdvanced::~OptiAdvanced ( )
inline

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

Definition at line 2795 of file optistack.hpp.

2795 {}

◆ OptiAdvanced() [2/2]

casadi::OptiAdvanced::OptiAdvanced ( )
inlineprotected

Definition at line 3503 of file optistack.hpp.

3503 {}

Member Function Documentation

◆ __hash__()

casadi_int casadi::GenericShared< SharedObject , SharedObjectInternal >::__hash__
inherited

If the Object does not point to any node, "0" is returned.

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

Definition at line 123 of file generic_shared_impl.hpp.

148  {
149  return reinterpret_cast<casadi_int>(get());
150  }

◆ active_symvar()

std::vector< MX > casadi::OptiAdvanced::active_symvar ( VariableType  type) const

Empty before the problem has been baked (solve, or any method that bakes).

>>> opti = Opti()
>>> x = opti.variable()
>>> y = opti.variable()
>>> opti.minimize(x**2)
>>> d = opti.debug
>>> d.active_symvar(OPTI_VAR)
[]
>>> d.bake()
>>> print(d.active_symvar(OPTI_VAR), d.active_values(OPTI_VAR))
[MX(opti..._x_1)] [DM(0)]

>> opti = Opti(); x = opti.variable(); y = opti.variable(); opti.minimize(x^2);
>> d = opti.debug; disp(isempty(d.active_symvar(OPTI_VAR)))
1
>> d.bake(); a = d.active_symvar(OPTI_VAR); v = d.active_values(OPTI_VAR);
>> a{1}, v{1}
opti..._x_1
0

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> y = ca.variable(opti);
julia> ca.minimize(opti, x^2)
julia> d = ca.debug(opti);
julia> ca.active_symvar(d, ca.OPTI_VAR)
MX[]
julia> ca.bake(d)
julia> print(ca.active_symvar(d, ca.OPTI_VAR), " ", ca.active_values(d, ca.OPTI_VAR))
MX[opti..._x_1] DM[0]

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

Definition at line 593 of file optistack.cpp.

593  {
594  try {
595  return (*this)->active_symvar(type);
596  } catch(std::exception& e) {
597  THROW_ERROR("active_symvar", e.what());
598  }
599 }

Referenced by casadi::Opti::disp().

◆ active_values()

std::vector< DM > casadi::OptiAdvanced::active_values ( VariableType  type) const

Definition at line 601 of file optistack.cpp.

601  {
602  try {
603  return (*this)->active_values(type);
604  } catch(std::exception& e) {
605  THROW_ERROR("active_values", e.what());
606  }
607 }

◆ advanced()

OptiAdvanced casadi::Opti::advanced ( ) const
inherited

Same as debug(); the name signals use of the unstable OptiAdvanced API rather than debugging. In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize(x**2)
>>> print(opti.advanced.symvar())
[MX(opti..._x_1)]

>> opti = Opti(); x = opti.variable(); opti.minimize(x^2);
>> sv = opti.advanced.symvar(); disp(numel(sv)), disp(sv{1})
1
opti..._x_1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, x^2)
julia> print(ca.symvar(ca.advanced(opti)))
MX[opti..._x_1]

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

Definition at line 854 of file optistack.cpp.

854  {
855  return copy();
856 }
Opti copy() const
Get a deep copy of the Opti instance.
Definition: optistack.cpp:857

References casadi::Opti::copy().

◆ arg()

DMDict casadi::OptiAdvanced::arg ( ) const

Definition at line 694 of file optistack.cpp.

694  {
695  try {
696  return (*this)->arg();
697  } catch(std::exception& e) {
698  THROW_ERROR("arg", e.what());
699  }
700 }

◆ assert_active_symbol()

void casadi::OptiAdvanced::assert_active_symbol ( const MX &  m) const

Definition at line 585 of file optistack.cpp.

585  {
586  try {
587  (*this)->assert_active_symbol(m);
588  } catch(std::exception& e) {
589  THROW_ERROR("assert_active_symbol", e.what());
590  }
591 }

◆ assert_baked()

void casadi::OptiAdvanced::assert_baked ( ) const

Definition at line 843 of file optistack.cpp.

843  {
844  try {
845  (*this)->assert_baked();
846  } catch(std::exception& e) {
847  THROW_ERROR("assert_baked", e.what());
848  }
849 }

◆ assert_empty()

void casadi::OptiAdvanced::assert_empty ( ) const

Definition at line 738 of file optistack.cpp.

738  {
739  try {
740  (*this)->assert_empty();
741  } catch(std::exception& e) {
742  THROW_ERROR("assert_empty", e.what());
743  }
744 }

◆ assert_solved()

void casadi::OptiAdvanced::assert_solved ( ) const

Definition at line 836 of file optistack.cpp.

836  {
837  try {
838  (*this)->assert_solved();
839  } catch(std::exception& e) {
840  THROW_ERROR("assert_solved", e.what());
841  }
842 }

◆ assign()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::assign ( Internal *  node)
inherited

improper use will cause memory leaks!

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

Definition at line 96 of file generic_shared_impl.hpp.

86  {
87  node = node_;
88  }

◆ bake()

void casadi::OptiAdvanced::bake ( )

Flattens the active variables, parameters and constraints into the x, p, g, lbg and ubg vectors and builds the bounds function. Called automatically by solve() and the accessors; raises an error when neither an objective nor a constraint is set.

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

Definition at line 782 of file optistack.cpp.

782  {
783  try {
784  (*this)->bake();
785  } catch(std::exception& e) {
786  THROW_ERROR("bake", e.what());
787  }
788 }

Referenced by casadi::OptiNode::baked_copy(), and casadi::Opti::disp().

◆ baked_copy()

OptiAdvanced casadi::OptiAdvanced::baked_copy ( ) const

Definition at line 730 of file optistack.cpp.

730  {
731  try {
732  return (*this)->baked_copy();
733  } catch(std::exception& e) {
734  THROW_ERROR("baked_copy", e.what());
735  }
736 }

References casadi::OptiNode::baked_copy().

◆ bounded()

static MX casadi::Opti::bounded ( const MX &  lb,
const MX &  expr,
const MX &  ub 
)
inlinestaticinherited

Returns the expression (lb <= expr) <= ub, which subject_to() recognizes as a double-bounded constraint lb <= expr <= ub when lb and ub are free of decision variables. Identical to writing lb <= (expr <= ub) by hand; provided because Python's chained comparison lb <= expr <= ub raises an error for MX. A static method; the instance is not needed.

>>> opti = Opti()
>>> x = opti.variable(2)
>>> opti.subject_to(opti.bounded(-1, x, 1))
>>> opti.subject_to(Opti.bounded(0, x[0] + x[1], 1))
>>> opti.ng, opti.lbg, opti.ubg
(3, MX(vertcat(all_-1(2x1), 0)), MX(ones(3x1)))

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> ca.subject_to(opti, ca.bounded(-1, x, 1))
julia> ca.subject_to(opti, ca.Opti.bounded(0, x[1] + x[2], 1))
julia> ca.ng(opti), ca.lbg(opti), ca.ubg(opti)
(3, vertcat(all_-1(2x1), 0), ones(3x1))

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

Definition at line 2353 of file optistack.hpp.

2353 { return (lb<=expr)<= ub; }

◆ callback_class() [1/2]

void casadi::Opti::callback_class ( )
inherited

Do not use directly; use opti.callback(fh) in Python/MATLAB, which wraps a callable in an OptiCallback and registers it here. The no-argument form removes the callback.

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

Definition at line 475 of file optistack.cpp.

475  {
476  try {
477  (*this)->callback_class();
478  } catch(std::exception& e) {
479  THROW_ERROR("callback_class", e.what());
480  }
481 }

Referenced by casadi::Opti::Opti().

◆ callback_class() [2/2]

void casadi::Opti::callback_class ( OptiCallback *  callback)
inherited

Do not use directly; use opti.callback(fh) in Python/MATLAB, which wraps a callable in an OptiCallback and registers it here. The no-argument form removes the callback.

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

Definition at line 467 of file optistack.cpp.

467  {
468  try {
469  (*this)->callback_class(callback);
470  } catch(std::exception& e) {
471  THROW_ERROR("callback_class", e.what());
472  }
473 }

◆ canon_expr()

MetaCon casadi::OptiAdvanced::canon_expr ( const MX &  expr) const

Returns the MetaCon that subject_to() would store: the constraint type, canonical expression and bounds.

>>> opti = Opti()
>>> x = opti.variable()
>>> c = opti.debug.canon_expr(0 <= (x <= 1))
>>> print(c.type == OPTI_DOUBLE_INEQUALITY, c.lb, c.ub, c.canon)
True 0 1 opti..._x_1
>>> opti.debug.canon_expr(x + 1).type == OPTI_UNKNOWN
True

>> opti = Opti(); x = opti.variable();
>> c = opti.debug.canon_expr(0 <= x <= 1);
>> c.type == OPTI_DOUBLE_INEQUALITY, c.lb, c.ub, c.canon
1
0
1
opti..._x_1
>> c = opti.debug.canon_expr(x + 1); disp(c.type == OPTI_UNKNOWN)
1

julia> opti = ca.Opti();
julia> x = opti.variable();
julia> c = ca.canon_expr(opti.debug, 0 <= (x <= 1));
julia> println(c.type == ca.OPTI_DOUBLE_INEQUALITY, " ", c.lb, " ", c.ub, " ", c.canon)
true 0 1 opti..._x_1
julia> ca.canon_expr(opti.debug, x + 1).type == ca.OPTI_UNKNOWN
true

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

Definition at line 544 of file optistack.cpp.

544  {
545  try {
546  return (*this)->canon_expr(expr);
547  } catch(std::exception& e) {
548  THROW_ERROR("canon_expr", e.what());
549  }
550 }

◆ casadi_solver()

Function casadi::OptiAdvanced::casadi_solver ( ) const

The solver Function constructed at the last solve() (null before that). Its inputs follow the nlpsol convention (x0, p, lbx, ubx, lbg, ubg, lam_x0, lam_g0), and its get_function() gives access to the derivative functions. In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable(2)
>>> opti.minimize(sumsqr(x))
>>> opti.subject_to(x[0] >= 1)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> S = opti.debug.casadi_solver
>>> S.name(), S.class_name(), S.name_in()
('solver', 'IpoptInterface', ['x0', 'p', 'lbx', 'ubx', 'lbg', 'ubg', 'lam_x0', 'lam_g0'])

>> opti = Opti(); x = opti.variable(2);
>> opti.minimize(sumsqr(x)); opti.subject_to(x(1) >= 1);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); S = opti.debug.casadi_solver();
>> S.name(), S.class_name(), strjoin(cellstr(S.name_in()), ' ')
solver
IpoptInterface
x0 p lbx ubx lbg ubg lam_x0 lam_g0

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> ca.minimize(opti, ca.sumsqr(x))
julia> ca.subject_to(opti, x[1] >= 1)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> S = opti.debug.casadi_solver;
julia> ca.name(S), ca.class_name(S)
("solver", "IpoptInterface")
julia> print(ca.name_in(S))
["x0", "p", "lbx", "ubx", "lbg", "ubg", "lam_x0", "lam_g0"]

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

Definition at line 504 of file optistack.cpp.

504  {
505  try {
506  return (*this)->casadi_solver();
507  } catch(std::exception& e) {
508  THROW_ERROR("casadi_solver", e.what());
509  }
510 }

◆ class_name()

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

◆ constraints()

std::vector< MX > casadi::OptiAdvanced::constraints ( ) const

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.subject_to(x >= 0)
>>> opti.subject_to(1 <= (x**2 <= 4))
>>> print(opti.debug.constraints())
[MX((0<=opti..._x_1)), MX((1<=(sq(opti..._x_1)<=4)))]

>> opti = Opti(); x = opti.variable();
>> opti.subject_to(x >= 0); opti.subject_to(1 <= x^2 <= 4);
>> c = opti.debug.constraints(); disp(c{1}), disp(c{2})
(0<=opti..._x_1)
((1<=sq(opti..._x_1))<=4)

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.subject_to(opti, x >= 0)
julia> ca.subject_to(opti, 1 <= (x^2 <= 4))
julia> print(ca.constraints(ca.debug(opti)))
MX[(0<=opti..._x_1), (1<=(sq(opti..._x_1)<=4))]

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

Definition at line 719 of file optistack.cpp.

719  {
720  try {
721  return (*this)->constraints();
722  } catch(std::exception& e) {
723  THROW_ERROR("constraints", e.what());
724  }
725 }

◆ copy()

Opti casadi::Opti::copy ( ) const
inherited

The copy shares the symbols (so expressions in them stay valid for both) but has its own constraints, values, initial guesses and solver state. Updating the copy does not update the original.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize(x**2)
>>> opti2 = opti.copy()
>>> opti2.subject_to(x >= 2)
>>> opti.ng, opti2.ng
(0, 1)

>> opti = Opti(); x = opti.variable(); opti.minimize(x^2);
>> opti2 = opti.copy(); opti2.subject_to(x >= 2); fprintf('%d %d\n', opti.ng, opti2.ng)
0 1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, x^2)
julia> opti2 = opti.copy();
julia> ca.subject_to(opti2, x >= 2)
julia> ca.ng(opti), ca.ng(opti2)
(0, 1)

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

Definition at line 857 of file optistack.cpp.

857  {
858  return (*this)->copy();
859 }

References casadi::OptiNode::copy().

Referenced by casadi::Opti::advanced(), and casadi::Opti::debug().

◆ count_down()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::count_down
protectedinherited

Definition at line 133 of file generic_shared_impl.hpp.

46  {
47 #ifdef WITH_EXTRA_CHECKS
48  casadi_assert_dev(Function::call_depth_==0);
49 #endif // WITH_EXTRA_CHECKS
50  if (!node) return;
51 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
52  GenericWeakRef<Shared, Internal>* weak_ref =
53  node->weak_ref_.load(std::memory_order_acquire);
54 #else
55  GenericWeakRef<Shared, Internal>* weak_ref = node->weak_ref_;
56 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
57  if (weak_ref) {
58 #ifdef CASADI_WITH_THREADSAFE_SYMBOLICS
59  // get_mutex() returns a shared_ptr copy, so the mutex outlives this lock
60  // even if delete node (below) destroys the WeakRefInternal holding it
61  auto mutex = weak_ref->get_mutex();
62  // Avoid triggering a delete while a weak_ref.shared_if_alive is being called
63  std::lock_guard<std::mutex> lock(*mutex);
64 #endif // CASADI_WITH_THREADSAFE_SYMBOLICS
65 
66  if (--static_cast<Internal*>(node)->count == 0) {
67  delete node;
68  node = nullptr;
69  }
70  } else {
71  if (--static_cast<Internal*>(node)->count == 0) {
72  delete node;
73  node = nullptr;
74  }
75  }
76  }

◆ count_up()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::count_up
protectedinherited

Definition at line 132 of file generic_shared_impl.hpp.

36  {
37 #ifdef WITH_EXTRA_CHECKS
38  casadi_assert_dev(Function::call_depth_==0);
39 #endif // WITH_EXTRA_CHECKS
40 
41  if (node) static_cast<Internal*>(node)->count++;
42 
43  }

◆ create()

Opti casadi::Opti::create ( OptiNode *  node)
staticinherited

Definition at line 86 of file optistack.cpp.

86  {
87  return Opti(node);
88 }

References casadi::Opti::Opti().

Referenced by casadi::OptiNode::copy().

◆ debug()

OptiAdvanced casadi::Opti::debug ( ) const
inherited

Returns an OptiAdvanced deep copy of the current state: same symbols, constraints, values and latest solver result, with extra methods such as value() at a non-converged iterate, show_infeasibilities(), x_describe()/g_describe() and casadi_solver(). Changes to the copy do not affect the original. No API stability is guaranteed for the extra methods. In Python this is a read-only property: opti.debug.value(x).

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize((x-1)**6)
>>> opti.solver("ipopt", {"print_time": False},
...             {"print_level": 0, "max_iter": 2, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   pass
>>> opti.debug.value(x)
0.36
>>> print(opti.debug.x_describe(0))
Opti decision variable 'opti..._x_1' of shape 1x1, called from ...

>> opti = Opti(); x = opti.variable(); opti.minimize((x-1)^6);
>> ipopt = struct('print_level', 0, 'max_iter', 2, 'sb', 'yes');
>> opti.solver('ipopt', struct('print_time', false), ipopt);
>> try, opti.solve(); catch e, end
>> opti.debug.value(x)
0.36
>> opti.debug.x_describe(1)
Opti decision variable 'opti..._x_1' of shape 1x1, called from ...

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, (x - 1)^6)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "max_iter" => 2, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
       end
julia> ca.value(ca.debug(opti), x)
0.36
julia> print(ca.x_describe(ca.debug(opti), 0))
Opti decision variable 'opti..._x_1' of shape 1x1, called from ...

See also
OptiAdvanced, advanced, copy

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

Definition at line 851 of file optistack.cpp.

851  {
852  return copy();
853 }

References casadi::Opti::copy().

Referenced by casadi::Opti::disp().

◆ debug_repr()

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

Definition at line 112 of file generic_shared_impl.hpp.

91  {
92  if (node) {
93  return node->debug_repr(node);
94  } else {
95  return "NULL";
96  }
97  }
std::string debug_repr(const Internal *) const

◆ describe()

std::string casadi::OptiAdvanced::describe ( const MX &  x,
casadi_index  indent = 0,
const Dict &  opts = Dict() 
) const

For a symbol: its kind, name, shape and origin, or a note that it belongs to another Opti instance or was declared outside of Opti. For a constraint: its shape and origin. For another expression: the symbols it depends on.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.debug.describe(MX.sym("w"))
"MX symbol 'w' of shape 1x1, declared outside of Opti."
>>> print(opti.debug.describe(x*p))
General expression, dependent on 2 symbols:
  Opti decision variable 'opti..._x_1' of shape 1x1, called from ...
  Opti parameter 'opti..._p_1' of shape 1x1, called from ...

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.debug.describe(MX.sym('w'))
MX symbol 'w' of shape 1x1, declared outside of Opti.
>> opti.debug.describe(x*p)
General expression, dependent on 2 symbols:
  Opti decision variable 'opti..._x_1' of shape 1x1, called from ...
  Opti parameter 'opti..._p_1' of shape 1x1, called from ...

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.describe(ca.debug(opti), ca.MX.sym("w"))
"MX symbol 'w' of shape 1x1, declared outside of Opti."
julia> print(ca.describe(ca.debug(opti), x*p))
General expression, dependent on 2 symbols:
  Opti decision variable 'opti..._x_1' of shape 1x1, called from ...
  Opti parameter 'opti..._p_1' of shape 1x1, called from ...

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

Definition at line 663 of file optistack.cpp.

663  {
664  try {
665  return (*this)->describe(x, indent, opts);
666  } catch(std::exception& e) {
667  THROW_ERROR("describe", e.what());
668  }
669 }
MX x() const
Get all (scalarised) decision variables as a symbolic column vector.
Definition: optistack.cpp:334

References casadi::Opti::x().

Referenced by casadi::OptiNode::describe().

◆ disp()

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

Shows the instance number, the number of variables, parameters and constraints that appear in the problem, whether the solver is up to date and the last return status.

>>> opti = Opti()
>>> x = opti.variable(2)
>>> opti.minimize(sumsqr(x))
>>> opti.subject_to(x[0] >= 1)
>>> print(opti)
Opti {
  instance #...
  #variables: 1 (nx = 2)
  #parameters: 0 (np = 0)
  #constraints: 1 (ng = 1)
  CasADi solver needs updating.
}

>> opti = Opti(); x = opti.variable(2);
>> opti.minimize(sumsqr(x)); opti.subject_to(x(1) >= 1); disp(opti)
Opti {
  instance #...
  #variables: 1 (nx = 2)
  #parameters: 0 (np = 0)
  #constraints: 1 (ng = 1)
  CasADi solver needs updating.
}

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> ca.minimize(opti, ca.sumsqr(x))
julia> ca.subject_to(opti, x[1] >= 1)
julia> opti
Opti(Opti {
  instance #45
  #variables: 1 (nx = 2)
  #parameters: 0 (np = 0)
  #constraints: 1 (ng = 1)
  CasADi solver needs updating.
})

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

Definition at line 754 of file optistack.cpp.

754  {
755  stream << "Opti {" << std::endl;
756  OptiAdvanced mycopy = debug();
757  stream << " instance #" << mycopy.instance_number() << std::endl;
758  if (mycopy.problem_dirty()) mycopy.bake();
759  stream << " #variables: " << mycopy.active_symvar(OPTI_VAR).size()
760  << " (nx = " << mycopy.nx() << ")" << std::endl;
761  stream << " #parameters: " << mycopy.active_symvar(OPTI_PAR).size()
762  << " (np = " << mycopy.np() << ")" << std::endl;
763  stream << " #constraints: " << mycopy.active_symvar(OPTI_DUAL_G).size()
764  << " (ng = " << mycopy.ng() << ")" << std::endl;
765  if (mycopy.solver_dirty()) {
766  stream << " CasADi solver needs updating." << std::endl;
767  } else {
768  stream << " CasADi solver allocated." << std::endl;
769  }
770  if (mycopy.solved()) {
771  stream << " CasADi solver was called: " << mycopy.return_status() << std::endl;
772  }
773  stream << "}";
774 }
OptiAdvanced debug() const
Get a copy with advanced (debugging) functionality.
Definition: optistack.cpp:851
@ OPTI_DUAL_G
Definition: optistack.hpp:2714

References active_symvar(), bake(), casadi::Opti::debug(), instance_number(), casadi::Opti::ng(), casadi::Opti::np(), casadi::Opti::nx(), casadi::OPTI_DUAL_G, casadi::OPTI_PAR, casadi::OPTI_VAR, problem_dirty(), casadi::Opti::return_status(), solved(), and solver_dirty().

Referenced by casadi::OptiSol::disp(), and casadi::Opti::get_str().

◆ dual()

MX casadi::Opti::dual ( const MX &  m) const
inherited

m must be the exact expression object that was passed to subject_to(). The result is symbolic; evaluate it with value(). For inequality constraints the dual is nonnegative (the sign of lam_g is removed); for equality constraints it equals the corresponding entries of lam_g. Keep a reference to the constraint expression when you need its dual later.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize((x-3)**2)
>>> con = x <= 1
>>> opti.subject_to(con)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> sol.value(opti.dual(con)), sol.value(opti.lam_g)
(4.0, 4.0)
>>> opti.subject_to()
>>> con = x >= 4
>>> opti.subject_to(con)
>>> sol = opti.solve()
>>> sol.value(opti.dual(con)), sol.value(opti.lam_g)
(2.0, -2.0)
>>> try:
...   opti.dual(x >= 4)
... except Exception as e:
...   print(str(e).splitlines()[-1])
Constraint not present in Opti stack.

>> opti = Opti(); x = opti.variable(); opti.minimize((x-3)^2);
>> con = x <= 1; opti.subject_to(con);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> sol.value(opti.dual(con)), sol.value(opti.lam_g)
4
4
>> opti.subject_to(); con = x >= 4; opti.subject_to(con); sol = opti.solve();
>> sol.value(opti.dual(con)), sol.value(opti.lam_g)
2
-2
>> try, opti.dual(x >= 4); catch e, disp(contains(e.message, 'Constraint not present')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, (x - 3)^2)
julia> con = x <= 1;
julia> ca.subject_to(opti, con)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(sol, ca.dual(opti, con))
4.0
julia> ca.value(sol, ca.lam_g(opti))
4.0
julia> ca.subject_to(opti)
julia> con = x >= 4;
julia> ca.subject_to(opti, con)
julia> sol = ca.solve(opti);
julia> ca.value(sol, ca.dual(opti, con))
2.0
julia> ca.value(sol, ca.lam_g(opti))
-2.0
julia> try
           ca.dual(opti, x >= 4)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Constraint not present in Opti stack.

See also
lam_g

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

Definition at line 302 of file optistack.cpp.

302  {
303  try {
304  return (*this)->dual(m);
305  } catch(std::exception& e) {
306  THROW_ERROR("dual", e.what());
307  }
308 }

◆ f()

MX casadi::Opti::f ( ) const
inherited

In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.f
MX(0)
>>> opti.minimize(x**2)
>>> print(opti.f)
sq(opti..._x_1)

>> opti = Opti(); x = opti.variable(); disp(opti.f)
0
>> opti.minimize(x^2); disp(opti.f)
sq(opti..._x_1)

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.f(opti)
MX(0)
julia> ca.minimize(opti, x^2)
julia> ca.f(opti)
MX(sq(opti34_x_1))

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

Definition at line 358 of file optistack.cpp.

358  {
359  try {
360  return (*this)->f();
361  } catch(std::exception& e) {
362  THROW_ERROR("f", e.what());
363  }
364 }

Referenced by casadi::Opti::minimize(), and objective().

◆ f_linear_scale()

double casadi::Opti::f_linear_scale ( ) const
inherited

Definition at line 415 of file optistack.cpp.

415  {
416  try {
417  return (*this)->f_linear_scale();
418  } catch(std::exception& e) {
419  THROW_ERROR("f_linear_scale", e.what());
420  }
421 }

◆ g()

MX casadi::Opti::g ( ) const
inherited

The expression g passed to the solver, with lbg <= g <= ubg. In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.subject_to(x >= 1)
>>> opti.subject_to(x**2 == 4)
>>> opti.minimize(x)
>>> print(opti.g)
vertcat(opti..._x_1, sq(opti..._x_1))

>> opti = Opti(); x = opti.variable();
>> opti.subject_to(x >= 1); opti.subject_to(x^2 == 4); opti.minimize(x);
>> opti.g
vertcat(opti..._x_1, sq(opti..._x_1))

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.subject_to(opti, x >= 1)
julia> ca.subject_to(opti, x^2 == 4)
julia> ca.minimize(opti, x)
julia> ca.g(opti)
MX(vertcat(opti33_x_1, sq(opti33_x_1)))

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

Definition at line 350 of file optistack.cpp.

350  {
351  try {
352  return (*this)->g();
353  } catch(std::exception& e) {
354  THROW_ERROR("g", e.what());
355  }
356 }

Referenced by casadi::Opti::subject_to().

◆ g_describe()

std::string casadi::OptiAdvanced::g_describe ( casadi_index  i,
const Dict &  opts = Dict() 
) const

>>> opti = Opti()
>>> x = opti.variable(3)
>>> opti.subject_to(x >= 0)
>>> print(opti.debug.g_describe(1))
Opti constraint of shape 3x1, called from ...
At nonzero 1, part 0.

>> opti = Opti(); x = opti.variable(3); opti.subject_to(x >= 0);
>> opti.debug.g_describe(2)
Opti constraint of shape 3x1, called from ...
At nonzero 2, part 0.

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 3);
julia> ca.subject_to(opti, x >= 0)
julia> print(ca.g_describe(ca.debug(opti), 1))
Opti constraint of shape 3x1, called from ...
At nonzero 1, part 0.

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

Definition at line 656 of file optistack.cpp.

656  {
657  try {
658  return (*this)->g_describe(i, opts);
659  } catch(std::exception& e) {
660  THROW_ERROR("g_describe", e.what());
661  }
662 }

Referenced by casadi::OptiNode::g_describe().

◆ g_index_reduce_g()

casadi_int casadi::OptiAdvanced::g_index_reduce_g ( casadi_index  i) const

Definition at line 617 of file optistack.cpp.

617  {
618  try {
619  return (*this)->g_index_reduce_g(i);
620  } catch(std::exception& e) {
621  THROW_ERROR("g_index_reduce_g", e.what());
622  }
623 }

◆ g_index_reduce_x()

casadi_int casadi::OptiAdvanced::g_index_reduce_x ( casadi_index  i) const

Definition at line 625 of file optistack.cpp.

625  {
626  try {
627  return (*this)->g_index_reduce_x(i);
628  } catch(std::exception& e) {
629  THROW_ERROR("g_index_reduce_x", e.what());
630  }
631 }

◆ g_index_unreduce_g()

casadi_int casadi::OptiAdvanced::g_index_unreduce_g ( casadi_index  i) const

Definition at line 633 of file optistack.cpp.

633  {
634  try {
635  return (*this)->g_index_unreduce_g(i);
636  } catch(std::exception& e) {
637  THROW_ERROR("g_index_unreduce_g", e.what());
638  }
639 }

◆ g_linear_scale()

DM casadi::Opti::g_linear_scale ( ) const
inherited

Definition at line 407 of file optistack.cpp.

407  {
408  try {
409  return (*this)->g_linear_scale();
410  } catch(std::exception& e) {
411  THROW_ERROR("g_linear_scale", e.what());
412  }
413 }

◆ g_lookup()

MX casadi::OptiAdvanced::g_lookup ( casadi_index  i) const

>>> opti = Opti()
>>> x = opti.variable(2)
>>> opti.subject_to(x >= 0)
>>> opti.subject_to(x[0] + x[1] == 1)
>>> print(opti.debug.g_lookup(2))
(1==(opti..._x_1[0]+opti..._x_1[1]))

>> opti = Opti(); x = opti.variable(2);
>> opti.subject_to(x >= 0); opti.subject_to(x(1) + x(2) == 1);
>> opti.debug.g_lookup(3)
(1==(opti..._x_1[0]+opti..._x_1[1]))

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> ca.subject_to(opti, x >= 0)
julia> ca.subject_to(opti, x[1] + x[2] == 1)
julia> ca.g_lookup(ca.debug(opti), 2)
MX((1==(opti52_x_1[0]+opti52_x_1[1])))

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

Definition at line 641 of file optistack.cpp.

641  {
642  try {
643  return (*this)->g_lookup(i);
644  } catch(std::exception& e) {
645  THROW_ERROR("g_lookup", e.what());
646  }
647 }

Referenced by casadi::OptiNode::g_lookup().

◆ get()

Definition at line 99 of file generic_shared_impl.hpp.

115  {
116  return node;
117  }

◆ get_meta()

MetaVar casadi::OptiAdvanced::get_meta ( const MX &  m) const

Definition at line 552 of file optistack.cpp.

552  {
553  try {
554  return (*this)->get_meta(m);
555  } catch(std::exception& e) {
556  THROW_ERROR("get_meta", e.what());
557  }
558 }

◆ get_meta_con()

MetaCon casadi::OptiAdvanced::get_meta_con ( const MX &  m) const

Definition at line 560 of file optistack.cpp.

560  {
561  try {
562  return (*this)->get_meta_con(m);
563  } catch(std::exception& e) {
564  THROW_ERROR("get_meta_con", e.what());
565  }
566 }

◆ get_str()

std::string casadi::Opti::get_str ( bool  more = false) const
inherited

Definition at line 776 of file optistack.cpp.

776  {
777  std::stringstream ss;
778  disp(ss, more);
779  return ss.str();
780 }
void disp(std::ostream &stream, bool more=false) const
Print a summary of the instance.
Definition: optistack.cpp:754

References casadi::Opti::disp().

Referenced by casadi::OptiSol::get_str().

◆ getCount()

casadi_int casadi::GenericShared< SharedObject , SharedObjectInternal >::getCount
inherited

Definition at line 102 of file generic_shared_impl.hpp.

138  {
139  return (*this)->getCount();
140  }

◆ initial()

std::vector< MX > casadi::Opti::initial ( ) const
inherited

One expression value==var per variable and dual variable, holding the current initial guess. Pass the list to value() to evaluate an expression at the initial guess, or to set_initial() of another Opti instance with the same symbols.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.set_initial(x, 2)
>>> opti.minimize(x**2)
>>> print(opti.initial())
[MX((2==opti..._x_1))]
>>> opti.value(x**2+1, opti.initial())
5.0

>> opti = Opti(); x = opti.variable(); opti.set_initial(x, 2); opti.minimize(x^2);
>> ini = opti.initial(); disp(ini{1})
(2==opti..._x_1)
>> opti.value(x^2+1, opti.initial())
5

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.set_initial(opti, x, 2)
julia> ca.minimize(opti, x^2)
julia> print(ca.initial(opti))
MX[(2==opti..._x_1)]
julia> opti.value(x^2 + 1, ca.initial(opti))
5.0

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

Definition at line 278 of file optistack.cpp.

278  {
279  try {
280  return (*this)->initial();
281  } catch(std::exception& e) {
282  THROW_ERROR("initial", e.what());
283  }
284 }

◆ instance_number()

casadi_int casadi::OptiAdvanced::instance_number ( ) const

Definition at line 746 of file optistack.cpp.

746  {
747  try {
748  return (*this)->instance_number();
749  } catch(std::exception& e) {
750  THROW_ERROR("instance_number", e.what());
751  }
752 }

Referenced by casadi::Opti::disp().

◆ is_null()

Definition at line 116 of file generic_shared_impl.hpp.

120  {
121  return node==nullptr;
122  }

◆ is_parametric()

bool casadi::OptiAdvanced::is_parametric ( const MX &  expr) const

True when no decision variable of this instance appears in expr (constants count as parametric).

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.debug.is_parametric(2*p), opti.debug.is_parametric(x*p)
(True, False)

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> fprintf('%d %d\n', opti.debug.is_parametric(2*p), opti.debug.is_parametric(x*p))
1 0

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> d = ca.debug(opti);
julia> ca.is_parametric(d, 2*p), ca.is_parametric(d, x*p)
(true, false)

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

Definition at line 512 of file optistack.cpp.

512  {
513  try {
514  return (*this)->is_parametric(expr);
515  } catch(std::exception& e) {
516  THROW_ERROR("is_parametric", e.what());
517  }
518 }

◆ lam_g()

MX casadi::Opti::lam_g ( ) const
inherited

One multiplier per row of g(), as the solver reports them: with Lagrangian f + lam_g'*g, an entry is positive when the upper bound is active and negative when the lower bound is active, and -lam_g is the sensitivity of the optimal objective to the active bound. Useful for the Lagrangian Hessian, warm starting (set_initial) and as input or output of to_function(). In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize(x**2)
>>> opti.subject_to(x >= p)
>>> opti.set_value(p, 1)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> sol.value(opti.lam_g)
-2.0
>>> sol.value(hessian(opti.f + dot(opti.lam_g, opti.g), opti.x)[0])
2.0

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.minimize(x^2); opti.subject_to(x >= p); opti.set_value(p, 1);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); disp(sol.value(opti.lam_g))
-2
>> H = hessian(opti.f + dot(opti.lam_g, opti.g), opti.x); disp(sol.value(H))
2

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, x^2)
julia> ca.subject_to(opti, x >= p)
julia> ca.set_value(opti, p, 1)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(sol, ca.lam_g(opti))
-2.0
julia> L = ca.f(opti) + ca.dot(ca.lam_g(opti), ca.g(opti));
julia> ca.value(sol, ca.hessian(L, ca.x(opti))[1])
2.0

See also
dual

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

Definition at line 383 of file optistack.cpp.

383  {
384  try {
385  return (*this)->lam_g();
386  } catch(std::exception& e) {
387  THROW_ERROR("lam_g", e.what());
388  }
389 }

◆ lbg()

MX casadi::Opti::lbg ( ) const
inherited

lbg() and ubg() are the lower and upper bounds matching g(); they are expressions in the parameters (constants otherwise), with -inf/inf for one-sided constraints. In Python these are read-only properties.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.subject_to(x >= 1)
>>> opti.subject_to(x <= p)
>>> opti.subject_to(x**2 == 4)
>>> opti.minimize(x)
>>> print(opti.lbg, opti.ubg)
vertcat(1, -inf, 4) vertcat(inf, opti..._p_1, 4)

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.subject_to(x >= 1); opti.subject_to(x <= p); opti.subject_to(x^2 == 4);
>> opti.minimize(x); disp(opti.lbg), disp(opti.ubg)
vertcat(1, -inf, 4)
vertcat(inf, opti..._p_1, 4)

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.subject_to(opti, x >= 1)
julia> ca.subject_to(opti, x <= p)
julia> ca.subject_to(opti, x^2 == 4)
julia> ca.minimize(opti, x)
julia> print(ca.lbg(opti), " ", ca.ubg(opti))
vertcat(1, -inf, 4) vertcat(inf, opti..._p_1, 4)

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

Definition at line 366 of file optistack.cpp.

366  {
367  try {
368  return (*this)->lbg();
369  } catch(std::exception& e) {
370  THROW_ERROR("lbg", e.what());
371  }
372 }

◆ mark_problem_dirty()

void casadi::OptiAdvanced::mark_problem_dirty ( bool  flag = true)

Definition at line 790 of file optistack.cpp.

790  {
791  try {
792  (*this)->mark_problem_dirty(flag);
793  } catch(std::exception& e) {
794  THROW_ERROR("mark_problem_dirty", e.what());
795  }
796 }

◆ mark_solved()

void casadi::OptiAdvanced::mark_solved ( bool  flag = true)

Definition at line 820 of file optistack.cpp.

820  {
821  try {
822  (*this)->mark_solved(flag);
823  } catch(std::exception& e) {
824  THROW_ERROR("mark_solved", e.what());
825  }
826 }

◆ mark_solver_dirty()

void casadi::OptiAdvanced::mark_solver_dirty ( bool  flag = true)

Definition at line 805 of file optistack.cpp.

805  {
806  try {
807  (*this)->mark_solver_dirty(flag);
808  } catch(std::exception& e) {
809  THROW_ERROR("mark_solver_dirty", e.what());
810  }
811 }

◆ minimize()

void casadi::Opti::minimize ( const MX &  f,
double  linear_scale = 1 
)
inherited

The objective must be a scalar expression in the variables and parameters of this instance; a non-scalar raises an error. The default objective is 0. Each call replaces the previous objective. Dual variables (opti.dual, opti.lam_g) may not appear in it.

Parameters
fScalar MX expression to minimize
linear_scaleThe solver sees f divided by this factor (default 1)

>>> opti = Opti()
>>> x = opti.variable(2)
>>> opti.minimize(sumsqr(x))
>>> opti.minimize(x[0]**2, 2)
>>> print(opti.f, opti.f_linear_scale)
sq(opti..._x_1[0]) 2.0
>>> try:
...   opti.minimize(x)
... except Exception as e:
...   print(str(e).splitlines()[-1])
Objective must be scalar, got 2x1.

>> opti = Opti(); x = opti.variable(2);
>> opti.minimize(sumsqr(x)); opti.minimize(x(1)^2, 2);
>> opti.f, opti.f_linear_scale
sq(opti..._x_1[0])
2
>> try, opti.minimize(x); catch e, disp(contains(e.message, 'Objective must be scalar')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> ca.minimize(opti, ca.sumsqr(x))
julia> opti.minimize(x[1]^2, 2)
julia> print(ca.f(opti), " ", ca.f_linear_scale(opti))
sq(opti..._x_1[0]) 2.0
julia> try
           ca.minimize(opti, x)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Objective must be scalar, got 2x1.

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

Definition at line 114 of file optistack.cpp.

114  {
115  try {
116  (*this)->minimize(f, linear_scale);
117  } catch(std::exception& e) {
118  THROW_ERROR("minimize", e.what());
119  }
120 }
MX f() const
Get the objective expression.
Definition: optistack.cpp:358

References casadi::Opti::f().

◆ ng()

casadi_int casadi::Opti::ng ( ) const
inherited

Total number of constraint rows; a double-bounded constraint counts once. In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable(2)
>>> opti.subject_to(0 <= (x <= 1))
>>> opti.subject_to(x[0] == x[1])
>>> opti.ng
3

>> opti = Opti(); x = opti.variable(2);
>> opti.subject_to(0 <= x <= 1); opti.subject_to(x(1) == x(2)); disp(opti.ng)
3

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> ca.subject_to(opti, 0 <= (x <= 1))
julia> ca.subject_to(opti, x[1] == x[2])
julia> ca.ng(opti)
3

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

Definition at line 326 of file optistack.cpp.

326  {
327  try {
328  return (*this)->ng();
329  } catch(std::exception& e) {
330  THROW_ERROR("ng", e.what());
331  }
332 }

Referenced by casadi::Opti::disp().

◆ np()

casadi_int casadi::Opti::np ( ) const
inherited

Counts the nonzeros of all parameters that appear in the problem. In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter(2, 2)
>>> opti.minimize(x*sum1(vec(p)))
>>> opti.np
4

>> opti = Opti(); x = opti.variable(); p = opti.parameter(2, 2);
>> opti.minimize(x*sum1(vec(p))); disp(opti.np)
4

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti, 2, 2);
julia> ca.minimize(opti, x*sum(vec(p)))
julia> ca.np(opti)
4

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

Definition at line 318 of file optistack.cpp.

318  {
319  try {
320  return (*this)->np();
321  } catch(std::exception& e) {
322  THROW_ERROR("nx", e.what());
323  }
324 }

Referenced by casadi::Opti::disp().

◆ nx()

casadi_int casadi::Opti::nx ( ) const
inherited

Counts the nonzeros of all variables that appear in the objective or constraints. In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable(3)
>>> y = opti.variable()
>>> opti.minimize(sumsqr(x))
>>> opti.nx
3

>> opti = Opti(); x = opti.variable(3); y = opti.variable();
>> opti.minimize(sumsqr(x)); disp(opti.nx)
3

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 3);
julia> y = ca.variable(opti);
julia> ca.minimize(opti, ca.sumsqr(x))
julia> ca.nx(opti)
3

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

Definition at line 310 of file optistack.cpp.

310  {
311  try {
312  return (*this)->nx();
313  } catch(std::exception& e) {
314  THROW_ERROR("nx", e.what());
315  }
316 }

Referenced by casadi::Opti::disp().

◆ objective()

MX casadi::OptiAdvanced::objective ( ) const

Definition at line 726 of file optistack.cpp.

726  {
727  return f();
728 }

References casadi::Opti::f().

◆ operator->() [1/2]

OptiNode * casadi::Opti::operator-> ( )
inherited

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

Definition at line 38 of file optistack.cpp.

38  {
39  return static_cast<OptiNode*>(SharedObject::operator->());
40 }
SharedObjectInternal * operator->() const
Access a member function or object.

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

◆ operator->() [2/2]

const OptiNode * casadi::Opti::operator-> ( ) const
inherited

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

Definition at line 42 of file optistack.cpp.

42  {
43  return static_cast<const OptiNode*>(SharedObject::operator->());
44 }

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

◆ own()

void casadi::GenericShared< SharedObject , SharedObjectInternal >::own ( Internal *  node)
inherited

Assign the node to a node class pointer (or null)

Definition at line 89 of file generic_shared_impl.hpp.

◆ p()

MX casadi::Opti::p ( ) const
inherited

Restricted to the parameters that appear in the problem. In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter(2)
>>> opti.minimize(x*p[0])
>>> opti.p.shape
(2, 1)

>> opti = Opti(); x = opti.variable(); p = opti.parameter(2);
>> opti.minimize(x*p(1)); disp(size(opti.p))
2 1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti, 2);
julia> ca.minimize(opti, x*p[1])
julia> size(ca.p(opti))
(2, 1)

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

Definition at line 342 of file optistack.cpp.

342  {
343  try {
344  return (*this)->p();
345  } catch(std::exception& e) {
346  THROW_ERROR("p", e.what());
347  }
348 }

◆ parameter() [1/3]

MX casadi::Opti::parameter ( casadi_int  n = 1,
casadi_int  m = 1,
const std::string &  attribute = "full" 
)
inherited

Returns an MX symbol that is held constant by the solver. Each parameter that appears in the problem must be given a numerical value with set_value() before solve(), otherwise solve() raises an error naming the parameter. The order of creation does not matter for the result.

Parameters
nNumber of rows (default 1)
mNumber of columns (default 1)
attribute"full" (default) or "symmetric"
Returns
A dense MX symbol of shape n-by-m

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter(2)
>>> opti.minimize(sumsqr(x-p))
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print(str(e).splitlines()[-2])
You have forgotten to assign a value to a parameter ('set_value'), or have set it to NaN/Inf:
>>> opti.set_value(p, [1, 3])
>>> opti.solve().value(x)
2.0

>> opti = Opti(); x = opti.variable(); p = opti.parameter(2);
>> opti.minimize(sumsqr(x-p));
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, disp(contains(e.message, 'forgotten to assign a value')); end
1
>> opti.set_value(p, [1; 3]); sol = opti.solve(); disp(sol.value(x))
2

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti, 2);
julia> ca.minimize(opti, ca.sumsqr(x - p))
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           println(split(sprint(showerror, e), "\n")[end-1])
       end
You have forgotten to assign a value to a parameter ('set_value'), or have set it to NaN/Inf:
julia> ca.set_value(opti, p, [1, 3])
julia> ca.value(ca.solve(opti), x)
2.0

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

Definition at line 90 of file optistack.cpp.

90  {
91  try {
92  return (*this)->parameter(n, m, attribute);
93  } catch(std::exception& e) {
94  THROW_ERROR("parameter", e.what());
95  }
96 }

◆ parameter() [2/3]

MX casadi::Opti::parameter ( const MX &  symbol,
const std::string &  attribute = "full" 
)
inherited

Definition at line 106 of file optistack.cpp.

106  {
107  try {
108  return (*this)->parameter(symbol, attribute);
109  } catch(std::exception& e) {
110  THROW_ERROR("parameter", e.what());
111  }
112 }

◆ parameter() [3/3]

MX casadi::Opti::parameter ( const Sparsity &  sp,
const std::string &  attribute = "full" 
)
inherited

Definition at line 98 of file optistack.cpp.

98  {
99  try {
100  return (*this)->parameter(sp, attribute);
101  } catch(std::exception& e) {
102  THROW_ERROR("parameter", e.what());
103  }
104 }

◆ print_ptr()

void casadi::SharedObject::print_ptr ( std::ostream &  stream = casadi::uout()) const
inherited

Print the pointer to the internal class

Definition at line 43 of file shared_object.cpp.

43  {
44  stream << get();
45  }
SharedObjectInternal * get() const
Get a const pointer to the node.

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

◆ problem_dirty()

bool casadi::OptiAdvanced::problem_dirty ( ) const

Definition at line 797 of file optistack.cpp.

797  {
798  try {
799  return (*this)->problem_dirty();
800  } catch(std::exception& e) {
801  THROW_ERROR("problem_dirty", e.what());
802  }
803 }

Referenced by casadi::OptiNode::baked_copy(), and casadi::Opti::disp().

◆ res() [1/2]

DMDict casadi::OptiAdvanced::res ( ) const

Definition at line 711 of file optistack.cpp.

711  {
712  try {
713  return (*this)->res();
714  } catch(std::exception& e) {
715  THROW_ERROR("res", e.what());
716  }
717 }

Referenced by res().

◆ res() [2/2]

void casadi::OptiAdvanced::res ( const DMDict &  res)

Definition at line 703 of file optistack.cpp.

703  {
704  try {
705  (*this)->res(res);
706  } catch(std::exception& e) {
707  THROW_ERROR("res", e.what());
708  }
709 }
DMDict res() const
Result dict of the latest solve (x, f, g, lam_x, lam_g, lam_p)
Definition: optistack.cpp:711

References res().

◆ return_status()

std::string casadi::Opti::return_status ( ) const
inherited

The plugin's "return_status" string (e.g. "Solve_Succeeded" or "Infeasible_Problem_Detected" for Ipopt), or "unknown" when no solve has happened. No stability is guaranteed for the strings.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize(x**2)
>>> opti.return_status()
'unknown'
>>> opti.subject_to(x >= 1)
>>> opti.subject_to(x <= -1)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print(opti.return_status())
Infeasible_Problem_Detected

>> opti = Opti(); x = opti.variable(); opti.minimize(x^2);
>> opti.return_status()
unknown
>> opti.subject_to(x >= 1); opti.subject_to(x <= -1);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, disp(opti.return_status()); end
Infeasible_Problem_Detected

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, x^2)
julia> ca.return_status(opti)
"unknown"
julia> ca.subject_to(opti, x >= 1)
julia> ca.subject_to(opti, x <= -1)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           println(ca.return_status(opti))
       end
Infeasible_Problem_Detected

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

Definition at line 270 of file optistack.cpp.

270  {
271  try {
272  return (*this)->return_status();
273  } catch(std::exception& e) {
274  THROW_ERROR("return_status", e.what());
275  }
276 }

Referenced by casadi::Opti::disp().

◆ scale_helper()

Function casadi::Opti::scale_helper ( const Function &  h) const
inherited

Wraps a user-written derivative function so that it operates in the scaled space the solver sees (set_linear_scale(), minimize()/subject_to() scales). h must be named "nlp_jac_g" (inputs x, p; outputs g, jac_g_x) or "nlp_hess_l" (inputs x, p, lam_f, lam_g; output the Lagrangian Hessian); other names raise an error. The result can be handed to a solver that accepts custom derivative functions.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.set_linear_scale(x, 2, 1)
>>> opti.minimize((x-p)**2)
>>> opti.subject_to(x >= 0)
>>> h = Function("nlp_jac_g", [opti.x, opti.p], [opti.g, jacobian(opti.g, opti.x)],
...              ["x", "p"], ["g", "jac_g_x"])
>>> hs = opti.scale_helper(h)
>>> hs(x=3, p=0)
{'g': DM(7), 'jac_g_x': DM(2)}

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.set_linear_scale(x, 2, 1); opti.minimize((x-p)^2); opti.subject_to(x >= 0);
>> J = jacobian(opti.g, opti.x);
>> h = Function('nlp_jac_g', {opti.x, opti.p}, {opti.g, J}, {'x', 'p'}, {'g', 'jac_g_x'});
>> hs = opti.scale_helper(h); r = hs('x', 3, 'p', 0); disp(r.g), disp(r.jac_g_x)
7
2

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.set_linear_scale(opti, x, 2, 1)
julia> ca.minimize(opti, (x - p)^2)
julia> ca.subject_to(opti, x >= 0)
julia> g, X = ca.g(opti), ca.x(opti);
julia> h = ca.Function("nlp_jac_g", [X, ca.p(opti)], [g, ca.jacobian(g, X)],
                       ["x", "p"], ["g", "jac_g_x"]);
julia> hs = ca.scale_helper(opti, h);
julia> hs(x=3, p=0)
Dict{String, DM} with 2 entries:
  "g" => 7
  "jac_g_x" => 2

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

Definition at line 254 of file optistack.cpp.

254  {
255  try {
256  return (*this)->scale_helper(h);
257  } catch(std::exception& e) {
258  THROW_ERROR("scale_helper", e.what());
259  }
260 }

Referenced by casadi::OptiNode::scale_helper().

◆ set_domain()

void casadi::Opti::set_domain ( const MX &  x,
const std::string &  domain 
)
inherited

Marks all scalars of x as integer or real (default). The information is passed to the solver as the nlpsol/qpsol option "discrete"; a solver without integer support raises an error at solve().

Parameters
xA decision variable (pure symbol, not an expression)
domain"real" or "integer"; anything else raises an error

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.set_domain(x, "integer")
>>> opti.minimize((x-1.4)**2)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print(str(e).splitlines()[-1])
Discrete variables require a solver with integer support
>>> try:
...   opti.set_domain(x, "binary")
... except Exception as e:
...   print("Unknown domain 'binary'. Known values are 'real', 'integer'." in str(e))
True

>> opti = Opti(); x = opti.variable(); opti.set_domain(x, 'integer');
>> opti.minimize((x-1.4)^2);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, disp(contains(e.message, 'solver with integer support')); end
1
>> try, opti.set_domain(x, 'binary'); catch e, disp(contains(e.message, 'Unknown')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.set_domain(opti, x, "integer")
julia> ca.minimize(opti, (x - 1.4)^2)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Discrete variables require a solver with integer support
julia> try
           ca.set_domain(opti, x, "binary")
       catch e
           msg = "Unknown domain 'binary'. Known values are 'real', 'integer'."
           println(occursin(msg, sprint(showerror, e)))
       end
true

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

Definition at line 189 of file optistack.cpp.

189  {
190  try {
191  (*this)->set_domain(x, domain);
192  } catch(std::exception& e) {
193  THROW_ERROR("set_domain", e.what());
194  }
195 }

References casadi::Opti::x().

◆ set_initial() [1/2]

void casadi::Opti::set_initial ( const MX &  x,
const DM &  v 
)
inherited

The guess is used as x0 (and lam_g0 for opti.lam_g or opti.dual(con)) at the next solve(); the default is 0. x may be a variable, a slice of one, or a linear mapping of variables such as 10*x[0]; a nonlinear expression raises an error. Parameters are refused with a hint to use set_value(). The list form takes assignment expressions var==value, as returned by value_variables() or initial(), which makes warm starting a one-liner. Calling this method invalidates value() until the next solve().

Parameters
xVariable (or linear mapping of variables) to initialize
vNumerical value; scalars are broadcast to the shape of x

>>> opti = Opti()
>>> x = opti.variable(2)
>>> p = opti.parameter()
>>> opti.set_initial(x, 1)
>>> opti.set_initial(10*x[0], 2)
>>> print(opti.initial())
[MX(([0.2, 1]==opti..._x_1))]
>>> try:
...   opti.set_initial(p, 1)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You cannot set an initial value for a parameter. Did you mean 'set_value'?
>>> try:
...   opti.set_initial(x[0]*x[1], 1)
... except Exception as e:
...   print("Use symbols or simple mappings of symbols" in str(e))
True

>> opti = Opti(); x = opti.variable(2); p = opti.parameter();
>> opti.set_initial(x, 1); opti.set_initial(10*x(1), 2);
>> ini = opti.initial(); disp(ini{1})
([0.2, 1]==opti..._x_1)
>> try, opti.set_initial(p, 1); catch e, disp(contains(e.message, 'mean ''set_value''')); end
1
>> try, opti.set_initial(x(1)*x(2), 1); catch e, disp(contains(e.message, 'simple')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> p = ca.parameter(opti);
julia> ca.set_initial(opti, x, 1)
julia> ca.set_initial(opti, 10*x[1], 2)
julia> print(ca.initial(opti))
MX[([0.2, 1]==opti..._x_1)]
julia> try
           ca.set_initial(opti, p, 1)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You cannot set an initial value for a parameter. Did you mean 'set_value'?
julia> try
           ca.set_initial(opti, x[1]*x[2], 1)
       catch e
           msg = "Use symbols or simple mappings of symbols"
           println(occursin(msg, sprint(showerror, e)))
       end
true

Warm start from a previous solution:

>>> opti = Opti()
>>> x = opti.variable()
>>> y = opti.variable()
>>> opti.minimize((y-x**2)**2)
>>> opti.subject_to(x**2+y**2==1)
>>> opti.subject_to(x+y>=1)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> opti.set_initial(sol.value_variables())
>>> opti.set_initial(opti.lam_g, sol.value(opti.lam_g))
>>> opti.solve().stats()["iter_count"] < sol.stats()["iter_count"]
True

>> opti = Opti(); x = opti.variable(); y = opti.variable();
>> opti.minimize((y-x^2)^2); opti.subject_to(x^2+y^2==1); opti.subject_to(x+y>=1);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> opti.set_initial(sol.value_variables());
>> opti.set_initial(opti.lam_g, sol.value(opti.lam_g));
>> sol2 = opti.solve(); s1 = sol.stats(); s2 = sol2.stats();
>> s2.iter_count < s1.iter_count
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> y = ca.variable(opti);
julia> ca.minimize(opti, (y - x^2)^2)
julia> ca.subject_to(opti, x^2 + y^2 == 1)
julia> ca.subject_to(opti, x + y >= 1)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> opti.set_initial(ca.value_variables(sol))
julia> ca.set_initial(opti, ca.lam_g(opti), ca.value(sol, ca.lam_g(opti)))
julia> ca.stats(ca.solve(opti))["iter_count"] < ca.stats(sol)["iter_count"]
true

See also
set_value, initial, value_variables

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

Definition at line 165 of file optistack.cpp.

165  {
166  try {
167  (*this)->set_initial(x, v);
168  } catch(std::exception& e) {
169  THROW_ERROR("set_initial", e.what());
170  }
171 }

References casadi::Opti::x().

◆ set_initial() [2/2]

void casadi::Opti::set_initial ( const std::vector< MX > &  assignments)
inherited

The guess is used as x0 (and lam_g0 for opti.lam_g or opti.dual(con)) at the next solve(); the default is 0. x may be a variable, a slice of one, or a linear mapping of variables such as 10*x[0]; a nonlinear expression raises an error. Parameters are refused with a hint to use set_value(). The list form takes assignment expressions var==value, as returned by value_variables() or initial(), which makes warm starting a one-liner. Calling this method invalidates value() until the next solve().

Parameters
xVariable (or linear mapping of variables) to initialize
vNumerical value; scalars are broadcast to the shape of x

>>> opti = Opti()
>>> x = opti.variable(2)
>>> p = opti.parameter()
>>> opti.set_initial(x, 1)
>>> opti.set_initial(10*x[0], 2)
>>> print(opti.initial())
[MX(([0.2, 1]==opti..._x_1))]
>>> try:
...   opti.set_initial(p, 1)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You cannot set an initial value for a parameter. Did you mean 'set_value'?
>>> try:
...   opti.set_initial(x[0]*x[1], 1)
... except Exception as e:
...   print("Use symbols or simple mappings of symbols" in str(e))
True

>> opti = Opti(); x = opti.variable(2); p = opti.parameter();
>> opti.set_initial(x, 1); opti.set_initial(10*x(1), 2);
>> ini = opti.initial(); disp(ini{1})
([0.2, 1]==opti..._x_1)
>> try, opti.set_initial(p, 1); catch e, disp(contains(e.message, 'mean ''set_value''')); end
1
>> try, opti.set_initial(x(1)*x(2), 1); catch e, disp(contains(e.message, 'simple')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> p = ca.parameter(opti);
julia> ca.set_initial(opti, x, 1)
julia> ca.set_initial(opti, 10*x[1], 2)
julia> print(ca.initial(opti))
MX[([0.2, 1]==opti..._x_1)]
julia> try
           ca.set_initial(opti, p, 1)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You cannot set an initial value for a parameter. Did you mean 'set_value'?
julia> try
           ca.set_initial(opti, x[1]*x[2], 1)
       catch e
           msg = "Use symbols or simple mappings of symbols"
           println(occursin(msg, sprint(showerror, e)))
       end
true

Warm start from a previous solution:

>>> opti = Opti()
>>> x = opti.variable()
>>> y = opti.variable()
>>> opti.minimize((y-x**2)**2)
>>> opti.subject_to(x**2+y**2==1)
>>> opti.subject_to(x+y>=1)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> opti.set_initial(sol.value_variables())
>>> opti.set_initial(opti.lam_g, sol.value(opti.lam_g))
>>> opti.solve().stats()["iter_count"] < sol.stats()["iter_count"]
True

>> opti = Opti(); x = opti.variable(); y = opti.variable();
>> opti.minimize((y-x^2)^2); opti.subject_to(x^2+y^2==1); opti.subject_to(x+y>=1);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> opti.set_initial(sol.value_variables());
>> opti.set_initial(opti.lam_g, sol.value(opti.lam_g));
>> sol2 = opti.solve(); s1 = sol.stats(); s2 = sol2.stats();
>> s2.iter_count < s1.iter_count
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> y = ca.variable(opti);
julia> ca.minimize(opti, (y - x^2)^2)
julia> ca.subject_to(opti, x^2 + y^2 == 1)
julia> ca.subject_to(opti, x + y >= 1)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> opti.set_initial(ca.value_variables(sol))
julia> ca.set_initial(opti, ca.lam_g(opti), ca.value(sol, ca.lam_g(opti)))
julia> ca.stats(ca.solve(opti))["iter_count"] < ca.stats(sol)["iter_count"]
true

See also
set_value, initial, value_variables

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

Definition at line 172 of file optistack.cpp.

172  {
173  try {
174  (*this)->set_initial(assignments);
175  } catch(std::exception& e) {
176  THROW_ERROR("set_initial", e.what());
177  }
178 }

◆ set_linear_scale()

void casadi::Opti::set_linear_scale ( const MX &  x,
const DM &  scale,
const DM &  offset = 0 
)
inherited

The solver works with (x-offset)/scale instead of x; all user-facing values (value(), initial guesses, duals) stay in the original units. Useful when variables differ by orders of magnitude.

Parameters
xDecision variable or linear mapping of variables
scaleScalar or matrix of the shape of x (default 1)
offsetScalar or matrix of the shape of x (default 0)

>>> opti = Opti()
>>> T = opti.variable()
>>> opti.set_linear_scale(T, 20, 273.15)
>>> opti.minimize((T-300)**2)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> sol.value(T), opti.x_linear_scale, opti.x_linear_scale_offset
(300.0, DM(20), DM(273.15))
>>> opti.debug.arg()["x0"]
DM(-13.6575)

>> opti = Opti(); T = opti.variable();
>> opti.set_linear_scale(T, 20, 273.15); opti.minimize((T-300)^2);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> sol.value(T), opti.x_linear_scale, opti.x_linear_scale_offset
300
20
273.15
>> a = opti.debug.arg(); disp(a.x0)
-13.6575

julia> opti = ca.Opti();
julia> T = ca.variable(opti);
julia> ca.set_linear_scale(opti, T, 20, 273.15)
julia> ca.minimize(opti, (T - 300)^2)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(sol, T)
300.0
julia> ca.x_linear_scale(opti), ca.x_linear_scale_offset(opti)
(20, 273.15)

See also
x_linear_scale, x_linear_scale_offset, scale_helper

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

Definition at line 197 of file optistack.cpp.

197  {
198  try {
199  (*this)->set_linear_scale(x, scale, offset);
200  } catch(std::exception& e) {
201  THROW_ERROR("set_linear_scale", e.what());
202  }
203 }

References casadi::Opti::x().

◆ set_meta()

void casadi::OptiAdvanced::set_meta ( const MX &  m,
const MetaVar &  meta 
)

Definition at line 568 of file optistack.cpp.

568  {
569  try {
570  (*this)->set_meta(m, meta);
571  } catch(std::exception& e) {
572  THROW_ERROR("set_meta", e.what());
573  }
574 }

◆ set_meta_con()

void casadi::OptiAdvanced::set_meta_con ( const MX &  m,
const MetaCon &  meta 
)

Definition at line 576 of file optistack.cpp.

576  {
577  try {
578  (*this)->set_meta_con(m, meta);
579  } catch(std::exception& e) {
580  THROW_ERROR("set_meta_con", e.what());
581  }
582 }

◆ set_value() [1/2]

void casadi::Opti::set_value ( const MX &  x,
const DM &  v 
)
inherited

Every parameter that appears in the problem must have a value before solve(); the value stays until changed, so re-solving with new data only needs set_value() and solve(). x may be a parameter, a slice, or a linear mapping of parameters. Decision variables are refused with a hint to use set_initial(). The list form accepts assignment expressions par==value, as returned by value_parameters(). Calling this method invalidates value() of variables until the next solve().

Parameters
xParameter (or linear mapping of parameters)
vNumerical value; scalars are broadcast

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter(2)
>>> opti.set_value(p, [1, 2])
>>> opti.set_value(p[1], 5)
>>> opti.value(p)
array([1., 5.])
>>> try:
...   opti.set_value(x, 1)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You cannot set a value for a variable. Did you mean 'set_initial'?
>>> opti.set_value([p==7])
>>> opti.value(p)
array([7., 7.])

>> opti = Opti(); x = opti.variable(); p = opti.parameter(2);
>> opti.set_value(p, [1; 2]); opti.set_value(p(2), 5); disp(opti.value(p)')
1 5
>> try, opti.set_value(x, 1); catch e, disp(contains(e.message, 'mean ''set_initial''')); end
1
>> opti.set_value({p==7}); disp(opti.value(p)')
7 7

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti, 2);
julia> ca.set_value(opti, p, [1, 2])
julia> ca.set_value(opti, p[2], 5)
julia> ca.value(opti, p)
2-element Vector{Float64}:
 1.0
 5.0
julia> try
           ca.set_value(opti, x, 1)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You cannot set a value for a variable. Did you mean 'set_initial'?
julia> ca.set_value(opti, [p == 7])
julia> ca.value(opti, p)
2-element Vector{Float64}:
 7.0
 7.0

See also
set_initial, value_parameters

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

Definition at line 181 of file optistack.cpp.

181  {
182  try {
183  (*this)->set_value(x, v);
184  } catch(std::exception& e) {
185  THROW_ERROR("set_value", e.what());
186  }
187 }

References casadi::Opti::x().

◆ set_value() [2/2]

void casadi::Opti::set_value ( const std::vector< MX > &  assignments)
inherited

Every parameter that appears in the problem must have a value before solve(); the value stays until changed, so re-solving with new data only needs set_value() and solve(). x may be a parameter, a slice, or a linear mapping of parameters. Decision variables are refused with a hint to use set_initial(). The list form accepts assignment expressions par==value, as returned by value_parameters(). Calling this method invalidates value() of variables until the next solve().

Parameters
xParameter (or linear mapping of parameters)
vNumerical value; scalars are broadcast

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter(2)
>>> opti.set_value(p, [1, 2])
>>> opti.set_value(p[1], 5)
>>> opti.value(p)
array([1., 5.])
>>> try:
...   opti.set_value(x, 1)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You cannot set a value for a variable. Did you mean 'set_initial'?
>>> opti.set_value([p==7])
>>> opti.value(p)
array([7., 7.])

>> opti = Opti(); x = opti.variable(); p = opti.parameter(2);
>> opti.set_value(p, [1; 2]); opti.set_value(p(2), 5); disp(opti.value(p)')
1 5
>> try, opti.set_value(x, 1); catch e, disp(contains(e.message, 'mean ''set_initial''')); end
1
>> opti.set_value({p==7}); disp(opti.value(p)')
7 7

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti, 2);
julia> ca.set_value(opti, p, [1, 2])
julia> ca.set_value(opti, p[2], 5)
julia> ca.value(opti, p)
2-element Vector{Float64}:
 1.0
 5.0
julia> try
           ca.set_value(opti, x, 1)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You cannot set a value for a variable. Did you mean 'set_initial'?
julia> ca.set_value(opti, [p == 7])
julia> ca.value(opti, p)
2-element Vector{Float64}:
 7.0
 7.0

See also
set_initial, value_parameters

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

Definition at line 205 of file optistack.cpp.

205  {
206  try {
207  (*this)->set_value(assignments);
208  } catch(std::exception& e) {
209  THROW_ERROR("set_value", e.what());
210  }
211 }

◆ show_infeasibilities()

void casadi::OptiAdvanced::show_infeasibilities ( double  tol = 0,
const Dict &  opts = Dict() 
) const

For every row of g whose violation max(g-ubg, lbg-g) is at least tol, prints the bounds, the value, the violation and the description of the constraint (also in scaled units when scaling is active). Requires a solve; typically called after an infeasible solve through opti.debug.

Parameters
tolViolation threshold (default 0, which also lists rounding-level violations)
optsPassed to g_describe

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize(x**2)
>>> opti.subject_to(x >= 1)
>>> opti.subject_to(x <= -1)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   pass
>>> opti.debug.show_infeasibilities(1e-6)
Violated constraints (tol 1e-06), in order of declaration:
------- i = 0/2 ------
1 <= ... <= inf (viol ...)
Opti constraint of shape 1x1, called from ...
------- i = 1/2 ------
-inf <= ... <= -1 (viol ...)
Opti constraint of shape 1x1, called from ...

>> opti = Opti(); x = opti.variable(); opti.minimize(x^2);
>> opti.subject_to(x >= 1); opti.subject_to(x <= -1);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, end
>> opti.debug.show_infeasibilities(1e-6)
Violated constraints (tol 1e-06), in order of declaration:
------- i = 1/2 ------
1 <= ... <= inf (viol ...)
Opti constraint of shape 1x1, called from ...
------- i = 2/2 ------
-inf <= ... <= -1 (viol ...)
Opti constraint of shape 1x1, called from ...

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, x^2)
julia> ca.subject_to(opti, x >= 1)
julia> ca.subject_to(opti, x <= -1)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
       end
julia> ca.show_infeasibilities(ca.debug(opti), 1e-6)
Violated constraints (tol 1e-06), in order of declaration:
------- i = 0/2 ------
1 <= ... <= inf (viol ...)
Opti constraint of shape 1x1, called from ...
------- i = 1/2 ------
-inf <= ... <= -1 (viol ...)
Opti constraint of shape 1x1, called from ...

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

Definition at line 671 of file optistack.cpp.

671  {
672  try {
673  (*this)->show_infeasibilities(tol, opts);
674  } catch(std::exception& e) {
675  THROW_ERROR("show_infeasibilities", e.what());
676  }
677 }

◆ solve()

OptiSol casadi::Opti::solve ( )
inherited

Builds (or reuses) the solver, evaluates the bounds for the current parameter values, runs the solver from the current initial guess and returns an OptiSol snapshot. Raises an error when the solver does not report success (including iteration or time limits, see solve_limited()); the latest iterate then remains available through opti.debug.value() and opti.value(). Calling solve() again without changing anything repeats the same solve from the same initial guess.

Returns
OptiSol copy of the problem and its solution

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize((x-1)**6)
>>> opti.solver("ipopt", {"print_time": False},
...             {"print_level": 0, "max_iter": 2, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print("Solver failed" in str(e), "'Maximum_Iterations_Exceeded'" in str(e))
True True
>>> opti.debug.value(x), opti.return_status()
(0.36, 'Maximum_Iterations_Exceeded')
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> sol.value(x), sol.stats()["success"]
(1.0, True)

>> opti = Opti(); x = opti.variable(); opti.minimize((x-1)^6);
>> ipopt = struct('print_level', 0, 'max_iter', 2, 'sb', 'yes');
>> opti.solver('ipopt', struct('print_time', false), ipopt);
>> try, opti.solve(); catch e, disp(contains(e.message, 'Maximum_Iterations_Exceeded')); end
1
>> opti.debug.value(x), opti.return_status()
0.36
Maximum_Iterations_Exceeded
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); s = sol.stats(); disp(sol.value(x)), disp(s.success)
1.0
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, (x - 1)^6)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "max_iter" => 2, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           msg = sprint(showerror, e)
           println(occursin("Solver failed", msg), " ",
                   occursin("'Maximum_Iterations_Exceeded'", msg))
       end
true true
julia> ca.value(ca.debug(opti), x), ca.return_status(opti)
(0.36, "Maximum_Iterations_Exceeded")
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(sol, x), ca.stats(sol)["success"]
(1.0, true)

See also
solve_limited, OptiSol, stats, return_status

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

Definition at line 213 of file optistack.cpp.

213  {
214  try {
215  return (*this)->solve(false);
216  } catch(std::exception& e) {
217  THROW_ERROR("solve", e.what());
218  }
219 }

◆ solve_actual()

DMDict casadi::OptiAdvanced::solve_actual ( const DMDict &  args)

Definition at line 686 of file optistack.cpp.

686  {
687  try {
688  return (*this)->solve_actual(args);
689  } catch(std::exception& e) {
690  THROW_ERROR("solve_actual", e.what());
691  }
692 }

◆ solve_limited()

OptiSol casadi::Opti::solve_limited ( )
inherited

Same as solve(), but does not raise when the solver stopped because of an iteration or time limit (unified_return_status "SOLVER_RET_LIMITED"); other failures such as infeasibility still raise.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize((x-1)**6)
>>> opti.solver("ipopt", {"print_time": False},
...             {"print_level": 0, "max_iter": 2, "sb": "yes"})
>>> sol = opti.solve_limited()
>>> sol.stats()["unified_return_status"], sol.value(x)
('SOLVER_RET_LIMITED', 0.36)

>> opti = Opti(); x = opti.variable(); opti.minimize((x-1)^6);
>> ipopt = struct('print_level', 0, 'max_iter', 2, 'sb', 'yes');
>> opti.solver('ipopt', struct('print_time', false), ipopt);
>> sol = opti.solve_limited(); s = sol.stats();
>> s.unified_return_status, sol.value(x)
SOLVER_RET_LIMITED
0.36

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, (x - 1)^6)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "max_iter" => 2, "sb" => "yes"))
julia> sol = ca.solve_limited(opti);
julia> ca.stats(sol)["unified_return_status"], ca.value(sol, x)
("SOLVER_RET_LIMITED", 0.36)

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

Definition at line 221 of file optistack.cpp.

221  {
222  try {
223  return (*this)->solve(true);
224  } catch(std::exception& e) {
225  THROW_ERROR("solve", e.what());
226  }
227 }

◆ solve_prepare()

void casadi::OptiAdvanced::solve_prepare ( )

Checks the constraints and parameter values and fills arg() with x0, p, lam_g0, lbg and ubg. solve_actual() then runs the solver on such a dict, and res() stores its result so that value() works. Together they allow custom solver invocations.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize((x-p)**2)
>>> opti.subject_to(x <= 1)
>>> opti.set_value(p, 3)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> d = opti.debug
>>> d.solve_prepare()
>>> d.arg()
{'lam_g0': DM(0), 'lbg': DM(-inf), 'p': DM(3), 'ubg': DM(1), 'x0': DM(0)}
>>> r = d.solve_actual(d.arg())
>>> d.res(r)
>>> d.value(x), sorted(d.res().keys())
(1.0, ['f', 'g', 'lam_g', 'lam_p', 'lam_x', 'x'])

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.minimize((x-p)^2); opti.subject_to(x <= 1); opti.set_value(p, 3);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); d = opti.debug; d.solve_prepare();
>> a = d.arg(); disp(fieldnames(a)'), disp(a.lbg), disp(a.ubg), disp(a.x0)
{'lam_g0'} {'lbg'} {'p'} {'ubg'} {'x0'}
-inf
1
0
>> r = d.solve_actual(d.arg()); d.res(r);
>> d.value(x), sort(fieldnames(d.res()))'
1
{'f'} {'g'} {'lam_g'} {'lam_p'} {'lam_x'} {'x'}

julia> opti = ca.Opti();
julia> x = opti.variable();
julia> p = opti.parameter();
julia> opti.minimize((x - p)^2)
julia> opti.subject_to(x <= 1)
julia> opti.set_value(p, 3)
julia> opti.solver("ipopt", Dict("print_time" => false), Dict("print_level" => 0, "sb" => "yes"))
julia> sol = opti.solve();
julia> d = opti.debug;
julia> ca.solve_prepare(d)
julia> sort(collect(ca.arg(d)), by=first)
5-element Vector{Pair{String, DM}}:
 "lam_g0" => 0
    "lbg" => -inf
      "p" => 3
    "ubg" => 1
     "x0" => 0
julia> r = ca.solve_actual(d, ca.arg(d));
julia> ca.res(d, r)
julia> ca.value(d, x), sort(collect(keys(ca.res(d))))
(1.0, ["f", "g", "lam_g", "lam_p", "lam_x", "x"])

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

Definition at line 679 of file optistack.cpp.

679  {
680  try {
681  (*this)->solve_prepare();
682  } catch(std::exception& e) {
683  THROW_ERROR("solve_prepare", e.what());
684  }
685 }

◆ solved()

bool casadi::OptiAdvanced::solved ( ) const

Definition at line 828 of file optistack.cpp.

828  {
829  try {
830  return (*this)->solved();
831  } catch(std::exception& e) {
832  THROW_ERROR("solved", e.what());
833  }
834 }

Referenced by casadi::Opti::disp().

◆ solver()

void casadi::Opti::solver ( const std::string &  solver,
const Dict &  plugin_options = Dict(),
const Dict &  solver_options = Dict() 
)
inherited

Must be called before solve(). The solver is (re)constructed lazily at the next solve() when this method or the problem structure changed.

Parameters
solverName of an nlpsol plugin ("ipopt", "sqpmethod", "bonmin", ...) or, for a "conic" Opti, of a qpsol plugin ("qrqp", "qpoases", "osqp", ...)
plugin_optionsDict passed as-is to nlpsol/qpsol: CasADi-level options such as "print_time", "expand", "detect_simple_bounds", "error_on_fail", "iteration_callback", and plugin options that are registered as CasADi options (e.g. "qpsol" and "print_iteration" of sqpmethod, "print_iter" of qrqp)
solver_optionsDict of the back-end's native options; it is nested under the key solver, so {"max_iter": 50} here equals {"ipopt": {"max_iter": 50}} in plugin_options. Opti also sets the nlpsol options "equality" and "discrete" unless given explicitly.

No stability is guaranteed for option names; they belong to the plugins.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize((x-2)**2)
>>> try:
...   opti.solve()
... except Exception as e:
...   print("You must call 'solver' on the Opti stack" in str(e))
True
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> opti.solve().value(x)
2.0
>>> opti.solver("sqpmethod", {"print_time": False, "print_header": False,
...   "print_iteration": False, "print_status": False, "qpsol": "qrqp",
...   "qpsol_options": {"print_iter": False, "print_header": False, "print_info": False}})
>>> opti.solve().value(x)
2.0

>> opti = Opti(); x = opti.variable(); opti.minimize((x-2)^2);
>> try, opti.solve(); catch e, disp(contains(e.message, 'You must call ''solver''')); end
1
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); disp(sol.value(x))
2
>> qp = struct('print_iter', false, 'print_header', false, 'print_info', false);
>> opts = struct('print_time', false, 'print_header', false, 'print_iteration', false);
>> opts.print_status = false; opts.qpsol = 'qrqp'; opts.qpsol_options = qp;
>> opti.solver('sqpmethod', opts); sol = opti.solve(); disp(sol.value(x))
2

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, (x - 2)^2)
julia> try
           ca.solve(opti)
       catch e
           println(occursin("You must call 'solver' on the Opti stack", sprint(showerror, e)))
       end
true
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> ca.value(ca.solve(opti), x)
2.0
julia> qp_opts = Dict("print_iter" => false, "print_header" => false, "print_info" => false);
julia> ca.solver(opti, "sqpmethod", Dict("print_time" => false, "print_header" => false,
           "print_iteration" => false, "print_status" => false, "qpsol" => "qrqp",
           "qpsol_options" => qp_opts))
julia> ca.value(ca.solve(opti), x)
2.0

See also
nlpsol, qpsol, solve

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

Definition at line 155 of file optistack.cpp.

157  {
158  try {
159  (*this)->solver(solver, plugin_options, solver_options);
160  } catch(std::exception& e) {
161  THROW_ERROR("solver", e.what());
162  }
163 }
void solver(const std::string &solver, const Dict &plugin_options=Dict(), const Dict &solver_options=Dict())
Select the numerical solver and its options.
Definition: optistack.cpp:155

◆ solver_dirty()

bool casadi::OptiAdvanced::solver_dirty ( ) const

Definition at line 812 of file optistack.cpp.

812  {
813  try {
814  return (*this)->solver_dirty();
815  } catch(std::exception& e) {
816  THROW_ERROR("solver_dirty", e.what());
817  }
818 }

Referenced by casadi::Opti::disp().

◆ stats()

Dict casadi::Opti::stats ( ) const
inherited

The dict returned by the nlpsol/qpsol plugin, passed as-is: always "success", "return_status" and "unified_return_status", plus plugin-specific entries such as "iter_count". Raises an error before the first solve(). No stability is guaranteed for the plugin-specific entries.

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize((x-1)**2)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> s = sol.stats()
>>> s["success"], s["return_status"], s["unified_return_status"], s["iter_count"]
(True, 'Solve_Succeeded', 'SOLVER_RET_SUCCESS', 1)

>> opti = Opti(); x = opti.variable(); opti.minimize((x-1)^2);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); s = sol.stats();
>> s.success, s.return_status, s.unified_return_status, s.iter_count
1
Solve_Succeeded
SOLVER_RET_SUCCESS
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.minimize(opti, (x - 1)^2)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> s = ca.stats(sol);
julia> s["success"], s["return_status"], s["unified_return_status"], s["iter_count"]
(true, "Solve_Succeeded", "SOLVER_RET_SUCCESS", 1)

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

Definition at line 262 of file optistack.cpp.

262  {
263  try {
264  return (*this)->stats();
265  } catch(std::exception& e) {
266  THROW_ERROR("stats", e.what());
267  }
268 }

Referenced by casadi::OptiSol::stats().

◆ subject_to() [1/5]

void casadi::Opti::subject_to ( )
inherited

Removes every constraint added so far, including their dual variables, so the problem can be restated (typical when the constraint set changes between solves). The objective, variables, parameters, values and initial guesses are kept.

>>> opti = Opti()
>>> x = opti.variable()
>>> con = x >= 1
>>> opti.subject_to(con)
>>> opti.minimize(x**2)
>>> opti.ng
1
>>> opti.subject_to()
>>> opti.ng
0
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> try:
...   sol.value(opti.dual(con))
... except Exception as e:
...   print(str(e).splitlines()[-2])
This expression has a dual for a constraint that is not given to Opti:

>> opti = Opti(); x = opti.variable(); con = x >= 1;
>> opti.subject_to(con); opti.minimize(x^2); disp(opti.ng)
1
>> opti.subject_to(); disp(opti.ng)
0
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> try, sol.value(opti.dual(con)); catch e, disp(contains(e.message, 'not given')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> con = x >= 1;
julia> ca.subject_to(opti, con)
julia> ca.minimize(opti, x^2)
julia> ca.ng(opti)
1
julia> ca.subject_to(opti)
julia> ca.ng(opti)
0
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> try
           ca.value(sol, ca.dual(opti, con))
       catch e
           println(split(sprint(showerror, e), "\n")[end-1])
       end
This expression has a dual for a constraint that is not given to Opti:

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

Definition at line 146 of file optistack.cpp.

146  {
147  try {
148  (*this)->subject_to();
149  } catch(std::exception& e) {
150  THROW_ERROR("subject_to", e.what());
151  }
152 }

Referenced by casadi::Opti::subject_to().

◆ subject_to() [2/5]

void casadi::Opti::subject_to ( const MX &  g,
const Dict &  options = Dict() 
)
inherited

g is a comparison expression built with ==, <=, >= (< and > behave as <= and >=). Vector expressions give one constraint per element; both sides may be vectors of the same shape or a scalar that is broadcast. Each call appends to the constraint set.

Recognized forms and how they reach the solver:

  • g(x,p) <= b(p), b(p) <= g(x,p), g(x,p) == b(p): one side free of decision variables becomes the bound (lbg/ubg) and the other side the constraint expression g.
  • lb(p) <= (g(x,p) <= ub(p)): a chained inequality whose outer sides are free of decision variables becomes a double-bounded constraint lb <= g <= ub (one row). Both bounds may be vectors. In Python the inner comparison must be parenthesized, because the plain chain 0 <= x <= 1 asks for the truth value of an MX and raises an error; bounded() builds the same expression.
  • g1(x,p) <= g2(x,p), g1(x,p) == g2(x,p): both sides depend on variables, giving g1-g2 <= 0 or g1-g2 == 0. A double-bounded constraint on a pure decision variable, such as -1 <= (x <= 1), is still passed as a constraint row; set the nlpsol option "detect_simple_bounds" in solver() to have it moved to the variable bounds lbx/ubx.

Errors: a constant comparison, an empty or fully sparse expression, a symbol not declared by this instance, and dual variables all raise an error immediately. A square matrix comparison A >= B is interpreted as a semidefinite constraint, which "nlp" does not support: vectorize the matrix with vec(A) for an elementwise constraint. An expression without comparison operator is accepted but rejected at solve().

Parameters
gConstraint expression, or a list of them (each added in turn)
linear_scaleScalar or same-shape matrix; the solver sees g divided by it
optionsDict with optional entries "meta" (dict stored in the user_dict of the constraint) and "stacktrace"; any other key raises an error

>>> opti = Opti()
>>> x = opti.variable(3)
>>> y = opti.variable()
>>> p = opti.parameter()
>>> opti.subject_to(x >= 0)
>>> opti.subject_to(x[0] + x[1] == p)
>>> opti.subject_to(-1 <= (y <= 1))
>>> opti.subject_to([y >= x[2], y*x[0] >= 1])
>>> opti.ng
7
>>> print(opti.lbg, opti.ubg)
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>>> try:
...   opti.subject_to(0 <= y <= 1)
... except Exception as e:
...   print("Can only determine truth value of a numeric MX" in str(e))
True
>>> try:
...   opti.subject_to(MX(2) <= 3)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You passed a constant to `subject_to`. You need a symbol to form a constraint.
>>> try:
...   opti.subject_to(MX.sym("w") <= 3)
... except Exception as e:
...   print("MX symbol 'w' of shape 1x1, declared outside of Opti" in str(e))
True

>> opti = Opti(); x = opti.variable(3); y = opti.variable(); p = opti.parameter();
>> opti.subject_to(x >= 0);
>> opti.subject_to(x(1) + x(2) == p);
>> opti.subject_to(-1 <= y <= 1);
>> opti.subject_to({y >= x(3), y*x(1) >= 1});
>> opti.ng
7
>> opti.lbg, opti.ubg
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1)
vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>> try, opti.subject_to(MX(2) <= 3); catch e, disp(contains(e.message, 'a constant')); end
1
>> w = MX.sym('w');
>> try, opti.subject_to(w <= 3); catch e, disp(contains(e.message, 'outside of Opti')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 3);
julia> y = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.subject_to(opti, x >= 0)
julia> ca.subject_to(opti, x[1] + x[2] == p)
julia> ca.subject_to(opti, -1 <= (y <= 1))
julia> ca.subject_to(opti, [y >= x[3], y*x[1] >= 1])
julia> ca.ng(opti)
7
julia> print(ca.lbg(opti), " ", ca.ubg(opti))
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
julia> try
           ca.subject_to(opti, 0 <= y <= 1)
       catch e
           println(typeof(e))
       end
TypeError
julia> try
           ca.subject_to(opti, ca.MX(2) <= 3)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You passed a constant to `subject_to`. You need a symbol to form a constraint.
julia> try
           ca.subject_to(opti, ca.MX.sym("w") <= 3)
       catch e
           msg = "MX symbol 'w' of shape 1x1, declared outside of Opti"
           println(occursin(msg, sprint(showerror, e)))
       end
true

Elementwise constraints on matrices need vec(); options attach metadata:

>>> opti = Opti()
>>> A = opti.variable(2, 2)
>>> opti.subject_to(A >= 0)
>>> opti.minimize(sumsqr(A))
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print("Psd constraints not implemented yet" in str(e))
True
>>> opti.subject_to()
>>> con = vec(A) >= 0
>>> opti.subject_to(con, {"meta": {"label": "nonneg"}})
>>> opti.ng, opti.user_dict(con)["label"]
(4, 'nonneg')

>> opti = Opti(); A = opti.variable(2, 2);
>> opti.subject_to(A >= 0); opti.minimize(sumsqr(A));
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, disp(contains(e.message, 'Psd constraints')); end
1
>> opti.subject_to(); con = vec(A) >= 0;
>> opti.subject_to(con, struct('meta', struct('label', 'nonneg')));
>> d = opti.user_dict(con); fprintf('%d %s\n', opti.ng, d.label)
4 nonneg

julia> opti = ca.Opti();
julia> A = ca.variable(opti, 2, 2);
julia> ca.subject_to(opti, A >= 0)
julia> ca.minimize(opti, ca.sumsqr(A))
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           println(occursin("Psd constraints not implemented yet", sprint(showerror, e)))
       end
true
julia> ca.subject_to(opti)
julia> con = vec(A) >= 0;
julia> ca.subject_to(opti, con, Dict("meta" => Dict("label" => "nonneg")))
julia> ca.ng(opti), ca.user_dict(opti, con)["label"]
(4, "nonneg")

See also
bounded, subject_to(), dual, lbg, ubg, g

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

Definition at line 122 of file optistack.cpp.

122  {
123  try {
124  (*this)->subject_to(g, 1, options);
125  } catch(std::exception& e) {
126  THROW_ERROR("subject_to", e.what());
127  }
128 }
MX g() const
Get all (scalarised) constraint expressions as a column vector.
Definition: optistack.cpp:350

References casadi::Opti::g().

◆ subject_to() [3/5]

void casadi::Opti::subject_to ( const MX &  g,
const DM &  linear_scale,
const Dict &  options = Dict() 
)
inherited

g is a comparison expression built with ==, <=, >= (< and > behave as <= and >=). Vector expressions give one constraint per element; both sides may be vectors of the same shape or a scalar that is broadcast. Each call appends to the constraint set.

Recognized forms and how they reach the solver:

  • g(x,p) <= b(p), b(p) <= g(x,p), g(x,p) == b(p): one side free of decision variables becomes the bound (lbg/ubg) and the other side the constraint expression g.
  • lb(p) <= (g(x,p) <= ub(p)): a chained inequality whose outer sides are free of decision variables becomes a double-bounded constraint lb <= g <= ub (one row). Both bounds may be vectors. In Python the inner comparison must be parenthesized, because the plain chain 0 <= x <= 1 asks for the truth value of an MX and raises an error; bounded() builds the same expression.
  • g1(x,p) <= g2(x,p), g1(x,p) == g2(x,p): both sides depend on variables, giving g1-g2 <= 0 or g1-g2 == 0. A double-bounded constraint on a pure decision variable, such as -1 <= (x <= 1), is still passed as a constraint row; set the nlpsol option "detect_simple_bounds" in solver() to have it moved to the variable bounds lbx/ubx.

Errors: a constant comparison, an empty or fully sparse expression, a symbol not declared by this instance, and dual variables all raise an error immediately. A square matrix comparison A >= B is interpreted as a semidefinite constraint, which "nlp" does not support: vectorize the matrix with vec(A) for an elementwise constraint. An expression without comparison operator is accepted but rejected at solve().

Parameters
gConstraint expression, or a list of them (each added in turn)
linear_scaleScalar or same-shape matrix; the solver sees g divided by it
optionsDict with optional entries "meta" (dict stored in the user_dict of the constraint) and "stacktrace"; any other key raises an error

>>> opti = Opti()
>>> x = opti.variable(3)
>>> y = opti.variable()
>>> p = opti.parameter()
>>> opti.subject_to(x >= 0)
>>> opti.subject_to(x[0] + x[1] == p)
>>> opti.subject_to(-1 <= (y <= 1))
>>> opti.subject_to([y >= x[2], y*x[0] >= 1])
>>> opti.ng
7
>>> print(opti.lbg, opti.ubg)
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>>> try:
...   opti.subject_to(0 <= y <= 1)
... except Exception as e:
...   print("Can only determine truth value of a numeric MX" in str(e))
True
>>> try:
...   opti.subject_to(MX(2) <= 3)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You passed a constant to `subject_to`. You need a symbol to form a constraint.
>>> try:
...   opti.subject_to(MX.sym("w") <= 3)
... except Exception as e:
...   print("MX symbol 'w' of shape 1x1, declared outside of Opti" in str(e))
True

>> opti = Opti(); x = opti.variable(3); y = opti.variable(); p = opti.parameter();
>> opti.subject_to(x >= 0);
>> opti.subject_to(x(1) + x(2) == p);
>> opti.subject_to(-1 <= y <= 1);
>> opti.subject_to({y >= x(3), y*x(1) >= 1});
>> opti.ng
7
>> opti.lbg, opti.ubg
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1)
vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>> try, opti.subject_to(MX(2) <= 3); catch e, disp(contains(e.message, 'a constant')); end
1
>> w = MX.sym('w');
>> try, opti.subject_to(w <= 3); catch e, disp(contains(e.message, 'outside of Opti')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 3);
julia> y = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.subject_to(opti, x >= 0)
julia> ca.subject_to(opti, x[1] + x[2] == p)
julia> ca.subject_to(opti, -1 <= (y <= 1))
julia> ca.subject_to(opti, [y >= x[3], y*x[1] >= 1])
julia> ca.ng(opti)
7
julia> print(ca.lbg(opti), " ", ca.ubg(opti))
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
julia> try
           ca.subject_to(opti, 0 <= y <= 1)
       catch e
           println(typeof(e))
       end
TypeError
julia> try
           ca.subject_to(opti, ca.MX(2) <= 3)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You passed a constant to `subject_to`. You need a symbol to form a constraint.
julia> try
           ca.subject_to(opti, ca.MX.sym("w") <= 3)
       catch e
           msg = "MX symbol 'w' of shape 1x1, declared outside of Opti"
           println(occursin(msg, sprint(showerror, e)))
       end
true

Elementwise constraints on matrices need vec(); options attach metadata:

>>> opti = Opti()
>>> A = opti.variable(2, 2)
>>> opti.subject_to(A >= 0)
>>> opti.minimize(sumsqr(A))
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print("Psd constraints not implemented yet" in str(e))
True
>>> opti.subject_to()
>>> con = vec(A) >= 0
>>> opti.subject_to(con, {"meta": {"label": "nonneg"}})
>>> opti.ng, opti.user_dict(con)["label"]
(4, 'nonneg')

>> opti = Opti(); A = opti.variable(2, 2);
>> opti.subject_to(A >= 0); opti.minimize(sumsqr(A));
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, disp(contains(e.message, 'Psd constraints')); end
1
>> opti.subject_to(); con = vec(A) >= 0;
>> opti.subject_to(con, struct('meta', struct('label', 'nonneg')));
>> d = opti.user_dict(con); fprintf('%d %s\n', opti.ng, d.label)
4 nonneg

julia> opti = ca.Opti();
julia> A = ca.variable(opti, 2, 2);
julia> ca.subject_to(opti, A >= 0)
julia> ca.minimize(opti, ca.sumsqr(A))
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           println(occursin("Psd constraints not implemented yet", sprint(showerror, e)))
       end
true
julia> ca.subject_to(opti)
julia> con = vec(A) >= 0;
julia> ca.subject_to(opti, con, Dict("meta" => Dict("label" => "nonneg")))
julia> ca.ng(opti), ca.user_dict(opti, con)["label"]
(4, "nonneg")

See also
bounded, subject_to(), dual, lbg, ubg, g

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

Definition at line 134 of file optistack.cpp.

134  {
135  try {
136  (*this)->subject_to(g, linear_scale, options);
137  } catch(std::exception& e) {
138  THROW_ERROR("subject_to", e.what());
139  }
140 }

References casadi::Opti::g().

◆ subject_to() [4/5]

void casadi::Opti::subject_to ( const std::vector< MX > &  g,
const Dict &  options = Dict() 
)
inherited

g is a comparison expression built with ==, <=, >= (< and > behave as <= and >=). Vector expressions give one constraint per element; both sides may be vectors of the same shape or a scalar that is broadcast. Each call appends to the constraint set.

Recognized forms and how they reach the solver:

  • g(x,p) <= b(p), b(p) <= g(x,p), g(x,p) == b(p): one side free of decision variables becomes the bound (lbg/ubg) and the other side the constraint expression g.
  • lb(p) <= (g(x,p) <= ub(p)): a chained inequality whose outer sides are free of decision variables becomes a double-bounded constraint lb <= g <= ub (one row). Both bounds may be vectors. In Python the inner comparison must be parenthesized, because the plain chain 0 <= x <= 1 asks for the truth value of an MX and raises an error; bounded() builds the same expression.
  • g1(x,p) <= g2(x,p), g1(x,p) == g2(x,p): both sides depend on variables, giving g1-g2 <= 0 or g1-g2 == 0. A double-bounded constraint on a pure decision variable, such as -1 <= (x <= 1), is still passed as a constraint row; set the nlpsol option "detect_simple_bounds" in solver() to have it moved to the variable bounds lbx/ubx.

Errors: a constant comparison, an empty or fully sparse expression, a symbol not declared by this instance, and dual variables all raise an error immediately. A square matrix comparison A >= B is interpreted as a semidefinite constraint, which "nlp" does not support: vectorize the matrix with vec(A) for an elementwise constraint. An expression without comparison operator is accepted but rejected at solve().

Parameters
gConstraint expression, or a list of them (each added in turn)
linear_scaleScalar or same-shape matrix; the solver sees g divided by it
optionsDict with optional entries "meta" (dict stored in the user_dict of the constraint) and "stacktrace"; any other key raises an error

>>> opti = Opti()
>>> x = opti.variable(3)
>>> y = opti.variable()
>>> p = opti.parameter()
>>> opti.subject_to(x >= 0)
>>> opti.subject_to(x[0] + x[1] == p)
>>> opti.subject_to(-1 <= (y <= 1))
>>> opti.subject_to([y >= x[2], y*x[0] >= 1])
>>> opti.ng
7
>>> print(opti.lbg, opti.ubg)
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>>> try:
...   opti.subject_to(0 <= y <= 1)
... except Exception as e:
...   print("Can only determine truth value of a numeric MX" in str(e))
True
>>> try:
...   opti.subject_to(MX(2) <= 3)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You passed a constant to `subject_to`. You need a symbol to form a constraint.
>>> try:
...   opti.subject_to(MX.sym("w") <= 3)
... except Exception as e:
...   print("MX symbol 'w' of shape 1x1, declared outside of Opti" in str(e))
True

>> opti = Opti(); x = opti.variable(3); y = opti.variable(); p = opti.parameter();
>> opti.subject_to(x >= 0);
>> opti.subject_to(x(1) + x(2) == p);
>> opti.subject_to(-1 <= y <= 1);
>> opti.subject_to({y >= x(3), y*x(1) >= 1});
>> opti.ng
7
>> opti.lbg, opti.ubg
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1)
vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>> try, opti.subject_to(MX(2) <= 3); catch e, disp(contains(e.message, 'a constant')); end
1
>> w = MX.sym('w');
>> try, opti.subject_to(w <= 3); catch e, disp(contains(e.message, 'outside of Opti')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 3);
julia> y = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.subject_to(opti, x >= 0)
julia> ca.subject_to(opti, x[1] + x[2] == p)
julia> ca.subject_to(opti, -1 <= (y <= 1))
julia> ca.subject_to(opti, [y >= x[3], y*x[1] >= 1])
julia> ca.ng(opti)
7
julia> print(ca.lbg(opti), " ", ca.ubg(opti))
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
julia> try
           ca.subject_to(opti, 0 <= y <= 1)
       catch e
           println(typeof(e))
       end
TypeError
julia> try
           ca.subject_to(opti, ca.MX(2) <= 3)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You passed a constant to `subject_to`. You need a symbol to form a constraint.
julia> try
           ca.subject_to(opti, ca.MX.sym("w") <= 3)
       catch e
           msg = "MX symbol 'w' of shape 1x1, declared outside of Opti"
           println(occursin(msg, sprint(showerror, e)))
       end
true

Elementwise constraints on matrices need vec(); options attach metadata:

>>> opti = Opti()
>>> A = opti.variable(2, 2)
>>> opti.subject_to(A >= 0)
>>> opti.minimize(sumsqr(A))
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print("Psd constraints not implemented yet" in str(e))
True
>>> opti.subject_to()
>>> con = vec(A) >= 0
>>> opti.subject_to(con, {"meta": {"label": "nonneg"}})
>>> opti.ng, opti.user_dict(con)["label"]
(4, 'nonneg')

>> opti = Opti(); A = opti.variable(2, 2);
>> opti.subject_to(A >= 0); opti.minimize(sumsqr(A));
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, disp(contains(e.message, 'Psd constraints')); end
1
>> opti.subject_to(); con = vec(A) >= 0;
>> opti.subject_to(con, struct('meta', struct('label', 'nonneg')));
>> d = opti.user_dict(con); fprintf('%d %s\n', opti.ng, d.label)
4 nonneg

julia> opti = ca.Opti();
julia> A = ca.variable(opti, 2, 2);
julia> ca.subject_to(opti, A >= 0)
julia> ca.minimize(opti, ca.sumsqr(A))
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           println(occursin("Psd constraints not implemented yet", sprint(showerror, e)))
       end
true
julia> ca.subject_to(opti)
julia> con = vec(A) >= 0;
julia> ca.subject_to(opti, con, Dict("meta" => Dict("label" => "nonneg")))
julia> ca.ng(opti), ca.user_dict(opti, con)["label"]
(4, "nonneg")

See also
bounded, subject_to(), dual, lbg, ubg, g

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

Definition at line 130 of file optistack.cpp.

130  {
131  for (const auto& gs : g) subject_to(gs, 1, options);
132 }
void subject_to()
Clear all constraints.
Definition: optistack.cpp:146

References casadi::Opti::g(), and casadi::Opti::subject_to().

◆ subject_to() [5/5]

void casadi::Opti::subject_to ( const std::vector< MX > &  g,
const DM &  linear_scale,
const Dict &  options = Dict() 
)
inherited

g is a comparison expression built with ==, <=, >= (< and > behave as <= and >=). Vector expressions give one constraint per element; both sides may be vectors of the same shape or a scalar that is broadcast. Each call appends to the constraint set.

Recognized forms and how they reach the solver:

  • g(x,p) <= b(p), b(p) <= g(x,p), g(x,p) == b(p): one side free of decision variables becomes the bound (lbg/ubg) and the other side the constraint expression g.
  • lb(p) <= (g(x,p) <= ub(p)): a chained inequality whose outer sides are free of decision variables becomes a double-bounded constraint lb <= g <= ub (one row). Both bounds may be vectors. In Python the inner comparison must be parenthesized, because the plain chain 0 <= x <= 1 asks for the truth value of an MX and raises an error; bounded() builds the same expression.
  • g1(x,p) <= g2(x,p), g1(x,p) == g2(x,p): both sides depend on variables, giving g1-g2 <= 0 or g1-g2 == 0. A double-bounded constraint on a pure decision variable, such as -1 <= (x <= 1), is still passed as a constraint row; set the nlpsol option "detect_simple_bounds" in solver() to have it moved to the variable bounds lbx/ubx.

Errors: a constant comparison, an empty or fully sparse expression, a symbol not declared by this instance, and dual variables all raise an error immediately. A square matrix comparison A >= B is interpreted as a semidefinite constraint, which "nlp" does not support: vectorize the matrix with vec(A) for an elementwise constraint. An expression without comparison operator is accepted but rejected at solve().

Parameters
gConstraint expression, or a list of them (each added in turn)
linear_scaleScalar or same-shape matrix; the solver sees g divided by it
optionsDict with optional entries "meta" (dict stored in the user_dict of the constraint) and "stacktrace"; any other key raises an error

>>> opti = Opti()
>>> x = opti.variable(3)
>>> y = opti.variable()
>>> p = opti.parameter()
>>> opti.subject_to(x >= 0)
>>> opti.subject_to(x[0] + x[1] == p)
>>> opti.subject_to(-1 <= (y <= 1))
>>> opti.subject_to([y >= x[2], y*x[0] >= 1])
>>> opti.ng
7
>>> print(opti.lbg, opti.ubg)
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>>> try:
...   opti.subject_to(0 <= y <= 1)
... except Exception as e:
...   print("Can only determine truth value of a numeric MX" in str(e))
True
>>> try:
...   opti.subject_to(MX(2) <= 3)
... except Exception as e:
...   print(str(e).splitlines()[-1])
You passed a constant to `subject_to`. You need a symbol to form a constraint.
>>> try:
...   opti.subject_to(MX.sym("w") <= 3)
... except Exception as e:
...   print("MX symbol 'w' of shape 1x1, declared outside of Opti" in str(e))
True

>> opti = Opti(); x = opti.variable(3); y = opti.variable(); p = opti.parameter();
>> opti.subject_to(x >= 0);
>> opti.subject_to(x(1) + x(2) == p);
>> opti.subject_to(-1 <= y <= 1);
>> opti.subject_to({y >= x(3), y*x(1) >= 1});
>> opti.ng
7
>> opti.lbg, opti.ubg
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1)
vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
>> try, opti.subject_to(MX(2) <= 3); catch e, disp(contains(e.message, 'a constant')); end
1
>> w = MX.sym('w');
>> try, opti.subject_to(w <= 3); catch e, disp(contains(e.message, 'outside of Opti')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 3);
julia> y = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.subject_to(opti, x >= 0)
julia> ca.subject_to(opti, x[1] + x[2] == p)
julia> ca.subject_to(opti, -1 <= (y <= 1))
julia> ca.subject_to(opti, [y >= x[3], y*x[1] >= 1])
julia> ca.ng(opti)
7
julia> print(ca.lbg(opti), " ", ca.ubg(opti))
vertcat(zeros(3x1), opti..._p_1, -1, -inf, 1) vertcat(inf(3x1), opti..._p_1, 1, 0, inf)
julia> try
           ca.subject_to(opti, 0 <= y <= 1)
       catch e
           println(typeof(e))
       end
TypeError
julia> try
           ca.subject_to(opti, ca.MX(2) <= 3)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You passed a constant to `subject_to`. You need a symbol to form a constraint.
julia> try
           ca.subject_to(opti, ca.MX.sym("w") <= 3)
       catch e
           msg = "MX symbol 'w' of shape 1x1, declared outside of Opti"
           println(occursin(msg, sprint(showerror, e)))
       end
true

Elementwise constraints on matrices need vec(); options attach metadata:

>>> opti = Opti()
>>> A = opti.variable(2, 2)
>>> opti.subject_to(A >= 0)
>>> opti.minimize(sumsqr(A))
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> try:
...   opti.solve()
... except Exception as e:
...   print("Psd constraints not implemented yet" in str(e))
True
>>> opti.subject_to()
>>> con = vec(A) >= 0
>>> opti.subject_to(con, {"meta": {"label": "nonneg"}})
>>> opti.ng, opti.user_dict(con)["label"]
(4, 'nonneg')

>> opti = Opti(); A = opti.variable(2, 2);
>> opti.subject_to(A >= 0); opti.minimize(sumsqr(A));
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> try, opti.solve(); catch e, disp(contains(e.message, 'Psd constraints')); end
1
>> opti.subject_to(); con = vec(A) >= 0;
>> opti.subject_to(con, struct('meta', struct('label', 'nonneg')));
>> d = opti.user_dict(con); fprintf('%d %s\n', opti.ng, d.label)
4 nonneg

julia> opti = ca.Opti();
julia> A = ca.variable(opti, 2, 2);
julia> ca.subject_to(opti, A >= 0)
julia> ca.minimize(opti, ca.sumsqr(A))
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> try
           ca.solve(opti)
       catch e
           println(occursin("Psd constraints not implemented yet", sprint(showerror, e)))
       end
true
julia> ca.subject_to(opti)
julia> con = vec(A) >= 0;
julia> ca.subject_to(opti, con, Dict("meta" => Dict("label" => "nonneg")))
julia> ca.ng(opti), ca.user_dict(opti, con)["label"]
(4, "nonneg")

See also
bounded, subject_to(), dual, lbg, ubg, g

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

Definition at line 142 of file optistack.cpp.

142  {
143  for (const auto& gs : g) subject_to(gs, linear_scale, options);
144 }

References casadi::Opti::g(), and casadi::Opti::subject_to().

◆ swap()

Definition at line 105 of file generic_shared_impl.hpp.

131  {
132  GenericShared<Shared, Internal> temp = *this;
133  *this = other;
134  other = temp;
135  }

◆ symvar() [1/3]

std::vector< MX > casadi::OptiAdvanced::symvar ( ) const

Without argument: every symbol created so far (variables, parameters and the dual variables of constraints), whether or not it appears in the problem. With expr: the symbols of this instance that expr depends on, optionally filtered by type. The result is ordered by creation.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> y = opti.variable()
>>> print(opti.debug.symvar())
[MX(opti..._x_1), MX(opti..._p_1), MX(opti..._x_2)]
>>> print(opti.debug.symvar(y*p + 1), opti.debug.symvar(y*p, OPTI_PAR))
[MX(opti..._p_1), MX(opti..._x_2)] [MX(opti..._p_1)]

>> opti = Opti(); x = opti.variable(); p = opti.parameter(); y = opti.variable();
>> sv = opti.debug.symvar(); disp(numel(sv)), disp(sv{2})
3
opti..._p_1
>> sv = opti.debug.symvar(y*p + 1); disp(sv{1}), disp(sv{2})
opti..._p_1
opti..._x_2
>> sv = opti.debug.symvar(y*p, OPTI_PAR); disp(numel(sv)), disp(sv{1})
1
opti..._p_1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> y = ca.variable(opti);
julia> d = ca.debug(opti);
julia> print(ca.symvar(d))
MX[opti..._x_1, opti..._p_1, opti..._x_2]
julia> print(ca.symvar(d, y*p + 1), " ", ca.symvar(d, y*p, ca.OPTI_PAR))
MX[opti..._p_1, opti..._x_2] MX[opti..._p_1]

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

Definition at line 520 of file optistack.cpp.

520  {
521  try {
522  return (*this)->symvar();
523  } catch(std::exception& e) {
524  THROW_ERROR("symvar", e.what());
525  }
526 }

◆ symvar() [2/3]

std::vector< MX > casadi::OptiAdvanced::symvar ( const MX &  expr) const

Without argument: every symbol created so far (variables, parameters and the dual variables of constraints), whether or not it appears in the problem. With expr: the symbols of this instance that expr depends on, optionally filtered by type. The result is ordered by creation.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> y = opti.variable()
>>> print(opti.debug.symvar())
[MX(opti..._x_1), MX(opti..._p_1), MX(opti..._x_2)]
>>> print(opti.debug.symvar(y*p + 1), opti.debug.symvar(y*p, OPTI_PAR))
[MX(opti..._p_1), MX(opti..._x_2)] [MX(opti..._p_1)]

>> opti = Opti(); x = opti.variable(); p = opti.parameter(); y = opti.variable();
>> sv = opti.debug.symvar(); disp(numel(sv)), disp(sv{2})
3
opti..._p_1
>> sv = opti.debug.symvar(y*p + 1); disp(sv{1}), disp(sv{2})
opti..._p_1
opti..._x_2
>> sv = opti.debug.symvar(y*p, OPTI_PAR); disp(numel(sv)), disp(sv{1})
1
opti..._p_1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> y = ca.variable(opti);
julia> d = ca.debug(opti);
julia> print(ca.symvar(d))
MX[opti..._x_1, opti..._p_1, opti..._x_2]
julia> print(ca.symvar(d, y*p + 1), " ", ca.symvar(d, y*p, ca.OPTI_PAR))
MX[opti..._p_1, opti..._x_2] MX[opti..._p_1]

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

Definition at line 528 of file optistack.cpp.

528  {
529  try {
530  return (*this)->symvar(expr);
531  } catch(std::exception& e) {
532  THROW_ERROR("symvar", e.what());
533  }
534 }

◆ symvar() [3/3]

std::vector< MX > casadi::OptiAdvanced::symvar ( const MX &  expr,
VariableType  type 
) const

Without argument: every symbol created so far (variables, parameters and the dual variables of constraints), whether or not it appears in the problem. With expr: the symbols of this instance that expr depends on, optionally filtered by type. The result is ordered by creation.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> y = opti.variable()
>>> print(opti.debug.symvar())
[MX(opti..._x_1), MX(opti..._p_1), MX(opti..._x_2)]
>>> print(opti.debug.symvar(y*p + 1), opti.debug.symvar(y*p, OPTI_PAR))
[MX(opti..._p_1), MX(opti..._x_2)] [MX(opti..._p_1)]

>> opti = Opti(); x = opti.variable(); p = opti.parameter(); y = opti.variable();
>> sv = opti.debug.symvar(); disp(numel(sv)), disp(sv{2})
3
opti..._p_1
>> sv = opti.debug.symvar(y*p + 1); disp(sv{1}), disp(sv{2})
opti..._p_1
opti..._x_2
>> sv = opti.debug.symvar(y*p, OPTI_PAR); disp(numel(sv)), disp(sv{1})
1
opti..._p_1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> y = ca.variable(opti);
julia> d = ca.debug(opti);
julia> print(ca.symvar(d))
MX[opti..._x_1, opti..._p_1, opti..._x_2]
julia> print(ca.symvar(d, y*p + 1), " ", ca.symvar(d, y*p, ca.OPTI_PAR))
MX[opti..._p_1, opti..._x_2] MX[opti..._p_1]

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

Definition at line 536 of file optistack.cpp.

536  {
537  try {
538  return (*this)->symvar(expr, type);
539  } catch(std::exception& e) {
540  THROW_ERROR("symvar", e.what());
541  }
542 }

◆ to_function() [1/3]

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

Definition at line 441 of file optistack.cpp.

445  {
446  std::vector<MX> ex_in(name_in.size()), ex_out(name_out.size());
447  for (auto&& i : dict) {
448  std::vector<std::string>::const_iterator it;
449  it=find(name_in.begin(), name_in.end(), i.first);
450  if (it!=name_in.end()) {
451  // Input expression
452  ex_in[it-name_in.begin()] = i.second;
453  } else {
454  it=find(name_out.begin(), name_out.end(), i.first);
455  if (it!=name_out.end()) {
456  // Output expression
457  ex_out[it-name_out.begin()] = i.second;
458  } else {
459  // Neither
460  casadi_error("Unknown dictionary entry: '" + i.first + "'");
461  }
462  }
463  }
464  return to_function(name, ex_in, ex_out, name_in, name_out, opts);
465 }
Function to_function(const std::string &name, const std::vector< MX > &args, const std::vector< MX > &res, const Dict &opts=Dict())
Create a CasADi Function from the Opti solver.
Definition: optistack.cpp:435
std::vector< casadi_int > find(const std::vector< T > &v)
find nonzeros

References casadi::find(), and casadi::Opti::to_function().

◆ to_function() [2/3]

Function casadi::Opti::to_function ( const std::string &  name,
const std::vector< MX > &  args,
const std::vector< MX > &  res,
const Dict &  opts = Dict() 
)
inherited

Packs bounds evaluation, the solver call and the evaluation of res into one Function, which is much cheaper to call repeatedly than set_value/solve/value. Inputs corresponding to parameters supply their values; inputs corresponding to variables or dual variables supply the initial guess; anything not listed keeps the value stored in the Opti at the time of the call. Outputs are evaluated at the solution.

A solver failure does not raise by default: the last iterate is returned and the Function's stats() report success False. Pass "error_on_fail": True in the plugin_options of solver() to raise instead. Function options in opts are applied to the result; the entry "helper_options" is applied to the internal evaluation function.

Parameters
nameName of the resulting Function
argsList of parameters, decision variables and dual variables (or vertcat of them); each must be purely symbolic and independent, else an error is raised
resList of expressions evaluated at the solution
name_inOptional input names (same length as args)
name_outOptional output names (same length as res)
optsFunction options

>>> opti = Opti()
>>> x = opti.variable()
>>> y = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize((x-p)**2 + (y-x)**2)
>>> opti.subject_to(x >= 0)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> F = opti.to_function("F", [p, x], [vertcat(x, y), opti.lam_g],
...                      ["p", "x0"], ["xy", "lam"])
>>> F
Function(F:(p,x0)->(xy[2],lam) MXFunction)
>>> r = F(p=2, x0=1)
>>> r["xy"], r["lam"]
(DM([2, 2]), DM(0.0000))
>>> F.stats()["success"]
True
>>> F = opti.to_function("F", {"p": p, "x": x}, ["p"], ["x"])
>>> F(3)
DM(3)
>>> try:
...   opti.to_function("F", [p+1], [x])
... except Exception as e:
...   print(str(e).splitlines()[-1])
Argument 0 is not purely symbolic.

>> opti = Opti(); x = opti.variable(); y = opti.variable(); p = opti.parameter();
>> opti.minimize((x-p)^2 + (y-x)^2); opti.subject_to(x >= 0);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> F = opti.to_function('F', {p, x}, {vertcat(x, y), opti.lam_g}, {'p', 'x0'}, {'xy', 'lam'});
>> F
F:(p,x0)->(xy[2],lam) MXFunction
>> r = F('p', 2, 'x0', 1); disp(r.xy), disp(r.lam)
[2, 2]
0.0000
>> s = F.stats(); disp(s.success)
1
>> F = opti.to_function('F', struct('p', p, 'x', x), {'p'}, {'x'}); disp(F(3))
3
>> try, opti.to_function('F', {p+1}, {x}); catch e, disp(contains(e.message, 'symbolic')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> y = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, (x - p)^2 + (y - x)^2)
julia> ca.subject_to(opti, x >= 0)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> F = ca.to_function(opti, "F", [p, x], [[x; y], ca.lam_g(opti)],
                          ["p", "x0"], ["xy", "lam"])
Function(F:(p,x0)->(xy[2],lam) MXFunction)
julia> r = F(p=2, x0=1);
julia> r["xy"], r["lam"]
([2, 2], 0.0000)
julia> ca.stats(F)["success"]
true
julia> F = ca.to_function(opti, "F", Dict("p" => p, "x" => x), ["p"], ["x"]);
julia> F(3)
DM(3)
julia> try
           ca.to_function(opti, "F", [p + 1], [x])
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Argument 0 is not purely symbolic.

See also
nlpsol

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

Definition at line 435 of file optistack.cpp.

437  {
438  return to_function(name, args, res, {}, {}, opts);
439 }

Referenced by casadi::Opti::to_function(), and casadi::OptiNode::to_function().

◆ to_function() [3/3]

Function casadi::Opti::to_function ( const std::string &  name,
const std::vector< MX > &  args,
const std::vector< MX > &  res,
const std::vector< std::string > &  name_in,
const std::vector< std::string > &  name_out,
const Dict &  opts = Dict() 
)
inherited

Packs bounds evaluation, the solver call and the evaluation of res into one Function, which is much cheaper to call repeatedly than set_value/solve/value. Inputs corresponding to parameters supply their values; inputs corresponding to variables or dual variables supply the initial guess; anything not listed keeps the value stored in the Opti at the time of the call. Outputs are evaluated at the solution.

A solver failure does not raise by default: the last iterate is returned and the Function's stats() report success False. Pass "error_on_fail": True in the plugin_options of solver() to raise instead. Function options in opts are applied to the result; the entry "helper_options" is applied to the internal evaluation function.

Parameters
nameName of the resulting Function
argsList of parameters, decision variables and dual variables (or vertcat of them); each must be purely symbolic and independent, else an error is raised
resList of expressions evaluated at the solution
name_inOptional input names (same length as args)
name_outOptional output names (same length as res)
optsFunction options

>>> opti = Opti()
>>> x = opti.variable()
>>> y = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize((x-p)**2 + (y-x)**2)
>>> opti.subject_to(x >= 0)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> F = opti.to_function("F", [p, x], [vertcat(x, y), opti.lam_g],
...                      ["p", "x0"], ["xy", "lam"])
>>> F
Function(F:(p,x0)->(xy[2],lam) MXFunction)
>>> r = F(p=2, x0=1)
>>> r["xy"], r["lam"]
(DM([2, 2]), DM(0.0000))
>>> F.stats()["success"]
True
>>> F = opti.to_function("F", {"p": p, "x": x}, ["p"], ["x"])
>>> F(3)
DM(3)
>>> try:
...   opti.to_function("F", [p+1], [x])
... except Exception as e:
...   print(str(e).splitlines()[-1])
Argument 0 is not purely symbolic.

>> opti = Opti(); x = opti.variable(); y = opti.variable(); p = opti.parameter();
>> opti.minimize((x-p)^2 + (y-x)^2); opti.subject_to(x >= 0);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> F = opti.to_function('F', {p, x}, {vertcat(x, y), opti.lam_g}, {'p', 'x0'}, {'xy', 'lam'});
>> F
F:(p,x0)->(xy[2],lam) MXFunction
>> r = F('p', 2, 'x0', 1); disp(r.xy), disp(r.lam)
[2, 2]
0.0000
>> s = F.stats(); disp(s.success)
1
>> F = opti.to_function('F', struct('p', p, 'x', x), {'p'}, {'x'}); disp(F(3))
3
>> try, opti.to_function('F', {p+1}, {x}); catch e, disp(contains(e.message, 'symbolic')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> y = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, (x - p)^2 + (y - x)^2)
julia> ca.subject_to(opti, x >= 0)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> F = ca.to_function(opti, "F", [p, x], [[x; y], ca.lam_g(opti)],
                          ["p", "x0"], ["xy", "lam"])
Function(F:(p,x0)->(xy[2],lam) MXFunction)
julia> r = F(p=2, x0=1);
julia> r["xy"], r["lam"]
([2, 2], 0.0000)
julia> ca.stats(F)["success"]
true
julia> F = ca.to_function(opti, "F", Dict("p" => p, "x" => x), ["p"], ["x"]);
julia> F(3)
DM(3)
julia> try
           ca.to_function(opti, "F", [p + 1], [x])
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Argument 0 is not purely symbolic.

See also
nlpsol

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

Definition at line 423 of file optistack.cpp.

427  {
428  try {
429  return (*this)->to_function(name, args, res, name_in, name_out, opts);
430  } catch(std::exception& e) {
431  THROW_ERROR("to_function", e.what());
432  }
433 }

◆ type_name()

std::string casadi::Opti::type_name ( ) const
inlineinherited

Definition at line 2600 of file optistack.hpp.

2600 { return "Opti"; }

◆ ubg()

MX casadi::Opti::ubg ( ) const
inherited

Definition at line 374 of file optistack.cpp.

374  {
375  try {
376  return (*this)->ubg();
377  } catch(std::exception& e) {
378  THROW_ERROR("ubg", e.what());
379  }
380 }

◆ update_user_dict() [1/2]

void casadi::Opti::update_user_dict ( const MX &  m,
const Dict &  meta 
)
inherited

Merges meta into the dict attached to a variable, parameter, dual variable (or every symbol of an expression) or to a constraint expression passed to subject_to(). Opti itself stores a "stacktrace" entry there in Python and MATLAB, which is what describe()/x_describe() print as "called from".

Parameters
mSymbol, expression of symbols, or constraint expression
metaDict entries to add (existing keys are overwritten)

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.update_user_dict(x, {"name": "speed", "unit": "m/s"})
>>> d = opti.user_dict(x)
>>> d["name"], d["unit"], "stacktrace" in d
('speed', 'm/s', True)
>>> con = x >= 0
>>> opti.subject_to(con)
>>> opti.update_user_dict(con, {"name": "nonneg"})
>>> opti.user_dict(con)["name"]
'nonneg'

>> opti = Opti(); x = opti.variable();
>> opti.update_user_dict(x, struct('name', 'speed', 'unit', 'm/s'));
>> d = opti.user_dict(x); fprintf('%s %s %d\n', d.name, d.unit, isfield(d, 'stacktrace'))
speed m/s 1
>> con = x >= 0; opti.subject_to(con); opti.update_user_dict(con, struct('name', 'nonneg'));
>> d = opti.user_dict(con); disp(d.name)
nonneg

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> ca.update_user_dict(opti, x, Dict("name" => "speed", "unit" => "m/s"))
julia> d = ca.user_dict(opti, x);
julia> d["name"], d["unit"], haskey(d, "stacktrace")
("speed", "m/s", true)
julia> con = x >= 0;
julia> ca.subject_to(opti, con)
julia> ca.update_user_dict(opti, con, Dict("name" => "nonneg"))
julia> ca.user_dict(opti, con)["name"]
"nonneg"

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

Definition at line 483 of file optistack.cpp.

483  {
484  try {
485  (*this)->update_user_dict(m, meta);
486  } catch(std::exception& e) {
487  THROW_ERROR("update_user_dict", e.what());
488  }
489 }

Referenced by casadi::Opti::update_user_dict().

◆ update_user_dict() [2/2]

void casadi::Opti::update_user_dict ( const std::vector< MX > &  m,
const Dict &  meta 
)
inherited

Definition at line 491 of file optistack.cpp.

491  {
492  for (const auto& m : ms)
493  update_user_dict(m, meta);
494 }
void update_user_dict(const MX &m, const Dict &meta)
Add user data to a symbol or constraint.
Definition: optistack.cpp:483

References casadi::Opti::update_user_dict().

◆ user_dict()

Dict casadi::Opti::user_dict ( const MX &  m) const
inherited
Parameters
mA single symbol or a constraint expression; other expressions raise an error

>>> opti = Opti()
>>> x = opti.variable()
>>> sorted(opti.user_dict(x).keys())
['stacktrace']
>>> try:
...   opti.user_dict(x+1)
... except Exception as e:
...   print(str(e).splitlines()[-1])
Symbol expected, got expression.

>> opti = Opti(); x = opti.variable(); disp(fieldnames(opti.user_dict(x)))
{'stacktrace'}
>> try, opti.user_dict(x+1); catch e, disp(contains(e.message, 'Symbol expected')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> sort(collect(keys(ca.user_dict(opti, x))))
1-element Vector{String}:
 "stacktrace"
julia> try
           ca.user_dict(opti, x + 1)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Symbol expected, got expression.

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

Definition at line 496 of file optistack.cpp.

496  {
497  try {
498  return (*this)->user_dict(m);
499  } catch(std::exception& e) {
500  THROW_ERROR("user_dict", e.what());
501  }
502 }

◆ value() [1/3]

DM casadi::Opti::value ( const DM &  x,
const std::vector< MX > &  values = std::vector<MX>() 
) const
inherited

Variables take the latest solver result, parameters their set_value(), dual variables the latest multipliers. Before the first solve(), or after set_initial()/set_value() changed the state, an expression involving variables raises an error unless every variable in it is overruled through values; parameter-only expressions always work. After a failed solve() the latest iterate is returned (the same holds for opti.debug.value()). A variable that does not appear in the problem raises an error.

Parameters
xExpression in the symbols of this instance (an MX). A DM is returned as is. SX expressions are not supported: a NaN matrix of the same sparsity is returned.
valuesOptional list of assignments var==value (e.g. opti.initial()) that overrule the stored values for this evaluation only
Returns
The numerical value

A scalar becomes a float, a dense matrix a numpy array and a sparse matrix a scipy sparse matrix.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize((x-p)**2)
>>> opti.set_value(p, 3)
>>> opti.value(2*p)
6.0
>>> try:
...   opti.value(x)
... except Exception as e:
...   print(str(e).splitlines()[-1])
This action is forbidden since you have not solved the Opti stack yet (with calling 'solve').
>>> opti.value(x+p, [x==1]), opti.value(x**2, opti.initial())
(4.0, 0.0)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> opti.value(x), sol.value(x), sol.value(x+p, [p==10])
(3.0, 3.0, 13.0)
>>> type(sol.value(vertcat(x, p))).__name__, sol.value(DM([1, 2]))
('ndarray', array([1., 2.]))

The value is a double matrix, sparse when the expression is sparse.

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.minimize((x-p)^2); opti.set_value(p, 3);
>> opti.value(2*p)
6
>> try, opti.value(x); catch e, disp(contains(e.message, 'not solved the Opti stack')); end
1
>> opti.value(x+p, {x==1}), opti.value(x^2, opti.initial())
4
0
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> opti.value(x), sol.value(x), sol.value(x+p, {p==10})
3
3
13
>> v = sol.value(vertcat(x, p)); disp(class(v)), disp(size(v)), disp(sol.value(DM([1; 2]))')
double
2 1
1 2

A scalar becomes a Float64, any other value a dense Matrix{Float64}.

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, (x - p)^2)
julia> ca.set_value(opti, p, 3)
julia> ca.value(opti, 2*p)
6.0
julia> try
           ca.value(opti, x)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
This action is forbidden since you have not solved the Opti stack yet (with calling 'solve').
julia> opti.value(x + p, [x == 1]), opti.value(x^2, ca.initial(opti))
(4.0, 0.0)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(opti, x), ca.value(sol, x)
(3.0, 3.0)
julia> sol.value(x + p, [p == 10])
13.0
julia> ca.value(sol, [x; p]), ca.value(sol, ca.DM([1, 2]))
([3.0, 3.0], [1.0, 2.0])

See also
initial, value_variables, OptiSol::value

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

Definition at line 238 of file optistack.cpp.

238  {
239  try {
240  return (*this)->value(x, values);
241  } catch(std::exception& e) {
242  THROW_ERROR("value", e.what());
243  }
244 }

References casadi::Opti::x().

◆ value() [2/3]

DM casadi::Opti::value ( const MX &  x,
const std::vector< MX > &  values = std::vector<MX>() 
) const
inherited

Variables take the latest solver result, parameters their set_value(), dual variables the latest multipliers. Before the first solve(), or after set_initial()/set_value() changed the state, an expression involving variables raises an error unless every variable in it is overruled through values; parameter-only expressions always work. After a failed solve() the latest iterate is returned (the same holds for opti.debug.value()). A variable that does not appear in the problem raises an error.

Parameters
xExpression in the symbols of this instance (an MX). A DM is returned as is. SX expressions are not supported: a NaN matrix of the same sparsity is returned.
valuesOptional list of assignments var==value (e.g. opti.initial()) that overrule the stored values for this evaluation only
Returns
The numerical value

A scalar becomes a float, a dense matrix a numpy array and a sparse matrix a scipy sparse matrix.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize((x-p)**2)
>>> opti.set_value(p, 3)
>>> opti.value(2*p)
6.0
>>> try:
...   opti.value(x)
... except Exception as e:
...   print(str(e).splitlines()[-1])
This action is forbidden since you have not solved the Opti stack yet (with calling 'solve').
>>> opti.value(x+p, [x==1]), opti.value(x**2, opti.initial())
(4.0, 0.0)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> opti.value(x), sol.value(x), sol.value(x+p, [p==10])
(3.0, 3.0, 13.0)
>>> type(sol.value(vertcat(x, p))).__name__, sol.value(DM([1, 2]))
('ndarray', array([1., 2.]))

The value is a double matrix, sparse when the expression is sparse.

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.minimize((x-p)^2); opti.set_value(p, 3);
>> opti.value(2*p)
6
>> try, opti.value(x); catch e, disp(contains(e.message, 'not solved the Opti stack')); end
1
>> opti.value(x+p, {x==1}), opti.value(x^2, opti.initial())
4
0
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> opti.value(x), sol.value(x), sol.value(x+p, {p==10})
3
3
13
>> v = sol.value(vertcat(x, p)); disp(class(v)), disp(size(v)), disp(sol.value(DM([1; 2]))')
double
2 1
1 2

A scalar becomes a Float64, any other value a dense Matrix{Float64}.

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, (x - p)^2)
julia> ca.set_value(opti, p, 3)
julia> ca.value(opti, 2*p)
6.0
julia> try
           ca.value(opti, x)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
This action is forbidden since you have not solved the Opti stack yet (with calling 'solve').
julia> opti.value(x + p, [x == 1]), opti.value(x^2, ca.initial(opti))
(4.0, 0.0)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(opti, x), ca.value(sol, x)
(3.0, 3.0)
julia> sol.value(x + p, [p == 10])
13.0
julia> ca.value(sol, [x; p]), ca.value(sol, ca.DM([1, 2]))
([3.0, 3.0], [1.0, 2.0])

See also
initial, value_variables, OptiSol::value

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

Definition at line 229 of file optistack.cpp.

229  {
230  try {
231  return (*this)->value(x, values);
232  } catch(std::exception& e) {
233  THROW_ERROR("value", e.what());
234  }
235 }

References casadi::Opti::x().

Referenced by casadi::OptiSol::value().

◆ value() [3/3]

DM casadi::Opti::value ( const SX &  x,
const std::vector< MX > &  values = std::vector<MX>() 
) const
inherited

Variables take the latest solver result, parameters their set_value(), dual variables the latest multipliers. Before the first solve(), or after set_initial()/set_value() changed the state, an expression involving variables raises an error unless every variable in it is overruled through values; parameter-only expressions always work. After a failed solve() the latest iterate is returned (the same holds for opti.debug.value()). A variable that does not appear in the problem raises an error.

Parameters
xExpression in the symbols of this instance (an MX). A DM is returned as is. SX expressions are not supported: a NaN matrix of the same sparsity is returned.
valuesOptional list of assignments var==value (e.g. opti.initial()) that overrule the stored values for this evaluation only
Returns
The numerical value

A scalar becomes a float, a dense matrix a numpy array and a sparse matrix a scipy sparse matrix.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize((x-p)**2)
>>> opti.set_value(p, 3)
>>> opti.value(2*p)
6.0
>>> try:
...   opti.value(x)
... except Exception as e:
...   print(str(e).splitlines()[-1])
This action is forbidden since you have not solved the Opti stack yet (with calling 'solve').
>>> opti.value(x+p, [x==1]), opti.value(x**2, opti.initial())
(4.0, 0.0)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> opti.value(x), sol.value(x), sol.value(x+p, [p==10])
(3.0, 3.0, 13.0)
>>> type(sol.value(vertcat(x, p))).__name__, sol.value(DM([1, 2]))
('ndarray', array([1., 2.]))

The value is a double matrix, sparse when the expression is sparse.

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.minimize((x-p)^2); opti.set_value(p, 3);
>> opti.value(2*p)
6
>> try, opti.value(x); catch e, disp(contains(e.message, 'not solved the Opti stack')); end
1
>> opti.value(x+p, {x==1}), opti.value(x^2, opti.initial())
4
0
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> opti.value(x), sol.value(x), sol.value(x+p, {p==10})
3
3
13
>> v = sol.value(vertcat(x, p)); disp(class(v)), disp(size(v)), disp(sol.value(DM([1; 2]))')
double
2 1
1 2

A scalar becomes a Float64, any other value a dense Matrix{Float64}.

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, (x - p)^2)
julia> ca.set_value(opti, p, 3)
julia> ca.value(opti, 2*p)
6.0
julia> try
           ca.value(opti, x)
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
This action is forbidden since you have not solved the Opti stack yet (with calling 'solve').
julia> opti.value(x + p, [x == 1]), opti.value(x^2, ca.initial(opti))
(4.0, 0.0)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(opti, x), ca.value(sol, x)
(3.0, 3.0)
julia> sol.value(x + p, [p == 10])
13.0
julia> ca.value(sol, [x; p]), ca.value(sol, ca.DM([1, 2]))
([3.0, 3.0], [1.0, 2.0])

See also
initial, value_variables, OptiSol::value

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

Definition at line 246 of file optistack.cpp.

246  {
247  try {
248  return (*this)->value(x, values);
249  } catch(std::exception& e) {
250  THROW_ERROR("value", e.what());
251  }
252 }

References casadi::Opti::x().

◆ value_parameters()

std::vector< MX > casadi::Opti::value_parameters ( ) const
inherited

Definition at line 294 of file optistack.cpp.

294  {
295  try {
296  return (*this)->value_parameters();
297  } catch(std::exception& e) {
298  THROW_ERROR("value_parameters", e.what());
299  }
300 }

Referenced by casadi::OptiSol::value_parameters().

◆ value_variables()

std::vector< MX > casadi::Opti::value_variables ( ) const
inherited

value_variables() gives value==var for every variable with its latest solver result; value_parameters() gives value==par for every parameter with its set value. Both feed set_initial()/set_value() to transfer a solution to the next solve or to another Opti.

>>> opti = Opti()
>>> x = opti.variable()
>>> p = opti.parameter()
>>> opti.minimize((x-p)**2)
>>> opti.set_value(p, 2)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> print(opti.value_variables(), opti.value_parameters())
[MX((2==opti..._x_1))] [MX((2==opti..._p_1))]
>>> opti.set_initial(sol.value_variables())
>>> opti.value(x, opti.initial())
2.0

>> opti = Opti(); x = opti.variable(); p = opti.parameter();
>> opti.minimize((x-p)^2); opti.set_value(p, 2);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve();
>> vv = opti.value_variables(); vp = opti.value_parameters(); disp(vv{1}), disp(vp{1})
(2==opti..._x_1)
(2==opti..._p_1)
>> opti.set_initial(sol.value_variables()); disp(opti.value(x, opti.initial()))
2

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, (x - p)^2)
julia> ca.set_value(opti, p, 2)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> print(ca.value_variables(opti), " ", ca.value_parameters(opti))
MX[(2==opti..._x_1)] MX[(2==opti..._p_1)]
julia> opti.set_initial(ca.value_variables(sol))
julia> opti.value(x, ca.initial(opti))
2.0

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

Definition at line 286 of file optistack.cpp.

286  {
287  try {
288  return (*this)->value_variables();
289  } catch(std::exception& e) {
290  THROW_ERROR("value_variables", e.what());
291  }
292 }

Referenced by casadi::OptiSol::value_variables().

◆ variable() [1/3]

MX casadi::Opti::variable ( casadi_int  n = 1,
casadi_int  m = 1,
const std::string &  attribute = "full" 
)
inherited

Returns an MX symbol of the requested shape, registered with this Opti instance. Variables are stacked into the solver's x vector in order of creation, so the order of variable() calls determines the layout of x and of lam_x. A variable that does not appear in the objective or the constraints is simply left out of the problem, but asking for its value after solve() raises an error.

With attribute "symmetric" (square shapes only) the returned expression is a symmetric matrix built from n*(n+1)/2 underlying scalars.

The default initial guess is 0; change it with set_initial().

Parameters
nNumber of rows (default 1)
mNumber of columns (default 1)
attribute"full" (default) or "symmetric"; anything else raises an error
Returns
A dense MX symbol of shape n-by-m

>>> opti = Opti()
>>> x = opti.variable()
>>> X = opti.variable(3, 2)
>>> x.shape, X.shape, X.is_symbolic()
((1, 1), (3, 2), True)
>>> S = opti.variable(2, 2, "symmetric")
>>> S.shape, S.is_symbolic()
((2, 2), False)
>>> opti.minimize(sumsqr(X) + x**2 + sumsqr(S))
>>> opti.nx
10
>>> try:
...   opti.variable(2, 3, "symmetric")
... except Exception as e:
...   print(str(e).splitlines()[-1])
You specified attribute 'symmetric', while matrix is not even square, but 2-by-3.

>> opti = Opti(); x = opti.variable(); X = opti.variable(3, 2);
>> size(x), size(X), X.is_symbolic()
1 1
3 2
1
>> S = opti.variable(2, 2, 'symmetric'); disp(size(S)), disp(S.is_symbolic())
2 2
0
>> opti.minimize(sumsqr(X) + x^2 + sumsqr(S)); disp(opti.nx)
10
>> try, opti.variable(2, 3, 'symmetric'); catch e, disp(contains(e.message, 'not even')); end
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti);
julia> X = ca.variable(opti, 3, 2);
julia> size(x), size(X), ca.is_symbolic(X)
((1, 1), (3, 2), true)
julia> S = ca.variable(opti, 2, 2, "symmetric");
julia> size(S), ca.is_symbolic(S)
((2, 2), false)
julia> ca.minimize(opti, ca.sumsqr(X) + x^2 + ca.sumsqr(S))
julia> ca.nx(opti)
10
julia> try
           ca.variable(opti, 2, 3, "symmetric")
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
You specified attribute 'symmetric', while matrix is not even square, but 2-by-3.

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

Definition at line 51 of file optistack.cpp.

51  {
52  try {
53  return (*this)->variable(n, m, attribute);
54  } catch(std::exception& e) {
55  THROW_ERROR("variable", e.what());
56  }
57 }

◆ variable() [2/3]

MX casadi::Opti::variable ( const MX &  symbol,
const std::string &  attribute = "full" 
)
inherited

Definition at line 67 of file optistack.cpp.

67  {
68  try {
69  return (*this)->variable(symbol, attribute);
70  } catch(std::exception& e) {
71  THROW_ERROR("variable", e.what());
72  }
73 }

◆ variable() [3/3]

MX casadi::Opti::variable ( const Sparsity &  sp,
const std::string &  attribute = "full" 
)
inherited

Definition at line 59 of file optistack.cpp.

59  {
60  try {
61  return (*this)->variable(sp, attribute);
62  } catch(std::exception& e) {
63  THROW_ERROR("variable", e.what());
64  }
65 }

◆ weak()

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

Definition at line 130 of file generic_shared_impl.hpp.

143  {
144  return (*this)->weak();
145  }

◆ x()

MX casadi::Opti::x ( ) const
inherited

The vector the solver optimizes over, in order of variable() creation, restricted to the variables that appear in the problem. Use it with jacobian(), hessian() or to_function(). In Python this is a read-only property.

>>> opti = Opti()
>>> x = opti.variable(2)
>>> y = opti.variable()
>>> opti.minimize(sumsqr(x) + y**2)
>>> opti.x.shape
(3, 1)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> sol = opti.solve()
>>> sol.value(jacobian(opti.f, opti.x))
array([0., 0., 0.])

>> opti = Opti(); x = opti.variable(2); y = opti.variable();
>> opti.minimize(sumsqr(x) + y^2); disp(size(opti.x))
3 1
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> sol = opti.solve(); disp(sol.value(jacobian(opti.f, opti.x)))
0 0 0

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> y = ca.variable(opti);
julia> ca.minimize(opti, ca.sumsqr(x) + y^2)
julia> size(ca.x(opti))
(3, 1)
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> sol = ca.solve(opti);
julia> ca.value(sol, ca.jacobian(ca.f(opti), ca.x(opti)))
3-element Vector{Float64}:
 0.0
 0.0
 0.0

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

Definition at line 334 of file optistack.cpp.

334  {
335  try {
336  return (*this)->x();
337  } catch(std::exception& e) {
338  THROW_ERROR("x", e.what());
339  }
340 }

Referenced by describe(), casadi::Opti::set_domain(), casadi::Opti::set_initial(), casadi::Opti::set_linear_scale(), casadi::Opti::set_value(), and casadi::Opti::value().

◆ x_describe()

std::string casadi::OptiAdvanced::x_describe ( casadi_index  i,
const Dict &  opts = Dict() 
) const

Human-readable description of the variable owning xi, plus the position inside the variable. Use it to trace NaN/Inf reports of a solver back to the source.

Parameters
opts"max_stacktrace_depth" (default 1)

>>> opti = Opti()
>>> x = opti.variable(3)
>>> opti.minimize(sumsqr(x))
>>> print(opti.debug.x_describe(2))
Opti decision variable 'opti..._x_1' of shape 3x1, called from ...
At nonzero 2.

>> opti = Opti(); x = opti.variable(3); opti.minimize(sumsqr(x));
>> opti.debug.x_describe(3)
Opti decision variable 'opti..._x_1' of shape 3x1, called from ...
At nonzero 3.

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 3);
julia> ca.minimize(opti, ca.sumsqr(x))
julia> print(ca.x_describe(ca.debug(opti), 2))
Opti decision variable 'opti..._x_1' of shape 3x1, called from ...
At nonzero 2.

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

Definition at line 649 of file optistack.cpp.

649  {
650  try {
651  return (*this)->x_describe(i, opts);
652  } catch(std::exception& e) {
653  THROW_ERROR("x_describe", e.what());
654  }
655 }

Referenced by casadi::OptiNode::x_describe().

◆ x_linear_scale()

DM casadi::Opti::x_linear_scale ( ) const
inherited

Definition at line 391 of file optistack.cpp.

391  {
392  try {
393  return (*this)->x_linear_scale();
394  } catch(std::exception& e) {
395  THROW_ERROR("x_linear_scale", e.what());
396  }
397 }

◆ x_linear_scale_offset()

DM casadi::Opti::x_linear_scale_offset ( ) const
inherited

Definition at line 399 of file optistack.cpp.

399  {
400  try {
401  return (*this)->x_linear_scale_offset();
402  } catch(std::exception& e) {
403  THROW_ERROR("x_linear_scale_offset", e.what());
404  }
405 }

◆ x_lookup()

MX casadi::OptiAdvanced::x_lookup ( casadi_index  i) const

>>> opti = Opti()
>>> x = opti.variable(2)
>>> y = opti.variable()
>>> opti.minimize(sumsqr(x) + y**2)
>>> print(opti.debug.x_lookup(1), opti.debug.x_lookup(2))
opti..._x_1 opti..._x_2

>> opti = Opti(); x = opti.variable(2); y = opti.variable();
>> opti.minimize(sumsqr(x) + y^2);
>> opti.debug.x_lookup(2), opti.debug.x_lookup(3)
opti..._x_1
opti..._x_2

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> y = ca.variable(opti);
julia> ca.minimize(opti, ca.sumsqr(x) + y^2)
julia> d = ca.debug(opti);
julia> print(ca.x_lookup(d, 1), " ", ca.x_lookup(d, 2))
opti..._x_1 opti..._x_2

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

Definition at line 609 of file optistack.cpp.

609  {
610  try {
611  return (*this)->x_lookup(i);
612  } catch(std::exception& e) {
613  THROW_ERROR("x_lookup", e.what());
614  }
615 }

Referenced by casadi::OptiNode::x_lookup().

Friends And Related Function Documentation

◆ InternalOptiCallback

friend class InternalOptiCallback
friend

Definition at line 2787 of file optistack.hpp.

Member Data Documentation

◆ problem_dirty_

bool casadi::OptiAdvanced::problem_dirty_

Definition at line 3476 of file optistack.hpp.

◆ solved_

bool casadi::OptiAdvanced::solved_

Definition at line 3488 of file optistack.hpp.

◆ solver_dirty_

bool casadi::OptiAdvanced::solver_dirty_

Definition at line 3482 of file optistack.hpp.


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