IPOPTSolver.hh 14.4 KB
Newer Older
David Bommes's avatar
David Bommes committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//=============================================================================
//
//  CLASS IPOPTSolver
//
//=============================================================================


#ifndef COMISO_IPOPTSOLVER_HH
#define COMISO_IPOPTSOLVER_HH


//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================
#include <CoMISo/Config/config.hh>
#if COMISO_IPOPT_AVAILABLE

//== INCLUDES =================================================================

Jan Möbius's avatar
Jan Möbius committed
18
#include <CoMISo/Config/CoMISoDefines.hh>
19
#include <CoMISo/Utils/StopWatch.hh>
David Bommes's avatar
David Bommes committed
20 21 22 23
#include <vector>
#include <cstddef>
#include <gmm/gmm.h>
#include "NProblemGmmInterface.hh"
David Bommes's avatar
David Bommes committed
24
#include "NProblemInterface.hh"
David Bommes's avatar
David Bommes committed
25
#include "NConstraintInterface.hh"
David Bommes's avatar
David Bommes committed
26
#include "BoundConstraint.hh"
David Bommes's avatar
David Bommes committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <IpTNLP.hpp>
#include <IpIpoptApplication.hpp>
#include <IpSolveStatistics.hpp>

//== FORWARDDECLARATIONS ======================================================

//== NAMESPACES ===============================================================

namespace COMISO {

//== CLASS DEFINITION =========================================================

	      

/** \class NewtonSolver NewtonSolver.hh <ACG/.../NewtonSolver.hh>

    Brief Description.
  
    A more elaborate description follows.
*/
Jan Möbius's avatar
Jan Möbius committed
47
class COMISODLLEXPORT IPOPTSolver
David Bommes's avatar
David Bommes committed
48 49 50
{
public:
   
David Bommes's avatar
David Bommes committed
51 52
  /// Default constructor -> set up IpOptApplication
  IPOPTSolver();
David Bommes's avatar
David Bommes committed
53 54 55 56
 
  /// Destructor
  ~IPOPTSolver() {}

David Bommes's avatar
David Bommes committed
57
  // ********** SOLVE **************** //
David Bommes's avatar
David Bommes committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  // solve -> returns ipopt status code
//------------------------------------------------------
//  enum ApplicationReturnStatus
//    {
//      Solve_Succeeded=0,
//      Solved_To_Acceptable_Level=1,
//      Infeasible_Problem_Detected=2,
//      Search_Direction_Becomes_Too_Small=3,
//      Diverging_Iterates=4,
//      User_Requested_Stop=5,
//      Feasible_Point_Found=6,
//
//      Maximum_Iterations_Exceeded=-1,
//      Restoration_Failed=-2,
//      Error_In_Step_Computation=-3,
//      Maximum_CpuTime_Exceeded=-4,
//      Not_Enough_Degrees_Of_Freedom=-10,
//      Invalid_Problem_Definition=-11,
//      Invalid_Option=-12,
//      Invalid_Number_Detected=-13,
//
//      Unrecoverable_Exception=-100,
//      NonIpopt_Exception_Thrown=-101,
//      Insufficient_Memory=-102,
//      Internal_Error=-199
//    };
//------------------------------------------------------

86
  int solve(NProblemInterface*    _problem, const std::vector<NConstraintInterface*>& _constraints);
David Bommes's avatar
David Bommes committed
87

88 89 90 91 92 93 94 95
  // same as above with additional lazy constraints that are only added iteratively to the problem if not satisfied
  int solve(NProblemInterface*                        _problem,
            const std::vector<NConstraintInterface*>& _constraints,
            const std::vector<NConstraintInterface*>& _lazy_constraints,
            const double                              _almost_infeasible = 0.5,
            const int                                 _max_passes        = 5   );


96 97 98
  // for convenience, if no constraints are given
  int solve(NProblemInterface*    _problem);

David Bommes's avatar
David Bommes committed
99
  // deprecated interface for backwards compatibility
David Bommes's avatar
David Bommes committed
100
  int solve(NProblemGmmInterface* _problem, std::vector<NConstraintInterface*>& _constraints);
David Bommes's avatar
David Bommes committed
101

David Bommes's avatar
David Bommes committed
102 103
  // ********* CONFIGURATION ********************* //
  // access the ipopt-application (for setting parameters etc.)
David Bommes's avatar
David Bommes committed
104 105
  // examples: app().Options()->SetIntegerValue("max_iter", 100);
  //           app().Options()->SetStringValue("derivative_test", "second-order");
David Bommes's avatar
David Bommes committed
106 107 108
  Ipopt::IpoptApplication& app() {return (*app_); }


David Bommes's avatar
David Bommes committed
109 110 111 112 113 114
  void set_print_level(const int _level)
  {
    app().Options()->SetIntegerValue("print_level", _level);
    print_level_ = _level;
  }

David Bommes's avatar
David Bommes committed
115 116 117 118 119 120 121 122 123 124 125
protected:
  double* P(std::vector<double>& _v)
  {
    if( !_v.empty())
      return ((double*)&_v[0]);
    else
      return 0;
  }

private:

David Bommes's avatar
David Bommes committed
126 127
  // smart pointer to IpoptApplication to set options etc.
  Ipopt::SmartPtr<Ipopt::IpoptApplication> app_;
David Bommes's avatar
David Bommes committed
128 129

  int print_level_;
David Bommes's avatar
David Bommes committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
};


//== CLASS DEFINITION PROBLEM INSTANCE=========================================================


class NProblemIPOPT : public Ipopt::TNLP
{
public:

  // Ipopt Types
  typedef Ipopt::Number                    Number;
  typedef Ipopt::Index                     Index;
  typedef Ipopt::SolverReturn              SolverReturn;
  typedef Ipopt::IpoptData                 IpoptData;
  typedef Ipopt::IpoptCalculatedQuantities IpoptCalculatedQuantities;

David Bommes's avatar
David Bommes committed
147 148 149 150 151 152
  // sparse matrix and vector types
  typedef NConstraintInterface::SVectorNC SVectorNC;
  typedef NConstraintInterface::SMatrixNC SMatrixNC;
  typedef NProblemInterface::SMatrixNP    SMatrixNP;

  /** default constructor */
David Bommes's avatar
David Bommes committed
153
  NProblemIPOPT(NProblemInterface* _problem, const std::vector<NConstraintInterface*>& _constraints, const bool _hessian_approximation = false)
154 155 156 157 158 159 160 161 162
   : problem_(_problem), store_solution_(false), hessian_approximation_(_hessian_approximation)
  {
    // initialize solution
    x_.resize(_problem->n_unknowns());
    _problem->initial_x(P(x_));

    split_constraints(_constraints);
    analyze_special_properties(_problem, _constraints);
  }
David Bommes's avatar
David Bommes committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

  /** default destructor */
  virtual ~NProblemIPOPT() {};

  /**@name Overloaded from TNLP */
  //@{
  /** Method to return some info about the nlp */
  virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,
                            Index& nnz_h_lag, IndexStyleEnum& index_style);

  /** Method to return the bounds for my problem */
  virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u,
                               Index m, Number* g_l, Number* g_u);

  /** Method to return the starting point for the algorithm */
  virtual bool get_starting_point(Index n, bool init_x, Number* x,
                                  bool init_z, Number* z_L, Number* z_U,
                                  Index m, bool init_lambda,
                                  Number* lambda);

  /** Method to return the objective value */
  virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value);

  /** Method to return the gradient of the objective */
  virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f);

  /** Method to return the constraint residuals */
  virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g);

  /** Method to return:
   *   1) The structure of the jacobian (if "values" is NULL)
   *   2) The values of the jacobian (if "values" is not NULL)
   */
  virtual bool eval_jac_g(Index n, const Number* x, bool new_x,
                          Index m, Index nele_jac, Index* iRow, Index *jCol,
                          Number* values);

  /** Method to return:
   *   1) The structure of the hessian of the lagrangian (if "values" is NULL)
   *   2) The values of the hessian of the lagrangian (if "values" is not NULL)
   */
  virtual bool eval_h(Index n, const Number* x, bool new_x,
                      Number obj_factor, Index m, const Number* lambda,
                      bool new_lambda, Index nele_hess, Index* iRow,
                      Index* jCol, Number* values);

  //@}

  /** @name Solution Methods */
  //@{
  /** This method is called when the algorithm is complete so the TNLP can store/write the solution */
  virtual void finalize_solution(SolverReturn status,
                                 Index n, const Number* x, const Number* z_L, const Number* z_U,
                                 Index m, const Number* g, const Number* lambda,
                                 Number obj_value,
                                 const IpoptData* ip_data,
                                 IpoptCalculatedQuantities* ip_cq);
  //@}

222 223 224 225 226 227 228 229
  // special properties of problem
  bool hessian_constant() const;
  bool jac_c_constant() const;
  bool jac_d_constant() const;

  bool&                 store_solution()  {return store_solution_; }
  std::vector<double>&  solution()        {return x_;}

David Bommes's avatar
David Bommes committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
private:
  /**@name Methods to block default compiler methods.
   * The compiler automatically generates the following three methods.
   *  Since the default compiler implementation is generally not what
   *  you want (for all but the most simple classes), we usually
   *  put the declarations of these methods in the private section
   *  and never implement them. This prevents the compiler from
   *  implementing an incorrect "default" behavior without us
   *  knowing. (See Scott Meyers book, "Effective C++")
   *
   */
  //@{
  //  MyNLP();
  NProblemIPOPT(const NProblemIPOPT&);
  NProblemIPOPT& operator=(const NProblemIPOPT&);
  //@}

  // split user-provided constraints into general-constraints and bound-constraints
248
  void split_constraints(const std::vector<NConstraintInterface*>& _constraints);
David Bommes's avatar
David Bommes committed
249

250 251 252 253
  // determine if hessian_constant, jac_c_constant or jac_d_constant
  void analyze_special_properties(const NProblemInterface* _problem, const std::vector<NConstraintInterface*>& _constraints);


David Bommes's avatar
David Bommes committed
254 255 256 257 258 259 260 261 262
protected:
  double* P(std::vector<double>& _v)
  {
    if( !_v.empty())
      return ((double*)&_v[0]);
    else
      return 0;
  }

David Bommes's avatar
David Bommes committed
263 264 265 266 267 268 269
private:

  // pointer to problem instance
  NProblemInterface* problem_;
  // reference to constraints vector
  std::vector<NConstraintInterface*> constraints_;
  std::vector<BoundConstraint*>      bound_constraints_;
270 271 272 273 274 275 276

  bool hessian_constant_;
  bool jac_c_constant_;
  bool jac_d_constant_;

  bool store_solution_;
  std::vector<double> x_;
David Bommes's avatar
David Bommes committed
277 278

  bool hessian_approximation_;
David Bommes's avatar
David Bommes committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
};


//== CLASS DEFINITION PROBLEM INSTANCE=========================================================


class NProblemGmmIPOPT : public Ipopt::TNLP
{
public:

  // Ipopt Types
  typedef Ipopt::Number                    Number;
  typedef Ipopt::Index                     Index;
  typedef Ipopt::SolverReturn              SolverReturn;
  typedef Ipopt::IpoptData                 IpoptData;
  typedef Ipopt::IpoptCalculatedQuantities IpoptCalculatedQuantities;

David Bommes's avatar
David Bommes committed
296 297 298 299 300
  // sparse matrix and vector types
  typedef NConstraintInterface::SVectorNC SVectorNC;
  typedef NConstraintInterface::SMatrixNC SMatrixNC;
  typedef gmm::wsvector<double>           SVectorNP;
  typedef NProblemGmmInterface::SMatrixNP SMatrixNP;
David Bommes's avatar
David Bommes committed
301 302 303 304 305 306 307

  typedef gmm::array1D_reference<       double* > VectorPT;
  typedef gmm::array1D_reference< const double* > VectorPTC;

  typedef gmm::array1D_reference<       Index* > VectorPTi;
  typedef gmm::array1D_reference< const Index* > VectorPTCi;

Jan Möbius's avatar
Jan Möbius committed
308 309
  typedef gmm::linalg_traits<SVectorNP>::const_iterator SVectorNP_citer;
  typedef gmm::linalg_traits<SVectorNP>::iterator       SVectorNP_iter;
David Bommes's avatar
David Bommes committed
310 311

  /** default constructor */
David Bommes's avatar
David Bommes committed
312
  NProblemGmmIPOPT(NProblemGmmInterface* _problem, std::vector<NConstraintInterface*>& _constraints)
313 314
   : problem_(_problem), constraints_(_constraints), nnz_jac_g_(0), nnz_h_lag_(0) 
   {}
David Bommes's avatar
David Bommes committed
315 316

  /** default destructor */
David Bommes's avatar
David Bommes committed
317
  virtual ~NProblemGmmIPOPT() {};
David Bommes's avatar
David Bommes committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

  /**@name Overloaded from TNLP */
  //@{
  /** Method to return some info about the nlp */
  virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,
                            Index& nnz_h_lag, IndexStyleEnum& index_style);

  /** Method to return the bounds for my problem */
  virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u,
                               Index m, Number* g_l, Number* g_u);

  /** Method to return the starting point for the algorithm */
  virtual bool get_starting_point(Index n, bool init_x, Number* x,
                                  bool init_z, Number* z_L, Number* z_U,
                                  Index m, bool init_lambda,
                                  Number* lambda);

  /** Method to return the objective value */
  virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value);

  /** Method to return the gradient of the objective */
  virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f);

  /** Method to return the constraint residuals */
  virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g);

  /** Method to return:
   *   1) The structure of the jacobian (if "values" is NULL)
   *   2) The values of the jacobian (if "values" is not NULL)
   */
  virtual bool eval_jac_g(Index n, const Number* x, bool new_x,
                          Index m, Index nele_jac, Index* iRow, Index *jCol,
                          Number* values);

  /** Method to return:
   *   1) The structure of the hessian of the lagrangian (if "values" is NULL)
   *   2) The values of the hessian of the lagrangian (if "values" is not NULL)
   */
  virtual bool eval_h(Index n, const Number* x, bool new_x,
                      Number obj_factor, Index m, const Number* lambda,
                      bool new_lambda, Index nele_hess, Index* iRow,
                      Index* jCol, Number* values);

  //@}

  /** @name Solution Methods */
  //@{
  /** This method is called when the algorithm is complete so the TNLP can store/write the solution */
  virtual void finalize_solution(SolverReturn status,
                                 Index n, const Number* x, const Number* z_L, const Number* z_U,
                                 Index m, const Number* g, const Number* lambda,
                                 Number obj_value,
                                 const IpoptData* ip_data,
                                 IpoptCalculatedQuantities* ip_cq);
  //@}

private:
  /**@name Methods to block default compiler methods.
   * The compiler automatically generates the following three methods.
   *  Since the default compiler implementation is generally not what
   *  you want (for all but the most simple classes), we usually
   *  put the declarations of these methods in the private section
   *  and never implement them. This prevents the compiler from
   *  implementing an incorrect "default" behavior without us
   *  knowing. (See Scott Meyers book, "Effective C++")
   *
   */
  //@{
  //  MyNLP();
David Bommes's avatar
David Bommes committed
387 388
  NProblemGmmIPOPT(const NProblemGmmIPOPT&);
  NProblemGmmIPOPT& operator=(const NProblemGmmIPOPT&);
David Bommes's avatar
David Bommes committed
389 390 391 392 393 394 395 396
  //@}


private:

  // pointer to problem instance
  NProblemGmmInterface* problem_;
  // reference to constraints vector
David Bommes's avatar
David Bommes committed
397
  std::vector<NConstraintInterface*>& constraints_;
David Bommes's avatar
David Bommes committed
398 399 400 401 402 403 404 405 406

  int nnz_jac_g_;
  int nnz_h_lag_;

  // constant structure of jacobian_of_constraints and hessian_of_lagrangian
  std::vector<Index> jac_g_iRow_;
  std::vector<Index> jac_g_jCol_;
  std::vector<Index> h_lag_iRow_;
  std::vector<Index> h_lag_jCol_;
David Bommes's avatar
David Bommes committed
407 408 409

  // Sparse Matrix of problem (don't initialize every time!!!)
  SMatrixNP HP_;
David Bommes's avatar
David Bommes committed
410 411 412 413 414 415 416 417 418 419 420 421
};


//=============================================================================
} // namespace COMISO

//=============================================================================
#endif // COMISO_IPOPT_AVAILABLE
//=============================================================================
#endif // ACG_IPOPTSOLVER_HH defined
//=============================================================================