optistack.hpp
1 /*
2  * This file is part of CasADi.
3  *
4  * CasADi -- A symbolic framework for dynamic optimization.
5  * Copyright (C) 2010-2023 Joel Andersson, Joris Gillis, Moritz Diehl,
6  * KU Leuven. All rights reserved.
7  * Copyright (C) 2011-2014 Greg Horn
8  *
9  * CasADi is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 3 of the License, or (at your option) any later version.
13  *
14  * CasADi is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with CasADi; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  */
24 
25 #ifndef CASADI_OPTISTACK_HPP
26 #define CASADI_OPTISTACK_HPP
27 
28 #include "function.hpp"
29 #include "callback.hpp"
30 
31 namespace casadi {
32 
33 typedef DM native_DM;
34 
35 class OptiNode;
36 class OptiSol;
37 class OptiAdvanced;
38 class OptiCallback;
234 class CASADI_EXPORT Opti
235  : public SWIG_IF_ELSE(PrintableCommon, Printable<Opti>),
236  public SharedObject {
237  friend class InternalOptiCallback;
238 public:
239 
308  Opti(const std::string& problem_type="nlp");
309 
389  MX variable(casadi_int n=1, casadi_int m=1, const std::string& attribute="full");
391  MX variable(const Sparsity& sp, const std::string& attribute="full");
393  MX variable(const MX& symbol, const std::string& attribute="full");
394 
458  MX parameter(casadi_int n=1, casadi_int m=1, const std::string& attribute="full");
460  MX parameter(const Sparsity& sp, const std::string& attribute="full");
462  MX parameter(const MX& symbol, const std::string& attribute="full");
463 
519  void minimize(const MX& f, double linear_scale=1);
520 
522 
702  void subject_to(const MX& g, const Dict& options=Dict());
703  void subject_to(const std::vector<MX>& g, const Dict& options=Dict());
704  void subject_to(const MX& g, const DM& linear_scale, const Dict& options=Dict());
705  void subject_to(const std::vector<MX>& g, const DM& linear_scale, const Dict& options=Dict());
707 
775  void subject_to();
776 
859  void solver(const std::string& solver,
860  const Dict& plugin_options=Dict(),
861  const Dict& solver_options=Dict());
862 
864 
990  void set_initial(const MX& x, const DM& v);
991  void set_initial(const std::vector<MX>& assignments);
993 
995 
1067  void set_value(const MX& x, const DM& v);
1068  void set_value(const std::vector<MX>& assignments);
1070 
1137  void set_domain(const MX& x, const std::string& domain);
1138 
1198  void set_linear_scale(const MX& x, const DM& scale, const DM& offset=0);
1199 
1278 
1325 
1327 
1430  native_DM value(const MX& x, const std::vector<MX>& values=std::vector<MX>()) const;
1431  native_DM value(const DM& x, const std::vector<MX>& values=std::vector<MX>()) const;
1432  native_DM value(const SX& x, const std::vector<MX>& values=std::vector<MX>()) const;
1434 
1483  Dict stats() const;
1484 
1542  std::string return_status() const;
1543 
1587  std::vector<MX> initial() const;
1588 
1645  std::vector<MX> value_variables() const;
1646  std::vector<MX> value_parameters() const;
1647 
1704  Function scale_helper(const Function& h) const;
1705 
1791  MX dual(const MX& m) const;
1792 
1829  casadi_int nx() const;
1830 
1867  casadi_int np() const;
1868 
1905  casadi_int ng() const;
1906 
1959  MX x() const;
1960 
1997  MX p() const;
1998 
2038  MX g() const;
2039 
2078  MX f() const;
2079 
2125  MX lbg() const;
2126  MX ubg() const;
2127 
2135  double f_linear_scale() const;
2136 
2196  MX lam_g() const;
2197 
2199 
2303  Function to_function(const std::string& name,
2304  const std::vector<MX>& args, const std::vector<MX>& res,
2305  const Dict& opts = Dict());
2306 
2307  Function to_function(const std::string& name,
2308  const std::vector<MX>& args, const std::vector<MX>& res,
2309  const std::vector<std::string>& name_in,
2310  const std::vector<std::string>& name_out,
2311  const Dict& opts = Dict());
2312 
2314  Function to_function(const std::string& name,
2315  const std::map<std::string, MX>& dict,
2316  const std::vector<std::string>& name_in,
2317  const std::vector<std::string>& name_out,
2318  const Dict& opts = Dict());
2320 
2321  #ifndef SWIGMATLAB
2353  static MX bounded(const MX& lb, const MX& expr, const MX& ub) { return (lb<=expr)<= ub; }
2354  #endif
2355 
2417 
2454 
2494  Opti copy() const;
2495 
2551  void update_user_dict(const MX& m, const Dict& meta);
2552  void update_user_dict(const std::vector<MX>& m, const Dict& meta);
2597  Dict user_dict(const MX& m) const;
2598 
2600  std::string type_name() const { return "Opti"; }
2601 
2656  void disp(std::ostream& stream, bool more=false) const;
2657 
2659  std::string get_str(bool more=false) const;
2660 
2662 
2668  void callback_class(OptiCallback* callback);
2671 
2672 #ifndef SWIG
2673  Opti(const Opti& x);
2674 
2678  ~Opti() {}
2679 
2680  static Opti create(OptiNode* node);
2683 
2686  OptiNode* operator->();
2687 
2691  const OptiNode* operator->() const;
2694 
2695  Opti(OptiNode* node);
2696 
2697 #endif // SWIG
2698 
2699 };
2700 
2703  OPTI_GENERIC_EQUALITY, // g1(x,p) == g2(x,p)
2704  OPTI_GENERIC_INEQUALITY, // g1(x,p) <= g2(x,p)
2705  OPTI_EQUALITY, // g(x,p) == bound(p)
2706  OPTI_INEQUALITY, // g(x,p) <= bound(p)
2707  OPTI_DOUBLE_INEQUALITY, // lb(p) <= g(x,p) <= ub(p)
2708  OPTI_PSD, // A(x,p) >= b(p)
2712  OPTI_VAR, // variable
2713  OPTI_PAR, // parameter
2714  OPTI_DUAL_G // dual
2715  };
2717  enum DomainType {
2720  };
2721 
2722 
2726  casadi_int start;
2727  casadi_int stop;
2728  };
2731  MetaCon() : n(1), flipped(false), linear_scale(1) {}
2732  MX original; // original expression
2733  MX canon; // Canonical expression
2737  casadi_int n;
2738  bool flipped;
2743  };
2746  std::string attribute;
2747  casadi_int n;
2748  casadi_int m;
2751  casadi_int count;
2752  casadi_int i;
2753  casadi_int active_i;
2755  };
2756 
2757 
2765 public:
2767  }
2769  casadi_error("Callback objects cannot be copied");
2770  }
2772  virtual void call(casadi_int i) {
2773  uout() << "This is a simple callback at iteration" << i << std::endl;
2774  }
2775  virtual ~OptiCallback() {}
2776 };
2777 
2786 class CASADI_EXPORT OptiAdvanced : public Opti {
2787  friend class InternalOptiCallback;
2788 public:
2789 
2790  OptiAdvanced(const Opti& x);
2791 
2796 
2797 
2851 
2887  bool is_parametric(const MX& expr) const;
2888 
2890 
2940  std::vector<MX> symvar() const;
2941  std::vector<MX> symvar(const MX& expr) const;
2942  std::vector<MX> symvar(const MX& expr, VariableType type) const;
2944 
2989  MetaCon canon_expr(const MX& expr) const;
2990 
2992  MetaVar get_meta(const MX& m) const;
2993 
2995  MetaCon get_meta_con(const MX& m) const;
2996 
2998  void set_meta(const MX& m, const MetaVar& meta);
2999 
3001  void set_meta_con(const MX& m, const MetaCon& meta);
3002 
3004  void assert_active_symbol(const MX& m) const;
3005 
3053  std::vector<MX> active_symvar(VariableType type) const;
3055  std::vector<DM> active_values(VariableType type) const;
3056 
3093  MX x_lookup(casadi_index i) const;
3128  MX g_lookup(casadi_index i) const;
3129 
3131  casadi_index g_index_reduce_g(casadi_index i) const;
3133  casadi_index g_index_reduce_x(casadi_index i) const;
3135  casadi_index g_index_unreduce_g(casadi_index i) const;
3136 
3177  std::string x_describe(casadi_index i, const Dict& opts=Dict()) const;
3212  std::string g_describe(casadi_index i, const Dict& opts=Dict()) const;
3260  std::string describe(const MX& x, casadi_index indent=0, const Dict& opts=Dict()) const;
3261 
3337  void show_infeasibilities(double tol=0, const Dict& opts=Dict()) const;
3338 
3414 
3416  DMDict arg() const;
3418  void res(const DMDict& res);
3420  DMDict res() const;
3456  std::vector<MX> constraints() const;
3458  MX objective() const;
3459 
3462 
3464  void assert_empty() const;
3465 
3466 
3474  void bake();
3475 
3478  void mark_problem_dirty(bool flag=true);
3480  bool problem_dirty() const;
3481 
3484  void mark_solver_dirty(bool flag=true);
3486  bool solver_dirty() const;
3487 
3488  bool solved_;
3490  void mark_solved(bool flag=true);
3492  bool solved() const;
3493 
3495  void assert_solved() const;
3497  void assert_baked() const;
3498 
3500  casadi_int instance_number() const;
3501 
3502 protected:
3504 };
3505 
3563 class CASADI_EXPORT OptiSol : public SWIG_IF_ELSE(PrintableCommon, Printable<OptiAdvanced>) {
3564  friend class OptiNode;
3565  public:
3566  std::string type_name() const {return "OptiSol";}
3567  void disp(std::ostream& stream, bool more=false) const;
3568  std::string get_str(bool more=false) const;
3570 
3649  native_DM value(const MX& x, const std::vector<MX>& values=std::vector<MX>()) const;
3650  native_DM value(const DM& x, const std::vector<MX>& values=std::vector<MX>()) const;
3651  native_DM value(const SX& x, const std::vector<MX>& values=std::vector<MX>()) const;
3653 
3711  std::vector<MX> value_variables() const;
3712  std::vector<MX> value_parameters() const;
3713 
3755  Dict stats() const;
3756 
3799  Opti opti() const { return optistack_; } // NOLINT(cppcoreguidelines-slicing)
3800 
3801  protected:
3802  OptiSol(const Opti& opti);
3804 };
3805 
3806 
3807 } // namespace casadi
3808 
3809 #endif // CASADI_OPTI_HPP
Function object.
Definition: function.hpp:126
MX - Matrix expression.
Definition: mx.hpp:145
Opti with debugging and low-level access.
Definition: optistack.hpp:2786
casadi_index g_index_unreduce_g(casadi_index i) const
Row of g for row i of the reduced g.
void mark_problem_dirty(bool flag=true)
Flag that the problem structure changed since the last bake.
MX objective() const
Objective expression; same as f()
void mark_solver_dirty(bool flag=true)
Flag that the solver must be reconstructed (solver() was called)
MX x_lookup(casadi_index i) const
Get the variable that owns entry i of the flattened x vector.
bool problem_dirty() const
True when the problem must be baked again before solving.
std::string describe(const MX &x, casadi_index indent=0, const Dict &opts=Dict()) const
Describe an expression in terms of this instance.
std::vector< MX > symvar(const MX &expr) const
Get the symbols of this instance.
std::vector< MX > constraints() const
Get the constraint expressions as passed to subject_to.
DMDict solve_actual(const DMDict &args)
Run the solver on an argument dict (see solve_prepare)
void bake()
Fix the structure of the optimization problem.
std::vector< MX > active_symvar(VariableType type) const
Get the symbols of a given type that appear in the problem.
MX g_lookup(casadi_index i) const
Get the constraint expression that owns row i of g.
OptiAdvanced(const Opti &x)
bool solver_dirty() const
True when the solver must be reconstructed.
void set_meta_con(const MX &m, const MetaCon &meta)
Set meta-data of an expression.
casadi_index g_index_reduce_x(casadi_index i) const
Index into x when row i of g was reduced to a simple bound (-1 otherwise)
MetaCon canon_expr(const MX &expr) const
Classify a constraint expression (for internal use only)
std::string x_describe(casadi_index i, const Dict &opts=Dict()) const
Describe entry i of the flattened x vector.
std::vector< MX > symvar() const
Get the symbols of this instance.
Function casadi_solver() const
Get the underlying nlpsol/qpsol Function.
void res(const DMDict &res)
Store a solver result dict as the latest values (marks the instance solved)
std::vector< MX > symvar(const MX &expr, VariableType type) const
Get the symbols of this instance.
void assert_baked() const
Raise an error when the problem is dirty.
std::string g_describe(casadi_index i, const Dict &opts=Dict()) const
Describe row i of the constraint vector g.
void assert_empty() const
Raise an error if an objective or constraints are present.
casadi_index g_index_reduce_g(casadi_index i) const
Row of the reduced g for row i of g when "detect_simple_bounds" is active (-1 if moved)
void mark_solved(bool flag=true)
Set or clear the solved state.
OptiAdvanced baked_copy() const
Copy of the instance with the problem baked (see bake)
bool is_parametric(const MX &expr) const
Check whether an expression depends on parameters only.
DMDict res() const
Result dict of the latest solve (x, f, g, lam_x, lam_g, lam_p)
void show_infeasibilities(double tol=0, const Dict &opts=Dict()) const
Print the constraints violated at the latest iterate.
std::vector< DM > active_values(VariableType type) const
Initial guesses (or parameter values) of the symbols returned by active_symvar.
void assert_active_symbol(const MX &m) const
Raise an error unless m is a symbol of this instance that appears in the problem.
void assert_solved() const
Raise an error unless solved()
DMDict arg() const
Solver arguments prepared by solve_prepare (x0, p, lam_g0, lbg, ubg)
void solve_prepare()
Prepare the solver arguments (first half of solve)
bool solved() const
True when a solver result is available for value()
~OptiAdvanced()
Destructor.
Definition: optistack.hpp:2795
void set_meta(const MX &m, const MetaVar &meta)
Set meta-data of an expression.
MetaVar get_meta(const MX &m) const
Get meta-data of symbol (for internal use only)
MetaCon get_meta_con(const MX &m) const
Get meta-data of symbol (for internal use only)
casadi_int instance_number() const
Sequence number of this Opti instance in the process; prefixes the symbol names.
Base class of iteration callbacks for Opti.
Definition: optistack.hpp:2764
virtual void call(casadi_int i)
Called after every solver iteration with the iteration number.
Definition: optistack.hpp:2772
OptiCallback(const OptiCallback &obj)
Definition: optistack.hpp:2768
A simplified interface for NLP modeling/solving.
Snapshot of an Opti problem and its solution.
Definition: optistack.hpp:3563
std::string get_str(bool more=false) const
std::vector< MX > value_parameters() const
void disp(std::ostream &stream, bool more=false) const
native_DM value(const DM &x, const std::vector< MX > &values=std::vector< MX >()) const
Evaluate an expression at the solution.
std::string type_name() const
Definition: optistack.hpp:3566
Dict stats() const
Get the solver statistics of this solve.
Opti opti() const
Get the Opti copy this solution belongs to.
Definition: optistack.hpp:3799
native_DM value(const MX &x, const std::vector< MX > &values=std::vector< MX >()) const
Evaluate an expression at the solution.
native_DM value(const SX &x, const std::vector< MX > &values=std::vector< MX >()) const
Evaluate an expression at the solution.
OptiAdvanced optistack_
Definition: optistack.hpp:3803
std::vector< MX > value_variables() const
Get assignment expressions for the optimal solution.
OptiSol(const Opti &opti)
A simplified interface for NLP modeling/solving.
Definition: optistack.hpp:236
native_DM value(const MX &x, const std::vector< MX > &values=std::vector< MX >()) const
Evaluate an expression at the current values.
native_DM value(const SX &x, const std::vector< MX > &values=std::vector< MX >()) const
Evaluate an expression at the current values.
std::vector< MX > value_variables() const
Get assignment expressions for the latest values.
Function scale_helper(const Function &h) const
Scale a helper function constructed via opti.x, opti.g, ...
void set_domain(const MX &x, const std::string &domain)
Set the domain of a decision variable.
void subject_to(const MX &g, const DM &linear_scale, const Dict &options=Dict())
Add constraints.
DM x_linear_scale() const
Per-entry scale of x (see set_linear_scale); a Python property.
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.
native_DM value(const DM &x, const std::vector< MX > &values=std::vector< MX >()) const
Evaluate an expression at the current values.
void subject_to()
Clear all constraints.
MX parameter(const Sparsity &sp, const std::string &attribute="full")
Create a parameter with a given sparsity pattern.
static MX bounded(const MX &lb, const MX &expr, const MX &ub)
Construct a double inequality.
Definition: optistack.hpp:2353
casadi_int ng() const
Number of (scalarised) constraints.
void minimize(const MX &f, double linear_scale=1)
Set the objective.
void callback_class(OptiCallback *callback)
Helper methods for callback()
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.
casadi_int np() const
Number of (scalarised) parameters.
void set_initial(const std::vector< MX > &assignments)
Set the initial guess of decision variables or dual variables.
Dict stats() const
Get the statistics of the last solve.
void subject_to(const std::vector< MX > &g, const Dict &options=Dict())
Add constraints.
MX variable(const MX &symbol, const std::string &attribute="full")
Register an existing MX symbol as a decision variable of this instance.
MX parameter(const MX &symbol, const std::string &attribute="full")
Register an existing MX symbol as a parameter of this instance.
void subject_to(const MX &g, const Dict &options=Dict())
Add constraints.
void disp(std::ostream &stream, bool more=false) const
Print a summary of the instance.
MX lbg() const
Get all (scalarised) bounds on constraints as a column vector.
std::string return_status() const
Get the return status of the last solve.
casadi_int nx() const
Number of (scalarised) decision variables.
Opti(const std::string &problem_type="nlp")
Create an empty Opti context.
std::string get_str(bool more=false) const
Get string representation.
OptiAdvanced debug() const
Get a copy with advanced (debugging) functionality.
MX variable(casadi_int n=1, casadi_int m=1, const std::string &attribute="full")
Create a decision variable (symbol)
MX f() const
Get the objective expression.
OptiAdvanced advanced() const
Get a copy with advanced functionality.
Opti copy() const
Get a deep copy of the Opti instance.
Dict user_dict(const MX &m) const
Get the user data of a symbol or constraint.
void subject_to(const std::vector< MX > &g, const DM &linear_scale, const Dict &options=Dict())
Add constraints.
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.
void set_linear_scale(const MX &x, const DM &scale, const DM &offset=0)
Set the linear scaling of a decision variable.
std::vector< MX > initial() const
Get assignment expressions for the initial guesses.
MX parameter(casadi_int n=1, casadi_int m=1, const std::string &attribute="full")
Create a parameter (symbol); fixed during optimization.
void set_value(const MX &x, const DM &v)
Set the value of a parameter.
DM x_linear_scale_offset() const
Per-entry offset of x (see set_linear_scale); a Python property.
void callback_class()
Helper methods for callback()
MX p() const
Get all (scalarised) parameters as a symbolic column vector.
MX variable(const Sparsity &sp, const std::string &attribute="full")
Create a decision variable with a given sparsity pattern; only "full" is supported.
MX ubg() const
void solver(const std::string &solver, const Dict &plugin_options=Dict(), const Dict &solver_options=Dict())
Select the numerical solver and its options.
std::vector< MX > value_parameters() const
MX dual(const MX &m) const
Get the dual variable (Lagrange multiplier) of a constraint.
void set_initial(const MX &x, const DM &v)
Set the initial guess of decision variables or dual variables.
void update_user_dict(const MX &m, const Dict &meta)
Add user data to a symbol or constraint.
OptiSol solve()
Solve the problem.
void set_value(const std::vector< MX > &assignments)
Set the value of a parameter.
DM g_linear_scale() const
Per-row scale of g (see subject_to); a Python property.
MX lam_g() const
Get all (scalarised) dual variables as a symbolic column vector.
MX x() const
Get all (scalarised) decision variables as a symbolic column vector.
void update_user_dict(const std::vector< MX > &m, const Dict &meta)
std::string type_name() const
Readable name of the class.
Definition: optistack.hpp:2600
double f_linear_scale() const
Scale of the objective (see minimize); a Python property.
OptiSol solve_limited()
Solve the problem, accepting a limit as outcome.
MX g() const
Get all (scalarised) constraint expressions as a column vector.
GenericShared implements a reference counting framework similar for efficient and.
General sparsity class.
Definition: sparsity.hpp:200
The casadi namespace.
Definition: archiver.hpp:32
CASADI_EXPORT std::ostream & uout()
VariableType
Kind of an Opti symbol (MetaVar::type)
Definition: optistack.hpp:2711
@ OPTI_DUAL_G
Definition: optistack.hpp:2714
DomainType
Domain of a decision variable (see Opti::set_domain)
Definition: optistack.hpp:2717
@ OPTI_DOMAIN_INTEGER
Definition: optistack.hpp:2719
@ OPTI_DOMAIN_REAL
Definition: optistack.hpp:2718
GenericType::Dict Dict
C++ equivalent of Python's dict or MATLAB's struct.
DM native_DM
Definition: optistack.hpp:33
ConstraintType
How subject_to() classified a constraint (MetaCon::type)
Definition: optistack.hpp:2702
@ OPTI_DOUBLE_INEQUALITY
Definition: optistack.hpp:2707
@ OPTI_INEQUALITY
Definition: optistack.hpp:2706
@ OPTI_GENERIC_INEQUALITY
Definition: optistack.hpp:2704
@ OPTI_EQUALITY
Definition: optistack.hpp:2705
@ OPTI_GENERIC_EQUALITY
Definition: optistack.hpp:2703
@ OPTI_UNKNOWN
Definition: optistack.hpp:2709
std::map< std::string, DM > DMDict
Definition: dm_fwd.hpp:36
Range [start, stop) of a symbol or constraint in the flattened x or g vector.
Definition: optistack.hpp:2724
Metadata of a constraint, as returned by OptiAdvanced::canon_expr/get_meta_con.
Definition: optistack.hpp:2730
ConstraintType type
Definition: optistack.hpp:2734
casadi_int n
Definition: optistack.hpp:2737
Metadata of a symbol, as returned by OptiAdvanced::get_meta.
Definition: optistack.hpp:2745
casadi_int active_i
Definition: optistack.hpp:2753
std::string attribute
Definition: optistack.hpp:2746
DomainType domain
Definition: optistack.hpp:2750
VariableType type
Definition: optistack.hpp:2749
casadi_int count
Definition: optistack.hpp:2751
casadi_int i
Definition: optistack.hpp:2752
casadi_int m
Definition: optistack.hpp:2748
casadi_int n
Definition: optistack.hpp:2747