Changeset 53


Ignore:
Timestamp:
Sep 28, 2006 2:19:58 PM (13 years ago)
Author:
pbonami
Message:

Did some space for other NLP solver
1 - Created new OsiTMINLPInterface as base class for interfaces
2 - Created new TNLPSolver as base class for the interface to a solver capable of solving a TNLP
3 - derived the classes for Ipopt
4 - Start putting some namespace Bonmin around

Location:
branches/devel/Bonmin
Files:
41 edited
4 copied

Legend:

Unmodified
Added
Removed
  • branches/devel/Bonmin/examples/CppExample/MyTMINLP.hpp

    r49 r53  
    1111#include "TMINLP.hpp"
    1212using namespace  Ipopt;
     13using namespace Bonmin;
    1314/** A C++ example for interfacing an MINLP with bonmin.
    1415   * This class implements the following NLP :
  • branches/devel/Bonmin/src/Apps/bonmin.cpp

    r26 r53  
    2222#include "CbcBonmin.hpp"
    2323
    24 
     24using namespace Bonmin;
    2525
    2626/** Procedure to ouptut relevant informations in the case of a failure.
     
    118118  using namespace Ipopt;
    119119 
    120   BonminAmplInterface * nlpSolver;
     120  AmplInterface * nlpSolver;
    121121  char * pbName = NULL;
    122122  if(argc > 1)
     
    127127  else //will just output usage
    128128  {
    129     nlpSolver = new BonminAmplInterface(argv);
     129    nlpSolver = new AmplInterface(argv);
    130130    delete nlpSolver;
    131131    return 0;
     
    133133  double time1 = CoinCpuTime();
    134134  try {
    135   nlpSolver = new BonminAmplInterface(argv);
     135  nlpSolver = new AmplInterface(argv);
    136136    BonminCbcParam par;
    137137    BonminBB bb;
  • branches/devel/Bonmin/src/Apps/nodeSolver.cpp

    r1 r53  
    2121#include "BonminAmplInterface.hpp"
    2222
    23 #include "IpCbcBoundsReader.hpp"
     23#include "BoundsReader.hpp"
    2424#include "IpCbcStartPointReader.hpp"
    2525
     
    5656
    5757
    58   BonminAmplInterface nlpSolver(myArgv);
     58  Bonmin::AmplInterface nlpSolver(myArgv);
    5959
    6060  Ipopt::SmartPtr<Ipopt::OptionsList> Options =
     
    6868      // Read the bounds and change them in Ipopt
    6969      if(argc>2) {
    70         IpCbcBoundsReader bounds(nodeFileName);
    71         bounds.readAndApply(nlpSolver);
     70        Bonmin::BoundsReader bounds(nodeFileName);
     71        bounds.readAndApply(&nlpSolver);
    7272      }
    7373      if(argc>3) {
    74         IpCbcStartPointReader init(startingPointFile);
     74        Bonmin::IpCbcStartPointReader init(startingPointFile);
    7575        init.readAndApply(nlpSolver);
    7676      }
     
    8686      }
    8787    }
    88   catch(IpoptInterface::SimpleError &E) {
     88  catch(Bonmin::OsiTMINLPInterface::SimpleError &E) {
    8989    std::cerr<<E.className()<<"::"<<E.methodName()
    9090             <<std::endl
  • branches/devel/Bonmin/src/BonminAmplInterface/AmplTMINLP.cpp

    r26 r53  
    2424  void sos_kludge(int nsos, int *sosbeg, double *sosref);
    2525}
    26 namespace Ipopt
     26namespace Bonmin
    2727{
    2828
     
    6363
    6464    if(suffix_handler==NULL)
    65       suffix_handler_ = suffix_handler = new AmplSuffixHandler();
     65      suffix_handler_ = suffix_handler = new Ipopt::AmplSuffixHandler();
    6666
    6767    // Add the suffix handler for scaling
     
    101101
    102102  AmplTMINLP::~AmplTMINLP()
    103   {}
     103  {delete ampl_tnlp_;}
    104104
    105105  void
  • branches/devel/Bonmin/src/BonminAmplInterface/AmplTMINLP.hpp

    r26 r53  
    1717#include "CoinPackedMatrix.hpp"
    1818#include "OsiCuts.hpp"
    19 
    20 namespace Ipopt
    21 {
    22 
    23 
    24   // Declarations, so that we don't have to include the Ipopt AMPL headers
     19// Declarations, so that we don't have to include the Ipopt AMPL headers
     20namespace Ipopt{
    2521  class AmplTNLP;
    2622  class AmplSuffixHandler;
    2723  class AmplOptionsList;
     24}
     25
     26namespace Bonmin
     27{
     28
     29
    2830
    2931  /** Ampl MINLP Interface.
  • branches/devel/Bonmin/src/BonminAmplInterface/BonminAmplInterface.cpp

    r1 r53  
    33#include <sstream>
    44
     5
     6namespace Bonmin {
    57/** Default constructor */
    6 BonminAmplInterface::BonminAmplInterface(): IpoptInterface(), amplTminlp_(NULL)
     8AmplInterface::AmplInterface(): IpoptInterface(), amplTminlp_(NULL)
    79{}
    810 
    911/** Constructor with inputed ampl command line (reads model from nl file)*/
    10 BonminAmplInterface::BonminAmplInterface(char **& amplArgs)
     12AmplInterface::AmplInterface(char **& amplArgs)
    1113:
    1214IpoptInterface(),
     
    1719
    1820/** Copy constructor */
    19 BonminAmplInterface::BonminAmplInterface(const BonminAmplInterface &other):
     21AmplInterface::AmplInterface(const AmplInterface &other):
    2022          IpoptInterface(other), amplTminlp_(NULL)
    2123{
    22   amplTminlp_ = dynamic_cast<Ipopt::AmplTMINLP *> (GetRawPtr(tminlp_));
     24  amplTminlp_ = dynamic_cast<Bonmin::AmplTMINLP *> (GetRawPtr(tminlp_));
    2325}
    2426/// Clone
    25 BonminAmplInterface *
    26 BonminAmplInterface::clone(bool CopyData )
     27AmplInterface *
     28AmplInterface::clone(bool CopyData )
    2729{
    28   return new BonminAmplInterface(*this);
     30  return new AmplInterface(*this);
    2931}
    3032
    3133///Destructor
    32 BonminAmplInterface::~BonminAmplInterface()
     34AmplInterface::~AmplInterface()
    3335{amplTminlp_ = NULL;}
    3436
    3537/** Read an ampl . nl file from the given filename */
    3638void
    37 BonminAmplInterface::readAmplNlFile(char**& filename,
     39AmplInterface::readAmplNlFile(char**& filename,
    3840    std::string* ipopt_file_content,
    3941    std::string* nl_file_content)
     
    4244
    4345
    44   app_ = new Ipopt::IpoptApplication();
     46  app_ = new IpoptSolver;
    4547
    4648  SmartPtr<RegisteredOptions> roptions = app_->RegOptions();
     
    6062
    6163  // set the default options... expect_infeasible, etc...
    62   set_ipopt_minlp_default(app_->Options());
    63 
     64  IpoptSolver * ipopt = dynamic_cast<IpoptSolver *> (GetRawPtr(app_));
    6465  if(!IsValid(tminlp_)) {
    65         amplTminlp_ = new AmplTMINLP(ConstPtr(app_->Jnlst()), app_->Options(), filename,
     66        amplTminlp_ = new AmplTMINLP(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
    6667        NULL, appName() , nl_file_content);
    6768        tminlp_ = GetRawPtr(amplTminlp_);
     
    7172    if(amplTMINLP) {
    7273      AmplTMINLP * newAmpl = amplTMINLP->createEmpty();
    73       newAmpl->Initialize(ConstPtr(app_->Jnlst()), app_->Options(), filename,
     74      newAmpl->Initialize(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
    7475          NULL, appName() , nl_file_content);
    7576      amplTminlp_ = newAmpl;
     
    7778    }
    7879    else {
    79       amplTminlp_ = new AmplTMINLP(ConstPtr(app_->Jnlst()), app_->Options(), filename,
     80      amplTminlp_ = new AmplTMINLP(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
    8081          NULL, appName() , nl_file_content);
    8182      tminlp_ = GetRawPtr(amplTminlp_);
    8283    }
    8384  }
    84   problem_ = new Ipopt::TMINLP2TNLP(tminlp_, *app_->Options());
     85  problem_ = new TMINLP2TNLP(tminlp_);//, *app_->Options());
    8586
    8687  bool print_options_documentation;
     
    9495    categories.push_back("bonmin options : B-Hyb specific options");
    9596//    roptions->OutputLatexOptionDocumentation2(*app_->Jnlst(),categories);
    96     roptions->OutputOptionDocumentation(*app_->Jnlst(),categories);
     97    roptions->OutputOptionDocumentation(*(ipopt->getIpoptApp().Jnlst()),categories);
    9798  }
    9899
     
    105106  extractInterfaceParams();
    106107  hasBeenOptimized_ = false;
    107   feasibilityProblem_ = new Ipopt::TNLP2FPNLP
    108       (Ipopt::SmartPtr<Ipopt::TNLP>(Ipopt::GetRawPtr(problem_)));
     108  feasibilityProblem_ = new TNLP2FPNLP
     109      (Ipopt::SmartPtr<TNLP>(Ipopt::GetRawPtr(problem_)));
    109110}
    110111
    111112/** write ampl solution file */
    112113void
    113 BonminAmplInterface::writeAmplSolFile(std::string message,const double * primalSol,const double * dualSol)
     114AmplInterface::writeAmplSolFile(std::string message,const double * primalSol,const double * dualSol)
    114115{
    115116  TMINLP * tminlp = GetRawPtr(tminlp_);
     
    121122}
    122123
    123 
     124}
  • branches/devel/Bonmin/src/BonminAmplInterface/BonminAmplInterface.hpp

    r1 r53  
    44#include "AmplTMINLP.hpp"
    55
     6namespace Bonmin {
    67/** Class for providing an Osi interface to Ipopt with an ampl nl file as input. */
    7 class BonminAmplInterface: public IpoptInterface
     8class AmplInterface: public IpoptInterface
    89{
    910  public:
    1011  /** Default constructor */
    11   BonminAmplInterface();
     12  AmplInterface();
    1213  /** Constructor with inputed ampl command line (reads model from nl file)*/
    13   BonminAmplInterface(char **& amplArgs);
     14  AmplInterface(char **& amplArgs);
    1415  /** Copy constructor */
    15   BonminAmplInterface(const BonminAmplInterface &other);
     16  AmplInterface(const AmplInterface &other);
    1617  /// Clone
    17   virtual BonminAmplInterface * clone(bool CopyData = true);
     18  virtual AmplInterface * clone(bool CopyData = true);
    1819
    1920  ///Destructor
    20   virtual ~BonminAmplInterface();
     21  virtual ~AmplInterface();
    2122
    2223   /**@name Methods to input a problem */
     
    3132
    3233  /** Fast access to AmplTMINLP */
    33    const Ipopt::AmplTMINLP * amplModel() const
     34   const AmplTMINLP * amplModel() const
    3435  {
    3536    return GetRawPtr(amplTminlp_);
     
    3839  protected:
    3940   /** TMINLP problem (the original problem usually an AmplTMINLP).*/
    40   Ipopt::SmartPtr<Ipopt::AmplTMINLP> amplTminlp_;
     41  Ipopt::SmartPtr<Bonmin::AmplTMINLP> amplTminlp_;
    4142};
    42 
     43}
    4344#endif
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcLpStrategy.cpp

    r1 r53  
    2323#include "CbcCompareActual.hpp"
    2424
     25
     26namespace Bonmin{
    2527CbcOaStrategy::CbcOaStrategy(int migFreq,
    2628    int probFreq,
     
    125127}
    126128
     129}
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcLpStrategy.hpp

    r1 r53  
    1313
    1414#include "CbcStrategy.hpp"
    15 
     15namespace Bonmin{
    1616/** A class to pass on a CbcStrategy to OA sub-milp solver.
    1717 This class allows to setup GMI, MIR, probing and cover cuts frequency.
     
    6060  int logLevel_;
    6161};
     62}
    6263#endif
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcNlpStrategy.cpp

    r1 r53  
    2323
    2424#include "IpoptInterface.hpp"
    25 
     25namespace Bonmin{
    2626// Default Constructor
    2727BonminCbcNlpStrategy::BonminCbcNlpStrategy(int maxFailures,
     
    147147    }
    148148    else
    149       throw IpoptInterface::UnsolvedError(ipopt->getOptStatus());
     149      throw ipopt->newUnsolvedError(ipopt->getOptStatus());
    150150  }
    151151  return returnStatus;
     
    167167BonminCbcNlpStrategy::setupOther(CbcModel &model)
    168168{}
     169}
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcNlpStrategy.hpp

    r1 r53  
    1818class CoinWarmStartDiff;
    1919
     20
     21namespace Bonmin{
    2022class BonminCbcNlpStrategy : public CbcStrategy
    2123{
     
    9193
    9294};
    93 
     95}
    9496
    9597#endif
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcNode.cpp

    r1 r53  
    2626using namespace std;
    2727
     28
     29namespace Bonmin{
    2830//Default constructor
    2931BonminCbcFullNodeInfo::BonminCbcFullNodeInfo()
     
    146148BonminCbcPartialNodeInfo::~BonminCbcPartialNodeInfo ()
    147149{}
     150}
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcNode.hpp

    r1 r53  
    1515
    1616
    17 
     17namespace Bonmin{
    1818/** \brief Holds information for recreating a subproblem by incremental change
    1919           from the parent for Bonmin
     
    125125  BonminCbcPartialNodeInfo & operator=(const BonminCbcPartialNodeInfo& rhs);
    126126};
     127}
    127128#endif
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcParam.cpp

    r1 r53  
    1212#include "BonminCbcParam.hpp"
    1313
     14namespace Bonmin {
    1415bool
    1516BonminCbcParam::extractParams(IpoptInterface &solver)
     
    9798  return success;
    9899}
     100}
  • branches/devel/Bonmin/src/CbcBonmin/BonminCbcParam.hpp

    r1 r53  
    1313
    1414#include "IpoptInterface.hpp"
     15namespace Bonmin {
    1516class BonminCbcParam
    1617{
     
    141142  }
    142143};
    143 
     144}
    144145#endif
    145146
  • branches/devel/Bonmin/src/CbcBonmin/CbcBonmin.cpp

    r1 r53  
    5151
    5252static CbcModel * currentBranchModel = NULL;
    53 static IpCbcOACutGenerator2 * currentOA = NULL;
     53static Bonmin::IpCbcOACutGenerator2 * currentOA = NULL;
    5454CbcModel * OAModel = NULL;
    5555
     
    6969}
    7070
    71 
     71namespace Bonmin {
    7272/** Constructor.*/
    7373BonminBB::BonminBB():
     
    471471  else return bestBound_;
    472472}
     473}
  • branches/devel/Bonmin/src/CbcBonmin/CbcBonmin.hpp

    r1 r53  
    44#include "BonminCbcParam.hpp"
    55
     6
     7class CbcObject;
     8
     9namespace Bonmin{
    610class IpoptInterface;
    7 class CbcObject;
    811/** Class which performs optimization of an MINLP stored in an IpoptInterface. */
    912class BonminBB
     
    8386  int mipIterationCount_;
    8487};
     88}
    8589#endif
  • branches/devel/Bonmin/src/IpoptInterface/BoundsReader.cpp

    r49 r53  
    88// Date : 26/05/2005
    99
    10 #include "IpCbcBoundsReader.hpp"
     10#include "BoundsReader.hpp"
    1111
    1212#include <fstream>
    13 IpCbcBoundsReader::~IpCbcBoundsReader()
     13
     14namespace Bonmin {
     15BoundsReader::~BoundsReader()
    1416{
    1517  gutsOfDestructor();
    1618}
    17 void IpCbcBoundsReader::gutsOfDestructor()
     19void BoundsReader::gutsOfDestructor()
    1820{
    1921  if(nLower_ > 0) {
     
    4547}
    4648
    47 void IpCbcBoundsReader::read(const std::string &fileName)
     49void BoundsReader::read(const std::string &fileName)
    4850{
    4951  setFileName(fileName);
     
    5153}
    5254
    53 void IpCbcBoundsReader::read()
     55void BoundsReader::read()
    5456{
    5557  gutsOfDestructor();
     
    107109}
    108110
    109 void IpCbcBoundsReader::readAndApply(IpoptInterface& solver)
     111void BoundsReader::readAndApply(OsiTMINLPInterface * solver)
    110112{
    111113  read();
    112114  for(int i = 0 ; i < nLower_ ; i++) {
    113     solver.setColLower(indexLowers_[i], lowerBounds_[i]);
     115    solver->setColLower(indexLowers_[i], lowerBounds_[i]);
    114116  }
    115117  for(int i = 0 ; i < nUpper_ ; i++) {
    116     solver.setColUpper(indexUppers_[i], upperBounds_[i]);
     118    solver->setColUpper(indexUppers_[i], upperBounds_[i]);
    117119  }
    118120}
     121}
  • branches/devel/Bonmin/src/IpoptInterface/BoundsReader.hpp

    r49 r53  
    88// Date : 26/05/2005
    99
    10 #ifndef IpCbcBoundsReader_HPP
    11 #define IpCbcBoundsReader_HPP
     10#ifndef BoundsReader_HPP
     11#define BoundsReader_HPP
    1212
    1313#include <string>
    14 #include "IpoptInterface.hpp"
     14#include "OsiTMINLPInterface.hpp"
    1515
     16
     17namespace Bonmin {
    1618/** Reads a file containing change bounds for variables.
    1719    Files follows pretty much the Bounds section in MPS standard.*/
    18 class IpCbcBoundsReader
     20class BoundsReader
    1921{
    2022public:
    2123  //Default constructor
    22   IpCbcBoundsReader():
     24  BoundsReader():
    2325      fileName_(),
    2426      lowerBounds_(NULL),
     
    2931
    3032  // Constructor with name of the file to read passed.
    31   IpCbcBoundsReader(const std::string &fileName):
     33  BoundsReader(const std::string &fileName):
    3234      fileName_(fileName),
    3335      lowerBounds_(NULL),
     
    4648
    4749  // Destructor
    48   ~IpCbcBoundsReader();
     50  ~BoundsReader();
    4951
    5052  // Cleanup allocated data
     
    5961
    6062  //Read fileName_ and apply the bounds read to solver
    61   void readAndApply(IpoptInterface& solver);
     63  void readAndApply(OsiTMINLPInterface * solver);
    6264private:
    6365
     
    7779  int nUpper_;
    7880};
    79 
     81}
    8082#endif
  • branches/devel/Bonmin/src/IpoptInterface/ColReader.hpp

    r49 r53  
    88// Date : 26/05/2005
    99
    10 #ifndef IpCbcColReader_HPP
    11 #define IpCbcColReader_HPP
     10#ifndef ColReader_HPP
     11#define ColReader_HPP
    1212#include <string>
    1313#include <vector>
     
    2020/** A class for reading a .col file containing name for variable (ampl generated file).
    2121   */
    22 class IpCbcColReader
     22class ColReader
    2323{
    2424public:
    2525  /** Constructor with a file name given by a const char * */
    26   IpCbcColReader(const char * fileName);
     26  ColReader(const char * fileName);
    2727  /** Constructor with a file name given by a string and also default (empty string) */
    28   IpCbcColReader(const std::string & fileName="");
     28  ColReader(const std::string & fileName="");
    2929  /** Reads the .col file*/
    3030  bool readFile();
  • branches/devel/Bonmin/src/IpoptInterface/IpCbcStartPointReader.cpp

    r1 r53  
    1010
    1111
     12namespace Bonmin {
    1213
     14  bool IpCbcStartPointReader::readFile()
     15  {
     16    std::ifstream inFile(fileName_.c_str());
     17    if(!inFile.is_open()) {
     18      std::cerr<<"Error in opening initial point file";
     19      return false;
     20    }
     21    int numPrimals;
     22    int numDuals;
     23    inFile>>numPrimals>>numDuals;
     24    gutsOfDestructor();
     25    primals_ = new double [numPrimals];
     26    duals_ = new double[numDuals];
     27    for(int i = 0; i < numPrimals ; i++) {
     28      inFile>>primals_[i];
     29    }
     30    for(int i = 0; i < numDuals ; i++) {
     31      inFile>>duals_[i];
     32    }
     33    return true;
     34  }
    1335
    14 bool IpCbcStartPointReader::readFile()
    15 {
    16   std::ifstream inFile(fileName_.c_str());
    17   if(!inFile.is_open()) {
    18     std::cerr<<"Error in opening initial point file";
    19     return false;
     36  bool IpCbcStartPointReader::readAndApply(IpoptInterface& solver)
     37  {
     38    readFile();
     39    solver.setWarmStartOptions();
     40    if(primals_)
     41      solver.setColSolution(primals_);
     42    else {
     43      std::cerr<<"No warm start info ???"<<std::endl;
     44      return 0;
     45    }
     46    if(duals_)
     47      solver.setRowPrice(duals_);
     48    else {
     49      std::cerr<<"No warm start info ???"<<std::endl;
     50      return 0;
     51    }
     52    return 1;
    2053  }
    21   int numPrimals;
    22   int numDuals;
    23   inFile>>numPrimals>>numDuals;
    24   gutsOfDestructor();
    25   primals_ = new double [numPrimals];
    26   duals_ = new double[numDuals];
    27   for(int i = 0; i < numPrimals ; i++) {
    28     inFile>>primals_[i];
    29   }
    30   for(int i = 0; i < numDuals ; i++) {
    31     inFile>>duals_[i];
    32   }
    33   return true;
    3454}
    35 
    36 bool IpCbcStartPointReader::readAndApply(IpoptInterface& solver)
    37 {
    38   readFile();
    39   solver.setWarmStartOptions();
    40   if(primals_)
    41     solver.setColSolution(primals_);
    42   else {
    43     std::cerr<<"No warm start info ???"<<std::endl;
    44     return 0;
    45   }
    46   if(duals_)
    47     solver.setRowPrice(duals_);
    48   else {
    49     std::cerr<<"No warm start info ???"<<std::endl;
    50     return 0;
    51   }
    52   return 1;
    53 }
  • branches/devel/Bonmin/src/IpoptInterface/IpCbcStartPointReader.hpp

    r1 r53  
    1616#include "IpoptInterface.hpp"
    1717
     18
     19
     20namespace Bonmin {
    1821/** This class reads a file with a starting point for Ipopt initalization. File format is number of primals number of duals then values one after another
    1922 * Numbering of variables is first variables, then duals on lower bounds duals on upper bounds and to finish duals on constraints */
     
    7881  double * duals_;
    7982};
     83
     84}
    8085#endif /*_IPCBCINITPOINTREADER_H_*/
  • branches/devel/Bonmin/src/IpoptInterface/IpoptIntegerBias.hpp

    r1 r53  
    99// Date : 12/01/2004
    1010
    11 #define INT_BIAS 0e-8
  • branches/devel/Bonmin/src/IpoptInterface/IpoptInterface.cpp

    r44 r53  
    2222
    2323#include "IpSolveStatistics.hpp"
    24 
    25 //For the branch and bound
    26 //#include "CbcModel.hpp"
    27 //#include "IpCbcExtraData.hpp"
    28 
    29 //#include "CbcCompareUser.hpp"
    30 //#include "CbcCompareActual.hpp"
    31 //#include "CbcBranchUser.hpp"
     24#include "IpoptSolver.hpp"
    3225
    3326using namespace Ipopt;
    3427
    35 ///Register options
    36 static void
    37 register_general_options
    38 (Ipopt::SmartPtr<Ipopt::RegisteredOptions> roptions)
    39 {
    40   roptions->SetRegisteringCategory("bonmin output options");
    41 
    42   roptions->AddBoundedIntegerOption("bb_log_level",
    43       "specify main branch-and-bound log level.",
    44       0,3,1,
    45       "Set the level of output of the branch-and-bound : "
    46       "0 - none, 1 - minimal, 2 - normal low, 3 - normal high"
    47                                    );
    48 
    49   roptions->AddLowerBoundedIntegerOption("bb_log_interval",
    50       "Interval at which node level output is printed.",
    51       0,100,
    52       "Set the interval (in terms of number of nodes) at which "
    53       "a log on node resolutions (consisting of lower and upper bounds) is given.");
    54 
    55   roptions->AddBoundedIntegerOption("lp_log_level",
    56       "specify LP log level.",
    57       0,4,0,
    58       "Set the level of output of the linear programming sub-solver in B-Hyb or B-QG : "
    59       "0 - none, 1 - minimal, 2 - normal low, 3 - normal high, 4 - verbose"
    60                                    );
    61 
    62   roptions->AddBoundedIntegerOption("milp_log_level",
    63       "specify MILP subsolver log level.",
    64       0,3,0,
    65       "Set the level of output of the MILP subsolver in OA : "
    66       "0 - none, 1 - minimal, 2 - normal low, 3 - normal high"
    67                                    );
    68 
    69   roptions->AddBoundedIntegerOption("oa_log_level",
    70       "specify OA iterations log level.",
    71       0,2,1,
    72       "Set the level of output of OA decomposition solver : "
    73       "0 - none, 1 - normal, 2 - verbose"
    74                                    );
    75 
    76   roptions->AddLowerBoundedNumberOption("oa_log_frequency",
    77       "display an update on lower and upper bounds in OA every n seconds",
    78       0.,1.,100.,
    79       "");
    80 
    81   roptions->AddBoundedIntegerOption("nlp_log_level",
    82       "specify NLP solver interface log level (independent from ipopt print_level).",
    83       0,2,1,
    84       "Set the level of output of the IpoptInterface : "
    85       "0 - none, 1 - normal, 2 - verbose"
    86                                    );
    87 
    88   roptions->SetRegisteringCategory("bonmin branch-and-bound options");
    89 
    90   roptions->AddStringOption4("algorithm",
    91       "Choice of the algorithm.",
    92       "B-Hyb",
    93       "B-BB","simple branch-and-bound algorithm,",
    94       "B-OA","OA Decomposition algorithm,",
    95       "B-QG","Quesada and Grossmann branch-and-cut algorithm,",
    96       "B-Hyb","hybrid outer approximation based branch-and-cut.",
    97       "This will preset default values for most options of bonmin but depending on which algorithm "
    98       "some of these can be changed.");
    99   roptions->AddLowerBoundedNumberOption("time_limit",
    100       "Set the global maximum computation time (in secs) for the algorithm.",
    101       0.,1,1e10,
    102       "");
    103 
    104   roptions->AddLowerBoundedIntegerOption("node_limit",
    105       "Set the maximum number of nodes explored in the branch-and-bound search.",
    106       0,INT_MAX,
    107       "");
    108 
    109   roptions->AddBoundedNumberOption("integer_tolerance",
    110       "Set integer tolerance.",
    111       0.,1,.5,1,1e-06,
    112       "Any number within that value of an integer is considered integer.");
    113 
    114   roptions->AddBoundedNumberOption("allowable_gap",
    115       "Specify the value of absolute gap under which the algorithm stops.",
    116       -1.e20,0,1.e20,0,0.,
    117       "Stop the tree search when the gap between the objective value of the best known solution"
    118       " and the best bound on the objective of any solution is less than this.");
    119 
    120   roptions->AddBoundedNumberOption("allowable_fraction_gap",
    121       "Specify the value of relative gap under which the algorithm stops.",
    122       -1.e20,0,1.e20,0,0.0,
    123       "Stop the tree search when the gap between the objective value of the best known solution "
    124       "and the best bound on the objective of any solution is less than this "
    125       "fraction of the absolute value of the best known solution value.");
    126 
    127   roptions->AddBoundedNumberOption("cutoff",
    128       "Specify cutoff value.",
    129       -1e100,0,1e100,0,1e100,
    130       "cutoff should be the value of a feasible solution known by the user "
    131       "(if any). The algorithm will only look for solutions better than cutoof.");
    132 
    133 
    134   roptions->AddBoundedNumberOption("cutoff_decr",
    135       "Specify cutoff decrement.",
    136       -1e10,0,1e10,0,1e-05,
    137       "Specify the amount by which cutoff is decremented below "
    138       "a new best upper-bound"
    139       " (usually a small postive value but in non-convex problems it may be a negative value).");
    140 
    141   roptions->AddStringOption4("nodeselect_stra",
    142       "Choose the node selection strategy.",
    143       "best-bound",
    144       "best-bound", "choose node whith the smallest bound,",
    145       "depth-first", "Perform depth first search,",
    146       "breadth-first", "Perform breadth first search,",
    147       "dynamic", "Cbc dynamic strategy (starts with a depth first search and turn to best bound after 3 "
    148       "integer feasible solutions have been found).",
    149       "Choose the strategy for selecting the next node to be processed.");
    150 
    151   roptions->AddLowerBoundedIntegerOption("number_strong_branch",
    152       "Choose the maximum number of variables considered for strong branching.",
    153       0,20,
    154       "Set the number of variables on which to do strong branching.");
    155 
    156   roptions->AddLowerBoundedIntegerOption
    157   ("number_before_trust",
    158    "Set the number of branches on a variable before its pseudo costs are to be believed "
    159    "in dynamic strong branching.",
    160    0,8,
    161    "A value of 0 disables dynamic strong branching.");
    162 
    163   roptions->AddStringOption3("warm_start",
    164       "Select the warm start method",
    165       "optimum",
    166       "none","No warm start",
    167       "optimum","Warm start with direct parent optimum",
    168       "interior_point","Warm start with an interior point of direct parent",
    169       "This will affect the function IpoptInterface::getWarmStart(), and as a consequence the wam starting in the various algorithms.");
    170 
    171   roptions->AddStringOption2("sos_constraints",
    172                              "Wether or not to activate SOS constraints.",
    173                              "enable",
    174                              "enable","",
    175                              "disable","",
    176                              "(only type 1 SOS are supported at the moment)");
    177 
    178   roptions->SetRegisteringCategory("bonmin options for robustness");
    179 
    180   roptions->AddLowerBoundedNumberOption("max_random_point_radius",
    181       "Set max value r for coordinate of a random point.",
    182       0.,1,1e5,
    183       "When picking a random point coordinate i will be in the interval [min(max(l,-r),u-r), max(min(u,r),l+r)] "
    184       "(where l is the lower bound for the variable and u is its upper bound)");
    185 
    186   roptions->AddLowerBoundedIntegerOption
    187   ("max_consecutive_failures",
    188    "(temporarily removed) Number $n$ of consecutive unsolved problems before aborting a branch of the tree.",
    189    0,10,
    190    "When $n > 0$, continue exploring a branch of the tree until $n$ "
    191    "consecutive problems in the branch are unsolved (we call unsolved a problem for which Ipopt can not "
    192    "guarantee optimality within the specified tolerances).");
    193 
    194   roptions->AddLowerBoundedIntegerOption
    195   ("num_iterations_suspect",
    196    "Number of iterations over which a node is considered \"suspect\" (for debugging purposes only, see detailed documentation).",
    197    -1,-1,
    198    "When the number of iterations to solve a node is above this number, the subproblem at this"
    199    " node is considered to be suspect and it will be outputed in a file (set to -1 to deactivate this).");
    200 
    201   roptions->AddStringOption2("nlp_failure_behavior",
    202       "Set the behavior when an NLP or a series of NLP are unsolved by Ipopt (we call unsolved an NLP for which Ipopt is not "
    203       "able to guarantee optimality within the specified tolerances).",
    204       "stop",
    205       "stop", "Stop when failure happens.",
    206       "fathom", "Continue when failure happens.",
    207       "If set to \"fathom\", the algorithm will fathom the node when Ipopt fails to find a solution to the nlp "
    208       "at that node whithin the specified tolerances. "
    209       "The algorithm then becomes a heuristic, and the user will be warned that the solution might not be optimal.");
    210 
    211   roptions->AddLowerBoundedIntegerOption("num_retry_unsolved_random_point",
    212       "Number $k$ of times that the algorithm will try to resolve an unsolved NLP with a random starting point "
    213       "(we call unsolved an NLP for which Ipopt is not "
    214       "able to guarantee optimality within the specified tolerances).",
    215       0,0,
    216       "When Ipopt fails to solve a continuous NLP sub-problem, if $k > 0$, the algorithm will "
    217       "try again to solve the failed NLP with $k$ new randomly chosen starting points "
    218       " or until the problem is solved with success.");
    219 
    220 
    221   roptions->SetRegisteringCategory("bonmin options for non-convex problems");
    222   roptions->AddLowerBoundedIntegerOption("max_consecutive_infeasible",
    223       "Number of consecutive infeasible subproblems before aborting a"
    224       " branch.",
    225       0,0,
    226       "Will continue exploring a branch of the tree until \"max_consecutive_infeasible\""
    227       "consecutive problems are infeasibles by the NLP sub-solver.");
    228 
    229   roptions->AddLowerBoundedIntegerOption("num_resolve_at_root",
    230       "Number $k$ of tries to resolve the root node with different starting points.",
    231       0,0,
    232       "The algorithm will solve the root node with $k$ random starting points"
    233       " and will keep the best local optimum found.");
    234 
    235   roptions->AddLowerBoundedIntegerOption("num_resolve_at_node",
    236       "Number $k$ of tries to resolve a node (other than the root) of the tree with different starting point.",
    237       0,0,
    238       "The algorithm will solve all the nodes with $k$ different random starting points "
    239       "and will keep the best local optimum found.");
    240 
    241 
    242 }
    243 
    244 static void register_OA_options
    245 (Ipopt::SmartPtr<Ipopt::RegisteredOptions> roptions)
    246 {
    247   roptions->SetRegisteringCategory("bonmin options : B-Hyb specific options");
    248 
    249   roptions->AddLowerBoundedIntegerOption("nlp_solve_frequency",
    250       "Specify the frequency (in terms of nodes) at which NLP relaxations are solved in B-Hyb.",
    251       0,10,
    252       "A frequency of 0 amounts to to never solve the NLP relaxation.");
    253 
    254   roptions->AddLowerBoundedNumberOption("oa_dec_time_limit",
    255       "Specify the maximum number of seconds spent overall in OA decomposition iterations.",
    256       0.,0,30.,
    257       "");
    258   roptions->AddLowerBoundedNumberOption("tiny_element","Value for tiny element in OA cut",
    259       -0.,0,1e-08,
    260       "We will remove \"cleanly\" (by relaxing cut) an element lower"
    261       " than this.");
    262 
    263   roptions->AddLowerBoundedNumberOption("very_tiny_element","Value for very tiny element in OA cut",
    264       -0.,0,1e-17,
    265       "Algorithm will take the risk of neglecting an element lower"
    266       " than this.");
    267 
    268   roptions->AddLowerBoundedIntegerOption("Gomory_cuts",
    269       "Frequency k (in terms of nodes) for generating Gomory cuts in branch-and-cut.",
    270       -100,-5,
    271       "If k > 0, cuts are generated every k nodes, if -99 < k < 0 cuts are generated every -k nodes but "
    272       "Cbc may decide to stop generating cuts, if not enough are generated at the root node, "
    273       "if k=-99 generate cuts only at the root node, if k=0 or 100 do not generate cuts.");
    274   roptions->AddLowerBoundedIntegerOption("probing_cuts",
    275       "Frequency (in terms of nodes) for generating probing cuts in branch-and-cut",
    276       -100,-5,
    277       "If k > 0, cuts are generated every k nodes, if -99 < k < 0 cuts are generated every -k nodes but "
    278       "Cbc may decide to stop generating cuts, if not enough are generated at the root node, "
    279       "if k=-99 generate cuts only at the root node, if k=0 or 100 do not generate cuts.");
    280 
    281   roptions->AddLowerBoundedIntegerOption("cover_cuts",
    282       "Frequency (in terms of nodes) for generating cover cuts in branch-and-cut",
    283       -100,-5,
    284       "If k > 0, cuts are generated every k nodes, if -99 < k < 0 cuts are generated every -k nodes but "
    285       "Cbc may decide to stop generating cuts, if not enough are generated at the root node, "
    286       "if k=-99 generate cuts only at the root node, if k=0 or 100 do not generate cuts.");
    287 
    288   roptions->AddLowerBoundedIntegerOption("mir_cuts",
    289       "Frequency (in terms of nodes) for generating MIR cuts in branch-and-cut",
    290       -100,-5,
    291       "If k > 0, cuts are generated every k nodes, if -99 < k < 0 cuts are generated every -k nodes but "
    292       "Cbc may decide to stop generating cuts, if not enough are generated at the root node, "
    293       "if k=-99 generate cuts only at the root node, if k=0 or 100 do not generate cuts.");
    294 
    295 }
    296 
    297 static void register_milp_sub_solver_options
    298 (Ipopt::SmartPtr<Ipopt::RegisteredOptions> roptions)
    299 {
    300   roptions->SetRegisteringCategory("bonmin options : Options for milp subsolver in OA decomposition");
    301   roptions->AddStringOption3("milp_subsolver",
    302       "Choose the subsolver to solve MILPs sub-problems in OA decompositions.",
    303       "Cbc_D",
    304       "Cbc_D","Coin Branch and Cut with its default",
    305       "Cbc_Par", "Coin Branch and Cut with passed parameters",
    306       "Cplex","Ilog Cplex",
    307       " To use Cplex, a valid license is required and you should have compiled OsiCpx in COIN-OR  (see Osi documentation).");
    308 }
    309 
    310 ///Register options
    311 void
    312 IpoptInterface::register_ALL_options
    313 (Ipopt::SmartPtr<Ipopt::RegisteredOptions> roptions)
    314 {
    315   register_general_options(roptions);
    316   register_OA_options(roptions);
    317   register_milp_sub_solver_options(roptions);
    318 }
    319 
    320 void
    321 IpoptInterface::set_ipopt_minlp_default(SmartPtr<OptionsList> Options)
    322 {
    323   Options->SetNumericValue("gamma_phi", 1e-8, true, true);
    324   Options->SetNumericValue("gamma_theta", 1e-4, true, true);
    325   Options->SetNumericValue("required_infeasibility_reduction", 0.1, true, true);
    326   Options->SetStringValue("expect_infeasible_problem","yes", true, true);
    327   Options->SetStringValue("mu_strategy", "adaptive", true, true);
    328   Options->SetStringValue("mu_oracle","probing", true, true);
    329   Options->SetIntegerValue("print_level",1, true, true);
    330 }
    331 
    332 
    333 IpoptInterface::Messages::Messages
    334 ():CoinMessages((int)IPOTPINTERFACE_DUMMY_END)
    335 {
    336   strcpy(source_ ,"IpOp");
    337   addMessage(SOLUTION_FOUND, CoinOneMessage
    338       (1,2,"After %d tries found a solution of %g "
    339        "(previous best %g)."));
    340   addMessage(INFEASIBLE_SOLUTION_FOUND, CoinOneMessage
    341       (2,2,"After %d tries found an solution of %g "
    342        "infeasible problem."));
    343 
    344   addMessage(UNSOLVED_PROBLEM_FOUND, CoinOneMessage
    345       (3,2,"After %d tries found an solution of %g "
    346        "unsolved problem."));
    347   addMessage(WARN_SUCCESS_WS,CoinOneMessage
    348       (3009,2,
    349        "Problem not solved with warm start but "
    350        "solved without"));
    351 
    352   addMessage(WARNING_RESOLVING,CoinOneMessage
    353       (3010,2,
    354        "Trying to resolve NLP with different starting "
    355        "point (%d attempts)."));
    356   addMessage(WARN_SUCCESS_RANDOM, CoinOneMessage
    357       (3011,1,
    358        "Problem initially not solved but solved with "
    359        "a random starting point (success on %d attempt)"));
    360   addMessage(WARN_CONTINUING_ON_FAILURE, CoinOneMessage
    361       (3017,1,
    362        "Warning : continuing branching, while there are "
    363        "unrecovered failures at nodes"));
    364 
    365   addMessage(SUSPECT_PROBLEM, CoinOneMessage
    366       (4,2,"NLP number %d is suspect (see bounds and start file)"));
    367   addMessage(IPOPT_SUMMARY, CoinOneMessage
    368       (6,2,"Ipopt return (for %s): status %2d, iter count %4d, time %g"));
    369   addMessage(BETTER_SOL, CoinOneMessage
    370       (7,2,"Solution of value %g found on %d'th attempt"));
    371 
    372   addMessage(LOG_HEAD, CoinOneMessage
    373       (8,1,"\n          "
    374        "    Num      Status      Obj             It       time"));
    375   addMessage(LOG_FIRST_LINE, CoinOneMessage
    376       (9,1,
    377        "    %-8d %-11s %-14g %-8d %-3g"));
    378   addMessage(LOG_LINE, CoinOneMessage
    379       (10,1,
    380        " %c  r%-7d %-11s %-14g %-8d %-3g"));
    381 
    382   addMessage(WARN_RESOLVE_BEFORE_INITIAL_SOLVE, CoinOneMessage
    383       (3012,1,"resolve called before any call to initialSolve"
    384        " can not use warm starts."));
    385 
    386 }
     28namespace Bonmin{
    38729bool IpoptInterface::hasPrintedOptions=0;
    38830
     
    39234/// Default Constructor
    39335IpoptInterface::IpoptInterface():
    394     OsiSolverInterface(),
    395     tminlp_(NULL),
    396     problem_(NULL),
    397     app_(NULL),
    398     rowsense_(NULL),
    399     rhs_(NULL),
    400     rowrange_(NULL),
    401     reducedCosts_(NULL),
    402     OsiDualObjectiveLimit_(1e200),
    403 //   optimization_status_(HasNotBeenOptimized),
    404     varNames_(NULL),
    405     hasVarNamesFile_(true),
    406     nCallOptimizeTNLP_(0),
    407     totalNlpSolveTime_(0),
    408     totalIterations_(0),
    409     maxRandomRadius_(1e08),
    410     pushValue_(1e-02),
    411     numRetryInitial_(-1),
    412     numRetryResolve_(-1),
    413     numRetryUnsolved_(1),
    414     ipoptIMessages_(),
    415     pretendFailIsInfeasible_(0),
    416     hasContinuedAfterNlpFailure_(false),
    417     numIterationSuspect_(-1),
    418     hasBeenOptimized_(false),
    419     warmStartStrategy_(1),
    420     obj_(NULL),
    421     feasibilityProblem_(NULL),
    422     jRow_(NULL),
    423     jCol_(NULL),
    424     jValues_(NULL),
    425     nnz_jac(0),
    426     constTypes_(NULL),
    427 //    constTypesNum_(NULL),
    428     nLinear_(0),
    429     nNonLinear_(0),
    430     tiny_(1e-8),
    431     veryTiny_(1e-20),
    432     infty_(1e100)
     36    OsiTMINLPInterface(),
     37    warmStartStrategy_(1)
    43338{}
    43439
    43540
    43641/** Constructor with given IpSolver and TMINLP */
    437 IpoptInterface::IpoptInterface (Ipopt::SmartPtr<Ipopt::TMINLP> tminlp):
    438     OsiSolverInterface(),
    439     tminlp_(tminlp),
    440     problem_(NULL),
    441     app_(NULL),
    442     rowsense_(NULL),
    443     rhs_(NULL),
    444     rowrange_(NULL),
    445     reducedCosts_(NULL),
    446     OsiDualObjectiveLimit_(1e200),
    447 //    optimization_status_(HasNotBeenOptimized),
    448     varNames_(NULL),
    449     hasVarNamesFile_(true),
    450     nCallOptimizeTNLP_(0),
    451     totalNlpSolveTime_(0),
    452     totalIterations_(0),
    453     maxRandomRadius_(1e08),
    454     pushValue_(1e-02),
    455     numRetryInitial_(-1),
    456     numRetryResolve_(-1),
    457     numRetryUnsolved_(1),
    458     ipoptIMessages_(),
    459     pretendFailIsInfeasible_(false),
    460     hasContinuedAfterNlpFailure_(false),
    461     numIterationSuspect_(-1),
    462     hasBeenOptimized_(false),
    463     warmStartStrategy_(1),
    464     obj_(NULL),
    465     feasibilityProblem_(NULL),
    466     jRow_(NULL),
    467     jCol_(NULL),
    468     jValues_(NULL),
    469     nnz_jac(0),
    470     constTypes_(NULL),
    471 //    constTypesNum_(NULL),
    472     nLinear_(0),
    473     nNonLinear_(0),
    474     tiny_(1e-08),
    475     veryTiny_(1e-17),
    476     infty_(1e100)
    477 {
    478   assert(IsValid(tminlp));
    479   app_ = new Ipopt::IpoptApplication();
    480 
    481   SmartPtr<RegisteredOptions> roptions = app_->RegOptions();
    482   register_ALL_options(roptions);
    483   app_->Initialize("");
    484   extractInterfaceParams();
    485   set_ipopt_minlp_default(app_->Options());
    486   // set the default options... expect_infeasible, etc...
    487   problem_ = new Ipopt::TMINLP2TNLP(tminlp_, *app_->Options());
    488   feasibilityProblem_ =
    489     new Ipopt::TNLP2FPNLP
    490     (Ipopt::SmartPtr<Ipopt::TNLP>(Ipopt::GetRawPtr(problem_)));
    491 
    492 }
    493 
    494 void
    495 IpoptInterface::readOptionFile(const char * fileName)
    496 {
    497   app_->Initialize(fileName);
    498   extractInterfaceParams();
    499   set_ipopt_minlp_default(app_->Options());
    500 }
    501 void
    502 IpoptInterface::extractInterfaceParams()
    503 {
    504   if (IsValid(app_)) {
    505     app_->Options()->GetNumericValue("max_random_point_radius",maxRandomRadius_,"bonmin.");
    506     app_->Options()->GetIntegerValue("num_retry_unsolved_random_point", numRetryUnsolved_,"bonmin.");
    507     app_->Options()->GetIntegerValue("num_resolve_at_root", numRetryInitial_,"bonmin.");
    508     app_->Options()->GetIntegerValue("num_resolve_at_node", numRetryResolve_,"bonmin.");
    509     app_->Options()->GetIntegerValue("num_iterations_suspect", numIterationSuspect_,"bonmin.");
    510     app_->Options()->GetEnumValue("nlp_failure_behavior",pretendFailIsInfeasible_,"bonmin.");
    511     app_->Options()->GetEnumValue("warm_start",warmStartStrategy_,"bonmin.");
    512     app_->Options()->GetNumericValue
    513     ("warm_start_bound_frac" ,pushValue_,"bonmin.");
    514     app_->Options()->GetNumericValue("tiny_element",tiny_,"bonmin.");
    515     app_->Options()->GetNumericValue("very_tiny_element",veryTiny_,"bonmin.");
    516     double lower_infty, upper_infty;
    517     app_->Options()->GetNumericValue("nlp_lower_bound_inf",lower_infty,"");
    518     app_->Options()->GetNumericValue("nlp_upper_bound_inf",upper_infty,"");
    519     infty_ = min(fabs(lower_infty), fabs(upper_infty));
    520   }
    521 }
     42IpoptInterface::IpoptInterface (Ipopt::SmartPtr<Bonmin::TMINLP> tminlp):
     43    OsiTMINLPInterface(),
     44    warmStartStrategy_(1)
     45{
     46  Ipopt::SmartPtr<Bonmin::TNLPSolver> app = new Bonmin::IpoptSolver();
     47  allocateTMINLP(tminlp, app);
     48}
     49
     50
     51
    52252
    52353/// Clone
     
    53363/// Copy constructor
    53464IpoptInterface::IpoptInterface (const IpoptInterface &source):
    535     OsiSolverInterface(source),
    536     tminlp_(source.tminlp_),
    537     problem_(NULL),
    538     app_(NULL),
    539     rowsense_(NULL),
    540     rhs_(NULL),
    541     rowrange_(NULL),
    542     reducedCosts_(NULL),
    543     OsiDualObjectiveLimit_(source.OsiDualObjectiveLimit_),
    544     optimization_status_(source.optimization_status_),
    545     varNames_(NULL),
    546     hasVarNamesFile_(source.hasVarNamesFile_),
    547     nCallOptimizeTNLP_(0),
    548     totalNlpSolveTime_(0),
    549     totalIterations_(0),
    550     maxRandomRadius_(source.maxRandomRadius_),
    551     pushValue_(source.pushValue_),
    552     numRetryInitial_(source.numRetryInitial_),
    553     numRetryResolve_(source.numRetryResolve_),
    554     numRetryUnsolved_(source.numRetryUnsolved_),
    555     ipoptIMessages_(),
    556     pretendFailIsInfeasible_(source.pretendFailIsInfeasible_),
    557     hasContinuedAfterNlpFailure_(source.hasContinuedAfterNlpFailure_),
    558     numIterationSuspect_(source.numIterationSuspect_),
    559     hasBeenOptimized_(source.hasBeenOptimized_),
    560     warmStartStrategy_(source.warmStartStrategy_),
    561     obj_(NULL),
    562     feasibilityProblem_(NULL),
    563     jRow_(NULL),
    564     jCol_(NULL),
    565     jValues_(NULL),
    566     nnz_jac(source.nnz_jac),
    567     constTypes_(NULL),
    568 //    constTypesNum_(NULL),
    569     nLinear_(0),
    570     nNonLinear_(0),
    571     tiny_(source.tiny_),
    572     veryTiny_(source.veryTiny_),
    573     infty_(source.infty_)
    574 {
    575   // Copy options from old application
    576   if(IsValid(source.tminlp_)) {
    577     app_ = new Ipopt::IpoptApplication();
    578 
    579     SmartPtr<RegisteredOptions> roptions = app_->RegOptions();
    580     register_ALL_options(roptions);
    581     // Copy the options
    582     *app_->Options()=*source.app_->Options();
    583 
    584     //    extractInterfaceParams();
    585 
    586     problem_ = new Ipopt::TMINLP2TNLP(tminlp_, *app_->Options());
    587     problem_->copyUserModification(*source.problem_);
    588     pretendFailIsInfeasible_ = source.pretendFailIsInfeasible_;
    589   }
    590   else {
    591     throw SimpleError("Don't know how to copy an empty IpoptInterface.",
    592         "copy constructor");
    593   }
    594 
    595   if(source.obj_) {
    596     obj_ = new double[source.getNumCols()];
    597     CoinCopyN(source.obj_, source.getNumCols(), obj_);
    598   }
    599   if(IsValid(source.tminlp_))
    600     feasibilityProblem_ = new Ipopt::TNLP2FPNLP
    601         (Ipopt::SmartPtr<Ipopt::TNLP>(Ipopt::GetRawPtr(problem_)));
    602   else
    603     throw CoinError("Don't know how to copy an empty IpoptOAInterface.",
    604         "copy constructor","IpoptOAInterface");
    605 
    606 
    607   if(source.jValues_!=NULL && source.jRow_ != NULL && source.jCol_ != NULL && nnz_jac>0) {
    608     jValues_ = new double [nnz_jac];
    609     jCol_    = new Ipopt::Index [nnz_jac];
    610     jRow_    = new Ipopt::Index [nnz_jac];
    611     CoinCopyN(source.jValues_ , nnz_jac,jValues_ );
    612     CoinCopyN(source.jCol_    , nnz_jac,jCol_    );
    613     CoinCopyN(source.jRow_    , nnz_jac,jRow_    );
    614 
    615     if(source.constTypes_ != NULL) {
    616       constTypes_ = new Ipopt::TMINLP::ConstraintType[getNumRows()];
    617       CoinCopyN(source.constTypes_, getNumRows(), constTypes_);
    618     }
    619 //    if(source.constTypesNum_ != NULL) {
    620 //      constTypesNum_ = new int[getNumRows()];
    621 //      CoinCopyN(source.constTypesNum_, getNumRows(), constTypesNum_);
    622 //    }
    623   }
    624   else if(nnz_jac > 0) {
    625     throw CoinError("Arrays for storing jacobian are inconsistant.",
    626         "copy constructor","IpoptOAInterface");
    627   }
    628   // Process the output options
    629   app_->Initialize("");
    630 }
    631 
    632 
    633 Ipopt::SmartPtr<Ipopt::OptionsList> IpoptInterface::retrieve_options()
    634 {
    635   if(!IsValid(app_)) {
    636     std::cout<<"Can not parse options when no IpApplication has been created"<<std::endl;
    637     return NULL;
    638   }
    639   else
    640     return app_->Options();
    641 }
     65    OsiTMINLPInterface(source),
     66    warmStartStrategy_(source.warmStartStrategy_)
     67{
     68}
     69
     70
     71
    64272
    64373/// Assignment operator
     
    64575{
    64676  if(this!= &rhs) {
    647     OsiSolverInterface::operator=(rhs);
    648     OsiDualObjectiveLimit_ = rhs.OsiDualObjectiveLimit_;
    649     nCallOptimizeTNLP_ = rhs.nCallOptimizeTNLP_;
    650     totalNlpSolveTime_ = rhs.nCallOptimizeTNLP_;
    651     totalIterations_ = rhs.totalIterations_;
    652     maxRandomRadius_ = rhs.maxRandomRadius_;
    653     hasVarNamesFile_ = rhs.hasVarNamesFile_;
    654     pushValue_ = rhs.pushValue_;
    655     optimization_status_ = rhs.optimization_status_;
    656 
    657     if(IsValid(rhs.tminlp_)) {
    658 
    659       tminlp_ = rhs.tminlp_;
    660       app_ = new Ipopt::IpoptApplication();
    661       problem_ = new Ipopt::TMINLP2TNLP(tminlp_, *app_->Options());
    662 
    663       feasibilityProblem_ = new Ipopt::TNLP2FPNLP
    664           (Ipopt::SmartPtr<Ipopt::TNLP>(Ipopt::GetRawPtr(problem_)));
    665       nnz_jac = rhs.nnz_jac;
    666 
    667       if(constTypes_ != NULL) {
    668         delete [] constTypes_;
    669         constTypes_ = NULL;
    670       }
    671       if(rhs.constTypes_ != NULL) {
    672         constTypes_ = new Ipopt::TMINLP::ConstraintType[getNumRows()];
    673         CoinCopyN(rhs.constTypes_, getNumRows(), constTypes_);
    674       }
    675 /*
    676       if(constTypesNum_ != NULL) {
    677         delete [] constTypesNum_;
    678         constTypesNum_ = NULL;
    679       }
    680       if(rhs.constTypesNum_ != NULL) {
    681         constTypesNum_ = new int[getNumRows()];
    682         CoinCopyN(rhs.constTypesNum_, getNumRows(), constTypesNum_);
    683       }
    684 */
    685       if(rhs.jValues_!=NULL && rhs.jRow_ != NULL && rhs.jCol_ != NULL && nnz_jac>0) {
    686         jValues_ = new double [nnz_jac];
    687         jCol_    = new Ipopt::Index [nnz_jac];
    688         jRow_    = new Ipopt::Index [nnz_jac];
    689         CoinCopyN(rhs.jValues_ , nnz_jac,jValues_ );
    690         CoinCopyN(rhs.jCol_    , nnz_jac,jCol_    );
    691         CoinCopyN(rhs.jRow_    , nnz_jac,jRow_    );
    692       }
    693       else if(nnz_jac > 0) {
    694         throw CoinError("Arrays for storing jacobian are inconsistant.",
    695             "copy constructor",
    696             "IpoptOAInterface");
    697       }
    698       tiny_ = rhs.tiny_;
    699       veryTiny_ = rhs.veryTiny_;
    700       infty_ = rhs.infty_;
    701 
    702 
    703     }
    704     else {
    705       tminlp_ =NULL;
    706       app_ = NULL;
    707       problem_ = NULL;
    708       feasibilityProblem_ = NULL;
    709     }
    710 
    711 
    712     if(obj_) {
    713       delete [] obj_;
    714       obj_ = NULL;
    715     }
    716     if(rhs.obj_) {
    717       obj_ = new double[rhs.getNumCols()];
    718       CoinCopyN(rhs.obj_, rhs.getNumCols(), obj_);
    719     }
    720 
    721     delete [] varNames_;
    722     varNames_ = NULL;
    723 
    724     if(rhs.varNames_) {
    725       rhs.varNames_ = new std::string[getNumCols()];
    726       CoinCopyN(rhs.varNames_, getNumCols(), varNames_);
    727     }
    728 
    729     hasVarNamesFile_ = rhs.hasVarNamesFile_;
    730 
    731     nCallOptimizeTNLP_ = rhs.nCallOptimizeTNLP_;
    732     totalNlpSolveTime_ = rhs.totalNlpSolveTime_;
    733     totalIterations_ = rhs.totalIterations_;
    734     maxRandomRadius_ = rhs.maxRandomRadius_;
    735     pushValue_ = rhs.pushValue_;
    736     numRetryInitial_ = rhs.numRetryInitial_;
    737     numRetryResolve_ = rhs.numRetryResolve_;
    738     numRetryUnsolved_ = rhs.numRetryUnsolved_;
    739     pretendFailIsInfeasible_ = rhs.pretendFailIsInfeasible_;
    740     numIterationSuspect_ = rhs.numIterationSuspect_;
    741 
    742     hasBeenOptimized_ = rhs.hasBeenOptimized_;
    743 
    744     freeCachedData();
     77    OsiTMINLPInterface::operator=(rhs);
    74578  }
    74679  return *this;
     
    75083IpoptInterface::~IpoptInterface ()
    75184{
    752   freeCachedData();
    753   delete [] jRow_;
    754   delete [] jCol_;
    755   delete [] jValues_;
    756   delete [] constTypes_;
    757 //  delete [] constTypesNum_;
    758 }
    759 
    760 void
    761 IpoptInterface::freeCachedColRim()
    762 {
    763   if(varNames_!=NULL) {
    764     delete [] varNames_;
    765     varNames_ = NULL;
    766   }
    767   if(reducedCosts_!=NULL) {
    768     delete []  reducedCosts_;
    769     reducedCosts_ = NULL;
    770   }
    771 
    772 }
    773 
    774 void
    775 IpoptInterface::freeCachedRowRim()
    776 {
    777   if(rowsense_!=NULL) {
    778     delete []  rowsense_;
    779     rowsense_ = NULL;
    780   }
    781   if(rhs_!=NULL) {
    782     delete []  rhs_;
    783     rhs_ = NULL;
    784   }
    785   if(rowrange_!=NULL) {
    786     delete []  rowrange_;
    787     rowrange_ = NULL;
    788   }
    789   //   if(dualsol_!=NULL)
    790   //     {
    791   //       delete []  dualsol_; dualsol_ = NULL;
    792   //     }
    793 }
    794 
    795 void
    796 IpoptInterface::freeCachedData()
    797 {
    798   freeCachedColRim();
    799   freeCachedRowRim();
    80085}
    80186
     
    80388// WarmStart Information                                                                           //
    80489///////////////////////////////////////////////////////////////////
     90
     91
     92CoinWarmStart* IpoptInterface::getEmptyWarmStart () const
     93{
     94  return (dynamic_cast<CoinWarmStart *>(new IpoptWarmStart(1)));
     95}
     96
    80597
    80698/// Get warmstarting information
     
    872164}
    873165
    874 static const char * OPT_SYMB="OPT";
    875 static const char * FAILED_SYMB="FAILED";
    876 static const char * INFEAS_SYMB="INFEAS";
    877 
    878 void
    879 IpoptInterface::solveAndCheckErrors(bool warmStarted, bool throwOnFailure,
    880     const char * whereFrom)
    881 {
    882   totalNlpSolveTime_-=CoinCpuTime();
    883   if(warmStarted)
    884     optimization_status_ = app_->ReOptimizeTNLP(GetRawPtr(problem_));
    885   else
    886     optimization_status_ = app_->OptimizeTNLP(GetRawPtr(problem_));
    887   totalNlpSolveTime_+=CoinCpuTime();
    888   nCallOptimizeTNLP_++;
    889   hasBeenOptimized_ = true;
    890 
    891   //Options should have been printed if not done already turn off Ipopt output
    892   if(!hasPrintedOptions) {
    893     hasPrintedOptions = 1;
    894     //app_->Options()->SetIntegerValue("print_level",0, true, true);
    895     app_->Options()->SetStringValue("print_user_options","no", false, true);
    896   }
    897 
    898   const SmartPtr<SolveStatistics>  stats = app_->Statistics();
    899 
    900 #if 1
    901   if(optimization_status_ == -10)//Too few degrees of freedom
    902     {
    903       std::cout<<"Too few degrees of freedom...."<<std::endl;
    904       int numrows = getNumRows();
    905       int numcols = getNumCols();
    906 
    907       const double * colLower = getColLower();
    908       const double * colUpper = getColUpper();
    909 
    910 
    911       const double * rowLower = getRowLower();
    912       const double * rowUpper = getRowUpper();
    913 
    914       int numberFixed = 0;
    915       for(int i = 0 ; i < numcols ; i++)
    916         {
    917           if(colUpper[i] - colLower[i] <= INT_BIAS)
    918             {
    919               numberFixed++;
    920             }
    921         }
    922       int numberEqualities = 0;
    923       for(int i = 0 ; i < numrows ; i++)
    924         {
    925           if(rowUpper[i] - rowLower[i] <= INT_BIAS)
    926             {
    927               numberEqualities++;
    928             }     
    929         }
    930       if(numcols - numberFixed > numberEqualities)
    931         {
    932           throw UnsolvedError(optimization_status_);
    933         }
    934       double * saveColLow = CoinCopyOfArray(getColLower(), getNumCols());
    935       double * saveColUp = CoinCopyOfArray(getColUpper(), getNumCols());
    936 
    937       for(int i = 0; i < numcols && numcols - numberFixed <= numberEqualities ; i++)
    938         {
    939           if(colUpper[i] - colLower[i] <= INT_BIAS)
    940             {
    941               setColLower(i, saveColLow[i]-1e-06);
    942               setColUpper(i, saveColLow[i]+1e-06);
    943               numberFixed--;
    944             }
    945         }
    946       solveAndCheckErrors(warmStarted, throwOnFailure, whereFrom);
    947       //restore
    948       for(int i = 0; i < numcols && numcols - numberFixed < numrows ; i++)
    949         {
    950           problem_->SetVariableLowerBound(i,saveColLow[i]);
    951           problem_->SetVariableUpperBound(i,saveColUp[i]);
    952         }
    953       delete [] saveColLow;
    954       delete [] saveColUp;
    955       return;
    956     }
    957   else
    958 #endif
    959     if(optimization_status_ < -9)//Ipopt failed and the error can not be recovered, throw it
    960   {
    961     throw UnsolvedError(optimization_status_);
    962   }
    963 
    964   if(IsValid(stats)) {
    965     totalIterations_ += stats->IterationCount();
    966   }
    967   else if (throwOnFailure)//something failed throw
    968   {
    969     throw SimpleError("No statistics available from Ipopt",whereFrom);
    970   }
    971   else return;
    972 
    973   messageHandler()->message(IPOPT_SUMMARY, ipoptIMessages_)
    974   <<whereFrom<<optimization_status_<<app_->Statistics()->IterationCount()<<app_->Statistics()->TotalCPUTime()<<CoinMessageEol;
    975 
    976   if((nCallOptimizeTNLP_ % 20) == 1)
    977     messageHandler()->message(LOG_HEAD, ipoptIMessages_)<<CoinMessageEol;
    978 
    979 
    980   if (numIterationSuspect_ >= 0 && (getIterationCount()>numIterationSuspect_ || isAbandoned())) {
    981     messageHandler()->message(SUSPECT_PROBLEM,
    982         ipoptIMessages_)<<nCallOptimizeTNLP_<<CoinMessageEol;
    983     std::string subProbName;
    984     getStrParam(OsiProbName, subProbName);
    985     std::ostringstream os;
    986     os<<"_"<<nCallOptimizeTNLP_;
    987     subProbName+=os.str();
    988     problem_->outputDiffs(subProbName, NULL/*getVarNames()*/);
    989   }
    990 
    991 }
    992 
    993 ////////////////////////////////////////////////////////////////////
    994 // Solve Methods                                                  //
    995 ////////////////////////////////////////////////////////////////////
    996 /// Solve initial continuous relaxation
    997 void IpoptInterface::initialSolve()
    998 {
    999   assert(IsValid(app_));
    1000   assert(IsValid(problem_));
    1001   if(!problem_->checkZeroDimension(optimization_status_)) {
    1002 
    1003     if(!hasPrintedOptions) {
    1004       int printOptions;
    1005       app_->Options()->GetEnumValue("print_user_options",printOptions,"bonmin.");
    1006       if(printOptions)
    1007         app_->Options()->SetStringValue("print_user_options","yes");
    1008     }
    1009     solveAndCheckErrors(0,1,"initialSolve");
    1010 
    1011     //Options should have been printed if not done already turn off Ipopt output
    1012     if(!hasPrintedOptions) {
    1013       hasPrintedOptions = 1;
    1014       app_->Options()->SetStringValue("print_user_options","no");
    1015       app_->Options()->SetIntegerValue("print_level",0);
    1016     }
    1017 
    1018     const char * status=OPT_SYMB;
    1019     ;
    1020     if(isAbandoned()) status=FAILED_SYMB;
    1021     else if(isProvenPrimalInfeasible()) status=INFEAS_SYMB;
    1022     messageHandler()->message(LOG_FIRST_LINE, ipoptIMessages_)<<nCallOptimizeTNLP_
    1023     <<status<<getObjValue()<<app_->Statistics()->IterationCount()<<app_->Statistics()->TotalCPUTime()<<CoinMessageEol;
    1024 
    1025     if(isAbandoned()) {
    1026       resolveForRobustness(numRetryUnsolved_);
    1027     }
    1028     else if(numRetryInitial_)
    1029     {
    1030       resolveForCost(numRetryInitial_);
    1031       /** Only do it once at the root.*/
    1032       numRetryInitial_ = 0;
    1033     }
    1034   }
    1035   else
    1036     hasBeenOptimized_ = true;
    1037 }
    1038 
    1039 /** Resolve the continuous relaxation after problem modification.
    1040  * \note for Ipopt, same as resolve */
    1041 void
    1042 IpoptInterface::resolve()
    1043 {
    1044   if (!IsValid(app_->Statistics())) {
    1045     messageHandler()->message(WARN_RESOLVE_BEFORE_INITIAL_SOLVE, ipoptIMessages_)
    1046     <<CoinMessageEol;
    1047     initialSolve();
    1048     return;
    1049   }
    1050   assert(IsValid(app_));
    1051   assert(IsValid(problem_));
    1052   if (INT_BIAS > 0.) {
    1053     app_->Options()->SetStringValue("warm_start_same_structure", "yes");
    1054   }
    1055   else {
    1056     app_->Options()->SetStringValue("warm_start_same_structure", "no");
    1057   }
    1058 
    1059   setWarmStartOptions();
    1060 
    1061   if(!problem_->checkZeroDimension(optimization_status_)) {
    1062     solveAndCheckErrors(1,1,"resolve");
    1063 
    1064     const char * status=OPT_SYMB;
    1065     ;
    1066     if(isAbandoned()) status=FAILED_SYMB;
    1067     else if(isProvenPrimalInfeasible()) status=INFEAS_SYMB;
    1068     messageHandler()->message(LOG_FIRST_LINE, ipoptIMessages_)<<nCallOptimizeTNLP_
    1069     <<status<<getObjValue()<<app_->Statistics()->IterationCount()<<app_->Statistics()->TotalCPUTime()<<CoinMessageEol;
    1070 
    1071     if(isAbandoned()) {
    1072       resolveForRobustness(numRetryUnsolved_);
    1073     }
    1074     else if(numRetryResolve_)
    1075       resolveForCost(numRetryResolve_);
    1076   }
    1077   else
    1078     hasBeenOptimized_ = true;
    1079 }
    1080 
    1081 void
    1082 IpoptInterface::resolveForCost(int numsolve)
    1083 {
    1084 
    1085   /** Save current optimum. */
    1086   double * point = new double[getNumCols()*3+ getNumRows()];
    1087   double bestBound = getObjValue();
    1088   CoinCopyN(getColSolution(),
    1089       getNumCols(), point);
    1090   CoinCopyN(getRowPrice(),
    1091       2*getNumCols()+ getNumRows(),
    1092       &point[getNumCols()]);
    1093 
    1094   if(isProvenOptimal())
    1095     messageHandler()->message(SOLUTION_FOUND,
    1096         ipoptIMessages_)
    1097     <<1<<getObjValue()<<bestBound
    1098     <<CoinMessageEol;
    1099   else
    1100     messageHandler()->message(INFEASIBLE_SOLUTION_FOUND,
    1101         ipoptIMessages_)
    1102     <<1
    1103     <<CoinMessageEol;
    1104   for(int f = 0; f < numsolve ; f++) {
    1105     messageHandler()->message(WARNING_RESOLVING,
    1106         ipoptIMessages_)
    1107     <<f+1<< CoinMessageEol ;
    1108     randomStartingPoint();
    1109     solveAndCheckErrors(0,0,"resolveForCost");
    1110 
    1111 
    1112     const SmartPtr<SolveStatistics>  stats = app_->Statistics();
    1113     if(IsValid(stats)) {
    1114       totalIterations_ += stats->IterationCount();
    1115     }
    1116     else//something failed (random point generation is not that clever and this can happen (for ex asked to compute sqrt(-1))
    1117       //just exit this procedure
    1118     {
    1119       return;
    1120       //throw SimpleError("No statistics available from Ipopt","resolveForCost");
    1121     }
    1122 
    1123 
    1124 
    1125 
    1126 
    1127     const char * status=OPT_SYMB;
    1128     ;
    1129     char c=' ';
    1130     if(isAbandoned()) {
    1131       status=FAILED_SYMB;
    1132     }
    1133     else if(isProvenPrimalInfeasible()) status=INFEAS_SYMB;
    1134 
    1135 
    1136     //Is solution better than previous
    1137     if(isProvenOptimal() &&
    1138         getObjValue()<bestBound) {
    1139       c='*';
    1140       messageHandler()->message(BETTER_SOL, ipoptIMessages_)<<getObjValue()<<f+1<< CoinMessageEol;
    1141       CoinCopyN(getColSolution(),
    1142           getNumCols(), point);
    1143       CoinCopyN(getRowPrice(),
    1144           2*getNumCols()+ getNumRows(),
    1145           &point[getNumCols()]);
    1146       bestBound = getObjValue();
    1147     }
    1148 
    1149     messageHandler()->message(LOG_LINE, ipoptIMessages_)
    1150     <<c<<f+1<<status<<getObjValue()<<app_->Statistics()->IterationCount()<<app_->Statistics()->TotalCPUTime()<<CoinMessageEol;
    1151 
    1152 
    1153     if(isProvenOptimal())
    1154       messageHandler()->message(SOLUTION_FOUND,
    1155           ipoptIMessages_)
    1156       <<f+2<<getObjValue()<<bestBound
    1157       <<CoinMessageEol;
    1158     else if(!isAbandoned())
    1159       messageHandler()->message(UNSOLVED_PROBLEM_FOUND,
    1160           ipoptIMessages_)
    1161       <<f+2
    1162       <<CoinMessageEol;
    1163     else
    1164       messageHandler()->message(INFEASIBLE_SOLUTION_FOUND,
    1165           ipoptIMessages_)
    1166       <<f+2
    1167       <<CoinMessageEol;
    1168   }
    1169   setColSolution(point);
    1170   setRowPrice(&point[getNumCols()]);
    1171   setWarmStartOptions();
    1172   delete [] point;
    1173 
    1174   optimization_status_ = app_->ReOptimizeTNLP(GetRawPtr(problem_));
    1175   hasBeenOptimized_ = true;
    1176 }
    1177 
    1178 void
    1179 IpoptInterface::resolveForRobustness(int numsolve)
    1180 {
    1181   //std::cerr<<"Resolving the problem for robustness"<<std::endl;
    1182   //First remove warm start point and resolve
    1183   unsetWarmStartOptions();
    1184   messageHandler()->message(WARNING_RESOLVING,
    1185       ipoptIMessages_)
    1186   <<1<< CoinMessageEol ;
    1187   solveAndCheckErrors(0,0,"resolveForRobustness");
    1188 
    1189 
    1190   const char * status=OPT_SYMB;
    1191   ;
    1192   char c='*';
    1193   if(isAbandoned()) {
    1194     status=FAILED_SYMB;
    1195     c=' ';
    1196   }
    1197   else if(isProvenPrimalInfeasible()) status=INFEAS_SYMB;
    1198   messageHandler()->message(LOG_LINE, ipoptIMessages_)
    1199   <<c<<1<<status<<getObjValue()<<app_->Statistics()->IterationCount()<<app_->Statistics()->TotalCPUTime()<<CoinMessageEol;
    1200 
    1201 
    1202   if(!isAbandoned()) {
    1203     messageHandler()->message(WARN_SUCCESS_WS,
    1204         ipoptIMessages_)
    1205     << CoinMessageEol ;
    1206     return; //we won go on
    1207   }
    1208 
    1209   //still unsolved try again with different random starting points
    1210   for(int f = 0; f < numsolve ; f++) {
    1211     messageHandler()->message(WARNING_RESOLVING,
    1212         ipoptIMessages_)
    1213     <<f+2<< CoinMessageEol ;
    1214 
    1215     randomStartingPoint();
    1216     solveAndCheckErrors(0,0,"resolveForRobustness");
    1217 
    1218 
    1219     messageHandler()->message(IPOPT_SUMMARY, ipoptIMessages_)
    1220     <<"resolveForRobustness"<<optimization_status_<<app_->Statistics()->IterationCount()<<app_->Statistics()->TotalCPUTime()<<CoinMessageEol;
    1221 
    1222 
    1223     const char * status=OPT_SYMB;
    1224     ;
    1225     char c='*';
    1226     if(isAbandoned()) {
    1227       status=FAILED_SYMB;
    1228       c=' ';
    1229     }
    1230     else if(isProvenPrimalInfeasible()) status=INFEAS_SYMB;
    1231     messageHandler()->message(LOG_LINE, ipoptIMessages_)
    1232     <<c<<f+2<<status<<getObjValue()<<app_->Statistics()->IterationCount()<<app_->Statistics()->TotalCPUTime()<<CoinMessageEol;
    1233 
    1234 
    1235     if(!isAbandoned()) {
    1236       messageHandler()->message(WARN_SUCCESS_RANDOM,
    1237           ipoptIMessages_)
    1238       <<f+2
    1239       << CoinMessageEol ;
    1240       return; //we have found a solution and continue
    1241     }
    1242   }
    1243   if(pretendFailIsInfeasible_) {
    1244     if(pretendFailIsInfeasible_ == 1) {
    1245       messageHandler()->message(WARN_CONTINUING_ON_FAILURE,
    1246           ipoptIMessages_)
    1247       <<CoinMessageEol;
    1248       hasContinuedAfterNlpFailure_ = 1;
    1249     }
    1250     return;
    1251   }
    1252   else {
    1253     throw UnsolvedError(optimization_status_);
    1254   }
    1255 }
    1256 
    1257 ////////////////////////////////////////////////////////////////////
    1258 // Methods returning info on how the solution process terminated  //
    1259 ////////////////////////////////////////////////////////////////////
    1260 /// Are there a numerical difficulties?
    1261 bool IpoptInterface::isAbandoned() const
    1262 {
    1263   return (
    1264         (optimization_status_==Ipopt::Maximum_Iterations_Exceeded)||
    1265         (optimization_status_==Ipopt::Restoration_Failed)||
    1266         (optimization_status_==Ipopt::Error_In_Step_Computation)||
    1267         (optimization_status_==Ipopt::Not_Enough_Degrees_Of_Freedom)||
    1268         (optimization_status_==Ipopt::Invalid_Problem_Definition)||
    1269         (optimization_status_==Ipopt::Invalid_Option)||
    1270         (optimization_status_==Ipopt::Invalid_Number_Detected)||
    1271         (optimization_status_==Ipopt::Unrecoverable_Exception)||
    1272         (optimization_status_==Ipopt::NonIpopt_Exception_Thrown)||
    1273         (optimization_status_==Ipopt::Insufficient_Memory)||
    1274         (optimization_status_==Ipopt::Internal_Error)
    1275       );
    1276 }
    1277 
    1278 /// Is optimality proven?
    1279 bool IpoptInterface::isProvenOptimal() const
    1280 {
    1281   if (optimization_status_==Ipopt::Search_Direction_Becomes_Too_Small) {
    1282     std::cerr<<"Warning : need to verify that Search_Direction_Becomes_Too_Small is indeed Ok"<<std::endl;
    1283   }
    1284   return (optimization_status_==Ipopt::Solve_Succeeded ||
    1285       optimization_status_==Ipopt::Search_Direction_Becomes_Too_Small ||
    1286       optimization_status_==Ipopt::Solved_To_Acceptable_Level);
    1287 }
    1288 /// Is primal infeasiblity proven?
    1289 bool IpoptInterface::isProvenPrimalInfeasible() const
    1290 {
    1291   return (optimization_status_ == Ipopt::Infeasible_Problem_Detected);
    1292 }
    1293 /// Is dual infeasiblity proven?
    1294 bool IpoptInterface::isProvenDualInfeasible() const
    1295 {
    1296   throw SimpleError("Don't have this optimization status yet.",
    1297       "isProvenDualInfeasible");
    1298 }
    1299 /// Is the given primal objective limit reached?
    1300 bool IpoptInterface::isPrimalObjectiveLimitReached() const
    1301 {
    1302   std::cerr<<"Warning : isPrimalObjectiveLimitReached not implemented yet"<<std::endl;
    1303   return 0;
    1304 }
    1305 /// Is the given dual objective limit reached?
    1306 bool IpoptInterface::isDualObjectiveLimitReached() const
    1307 {
    1308   //  std::cerr<<"Warning : isDualObjectiveLimitReached not implemented yet"<<std::endl;
    1309   return (optimization_status_==Ipopt::Diverging_Iterates);
    1310 
    1311 }
    1312 /// Iteration limit reached?
    1313 bool IpoptInterface::isIterationLimitReached() const
    1314 {
    1315   return (optimization_status_==Ipopt::Maximum_Iterations_Exceeded);
    1316   //  return (problem_->optimization_status()==Ipopt::Maximum_Iterations_Exceeded);
    1317 }
    1318 ////////////////////////////////////////////////////////////////////
    1319 // Problem information methods                                    //
    1320 ////////////////////////////////////////////////////////////////////
    1321 /// Get number of columns
    1322 int IpoptInterface::getNumCols() const
    1323 {
    1324 
    1325   return problem_->num_variables();
    1326 }
    1327 
    1328 
    1329 /// Get number of rows
    1330 int
    1331 IpoptInterface::getNumRows() const
    1332 {
    1333   return problem_->num_constraints();
    1334 }
    1335 
    1336 const double *
    1337 IpoptInterface::getColLower() const
    1338 {
    1339   return problem_->x_l();
    1340 }
    1341 
    1342 const double *
    1343 IpoptInterface::getColUpper() const
    1344 {
    1345   return problem_->x_u();
    1346 }
    1347 
    1348 void
    1349 IpoptInterface::readVarNames() const
    1350 {
    1351   delete []varNames_;
    1352   varNames_ = NULL;
    1353   std::string probName;
    1354   getStrParam(OsiProbName, probName);
    1355   IpCbcColReader colRead(probName);
    1356   if(colRead.readFile()) {
    1357     varNames_ = new std::string[problem_->num_variables()];
    1358     colRead.copyNames(varNames_,problem_->num_variables());
    1359     hasVarNamesFile_ = true;
    1360   }
    1361   else
    1362     hasVarNamesFile_ = false;
    1363 }
    1364 
    1365 ///get name of a variable
    1366 const std::string *
    1367 IpoptInterface::getVarNames() const
    1368 {
    1369   if(varNames_ == NULL && hasVarNamesFile_ ) {
    1370     readVarNames();
    1371   }
    1372   return varNames_;
    1373 }
    1374 
    1375 void IpoptInterface::extractSenseRhsAndRange() const
    1376 {
    1377   assert(rowsense_==NULL&&rhs_==NULL&&rowrange_==NULL);
    1378   int numrows = problem_->num_constraints();
    1379   const double * rowLower = getRowLower();
    1380   const double * rowUpper = getRowUpper();
    1381   rowsense_ = new char [numrows];
    1382   rhs_ = new double [numrows];
    1383   rowrange_ = new double [numrows];
    1384   for(int i = 0 ; i < numrows ; i++) {
    1385     rowrange_[i]=0.;
    1386     convertBoundToSense(rowLower[i], rowUpper[i], rowsense_[i], rhs_[i], rowrange_[i]);
    1387   }
    1388 }
    1389 
    1390 /** Get pointer to array[getNumRows()] of row constraint senses.
    1391     <ul>
    1392     <li>'L': <= constraint
    1393     <li>'E': =  constraint
    1394     <li>'G': >= constraint
    1395     <li>'R': ranged constraint
    1396     <li>'N': free constraint
    1397     </ul>
    1398 */
    1399 const char *
    1400 IpoptInterface::getRowSense() const
    1401 {
    1402   if(rowsense_==NULL) {
    1403     extractSenseRhsAndRange();
    1404   }
    1405   return rowsense_;
    1406 }
    1407 
    1408 /** Get pointer to array[getNumRows()] of rows right-hand sides
    1409     <ul>
    1410     <li> if rowsense()[i] == 'L' then rhs()[i] == rowupper()[i]
    1411     <li> if rowsense()[i] == 'G' then rhs()[i] == rowlower()[i]
    1412     <li> if rowsense()[i] == 'R' then rhs()[i] == rowupper()[i]
    1413     <li> if rowsense()[i] == 'N' then rhs()[i] == 0.0
    1414     </ul>
    1415 */
    1416 const double *
    1417 IpoptInterface::getRightHandSide() const
    1418 {
    1419   if(rhs_==NULL) {
    1420     extractSenseRhsAndRange();
    1421   }
    1422   return rhs_;
    1423 }
    1424 
    1425 /** Get pointer to array[getNumRows()] of row ranges.
    1426     <ul>
    1427     <li> if rowsense()[i] == 'R' then
    1428     rowrange()[i] == rowupper()[i] - rowlower()[i]
    1429     <li> if rowsense()[i] != 'R' then
    1430     rowrange()[i] is 0.0
    1431     </ul>
    1432 */
    1433 const double *
    1434 IpoptInterface::getRowRange() const
    1435 {
    1436   if(rowrange_==NULL) {
    1437     extractSenseRhsAndRange();
    1438   }
    1439   return rowrange_;
    1440 }
    1441 
    1442 const double *
    1443 IpoptInterface::getRowLower() const
    1444 {
    1445   return problem_->g_l();
    1446 }
    1447 
    1448 const double *
    1449 IpoptInterface::getRowUpper() const
    1450 {
    1451   return problem_->g_u();
    1452 }
    1453 
    1454 /// Return true if column is continuous
    1455 bool
    1456 IpoptInterface::isContinuous(int colNumber) const
    1457 {
    1458   return (problem_->var_types()[colNumber]==Ipopt::TMINLP::CONTINUOUS);
    1459 }
    1460 
    1461 /// Return true if column is binary
    1462 bool
    1463 IpoptInterface::isBinary(int colNumber) const
    1464 {
    1465   return (problem_->var_types()[colNumber]==Ipopt::TMINLP::BINARY);
    1466 }
    1467 
    1468 /** Return true if column is integer.
    1469     Note: This function returns true if the the column
    1470     is binary or a general integer.
    1471 */
    1472 bool
    1473 IpoptInterface::isInteger(int colNumber) const
    1474 {
    1475   return ((problem_->var_types()[colNumber]==Ipopt::TMINLP::BINARY)||
    1476       (problem_->var_types()[colNumber]==Ipopt::TMINLP::INTEGER));
    1477 }
    1478 
    1479 /// Return true if column is general integer
    1480 bool
    1481 IpoptInterface::isIntegerNonBinary(int colNumber) const
    1482 {
    1483   return (problem_->var_types()[colNumber]==Ipopt::TMINLP::INTEGER);
    1484 }
    1485 /// Return true if column is binary and not fixed at either bound
    1486 bool
    1487 IpoptInterface::isFreeBinary(int colNumber) const
    1488 {
    1489   return ((problem_->var_types()[colNumber]==Ipopt::TMINLP::BINARY)
    1490       &&((getColUpper()[colNumber]-getColLower()[colNumber]) > 1 - 1e-09));
    1491 }
    1492 
    1493 /// Get solver's value for infinity
    1494 double
    1495 IpoptInterface::getInfinity() const
    1496 {
    1497   return DBL_MAX;
    1498 }
    1499 
    1500 /// Get pointer to array[getNumCols()] of primal solution vector
    1501 const double *
    1502 IpoptInterface::getColSolution() const
    1503 {
    1504   if(hasBeenOptimized_)
    1505     return problem_->x_sol();
    1506   else
    1507     return problem_->x_init();
    1508 }
    1509 
    1510 /// Get pointer to array[getNumRows()] of dual prices
    1511 const double *
    1512 IpoptInterface::getRowPrice() const
    1513 {
    1514   if(hasBeenOptimized_)
    1515     return problem_->duals_sol();
    1516   else
    1517     return problem_->duals_init();
    1518 }
    1519 
    1520 /// Get a pointer to array[getNumCols()] of reduced costs
    1521 const double *
    1522 IpoptInterface::getReducedCost() const
    1523 {
    1524   std::cerr<<"WARNING : trying to access reduced cost in Ipopt always retrun 0"<<std::endl;
    1525   if(reducedCosts_==NULL) {
    1526     reducedCosts_ = new double [getNumCols()];
    1527     CoinFillN(reducedCosts_,getNumCols(),0.);
    1528   }
    1529   return reducedCosts_;
    1530 }
    1531 
    1532 /** Get pointer to array[getNumRows()] of row activity levels (constraint
    1533     matrix times the solution vector */
    1534 const double *
    1535 IpoptInterface::getRowActivity() const
    1536 {
    1537   return problem_->g_sol();
    1538 }
    1539 
    1540 /** Get how many iterations it took to solve the problem (whatever
    1541     "iteration" mean to the solver.
    1542 */
    1543 int
    1544 IpoptInterface::getIterationCount() const
    1545 {
    1546   if(IsValid(app_->Statistics()))
    1547     return app_->Statistics()->IterationCount();
    1548   else
    1549     return 0;
    1550 }
    1551 
    1552 
    1553 /** Set a single column lower bound.
    1554     Use -getInfinity() for -infinity. */
    1555 void
    1556 IpoptInterface::setColLower( int elementIndex, double elementValue )
    1557 {
    1558   //  if(fabs(problem_->x_l()[elementIndex]-elementValue)>1e-06)
    1559   problem_->SetVariableLowerBound(elementIndex,elementValue);
    1560   hasBeenOptimized_ = false;
    1561 }
    1562 
    1563 /** Set a single column upper bound.
    1564     Use getInfinity() for infinity. */
    1565 void
    1566 IpoptInterface::setColUpper( int elementIndex, double elementValue )
    1567 {
    1568   //  if(fabs(problem_->x_u()[elementIndex]-elementValue)>1e-06)
    1569   problem_->SetVariableUpperBound(elementIndex,elementValue);
    1570   hasBeenOptimized_ = false;
    1571 }
    1572 
    1573 /** Set a single row lower bound.
    1574     Use -getInfinity() for -infinity. */
    1575 void
    1576 IpoptInterface::setRowLower( int elementIndex, double elementValue )
    1577 {
    1578   throw SimpleError("Not implemented yet but should be if necessary.",
    1579       "setRowLower");
    1580   hasBeenOptimized_ = false;
    1581 }
    1582 
    1583 /** Set a single row upper bound.
    1584     Use getInfinity() for infinity. */
    1585 void
    1586 IpoptInterface::setRowUpper( int elementIndex, double elementValue )
    1587 {
    1588   throw SimpleError("Not implemented yet but should be if necessary.",
    1589       "setRowUpper");
    1590   hasBeenOptimized_ = false;
    1591 }
    1592 
    1593 /** Set the type of a single row */
    1594 void
    1595 IpoptInterface::setRowType(int index, char sense, double rightHandSide,
    1596     double range)
    1597 {
    1598   throw SimpleError("Not implemented yet but should be if necessary.",
    1599       "setRowType");
    1600   hasBeenOptimized_ = false;
    1601 }
    1602 
    1603 
    1604 /// Set the objective function sense.
    1605 /// (1 for min (default), -1 for max)
    1606 void
    1607 IpoptInterface::setObjSense(double s)
    1608 {
    1609   throw SimpleError("Can not change objective sense of an Ipopt problem.",
    1610       "setObjSense");
    1611   hasBeenOptimized_ = false;
    1612 }
    1613 
    1614 /** Set the primal solution variable values
    1615 
    1616 colsol[getNumCols()] is an array of values for the primal variables.
    1617 These values are copied to memory owned by the solver interface object
    1618 or the solver.  They will be returned as the result of getColSolution()
    1619 until changed by another call to setColSolution() or by a call to any
    1620 solver routine.  Whether the solver makes use of the solution in any
    1621 way is solver-dependent.
    1622 */
    1623 void
    1624 IpoptInterface::setColSolution(const double *colsol)
    1625 {
    1626   problem_->setxInit(getNumCols(), colsol);
    1627   hasBeenOptimized_ = false;
    1628   //  problem_->SetStartingPoint(getNumCols(), colsol);
    1629 }
    1630 
    1631 /** Set dual solution variable values
    1632 
    1633 rowprice[getNumRows()] is an array of values for the dual
    1634 variables. These values are copied to memory owned by the solver
    1635 interface object or the solver.  They will be returned as the result of
    1636 getRowPrice() until changed by another call to setRowPrice() or by a
    1637 call to any solver routine.  Whether the solver makes use of the
    1638 solution in any way is solver-dependent.
    1639 */
    1640 
    1641 void
    1642 IpoptInterface::setRowPrice(const double * rowprice)
    1643 {
    1644   problem_->setDualsInit(getNumCols()*2 + getNumRows(), rowprice);
    1645   hasBeenOptimized_ = false;
    1646 }
    1647 
    1648 
    1649 /** Set the index-th variable to be a continuous variable */
    1650 void
    1651 IpoptInterface::setContinuous(int index)
    1652 {
    1653   problem_->SetVariableType(index, Ipopt::TMINLP::CONTINUOUS);
    1654   hasBeenOptimized_ = false;
    1655 }
    1656 /** Set the index-th variable to be an integer variable */
    1657 void
    1658 IpoptInterface::setInteger(int index)
    1659 {
    1660   problem_->SetVariableType(index, Ipopt::TMINLP::INTEGER);
    1661   hasBeenOptimized_ = false;
    1662 }
    1663 
    1664 /// Get objective function value (can't use default)
    1665 double
    1666 IpoptInterface::getObjValue() const
    1667 {
    1668   return problem_->obj_value();
    1669 }
    1670 
    1671 
    1672 CoinWarmStart* IpoptInterface::getEmptyWarmStart () const
    1673 {
    1674   return (dynamic_cast<CoinWarmStart *>(new IpoptWarmStart(1)));
    1675 }
    1676 
    1677 //#############################################################################
    1678 // Parameter related methods
    1679 //#############################################################################
    1680 
    1681 bool
    1682 IpoptInterface::setIntParam(OsiIntParam key, int value)
    1683 {
    1684   //  debugMessage("OsiCpxSolverInterface::setIntParam(%d, %d)\n", key, value);
    1685 
    1686   bool retval = false;
    1687   switch (key) {
    1688   case OsiMaxNumIteration:
    1689     retval = false;
    1690     break;
    1691   case OsiMaxNumIterationHotStart:
    1692     if( value >= 0 ) {
    1693       retval = false;
    1694     }
    1695     else
    1696       retval = false;
    1697     break;
    1698   case OsiLastIntParam:
    1699     retval = false;
    1700     break;
    1701   }
    1702   return retval;
    1703 }
    1704 
    1705 //-----------------------------------------------------------------------------
    1706 
    1707 bool
    1708 IpoptInterface::setDblParam(OsiDblParam key, double value)
    1709 {
    1710   //  debugMessage("IpoptInterface::setDblParam(%d, %g)\n", key, value);
    1711 
    1712   bool retval = false;
    1713   switch (key) {
    1714   case OsiDualObjectiveLimit:
    1715     OsiDualObjectiveLimit_ = value;
    1716     retval = true;
    1717     break;
    1718   case OsiPrimalObjectiveLimit:
    1719     std::cerr<<"Can not set primal objective limit parameter"<<std::endl;
    1720     retval = false;
    1721     break;
    1722   case OsiDualTolerance:
    1723     std::cerr<<"Can not set dual tolerance parameter"<<std::endl;
    1724     retval = false;
    1725     break;
    1726   case OsiPrimalTolerance:
    1727     std::cerr<<"Can not set primal tolerance parameter"<<std::endl;
    1728     retval = false;
    1729   case OsiObjOffset:
    1730     retval = OsiSolverInterface::setDblParam(key,value);
    1731     break;
    1732   case OsiLastDblParam:
    1733     retval = false;
    1734     break;
    1735   }
    1736   return retval;
    1737 }
    1738 
    1739 
    1740 //-----------------------------------------------------------------------------
    1741 
    1742 bool
    1743 IpoptInterface::setStrParam(OsiStrParam key, const std::string & value)
    1744 {
    1745   //  debugMessage("IpoptInterface::setStrParam(%d, %s)\n", key, value.c_str());
    1746 
    1747   bool retval=false;
    1748   switch (key) {
    1749   case OsiProbName:
    1750     OsiSolverInterface::setStrParam(key,value);
    1751     return retval = true;
    1752   case OsiSolverName:
    1753     return false;
    1754   case OsiLastStrParam:
    1755     return false;
    1756   }
    1757   return false;
    1758 }
    1759 
    1760 //-----------------------------------------------------------------------------
    1761 
    1762 bool
    1763 IpoptInterface::getIntParam(OsiIntParam key, int& value) const
    1764 {
    1765   //  debugMessage("IpoptInterface::getIntParam(%d)\n", key);
    1766 
    1767   bool retval = false;
    1768   switch (key) {
    1769   case OsiMaxNumIteration:
    1770     retval = false;
    1771     break;
    1772   case OsiMaxNumIterationHotStart:
    1773     retval = false;
    1774     break;
    1775   case OsiLastIntParam:
    1776     retval = false;
    1777     break;
    1778   }
    1779   return retval;
    1780 }
    1781 
    1782 //-----------------------------------------------------------------------------
    1783 
    1784 bool
    1785 IpoptInterface::getDblParam(OsiDblParam key, double& value) const
    1786 {
    1787   //  debugMessage("IpoptInterface::getDblParam(%d)\n", key);
    1788 
    1789   bool retval = false;
    1790   switch (key) {
    1791   case OsiDualObjectiveLimit:
    1792     value = OsiDualObjectiveLimit_;
    1793     retval = true;
    1794     break;
    1795   case OsiPrimalObjectiveLimit:
    1796     value = getInfinity();
    1797     retval = true;
    1798     break;
    1799   case OsiDualTolerance:
    1800     retval = false;
    1801     break;
    1802   case OsiPrimalTolerance:
    1803     retval = false;
    1804     break;
    1805   case OsiObjOffset:
    1806     retval = OsiSolverInterface::getDblParam(key, value);
    1807     break;
    1808   case OsiLastDblParam:
    1809     retval = false;
    1810     break;
    1811   }
    1812   return retval;
    1813 }
    1814 
    1815 
    1816 //-----------------------------------------------------------------------------
    1817 
    1818 bool
    1819 IpoptInterface::getStrParam(OsiStrParam key, std::string & value) const
    1820 {
    1821   //  debugMessage("IpoptInterface::getStrParam(%d)\n", key);
    1822 
    1823   switch (key) {
    1824   case OsiProbName:
    1825     OsiSolverInterface::getStrParam(key, value);
    1826     break;
    1827   case OsiSolverName:
    1828     value = "Ipopt";
    1829     break;
    1830   case OsiLastStrParam:
    1831     return false;
    1832   }
    1833 
    1834   return true;
    1835 }
    1836166
    1837167void
     
    1848178}
    1849179
    1850 void
    1851 IpoptInterface::randomStartingPoint()
    1852 {
    1853   int numcols = getNumCols();
    1854   const double * colLower = getColLower();
    1855   const double * colUpper = getColUpper();
    1856   double * sol = new double[numcols];
    1857   for(int i = 0 ; i < numcols ; i++) {
    1858     double lower = min(-maxRandomRadius_,colUpper[i] - maxRandomRadius_);
    1859     lower = max(colLower[i], lower);
    1860     double upper = max(maxRandomRadius_,colLower[i] + maxRandomRadius_);
    1861     upper = min(colUpper[i],upper);
    1862     lower = min(upper,lower);
    1863     upper = max(upper, lower);
    1864     double interval = upper - lower;
    1865     sol[i] = CoinDrand48()*(interval) + lower;
    1866 //    printf("%f in [%f,%f]\n",sol[i],lower,upper);
    1867     //  std::cout<<interval<<"\t";
    1868   }
    1869   //std::cout<<std::endl;
    1870   unsetWarmStartOptions();
    1871   setColSolution(sol);
    1872   delete [] sol;
    1873 }
     180
    1874181
    1875182/*******************************************************************************/
     
    1878185
    1879186std::string
    1880 IpoptInterface::UnsolvedError::errorNames[17] ={"Solve succeeded",
     187IpoptInterface::UnsolvedIpoptError::errorNames[17] ={"Solve succeeded",
    1881188    "Solved to acceptable level",
    1882     "Infeasible Problem Detected",
    1883     "Search_Direction_Becomes_Too_Small",
     189    "Infeasible problem detected",
     190    "Search direction becomes too small",
    1884191    "Diverging iterates",
    1885     "User Requested Stop",
    1886     "Maximum Iterations Exceeded",
    1887     "Restoration Failed",
     192    "User requested stop",
     193    "Maximum iterations exceeded",
     194    "Restoration failed",
    1888195    "Error in step computation",
    1889196    "Not enough degrees of freedom",
     
    1896203    "Internal error"};
    1897204
    1898 IpoptInterface::UnsolvedError::UnsolvedError(int errorNum)
    1899 {
    1900   errorNum_ = errorNum;
    1901 }
    1902 
    1903205const std::string &
    1904 IpoptInterface::UnsolvedError::errorName() const
    1905 {
    1906   if(errorNum_ >=0)
    1907     return errorNames[errorNum_];
    1908   if(errorNum_ == -1) return errorNames[6];
    1909   else if(errorNum_ == -2) return errorNames[7];
    1910   else if(errorNum_ == -3) return errorNames[8];
    1911   else if(errorNum_ == -10) return errorNames[9];
    1912   else if(errorNum_ == -11) return errorNames[10];
    1913   else if(errorNum_ == -12) return errorNames[11];
    1914   else if(errorNum_ == -13) return errorNames[12];
    1915   else if(errorNum_ == -100) return errorNames[13];
    1916   else if(errorNum_ == -101) return errorNames[14];
    1917   else if(errorNum_ == -102) return errorNames[15];
    1918   else if(errorNum_ == -199) return errorNames[16];
     206IpoptInterface::UnsolvedIpoptError::errorName() const
     207{
     208  if(errorNum() >=0)
     209    return errorNames[errorNum()];
     210  if(errorNum() == -1) return errorNames[6];
     211  else if(errorNum() == -2) return errorNames[7];
     212  else if(errorNum() == -3) return errorNames[8];
     213  else if(errorNum() == -10) return errorNames[9];
     214  else if(errorNum() == -11) return errorNames[10];
     215  else if(errorNum() == -12) return errorNames[11];
     216  else if(errorNum() == -13) return errorNames[12];
     217  else if(errorNum() == -100) return errorNames[13];
     218  else if(errorNum() == -101) return errorNames[14];
     219  else if(errorNum() == -102) return errorNames[15];
     220  else if(errorNum() == -199) return errorNames[16];
    1919221  throw IpoptInterface::SimpleError("UnsolvedError::errorName()","Unrecognized optimization status in ipopt.");
    1920222}
    1921223
     224std::string IpoptInterface::UnsolvedIpoptError::solverName_ = "Ipopt";
     225
     226const std::string &
     227IpoptInterface::UnsolvedIpoptError::solverName() const
     228{
     229   return solverName_;
     230}
     231
     232
     233
     234/// Return status of last optimization
     235Ipopt::ApplicationReturnStatus
     236IpoptInterface::getOptStatus() const
     237{
     238  IpoptSolver* ipoptApp = dynamic_cast<IpoptSolver *>(GetRawPtr(app_));
     239  return ipoptApp->getOptStatus();
     240}
     241
    1922242void
    1923 IpoptInterface::UnsolvedError::printError(std::ostream &os)
    1924 {
    1925   os<<"Ipopt exited with error code "<<errorNum_<<" "<<errorName()<<std::endl;
    1926 }
    1927 
    1928 
    1929 /** This methods initialiaze arrays for storing the jacobian */
    1930 int IpoptInterface::initializeJacobianArrays()
    1931 {
    1932   Ipopt::Index n, m, nnz_h_lag;
    1933   Ipopt::TNLP::IndexStyleEnum index_style;
    1934   tminlp_->get_nlp_info( n, m, nnz_jac, nnz_h_lag, index_style);
    1935 
    1936   if(jRow_ != NULL) delete jRow_;
    1937   if(jCol_ != NULL) delete jCol_;
    1938   if(jValues_ != NULL) delete jValues_;
    1939 
    1940   jRow_ = new Ipopt::Index[nnz_jac];
    1941   jCol_ = new Ipopt::Index[nnz_jac];
    1942   jValues_ = new Ipopt::Number[nnz_jac];
    1943   tminlp_->eval_jac_g(n, NULL, 0, m, nnz_jac, jRow_, jCol_, NULL);
    1944 
    1945 
    1946   if(constTypes_ != NULL) delete [] constTypes_;
    1947 //  if(constTypesNum_ != NULL) delete [] constTypesNum_;
    1948 
    1949   constTypes_ = new Ipopt::TMINLP::ConstraintType[getNumRows()];
    1950   tminlp_->get_constraints_types(getNumRows(), constTypes_);
    1951 //  constTypesNum_ = new int[getNumRows()];
    1952   for(int i = 0; i < getNumRows() ; i++) {
    1953     if(constTypes_[i]==Ipopt::TMINLP::LINEAR) {
    1954       //constTypesNum_[i] =
    1955       nLinear_++;
    1956     }
    1957     else if(constTypes_[i]==Ipopt::TMINLP::NON_LINEAR) {
    1958       //constTypesNum_[i] =
    1959       nNonLinear_++;
    1960     }
    1961   }
    1962   return nnz_jac;
    1963 }
    1964 
    1965 
    1966 /** get NLP constraint violation of current point */
    1967 double
    1968 IpoptInterface::getConstraintViolation()
    1969 {
    1970   int numcols = getNumCols();
    1971   int numrows = getNumRows();
    1972   double * g = new double[numrows];
    1973   tminlp_->eval_g(numcols,getColSolution(),1,numrows,g);
    1974   const double * rowLower = getRowLower();
    1975   const double * rowUpper = getRowUpper();
    1976 
    1977 
    1978   double norm = 0;
    1979   for(int i = 0; i< numrows ; i++) {
    1980     if(constTypes_[i] == Ipopt::TMINLP::NON_LINEAR) {
    1981       double rowViolation = max(0.,rowLower[i] - g[i]);
    1982       if(rowViolation  > 0.) rowViolation  /= fabs(rowLower[i]);
    1983       double rowViolation2 = max(0.,g[i] - rowUpper[i]);
    1984       if(rowViolation2 > 0.) rowViolation2 /= fabs(rowUpper[i]);
    1985       norm = max(rowViolation, norm);
    1986     }
    1987   }
    1988   return norm;
    1989 }
    1990 
    1991 
    1992 //A procedure to try to remove small coefficients in OA cuts (or make it non small
    1993 static inline
    1994 bool cleanNnz(double &value, double colLower, double colUpper,
    1995     double rowLower, double rowUpper, double colsol,
    1996     double & lb, double &ub, double tiny, double veryTiny)
    1997 {
    1998   if(fabs(value)>= tiny) return 1;
    1999 
    2000   if(fabs(value)<veryTiny) return 0;//Take the risk?
    2001 
    2002   //try and remove
    2003   double infty = 1e20;
    2004   bool colUpBounded = colUpper < 10000;
    2005   bool colLoBounded = colLower > -10000;
    2006   bool rowNotLoBounded =  rowLower <= - infty;
    2007   bool rowNotUpBounded = rowUpper >= infty;
    2008   bool pos =  value > 0;
    2009 
    2010   if(!rowNotLoBounded && ! rowNotUpBounded)//would have to either choose side or duplicate cut
    2011   {
    2012     std::cerr<<"OA on non-convex constraint is very experimental, don't know how to remove"
    2013     <<std::endl;
    2014   }
    2015 
    2016   if(colLoBounded && pos && rowNotUpBounded) {
    2017     lb += value * (colsol - colLower);
    2018     return 0;
    2019   }
    2020   else
    2021     if(colLoBounded && !pos && rowNotLoBounded) {
    2022       ub += value * (colsol - colLower);
    2023       return 0;
    2024     }
    2025     else
    2026       if(colUpBounded && !pos && rowNotUpBounded) {
    2027         lb += value * (colsol - colUpper);
    2028         return 0;
    2029       }
    2030       else
    2031         if(colUpBounded && pos && rowNotLoBounded) {
    2032           ub += value * (colsol - colUpper);
    2033           return 0;
    2034         }
    2035   //can not remove coefficient increase it to smallest non zero
    2036   if(pos) value = tiny;
    2037   else
    2038     value = - tiny;
    2039   return 1;
    2040 }
    2041 
    2042 /** Get the outer approximation constraints at the current optimum of the
    2043   current ipopt problem */
    2044 void
    2045 IpoptInterface::getOuterApproximation(OsiCuts &cs, bool getObj)
    2046 {
    2047   int n,m, nnz_jac_g, nnz_h_lag;
    2048   Ipopt::TNLP::IndexStyleEnum index_style;
    2049   tminlp_->get_nlp_info( n, m, nnz_jac_g, nnz_h_lag, index_style);
    2050   if(jRow_ == NULL || jCol_ == NULL || jValues_ == NULL)
    2051     initializeJacobianArrays();
    2052   assert(jRow_ != NULL);
    2053   assert(jCol_ != NULL);
    2054   double * g = new double[m];
    2055   tminlp_->eval_jac_g(n, getColSolution(), 1, m, nnz_jac_g, NULL, NULL, jValues_);
    2056   tminlp_->eval_g(n,getColSolution(),1,m,g);
    2057   //As jacobian is stored by cols fill OsiCuts with cuts
    2058   CoinPackedVector * cuts = new CoinPackedVector[nNonLinear_ + 1];
    2059   double * lb = new double[nNonLinear_ + 1];
    2060   double * ub = new double[nNonLinear_ + 1];
    2061   int * binding = new int[nNonLinear_ + 1];//store binding constraints at current opt (which are added to OA) -1 if constraint is not binding, otherwise index in subset of binding constraints
    2062   int numBindings = 0;
    2063    
    2064   const double * rowLower = getRowLower();
    2065   const double * rowUpper = getRowUpper();
    2066   const double * colLower = getColLower();
    2067   const double * colUpper = getColUpper();
    2068   const double * duals = getRowPrice();
    2069   double infty = getInfinity();
    2070   double nlp_infty = infty_;
    2071  
    2072   for(int i = 0; i< m ; i++) {
    2073     if(constTypes_[i] == Ipopt::TMINLP::NON_LINEAR) {
    2074       if(rowLower[i] > - nlp_infty && rowUpper[i] < nlp_infty && fabs(duals[i]) == 0.)
    2075       {
    2076         binding[i] = -1;
    2077         std::cerr<<"non binding constraint"<<std::endl;
    2078         continue;
    2079       }
    2080       binding[i] = numBindings;
    2081       if(rowLower[i] > - nlp_infty)
    2082         lb[numBindings] = rowLower[i] - g[i];
    2083       else
    2084         lb[numBindings] = - infty;
    2085       if(rowUpper[i] < nlp_infty)
    2086         ub[numBindings] = rowUpper[i] - g[i];
    2087       else
    2088         ub[numBindings] = infty;
    2089       if(rowLower[i] > -infty && rowUpper[i] < infty)
    2090       {
    2091         if(duals[i] >= 0)// <= inequality
    2092           lb[numBindings] = - infty;
    2093         if(duals[i] <= 0)// >= inequality
    2094           ub[numBindings] = infty;
    2095       }
    2096      
    2097       numBindings++;
    2098     }
    2099   }
    2100 
    2101   for(int i = 0 ; i < nnz_jac_g ; i++) {
    2102     if(constTypes_[jRow_[i] - 1] == Ipopt::TMINLP::NON_LINEAR) {
    2103       //"clean" coefficient
    2104       if(cleanNnz(jValues_[i],colLower[jCol_[i] - 1], colUpper[jCol_[i]-1],
    2105           rowLower[jRow_[i] - 1], rowUpper[jRow_[i] - 1],
    2106           getColSolution()[jCol_[i] - 1],
    2107           lb[binding[jRow_[i] - 1]],
    2108           ub[binding[jRow_[i] - 1]], tiny_, veryTiny_)) {
    2109         cuts[binding[jRow_[i] - 1]].insert(jCol_[i]-1,jValues_[i]);
    2110         if(lb[binding[jRow_[i] - 1]] > - infty)
    2111           lb[binding[jRow_[i] - 1]] += jValues_[i] * getColSolution()[jCol_ [i] - 1];
    2112         if(ub[binding[jRow_[i] - 1]] < infty)
    2113         ub[binding[jRow_[i] - 1]] += jValues_[i] * getColSolution()[jCol_ [i] - 1];
    2114       }
    2115     }
    2116   }
    2117 
    2118   for(int i = 0; i< numBindings ; i++) {
    2119     OsiRowCut newCut;
    2120     //    if(lb[i]>-1e20) assert (ub[i]>1e20);
    2121 
    2122     newCut.setGloballyValid();
    2123     newCut.setEffectiveness(99.99e99);
    2124     newCut.setLb(lb[i]);
    2125     newCut.setUb(ub[i]);
    2126     newCut.setRow(cuts[i]);
    2127     //    CftValidator validator;
    2128     //    validator(newCut);
    2129     cs.insert(newCut);
    2130   }
    2131 
    2132   delete[] g;
    2133   delete [] cuts;
    2134 
    2135   if(getObj)  // Get the objective cuts
    2136   {
    2137     double * obj = new double [n];
    2138     tminlp_->eval_grad_f(n, getColSolution(), 1,obj);
    2139     double f;
    2140     tminlp_->eval_f(n, getColSolution(), 1, f);
    2141 
    2142     CoinPackedVector v;
    2143     v.reserve(n);
    2144     lb[nNonLinear_] = -f;
    2145     ub[nNonLinear_] = -f;
    2146     //double minCoeff = 1e50;
    2147     for(int i = 0; i<n ; i++)
    2148     {
    2149       if(cleanNnz(obj[i],colLower[i], colUpper[i],
    2150           -getInfinity(), 0,
    2151           getColSolution()[i],
    2152           lb[nNonLinear_],
    2153           ub[nNonLinear_],tiny_, 1e-15)) {
    2154         //            minCoeff = min(fabs(obj[i]), minCoeff);
    2155         v.insert(i,obj[i]);
    2156         lb[nNonLinear_] += obj[i] * getColSolution()[i];
    2157         ub[nNonLinear_] += obj[i] * getColSolution()[i];
    2158       }
    2159     }
    2160     v.insert(n,-1);
    2161     OsiRowCut newCut;
    2162     newCut.setGloballyValid();
    2163     newCut.setEffectiveness(99.99e99);
    2164     newCut.setRow(v);
    2165     newCut.setLb(-DBL_MAX/*Infinity*/);
    2166     newCut.setUb(ub[nNonLinear_]);
    2167 //     CftValidator validator;
    2168 //     validator(newCut);
    2169     cs.insert(newCut);
    2170     delete [] obj;
    2171   }
    2172 
    2173   delete []lb;
    2174   delete[]ub;
    2175 }
    2176 
    2177 double
    2178 IpoptInterface::getFeasibilityOuterApproximation(int n,const double * x_bar,const int *inds, OsiCuts &cs)
    2179 {
    2180   if(! IsValid(feasibilityProblem_)) {
    2181     throw SimpleError("No feasibility problem","getFeasibilityOuterApproximation");
    2182   }
    2183   feasibilityProblem_->set_dist2point_obj(n,(const Ipopt::Number *) x_bar,(const Ipopt::Index *) inds);
    2184   nCallOptimizeTNLP_++;
    2185   totalNlpSolveTime_-=CoinCpuTime();
    2186   Ipopt::IpoptApplication app2;
    2187   app2.Options()->SetIntegerValue("print_level", (Ipopt::Index) 0);
    2188   optimization_status_ = app2.OptimizeTNLP(GetRawPtr(feasibilityProblem_));
    2189   totalNlpSolveTime_+=CoinCpuTime();
    2190   getOuterApproximation(cs, 0);
    2191   hasBeenOptimized_=true;
    2192   return getObjValue();
    2193 }
    2194 
    2195 
    2196 
    2197 
    2198 
    2199 void
    2200 IpoptInterface::extractLinearRelaxation(OsiSolverInterface &si, bool getObj)
    2201 {
    2202   initialSolve();
    2203 
    2204   CoinPackedMatrix mat;
    2205   double * rowLow = NULL;
    2206   double * rowUp = NULL;
    2207 
    2208   int n;
    2209   int m;
    2210   int nnz_jac_g;
    2211   int nnz_h_lag;
    2212   Ipopt::TNLP::IndexStyleEnum index_style;
    2213   //Get problem information
    2214   tminlp_->get_nlp_info( n, m, nnz_jac_g, nnz_h_lag, index_style);
    2215 
    2216   //if not allocated allocate spaced for stroring jacobian
    2217   if(jRow_ == NULL || jCol_ == NULL || jValues_ == NULL)
    2218     initializeJacobianArrays();
    2219 
    2220   //get Jacobian
    2221   tminlp_->eval_jac_g(n, getColSolution(), 1, m, nnz_jac_g, NULL, NULL, jValues_);
    2222 
    2223 
    2224   double *g = new double[m];
    2225   tminlp_->eval_g(n, getColSolution(),1,m,g);
    2226 
    2227   rowLow = new double[m];
    2228   rowUp = new double[m];
    2229   int * binding = new int[m];//store binding constraints at current opt (which are added to OA) -1 if constraint is not binding, otherwise index in subset of binding constraints
    2230   int numBindings = 0;
    2231   const double * rowLower = getRowLower();
    2232   const double * rowUpper = getRowUpper();
    2233   const double * colLower = getColLower();
    2234   const double * colUpper = getColUpper();
    2235   const double * duals = getRowPrice();
    2236   assert(m==getNumRows());
    2237   double infty = getInfinity();
    2238   double nlp_infty = infty_;
    2239   for(int i = 0 ; i < m ; i++) {
    2240     {
    2241       if(constTypes_[i] == Ipopt::TMINLP::NON_LINEAR) {
    2242         //If constraint is equality not binding do not add
    2243         if(rowLower[i] > -nlp_infty && rowUpper[i] < nlp_infty && fabs(duals[i]) == 0.)
    2244         {
    2245             binding[i] = -1;
    2246             continue;
    2247         }
    2248         else
    2249           binding[i] = numBindings;
    2250         if(rowLower[i] > - nlp_infty)
    2251           rowLow[numBindings] = (rowLower[i] - g[i]) - 1e-07;
    2252         else
    2253           rowLow[numBindings] = - infty;
    2254         if(rowUpper[i] < nlp_infty)
    2255           rowUp[numBindings] =  (rowUpper[i] - g[i]) + 1e-07;
    2256         else
    2257           rowUp[numBindings] = infty;
    2258        
    2259         //If equality or ranged constraint only add one side by looking at sign of dual multiplier
    2260         if(rowLower[i] > -nlp_infty && rowUpper[i] < nlp_infty)
    2261         {
    2262           if(duals[i] >= 0)// <= inequality
    2263             rowLow[numBindings] = - infty;
    2264           if(duals[i] <= 0)// >= inequality
    2265             rowUp[numBindings] = infty;
    2266         }
    2267         numBindings++;
    2268       }
    2269       else {
    2270         binding[i] = numBindings;//All are considered as bindings
    2271         rowLow[numBindings] = (rowLower[i] - g[i]);
    2272         rowUp[numBindings] =  (rowUpper[i] - g[i]);
    2273         numBindings++;
    2274       }
    2275     }
    2276   }
    2277 
    2278   //Then convert everything to a CoinPackedMatrix (col ordered)
    2279   CoinBigIndex * inds = new CoinBigIndex[nnz_jac_g + 1];
    2280   double * vals = new double [nnz_jac_g + 1];
    2281   int * start = new int[n+1];
    2282   int * length = new int[n];
    2283   bool needOrder = false;
    2284   int nnz = 0;
    2285   if(nnz_jac_g > 0)
    2286   {
    2287   for(int k = 0; k < jCol_[0]; k++) {
    2288     start[k] = nnz;
    2289     length[k] = 0;
    2290   }
    2291   for(int i = 0 ; i < nnz_jac_g - 1 ; i++) {
    2292     {
    2293       if(jCol_[i + 1] < jCol_ [i] || ( jCol_ [i+1] == jCol_[i] && jRow_[i + 1] <= jRow_[i]) ) {
    2294         needOrder = 1;
    2295         break;
    2296       }
    2297       if(Ipopt::TMINLP::LINEAR //Always accept coefficients from linear constraints
    2298           || //For other clean tinys
    2299           cleanNnz(jValues_[i],colLower[jCol_[i] - 1], colUpper[jCol_[i]-1],
    2300               rowLower[jRow_[i] - 1], rowUpper[jRow_[i] - 1],
    2301               getColSolution()[jCol_[i] - 1],
    2302               rowLow[binding[jRow_[i] - 1]],
    2303               rowUp[binding[jRow_[i] -1]], tiny_, veryTiny_)) {
    2304         if(binding[jRow_[i] - 1] == -1) continue;
    2305         vals[nnz] = jValues_[i];
    2306         if(rowLow[binding[jRow_[i] - 1]] > - infty_)
    2307           rowLow[binding[jRow_[i] - 1]] += jValues_[i] * getColSolution()[jCol_ [i] - 1];
    2308         if(rowUp[binding[jRow_[i] - 1]] < infty_)
    2309           rowUp[binding[jRow_[i] -1]] += jValues_[i] *getColSolution()[jCol_[i] -1];
    2310         inds[nnz] = binding[jRow_[i] - 1];//jRow_[i ] - 1;
    2311         length[jCol_[i] - 1]++;
    2312         nnz++;
    2313       }
    2314     }
    2315     if(jCol_[i + 1] > jCol_[i]) {
    2316       for(int k = jCol_[i]; k < jCol_[i + 1]; k++) {
    2317         start[k] = nnz;
    2318         length[k] = 0;
    2319       }
    2320     }
    2321   }
    2322   if(!needOrder) {
    2323     {
    2324       length[jCol_[nnz_jac_g -1] - 1]++;
    2325       vals[nnz] = jValues_[nnz_jac_g - 1];
    2326       rowLow[binding[jRow_[nnz_jac_g - 1] - 1]] += jValues_[nnz_jac_g - 1] * getColSolution()[jCol_ [nnz_jac_g - 1] - 1];
    2327       rowUp[binding[jRow_[nnz_jac_g - 1] -1]] += jValues_[nnz_jac_g - 1] *getColSolution()[jCol_[nnz_jac_g - 1] -1];
    2328       inds[nnz++] = binding[jRow_[nnz_jac_g - 1] - 1];
    2329     }
    2330     for(int i = jCol_[nnz_jac_g -1] ; i < n ; i++) {
    2331       start[i] = nnz;
    2332       length[i] = 0;
    2333     }
    2334     start[n]=nnz;
    2335   }
    2336   else {
    2337     std::cerr<<"jacobian matrix is not ordered properly"<<std::endl;
    2338     throw -1;
    2339   }
    2340   delete [] g;
    2341   }
    2342   else {
    2343    for (int i = 0 ; i < n ; i++)
    2344    {
    2345      length[i] = 0;
    2346      start[i] = 0;
    2347    }
    2348    start[n]=0;
    2349  }
    2350  mat.assignMatrix(false, m, n, nnz, vals, inds, start, length);
    2351   int numcols=getNumCols();
    2352   double *obj = new double[numcols];
    2353   for(int i = 0 ; i < numcols ; i++)
    2354     obj[i] = 0;
    2355   mat.transpose();
    2356  
    2357 #if 0
    2358   std::cout<<"Mat is ordered by "<<
    2359   <<mat.isColOrdered?"columns.":"rows."
    2360   <<std::endl;
    2361 #endif
    2362  
    2363   si.loadProblem(mat, getColLower(), getColUpper(), obj, rowLow, rowUp);
    2364   delete [] rowLow;
    2365   delete [] rowUp;
    2366   delete [] binding;
    2367   for(int i = 0 ; i < getNumCols() ; i++) {
    2368     if(isInteger(i))
    2369       si.setInteger(i);
    2370   }
    2371   if(getObj) {
    2372     //add variable alpha
    2373     //(alpha should be empty in the matrix with a coefficient of -1 and unbounded)
    2374     CoinPackedVector a;
    2375     si.addCol(a,-si.getInfinity(), si.getInfinity(), 1.);
    2376 
    2377     // Now get the objective cuts
    2378     // get the gradient, pack it and add the cut
    2379     tminlp_->eval_grad_f(n, getColSolution(), 1,obj);
    2380     double ub;
    2381     tminlp_->eval_f(n, getColSolution(), 1, ub);
    2382     ub*=-1;
    2383     double lb = -1e300;
    2384     CoinPackedVector objCut;
    2385     CoinPackedVector * v = &objCut;
    2386     v->reserve(n);
    2387     for(int i = 0; i<n ; i++) {
    2388      if(nnz_jac_g)
    2389      {
    2390       if(cleanNnz(obj[i],colLower[i], colUpper[i],
    2391           -getInfinity(), 0,
    2392           getColSolution()[i],
    2393           lb,
    2394           ub, tiny_, veryTiny_)) {
    2395         v->insert(i,obj[i]);
    2396         lb += obj[i] * getColSolution()[i];
    2397         ub += obj[i] * getColSolution()[i];
    2398       }
    2399      }
    2400      else //Unconstrained problem can not put clean coefficient
    2401      {
    2402          if(cleanNnz(obj[i],colLower[i], colUpper[i],
    2403           -getInfinity(), 0,
    2404           getColSolution()[i],
    2405           lb,
    2406           ub, 1e-03, 1e-08)) {
    2407         v->insert(i,obj[i]);
    2408         lb += obj[i] * getColSolution()[i];
    2409         ub += obj[i] * getColSolution()[i];
    2410          }
    2411      }
    2412     }
    2413     v->insert(n,-1);
    2414     si.addRow(objCut, lb, ub);
    2415     delete [] obj;
    2416   }
    2417 
    2418 
    2419   setWarmStartOptions();
    2420   setColSolution(problem()->x_sol());
    2421   setRowPrice(problem()->duals_sol());
    2422 
    2423 }
    2424 
    2425 /** Add a collection of linear cuts to problem formulation.*/
    2426 void
    2427 IpoptInterface::applyRowCuts(int numberCuts, const OsiRowCut * cuts)
    2428 {
    2429   const OsiRowCut ** cutsPtrs = new const OsiRowCut*[numberCuts];
    2430   for(int i = 0 ; i < numberCuts ; i++)
    2431   {
    2432     cutsPtrs[i] = &cuts[i];
    2433   }
    2434   tminlp_->addCuts(numberCuts, cutsPtrs);
    2435   delete [] cutsPtrs;
    2436 }
    2437 
     243IpoptInterface::extractInterfaceParams()
     244{
     245  OsiTMINLPInterface::extractInterfaceParams();
     246  app_->Options()->GetEnumValue("warm_start",warmStartStrategy_,"bonmin.");
     247
     248}
     249
     250} /* end namespace Bonmin */
  • branches/devel/Bonmin/src/IpoptInterface/IpoptInterface.hpp

    r44 r53  
    1414#define IpoptInterface_H
    1515
    16 #include <string>
    17 #include <iostream>
    1816
    19 #include "OsiSolverInterface.hpp"
    20 #include "CoinWarmStartBasis.hpp"
     17#include "OsiTMINLPInterface.hpp"
     18#include "IpoptSolver.hpp"
    2119
    22 #include "TMINLP.hpp"
    23 #include "TMINLP2TNLP.hpp"
    24 #include "TNLP2FPNLP.hpp"
    25 
    26 #include "IpIpoptApplication.hpp"
    27 
    28 
     20namespace Bonmin{
    2921/**
    3022   This is class provides an Osi interface for Ipopt
     
    3224*/
    3325
    34 class IpoptInterface : public OsiSolverInterface
     26class IpoptInterface : public OsiTMINLPInterface
    3527{
    3628  friend class BonminParam;
     
    3830public:
    3931
    40   //#############################################################################
    41 
    42   /**Error class to throw exceptions from IpoptInterface.
    43    * Inherited from CoinError, we just want to have a different class to be able to catch
    44    * errors thrown by IpoptInterface.
    45   */
    46 class SimpleError : public CoinError
    47   {
    48   public:
    49     /// Default constructor
    50     SimpleError() : CoinError()
    51     {}
    52 
    53     ///Alternate constructor using strings
    54     SimpleError(std::string message,
    55         std::string methodName)
    56         :
    57         CoinError(message,methodName,std::string("IpoptInterface"))
    58     {}
    59     ///Alternate constructor using const char *
    60     SimpleError (const char * message,
    61         const char * methodName)
    62         :
    63         CoinError(message,methodName,"IpoptInterface")
    64     {}
    65 
    66   }
    67   ;
    68 
    69   //#############################################################################
    70 
    71   /** We will throw this error when a problem is not solved.
    72       Eventually store the error code from Ipopt*/
    73   class UnsolvedError
    74   {
    75   public:
    76     /** Constructor */
    77     UnsolvedError(int errorNum_ = 10000);
    78     /** Print error message.*/
    79     void printError(std::ostream & os);
    80     /** Get the string corresponding to error.*/
    81     const std::string& errorName() const;
    82   private:
    83     int errorNum_;
    84     static std::string errorNames [17];
    85   }
    86   ;
    8732
    8833
    89   //#############################################################################
     34class UnsolvedIpoptError: public OsiTMINLPInterface::UnsolvedError
     35{
     36 public:
     37  UnsolvedIpoptError(int errorNum = 10000):
     38  OsiTMINLPInterface::UnsolvedError(errorNum)
     39  {}
     40  virtual const std::string& errorName() const;
     41 
     42  virtual const std::string& solverName() const;
     43  virtual ~UnsolvedIpoptError(){}
     44  private:
     45  static std::string errorNames [17];
     46  static std::string solverName_;
     47};
    9048
    91 
    92   /** Type of the messages specifically outputed by IpoptInterface.*/
    93   enum MessagesTypes{
    94     SOLUTION_FOUND/**found a feasible solution*/,
    95     INFEASIBLE_SOLUTION_FOUND/**found an infeasible problem*/,
    96     UNSOLVED_PROBLEM_FOUND/**found an unsolved problem*/,
    97     WARNING_RESOLVING /** Warn that a problem is resolved*/,
    98     WARN_SUCCESS_WS/** Problem not solved with warm start but solved without*/,
    99     WARN_SUCCESS_RANDOM/** Subproblem not solve with warm start but solved with random point*/,
    100     WARN_CONTINUING_ON_FAILURE/** a failure occured but is continuing*/,
    101     SUSPECT_PROBLEM/** Output the number of the problem.*/,
    102     SUSPECT_PROBLEM2/** Output the number of the problem.*/,
    103     IPOPT_SUMMARY /** Output summary statistics on Ipopt solution.*/,
    104     BETTER_SOL /** Found a better solution with random values.*/,
    105     LOG_HEAD/** Head of "civilized" log.*/,
    106     LOG_FIRST_LINE/** First line (first solve) of log.*/,
    107     LOG_LINE/**standard line (retry solving) of log.*/,
    108     WARN_RESOLVE_BEFORE_INITIAL_SOLVE /** resolve() has been called but there
    109                                               was no previous call to initialSolve().
    110                                          */,
    111     IPOTPINTERFACE_DUMMY_END
    112   };
    113 
    114   //#############################################################################
    115 
    116 
    117   /** Messages outputed by an IpoptInterface. */
    118 class Messages : public CoinMessages
    119   {
    120   public:
    121     /// Constructor
    122     Messages();
    123   };
    124 
    125 
     49  virtual UnsolvedError * newUnsolvedError(int num){
     50    return new UnsolvedIpoptError(num);}
    12651  //#############################################################################
    12752
     
    13459    \warning In this constructor option file is not read, use readOptionFile to read one.
    13560  */
    136   IpoptInterface (Ipopt::SmartPtr<Ipopt::TMINLP> tminlp);
     61  IpoptInterface (Ipopt::SmartPtr<Bonmin::TMINLP> tminlp);
    13762
    13863  /// Clone
     
    15075
    15176
    152   /// Retrieve IpoptApplication option list
    153   Ipopt::SmartPtr<Ipopt::OptionsList> retrieve_options();
    154 
    155   /** Register all possible options to Ipopt */
    156   void register_ALL_options (Ipopt::SmartPtr<Ipopt::RegisteredOptions> roptions);
    157 
    158   /** Set specific Ipopt default for MINLP's */
    159   void set_ipopt_minlp_default(SmartPtr<OptionsList> Options);
    160 
    161   /// Read parameter file
    162   void readOptionFile(const char * fileName);
    163   //@}
    164 
    16577  void extractInterfaceParams();
    166 
    167   //---------------------------------------------------------------------------
    168   /**@name Solve methods */
    169   //@{
    170   /// Solve initial continuous relaxation
    171   virtual void initialSolve();
    172 
    173   /** Resolve the continuous relaxation after problem modification.
    174       Have to call initialSolve before calling this
    175    */
    176   virtual void resolve();
    177 
    178   /** Resolve the problem with different random starting points
    179       to try to find a better solution (only makes sense for a non-convex problem.*/
    180   void resolveForCost(int numretry);
    181 
    182   /** Method to be called when a problem has failed to be solved. Will try
    183       to resolve it with different settings.
    184   */
    185   void resolveForRobustness(int numretry);
    186 
    187   /// Nescessary for compatibility with OsiSolverInterface but does nothing.
    188   virtual void branchAndBound()
    189   {
    190     throw SimpleError("Function not implemented for IpoptInterface","branchAndBound()");
    191   }
    192   //@}
    193 
    194 
    195 
    196   //---------------------------------------------------------------------------
    197   ///@name Methods returning info on how the solution process terminated
    198   //@{
    199   /// Are there a numerical difficulties?
    200   virtual bool isAbandoned() const;
    201   /// Is optimality proven?
    202   virtual bool isProvenOptimal() const;
    203   /// Is primal infeasiblity proven?
    204   virtual bool isProvenPrimalInfeasible() const;
    205   /// Is dual infeasiblity proven?
    206   virtual bool isProvenDualInfeasible() const;
    207   /// Is the given primal objective limit reached?
    208   virtual bool isPrimalObjectiveLimitReached() const;
    209   /// Is the given dual objective limit reached?
    210   virtual bool isDualObjectiveLimitReached() const;
    211   /// Iteration limit reached?
    212   virtual bool isIterationLimitReached() const;
    213   /// Return status of last optimization
    214   Ipopt::ApplicationReturnStatus getOptStatus() const
    215   {
    216     return optimization_status_;
    217   }
    218 
    219   ///Warn solver that branch-and-bound is continuing after a failure
    220   void continuingOnAFailure()
    221   {
    222     hasContinuedAfterNlpFailure_ = true;
    223   }
    224   /// Did we continue on a failure
    225   bool hasContinuedOnAFailure()
    226   {
    227     return hasContinuedAfterNlpFailure_;
    228   }
    229   /// tell to ignore the failures (don't throw, don't fathom, don't report)
    230   void ignoreFailures()
    231   {
    232     pretendFailIsInfeasible_ = 2;
    233   }
    234   /// Force current solution to be infeasible
    235   void forceInfeasible()
    236   {
    237     problem_->set_obj_value(1e200);
    238   }
    239   /// Force current solution to be branched on (make it fractionnal with small objective)
    240   void forceBranchable()
    241   {
    242     problem_->set_obj_value(-1e200);
    243     problem_->force_fractionnal_sol();
    244   }
    245   //@}
    246 
    247 
    248   //---------------------------------------------------------------------------
    249   /**@name Parameter set/get methods
    250 
    251      The set methods return true if the parameter was set to the given value,
    252      false otherwise. There can be various reasons for failure: the given
    253      parameter is not applicable for the solver (e.g., refactorization
    254      frequency for the clp algorithm), the parameter is not yet implemented
    255      for the solver or simply the value of the parameter is out of the range
    256      the solver accepts. If a parameter setting call returns false check the
    257      details of your solver.
    258 
    259      The get methods return true if the given parameter is applicable for the
    260      solver and is implemented. In this case the value of the parameter is
    261      returned in the second argument. Otherwise they return false.
    262   */
    263   //@{
    264   // Set an integer parameter
    265   bool setIntParam(OsiIntParam key, int value);
    266   // Set an double parameter
    267   bool setDblParam(OsiDblParam key, double value);
    268   // Set a string parameter
    269   bool setStrParam(OsiStrParam key, const std::string & value);
    270   // Get an integer parameter
    271   bool getIntParam(OsiIntParam key, int& value) const;
    272   // Get an double parameter
    273   bool getDblParam(OsiDblParam key, double& value) const;
    274   // Get a string parameter
    275   bool getStrParam(OsiStrParam key, std::string& value) const;
    276 
    277   // Get the push values for starting point
    278   inline double getPushFact() const
    279   {
    280     return pushValue_;
    281   }
    282 
    28378  //@}
    28479
    28580  //---------------------------------------------------------------------------
    286   /**@name Problem information methods
    28781
    288      These methods call the solver's query routines to return
    289      information about the problem referred to by the current object.
    290      Querying a problem that has no data associated with it result in
    291      zeros for the number of rows and columns, and NULL pointers from
    292      the methods that return vectors.
    293 
    294      Const pointers returned from any data-query method are valid as
    295      long as the data is unchanged and the solver is not called.
    296   */
    297   //@{
    298   /**@name Methods related to querying the input data */
    299   //@{
    300   /// Get number of columns
    301   virtual int getNumCols() const;
    302 
    303   /// Get number of rows
    304   virtual int getNumRows() const;
    305 
    306   ///get name of variables
    307   const std::string * getVarNames() const;
    308   /// Get pointer to array[getNumCols()] of column lower bounds
    309   virtual const double * getColLower() const;
    310 
    311   /// Get pointer to array[getNumCols()] of column upper bounds
    312   virtual const double * getColUpper() const;
    313 
    314   /** Get pointer to array[getNumRows()] of row constraint senses.
    315       <ul>
    316       <li>'L': <= constraint
    317       <li>'E': =  constraint
    318       <li>'G': >= constraint
    319       <li>'R': ranged constraint
    320       <li>'N': free constraint
    321       </ul>
    322   */
    323   virtual const char * getRowSense() const;
    324 
    325   /** Get pointer to array[getNumRows()] of rows right-hand sides
    326       <ul>
    327       <li> if rowsense()[i] == 'L' then rhs()[i] == rowupper()[i]
    328       <li> if rowsense()[i] == 'G' then rhs()[i] == rowlower()[i]
    329       <li> if rowsense()[i] == 'R' then rhs()[i] == rowupper()[i]
    330       <li> if rowsense()[i] == 'N' then rhs()[i] == 0.0
    331       </ul>
    332   */
    333   virtual const double * getRightHandSide() const;
    334 
    335   /** Get pointer to array[getNumRows()] of row ranges.
    336       <ul>
    337       <li> if rowsense()[i] == 'R' then
    338       rowrange()[i] == rowupper()[i] - rowlower()[i]
    339       <li> if rowsense()[i] != 'R' then
    340       rowrange()[i] is 0.0
    341       </ul>
    342   */
    343   virtual const double * getRowRange() const;
    344 
    345   /// Get pointer to array[getNumRows()] of row lower bounds
    346   virtual const double * getRowLower() const;
    347 
    348   /// Get pointer to array[getNumRows()] of row upper bounds
    349   virtual const double * getRowUpper() const;
    350 
    351   /** Get objective function sense (1 for min (default), -1 for max)
    352    * Ipopt always minimizes */
    353   virtual double getObjSense() const
    354   {
    355     return 1;
    356   }
    357 
    358   /// Return true if column is continuous
    359   virtual bool isContinuous(int colNumber) const;
    360 
    361   /// Return true if column is binary
    362   virtual bool isBinary(int columnNumber) const;
    363 
    364   /** Return true if column is integer.
    365       Note: This function returns true if the the column
    366       is binary or a general integer.
    367   */
    368   virtual bool isInteger(int columnNumber) const;
    369 
    370   /// Return true if column is general integer
    371   virtual bool isIntegerNonBinary(int columnNumber) const;
    372 
    373   /// Return true if column is binary and not fixed at either bound
    374   virtual bool isFreeBinary(int columnNumber) const;
    375 
    376   /// Get solver's value for infinity
    377   virtual double getInfinity() const;
    378 
    379   ///Get priorities on integer variables.
    380   const int * getPriorities() const
    381   {
    382     const Ipopt::TMINLP::BranchingInfo * branch = tminlp_->branchingInfo();
    383     if(branch)
    384       return branch->priorities;
    385     else return NULL;
    386   }
    387   ///get prefered branching directions
    388   const int * getBranchingDirections() const
    389   {
    390     const Ipopt::TMINLP::BranchingInfo * branch = tminlp_->branchingInfo();
    391     if(branch)
    392       return branch->branchingDirections;
    393     else return NULL;
    394   }
    395   const double * getUpPsCosts() const
    396   {
    397     const Ipopt::TMINLP::BranchingInfo * branch = tminlp_->branchingInfo();
    398     if(branch)
    399     return branch->upPsCosts;
    400     else return NULL;
    401   }
    402   const double * getDownPsCosts() const
    403   {
    404     const Ipopt::TMINLP::BranchingInfo * branch = tminlp_->branchingInfo();
    405     if(branch)
    406     return branch->downPsCosts;
    407     else return NULL;
    408   }
     82  /// Return status of last optimization
     83  Ipopt::ApplicationReturnStatus getOptStatus() const;
    40984
    41085
    411   //@}
    412 
    413   /**@name Methods related to querying the solution */
    414   //@{
    415   /// Get pointer to array[getNumCols()] of primal solution vector
    416   virtual const double * getColSolution() const;
    417 
    418   /// Get pointer to array[getNumRows()] of dual prices
    419   virtual const double * getRowPrice() const;
    420 
    421   /// Get a pointer to array[getNumCols()] of reduced costs
    422   virtual const double * getReducedCost() const;
    423 
    424   /** Get pointer to array[getNumRows()] of row activity levels (constraint
    425       matrix times the solution vector */
    426   virtual const double * getRowActivity() const;
    427 
    428 
    429   /** Get how many iterations it took to solve the problem (whatever
    430       "iteration" mean to the solver.
    431       * \todo Figure out what it could mean for Ipopt.
    432       */
    433   virtual int getIterationCount() const;
    434 
    435   /** get total number of calls to solve.*/
    436   int nCallOptimizeTNLP()
    437   {
    438     return nCallOptimizeTNLP_;
    439   }
    440   /** get total time taken to solve NLP's. */
    441   double totalNlpSolveTime()
    442   {
    443     return totalNlpSolveTime_;
    444   }
    445   /** get total number of iterations */
    446   int totalIterations()
    447   {
    448     return totalIterations_;
    449   }
    450 
    451 
    452   //@}
    453   //-------------------------------------------------------------------------
    454   /**@name Methods to modify the objective, bounds, and solution
    455   */
    456   //@{
    457 
    458   /** Set a single column lower bound.
    459       Use -getInfinity() for -infinity. */
    460   virtual void setColLower( int elementIndex, double elementValue );
    461 
    462   /** Set a single column upper bound.
    463       Use getInfinity() for infinity. */
    464   virtual void setColUpper( int elementIndex, double elementValue );
    465 
    466 
    467 
    468   /** Set a single row lower bound.
    469       Use -getInfinity() for -infinity. */
    470   virtual void setRowLower( int elementIndex, double elementValue );
    471 
    472   /** Set a single row upper bound.
    473       Use getInfinity() for infinity. */
    474   virtual void setRowUpper( int elementIndex, double elementValue );
    475 
    476   /** Set the type of a single row */
    477   virtual void setRowType(int index, char sense, double rightHandSide,
    478       double range);
    479 
    480 
    481   /** \brief Set the objective function sense (disabled).
    482    * (1 for min (default), -1 for max)
    483    \todo Make it work.
    484    \bug Can not treat maximisation problems. */
    485   virtual void setObjSense(double s);
    486 
    487   /** Set the primal solution variable values
    488       Set the values for the starting point.
    489       \warning getColSolution will never return this vector (unless it is optimal).
    490   */
    491   virtual void setColSolution(const double *colsol);
    492 
    493   /** Set dual solution variable values.
    494       set the values for the starting point.
    495       \warning getRowPrice will never return this vector (unless it is optimal).
    496   */
    497   virtual void setRowPrice(const double * rowprice);
    498 
    499   //@}
    50086
    50187
     
    532118  }
    533119
    534   void randomStartingPoint();
    535 
    536   //Returns true if a basis is available
    537   virtual bool basisIsAvailable() const
    538   {
    539     // Throw an exception
    540     throw SimpleError("Needs coding for this interface", "basisIsAvailable");
    541   }
    542 
    543 
    544120  //@}
    545121
    546   //-------------------------------------------------------------------------
    547   /**@name Methods to set variable type */
    548   //@{
    549   /** Set the index-th variable to be a continuous variable */
    550   virtual void setContinuous(int index);
    551   /** Set the index-th variable to be an integer variable */
    552   virtual void setInteger(int index);
    553   //@}
    554 
    555   //Set numIterationSuspect_
    556   void setNumIterationSuspect(int value)
    557   {
    558     numIterationSuspect_ = value;
    559   }
    560 
    561   /**@name Dummy functions
    562    * Functions which have to be implemented in an OsiSolverInterface,
    563    * but which do not do anything (but throwing exceptions) here in the case of a
    564    * minlp solved using Ipopt for continuous relaxations */
    565   //@{
    566 
    567   /** Cbc will understand that no matrix exsits if return -1
    568   */
    569   virtual int getNumElements() const
    570   {
    571     return -1;
    572   }
    573 
    574 
    575   /** We have to keep this but it will throw an error.
    576   */
    577   virtual const double * getObjCoefficients() const
    578   {
    579     if(!obj_)
    580       throw SimpleError("Ipopt model does not implement this function (function irelevant in an minlp).",
    581           "getObjCoefficients");
    582     return obj_;
    583   }
    584 
    585   /** We have to keep this but it will throw an error.
    586    */
    587   virtual const CoinPackedMatrix * getMatrixByRow() const
    588   {
    589     throw CoinError("Ipopt model does not implement this function.",
    590         "getMatrixByRow()","IpoptInterface");
    591   }
    592 
    593 
    594   /** We have to keep this but it will throw an error.
    595    */
    596   virtual const CoinPackedMatrix * getMatrixByCol() const
    597   {
    598     throw CoinError("Ipopt model does not implement this function.",
    599         "getMatrixByCol()","IpoptInterface");
    600   }
    601 
    602   /** We have to keep this but it will throw an error.
    603   */
    604   virtual void setObjCoeff( int elementIndex, double elementValue )
    605   {
    606     throw CoinError("Ipopt model does not implement this function.",
    607         "setObjCoeff","IpoptInterface");
    608   }
    609 
    610   /** We have to keep this but it will throw an error.
    611   */
    612   virtual void addCol(const CoinPackedVectorBase& vec,
    613       const double collb, const double colub,
    614       const double obj)
    615   {
    616     throw CoinError("Ipopt model does not implement this function.",
    617         "addCol","IpoptInterface");
    618   }
    619   /** We have to keep this but it will throw an error.
    620   */
    621   virtual void deleteCols(const int num, const int * colIndices)
    622   {
    623     throw CoinError("Ipopt model does not implement this function.",
    624         "deleteCols","IpoptInterface");
    625   }
    626 
    627   /** We have to keep this but it will throw an error.
    628   */
    629   virtual void addRow(const CoinPackedVectorBase& vec,
    630       const double rowlb, const double rowub)
    631   {
    632     throw CoinError("Ipopt model does not implement this function.",
    633         "addRow","IpoptInterface");
    634   }
    635   /** We have to keep this but it will throw an error.
    636   */
    637   virtual void addRow(const CoinPackedVectorBase& vec,
    638       const char rowsen, const double rowrhs,
    639       const double rowrng)
    640   {
    641     throw CoinError("Ipopt model does not implement this function.",
    642         "addRow","IpoptInterface");
    643   }
    644   /** We have to keep this but it will throw an error.
    645   */
    646   virtual void deleteRows(const int num, const int * rowIndices)
    647   {
    648      tminlp_->removeCuts(num, rowIndices);
    649   }
    650 
    651   void deleteLastRows(int number){
    652   tminlp_->removeLastCuts(number);
    653   }
    654 
    655   /** We have to keep this but it will throw an error
    656   */
    657   virtual void loadProblem(const CoinPackedMatrix& matrix,
    658       const double* collb, const double* colub,
    659       const double* obj,
    660       const double* rowlb, const double* rowub)
    661   {
    662     throw CoinError("Ipopt model does not implement this function.",
    663         "loadProblem","IpoptInterface");
    664   }
    665 
    666 
    667   /** We have to keep this but it will throw an error.
    668   */
    669   virtual void assignProblem(CoinPackedMatrix*& matrix,
    670       double*& collb, double*& colub, double*& obj,
    671       double*& rowlb, double*& rowub)
    672   {
    673     throw CoinError("Ipopt model does not implement this function.",
    674         "assignProblem","IpoptInterface");
    675   }
    676 
    677   /** We have to keep this but it will throw an error.
    678   */
    679   virtual void loadProblem(const CoinPackedMatrix& matrix,
    680       const double* collb, const double* colub,
    681       const double* obj,
    682       const char* rowsen, const double* rowrhs,
    683       const double* rowrng)
    684   {
    685     throw CoinError("Ipopt model does not implement this function.",
    686         "loadProblem","IpoptInterface");
    687   }
    688 
    689   /** We have to keep this but it will throw an error.
    690   */
    691   virtual void assignProblem(CoinPackedMatrix*& matrix,
    692       double*& collb, double*& colub, double*& obj,
    693       char*& rowsen, double*& rowrhs,
    694       double*& rowrng)
    695   {
    696     throw CoinError("Ipopt model does not implement this function.",
    697         "assignProblem","IpoptInterface");
    698   }
    699 
    700 
    701   /** We have to keep this but it will throw an error.
    702   */
    703   virtual void loadProblem(const int numcols, const int numrows,
    704       const int* start, const int* index,
    705       const double* value,
    706       const double* collb, const double* colub,
    707       const double* obj,
    708       const double* rowlb, const double* rowub)
    709   {
    710     throw CoinError("Ipopt model does not implement this function.",
    711         "loadProblem","IpoptInterface");
    712   }
    713 
    714   /** We have to keep this but it will throw an error.
    715   */
    716   virtual void loadProblem(const int numcols, const int numrows,
    717       const int* start, const int* index,
    718       const double* value,
    719       const double* collb, const double* colub,
    720       const double* obj,
    721       const char* rowsen, const double* rowrhs,
    722       const double* rowrng)
    723   {
    724     throw CoinError("Ipopt model does not implement this function.",
    725         "loadProblem","IpoptInterface");
    726   }
    727 
    728   /** We have to keep this but it will throw an error.
    729   */
    730   virtual int readMps(const char *filename,
    731       const char *extension = "mps")
    732   {
    733     throw CoinError("Ipopt model does not implement this function.",
    734         "readMps","IpoptInterface");
    735   }
    736 
    737 
    738   /** We have to keep this but it will throw an error.
    739   */
    740   virtual void writeMps(const char *filename,
    741       const char *extension = "mps",
    742       double objSense=0.0) const
    743   {
    744     throw CoinError("Ipopt model does not implement this function.",
    745         "writeMps","IpoptInterface");
    746   }
    747 
    748   /** Throws an error */
    749   virtual std::vector<double*> getDualRays(int maxNumRays) const
    750   {
    751     throw SimpleError("Ipopt model does not implement this function.",
    752         "getDualRays");
    753   }
    754 
    755   /** Throws an error */
    756   virtual std::vector<double*> getPrimalRays(int maxNumRays) const
    757   {
    758     throw CoinError("Ipopt model does not implement this function.",
    759         "getPrimalRays","IpoptInterface");
    760   }
    761 
    762   //@}
    763122
    764123  //---------------------------------------------------------------------------
     
    773132  //@}
    774133
    775   /**@name Sets and Getss */
    776   //@{
    777   /// Get objective function value (can't use default)
    778   virtual double getObjValue() const;
    779 
    780   //@}
    781 
    782   /** get pointer to the TMINLP2TNLP adapter */
    783   const Ipopt::TMINLP2TNLP * problem() const
    784   {
    785     return GetRawPtr(problem_);
    786   }
    787 
    788   const Ipopt::TMINLP * model() const
    789   {
    790     return GetRawPtr(tminlp_);
    791   }
    792134 
    793   /** Methods to build outer approximations */
    794   //@{
    795   /** \brief Extract a linear relaxation of the MINLP.
    796    * Solve the continuous relaxation and takes first-order outer-approximation constraints at the optimum.
    797    * The put everything in an OsiSolverInterface.
    798    */
    799   void extractLinearRelaxation(OsiSolverInterface &si, bool getObj = 1);
    800 
    801   /** Get the outer approximation constraints at the currently stored optimal point.
    802    (Only get outer-approximations of nonlinear constraints of the problem.)*/
    803   void getOuterApproximation(OsiCuts &cs, bool getObj = 1);
    804 
    805   /** solve the problem of finding the closest point to x_bar in the subspace of coordinates given by ind
    806    * (i.e., \f$ min \sum\limits_{i=1}^n (x_{ind[i]} -\overline{x}_i)^2 \f$ ,
    807    * and get the corresponding outer-approximation constraints.
    808       (Only get outer-approximations of nonlinear constraints of the problem.)
    809    * \return Distance between feasibility set and x
    810    * \param n number of element in arrays x and ind
    811    * \param ind indices of the coordinate*/
    812   double getFeasibilityOuterApproximation(int n, const double * x_bar,const int *ind, OsiCuts &cs);
    813   //@}
    814   /** get NLP constraint violation of current point */
    815 
    816 
    817    /** Add a collection of linear cuts to problem formulation.*/
    818   virtual void applyRowCuts(int numberCuts, const OsiRowCut * cuts);
    819 
    820 
    821   /** Add a collection of linear cuts to the problem formulation */
    822   virtual void applyRowCuts(int numberCuts, const OsiRowCut ** cuts)
    823   {
    824     tminlp_->addCuts(numberCuts, cuts);
    825   }
    826 
    827 
    828  double getConstraintViolation();
    829 
    830135//---------------------------------------------------------------------------
    831136protected:
    832 
    833   /// Initialize data structures for storing the jacobian
    834   int initializeJacobianArrays();
    835 
    836   ///@name Virtual callbacks for application specific stuff
    837   //@{
    838   virtual std::string  appName()
    839   {
    840     return "bonmin";
    841   }
    842   //@}
    843   ///@name Protected methods
    844   //@{
    845137
    846138  /** Call Ipopt to solve or resolve the problem and check for errors.*/
     
    849141
    850142
    851   /** Add a linear cut to the problem formulation.
    852   */
    853   virtual void applyRowCut( const OsiRowCut & rc )
    854   {
    855     const OsiRowCut * cut = &rc;
    856     tminlp_->addCuts(1, &cut);
    857   }
    858   /** We have to keep this but it will throw an error.
    859   */
    860   virtual void applyColCut( const OsiColCut & cc )
    861   {
    862     throw SimpleError("Ipopt model does not implement this function.",
    863         "applyColCut");
    864   }
    865 
    866   /** Read the name of the variables in an ampl .col file. */
    867   void readVarNames() const;
    868 
    869143  //@}
    870144
    871   /**@name Ipopt structures */
    872   //@{
    873   /** TMINLP model.*/
    874   Ipopt::SmartPtr<Ipopt::TMINLP> tminlp_;
    875   /** Adapter for a MINLP to a NLP */
    876   Ipopt::SmartPtr<Ipopt::TMINLP2TNLP> problem_;
    877   /** IpoptApplication */
    878   Ipopt::SmartPtr<Ipopt::IpoptApplication> app_;
    879   //@}
    880 
    881   /**@name Cached information on the problem */
    882   //@{
    883   /** Free cached data relative to variables */
    884   void freeCachedColRim();
    885   /** Free cached data relative to constraints */
    886   void freeCachedRowRim();
    887   /** Free all cached data*/
    888   void freeCachedData();
    889   /** Extract rowsense_ vector rhs_ vector and rowrange_ vector from the lower and upper bounds
    890    *  on the constraints */
    891   void extractSenseRhsAndRange() const;
    892   /// Pointer to dense vector of row sense indicators
    893   mutable char    *rowsense_;
    894 
    895   /// Pointer to dense vector of row right-hand side values
    896   mutable double  *rhs_;
    897 
    898   /// Pointer to dense vector of slack upper bounds for range constraints (undefined for non-range rows)
    899   mutable double  *rowrange_;
    900   /** Pointer to dense vector of reduced costs
    901       \warning Always 0. with Ipopt*/
    902   mutable double  *reducedCosts_;
    903   /** DualObjectiveLimit is used to store the cutoff in Cbc*/
    904   double OsiDualObjectiveLimit_;
    905   /** Return status of the Ipopt optimization */
    906   Ipopt::ApplicationReturnStatus optimization_status_;
    907   /** Variable names */
    908   mutable std::string * varNames_;
    909   /** does the file variable names exists (will check automatically).*/
    910   mutable bool hasVarNamesFile_;
    911   //@}
    912   /// number of time NLP has been solved
    913   int nCallOptimizeTNLP_;
    914   /// Total solution time of NLP
    915   double totalNlpSolveTime_;
    916   /// toatal number of iterations
    917   int totalIterations_;
    918   /// max radius for random point
    919   double maxRandomRadius_;
    920   /// Ipopt value for pushing initial point inside the bounds
    921   double pushValue_;
    922   /// Number of times problem will be resolved in initialSolve (root node)
    923   int numRetryInitial_;
    924   /// Number of times problem will be resolved in resolve
    925   int numRetryResolve_;
    926   /// Number of times problem will be resolved in case of a failure
    927   int numRetryUnsolved_;
    928   /** Messages specific to an IpoptInterface. */
    929   Messages ipoptIMessages_;
    930   /** If not 0 when a problem is not solved (failed to be solved)
    931       will pretend that it is infeasible. If == 1 will care
    932       (i.e. record the fact issue messages to user), if ==2 don't care (somebody else will) */
    933   int pretendFailIsInfeasible_;
    934   /** did we ever continue optimization ignoring a failure. */
    935   bool hasContinuedAfterNlpFailure_;
    936   /** number iterations above which a problem is considered suspect (-1 is considered \f$+ \infty \f$).
    937         If in a call to solve a problem takes more than that number of iterations it will be outputed to files.*/
    938   int numIterationSuspect_ ;
    939   /** Has problem been optimized since last change (include setColSolution).
    940      If yes getColSolution will return Ipopt point, otherwise will return
    941      initial point.*/
    942   bool hasBeenOptimized_;
    943145  /** Warm start strategy :
    944146  <ol>
     
    949151  */
    950152  int warmStartStrategy_;
    951   /** A fake objective function (all variables to 1) to please Cbc pseudo costs initialization.*/
    952   double * obj_;
    953153  /** flag to say wether options have been printed or not.*/
    954154  static bool hasPrintedOptions;
    955 
    956   /** Adapter for TNLP to a feasibility problem */
    957   Ipopt::SmartPtr<Ipopt::TNLP2FPNLP> feasibilityProblem_;
    958 
    959 
    960   /** \name Arrays to store Jacobian matrix */
    961   //@{
    962   /** Row indices.*/
    963   int * jRow_;
    964   /** Column indices.*/
    965   int * jCol_;
    966   /** Values */
    967   double * jValues_;
    968   /** Number of elements.*/
    969   int nnz_jac;
    970   //@}
    971 
    972   ///Store the types of the constraints (linear and nonlinear).
    973   Ipopt::TMINLP::ConstraintType * constTypes_;
    974   /* Numerotation of linear/nonlinear constraints
    975    * Perform independent numerotation of linear (resp. nonlinear constraints)
    976    * so that constraints of each type are numeroted consecutively */
    977  // int * constTypesNum_;
    978   /** Number of linear constraints */
    979   int nLinear_;
    980   /** Number of nonlinear constraint
    981    */
    982   int nNonLinear_;
    983   /** Value for small non-zero element which we will try to remove cleanly in OA cuts.*/
    984   double tiny_;
    985   /** Value for small non-zero element which we will take the risk to ignore in OA cuts.*/
    986   double veryTiny_;
    987   /** Value for infinity. */
    988   double infty_;
    989 
    990155};
    991 
     156}
    992157#endif
  • branches/devel/Bonmin/src/IpoptInterface/IpoptWarmStart.cpp

    r1 r53  
    1919
    2020
     21namespace Bonmin {
    2122/// Default constructor
    2223IpoptWarmStart::IpoptWarmStart
     
    158159  }
    159160}
     161}
  • branches/devel/Bonmin/src/IpoptInterface/IpoptWarmStart.hpp

    r1 r53  
    1616#include "IpoptInteriorWarmStarter.hpp"
    1717
     18
     19namespace Bonmin {
    1820class IpoptInterface;
    1921
     
    145147  SmartPtr<IpoptInteriorWarmStarter> warm_starter_;
    146148};
     149
     150}
    147151#endif
  • branches/devel/Bonmin/src/IpoptInterface/Makefile.am

    r44 r53  
    1717# List all source files, including headers
    1818libipoptinterface_la_SOURCES = \
    19         IpCbcBoundsReader.cpp IpCbcBoundsReader.hpp \
     19        BoundsReader.cpp BoundsReader.hpp \
    2020        IpCbcColReader.cpp IpCbcColReader.hpp \
    2121        IpCbcStartPointReader.cpp IpCbcStartPointReader.hpp \
    2222        IpoptIntegerBias.hpp \
    2323        IpoptInterface.cpp IpoptInterface.hpp \
     24        OsiTMINLPInterface.cpp OsiTMINLPInterface.hpp \
    2425        IpoptInteriorWarmStarter.cpp IpoptInteriorWarmStarter.hpp \
    2526        IpoptWarmStart.cpp IpoptWarmStart.hpp \
    2627        TMINLP2TNLP.cpp TMINLP2TNLP.hpp \
    2728        TMINLP.cpp TMINLP.hpp \
     29        IpoptSolver.hpp IpoptSolver.cpp \
     30        TNLPSolver.hpp TNLPSolver.cpp \
    2831        TNLP2FPNLP.cpp TNLP2FPNLP.hpp
    2932
     
    5760include_HEADERS = \
    5861        IpoptInterface.hpp \
     62        OsiTMINLPInterface.hpp \
    5963        IpoptInteriorWarmStarter.hpp \
    6064        TMINLP2TNLP.hpp \
    6165        TMINLP.hpp \
    62         TNLP2FPNLP.hpp
     66        TNLP2FPNLP.hpp \
     67        TNLPSolver.hpp \
     68        IpoptSolver.hpp
    6369
    6470#############################################################################
     
    8692# Here repeat all source files, with "bak" appended
    8793ASTYLE_FILES = \
    88         IpCbcBoundsReader.cppbak IpCbcBoundsReader.hppbak \
     94        BoundsReader.cppbak BoundsReader.hppbak \
    8995        IpCbcColReader.cppbak IpCbcColReader.hppbak \
    9096        IpCbcStartPointReader.cppbak IpCbcStartPointReader.hppbak \
    9197        IpoptIntegerBias.hppbak \
    9298        IpoptInterface.cppbak IpoptInterface.hppbak \
     99        OsiTMINLPInterface.cppbak OsiTMINLPInterface.hppbak \
    93100        IpoptInteriorWarmStarter.cppbak IpoptInteriorWarmStarter.hppbak \
    94101        IpoptWarmStart.cppbak IpoptWarmStart.hppbak \
    95102        TMINLP2TNLP.cppbak TMINLP2TNLP.hppbak \
    96103        TMINLP.hppbak TMINLP.hppbak \
     104        TNLPSolver.hppbak TNLPSolver.hppbak \
     105        IpoptSolver.hppbak  IpoptSolver.cpp \
    97106        TNLP2FPNLP.cppbak TNLP2FPNLP.hppbak
    98107
  • branches/devel/Bonmin/src/IpoptInterface/Makefile.in

    r44 r53  
    5757LTLIBRARIES = $(noinst_LTLIBRARIES)
    5858libipoptinterface_la_LIBADD =
    59 am_libipoptinterface_la_OBJECTS = IpCbcBoundsReader.lo \
    60         IpCbcColReader.lo IpCbcStartPointReader.lo IpoptInterface.lo \
    61         IpoptInteriorWarmStarter.lo IpoptWarmStart.lo TMINLP2TNLP.lo \
    62         TMINLP.lo TNLP2FPNLP.lo
     59am_libipoptinterface_la_OBJECTS = BoundsReader.lo IpCbcColReader.lo \
     60        IpCbcStartPointReader.lo IpoptInterface.lo \
     61        OsiTMINLPInterface.lo IpoptInteriorWarmStarter.lo \
     62        IpoptWarmStart.lo TMINLP2TNLP.lo TMINLP.lo IpoptSolver.lo \
     63        TNLPSolver.lo TNLP2FPNLP.lo
    6364libipoptinterface_la_OBJECTS = $(am_libipoptinterface_la_OBJECTS)
    6465depcomp = $(SHELL) $(top_srcdir)/../depcomp
     
    309310# List all source files, including headers
    310311libipoptinterface_la_SOURCES = \
    311         IpCbcBoundsReader.cpp IpCbcBoundsReader.hpp \
     312        BoundsReader.cpp BoundsReader.hpp \
    312313        IpCbcColReader.cpp IpCbcColReader.hpp \
    313314        IpCbcStartPointReader.cpp IpCbcStartPointReader.hpp \
    314315        IpoptIntegerBias.hpp \
    315316        IpoptInterface.cpp IpoptInterface.hpp \
     317        OsiTMINLPInterface.cpp OsiTMINLPInterface.hpp \
    316318        IpoptInteriorWarmStarter.cpp IpoptInteriorWarmStarter.hpp \
    317319        IpoptWarmStart.cpp IpoptWarmStart.hpp \
    318320        TMINLP2TNLP.cpp TMINLP2TNLP.hpp \
    319321        TMINLP.cpp TMINLP.hpp \
     322        IpoptSolver.hpp IpoptSolver.cpp \
     323        TNLPSolver.hpp TNLPSolver.cpp \
    320324        TNLP2FPNLP.cpp TNLP2FPNLP.hpp
    321325
     
    350354include_HEADERS = \
    351355        IpoptInterface.hpp \
     356        OsiTMINLPInterface.hpp \
    352357        IpoptInteriorWarmStarter.hpp \
    353358        TMINLP2TNLP.hpp \
    354359        TMINLP.hpp \
    355         TNLP2FPNLP.hpp
     360        TNLP2FPNLP.hpp \
     361        TNLPSolver.hpp \
     362        IpoptSolver.hpp
    356363
    357364
     
    369376# Here repeat all source files, with "bak" appended
    370377ASTYLE_FILES = \
    371         IpCbcBoundsReader.cppbak IpCbcBoundsReader.hppbak \
     378        BoundsReader.cppbak BoundsReader.hppbak \
    372379        IpCbcColReader.cppbak IpCbcColReader.hppbak \
    373380        IpCbcStartPointReader.cppbak IpCbcStartPointReader.hppbak \
    374381        IpoptIntegerBias.hppbak \
    375382        IpoptInterface.cppbak IpoptInterface.hppbak \
     383        OsiTMINLPInterface.cppbak OsiTMINLPInterface.hppbak \
    376384        IpoptInteriorWarmStarter.cppbak IpoptInteriorWarmStarter.hppbak \
    377385        IpoptWarmStart.cppbak IpoptWarmStart.hppbak \
    378386        TMINLP2TNLP.cppbak TMINLP2TNLP.hppbak \
    379387        TMINLP.hppbak TMINLP.hppbak \
     388        TNLPSolver.hppbak TNLPSolver.hppbak \
     389        IpoptSolver.hppbak  IpoptSolver.cpp \
    380390        TNLP2FPNLP.cppbak TNLP2FPNLP.hppbak
    381391
     
    433443        -rm -f *.tab.c
    434444
    435 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/IpCbcBoundsReader.Plo@am__quote@
     445@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BoundsReader.Plo@am__quote@
    436446@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/IpCbcColReader.Plo@am__quote@
    437447@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/IpCbcStartPointReader.Plo@am__quote@
    438448@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/IpoptInterface.Plo@am__quote@
    439449@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/IpoptInteriorWarmStarter.Plo@am__quote@
     450@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/IpoptSolver.Plo@am__quote@
    440451@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/IpoptWarmStart.Plo@am__quote@
     452@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OsiTMINLPInterface.Plo@am__quote@
    441453@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/TMINLP.Plo@am__quote@
    442454@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/TMINLP2TNLP.Plo@am__quote@
    443455@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/TNLP2FPNLP.Plo@am__quote@
     456@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/TNLPSolver.Plo@am__quote@
    444457
    445458.cpp.o:
  • branches/devel/Bonmin/src/IpoptInterface/TMINLP.cpp

    r49 r53  
     1// (C) Copyright International Business Machines (IBM) 2005
     2// All Rights Reserved.
     3// This code is published under the Common Public License.
     4//
     5// Authors :
     6// Pierre Bonami, IBM
     7//
     8// Date : 26/09/2006
     9
    110#include "TMINLP.hpp"
    211#include "IpBlas.hpp"
    312
    4 
     13namespace Bonmin{
    514
    615/** default constructor for Sos constraints */
    7 Ipopt::TMINLP::SosInfo::SosInfo():
     16TMINLP::SosInfo::SosInfo():
    817        num(0),
    918        types(NULL),
     
    1625
    1726/** Copy constructor.*/
    18 Ipopt::TMINLP::SosInfo::SosInfo(const SosInfo & source):
     27TMINLP::SosInfo::SosInfo(const SosInfo & source):
    1928        num(source.num),
    2029        types(NULL),
     
    6069/** Reset information */
    6170void
    62 Ipopt::TMINLP::SosInfo::gutsOfDestructor()
     71TMINLP::SosInfo::gutsOfDestructor()
    6372{
    6473  num = 0;
     
    7786
    7887
    79 Ipopt::TMINLP::TMINLP():
     88TMINLP::TMINLP():
    8089    jCol_(NULL),
    8190    iRow_(NULL),
     
    91100
    92101void
    93 Ipopt::TMINLP::addCuts(int numberCuts, const OsiRowCut ** cuts){
     102TMINLP::addCuts(int numberCuts, const OsiRowCut ** cuts){
    94103
    95104 int n,m,nnz_lag,nnz_hess;
     
    133142
    134143void
    135 Ipopt::TMINLP::resizeLinearCuts(int newNumberCuts, int newNnz)
     144TMINLP::resizeLinearCuts(int newNumberCuts, int newNnz)
    136145{
    137146  if(newNumberCuts > linearCutsCapacity_)
     
    174183}
    175184void
    176 Ipopt::TMINLP::removeCuts(int number, const int * toRemove){
     185TMINLP::removeCuts(int number, const int * toRemove){
    177186 if(! CoinIsSorted(toRemove, number))
    178187 {
     
    196205}
    197206void
    198 Ipopt::TMINLP::removeLastCuts(int number){
     207TMINLP::removeLastCuts(int number){
    199208 number = nLinearCuts_ - number;
    200209 int iNew = 0;
     
    211220 std::cout<<"Number of cuts remaining "<<nLinearCuts_<<std::endl;
    212221 }
     222}
  • branches/devel/Bonmin/src/IpoptInterface/TMINLP.hpp

    r44 r53  
    2222
    2323#include "CoinHelperFunctions.hpp"
    24 namespace Ipopt
     24using namespace Ipopt;
     25namespace Bonmin
    2526{
    2627
     
    5253   *  -ipopt_inf or +ipopt_inf respectively
    5354   */
    54   class TMINLP : public ReferencedObject
     55  class TMINLP : public Ipopt::ReferencedObject
    5556  {
    5657  public:
  • branches/devel/Bonmin/src/IpoptInterface/TMINLP2TNLP.cpp

    r44 r53  
    1717#include <fstream>
    1818#include <sstream>
    19 namespace Ipopt
     19namespace Bonmin
    2020{
    21   TMINLP2TNLP::TMINLP2TNLP(const SmartPtr<TMINLP> tminlp,
    22       const OptionsList& options)
     21  TMINLP2TNLP::TMINLP2TNLP(const SmartPtr<TMINLP> tminlp
     22#ifdef WARM_STARTER
     23       ,
     24      const OptionsList& options
     25#endif
     26       )
    2327      :
    2428      tminlp_(tminlp),
     
    8387    duals_sol_ = NULL;
    8488    duals_init_ = NULL;
     89
     90#ifdef WARM_STARTER
    8591    // Get values for parameters
    8692    options.GetNumericValue("nlp_lower_bound_inf", nlp_lower_bound_inf_, "");
     
    8894    options.GetBoolValue("warm_start_entire_iterate",
    8995        warm_start_entire_iterate_, "");
     96#endif
    9097  }
    9198
     
    440447    }
    441448  }
    442   bool TMINLP2TNLP::checkZeroDimension(ApplicationReturnStatus
    443       &optimization_status)
    444   {
    445     for(int i = 0 ; i < n_ ; i++) {
    446       if(x_u_[i] - x_l_[i] > 1e-5)
    447         return 0;
    448     }
    449 
    450     //Problem has no variables just check if the unique solution given by the bounds is
    451     // feasible or not.
    452     eval_f(n_, x_l_, true, obj_value_);
    453     if (!x_sol_) {
    454       x_sol_ = new Number[n_];
    455     }
    456     IpBlasDcopy(n_, x_l_, 1, x_sol_, 1);
    457 
    458     if(!g_sol_) {
    459       g_sol_ = new Number [m_];
    460     }
    461     eval_g(n_, x_l_, true, m_, g_sol_);
    462     optimization_status = Solve_Succeeded;
    463     for(int i = 0 ; i < m_ ; i++) {
    464       if(g_sol_[i] - g_l_[i] <  - 1e-07 || g_sol_[i] - g_u_[i] > 1e-07) {
    465         optimization_status = Infeasible_Problem_Detected;
    466         return 1;
    467       }
    468     }
    469     return 1;
    470   }
     449
    471450
    472451  bool TMINLP2TNLP::intermediate_callback(AlgorithmMode mode,
     
    480459      IpoptCalculatedQuantities* ip_cq)
    481460  {
     461#if WARM_STARTER
    482462    // If we don't have this swtiched on, we assume that also the
    483463    // "warm_start" option for bonmin is set not to refer to the
     
    486466      return true;
    487467    }
    488 
    489468    if (need_new_warm_starter_) {
    490469      // Create a new object for later warm start information
     
    497476
    498477    return curr_warm_starter_->UpdateStoredIterates(mode, *ip_data, *ip_cq);
     478#else
     479    return true;
     480#endif
    499481  }
    500482
  • branches/devel/Bonmin/src/IpoptInterface/TMINLP2TNLP.hpp

    r1 r53  
    2020#include "IpoptInteriorWarmStarter.hpp"
    2121
    22 namespace Ipopt
     22namespace Bonmin
    2323{
    2424  /** This is an adapter class that converts a TMINLP to
     
    2828   *  relaxed, or fixed
    2929   */
    30   class TMINLP2TNLP : public TNLP
     30  class TMINLP2TNLP : public Ipopt::TNLP
    3131  {
    3232  public:
    3333    /**@name Constructors/Destructors */
    3434    //@{
    35     TMINLP2TNLP(const SmartPtr<TMINLP> tminlp,
    36         const OptionsList& options);
     35    TMINLP2TNLP(const SmartPtr<TMINLP> tminlp
     36#ifdef WARM_STARTER
     37        ,
     38        const OptionsList& options
     39#endif
     40        );
    3741
    3842    /** Default destructor */
     
    296300    /** Method called to check wether a problem has still some variable not fixed. If there are no more
    297301        unfixed vars, checks wether the solution given by the bounds is feasible.*/
    298     bool checkZeroDimension(ApplicationReturnStatus& optimization_status);
    299302
    300303    /** @name Methods for setting and getting the warm starter */
  • branches/devel/Bonmin/src/IpoptInterface/TNLP2FPNLP.cpp

    r1 r53  
    1111#include "TNLP2FPNLP.hpp"
    1212#include "IpBlas.hpp"
    13 namespace Ipopt
     13namespace Bonmin
    1414{
    1515  TNLP2FPNLP::TNLP2FPNLP(const SmartPtr<TNLP> tnlp, double objectiveScalingFactor):
  • branches/devel/Bonmin/src/IpoptInterface/TNLP2FPNLP.hpp

    r1 r53  
    1313#include "IpSmartPtr.hpp"
    1414
    15 namespace Ipopt
     15namespace Bonmin
    1616{
    1717  /** This is an adapter class to convert an NLP to a Feasibility Pump NLP
     
    1919   * The extra function is set_dist2point_obj(int n, const double *, const int *)
    2020   */
    21   class TNLP2FPNLP : public TNLP
     21  class TNLP2FPNLP : public Ipopt::TNLP
    2222  {
    2323  public:
  • branches/devel/Bonmin/src/OaInterface/IpCbcDummyHeuristic.cpp

    r1 r53  
    1313
    1414#include "OsiAuxInfo.hpp"
     15namespace Bonmin{
    1516/// Default constructor
    1617IpCbcDummyHeuristic::IpCbcDummyHeuristic(CbcModel &model,
     
    4647}
    4748
     49}
  • branches/devel/Bonmin/src/OaInterface/IpCbcDummyHeuristic.hpp

    r1 r53  
    1313
    1414#include "CbcHeuristic.hpp"
    15 
     15namespace Bonmin{
    1616class  IpCbcDummyHeuristic : public CbcHeuristic
    1717{
     
    4747  bool knowsSolution;
    4848};
     49}
    4950#endif
  • branches/devel/Bonmin/src/OaInterface/IpCbcOACutGenerator.cpp

    r44 r53  
    1010#include "IpCbcOACutGenerator.hpp"
    1111#include "OsiAuxInfo.hpp"
     12
     13namespace Bonmin{
    1214/// Default constructor
    1315IpCbcOACutGenerator::IpCbcOACutGenerator(IpoptInterface * si,
     
    6062  }
    6163
    62 #ifdef 0
     64#if 0
    6365 //Add tight cuts at LP optimum
    6466 int numberCuts = si.getNumRows() - nlp_->getNumRows();
     
    171173    }
    172174  }
     175#if 0
    173176  nlp_->deleteLastRows(numberCuts);
     177#endif
    174178  delete [] saveColLb;
    175179  delete [] saveColUb;
    176180}
     181}
  • branches/devel/Bonmin/src/OaInterface/IpCbcOACutGenerator.hpp

    r1 r53  
    1313#include "IpoptInterface.hpp"
    1414#include "OaMessages.hpp"
    15 
     15namespace Bonmin{
    1616class IpCbcOACutGenerator : public CglCutGenerator
    1717{
     
    7878  CoinMessages messages_;
    7979};
     80}
    8081#endif
  • branches/devel/Bonmin/src/OaInterface/IpCbcOACutGenerator2.cpp

    r26 r53  
    2323
    2424extern CbcModel * OAModel;
    25 
     25namespace Bonmin{
    2626/// Default constructor
    2727IpCbcOACutGenerator2::IpCbcOACutGenerator2():
     
    867867  delete strategy;
    868868}
     869}
  • branches/devel/Bonmin/src/OaInterface/IpCbcOACutGenerator2.hpp

    r1 r53  
    2020#include "CoinTime.hpp"
    2121
    22 
     22namespace Bonmin{
    2323class IpCbcOACutGenerator2 : public CglCutGenerator
    2424{
     
    183183  double logFrequency_;
    184184};
     185}
    185186#endif
  • branches/devel/Bonmin/test/InterfaceTest.cpp

    r49 r53  
    1313#include "AmplTMINLP.hpp"
    1414#include "IpIpoptApplication.hpp"
     15
     16using namespace Bonmin;
    1517/** Test function for the Osi interface to Ipopt (or any nlp solver). <br>
    1618    If Solver passes all the test then it should have everything needed to be integrated into bonmin. */
     
    148150}
    149151
    150 void testOa(BonminAmplInterface &si)
     152void testOa(Bonmin::AmplInterface &si)
    151153{
    152154        CoinRelFltEq eq(1e-07);// to test equality of doubles   
     
    208210}
    209211
    210 void testFp(BonminAmplInterface &si)
     212void testFp(Bonmin::AmplInterface &si)
    211213{
    212214        CoinRelFltEq eq(1e-07);// to test equality of doubles
     
    243245        //Setup Ipopt should be replaced if solver is changed
    244246        using namespace Ipopt;
    245       SmartPtr<Ipopt::IpoptApplication> app = new Ipopt::IpoptApplication();
     247      SmartPtr<Bonmin::IpoptSolver> app = new Bonmin::IpoptSolver();
    246248       const char * args[3] ={"name","mytoy",NULL}; //Ugly, but I don't know how to do differently
    247249       const char ** argv = args;
    248       SmartPtr<Ipopt::TMINLP> ampl_tminlp = new Ipopt::AmplTMINLP(ConstPtr(app->Jnlst()), app->Options(), const_cast<char**&>(argv));
     250      SmartPtr<TMINLP> ampl_tminlp = new AmplTMINLP(ConstPtr(app->getIpoptApp().Jnlst()), app->Options(), const_cast<char**&>(argv));
    249251      IpoptInterface si(ampl_tminlp);
    250252    std::cout<<"---------------------------------------------------------------------------------------------------------------------------------------------------------"
     
    277279      const char * args[3] ={"name","mytoy",NULL}; //Ugly, but I don't know how to do differently
    278280      const char ** argv = args;
    279       SmartPtr<Ipopt::TMINLP> ampl_tminlp = new Ipopt::AmplTMINLP(ConstPtr(app->Jnlst()),  app->Options(), const_cast<char**&>(argv));
     281      SmartPtr<TMINLP> ampl_tminlp = new AmplTMINLP(ConstPtr(app->Jnlst()),  app->Options(), const_cast<char**&>(argv));
    280282      IpoptInterface si1(ampl_tminlp);
    281283     
     
    296298        const char * args[3] ={"name","mytoy",NULL}; //Ugly, but I don't know how to do differently
    297299        const char ** argv = args;
    298       BonminAmplInterface si(const_cast<char**&>(argv));
     300      Bonmin::AmplInterface si(const_cast<char**&>(argv));
    299301      std::cout<<"---------------------------------------------------------------------------------------------------------------------------------------------------------"
    300302               <<std::endl<<"Testing outer approximations related methods"<<std::endl
     
    310312//    char * args[3] ={"name","toy3",NULL}; //Ugly, but I don't know how to do differently
    311313//    char ** argv = args;
    312 //    SmartPtr<Ipopt::TMINLP> ampl_tminlp = new Ipopt::AmplTMINLP(ConstPtr(app->Jnlst()),  app->Options(), argv);
    313 //    BonminAmplInterface si(ampl_tminlp);
     314//    SmartPtr<TMINLP> ampl_tminlp = new AmplTMINLP(ConstPtr(app->Jnlst()),  app->Options(), argv);
     315//    Bonmin::AmplInterface si(ampl_tminlp);
    314316//    std::cout<<"---------------------------------------------------------------------------------------------------------------------------------------------------------"
    315317//           <<std::endl<<"Testing optimization of some distance over feasible set"<<std::endl
  • branches/devel/Bonmin/test/Makefile.am

    r49 r53  
    7575        -I`$(CYGPATH_W) $(IPOPTSRCDIR)/src/LinAlg` \
    7676        -I`$(CYGPATH_W) $(COINUTILSSRCDIR)/src` \
     77        -I`$(CYGPATH_W) $(COINUTILSOBJDIR)/inc` \
    7778        -I`$(CYGPATH_W) $(OSISRCDIR)/src` \
    7879        -I`$(CYGPATH_W) $(OSISRCDIR)/src/OsiClp` \
  • branches/devel/Bonmin/test/Makefile.in

    r49 r53  
    363363        -I`$(CYGPATH_W) $(IPOPTSRCDIR)/src/LinAlg` \
    364364        -I`$(CYGPATH_W) $(COINUTILSSRCDIR)/src` \
     365        -I`$(CYGPATH_W) $(COINUTILSOBJDIR)/inc` \
    365366        -I`$(CYGPATH_W) $(OSISRCDIR)/src` \
    366367        -I`$(CYGPATH_W) $(OSISRCDIR)/src/OsiClp` \
Note: See TracChangeset for help on using the changeset viewer.