List of all members | Public Types | Public Member Functions | Static Public Member Functions | Protected 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]
Collaboration diagram for casadi::Opti:
Collaboration 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...
 
 Opti (const Opti &x)
 
 ~Opti ()
 Destructor. More...
 
 Opti (OptiNode *node)
 
std::string class_name () const
 Get class name. More...
 
void print_ptr (std::ostream &stream=casadi::uout()) const
 
void own (SharedObjectInternal *node)
 
void assign (SharedObjectInternal *node)
 Assign the node to a node class pointer without reference counting. More...
 
SharedObjectInternal * get () const
 Get a const pointer to the node. More...
 
casadi_int getCount () const
 Get the reference count. More...
 
void swap (GenericShared &other)
 Swap content with another instance. More...
 
std::string debug_repr () const
 
bool is_null () const
 Is a null pointer? More...
 
casadi_int __hash__ () const
 Returns a number that is unique for a given Node. More...
 
GenericWeakRef< SharedObject, SharedObjectInternal > * weak ()
 Get a weak reference to the object. More...
 
void subject_to (const MX &g, const Dict &options=Dict())
 Add constraints. More...
 
void subject_to (const std::vector< MX > &g, const Dict &options=Dict())
 Add constraints. More...
 
void subject_to (const MX &g, const DM &linear_scale, const Dict &options=Dict())
 Add constraints. More...
 
void subject_to (const std::vector< MX > &g, const DM &linear_scale, const Dict &options=Dict())
 Add constraints. More...
 
void set_initial (const MX &x, const DM &v)
 Set the initial guess of decision variables or dual variables. More...
 
void set_initial (const std::vector< MX > &assignments)
 Set the initial guess of decision variables or dual variables. More...
 
void set_value (const MX &x, const DM &v)
 Set the value of a parameter. More...
 
void set_value (const std::vector< MX > &assignments)
 Set the value of a parameter. More...
 
native_DM value (const MX &x, const std::vector< MX > &values=std::vector< MX >()) const
 Evaluate an expression at the current values. More...
 
native_DM value (const DM &x, const std::vector< MX > &values=std::vector< MX >()) const
 Evaluate an expression at the current values. More...
 
native_DM value (const SX &x, const std::vector< MX > &values=std::vector< MX >()) const
 Evaluate an expression at the current values. More...
 
Function to_function (const std::string &name, const std::vector< MX > &args, const std::vector< MX > &res, const Dict &opts=Dict())
 Create a CasADi Function from the Opti solver. More...
 
Function to_function (const std::string &name, const std::vector< MX > &args, const std::vector< MX > &res, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Create a CasADi Function from the Opti solver. More...
 
Function to_function (const std::string &name, const std::map< std::string, MX > &dict, const std::vector< std::string > &name_in, const std::vector< std::string > &name_out, const Dict &opts=Dict())
 Same, with inputs and outputs picked by name from a dict of expressions. More...
 
void callback_class (OptiCallback *callback)
 Helper methods for callback() More...
 
void callback_class ()
 Helper methods for callback() More...
 
OptiNode * operator-> ()
 Access a member of the node. More...
 
const OptiNode * operator-> () const
 Const access a member of the node. More...
 

Static Public Member Functions

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

Protected Member Functions

void count_up ()
 
void count_down ()
 

Friends

class InternalOptiCallback
 

Member Typedef Documentation

◆ base_type

Definition at line 103 of file shared_object.hpp.

◆ internal_base_type

Definition at line 102 of file shared_object.hpp.

Constructor & Destructor Documentation

◆ Opti() [1/3]

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

Definition at line 47 of file optistack.cpp.

47  {
48  own(OptiNode::create(problem_type));
49 }
static OptiNode * create(const std::string &problem_type)

References casadi::OptiNode::create(), and casadi::GenericShared< SharedObject, SharedObjectInternal >::own().

Referenced by create().

◆ Opti() [2/3]

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

Definition at line 79 of file optistack.cpp.

79  : SharedObject(rhs) {
81 }
void callback_class()
Helper methods for callback()
Definition: optistack.cpp:475

References callback_class().

◆ ~Opti()

casadi::Opti::~Opti ( )
inline

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

Definition at line 2678 of file optistack.hpp.

2678 {}

◆ Opti() [3/3]

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

Definition at line 75 of file optistack.cpp.

75  {
76  own(node);
77 }

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

Member Function Documentation

◆ __hash__()

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

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

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

Definition at line 123 of file generic_shared_impl.hpp.

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

◆ 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

Definition at line 854 of file optistack.cpp.

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

References copy().

◆ assign()

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

improper use will cause memory leaks!

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

Definition at line 96 of file generic_shared_impl.hpp.

86  {
87  node = node_;
88  }

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

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

◆ 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

Definition at line 475 of file optistack.cpp.

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

Referenced by Opti().

◆ 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

Definition at line 467 of file optistack.cpp.

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

◆ 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

Definition at line 857 of file optistack.cpp.

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

References casadi::OptiNode::copy().

Referenced by advanced(), and debug().

◆ count_down()

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

Definition at line 133 of file generic_shared_impl.hpp.

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

◆ count_up()

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

Definition at line 132 of file generic_shared_impl.hpp.

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

◆ create()

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

Definition at line 86 of file optistack.cpp.

86  {
87  return Opti(node);
88 }
Opti(const std::string &problem_type="nlp")
Create an empty Opti context.
Definition: optistack.cpp:47

References Opti().

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

◆ 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

Definition at line 851 of file optistack.cpp.

851  {
852  return copy();
853 }

References copy().

Referenced by disp().

◆ debug_repr()

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

Definition at line 112 of file generic_shared_impl.hpp.

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

◆ 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

Definition at line 754 of file optistack.cpp.

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

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

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

◆ 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

Definition at line 302 of file optistack.cpp.

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

◆ f()

MX casadi::Opti::f ( ) const

In Python this is a read-only property.

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

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

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

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

Definition at line 358 of file optistack.cpp.

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

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

◆ f_linear_scale()

double casadi::Opti::f_linear_scale ( ) const

Definition at line 415 of file optistack.cpp.

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

◆ g()

MX casadi::Opti::g ( ) const

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

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

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

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

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

Definition at line 350 of file optistack.cpp.

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

Referenced by subject_to().

◆ g_linear_scale()

DM casadi::Opti::g_linear_scale ( ) const

Definition at line 407 of file optistack.cpp.

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

◆ get()

Definition at line 99 of file generic_shared_impl.hpp.

115  {
116  return node;
117  }

◆ get_str()

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

Definition at line 776 of file optistack.cpp.

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

References disp().

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

◆ getCount()

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

Definition at line 102 of file generic_shared_impl.hpp.

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

◆ initial()

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

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

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

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

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

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

Definition at line 278 of file optistack.cpp.

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

◆ is_null()

Definition at line 116 of file generic_shared_impl.hpp.

120  {
121  return node==nullptr;
122  }

◆ 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

Definition at line 383 of file optistack.cpp.

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

◆ lbg()

MX casadi::Opti::lbg ( ) const

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

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

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

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

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

Definition at line 366 of file optistack.cpp.

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

◆ 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

Definition at line 114 of file optistack.cpp.

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

References f().

◆ 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

Definition at line 326 of file optistack.cpp.

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

Referenced by disp().

◆ 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

Definition at line 318 of file optistack.cpp.

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

Referenced by disp().

◆ 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

Definition at line 310 of file optistack.cpp.

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

Referenced by disp().

◆ operator->() [1/2]

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

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

Definition at line 38 of file optistack.cpp.

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

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

◆ operator->() [2/2]

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

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

Definition at line 42 of file optistack.cpp.

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

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

◆ own()

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

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

Definition at line 89 of file generic_shared_impl.hpp.

◆ p()

MX casadi::Opti::p ( ) const

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

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

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

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

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

Definition at line 342 of file optistack.cpp.

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

◆ parameter() [1/3]

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

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

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

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

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

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

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

Definition at line 90 of file optistack.cpp.

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

◆ parameter() [2/3]

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

Definition at line 106 of file optistack.cpp.

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

◆ parameter() [3/3]

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

Definition at line 98 of file optistack.cpp.

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

◆ print_ptr()

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

Print the pointer to the internal class

Definition at line 43 of file shared_object.cpp.

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

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

◆ 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

Definition at line 270 of file optistack.cpp.

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

Referenced by disp().

◆ 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

Definition at line 254 of file optistack.cpp.

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

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

◆ set_domain()

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

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

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

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

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

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

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

Definition at line 189 of file optistack.cpp.

189  {
190  try {
191  (*this)->set_domain(x, domain);
192  } catch(std::exception& e) {
193  THROW_ERROR("set_domain", e.what());
194  }
195 }
MX x() const
Get all (scalarised) decision variables as a symbolic column vector.
Definition: optistack.cpp:334

References x().

◆ 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

Definition at line 165 of file optistack.cpp.

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

References x().

◆ 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

Definition at line 172 of file optistack.cpp.

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

◆ set_linear_scale()

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

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

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

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

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

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

See also
x_linear_scale, x_linear_scale_offset, scale_helper

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

Definition at line 197 of file optistack.cpp.

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

References x().

◆ 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

Definition at line 181 of file optistack.cpp.

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

References x().

◆ 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

Definition at line 205 of file optistack.cpp.

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

◆ 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

Definition at line 213 of file optistack.cpp.

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

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

Definition at line 221 of file optistack.cpp.

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

◆ 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

Definition at line 155 of file optistack.cpp.

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

◆ 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

Definition at line 262 of file optistack.cpp.

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

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

◆ subject_to() [1/5]

void casadi::Opti::subject_to ( )

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

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

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

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

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

Definition at line 146 of file optistack.cpp.

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

Referenced by subject_to().

◆ 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

Definition at line 122 of file optistack.cpp.

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

References g().

◆ 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

Definition at line 134 of file optistack.cpp.

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

References g().

◆ 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

Definition at line 130 of file optistack.cpp.

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

References g(), and subject_to().

◆ 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

Definition at line 142 of file optistack.cpp.

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

References g(), and subject_to().

◆ swap()

Definition at line 105 of file generic_shared_impl.hpp.

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

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

Definition at line 441 of file optistack.cpp.

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

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

◆ to_function() [2/3]

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

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

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

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

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

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

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

See also
nlpsol

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

Definition at line 435 of file optistack.cpp.

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

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

◆ to_function() [3/3]

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

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

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

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

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

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

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

See also
nlpsol

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

Definition at line 423 of file optistack.cpp.

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

◆ type_name()

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

Definition at line 2600 of file optistack.hpp.

2600 { return "Opti"; }

◆ ubg()

MX casadi::Opti::ubg ( ) const

Definition at line 374 of file optistack.cpp.

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

◆ update_user_dict() [1/2]

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

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

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

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

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

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

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

Definition at line 483 of file optistack.cpp.

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

Referenced by update_user_dict().

◆ update_user_dict() [2/2]

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

Definition at line 491 of file optistack.cpp.

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

References update_user_dict().

◆ 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

Definition at line 496 of file optistack.cpp.

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

◆ value() [1/3]

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

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

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

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

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

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

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

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

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

See also
initial, value_variables, OptiSol::value

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

Definition at line 238 of file optistack.cpp.

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

References x().

◆ value() [2/3]

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

Definition at line 229 of file optistack.cpp.

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

References x().

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

◆ value() [3/3]

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

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

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

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

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

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

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

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

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

See also
initial, value_variables, OptiSol::value

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

Definition at line 246 of file optistack.cpp.

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

References x().

◆ value_parameters()

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

Definition at line 294 of file optistack.cpp.

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

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

◆ value_variables()

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

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

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

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

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

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

Definition at line 286 of file optistack.cpp.

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

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

◆ variable() [1/3]

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

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

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

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

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

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

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

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

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

Definition at line 51 of file optistack.cpp.

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

◆ variable() [2/3]

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

Definition at line 67 of file optistack.cpp.

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

◆ variable() [3/3]

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

Definition at line 59 of file optistack.cpp.

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

◆ weak()

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

Definition at line 130 of file generic_shared_impl.hpp.

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

◆ x()

MX casadi::Opti::x ( ) const

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

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

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

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

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

Definition at line 334 of file optistack.cpp.

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

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

◆ x_linear_scale()

DM casadi::Opti::x_linear_scale ( ) const

Definition at line 391 of file optistack.cpp.

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

◆ x_linear_scale_offset()

DM casadi::Opti::x_linear_scale_offset ( ) const

Definition at line 399 of file optistack.cpp.

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

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 files: