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

A simplified interface for NLP modeling/solving. More...

#include <optistack.hpp>

Detailed Description

Opti collects decision variables, parameters, an objective and constraints written in natural syntax, builds an nlpsol (or qpsol) instance from them and gives numerical access to the solution. The bookkeeping of flattening variables into one vector and constraints into bounds is hidden.

Workflow:

Opti is stateful: every call above mutates the instance, and the problem is rebuilt lazily at the next solve(). An OptiSol is a copy taken at the time of solve(), so later changes to the Opti do not affect it. Only symbols created by this instance may appear in its expressions; raw MX.sym symbols or symbols of another Opti raise an error.

The constructor argument selects the problem class: "nlp" (default, solved with nlpsol) or "conic" (quadratic programs and SOCPs, solved with qpsol).

An iteration callback can be registered with opti.callback(fh); fh is called with the iteration number after every solver iteration, and opti.debug.value() inside it returns the current iterate. Calling opti.callback() without argument removes it.

>>> 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()
>>> sol.value(x), sol.value(y)
(0.7862, 0.6180)
>>> sol.value(opti.f)
0

>> 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();
>> sol.value(x), sol.value(y)
0.7862
0.6180
>> sol.value(opti.f)
0

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> ca.value(sol, x), ca.value(sol, y)
(0.7862, 0.6180)
julia> ca.value(sol, ca.f(opti))
0

Parametric problems are re-solved by changing parameter values:

>>> opti = Opti()
>>> x = opti.variable(2)
>>> p = opti.parameter()
>>> opti.minimize(sumsqr(x-p))
>>> opti.subject_to(1 <= (sum1(x) <= 2))
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> opti.set_value(p, 3)
>>> sol = opti.solve()
>>> sol.value(sum1(x))
2.0
>>> opti.set_value(p, 0)
>>> sol = opti.solve()
>>> sol.value(sum1(x))
1.0

>> opti = Opti();
>> x = opti.variable(2); p = opti.parameter();
>> opti.minimize(sumsqr(x-p));
>> opti.subject_to(1 <= sum1(x) <= 2);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> opti.set_value(p, 3); sol = opti.solve();
>> sol.value(sum1(x))
2
>> opti.set_value(p, 0); sol = opti.solve();
>> sol.value(sum1(x))
1

julia> opti = ca.Opti();
julia> x = ca.variable(opti, 2);
julia> p = ca.parameter(opti);
julia> ca.minimize(opti, ca.sumsqr(x - p))
julia> ca.subject_to(opti, 1 <= (sum(x) <= 2))
julia> ca.solver(opti, "ipopt", Dict("print_time" => false),
                  Dict("print_level" => 0, "sb" => "yes"))
julia> ca.set_value(opti, p, 3)
julia> sol = ca.solve(opti);
julia> ca.value(sol, sum(x))
2.0
julia> ca.set_value(opti, p, 0)
julia> sol = ca.solve(opti);
julia> ca.value(sol, sum(x))
1.0

An iteration callback:

>>> opti = Opti()
>>> x = opti.variable()
>>> opti.minimize((x-1)**2)
>>> opti.solver("ipopt", {"print_time": False}, {"print_level": 0, "sb": "yes"})
>>> history = []
>>> opti.callback(lambda i: history.append((i, opti.debug.value(x))))
>>> sol = opti.solve()
>>> history
[(0, 0.0), (1, 1.0)]
>>> opti.callback()
>>> sol = opti.solve()
>>> len(history)
2

>> opti = Opti(); x = opti.variable(); opti.minimize((x-1)^2);
>> opti.solver('ipopt', struct('print_time', false), struct('print_level', 0, 'sb', 'yes'));
>> opti.callback(@(i) fprintf('%d %.3f\n', i, opti.debug.value(x)));
>> sol = opti.solve();
0 0.000
1 1.000
>> opti.callback();
>> sol = opti.solve();

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> history = Tuple{Int,Float64}[];
julia> ca.callback(opti, i -> push!(history, (i, ca.value(ca.debug(opti), x))))
julia> sol = ca.solve(opti);
julia> history
2-element Vector{Tuple{Int64, Float64}}:
 (0, 0.0)
 (1, 1.0)
julia> ca.callback(opti)
julia> sol = ca.solve(opti);
julia> length(history)
2

See also
OptiSol, OptiAdvanced, nlpsol, qpsol
Date
2017
Author
Joris Gillis, Erik Lambrechts, Joel Andersson

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

Definition at line 234 of file optistack.hpp.

Inheritance diagram for casadi::Opti:
Inheritance graph
[legend]

Public Types

using internal_base_type = SharedObjectInternal
 
using base_type = SharedObject
 

Public Member Functions

 Opti (const std::string &problem_type="nlp")
 Create an empty Opti context. 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...
 
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...
 
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...
 

Static Public Member Functions

static MX bounded (const MX &lb, const MX &expr, const MX &ub)
 Construct a double inequality. More...
 

Friends

class InternalOptiCallback
 

Member Typedef Documentation

◆ base_type

Definition at line 103 of file shared_object.hpp.

◆ internal_base_type

using casadi::SharedObject::internal_base_type = SharedObjectInternal
inherited

Definition at line 102 of file shared_object.hpp.

Constructor & Destructor Documentation

◆ Opti()

casadi::Opti::Opti ( const std::string &  problem_type = "nlp")
Parameters
problem_type"nlp" (default): general nonlinear program, solved with an nlpsol plugin. "conic": quadratic program or SOCP, solved with a qpsol plugin; the objective must then be quadratic and the constraints linear or second-order cone. Any other string raises an error.

>>> opti = Opti()
>>> opti.nx, opti.np, opti.ng
(0, 0, 0)
>>> opti = Opti("conic")
>>> x = opti.variable(2)
>>> opti.minimize(sumsqr(x-1))
>>> opti.subject_to(x[0]+x[1] <= 1)
>>> opti.solver("qrqp", {"print_time": False, "print_iter": False,
...                      "print_header": False, "print_info": False})
>>> opti.solve().value(x)
array([0.5, 0.5])
>>> try:
...   Opti("lp")
... except Exception as e:
...   print(str(e).splitlines()[-1])
Specified problem type 'lp'unknown. Choose 'nlp' (default) or 'conic'.

>> opti = Opti(); fprintf('%d %d %d\n', opti.nx, opti.np, opti.ng)
0 0 0
>> opti = Opti('conic'); x = opti.variable(2);
>> opti.minimize(sumsqr(x-1)); opti.subject_to(x(1)+x(2) <= 1);
>> opts = struct('print_time', false, 'print_iter', false, 'print_header', false);
>> opts.print_info = false; opti.solver('qrqp', opts);
>> sol = opti.solve(); disp(sol.value(x)')
0.5000 0.5000
>> try, Opti('lp'); catch e, disp(contains(e.message, 'Specified problem type')); end
1

julia> opti = ca.Opti();
julia> ca.nx(opti), ca.np(opti), ca.ng(opti)
(0, 0, 0)
julia> opti = ca.Opti("conic");
julia> x = ca.variable(opti, 2);
julia> ca.minimize(opti, ca.sumsqr(x - 1))
julia> ca.subject_to(opti, x[1] + x[2] <= 1)
julia> ca.solver(opti, "qrqp", Dict("print_time" => false, "print_iter" => false,
                                     "print_header" => false, "print_info" => false))
julia> ca.value(ca.solve(opti), x)
2-element Vector{Float64}:
 0.5
 0.5
julia> try
           ca.Opti("lp")
       catch e
           println(last(split(sprint(showerror, e), "\n")))
       end
Specified problem type 'lp'unknown. Choose 'nlp' (default) or 'conic'.

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

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.

◆ advanced()

OptiAdvanced casadi::Opti::advanced ( ) const

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

◆ bounded()

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

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.

◆ callback_class() [1/2]

void casadi::Opti::callback_class ( )

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

◆ callback_class() [2/2]

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

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

◆ class_name()

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

◆ copy()

Opti casadi::Opti::copy ( ) const

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

◆ debug()

OptiAdvanced casadi::Opti::debug ( ) const

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

◆ debug_repr()

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

Definition at line 112 of file generic_shared_impl.hpp.

◆ disp()

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

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

◆ dual()

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

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

◆ f()

MX casadi::Opti::f ( ) const

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

◆ f_linear_scale()

double casadi::Opti::f_linear_scale ( ) const

◆ g()

MX casadi::Opti::g ( ) const

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

◆ g_linear_scale()

DM casadi::Opti::g_linear_scale ( ) const

◆ get_str()

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

◆ initial()

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

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

◆ is_null()

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

Definition at line 116 of file generic_shared_impl.hpp.

◆ lam_g()

MX casadi::Opti::lam_g ( ) const

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

◆ lbg()

MX casadi::Opti::lbg ( ) const

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

◆ minimize()

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

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

◆ ng()

casadi_int casadi::Opti::ng ( ) const

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

◆ np()

casadi_int casadi::Opti::np ( ) const

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

◆ nx()

casadi_int casadi::Opti::nx ( ) const

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

◆ p()

MX casadi::Opti::p ( ) const

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

◆ parameter() [1/3]

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

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

◆ parameter() [2/3]

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

◆ parameter() [3/3]

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

◆ return_status()

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

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

◆ scale_helper()

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

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

◆ set_domain()

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

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

◆ set_initial() [1/2]

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

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

◆ set_initial() [2/2]

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

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

◆ set_linear_scale()

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

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

◆ set_value() [1/2]

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

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

◆ set_value() [2/2]

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

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

◆ solve()

OptiSol casadi::Opti::solve ( )

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

◆ solve_limited()

OptiSol casadi::Opti::solve_limited ( )

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

◆ solver()

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

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

◆ stats()

Dict casadi::Opti::stats ( ) const

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

◆ subject_to() [1/5]

void casadi::Opti::subject_to ( )

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

◆ subject_to() [2/5]

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

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

◆ subject_to() [3/5]

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

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

◆ subject_to() [4/5]

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

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

◆ subject_to() [5/5]

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

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

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

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

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

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

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

◆ type_name()

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

Definition at line 2600 of file optistack.hpp.

◆ ubg()

MX casadi::Opti::ubg ( ) const

◆ update_user_dict() [1/2]

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

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

◆ update_user_dict() [2/2]

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

◆ user_dict()

Dict casadi::Opti::user_dict ( const MX &  m) const
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

◆ value() [1/3]

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

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

◆ value() [2/3]

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

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

◆ value() [3/3]

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

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

◆ value_parameters()

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

◆ value_variables()

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

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

◆ variable() [1/3]

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

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

◆ variable() [2/3]

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

◆ variable() [3/3]

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

◆ x()

MX casadi::Opti::x ( ) const

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

◆ x_linear_scale()

DM casadi::Opti::x_linear_scale ( ) const

◆ x_linear_scale_offset()

DM casadi::Opti::x_linear_scale_offset ( ) const

Friends And Related Function Documentation

◆ InternalOptiCallback

friend class InternalOptiCallback
friend

Definition at line 237 of file optistack.hpp.


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