Changeset 62


Ignore:
Timestamp:
Sep 29, 2006 4:48:36 PM (13 years ago)
Author:
pbonami
Message:

astyled the devel branch

Location:
branches/devel/Bonmin/src
Files:
22 edited

Legend:

Unmodified
Added
Removed
  • branches/devel/Bonmin/src/BonminAmplInterface/BonAmplInterface.cpp

    r57 r62  
    44
    55
    6 namespace Bonmin {
    7 /** Default constructor */
    8 AmplInterface::AmplInterface(): IpoptInterface(), amplTminlp_(NULL)
    9 {}
    10  
    11 /** Constructor with inputed ampl command line (reads model from nl file)*/
    12 AmplInterface::AmplInterface(char **& amplArgs)
    13 :
    14 IpoptInterface(),
    15 amplTminlp_(NULL)
     6namespace Bonmin
    167{
    17   readAmplNlFile(amplArgs, NULL, NULL);
    18 }
     8  /** Default constructor */
     9  AmplInterface::AmplInterface(): IpoptInterface(), amplTminlp_(NULL)
     10  {}
    1911
    20 /** Copy constructor */
    21 AmplInterface::AmplInterface(const AmplInterface &other):
    22           IpoptInterface(other), amplTminlp_(NULL)
    23 {
    24   amplTminlp_ = dynamic_cast<Bonmin::AmplTMINLP *> (GetRawPtr(tminlp_));
    25 }
     12  /** Constructor with inputed ampl command line (reads model from nl file)*/
     13  AmplInterface::AmplInterface(char **& amplArgs)
     14      :
     15      IpoptInterface(),
     16      amplTminlp_(NULL)
     17  {
     18    readAmplNlFile(amplArgs, NULL, NULL);
     19  }
     20
     21  /** Copy constructor */
     22  AmplInterface::AmplInterface(const AmplInterface &other):
     23      IpoptInterface(other), amplTminlp_(NULL)
     24  {
     25    amplTminlp_ = dynamic_cast<Bonmin::AmplTMINLP *> (GetRawPtr(tminlp_));
     26  }
    2627/// Clone
    27 AmplInterface *
    28 AmplInterface::clone(bool CopyData )
    29 {
    30   return new AmplInterface(*this);
    31 }
     28  AmplInterface *
     29  AmplInterface::clone(bool CopyData )
     30  {
     31    return new AmplInterface(*this);
     32  }
    3233
    3334///Destructor
    34 AmplInterface::~AmplInterface()
    35 {amplTminlp_ = NULL;}
     35  AmplInterface::~AmplInterface()
     36  {
     37    amplTminlp_ = NULL;
     38  }
    3639
    37 /** Read an ampl . nl file from the given filename */
    38 void
    39 AmplInterface::readAmplNlFile(char**& filename,
    40     std::string* ipopt_file_content,
    41     std::string* nl_file_content)
    42 {
     40  /** Read an ampl . nl file from the given filename */
     41  void
     42  AmplInterface::readAmplNlFile(char**& filename,
     43      std::string* ipopt_file_content,
     44      std::string* nl_file_content)
     45  {
    4346
    4447
    4548
    46   app_ = new IpoptSolver;
     49    app_ = new IpoptSolver;
    4750
    48   SmartPtr<RegisteredOptions> roptions = app_->RegOptions();
    49   register_ALL_options(roptions);
     51    SmartPtr<RegisteredOptions> roptions = app_->RegOptions();
     52    register_ALL_options(roptions);
    5053
    51   // Call initalize to open output
    52   app_->Initialize("");
    53   // Read the bonmin.opt input file
    54   if (ipopt_file_content == NULL) {
    55     app_->Initialize("bonmin.opt");
    56   }
    57   else {
    58     std::stringstream ss(ipopt_file_content->c_str());
    59     app_->Initialize(ss);
    60   }
     54    // Call initalize to open output
     55    app_->Initialize("");
     56    // Read the bonmin.opt input file
     57    if (ipopt_file_content == NULL) {
     58      app_->Initialize("bonmin.opt");
     59    }
     60    else {
     61      std::stringstream ss(ipopt_file_content->c_str());
     62      app_->Initialize(ss);
     63    }
    6164
    6265
    63   // set the default options... expect_infeasible, etc...
    64   IpoptSolver * ipopt = dynamic_cast<IpoptSolver *> (GetRawPtr(app_));
    65   if(!IsValid(tminlp_)) {
    66         amplTminlp_ = new AmplTMINLP(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
    67         NULL, appName() , nl_file_content);
    68         tminlp_ = GetRawPtr(amplTminlp_);
    69   }
    70   else {
    71     AmplTMINLP * amplTMINLP = dynamic_cast<AmplTMINLP *> (GetRawPtr(tminlp_));
    72     if(amplTMINLP) {
    73       AmplTMINLP * newAmpl = amplTMINLP->createEmpty();
    74       newAmpl->Initialize(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
    75           NULL, appName() , nl_file_content);
    76       amplTminlp_ = newAmpl;
    77       tminlp_ = GetRawPtr(amplTminlp_);
    78     }
    79     else {
     66    // set the default options... expect_infeasible, etc...
     67    IpoptSolver * ipopt = dynamic_cast<IpoptSolver *> (GetRawPtr(app_));
     68    if (!IsValid(tminlp_)) {
    8069      amplTminlp_ = new AmplTMINLP(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
    8170          NULL, appName() , nl_file_content);
    8271      tminlp_ = GetRawPtr(amplTminlp_);
    8372    }
    84   }
    85   problem_ = new TMINLP2TNLP(tminlp_);//, *app_->Options());
     73    else {
     74      AmplTMINLP * amplTMINLP = dynamic_cast<AmplTMINLP *> (GetRawPtr(tminlp_));
     75      if (amplTMINLP) {
     76        AmplTMINLP * newAmpl = amplTMINLP->createEmpty();
     77        newAmpl->Initialize(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
     78            NULL, appName() , nl_file_content);
     79        amplTminlp_ = newAmpl;
     80        tminlp_ = GetRawPtr(amplTminlp_);
     81      }
     82      else {
     83        amplTminlp_ = new AmplTMINLP(ConstPtr(ipopt->getIpoptApp().Jnlst()), app_->Options(), filename,
     84            NULL, appName() , nl_file_content);
     85        tminlp_ = GetRawPtr(amplTminlp_);
     86      }
     87    }
     88    problem_ = new TMINLP2TNLP(tminlp_);//, *app_->Options());
    8689
    87   bool print_options_documentation;
    88   app_->Options()->GetBoolValue("print_options_documentation",
    89       print_options_documentation, "");
    90   if (print_options_documentation) {
    91     std::list<std::string> categories;
    92     categories.push_back("bonmin branch-and-bound options");
    93     categories.push_back("bonmin options for robustness");
    94     categories.push_back("bonmin options for non-convex problems");
    95     categories.push_back("bonmin options : B-Hyb specific options");
     90    bool print_options_documentation;
     91    app_->Options()->GetBoolValue("print_options_documentation",
     92        print_options_documentation, "");
     93    if (print_options_documentation) {
     94      std::list<std::string> categories;
     95      categories.push_back("bonmin branch-and-bound options");
     96      categories.push_back("bonmin options for robustness");
     97      categories.push_back("bonmin options for non-convex problems");
     98      categories.push_back("bonmin options : B-Hyb specific options");
    9699//    roptions->OutputLatexOptionDocumentation2(*app_->Jnlst(),categories);
    97     roptions->OutputOptionDocumentation(*(ipopt->getIpoptApp().Jnlst()),categories);
     100      roptions->OutputOptionDocumentation(*(ipopt->getIpoptApp().Jnlst()),categories);
     101    }
     102
     103    int numcols = getNumCols();
     104    if (obj_)
     105      delete [] obj_;
     106    obj_ = new double[numcols];
     107    CoinFillN(obj_,numcols,1.);
     108    setStrParam(OsiProbName, std::string(filename[1]));
     109    extractInterfaceParams();
     110    hasBeenOptimized_ = false;
     111    feasibilityProblem_ = new TNLP2FPNLP
     112        (Ipopt::SmartPtr<TNLP>(Ipopt::GetRawPtr(problem_)));
    98113  }
    99114
    100   int numcols = getNumCols();
    101   if(obj_)
    102     delete [] obj_;
    103   obj_ = new double[numcols];
    104   CoinFillN(obj_,numcols,1.);
    105   setStrParam(OsiProbName, std::string(filename[1]));
    106   extractInterfaceParams();
    107   hasBeenOptimized_ = false;
    108   feasibilityProblem_ = new TNLP2FPNLP
    109       (Ipopt::SmartPtr<TNLP>(Ipopt::GetRawPtr(problem_)));
    110 }
    111 
    112 /** write ampl solution file */
    113 void
    114 AmplInterface::writeAmplSolFile(std::string message,const double * primalSol,const double * dualSol)
    115 {
    116   TMINLP * tminlp = GetRawPtr(tminlp_);
    117   AmplTMINLP * ampl_tminlp = dynamic_cast<AmplTMINLP *> (tminlp);
    118   if(ampl_tminlp)
    119     ampl_tminlp->write_solution(message,primalSol,dualSol);
    120   else
    121     std::cerr<<"Errot can not write .sol file for non ampl problem"<<std::endl;
    122 }
     115  /** write ampl solution file */
     116  void
     117  AmplInterface::writeAmplSolFile(std::string message,const double * primalSol,const double * dualSol)
     118  {
     119    TMINLP * tminlp = GetRawPtr(tminlp_);
     120    AmplTMINLP * ampl_tminlp = dynamic_cast<AmplTMINLP *> (tminlp);
     121    if (ampl_tminlp)
     122      ampl_tminlp->write_solution(message,primalSol,dualSol);
     123    else
     124      std::cerr<<"Errot can not write .sol file for non ampl problem"<<std::endl;
     125  }
    123126
    124127}
  • branches/devel/Bonmin/src/BonminAmplInterface/BonAmplInterface.hpp

    r57 r62  
    44#include "BonAmplTMINLP.hpp"
    55
    6 namespace Bonmin {
    7 /** Class for providing an Osi interface to Ipopt with an ampl nl file as input. */
    8 class AmplInterface: public IpoptInterface
     6namespace Bonmin
    97{
     8  /** Class for providing an Osi interface to Ipopt with an ampl nl file as input. */
     9  class AmplInterface: public IpoptInterface
     10  {
    1011  public:
    11   /** Default constructor */
    12   AmplInterface();
    13   /** Constructor with inputed ampl command line (reads model from nl file)*/
    14   AmplInterface(char **& amplArgs);
    15   /** Copy constructor */
    16   AmplInterface(const AmplInterface &other);
    17   /// Clone
    18   virtual AmplInterface * clone(bool CopyData = true);
     12    /** Default constructor */
     13    AmplInterface();
     14    /** Constructor with inputed ampl command line (reads model from nl file)*/
     15    AmplInterface(char **& amplArgs);
     16    /** Copy constructor */
     17    AmplInterface(const AmplInterface &other);
     18    /// Clone
     19    virtual AmplInterface * clone(bool CopyData = true);
    1920
    20   ///Destructor
    21   virtual ~AmplInterface();
     21    ///Destructor
     22    virtual ~AmplInterface();
    2223
    23    /**@name Methods to input a problem */
    24   //@{
    25   /** Read an ampl . nl file from the given filename */
    26   virtual void readAmplNlFile(char**& filename,
    27       std::string* ipopt_file_content =NULL,
    28       std::string* nl_file_content = NULL);
    29   /** write ampl solution file */
    30   void writeAmplSolFile(std::string message,const double * primalSol = NULL,const double * dualSol = NULL);
    31   //@}
     24    /**@name Methods to input a problem */
     25    //@{
     26    /** Read an ampl . nl file from the given filename */
     27    virtual void readAmplNlFile(char**& filename,
     28        std::string* ipopt_file_content =NULL,
     29        std::string* nl_file_content = NULL);
     30    /** write ampl solution file */
     31    void writeAmplSolFile(std::string message,const double * primalSol = NULL,const double * dualSol = NULL);
     32    //@}
    3233
    33   /** Fast access to AmplTMINLP */
    34    const AmplTMINLP * amplModel() const
    35   {
    36     return GetRawPtr(amplTminlp_);
    37   }
    38  
     34    /** Fast access to AmplTMINLP */
     35    const AmplTMINLP * amplModel() const
     36    {
     37      return GetRawPtr(amplTminlp_);
     38    }
     39
    3940  protected:
    40    /** TMINLP problem (the original problem usually an AmplTMINLP).*/
    41   Ipopt::SmartPtr<Bonmin::AmplTMINLP> amplTminlp_;
    42 };
     41    /** TMINLP problem (the original problem usually an AmplTMINLP).*/
     42    Ipopt::SmartPtr<Bonmin::AmplTMINLP> amplTminlp_;
     43  };
    4344}
    4445#endif
  • branches/devel/Bonmin/src/BonminAmplInterface/BonAmplTMINLP.cpp

    r60 r62  
    6262
    6363
    64     if(suffix_handler==NULL)
     64    if (suffix_handler==NULL)
    6565      suffix_handler_ = suffix_handler = new AmplSuffixHandler();
    6666
     
    6969    suffix_handler->AddAvailableSuffix("scaling_factor", AmplSuffixHandler::Constraint_Source, AmplSuffixHandler::Number_Type);
    7070    suffix_handler->AddAvailableSuffix("scaling_factor", AmplSuffixHandler::Objective_Source, AmplSuffixHandler::Number_Type);
    71  
     71
    7272    // priority suffix
    7373    suffix_handler->AddAvailableSuffix("priority", AmplSuffixHandler::Variable_Source, AmplSuffixHandler::Index_Type);
     
    8686    suffix_handler->AddAvailableSuffix("sstatus", AmplSuffixHandler::Variable_Source, AmplSuffixHandler::Index_Type);
    8787    suffix_handler->AddAvailableSuffix("sstatus", AmplSuffixHandler::Constraint_Source, AmplSuffixHandler::Index_Type);
    88    
     88
    8989
    9090    SmartPtr<AmplOptionsList> ampl_options_list = new AmplOptionsList();
     
    9393    std::string options_id = appName + "_options";
    9494    ampl_tnlp_ = new AmplTNLP(jnlst, options, argv, suffix_handler, true,
    95          ampl_options_list, options_id.c_str(),
     95        ampl_options_list, options_id.c_str(),
    9696        appName.c_str(), appName.c_str(), nl_file_content);
    9797    /* Read suffixes */
     
    101101
    102102  AmplTMINLP::~AmplTMINLP()
    103   {delete ampl_tnlp_;}
     103  {
     104    delete ampl_tnlp_;
     105  }
    104106
    105107  void
     
    120122    branch_.gutsOfDestructor();
    121123    branch_.size = numcols;
    122     if(pri) {
     124    if (pri) {
    123125      branch_.priorities = new int[numcols];
    124       for(int i = 0 ; i < numcols ; i++) {
     126      for (int i = 0 ; i < numcols ; i++) {
    125127        branch_.priorities [i] = -pri[i] + 9999;
    126128      }
    127129    }
    128     if(brac) {
     130    if (brac) {
    129131      branch_.branchingDirections = CoinCopyOfArray(brac,numcols);
    130132    }
    131     if(upPs && !dwPs) dwPs = upPs;
    132     else if(dwPs && !upPs) upPs = dwPs;
    133  
    134     if(upPs) {
     133    if (upPs && !dwPs) dwPs = upPs;
     134    else if (dwPs && !upPs) upPs = dwPs;
     135
     136    if (upPs) {
    135137      branch_.upPsCosts = CoinCopyOfArray(upPs,numcols);
    136138    }
    137     if(dwPs) {
     139    if (dwPs) {
    138140      branch_.downPsCosts = CoinCopyOfArray(dwPs,numcols);
    139141    }
    140   } 
     142  }
    141143
    142144  void
     
    171173      for (int ii=0;ii<sos_.num;ii++) {
    172174        int ichar = sos_.types[ii];
    173         if(ichar != '1') {
     175        if (ichar != '1') {
    174176          std::cerr<<"Unsuported type of sos constraint: "<<sos_.types[ii]<<std::endl;
    175177          throw;
     
    287289    //the first nlc constraints are non linear the rest is linear
    288290    int i;
    289     for(i = 0 ; i < nlc ; i++)
     291    for (i = 0 ; i < nlc ; i++)
    290292      const_types[i]=NON_LINEAR;
    291293    // the rest is linear
    292     for(; i < n_con ; i++)
     294    for (; i < n_con ; i++)
    293295      const_types[i]=LINEAR;
    294296    return true;
     
    302304
    303305  bool AmplTMINLP::get_starting_point(Index n, bool init_x, Number* x,
    304                                     bool init_z, Number* z_L, Number* z_U,
     306      bool init_z, Number* z_L, Number* z_U,
    305307      Index m, bool init_lambda, Number* lambda)
    306308  {
  • branches/devel/Bonmin/src/BonminAmplInterface/BonAmplTMINLP.hpp

    r57 r62  
    1818#include "OsiCuts.hpp"
    1919// Declarations, so that we don't have to include the Ipopt AMPL headers
    20 namespace Ipopt{
     20namespace Ipopt
     21{
    2122  class AmplTNLP;
    2223  class AmplSuffixHandler;
     
    9293    from TMINLP */
    9394    virtual bool get_starting_point(Index n, bool init_x, Number* x,
    94                                     bool init_z, Number* z_L, Number* z_U,
     95        bool init_z, Number* z_L, Number* z_U,
    9596        Index m, bool init_lambda, Number* lambda);
    9697
     
    140141    //@}
    141142
    142    
     143
    143144    virtual const BranchingInfo * branchingInfo() const
    144145    {
    145146      return &branch_;
    146     } 
     147    }
    147148
    148149    virtual const SosInfo * sosConstraints() const
  • branches/devel/Bonmin/src/CbcBonmin/BonCbc.cpp

    r58 r62  
    6464#include "CoinSignal.hpp"
    6565
    66 extern "C" {
    67    static void signal_handler(int whichSignal)
    68   {
    69       if (currentBranchModel!=NULL)
    70         currentBranchModel->setMaximumNodes(0); // stop at next node
    71       if (OAModel!=NULL)
    72         OAModel->setMaximumNodes(0); // stop at next node
    73       if (currentOA!=NULL)
    74         currentOA->setMaxLocalSearchTime(0.); // stop at next node
    75       return;
    76    }
     66extern "C"
     67{
     68  static void signal_handler(int whichSignal) {
     69    if (currentBranchModel!=NULL)
     70      currentBranchModel->setMaximumNodes(0); // stop at next node
     71    if (OAModel!=NULL)
     72      OAModel->setMaximumNodes(0); // stop at next node
     73    if (currentOA!=NULL)
     74      currentOA->setMaxLocalSearchTime(0.); // stop at next node
     75    return;
     76  }
    7777}
    7878
    79 namespace Bonmin {
    80 /** Constructor.*/
    81 Bab::Bab():
    82     bestSolution_(NULL),
    83     mipStatus_(),
    84     bestObj_(1e200),
    85     bestBound_(-1e200),
    86     continuousRelaxation_(-DBL_MAX),
    87     numNodes_(0),
    88     mipIterationCount_(0)
    89 {}
    90 
    91 /** Destructor.*/
    92 Bab::~Bab()
     79namespace Bonmin
    9380{
    94   if(bestSolution_) delete [] bestSolution_;
    95   bestSolution_ = NULL;
     81  /** Constructor.*/
     82  Bab::Bab():
     83      bestSolution_(NULL),
     84      mipStatus_(),
     85      bestObj_(1e200),
     86      bestBound_(-1e200),
     87      continuousRelaxation_(-DBL_MAX),
     88      numNodes_(0),
     89      mipIterationCount_(0)
     90  {}
     91
     92  /** Destructor.*/
     93  Bab::~Bab()
     94  {
     95    if (bestSolution_) delete [] bestSolution_;
     96    bestSolution_ = NULL;
     97  }
     98  /** Perform a branch-and-bound on given IpoptInterface using passed parameters.*/
     99  void
     100  Bab::branchAndBound(OsiTMINLPInterface *nlpSolver,
     101      const BonminCbcParam &par)
     102  {
     103
     104    //Now set-up b&b
     105    OsiSolverInterface * si;
     106
     107
     108    nlpSolver->messageHandler()->setLogLevel(par.nlpLogLevel);
     109
     110    if (par.algo > 0) //OA based
     111    {
     112      si = new OsiClpSolverInterface;
     113      nlpSolver->extractLinearRelaxation(*si);
     114      // say bound dubious, does cuts at solution
     115      OsiBabSolver * extraStuff = new OsiBabSolver(3);
     116      si->setAuxiliaryInfo(extraStuff);
     117      delete extraStuff;
     118    }
     119    else {
     120      si = nlpSolver;
     121      nlpSolver->ignoreFailures();
     122      OsiBabSolver * extraStuff = new OsiBabSolver(2);
     123      si->setAuxiliaryInfo(extraStuff);
     124      delete extraStuff;
     125    }
     126    CbcModel model(*si);
     127
     128
     129
     130    if (par.algo==0)//Switch off some feasibility checks and switch on specific nodes info
     131    {
     132      int specOpt = model.specialOptions();
     133      specOpt = 16;
     134      model.setSpecialOptions(specOpt);
     135      CbcNlpStrategy strat(par.maxFailures, par.maxInfeasible, par.failureBehavior);
     136      model.setStrategy(strat);
     137    }
     138
     139    //Setup likely milp cut generator
     140    CglGomory miGGen;
     141
     142    CglProbing probGen;
     143    probGen.setUsingObjective(true);
     144    probGen.setMaxPass(3);
     145    probGen.setMaxProbe(100);
     146    probGen.setMaxLook(50);
     147
     148    CglKnapsackCover knapsackGen;
     149    CglMixedIntegerRounding mixedGen;
     150
     151    //Setup OA generators
     152
     153    //Resolution of nlp relaxations
     154    OACutGenerator oaGen(nlpSolver);
     155    oaGen.setMaxDepth(100000);
     156    oaGen.setLogLevel(par.oaLogLevel);
     157
     158
     159    //Outer approximation iterations
     160    OsiSolverInterface * localSearchSolver=NULL;
     161    if (par.milpSubSolver <= 1)/* use cbc */
     162    {
     163      localSearchSolver = model.solver();
     164      //localSearchSolver->messageHandler()->setLogLevel(0);
     165    }
     166    else if (par.milpSubSolver ==2) /* try to use cplex */
     167    {
     168#ifdef COIN_HAS_CPX
     169      OsiCpxSolverInterface * cpxSolver = new OsiCpxSolverInterface;
     170      localSearchSolver = cpxSolver;
     171      nlpSolver->extractLinearRelaxation(*localSearchSolver);
     172#else
     173
     174      std::cerr<<"You have set an option to use CPLEX as the milp subsolver in oa decomposition."<<std::endl
     175      <<"but apparently CPLEX is not configured to be used in bonmin, see the manual for configuring CPLEX"<<std::endl;
     176      throw -1;
     177#endif
     178
     179    }
     180    CbcStrategy * strategy = NULL;
     181    if (par.milpSubSolver == 1) {
     182      strategy = new CbcOaStrategy(par.milpSubSolver_migFreq,
     183          par.milpSubSolver_probFreq,
     184          par.milpSubSolver_mirFreq,
     185          par.milpSubSolver_coverFreq,
     186          par.milpSubSolver_minReliability,
     187          par.milpSubSolver_numberStrong,
     188          par.milpSubSolver_nodeSelection,
     189          par.intTol,
     190          par.milpLogLevel
     191                                  );
     192    }
     193    OACutGenerator2 oaDec(nlpSolver, localSearchSolver, strategy, par.cutoffDecr, par.intTol, 0,1);
     194    if (par.algo>0) {
     195      oaDec.setLocalSearchNodeLimit(1000000);
     196      oaDec.setMaxLocalSearch(100000);
     197      oaDec.setMaxLocalSearchPerNode(10000);
     198      oaDec. setMaxLocalSearchTime(min(par.maxTime,par.oaDecMaxTime));
     199      oaDec.setLogLevel(par.oaLogLevel);
     200      oaDec.setLogFrequency(par.oaLogFrequency);
     201      oaDec.setSubMilpLogLevel(par.milpLogLevel);
     202    }
     203    //Setup solver for checking validity of integral solutions
     204    OACutGenerator2 feasCheck(nlpSolver, model.solver(),
     205        NULL,
     206        par.cutoffDecr, par.intTol,
     207        0, 0);
     208    if (par.algo>0) {
     209      feasCheck.setLocalSearchNodeLimit(0);
     210      feasCheck.setMaxLocalSearch(0);
     211      feasCheck.setMaxLocalSearchPerNode(100000);
     212    }
     213    DummyHeuristic oaHeu(model, nlpSolver);
     214
     215    if (par.algo>0) {
     216      int numGen = 0;
     217      if (par.nlpSolveFrequency != 0) {
     218        model.addCutGenerator(&oaGen,par.nlpSolveFrequency,"Outer Approximation Supporting Hyperplanes for NLP optimum");
     219        numGen++;
     220      }
     221      if (par.migFreq != 0) {
     222        model.addCutGenerator(&miGGen,par.migFreq,"GMI");
     223        numGen++;
     224      }
     225      if (par.probFreq != 0) {
     226        model.addCutGenerator(&probGen,par.probFreq,"Probing");
     227        numGen++;
     228      }
     229      if (par.coverFreq != 0) {
     230        model.addCutGenerator(&knapsackGen,par.coverFreq,"covers");
     231        numGen++;
     232      }
     233      if (par.mirFreq != 0) {
     234        model.addCutGenerator(&mixedGen,par.mirFreq,"MIR");
     235        numGen++;
     236      }
     237      if (par.oaDecMaxTime>0.) {
     238        model.addCutGenerator(&oaDec,1,"Outer Approximation local enumerator");
     239        OACutGenerator2 * oaDecCopy = dynamic_cast<OACutGenerator2 *>
     240            (model.cutGenerators()[numGen]->generator());
     241        assert(oaDecCopy);
     242        currentOA = oaDecCopy;
     243        numGen++;
     244      }
     245      model.addCutGenerator(&feasCheck,1,"Outer Approximation feasibility checker",false,true);
     246      numGen++;
     247
     248      model.addHeuristic(&oaHeu);
     249    }
     250
     251    //Set true branch-and-bound parameters
     252    model.messageHandler()->setLogLevel(par.bbLogLevel);
     253    if (par.algo > 0)
     254      model.solver()->messageHandler()->setLogLevel(par.lpLogLevel);
     255
     256
     257    //   model.setMaxFailure(par.maxFailures);
     258    //   model.setMaxInfeasible(par.maxInfeasible);
     259
     260    //Pass over user set branching priorities to Cbc
     261    {
     262      //set priorities, prefered directions...
     263      const int * priorities = nlpSolver->getPriorities();
     264      const double * upPsCosts = nlpSolver->getUpPsCosts();
     265      const double * downPsCosts = nlpSolver->getDownPsCosts();
     266      const int * directions = nlpSolver->getBranchingDirections();
     267      bool hasPseudo = (upPsCosts!=NULL);
     268      model.findIntegers(true,hasPseudo);
     269      CbcObject ** simpleIntegerObjects = model.objects();
     270      int numberObjects = model.numberObjects();
     271      for (int i = 0 ; i < numberObjects ; i++)
     272      {
     273        int iCol = simpleIntegerObjects[i]->columnNumber();
     274        if (priorities)
     275          simpleIntegerObjects[i]->setPriority(priorities[iCol]);
     276        if (directions)
     277          simpleIntegerObjects[i]->setPreferredWay(directions[iCol]);
     278        if (upPsCosts) {
     279          CbcSimpleIntegerPseudoCost * pscObject =
     280            dynamic_cast<CbcSimpleIntegerPseudoCost*> (simpleIntegerObjects[i]);
     281          pscObject->setUpPseudoCost(upPsCosts[iCol]);
     282          pscObject->setDownPseudoCost(downPsCosts[iCol]);
     283        }
     284      }
     285
     286    }
     287
     288    // Now pass user set Sos constraints (code inspired from CoinSolve.cpp)
     289    const TMINLP::SosInfo * sos = nlpSolver->model()->sosConstraints();
     290    if (!par.disableSos && sos && sos->num > 0) //we have some sos constraints
     291    {
     292      const int & numSos = sos->num;
     293      CbcObject ** objects = new CbcObject*[numSos];
     294      const int * starts = sos->starts;
     295      const int * indices = sos->indices;
     296      const char * types = sos->types;
     297      const double * weights = sos->weights;
     298      //verify if model has user set priorities
     299      bool hasPriorities = false;
     300      const int * varPriorities = nlpSolver->getPriorities();
     301      int numberObjects = model.numberObjects();
     302      if (varPriorities)
     303      {
     304        for (int i = 0 ; i < numberObjects ; i++) {
     305          if (varPriorities[i]) {
     306            hasPriorities = true;
     307            break;
     308          }
     309        }
     310      }
     311      const int * sosPriorities = sos->priorities;
     312      if (sosPriorities)
     313      {
     314        for (int i = 0 ; i < numSos ; i++) {
     315          if (sosPriorities[i]) {
     316            hasPriorities = true;
     317            break;
     318          }
     319        }
     320      }
     321      for (int i = 0 ; i < numSos ; i++)
     322      {
     323        int start = starts[i];
     324        int length = starts[i + 1] - start;
     325        objects[i] = new CbcSOS(&model, length, &indices[start],
     326            &weights[start], i, types[i]);
     327
     328        objects[i]->setPriority(10);
     329        if (hasPriorities && sosPriorities && sosPriorities[i]) {
     330          objects[i]->setPriority(sosPriorities[i]);
     331        }
     332      }
     333      model.addObjects(numSos, objects);
     334      for (int i = 0 ; i < numSos ; i++)
     335        delete objects[i];
     336      delete [] objects;
     337    }
     338
     339    replaceIntegers(model.objects(), model.numberObjects());
     340
     341    model.setPrintFrequency(par.logInterval);
     342
     343    model.setDblParam(CbcModel::CbcCutoffIncrement, par.cutoffDecr);
     344
     345    model.setCutoff(par.cutoff);
     346    //  model.setBestObjectiveValue(par.cutoff);
     347
     348    model.setDblParam(CbcModel::CbcAllowableGap, par.allowableGap);
     349    model.setDblParam(CbcModel::CbcAllowableFractionGap, par.allowableFractionGap);
     350
     351    // Definition of node selection strategy
     352    CbcCompareObjective compare0;
     353    CbcCompareDepth compare1;
     354    CbcCompareUser compare2;
     355    if (par.nodeSelection==0) {
     356      model.setNodeComparison(compare0);
     357    }
     358    else if (par.nodeSelection==1) {
     359      model.setNodeComparison(compare1);
     360    }
     361    else if (par.nodeSelection==2) {
     362      compare2.setWeight(0.0);
     363      model.setNodeComparison(compare2);
     364    }
     365    else if (par.nodeSelection==3) {
     366      model.setNodeComparison(compare2);
     367    }
     368
     369    model.setNumberStrong(par.numberStrong);
     370
     371    model.setNumberBeforeTrust(par.minReliability);
     372
     373    model.setNumberPenalties(8);
     374
     375    model.setDblParam(CbcModel::CbcMaximumSeconds, par.maxTime);
     376
     377    model.setMaximumNodes(par.maxNodes);
     378
     379    model.setIntegerTolerance(par.intTol);
     380
     381
     382    // Redundant definition of default branching (as Default == User)
     383    CbcBranchUserDecision branch;
     384    model.setBranchingMethod(&branch);
     385
     386    //Get the time and start.
     387    model.initialSolve();
     388
     389    continuousRelaxation_ =model.solver()->getObjValue();
     390    if (par.algo == 0)//Set warm start point for Ipopt
     391    {
     392      const double * colsol = model.solver()->getColSolution();
     393      const double * duals = model.solver()->getRowPrice();
     394      model.solver()->setColSolution(colsol);
     395      model.solver()->setRowPrice(duals);
     396    }
     397
     398    CoinSighandler_t saveSignal=SIG_DFL;
     399    // register signal handler
     400    saveSignal = signal(SIGINT,signal_handler);
     401
     402
     403    currentBranchModel = &model;
     404
     405    model.branchAndBound();
     406    numNodes_ = model.getNodeCount();
     407    bestObj_ = model.getObjValue();
     408    bestBound_ = model.getBestPossibleObjValue();
     409    mipIterationCount_ = model.getIterationCount();
     410
     411    bool hasFailed = false;
     412    if (par.algo==0)//Did we continue branching on a failure
     413    {
     414      CbcNlpStrategy * nlpStrategy = dynamic_cast<CbcNlpStrategy *>(model.strategy());
     415      if (nlpStrategy)
     416        hasFailed = nlpStrategy->hasFailed();
     417      else
     418        throw -1;
     419    }
     420    else
     421      hasFailed = nlpSolver->hasContinuedOnAFailure();
     422
     423
     424    if (hasFailed) {
     425      std::cout<<"************************************************************"<<std::endl
     426      <<"WARNING : Optimization failed on an NLP during optimization"
     427      <<"\n (no optimal value found within tolerances)."<<std::endl
     428      <<"Optimization was not stopped because option \n"
     429      <<"\"nlp_failure_behavior\" has been set to fathom but"
     430      <<" beware that reported solution may not be optimal"<<std::endl
     431      <<"************************************************************"<<std::endl;
     432    }
     433
     434    if (model.bestSolution()) {
     435      if (bestSolution_)
     436        delete [] bestSolution_;
     437      bestSolution_ = new double[nlpSolver->getNumCols()];
     438      CoinCopyN(model.bestSolution(), nlpSolver->getNumCols(), bestSolution_);
     439    }
     440    if (!model.status()) {
     441      if (bestSolution_)
     442        mipStatus_ = FeasibleOptimal;
     443      else
     444        mipStatus_ = ProvenInfeasible;
     445    }
     446    else {
     447      if (bestSolution_)
     448        mipStatus_ = Feasible;
     449      else
     450        mipStatus_ = NoSolutionKnown;
     451    }
     452
     453
     454    if (par.algo > 0)
     455      delete si;
     456#ifdef COIN_HAS_CPX
     457
     458    if (par.milpSubSolver ==1)
     459      delete localSearchSolver;
     460#endif
     461    std::cout<<"Finished"<<std::endl;
     462    if (strategy)
     463      delete strategy;
     464
     465  }
     466
     467
     468  /** return the best known lower bound on the objective value*/
     469  double
     470  Bab::bestBound()
     471  {
     472    if (mipStatus_ == FeasibleOptimal) return bestObj_;
     473    else if (mipStatus_ == ProvenInfeasible) return 1e200;
     474    else return bestBound_;
     475  }
    96476}
    97 /** Perform a branch-and-bound on given IpoptInterface using passed parameters.*/
    98 void
    99 Bab::branchAndBound(OsiTMINLPInterface *nlpSolver,
    100     const BonminCbcParam &par)
    101 {
    102 
    103   //Now set-up b&b
    104   OsiSolverInterface * si;
    105 
    106 
    107   nlpSolver->messageHandler()->setLogLevel(par.nlpLogLevel);
    108 
    109   if (par.algo > 0) //OA based
    110   {
    111     si = new OsiClpSolverInterface;
    112     nlpSolver->extractLinearRelaxation(*si);
    113     // say bound dubious, does cuts at solution
    114     OsiBabSolver * extraStuff = new OsiBabSolver(3);
    115     si->setAuxiliaryInfo(extraStuff);
    116     delete extraStuff;
    117   }
    118   else {
    119     si = nlpSolver;
    120     nlpSolver->ignoreFailures();
    121     OsiBabSolver * extraStuff = new OsiBabSolver(2);
    122     si->setAuxiliaryInfo(extraStuff);
    123     delete extraStuff;
    124   }
    125   CbcModel model(*si);
    126 
    127 
    128 
    129   if(par.algo==0)//Switch off some feasibility checks and switch on specific nodes info
    130   {
    131     int specOpt = model.specialOptions();
    132     specOpt = 16;
    133     model.setSpecialOptions(specOpt);
    134     CbcNlpStrategy strat(par.maxFailures, par.maxInfeasible, par.failureBehavior);
    135     model.setStrategy(strat);
    136   }
    137 
    138   //Setup likely milp cut generator
    139   CglGomory miGGen;
    140 
    141   CglProbing probGen;
    142   probGen.setUsingObjective(true);
    143   probGen.setMaxPass(3);
    144   probGen.setMaxProbe(100);
    145   probGen.setMaxLook(50);
    146 
    147   CglKnapsackCover knapsackGen;
    148   CglMixedIntegerRounding mixedGen;
    149 
    150   //Setup OA generators
    151 
    152   //Resolution of nlp relaxations
    153   OACutGenerator oaGen(nlpSolver);
    154   oaGen.setMaxDepth(100000);
    155   oaGen.setLogLevel(par.oaLogLevel);
    156 
    157 
    158   //Outer approximation iterations
    159   OsiSolverInterface * localSearchSolver=NULL;
    160   if(par.milpSubSolver <= 1)/* use cbc */
    161   {
    162     localSearchSolver = model.solver();
    163     //localSearchSolver->messageHandler()->setLogLevel(0);
    164   }
    165   else if (par.milpSubSolver ==2) /* try to use cplex */
    166   {
    167 #ifdef COIN_HAS_CPX
    168     OsiCpxSolverInterface * cpxSolver = new OsiCpxSolverInterface;
    169     localSearchSolver = cpxSolver;
    170     nlpSolver->extractLinearRelaxation(*localSearchSolver);
    171 #else
    172 
    173     std::cerr<<"You have set an option to use CPLEX as the milp subsolver in oa decomposition."<<std::endl
    174     <<"but apparently CPLEX is not configured to be used in bonmin, see the manual for configuring CPLEX"<<std::endl;
    175     throw -1;
    176 #endif
    177 
    178   }
    179   CbcStrategy * strategy = NULL;
    180   if(par.milpSubSolver == 1) {
    181     strategy = new CbcOaStrategy(par.milpSubSolver_migFreq,
    182         par.milpSubSolver_probFreq,
    183         par.milpSubSolver_mirFreq,
    184         par.milpSubSolver_coverFreq,
    185         par.milpSubSolver_minReliability,
    186         par.milpSubSolver_numberStrong,
    187         par.milpSubSolver_nodeSelection,
    188         par.intTol,
    189         par.milpLogLevel
    190                                 );
    191   }
    192   OACutGenerator2 oaDec(nlpSolver, localSearchSolver, strategy, par.cutoffDecr, par.intTol, 0,1);
    193   if(par.algo>0) {
    194     oaDec.setLocalSearchNodeLimit(1000000);
    195     oaDec.setMaxLocalSearch(100000);
    196     oaDec.setMaxLocalSearchPerNode(10000);
    197     oaDec. setMaxLocalSearchTime(min(par.maxTime,par.oaDecMaxTime));
    198     oaDec.setLogLevel(par.oaLogLevel);
    199     oaDec.setLogFrequency(par.oaLogFrequency);
    200     oaDec.setSubMilpLogLevel(par.milpLogLevel);
    201   }
    202   //Setup solver for checking validity of integral solutions
    203   OACutGenerator2 feasCheck(nlpSolver, model.solver(),
    204       NULL,
    205       par.cutoffDecr, par.intTol,
    206       0, 0);
    207   if(par.algo>0) {
    208     feasCheck.setLocalSearchNodeLimit(0);
    209     feasCheck.setMaxLocalSearch(0);
    210     feasCheck.setMaxLocalSearchPerNode(100000);
    211   }
    212   DummyHeuristic oaHeu(model, nlpSolver);
    213 
    214   if(par.algo>0) {
    215     int numGen = 0;
    216     if(par.nlpSolveFrequency != 0)
    217       {
    218         model.addCutGenerator(&oaGen,par.nlpSolveFrequency,"Outer Approximation Supporting Hyperplanes for NLP optimum");
    219         numGen++;
    220       }
    221     if(par.migFreq != 0)
    222       {
    223         model.addCutGenerator(&miGGen,par.migFreq,"GMI");
    224         numGen++;
    225       }
    226     if(par.probFreq != 0)
    227       {
    228         model.addCutGenerator(&probGen,par.probFreq,"Probing");
    229         numGen++;
    230       }
    231     if(par.coverFreq != 0)
    232       {
    233         model.addCutGenerator(&knapsackGen,par.coverFreq,"covers");
    234         numGen++;
    235       }
    236     if(par.mirFreq != 0)
    237       {
    238         model.addCutGenerator(&mixedGen,par.mirFreq,"MIR");
    239         numGen++;
    240       }
    241     if(par.oaDecMaxTime>0.)
    242       {
    243         model.addCutGenerator(&oaDec,1,"Outer Approximation local enumerator");     
    244         OACutGenerator2 * oaDecCopy = dynamic_cast<OACutGenerator2 *>
    245           (model.cutGenerators()[numGen]->generator());
    246         assert(oaDecCopy);
    247         currentOA = oaDecCopy;
    248           numGen++;
    249       }
    250     model.addCutGenerator(&feasCheck,1,"Outer Approximation feasibility checker",false,true);
    251     numGen++;
    252 
    253     model.addHeuristic(&oaHeu);
    254   }
    255 
    256   //Set true branch-and-bound parameters
    257   model.messageHandler()->setLogLevel(par.bbLogLevel);
    258   if(par.algo > 0)
    259     model.solver()->messageHandler()->setLogLevel(par.lpLogLevel);
    260 
    261 
    262   //   model.setMaxFailure(par.maxFailures);
    263   //   model.setMaxInfeasible(par.maxInfeasible);
    264 
    265   //Pass over user set branching priorities to Cbc
    266   {
    267     //set priorities, prefered directions...
    268     const int * priorities = nlpSolver->getPriorities();
    269     const double * upPsCosts = nlpSolver->getUpPsCosts();
    270     const double * downPsCosts = nlpSolver->getDownPsCosts();
    271     const int * directions = nlpSolver->getBranchingDirections();
    272     bool hasPseudo = (upPsCosts!=NULL);
    273     model.findIntegers(true,hasPseudo);
    274     CbcObject ** simpleIntegerObjects = model.objects();
    275     int numberObjects = model.numberObjects();
    276     for(int i = 0 ; i < numberObjects ; i++)
    277     {
    278       int iCol = simpleIntegerObjects[i]->columnNumber();
    279       if(priorities)
    280         simpleIntegerObjects[i]->setPriority(priorities[iCol]);
    281       if(directions)
    282         simpleIntegerObjects[i]->setPreferredWay(directions[iCol]);
    283       if(upPsCosts) {
    284         CbcSimpleIntegerPseudoCost * pscObject =
    285           dynamic_cast<CbcSimpleIntegerPseudoCost*> (simpleIntegerObjects[i]);
    286         pscObject->setUpPseudoCost(upPsCosts[iCol]);
    287         pscObject->setDownPseudoCost(downPsCosts[iCol]);
    288       }
    289     }
    290 
    291   }
    292 
    293   // Now pass user set Sos constraints (code inspired from CoinSolve.cpp)
    294   const TMINLP::SosInfo * sos = nlpSolver->model()->sosConstraints();
    295   if(!par.disableSos && sos && sos->num > 0) //we have some sos constraints
    296   {
    297     const int & numSos = sos->num;
    298     CbcObject ** objects = new CbcObject*[numSos];
    299     const int * starts = sos->starts;
    300     const int * indices = sos->indices;
    301     const char * types = sos->types;
    302     const double * weights = sos->weights;
    303     //verify if model has user set priorities
    304     bool hasPriorities = false;
    305     const int * varPriorities = nlpSolver->getPriorities();
    306     int numberObjects = model.numberObjects();
    307     if(varPriorities)
    308     {
    309       for(int i = 0 ; i < numberObjects ; i++) {
    310         if(varPriorities[i]) {
    311           hasPriorities = true;
    312           break;
    313         }
    314       }
    315     }
    316     const int * sosPriorities = sos->priorities;
    317     if(sosPriorities)
    318     {
    319       for(int i = 0 ; i < numSos ; i++) {
    320         if(sosPriorities[i]) {
    321           hasPriorities = true;
    322           break;
    323         }
    324       }
    325     }
    326     for(int i = 0 ; i < numSos ; i++)
    327     {
    328       int start = starts[i];
    329       int length = starts[i + 1] - start;
    330       objects[i] = new CbcSOS(&model, length, &indices[start],
    331           &weights[start], i, types[i]);
    332 
    333       objects[i]->setPriority(10);
    334       if(hasPriorities && sosPriorities && sosPriorities[i]) {
    335         objects[i]->setPriority(sosPriorities[i]);
    336       }
    337     }
    338     model.addObjects(numSos, objects);
    339     for(int i = 0 ; i < numSos ; i++)
    340       delete objects[i];
    341     delete [] objects;
    342   }
    343 
    344   replaceIntegers(model.objects(), model.numberObjects());
    345 
    346   model.setPrintFrequency(par.logInterval);
    347 
    348   model.setDblParam(CbcModel::CbcCutoffIncrement, par.cutoffDecr);
    349 
    350   model.setCutoff(par.cutoff);
    351   //  model.setBestObjectiveValue(par.cutoff);
    352 
    353   model.setDblParam(CbcModel::CbcAllowableGap, par.allowableGap);
    354   model.setDblParam(CbcModel::CbcAllowableFractionGap, par.allowableFractionGap);
    355 
    356   // Definition of node selection strategy
    357   CbcCompareObjective compare0;
    358   CbcCompareDepth compare1;
    359   CbcCompareUser compare2;
    360   if(par.nodeSelection==0) {
    361     model.setNodeComparison(compare0);
    362   }
    363   else if(par.nodeSelection==1) {
    364     model.setNodeComparison(compare1);
    365   }
    366   else if(par.nodeSelection==2) {
    367     compare2.setWeight(0.0);
    368     model.setNodeComparison(compare2);
    369   }
    370   else if(par.nodeSelection==3) {
    371     model.setNodeComparison(compare2);
    372   }
    373 
    374   model.setNumberStrong(par.numberStrong);
    375 
    376   model.setNumberBeforeTrust(par.minReliability);
    377 
    378   model.setNumberPenalties(8);
    379 
    380   model.setDblParam(CbcModel::CbcMaximumSeconds, par.maxTime);
    381 
    382   model.setMaximumNodes(par.maxNodes);
    383 
    384   model.setIntegerTolerance(par.intTol);
    385 
    386 
    387   // Redundant definition of default branching (as Default == User)
    388   CbcBranchUserDecision branch;
    389   model.setBranchingMethod(&branch);
    390 
    391   //Get the time and start.
    392   model.initialSolve();
    393 
    394   continuousRelaxation_ =model.solver()->getObjValue();
    395   if(par.algo == 0)//Set warm start point for Ipopt
    396   {
    397     const double * colsol = model.solver()->getColSolution();
    398     const double * duals = model.solver()->getRowPrice();
    399     model.solver()->setColSolution(colsol);
    400     model.solver()->setRowPrice(duals);
    401   }
    402  
    403   CoinSighandler_t saveSignal=SIG_DFL;
    404   // register signal handler
    405   saveSignal = signal(SIGINT,signal_handler);
    406 
    407 
    408   currentBranchModel = &model;
    409  
    410   model.branchAndBound();
    411   numNodes_ = model.getNodeCount();
    412   bestObj_ = model.getObjValue();
    413   bestBound_ = model.getBestPossibleObjValue();
    414   mipIterationCount_ = model.getIterationCount();
    415 
    416   bool hasFailed = false;
    417   if(par.algo==0)//Did we continue branching on a failure
    418   {
    419     CbcNlpStrategy * nlpStrategy = dynamic_cast<CbcNlpStrategy *>(model.strategy());
    420     if(nlpStrategy)
    421       hasFailed = nlpStrategy->hasFailed();
    422     else
    423       throw -1;
    424   }
    425   else
    426     hasFailed = nlpSolver->hasContinuedOnAFailure();
    427 
    428 
    429   if(hasFailed) {
    430     std::cout<<"************************************************************"<<std::endl
    431     <<"WARNING : Optimization failed on an NLP during optimization"
    432     <<"\n (no optimal value found within tolerances)."<<std::endl
    433     <<"Optimization was not stopped because option \n"
    434     <<"\"nlp_failure_behavior\" has been set to fathom but"
    435     <<" beware that reported solution may not be optimal"<<std::endl
    436     <<"************************************************************"<<std::endl;
    437   }
    438 
    439   if(model.bestSolution()) {
    440     if(bestSolution_)
    441       delete [] bestSolution_;
    442     bestSolution_ = new double[nlpSolver->getNumCols()];
    443     CoinCopyN(model.bestSolution(), nlpSolver->getNumCols(), bestSolution_);
    444   }
    445   if(!model.status()) {
    446     if(bestSolution_)
    447       mipStatus_ = FeasibleOptimal;
    448     else
    449       mipStatus_ = ProvenInfeasible;
    450   }
    451   else {
    452     if(bestSolution_)
    453       mipStatus_ = Feasible;
    454     else
    455       mipStatus_ = NoSolutionKnown;
    456   }
    457 
    458 
    459   if(par.algo > 0)
    460     delete si;
    461 #ifdef COIN_HAS_CPX
    462 
    463   if (par.milpSubSolver ==1)
    464     delete localSearchSolver;
    465 #endif
    466   std::cout<<"Finished"<<std::endl;
    467   if(strategy)
    468     delete strategy;
    469 
    470 }
    471 
    472 
    473 /** return the best known lower bound on the objective value*/
    474 double
    475 Bab::bestBound()
    476 {
    477   if(mipStatus_ == FeasibleOptimal) return bestObj_;
    478   else if(mipStatus_ == ProvenInfeasible) return 1e200;
    479   else return bestBound_;
    480 }
    481 }
  • branches/devel/Bonmin/src/CbcBonmin/BonCbc.hpp

    r57 r62  
    77class CbcObject;
    88
    9 namespace Bonmin{
    10 class OsiTMINLPInterface;
    11 /** Class which performs optimization of an MINLP stored in an IpoptInterface. */
    12 class Bab
     9namespace Bonmin
    1310{
    14 public:
    15   /** Integer optimization return codes.*/
    16   enum MipStatuses {FeasibleOptimal /** Optimum solution has been found and its optimality proved.*/,
    17       ProvenInfeasible /** Problem has been proven to be infeasible.*/,
    18       Feasible /** An integer solution to the problem has been found.*/,
    19       NoSolutionKnown/** No feasible solution to the problem is known*/};
    20   /** Constructor.*/
    21   Bab();
    22   /** destructor.*/
    23   virtual ~Bab();
    24   /** Perform a branch-and-bound on given IpoptInterface using passed parameters.*/
    25   void branchAndBound(OsiTMINLPInterface * nlp,
    26       const BonminCbcParam&par);
     11  class OsiTMINLPInterface;
     12  /** Class which performs optimization of an MINLP stored in an IpoptInterface. */
     13  class Bab
     14  {
     15  public:
     16    /** Integer optimization return codes.*/
     17    enum MipStatuses {FeasibleOptimal /** Optimum solution has been found and its optimality proved.*/,
     18        ProvenInfeasible /** Problem has been proven to be infeasible.*/,
     19        Feasible /** An integer solution to the problem has been found.*/,
     20        NoSolutionKnown/** No feasible solution to the problem is known*/};
     21    /** Constructor.*/
     22    Bab();
     23    /** destructor.*/
     24    virtual ~Bab();
     25    /** Perform a branch-and-bound on given IpoptInterface using passed parameters.*/
     26    void branchAndBound(OsiTMINLPInterface * nlp,
     27        const BonminCbcParam&par);
    2728
    28   /**operator() performs the branchAndBound*/
    29   void operator()(OsiTMINLPInterface * nlp, const BonminCbcParam& par)
    30   {
    31     branchAndBound(nlp,par);
    32   }
     29    /**operator() performs the branchAndBound*/
     30    void operator()(OsiTMINLPInterface * nlp, const BonminCbcParam& par)
     31    {
     32      branchAndBound(nlp,par);
     33    }
    3334
    34   /** get the best solution known to the problem (is optimal if MipStatus is FeasibleOptimal).
    35       if no solution is known returns NULL.*/
    36   const double * bestSolution() const
    37   {
    38     return bestSolution_;
    39   }
    40   /** return objective value of the bestSolution */
    41   double bestObj() const
    42   {
    43     return bestObj_;
    44   }
    45   /** return Mip Status */
    46   MipStatuses mipStatus() const
    47   {
    48     return mipStatus_;
    49   }
    50   /** return the best known lower bound on the objective value*/
    51   double bestBound();
    52   /** return the total number of nodes explored.*/
    53   int numNodes() const
    54   {
    55     return numNodes_;
    56   }
    57   /** return the total number of iterations in the last mip solved.*/
    58   int iterationCount()
    59   {
    60     return mipIterationCount_;
    61   }
    62   /** returns the value of the continuous relaxation. */
    63   double continuousRelaxation()
    64   {
    65     return continuousRelaxation_;
    66   }
     35    /** get the best solution known to the problem (is optimal if MipStatus is FeasibleOptimal).
     36        if no solution is known returns NULL.*/
     37    const double * bestSolution() const
     38    {
     39      return bestSolution_;
     40    }
     41    /** return objective value of the bestSolution */
     42    double bestObj() const
     43    {
     44      return bestObj_;
     45    }
     46    /** return Mip Status */
     47    MipStatuses mipStatus() const
     48    {
     49      return mipStatus_;
     50    }
     51    /** return the best known lower bound on the objective value*/
     52    double bestBound();
     53    /** return the total number of nodes explored.*/
     54    int numNodes() const
     55    {
     56      return numNodes_;
     57    }
     58    /** return the total number of iterations in the last mip solved.*/
     59    int iterationCount()
     60    {
     61      return mipIterationCount_;
     62    }
     63    /** returns the value of the continuous relaxation. */
     64    double continuousRelaxation()
     65    {
     66      return continuousRelaxation_;
     67    }
    6768
    68   /** virtual callback function to eventually modify objects for integer variable
    69       (replace with user set). This is called after CbcModel::findIntegers */
    70   virtual void replaceIntegers(CbcObject ** objects, int numberObjects)
    71   {};
    72 private:
    73   /** Stores the solution of MIP. */
    74   double * bestSolution_;
    75   /** Status of the mixed integer program. */
    76   MipStatuses mipStatus_;
    77   /** objValue of MIP */
    78   double bestObj_;
    79   /** best known (lower) bound.*/
    80   double bestBound_;
    81   /** Continuous relaxation of the problem */
    82   double continuousRelaxation_;
    83   /** Number of nodes enumerated.*/
    84   int numNodes_;
    85   /** get total number of iterations in last mip solved.*/
    86   int mipIterationCount_;
    87 };
     69    /** virtual callback function to eventually modify objects for integer variable
     70        (replace with user set). This is called after CbcModel::findIntegers */
     71    virtual void replaceIntegers(CbcObject ** objects, int numberObjects)
     72    {};
     73  private:
     74    /** Stores the solution of MIP. */
     75    double * bestSolution_;
     76    /** Status of the mixed integer program. */
     77    MipStatuses mipStatus_;
     78    /** objValue of MIP */
     79    double bestObj_;
     80    /** best known (lower) bound.*/
     81    double bestBound_;
     82    /** Continuous relaxation of the problem */
     83    double continuousRelaxation_;
     84    /** Number of nodes enumerated.*/
     85    int numNodes_;
     86    /** get total number of iterations in last mip solved.*/
     87    int mipIterationCount_;
     88  };
    8889}
    8990#endif
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcLpStrategy.cpp

    r57 r62  
    3030
    3131
    32 namespace Bonmin{
    33 CbcOaStrategy::CbcOaStrategy(int migFreq,
    34     int probFreq,
    35     int mirFreq,
    36     int coverFreq,
    37     int minReliability,
    38     int numberStrong,
    39     int nodeSelection,
    40     double intTol,
    41     int logLevel
    42                             ):
    43     CbcStrategy(),
    44     migFreq_(migFreq),
    45     probFreq_(probFreq),
    46     mirFreq_(mirFreq),
    47     coverFreq_(coverFreq),
    48     minReliability_(minReliability),
    49     numberStrong_(numberStrong),
    50     nodeSelection_(nodeSelection),
    51     intTol_(intTol),
    52     logLevel_(logLevel)
     32namespace Bonmin
    5333{
    54   setPreProcessState(0);
    55 }
     34  CbcOaStrategy::CbcOaStrategy(int migFreq,
     35      int probFreq,
     36      int mirFreq,
     37      int coverFreq,
     38      int minReliability,
     39      int numberStrong,
     40      int nodeSelection,
     41      double intTol,
     42      int logLevel
     43                              ):
     44      CbcStrategy(),
     45      migFreq_(migFreq),
     46      probFreq_(probFreq),
     47      mirFreq_(mirFreq),
     48      coverFreq_(coverFreq),
     49      minReliability_(minReliability),
     50      numberStrong_(numberStrong),
     51      nodeSelection_(nodeSelection),
     52      intTol_(intTol),
     53      logLevel_(logLevel)
     54  {
     55    setPreProcessState(0);
     56  }
    5657
    57 CbcStrategy *
    58 CbcOaStrategy::clone () const
    59 {
    60   return new CbcOaStrategy(migFreq_, probFreq_,  mirFreq_, coverFreq_, minReliability_,
    61       numberStrong_, nodeSelection_, intTol_,
    62       logLevel_);
    63 }
     58  CbcStrategy *
     59  CbcOaStrategy::clone () const
     60  {
     61    return new CbcOaStrategy(migFreq_, probFreq_,  mirFreq_, coverFreq_, minReliability_,
     62        numberStrong_, nodeSelection_, intTol_,
     63        logLevel_);
     64  }
    6465
    65 void
    66 CbcOaStrategy::setupCutGenerators(CbcModel & model)
    67 {
     66  void
     67  CbcOaStrategy::setupCutGenerators(CbcModel & model)
     68  {
    6869
    69   CglGomory miGGen;
     70    CglGomory miGGen;
    7071
    71   CglProbing probGen;
    72   probGen.setUsingObjective(true);
    73   probGen.setMaxPass(3);
    74   probGen.setMaxProbe(100);
    75   probGen.setMaxLook(50);
     72    CglProbing probGen;
     73    probGen.setUsingObjective(true);
     74    probGen.setMaxPass(3);
     75    probGen.setMaxProbe(100);
     76    probGen.setMaxLook(50);
    7677
    77   CglKnapsackCover knapsackGen;
    78   CglMixedIntegerRounding mixedGen;
     78    CglKnapsackCover knapsackGen;
     79    CglMixedIntegerRounding mixedGen;
    7980
    80   if(migFreq_ != 0)
    81     model.addCutGenerator(&miGGen,migFreq_,"GMI");
    82   if(probFreq_ != 0)
    83     model.addCutGenerator(&probGen,probFreq_,"Probing");
    84   if(coverFreq_ != 0)
    85     model.addCutGenerator(&knapsackGen,coverFreq_,"covers");
    86   if(mirFreq_ != 0)
    87     model.addCutGenerator(&mixedGen,mirFreq_,"MIR");
     81    if (migFreq_ != 0)
     82      model.addCutGenerator(&miGGen,migFreq_,"GMI");
     83    if (probFreq_ != 0)
     84      model.addCutGenerator(&probGen,probFreq_,"Probing");
     85    if (coverFreq_ != 0)
     86      model.addCutGenerator(&knapsackGen,coverFreq_,"covers");
     87    if (mirFreq_ != 0)
     88      model.addCutGenerator(&mixedGen,mirFreq_,"MIR");
    8889
    89 }
     90  }
    9091
    9192/// Setup heuristics
    92 void
    93 CbcOaStrategy::setupHeuristics(CbcModel & model)
     93  void
     94  CbcOaStrategy::setupHeuristics(CbcModel & model)
    9495{}
    9596
    9697/// Do printing stuff
    97 void
    98 CbcOaStrategy::setupPrinting(CbcModel & model,int modelLogLevel)
    99 {
    100   //  throw -1;
    101   model.messageHandler()->setLogLevel(logLevel_);
    102   model.solver()->messageHandler()->setLogLevel(0);
    103   model.setPrintFrequency(100);
    104 }
     98  void
     99  CbcOaStrategy::setupPrinting(CbcModel & model,int modelLogLevel)
     100  {
     101    //  throw -1;
     102    model.messageHandler()->setLogLevel(logLevel_);
     103    model.solver()->messageHandler()->setLogLevel(0);
     104    model.setPrintFrequency(100);
     105  }
    105106
    106107// Other stuff e.g. strong branching
    107 void
    108 CbcOaStrategy::setupOther(CbcModel & model)
    109 {
    110   model.setNumberStrong(numberStrong_);
    111   model.setNumberBeforeTrust(minReliability_);
     108  void
     109  CbcOaStrategy::setupOther(CbcModel & model)
     110  {
     111    model.setNumberStrong(numberStrong_);
     112    model.setNumberBeforeTrust(minReliability_);
    112113
    113   model.setIntegerTolerance(intTol_);
     114    model.setIntegerTolerance(intTol_);
    114115
    115   // Definition of node selection strategy
    116   CbcCompareObjective compare0;
    117   CbcCompareDepth compare1;
    118   CbcCompareUser compare2;
    119   if(nodeSelection_==0) {
    120     model.setNodeComparison(compare0);
    121   }
    122   else if(nodeSelection_==1) {
    123     model.setNodeComparison(compare1);
    124   }
    125   else if(nodeSelection_==2) {
    126     compare2.setWeight(0.0);
    127     model.setNodeComparison(compare2);
    128   }
    129   else if(nodeSelection_==3) {
    130     model.setNodeComparison(compare2);
     116    // Definition of node selection strategy
     117    CbcCompareObjective compare0;
     118    CbcCompareDepth compare1;
     119    CbcCompareUser compare2;
     120    if (nodeSelection_==0) {
     121      model.setNodeComparison(compare0);
     122    }
     123    else if (nodeSelection_==1) {
     124      model.setNodeComparison(compare1);
     125    }
     126    else if (nodeSelection_==2) {
     127      compare2.setWeight(0.0);
     128      model.setNodeComparison(compare2);
     129    }
     130    else if (nodeSelection_==3) {
     131      model.setNodeComparison(compare2);
     132    }
     133
    131134  }
    132135
    133136}
    134 
    135 }
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcLpStrategy.hpp

    r57 r62  
    1313
    1414#include "CbcStrategy.hpp"
    15 namespace Bonmin{
    16 /** A class to pass on a CbcStrategy to OA sub-milp solver.
    17  This class allows to setup GMI, MIR, probing and cover cuts frequency.
    18 Number of variables to strong branch on and minimum number of branches on a variable before its
    19 pseudo-cost is to be trusted.*/
    20 class CbcOaStrategy : public CbcStrategy
     15namespace Bonmin
    2116{
    22 public:
    23   /// Default constructor
    24   CbcOaStrategy(
    25     int migFreq = -5,
    26     int probFreq = -5,
    27     int mirFreq = -5,
    28     int coverFreq = -5,
    29     int minReliability = 8,
    30     int numberStrong = 20,
    31     int nodeSelection = 0,
    32     double intTol = 1e-05,
    33     int logLevel = 0);
    34   /// Destructor
    35   virtual ~CbcOaStrategy()
    36   {}
     17  /** A class to pass on a CbcStrategy to OA sub-milp solver.
     18   This class allows to setup GMI, MIR, probing and cover cuts frequency.
     19  Number of variables to strong branch on and minimum number of branches on a variable before its
     20  pseudo-cost is to be trusted.*/
     21  class CbcOaStrategy : public CbcStrategy
     22  {
     23  public:
     24    /// Default constructor
     25    CbcOaStrategy(
     26      int migFreq = -5,
     27      int probFreq = -5,
     28      int mirFreq = -5,
     29      int coverFreq = -5,
     30      int minReliability = 8,
     31      int numberStrong = 20,
     32      int nodeSelection = 0,
     33      double intTol = 1e-05,
     34      int logLevel = 0);
     35    /// Destructor
     36    virtual ~CbcOaStrategy()
     37    {}
    3738
    38   /// Virtual copy constructor
    39   virtual CbcStrategy * clone () const;
     39    /// Virtual copy constructor
     40    virtual CbcStrategy * clone () const;
    4041
    41   /// Setup cut generators
    42   virtual void setupCutGenerators(CbcModel & model);
    43   /// Setup heuristics
    44   virtual void setupHeuristics(CbcModel & model);
    45   /// Do printing stuff
    46   virtual void setupPrinting(CbcModel & model,int modelLogLevel);
    47   /// Other stuff e.g. strong branching and preprocessing
    48   virtual void setupOther(CbcModel & model);
     42    /// Setup cut generators
     43    virtual void setupCutGenerators(CbcModel & model);
     44    /// Setup heuristics
     45    virtual void setupHeuristics(CbcModel & model);
     46    /// Do printing stuff
     47    virtual void setupPrinting(CbcModel & model,int modelLogLevel);
     48    /// Other stuff e.g. strong branching and preprocessing
     49    virtual void setupOther(CbcModel & model);
    4950
    5051
    51 private:
    52   int migFreq_;
    53   int probFreq_;
    54   int mirFreq_;
    55   int coverFreq_;
    56   int minReliability_;
    57   int numberStrong_;
    58   int nodeSelection_;
    59   double intTol_;
    60   int logLevel_;
    61 };
     52  private:
     53    int migFreq_;
     54    int probFreq_;
     55    int mirFreq_;
     56    int coverFreq_;
     57    int minReliability_;
     58    int numberStrong_;
     59    int nodeSelection_;
     60    double intTol_;
     61    int logLevel_;
     62  };
    6263}
    6364#endif
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcNlpStrategy.cpp

    r58 r62  
    2323
    2424#include "BonOsiTMINLPInterface.hpp"
    25 namespace Bonmin{
     25namespace Bonmin
     26{
    2627// Default Constructor
    27 CbcNlpStrategy::CbcNlpStrategy(int maxFailures,
    28     int maxInfeasibles,
    29     int pretendFailIsInfeasible)
    30     :
    31     hasFailed_(false),
    32     maxFailure_(maxFailures),
    33     maxInfeasible_(maxInfeasibles),
    34     pretendFailIsInfeasible_(pretendFailIsInfeasible)
    35 {
    36   setPreProcessState(0);
    37 }
     28  CbcNlpStrategy::CbcNlpStrategy(int maxFailures,
     29      int maxInfeasibles,
     30      int pretendFailIsInfeasible)
     31      :
     32      hasFailed_(false),
     33      maxFailure_(maxFailures),
     34      maxInfeasible_(maxInfeasibles),
     35      pretendFailIsInfeasible_(pretendFailIsInfeasible)
     36  {
     37    setPreProcessState(0);
     38  }
    3839
    3940
    4041// Destructor
    41 CbcNlpStrategy::~CbcNlpStrategy ()
    42 {}
     42  CbcNlpStrategy::~CbcNlpStrategy ()
     43  {}
    4344
    4445// Clone
    45 CbcStrategy *
    46 CbcNlpStrategy::clone() const
    47 {
    48   return new CbcNlpStrategy(*this);
    49 }
     46  CbcStrategy *
     47  CbcNlpStrategy::clone() const
     48  {
     49    return new CbcNlpStrategy(*this);
     50  }
    5051
    5152// Copy constructor
    52 CbcNlpStrategy::CbcNlpStrategy(const CbcNlpStrategy & rhs)
    53     :
    54     hasFailed_(false),
    55     maxFailure_(rhs.maxFailure_),
    56     maxInfeasible_(rhs.maxInfeasible_),
    57     pretendFailIsInfeasible_(rhs.pretendFailIsInfeasible_)
    58 {}
     53  CbcNlpStrategy::CbcNlpStrategy(const CbcNlpStrategy & rhs)
     54      :
     55      hasFailed_(false),
     56      maxFailure_(rhs.maxFailure_),
     57      maxInfeasible_(rhs.maxInfeasible_),
     58      pretendFailIsInfeasible_(rhs.pretendFailIsInfeasible_)
     59  {}
    5960// Return a new Full node information pointer (descendant of CbcFullNodeInfo)
    60 CbcNodeInfo *
    61 CbcNlpStrategy::fullNodeInfo(CbcModel * model,int numberRowsAtContinuous) const
    62 {
    63   return new CbcFullNodeInfo(model,numberRowsAtContinuous);
    64 }
     61  CbcNodeInfo *
     62  CbcNlpStrategy::fullNodeInfo(CbcModel * model,int numberRowsAtContinuous) const
     63  {
     64    return new CbcFullNodeInfo(model,numberRowsAtContinuous);
     65  }
    6566// Return a new Partial node information pointer (descendant of CbcPartialNodeInfo)
    66 CbcNodeInfo *
    67 CbcNlpStrategy::partialNodeInfo(CbcModel * model, CbcNodeInfo * parent, CbcNode * owner,
    68     int numberChangedBounds,const int * variables,
    69     const double * boundChanges,
    70     const CoinWarmStartDiff *basisDiff) const
    71 {
    72   return new BonCbcPartialNodeInfo(model,parent, owner, numberChangedBounds, variables,
    73       boundChanges,basisDiff);
    74 }
    75 /* After a CbcModel::resolve this can return a status
    76    -1 no effect
    77    0 treat as optimal
    78    1 as 0 but do not do any more resolves (i.e. no more cuts)
    79    2 treat as infeasible
    80 */
    81 int
    82 CbcNlpStrategy::status(CbcModel * model, CbcNodeInfo * parent,int whereFrom)
    83 {
    84   OsiSolverInterface * solver = model->solver();//get solver
    85   int feasible = 1;
    86   bool solved = true;
    87   int returnStatus = -1;
    88   BonCbcPartialNodeInfo * bmNodeInfo = dynamic_cast<BonCbcPartialNodeInfo *>(parent);
    89   if(!bmNodeInfo) return -1;
     67  CbcNodeInfo *
     68  CbcNlpStrategy::partialNodeInfo(CbcModel * model, CbcNodeInfo * parent, CbcNode * owner,
     69      int numberChangedBounds,const int * variables,
     70      const double * boundChanges,
     71      const CoinWarmStartDiff *basisDiff) const
     72  {
     73    return new BonCbcPartialNodeInfo(model,parent, owner, numberChangedBounds, variables,
     74        boundChanges,basisDiff);
     75  }
     76  /* After a CbcModel::resolve this can return a status
     77     -1 no effect
     78     0 treat as optimal
     79     1 as 0 but do not do any more resolves (i.e. no more cuts)
     80     2 treat as infeasible
     81  */
     82  int
     83  CbcNlpStrategy::status(CbcModel * model, CbcNodeInfo * parent,int whereFrom)
     84  {
     85    OsiSolverInterface * solver = model->solver();//get solver
     86    int feasible = 1;
     87    bool solved = true;
     88    int returnStatus = -1;
     89    BonCbcPartialNodeInfo * bmNodeInfo = dynamic_cast<BonCbcPartialNodeInfo *>(parent);
     90    if (!bmNodeInfo) return -1;
    9091
    91   int seqOfInfeasiblesSize = bmNodeInfo->getSequenceOfInfeasiblesSize();
    92   int seqOfUnsolvedSize = bmNodeInfo->getSequenceOfUnsolvedSize();
     92    int seqOfInfeasiblesSize = bmNodeInfo->getSequenceOfInfeasiblesSize();
     93    int seqOfUnsolvedSize = bmNodeInfo->getSequenceOfUnsolvedSize();
    9394
    9495
    95   if(solver->isAbandoned()) {
    96     solved = false;
    97     seqOfUnsolvedSize++;
    98     ;
    99   }
    100   else if(solver->isProvenPrimalInfeasible()) {
    101     feasible = 0;
    102     seqOfInfeasiblesSize++;
    103   }
     96    if (solver->isAbandoned()) {
     97      solved = false;
     98      seqOfUnsolvedSize++;
     99      ;
     100    }
     101    else if (solver->isProvenPrimalInfeasible()) {
     102      feasible = 0;
     103      seqOfInfeasiblesSize++;
     104    }
    104105
    105   if((seqOfUnsolvedSize==0) || (maxFailure_ == 0) &&
    106       (maxInfeasible_== 0) || (seqOfInfeasiblesSize==0))
     106    if ((seqOfUnsolvedSize==0) || (maxFailure_ == 0) &&
     107        (maxInfeasible_== 0) || (seqOfInfeasiblesSize==0))
    107108
    108     if(feasible && seqOfInfeasiblesSize > 1) {
    109       std::cerr<<"Feasible node while father was infeasible."
     109      if (feasible && seqOfInfeasiblesSize > 1) {
     110        std::cerr<<"Feasible node while father was infeasible."
     111        <<std::endl;
     112      }
     113
     114    if (solved && seqOfUnsolvedSize > 1) {
     115      std::cerr<<"Solved node while father was unsolved."
    110116      <<std::endl;
    111117    }
    112118
    113   if(solved && seqOfUnsolvedSize > 1) {
    114     std::cerr<<"Solved node while father was unsolved."
    115     <<std::endl;
     119    if (seqOfInfeasiblesSize < maxInfeasible_ &&
     120        solved && !feasible) {
     121      std::cerr<<"Branching on infeasible node, sequence of infeasibles size "
     122      <<seqOfInfeasiblesSize<<std::endl;
     123      // Have to make sure that we will branch
     124      OsiTMINLPInterface * ipopt = dynamic_cast<OsiTMINLPInterface *>(solver);
     125      ipopt->forceBranchable();
     126      //change objective value
     127      returnStatus = 0;
     128
     129    }
     130
     131    if (!solved && parent != NULL &&
     132        seqOfUnsolvedSize <= maxFailure_) {
     133      std::cout<<"Branching on unsolved node, sequence of unsolved size "<<seqOfUnsolvedSize<<std::endl;
     134      // Have to make sure that we will branch
     135      OsiTMINLPInterface * ipopt = dynamic_cast<OsiTMINLPInterface *>(solver);
     136      ipopt->forceBranchable();     //      feasible=1;
     137      returnStatus = 0;
     138    }
     139
     140    if (solver->isAbandoned() && parent != NULL &&
     141        seqOfUnsolvedSize > maxFailure_) {
     142      hasFailed_ = true;
     143      OsiTMINLPInterface * ipopt =
     144        dynamic_cast<OsiTMINLPInterface *>(solver);
     145      if (pretendFailIsInfeasible_) {
     146        //force infeasible
     147        ipopt->forceInfeasible();
     148        returnStatus = 2;
     149      }
     150      else
     151        throw ipopt->newUnsolvedError(0);
     152    }
     153    return returnStatus;
    116154  }
    117155
    118   if(seqOfInfeasiblesSize < maxInfeasible_ &&
    119       solved && !feasible) {
    120     std::cerr<<"Branching on infeasible node, sequence of infeasibles size "
    121     <<seqOfInfeasiblesSize<<std::endl;
    122     // Have to make sure that we will branch
    123     OsiTMINLPInterface * ipopt = dynamic_cast<OsiTMINLPInterface *>(solver);
    124     ipopt->forceBranchable();
    125     //change objective value
    126     returnStatus = 0;
    127 
    128   }
    129 
    130   if(!solved && parent != NULL &&
    131       seqOfUnsolvedSize <= maxFailure_) {
    132     std::cout<<"Branching on unsolved node, sequence of unsolved size "<<seqOfUnsolvedSize<<std::endl;
    133     // Have to make sure that we will branch
    134     OsiTMINLPInterface * ipopt = dynamic_cast<OsiTMINLPInterface *>(solver);
    135     ipopt->forceBranchable();     //      feasible=1;
    136     returnStatus = 0;
    137   }
    138 
    139   if(solver->isAbandoned() && parent != NULL &&
    140       seqOfUnsolvedSize > maxFailure_) {
    141     hasFailed_ = true;
    142     OsiTMINLPInterface * ipopt =
    143       dynamic_cast<OsiTMINLPInterface *>(solver);
    144     if(pretendFailIsInfeasible_) {
    145       //force infeasible
    146       ipopt->forceInfeasible();
    147       returnStatus = 2;
    148     }
    149     else
    150       throw ipopt->newUnsolvedError(0);
    151   }
    152   return returnStatus;
    153 }
    154 
    155 void
    156 CbcNlpStrategy::setupCutGenerators(CbcModel &model)
     156  void
     157  CbcNlpStrategy::setupCutGenerators(CbcModel &model)
    157158{}
    158159
    159 void
    160 CbcNlpStrategy::setupHeuristics(CbcModel &model)
    161 {}
     160  void
     161  CbcNlpStrategy::setupHeuristics(CbcModel &model)
     162  {}
    162163
    163 void
    164 CbcNlpStrategy::setupPrinting(CbcModel &model, int toto)
    165 {}
     164  void
     165  CbcNlpStrategy::setupPrinting(CbcModel &model, int toto)
     166  {}
    166167
    167 void
    168 CbcNlpStrategy::setupOther(CbcModel &model)
    169 {}
     168  void
     169  CbcNlpStrategy::setupOther(CbcModel &model)
     170  {}
    170171}
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcNlpStrategy.hpp

    r57 r62  
    1919
    2020
    21 namespace Bonmin{
    22 class CbcNlpStrategy : public CbcStrategy
     21namespace Bonmin
    2322{
    24 public:
     23  class CbcNlpStrategy : public CbcStrategy
     24  {
     25  public:
    2526
    26   // Default Constructor
    27   CbcNlpStrategy (int maxFailures,
    28       int maxInfeasibles,
    29       int pretendFailIsInfeasible);
     27    // Default Constructor
     28    CbcNlpStrategy (int maxFailures,
     29        int maxInfeasibles,
     30        int pretendFailIsInfeasible);
    3031
    31   // Copy constructor
    32   CbcNlpStrategy ( const CbcNlpStrategy &);
     32    // Copy constructor
     33    CbcNlpStrategy ( const CbcNlpStrategy &);
    3334
    34   // Destructor
    35   virtual ~CbcNlpStrategy ();
     35    // Destructor
     36    virtual ~CbcNlpStrategy ();
    3637
    37   /// Clone
    38   virtual CbcStrategy * clone() const;
     38    /// Clone
     39    virtual CbcStrategy * clone() const;
    3940
    40   /// Return a new Full node information pointer (descendant of CbcFullNodeInfo)
    41   virtual CbcNodeInfo * fullNodeInfo(CbcModel * model,int numberRowsAtContinuous) const;
    42   /// Return a new Partial node information pointer (descendant of CbcPartialNodeInfo)
    43   virtual CbcNodeInfo * partialNodeInfo(CbcModel * model, CbcNodeInfo * parent, CbcNode * owner,
    44       int numberChangedBounds,const int * variables,
    45       const double * boundChanges,
    46       const CoinWarmStartDiff *basisDiff) const;
    47   /** After a CbcModel::resolve this can return a status
    48       -1 no effect
    49       0 treat as optimal
    50       1 as 0 but do not do any more resolves (i.e. no more cuts)
    51       2 treat as infeasible
    52   */
    53   virtual int status(CbcModel * model, CbcNodeInfo * parent, int whereFrom);
    54   /// set maximum number of consecutive failures in a branch before giving up
    55   inline void setMaxFailure(int value)
    56   {
    57     maxFailure_ = value;
    58   }
    59   /// maximum number of consecutive infeasible nodes before giving up
    60   inline void setMaxInfeasible(int value)
    61   {
    62     maxInfeasible_ = value;
    63   }
     41    /// Return a new Full node information pointer (descendant of CbcFullNodeInfo)
     42    virtual CbcNodeInfo * fullNodeInfo(CbcModel * model,int numberRowsAtContinuous) const;
     43    /// Return a new Partial node information pointer (descendant of CbcPartialNodeInfo)
     44    virtual CbcNodeInfo * partialNodeInfo(CbcModel * model, CbcNodeInfo * parent, CbcNode * owner,
     45        int numberChangedBounds,const int * variables,
     46        const double * boundChanges,
     47        const CoinWarmStartDiff *basisDiff) const;
     48    /** After a CbcModel::resolve this can return a status
     49        -1 no effect
     50        0 treat as optimal
     51        1 as 0 but do not do any more resolves (i.e. no more cuts)
     52        2 treat as infeasible
     53    */
     54    virtual int status(CbcModel * model, CbcNodeInfo * parent, int whereFrom);
     55    /// set maximum number of consecutive failures in a branch before giving up
     56    inline void setMaxFailure(int value)
     57    {
     58      maxFailure_ = value;
     59    }
     60    /// maximum number of consecutive infeasible nodes before giving up
     61    inline void setMaxInfeasible(int value)
     62    {
     63      maxInfeasible_ = value;
     64    }
    6465
    65   /// Setup cut generators
    66   virtual void setupCutGenerators(CbcModel & model);
    67   /// Setup heuristics
    68   virtual void setupHeuristics(CbcModel & model);
    69   /// Do printing stuff
    70   virtual void setupPrinting(CbcModel & model,int modelLogLevel);
    71   /// Other stuff e.g. strong branching and preprocessing
    72   virtual void setupOther(CbcModel & model);
     66    /// Setup cut generators
     67    virtual void setupCutGenerators(CbcModel & model);
     68    /// Setup heuristics
     69    virtual void setupHeuristics(CbcModel & model);
     70    /// Do printing stuff
     71    virtual void setupPrinting(CbcModel & model,int modelLogLevel);
     72    /// Other stuff e.g. strong branching and preprocessing
     73    virtual void setupOther(CbcModel & model);
    7374
    74   bool hasFailed()
    75   {
    76     return hasFailed_;
    77   }
    78 protected:
    79   // Data
    80   /// did we fail?
    81   bool hasFailed_;
    82   /// maximum number of consecutive failures in a branch before giving up
    83   int maxFailure_;
    84   /// maximum number of consecutive infeasible nodes before giving up
    85   int maxInfeasible_;
    86   /** If yes when a problem is not solved (failed to be solved)
    87       will pretend that it is infeasible. */
    88   int pretendFailIsInfeasible_;
     75    bool hasFailed()
     76    {
     77      return hasFailed_;
     78    }
     79  protected:
     80    // Data
     81    /// did we fail?
     82    bool hasFailed_;
     83    /// maximum number of consecutive failures in a branch before giving up
     84    int maxFailure_;
     85    /// maximum number of consecutive infeasible nodes before giving up
     86    int maxInfeasible_;
     87    /** If yes when a problem is not solved (failed to be solved)
     88        will pretend that it is infeasible. */
     89    int pretendFailIsInfeasible_;
    8990
    90 private:
    91   /// Illegal Assignment operator
    92   CbcNlpStrategy & operator=(const CbcNlpStrategy& rhs);
     91  private:
     92    /// Illegal Assignment operator
     93    CbcNlpStrategy & operator=(const CbcNlpStrategy& rhs);
    9394
    94 };
     95  };
    9596}
    9697
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcNode.cpp

    r58 r62  
    2828
    2929
    30 namespace Bonmin{
     30namespace Bonmin
     31{
    3132//Default constructor
    32 BonCbcFullNodeInfo::BonCbcFullNodeInfo()
    33     :
    34     CbcFullNodeInfo(),
    35     sequenceOfInfeasiblesSize_(0),
    36     sequenceOfUnsolvedSize_(0)
     33  BonCbcFullNodeInfo::BonCbcFullNodeInfo()
     34      :
     35      CbcFullNodeInfo(),
     36      sequenceOfInfeasiblesSize_(0),
     37      sequenceOfUnsolvedSize_(0)
     38  {}
     39
     40  BonCbcFullNodeInfo::BonCbcFullNodeInfo(CbcModel * model,
     41      int numberRowsAtContinuous) :
     42      CbcFullNodeInfo(model, numberRowsAtContinuous),
     43      sequenceOfInfeasiblesSize_(0),
     44      sequenceOfUnsolvedSize_(0)
     45  {}
     46
     47// Copy constructor
     48  BonCbcFullNodeInfo::BonCbcFullNodeInfo ( const BonCbcFullNodeInfo &other):
     49      CbcFullNodeInfo(other),
     50      sequenceOfInfeasiblesSize_(other.sequenceOfInfeasiblesSize_),
     51      sequenceOfUnsolvedSize_(other.sequenceOfUnsolvedSize_)
     52
     53  {}
     54
     55
     56  void
     57  BonCbcFullNodeInfo::allBranchesGone()
     58  {
     59    IpoptWarmStart * ipws = dynamic_cast<IpoptWarmStart *>(basis_);
     60    if (ipws)
     61      ipws->flushPoint();
     62  }
     63
     64  BonCbcFullNodeInfo::~BonCbcFullNodeInfo()
    3765{}
    3866
    39 BonCbcFullNodeInfo::BonCbcFullNodeInfo(CbcModel * model,
    40     int numberRowsAtContinuous) :
    41     CbcFullNodeInfo(model, numberRowsAtContinuous),
    42     sequenceOfInfeasiblesSize_(0),
    43     sequenceOfUnsolvedSize_(0)
    44 {
    45 }
    46 
    47 // Copy constructor
    48 BonCbcFullNodeInfo::BonCbcFullNodeInfo ( const BonCbcFullNodeInfo &other):
    49     CbcFullNodeInfo(other),
    50     sequenceOfInfeasiblesSize_(other.sequenceOfInfeasiblesSize_),
    51     sequenceOfUnsolvedSize_(other.sequenceOfUnsolvedSize_)
    52 
    53 {}
    54 
    55 
    56 void
    57 BonCbcFullNodeInfo::allBranchesGone()
    58 {
    59   IpoptWarmStart * ipws = dynamic_cast<IpoptWarmStart *>(basis_);
    60   if(ipws)
    61     ipws->flushPoint();
    62 }
    63 
    64 BonCbcFullNodeInfo::~BonCbcFullNodeInfo()
    65 {}
    66 
    67 CbcNodeInfo *
    68 BonCbcFullNodeInfo::clone() const
    69 {
    70   return new BonCbcFullNodeInfo(*this);
    71 }
    72 /****************************************************************************************************/
     67  CbcNodeInfo *
     68  BonCbcFullNodeInfo::clone() const
     69  {
     70    return new BonCbcFullNodeInfo(*this);
     71  }
     72  /****************************************************************************************************/
    7373
    7474// Default constructor
    75 BonCbcPartialNodeInfo::BonCbcPartialNodeInfo ()
    76     : CbcPartialNodeInfo(),
    77     sequenceOfInfeasiblesSize_(0),
    78     sequenceOfUnsolvedSize_(0)
    79 {
    80 }
     75  BonCbcPartialNodeInfo::BonCbcPartialNodeInfo ()
     76      : CbcPartialNodeInfo(),
     77      sequenceOfInfeasiblesSize_(0),
     78      sequenceOfUnsolvedSize_(0)
     79  {}
    8180// Constructor from current state
    82 BonCbcPartialNodeInfo::BonCbcPartialNodeInfo (CbcModel * model,CbcNodeInfo *parent, CbcNode *owner,
    83     int numberChangedBounds,
    84     const int *variables,
    85     const double *boundChanges,
    86     const CoinWarmStartDiff *basisDiff)
    87     : CbcPartialNodeInfo(parent,owner,numberChangedBounds,variables,
    88         boundChanges,basisDiff),
    89     sequenceOfInfeasiblesSize_(0),
    90     sequenceOfUnsolvedSize_(0)
    91 {
    92   IpoptInterface * ipopt = dynamic_cast<IpoptInterface *>(model->solver());
    93   assert (ipopt);
    94   Ipopt::ApplicationReturnStatus optimization_status
    95   = ipopt->getOptStatus();
    96   BonCbcPartialNodeInfo * nlpParent = dynamic_cast<BonCbcPartialNodeInfo *> (parent);
    97   int numberInfeasible = 0;
    98   int numberUnsolved = 0;
    99   if(nlpParent)//father is not root
     81  BonCbcPartialNodeInfo::BonCbcPartialNodeInfo (CbcModel * model,CbcNodeInfo *parent, CbcNode *owner,
     82      int numberChangedBounds,
     83      const int *variables,
     84      const double *boundChanges,
     85      const CoinWarmStartDiff *basisDiff)
     86      : CbcPartialNodeInfo(parent,owner,numberChangedBounds,variables,
     87          boundChanges,basisDiff),
     88      sequenceOfInfeasiblesSize_(0),
     89      sequenceOfUnsolvedSize_(0)
    10090  {
    101     numberInfeasible = nlpParent->getSequenceOfInfeasiblesSize();
    102     numberUnsolved =  nlpParent->getSequenceOfUnsolvedSize();
     91    IpoptInterface * ipopt = dynamic_cast<IpoptInterface *>(model->solver());
     92    assert (ipopt);
     93    Ipopt::ApplicationReturnStatus optimization_status
     94    = ipopt->getOptStatus();
     95    BonCbcPartialNodeInfo * nlpParent = dynamic_cast<BonCbcPartialNodeInfo *> (parent);
     96    int numberInfeasible = 0;
     97    int numberUnsolved = 0;
     98    if (nlpParent)//father is not root
     99    {
     100      numberInfeasible = nlpParent->getSequenceOfInfeasiblesSize();
     101      numberUnsolved =  nlpParent->getSequenceOfUnsolvedSize();
    103102//       if(!nlpParent->numberBranchesLeft_){
    104103//      IpoptWarmStartDiff * ipws = dynamic_cast<IpoptWarmStartDiff *>(nlpParent->basisDiff_);
    105104//      ipws->flushPoint();
    106105//       }
     106    }
     107    else {
     108      BonCbcFullNodeInfo * nlpRoot = dynamic_cast<BonCbcFullNodeInfo *> (parent);
     109      if (nlpRoot) {
     110        numberInfeasible = nlpRoot->getSequenceOfInfeasiblesSize();
     111        numberUnsolved =  nlpRoot->getSequenceOfUnsolvedSize();
     112      }
     113    }
     114    if ((optimization_status==Ipopt::Unrecoverable_Exception)||
     115        (optimization_status==Ipopt::NonIpopt_Exception_Thrown)||
     116        (optimization_status==Ipopt::Insufficient_Memory)||
     117        (optimization_status==Ipopt::Restoration_Failed)||
     118        (optimization_status==Ipopt::Internal_Error)||
     119        (optimization_status==Ipopt::Maximum_Iterations_Exceeded))
     120      sequenceOfUnsolvedSize_ = numberUnsolved + 1;
     121
     122    if (optimization_status==Ipopt::Infeasible_Problem_Detected)
     123      sequenceOfInfeasiblesSize_ = numberInfeasible + 1;
    107124  }
    108   else {
    109     BonCbcFullNodeInfo * nlpRoot = dynamic_cast<BonCbcFullNodeInfo *> (parent);
    110     if(nlpRoot) {
    111       numberInfeasible = nlpRoot->getSequenceOfInfeasiblesSize();
    112       numberUnsolved =  nlpRoot->getSequenceOfUnsolvedSize();
    113     }
    114   }
    115   if((optimization_status==Ipopt::Unrecoverable_Exception)||
    116       (optimization_status==Ipopt::NonIpopt_Exception_Thrown)||
    117       (optimization_status==Ipopt::Insufficient_Memory)||
    118       (optimization_status==Ipopt::Restoration_Failed)||
    119       (optimization_status==Ipopt::Internal_Error)||
    120       (optimization_status==Ipopt::Maximum_Iterations_Exceeded))
    121     sequenceOfUnsolvedSize_ = numberUnsolved + 1;
    122125
    123   if(optimization_status==Ipopt::Infeasible_Problem_Detected)
    124     sequenceOfInfeasiblesSize_ = numberInfeasible + 1;
    125 }
     126  BonCbcPartialNodeInfo::BonCbcPartialNodeInfo (const BonCbcPartialNodeInfo & rhs)
    126127
    127 BonCbcPartialNodeInfo::BonCbcPartialNodeInfo (const BonCbcPartialNodeInfo & rhs)
    128 
    129     : CbcPartialNodeInfo(rhs),
    130     sequenceOfInfeasiblesSize_(rhs.sequenceOfInfeasiblesSize_),
    131     sequenceOfUnsolvedSize_(rhs.sequenceOfUnsolvedSize_)
     128      : CbcPartialNodeInfo(rhs),
     129      sequenceOfInfeasiblesSize_(rhs.sequenceOfInfeasiblesSize_),
     130      sequenceOfUnsolvedSize_(rhs.sequenceOfUnsolvedSize_)
    132131
    133132{}
    134133
    135 CbcNodeInfo *
    136 BonCbcPartialNodeInfo::clone() const
    137 {
    138   return (new BonCbcPartialNodeInfo(*this));
    139 }
     134  CbcNodeInfo *
     135  BonCbcPartialNodeInfo::clone() const
     136  {
     137    return (new BonCbcPartialNodeInfo(*this));
     138  }
    140139
    141 void
    142 BonCbcPartialNodeInfo::allBranchesGone()
    143 {
    144   IpoptWarmStartDiff * ipws = dynamic_cast<IpoptWarmStartDiff *>(basisDiff_);
    145   if(ipws)
    146     ipws->flushPoint();
    147 }
     140  void
     141  BonCbcPartialNodeInfo::allBranchesGone()
     142  {
     143    IpoptWarmStartDiff * ipws = dynamic_cast<IpoptWarmStartDiff *>(basisDiff_);
     144    if (ipws)
     145      ipws->flushPoint();
     146  }
    148147
    149 BonCbcPartialNodeInfo::~BonCbcPartialNodeInfo ()
     148  BonCbcPartialNodeInfo::~BonCbcPartialNodeInfo ()
    150149{}
    151150}
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcNode.hpp

    r57 r62  
    1515
    1616
    17 namespace Bonmin{
    18 /** \brief Holds information for recreating a subproblem by incremental change
    19            from the parent for Bonmin
     17namespace Bonmin
     18{
     19  /** \brief Holds information for recreating a subproblem by incremental change
     20           from the parent for Bonmin
    2021
    21   A BonminBonminCbcPartialNodeInfo object contains changes to the bounds and basis, and
    22   additional cuts, required to recreate a subproblem by modifying and
    23   augmenting the parent subproblem.
    24 */
     22    A BonminBonminCbcPartialNodeInfo object contains changes to the bounds and basis, and
     23    additional cuts, required to recreate a subproblem by modifying and
     24    augmenting the parent subproblem.
     25  */
    2526
    26 class BonCbcFullNodeInfo : public CbcFullNodeInfo
    27 {
     27  class BonCbcFullNodeInfo : public CbcFullNodeInfo
     28  {
    2829
    29 public:
    30   friend class BonCbcPartialNodeInfo;
    31   // Default Constructor
    32   BonCbcFullNodeInfo ();
     30  public:
     31    friend class BonCbcPartialNodeInfo;
     32    // Default Constructor
     33    BonCbcFullNodeInfo ();
    3334
    34   // Constructor from current state
    35   BonCbcFullNodeInfo (CbcModel * model, int numberRowsAtContinuous);
     35    // Constructor from current state
     36    BonCbcFullNodeInfo (CbcModel * model, int numberRowsAtContinuous);
    3637
    37   // Copy constructor
    38   BonCbcFullNodeInfo ( const BonCbcFullNodeInfo &);
     38    // Copy constructor
     39    BonCbcFullNodeInfo ( const BonCbcFullNodeInfo &);
    3940
    40   // Destructor
    41   ~BonCbcFullNodeInfo ();
     41    // Destructor
     42    ~BonCbcFullNodeInfo ();
    4243
    43   /// Clone
    44   virtual CbcNodeInfo * clone() const;
     44    /// Clone
     45    virtual CbcNodeInfo * clone() const;
    4546
    46   /**Method called when all direct sons have been explored to flush
    47      useless warm start information.*/
    48   virtual void allBranchesGone();
     47    /**Method called when all direct sons have been explored to flush
     48       useless warm start information.*/
     49    virtual void allBranchesGone();
    4950
    50   /** Number of consecutive infeasible parents only recorded if node is infeasible*/
    51   inline int getSequenceOfInfeasiblesSize()
     51    /** Number of consecutive infeasible parents only recorded if node is infeasible*/
     52    inline int getSequenceOfInfeasiblesSize()
     53    {
     54      return sequenceOfInfeasiblesSize_;
     55    }
     56    /** Number of consecutive unsolved parents only recorded if node is infeasible*/
     57    inline int getSequenceOfUnsolvedSize()
     58    {
     59      return sequenceOfUnsolvedSize_;
     60    }
     61  private:
     62    /* Data values */
     63    /** Number of consecutive infeasible parents only recorded if node is infeasible*/
     64    int sequenceOfInfeasiblesSize_;
     65    /** Number of consecutive unsolved parents only recorded if node is infeasible*/
     66    int sequenceOfUnsolvedSize_;
     67  private:
     68
     69    /// Illegal Assignment operator
     70    BonCbcFullNodeInfo & operator=(const BonCbcFullNodeInfo& rhs);
     71  };
     72
     73  /** \brief Holds information for recreating a subproblem by incremental change
     74           from the parent for
     75
     76    A BonminCbcPartialNodeInfo object contains changes to the bounds and basis, and
     77    additional cuts, required to recreate a subproblem by modifying and
     78    augmenting the parent subproblem.
     79  */
     80
     81  class BonCbcPartialNodeInfo : public CbcPartialNodeInfo
    5282  {
    53     return sequenceOfInfeasiblesSize_;
    54   }
    55   /** Number of consecutive unsolved parents only recorded if node is infeasible*/
    56   inline int getSequenceOfUnsolvedSize()
    57   {
    58     return sequenceOfUnsolvedSize_;
    59   }
    60 private:
    61   /* Data values */
    62   /** Number of consecutive infeasible parents only recorded if node is infeasible*/
    63   int sequenceOfInfeasiblesSize_;
    64   /** Number of consecutive unsolved parents only recorded if node is infeasible*/
    65   int sequenceOfUnsolvedSize_;
    66 private:
    6783
    68   /// Illegal Assignment operator
    69   BonCbcFullNodeInfo & operator=(const BonCbcFullNodeInfo& rhs);
    70 };
     84  public:
     85    // Default Constructor
     86    BonCbcPartialNodeInfo ();
    7187
    72 /** \brief Holds information for recreating a subproblem by incremental change
    73            from the parent for
     88    // Constructor from current state
     89    BonCbcPartialNodeInfo (CbcModel * model, CbcNodeInfo * parent, CbcNode * owner,
     90        int numberChangedBounds,const int * variables,
     91        const double * boundChanges,
     92        const CoinWarmStartDiff *basisDiff) ;
    7493
    75   A BonminCbcPartialNodeInfo object contains changes to the bounds and basis, and
    76   additional cuts, required to recreate a subproblem by modifying and
    77   augmenting the parent subproblem.
    78 */
     94    // Copy constructor
     95    BonCbcPartialNodeInfo ( const BonCbcPartialNodeInfo &);
    7996
    80 class BonCbcPartialNodeInfo : public CbcPartialNodeInfo
    81 {
     97    // Destructor
     98    ~BonCbcPartialNodeInfo ();
    8299
    83 public:
    84   // Default Constructor
    85   BonCbcPartialNodeInfo ();
     100    /// Clone
     101    virtual CbcNodeInfo * clone() const;
    86102
    87   // Constructor from current state
    88   BonCbcPartialNodeInfo (CbcModel * model, CbcNodeInfo * parent, CbcNode * owner,
    89       int numberChangedBounds,const int * variables,
    90       const double * boundChanges,
    91       const CoinWarmStartDiff *basisDiff) ;
     103    /**Method called when all direct sons have been explored to flush
     104       useless warm start information.*/
     105    virtual void allBranchesGone();
    92106
    93   // Copy constructor
    94   BonCbcPartialNodeInfo ( const BonCbcPartialNodeInfo &);
     107    /** Number of consecutive infeasible parents only recorded if node is infeasible*/
     108    inline int getSequenceOfInfeasiblesSize()
     109    {
     110      return sequenceOfInfeasiblesSize_;
     111    }
     112    /** Number of consecutive unsolved parents only recorded if node is infeasible*/
     113    inline int getSequenceOfUnsolvedSize()
     114    {
     115      return sequenceOfUnsolvedSize_;
     116    }
     117  private:
     118    /* Data values */
     119    /** Number of consecutive infeasible parents only recorded if node is infeasible*/
     120    int sequenceOfInfeasiblesSize_;
     121    /** Number of consecutive unsolved parents only recorded if node is infeasible*/
     122    int sequenceOfUnsolvedSize_;
     123  private:
    95124
    96   // Destructor
    97   ~BonCbcPartialNodeInfo ();
    98 
    99   /// Clone
    100   virtual CbcNodeInfo * clone() const;
    101 
    102   /**Method called when all direct sons have been explored to flush
    103      useless warm start information.*/
    104   virtual void allBranchesGone();
    105 
    106   /** Number of consecutive infeasible parents only recorded if node is infeasible*/
    107   inline int getSequenceOfInfeasiblesSize()
    108   {
    109     return sequenceOfInfeasiblesSize_;
    110   }
    111   /** Number of consecutive unsolved parents only recorded if node is infeasible*/
    112   inline int getSequenceOfUnsolvedSize()
    113   {
    114     return sequenceOfUnsolvedSize_;
    115   }
    116 private:
    117   /* Data values */
    118   /** Number of consecutive infeasible parents only recorded if node is infeasible*/
    119   int sequenceOfInfeasiblesSize_;
    120   /** Number of consecutive unsolved parents only recorded if node is infeasible*/
    121   int sequenceOfUnsolvedSize_;
    122 private:
    123 
    124   /// Illegal Assignment operator
    125   BonCbcPartialNodeInfo & operator=(const Bonmin::BonCbcPartialNodeInfo& rhs);
    126 };
     125    /// Illegal Assignment operator
     126    BonCbcPartialNodeInfo & operator=(const Bonmin::BonCbcPartialNodeInfo& rhs);
     127  };
    127128}
    128129#endif
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcParam.cpp

    r58 r62  
    1212#include "BonCbcParam.hpp"
    1313
    14 namespace Bonmin {
    15 bool
    16 BonminCbcParam::extractParams(OsiTMINLPInterface * solver)
     14namespace Bonmin
    1715{
    18   bool success = true;
     16  bool
     17  BonminCbcParam::extractParams(OsiTMINLPInterface * solver)
     18  {
     19    bool success = true;
    1920
    20   Ipopt::SmartPtr<Ipopt::OptionsList> Options = solver->retrieve_options();
     21    Ipopt::SmartPtr<Ipopt::OptionsList> Options = solver->retrieve_options();
    2122
    22   //extract IpoptInterface special params
    23   solver->extractInterfaceParams();
     23    //extract IpoptInterface special params
     24    solver->extractInterfaceParams();
    2425
    25   //log levels
    26   success &= Options->GetIntegerValue("bb_log_level",bbLogLevel,"bonmin.");
    27   success &= Options->GetIntegerValue("bb_log_interval",logInterval,"bonmin.");
    28   success &= Options->GetIntegerValue("lp_log_level",lpLogLevel,"bonmin.");
    29   success &= Options->GetIntegerValue("milp_log_level",milpLogLevel,"bonmin.");
    30   success &= Options->GetIntegerValue("oa_log_level",oaLogLevel,"bonmin.");
    31   success &= Options->GetNumericValue("oa_log_frequency",oaLogFrequency,"bonmin.");
    32   success &= Options->GetIntegerValue("nlp_log_level",nlpLogLevel,"bonmin.");
    33   //General options
    34   success &= Options->GetEnumValue("algorithm",algo,"bonmin.");
    35   success &= Options->GetNumericValue("time_limit", maxTime, "bonmin.");
    36   success &= Options->GetIntegerValue("node_limit",maxNodes,"bonmin.");
    37   success &= Options->GetNumericValue("integer_tolerance",intTol,"bonmin.");
    38   success &= Options->GetNumericValue("allowable_gap",allowableGap,"bonmin.");
    39   success &= Options->GetNumericValue("allowable_fraction_gap",allowableFractionGap,"bonmin.");
    40   success &= Options->GetNumericValue("cutoff_decr",cutoffDecr,"bonmin.");
    41   success &= Options->GetNumericValue("cutoff",cutoff,"bonmin.");
     26    //log levels
     27    success &= Options->GetIntegerValue("bb_log_level",bbLogLevel,"bonmin.");
     28    success &= Options->GetIntegerValue("bb_log_interval",logInterval,"bonmin.");
     29    success &= Options->GetIntegerValue("lp_log_level",lpLogLevel,"bonmin.");
     30    success &= Options->GetIntegerValue("milp_log_level",milpLogLevel,"bonmin.");
     31    success &= Options->GetIntegerValue("oa_log_level",oaLogLevel,"bonmin.");
     32    success &= Options->GetNumericValue("oa_log_frequency",oaLogFrequency,"bonmin.");
     33    success &= Options->GetIntegerValue("nlp_log_level",nlpLogLevel,"bonmin.");
     34    //General options
     35    success &= Options->GetEnumValue("algorithm",algo,"bonmin.");
     36    success &= Options->GetNumericValue("time_limit", maxTime, "bonmin.");
     37    success &= Options->GetIntegerValue("node_limit",maxNodes,"bonmin.");
     38    success &= Options->GetNumericValue("integer_tolerance",intTol,"bonmin.");
     39    success &= Options->GetNumericValue("allowable_gap",allowableGap,"bonmin.");
     40    success &= Options->GetNumericValue("allowable_fraction_gap",allowableFractionGap,"bonmin.");
     41    success &= Options->GetNumericValue("cutoff_decr",cutoffDecr,"bonmin.");
     42    success &= Options->GetNumericValue("cutoff",cutoff,"bonmin.");
    4243
    43   // Branch & bound setting
    44   success &= Options->GetEnumValue("nodeselect_stra",nodeSelection,"bonmin.");
    45   success &= Options->GetIntegerValue("number_strong_branch",numberStrong,"bonmin.");
    46   success &= Options->GetIntegerValue("number_before_trust", minReliability,"bonmin.");
     44    // Branch & bound setting
     45    success &= Options->GetEnumValue("nodeselect_stra",nodeSelection,"bonmin.");
     46    success &= Options->GetIntegerValue("number_strong_branch",numberStrong,"bonmin.");
     47    success &= Options->GetIntegerValue("number_before_trust", minReliability,"bonmin.");
    4748
    48   success &=  Options->GetEnumValue("sos_constraints",disableSos,"bonmin.");
    49   // Robustness and non convex minlps
    50   success &= Options->GetIntegerValue("max_consecutive_failures",
    51       maxFailures,"bonmin.");
    52   success &= Options->GetIntegerValue("max_consecutive_infeasible",
    53       maxInfeasible,"bonmin.");
    54   success &= Options->GetEnumValue("nlp_failure_behavior",failureBehavior,".bonmin");
     49    success &=  Options->GetEnumValue("sos_constraints",disableSos,"bonmin.");
     50    // Robustness and non convex minlps
     51    success &= Options->GetIntegerValue("max_consecutive_failures",
     52        maxFailures,"bonmin.");
     53    success &= Options->GetIntegerValue("max_consecutive_infeasible",
     54        maxInfeasible,"bonmin.");
     55    success &= Options->GetEnumValue("nlp_failure_behavior",failureBehavior,".bonmin");
    5556
    56   // Hybrid options
    57   success &= Options->GetIntegerValue("nlp_solve_frequency",nlpSolveFrequency,"bonmin.");
    58   success &= Options->GetNumericValue("oa_dec_time_limit",oaDecMaxTime,"bonmin.");
    59   success &= Options->GetIntegerValue("Gomory_cuts", migFreq,"bonmin.");
    60   success &= Options->GetIntegerValue("probing_cuts",probFreq,"bonmin.");
    61   success &= Options->GetIntegerValue("mir_cuts",mirFreq,"bonmin.");
    62   success &= Options->GetIntegerValue("cover_cuts",coverFreq,"bonmin.");
     57    // Hybrid options
     58    success &= Options->GetIntegerValue("nlp_solve_frequency",nlpSolveFrequency,"bonmin.");
     59    success &= Options->GetNumericValue("oa_dec_time_limit",oaDecMaxTime,"bonmin.");
     60    success &= Options->GetIntegerValue("Gomory_cuts", migFreq,"bonmin.");
     61    success &= Options->GetIntegerValue("probing_cuts",probFreq,"bonmin.");
     62    success &= Options->GetIntegerValue("mir_cuts",mirFreq,"bonmin.");
     63    success &= Options->GetIntegerValue("cover_cuts",coverFreq,"bonmin.");
    6364
    64   // milp subsolver options
    65   success &= Options->GetEnumValue("milp_subsolver",milpSubSolver,"bonmin.");
    66   success &= Options->GetEnumValue("nodeselect_stra",milpSubSolver_nodeSelection,"milp_sub.");
    67   success &= Options->GetIntegerValue("number_strong_branch",milpSubSolver_numberStrong,"milp_sub.");
    68   success &= Options->GetIntegerValue("number_before_trust", milpSubSolver_minReliability,"milp_sub.");
    69   success &= Options->GetIntegerValue("Gomory_cuts", milpSubSolver_migFreq,"milp_sub.");
    70   success &= Options->GetIntegerValue("probing_cuts",milpSubSolver_probFreq,"milp_sub.");
    71   success &= Options->GetIntegerValue("mir_cuts",milpSubSolver_mirFreq,"milp_sub.");
    72   success &= Options->GetIntegerValue("cover_cuts",milpSubSolver_coverFreq,"milp_sub.");
     65    // milp subsolver options
     66    success &= Options->GetEnumValue("milp_subsolver",milpSubSolver,"bonmin.");
     67    success &= Options->GetEnumValue("nodeselect_stra",milpSubSolver_nodeSelection,"milp_sub.");
     68    success &= Options->GetIntegerValue("number_strong_branch",milpSubSolver_numberStrong,"milp_sub.");
     69    success &= Options->GetIntegerValue("number_before_trust", milpSubSolver_minReliability,"milp_sub.");
     70    success &= Options->GetIntegerValue("Gomory_cuts", milpSubSolver_migFreq,"milp_sub.");
     71    success &= Options->GetIntegerValue("probing_cuts",milpSubSolver_probFreq,"milp_sub.");
     72    success &= Options->GetIntegerValue("mir_cuts",milpSubSolver_mirFreq,"milp_sub.");
     73    success &= Options->GetIntegerValue("cover_cuts",milpSubSolver_coverFreq,"milp_sub.");
    7374
    74   //Preset default for algorithm
    75   if(algo==0)//B-BB
    76   {
    77     minReliability=0;
    78     numberStrong=0;
     75    //Preset default for algorithm
     76    if (algo==0)//B-BB
     77    {
     78      minReliability=0;
     79      numberStrong=0;
     80    }
     81    else if (algo==1)//B-OA
     82    {
     83      oaDecMaxTime = DBL_MAX;
     84      nlpSolveFrequency = 0;
     85      bbLogLevel = 0;
     86    }
     87    else if (algo==2) {
     88      oaDecMaxTime = 0;
     89      nlpSolveFrequency = 0;
     90      migFreq = 0;
     91      probFreq = 0;
     92      mirFreq = 0;
     93      coverFreq = 0;
     94    }
     95    else if (algo==3)//Nothing to do
     96    {
     97    }
     98
     99    return success;
    79100  }
    80   else if (algo==1)//B-OA
    81   {
    82     oaDecMaxTime = DBL_MAX;
    83     nlpSolveFrequency = 0;
    84     bbLogLevel = 0;
    85   }
    86   else if (algo==2) {
    87     oaDecMaxTime = 0;
    88     nlpSolveFrequency = 0;
    89     migFreq = 0;
    90     probFreq = 0;
    91     mirFreq = 0;
    92     coverFreq = 0;
    93   }
    94   else if (algo==3)//Nothing to do
    95   {
    96   }
    97 
    98   return success;
    99101}
    100 }
  • branches/devel/Bonmin/src/CbcBonmin/BonCbcParam.hpp

    r58 r62  
    1313
    1414#include "BonOsiTMINLPInterface.hpp"
    15 namespace Bonmin {
    16 class BonminCbcParam
     15namespace Bonmin
    1716{
    18 public:
    19   /** Algorithm type
    20       <ul>
    21       <li> 0 "B-BB"
    22       <li> 1 "B-OA"
    23       <li> 2 "B-QG"
    24       <li> 3 "B-Hyb"
    25       </ul>
    26   */
    27   int algo;
    28   /** log level for the branch-and-bound */
    29   int bbLogLevel;
    30   /** Display information every logIntervval nodes.*/
    31   int logInterval;
    32   /** log level for the continuous subsolver */
    33   int lpLogLevel;
    34   /** log level for milp sub-solver in OA. */
    35   int milpLogLevel;
    36   /** log level for OA decomposition */
    37   int oaLogLevel;
    38   /** log frequency for OA */
    39   double oaLogFrequency;
    40   /** log level for the nlp subsolver interface (different from ipopt
    41       log and log level which should be set with print_level).*/
    42   int nlpLogLevel;
    43   /** Max number of failures in a branch.*/
    44   int maxFailures;
    45   /** Behavior of the algorithm in the case of a failure.*/
    46   int failureBehavior;
    47   /** Max number of consecutive infeasible problem in a branch
    48       before fathoming.*/
    49   int maxInfeasible;
    50   /** Amount by which cutoff is incremented */
    51   double cutoffDecr;
    52   /** cutoff value */
    53   double cutoff;
    54   /** Stop if absolute gap is less than :*/
    55   double allowableGap;
    56   /** Stop if relative gap is less than :*/
    57   double allowableFractionGap;
    58   /** Node selection strategy :
    59       <ul>
    60       <li> 0: best boud,
    61       <li> 1: DFS,
    62       <li> 2: BFS,
    63       <li> 3: dynamic (see
    64       <a href="http://www.coin-or.org/Doxygen/Cbc/class_cbc_branch_dynamic_decision.html">
    65       CbcBranchActual.hpp </a>
    66       </ul>
    67   */
    68   int nodeSelection;
    69   /** Number of candidates for strong branching.*/
    70   int numberStrong;
    71   /** Minimum reliability before trust pseudo-costs.*/
    72   int minReliability;
    73   /** Global time limit. */
    74   double maxTime;
    75   /** Global node limit.*/
    76   int maxNodes;
    77   /** Integer tolerance.*/
    78   double intTol;
    79   /** Conssider or not SOS constraints.*/
    80   int disableSos;
    81   /** frequency to solve nlp's in B-Hyb.*/
    82   int nlpSolveFrequency;
    83   /** Max OA decomposition time in B-Hyb.*/
    84   double oaDecMaxTime;
    85   /** milp subsolver:
    86       <ul>
    87       <li> 0 Cbc with defaults,
    88       <li> 1 Cbc with passed parameters,
    89       <li> 2 Cplex.
    90       </ul>
    91   */
    92   int milpSubSolver;
    93   /** Mig cuts generation frequency.*/
    94   int migFreq;
    95   /** Probing cuts generation frequency.*/
    96   int probFreq;
    97   /** Mir cuts generation frequency.*/
    98   int mirFreq;
    99   /** Cover cuts generation frequency.*/
    100   int coverFreq;
     17  class BonminCbcParam
     18  {
     19  public:
     20    /** Algorithm type
     21        <ul>
     22        <li> 0 "B-BB"
     23        <li> 1 "B-OA"
     24        <li> 2 "B-QG"
     25        <li> 3 "B-Hyb"
     26        </ul>
     27    */
     28    int algo;
     29    /** log level for the branch-and-bound */
     30    int bbLogLevel;
     31    /** Display information every logIntervval nodes.*/
     32    int logInterval;
     33    /** log level for the continuous subsolver */
     34    int lpLogLevel;
     35    /** log level for milp sub-solver in OA. */
     36    int milpLogLevel;
     37    /** log level for OA decomposition */
     38    int oaLogLevel;
     39    /** log frequency for OA */
     40    double oaLogFrequency;
     41    /** log level for the nlp subsolver interface (different from ipopt
     42        log and log level which should be set with print_level).*/
     43    int nlpLogLevel;
     44    /** Max number of failures in a branch.*/
     45    int maxFailures;
     46    /** Behavior of the algorithm in the case of a failure.*/
     47    int failureBehavior;
     48    /** Max number of consecutive infeasible problem in a branch
     49        before fathoming.*/
     50    int maxInfeasible;
     51    /** Amount by which cutoff is incremented */
     52    double cutoffDecr;
     53    /** cutoff value */
     54    double cutoff;
     55    /** Stop if absolute gap is less than :*/
     56    double allowableGap;
     57    /** Stop if relative gap is less than :*/
     58    double allowableFractionGap;
     59    /** Node selection strategy :
     60        <ul>
     61        <li> 0: best boud,
     62        <li> 1: DFS,
     63        <li> 2: BFS,
     64        <li> 3: dynamic (see
     65        <a href="http://www.coin-or.org/Doxygen/Cbc/class_cbc_branch_dynamic_decision.html">
     66        CbcBranchActual.hpp </a>
     67        </ul>
     68    */
     69    int nodeSelection;
     70    /** Number of candidates for strong branching.*/
     71    int numberStrong;
     72    /** Minimum reliability before trust pseudo-costs.*/
     73    int minReliability;
     74    /** Global time limit. */
     75    double maxTime;
     76    /** Global node limit.*/
     77    int maxNodes;
     78    /** Integer tolerance.*/
     79    double intTol;
     80    /** Conssider or not SOS constraints.*/
     81    int disableSos;
     82    /** frequency to solve nlp's in B-Hyb.*/
     83    int nlpSolveFrequency;
     84    /** Max OA decomposition time in B-Hyb.*/
     85    double oaDecMaxTime;
     86    /** milp subsolver:
     87        <ul>
     88        <li> 0 Cbc with defaults,
     89        <li> 1 Cbc with passed parameters,
     90        <li> 2 Cplex.
     91        </ul>
     92    */
     93    int milpSubSolver;
     94    /** Mig cuts generation frequency.*/
     95    int migFreq;
     96    /** Probing cuts generation frequency.*/
     97    int probFreq;
     98    /** Mir cuts generation frequency.*/
     99    int mirFreq;
     100    /** Cover cuts generation frequency.*/
     101    int coverFreq;
    101102
    102   /** (only set if milpSubSolver is 1) milpsubsolver
    103       Node selection strategy :
    104       <ul>
    105       <li> 0: best boud,
    106       <li> 1: DFS,
    107       <li> 2: BFS,
    108       <li> 3: dynamic (see
    109       <a href="http://www.coin-or.org/Doxygen/Cbc/class_cbc_branch_dynamic_decision.html">
    110       CbcBranchActual.hpp </a>
    111       </ul>
    112   */
    113   int milpSubSolver_nodeSelection;
    114   /** (only set if milpSubSolver is 1) milpsubsolver
    115       Number of candidates for strong branching.*/
    116   int milpSubSolver_numberStrong;
    117   /** (only set if milpSubSolver is 1) milpsubsolver
    118       Minimum reliability before trust pseudo-costs.*/
    119   int milpSubSolver_minReliability;
    120   /** (only set if milpSubSolver is 1) milpsubsolver Mig cuts generation frequency.*/
    121   int milpSubSolver_migFreq;
    122   /** (only set if milpSubSolver is 1) milpsubsolver Probing cuts generation frequency.*/
    123   int milpSubSolver_probFreq;
    124   /** (only set if milpSubSolver is 1) milpsubsolver Mir cuts generation frequency.*/
    125   int milpSubSolver_mirFreq;
    126   /** (only set if milpSubSolver is 1) milpsubsolver Cover cuts generation frequency.*/
    127   int milpSubSolver_coverFreq;
     103    /** (only set if milpSubSolver is 1) milpsubsolver
     104        Node selection strategy :
     105        <ul>
     106        <li> 0: best boud,
     107        <li> 1: DFS,
     108        <li> 2: BFS,
     109        <li> 3: dynamic (see
     110        <a href="http://www.coin-or.org/Doxygen/Cbc/class_cbc_branch_dynamic_decision.html">
     111        CbcBranchActual.hpp </a>
     112        </ul>
     113    */
     114    int milpSubSolver_nodeSelection;
     115    /** (only set if milpSubSolver is 1) milpsubsolver
     116        Number of candidates for strong branching.*/
     117    int milpSubSolver_numberStrong;
     118    /** (only set if milpSubSolver is 1) milpsubsolver
     119        Minimum reliability before trust pseudo-costs.*/
     120    int milpSubSolver_minReliability;
     121    /** (only set if milpSubSolver is 1) milpsubsolver Mig cuts generation frequency.*/
     122    int milpSubSolver_migFreq;
     123    /** (only set if milpSubSolver is 1) milpsubsolver Probing cuts generation frequency.*/
     124    int milpSubSolver_probFreq;
     125    /** (only set if milpSubSolver is 1) milpsubsolver Mir cuts generation frequency.*/
     126    int milpSubSolver_mirFreq;
     127    /** (only set if milpSubSolver is 1) milpsubsolver Cover cuts generation frequency.*/
     128    int milpSubSolver_coverFreq;
    128129
    129 public:
    130   /** Empty constructor. */
    131   BonminCbcParam()
    132   {}
    133   /** Destructor.*/
    134   ~BonminCbcParam()
    135   {}
    136   ///Process parameter file and extract MIP options.
    137   bool extractParams(OsiTMINLPInterface * solver);
    138   ///operator() will extractParameters from IpoptInterface.
    139   bool operator()(OsiTMINLPInterface * solver)
    140   {
    141     return extractParams(solver);
    142   }
    143 };
     130  public:
     131    /** Empty constructor. */
     132    BonminCbcParam()
     133    {}
     134    /** Destructor.*/
     135    ~BonminCbcParam()
     136    {}
     137    ///Process parameter file and extract MIP options.
     138    bool extractParams(OsiTMINLPInterface * solver);
     139    ///operator() will extractParameters from IpoptInterface.
     140    bool operator()(OsiTMINLPInterface * solver)
     141    {
     142      return extractParams(solver);
     143    }
     144  };
    144145} //end namespace Bonmin
    145146#endif
  • branches/devel/Bonmin/src/OaInterface/BonDummyHeuristic.cpp

    r57 r62  
    1313
    1414#include "OsiAuxInfo.hpp"
    15 namespace Bonmin{
     15namespace Bonmin
     16{
    1617/// Default constructor
    17 DummyHeuristic::DummyHeuristic(CbcModel &model,
    18     OsiTMINLPInterface * si)
    19     :
    20     CbcHeuristic(model),
    21     nlp_(si)
    22 {}
     18  DummyHeuristic::DummyHeuristic(CbcModel &model,
     19      OsiTMINLPInterface * si)
     20      :
     21      CbcHeuristic(model),
     22      nlp_(si)
     23  {}
    2324
    24 DummyHeuristic::DummyHeuristic(OsiTMINLPInterface * si)
    25     :
    26     CbcHeuristic(),
    27     nlp_(si)
    28 {}
     25  DummyHeuristic::DummyHeuristic(OsiTMINLPInterface * si)
     26      :
     27      CbcHeuristic(),
     28      nlp_(si)
     29  {}
    2930/// Assign an OsiTMINLPInterface
    30 void
    31 DummyHeuristic::assignInterface(OsiTMINLPInterface * si)
    32 {
    33   nlp_ = si;
    34 }
     31  void
     32  DummyHeuristic::assignInterface(OsiTMINLPInterface * si)
     33  {
     34    nlp_ = si;
     35  }
    3536/// heuristic method
    36 int
    37 DummyHeuristic::solution(double &solutionValue, double *betterSolution)
    38 {
    39   OsiBabSolver * babSolver = dynamic_cast<OsiBabSolver *>
    40       (model_->solver()->getAuxiliaryInfo());
    41   //  double bestKnown = getObjValue();
    42   if(babSolver) {
    43     return babSolver->solution(solutionValue, betterSolution,
    44         model_->getNumCols());
     37  int
     38  DummyHeuristic::solution(double &solutionValue, double *betterSolution)
     39  {
     40    OsiBabSolver * babSolver = dynamic_cast<OsiBabSolver *>
     41        (model_->solver()->getAuxiliaryInfo());
     42    //  double bestKnown = getObjValue();
     43    if (babSolver) {
     44      return babSolver->solution(solutionValue, betterSolution,
     45          model_->getNumCols());
     46    }
     47    return 0;
    4548  }
    46   return 0;
    47 }
    4849
    4950}
  • branches/devel/Bonmin/src/OaInterface/BonDummyHeuristic.hpp

    r58 r62  
    1313
    1414#include "CbcHeuristic.hpp"
    15 namespace Bonmin{
    16 class  DummyHeuristic : public CbcHeuristic
     15namespace Bonmin
    1716{
    18 public:
    19   /// Default constructor
    20   DummyHeuristic(OsiTMINLPInterface * si = NULL);
    21   /// Usefull constructor
    22   DummyHeuristic(CbcModel &model, OsiTMINLPInterface * si = NULL);
    23   ///Copy constructor
    24   DummyHeuristic( const DummyHeuristic &copy):
    25       CbcHeuristic(copy),
    26       nlp_(copy.nlp_),
    27       knowsSolution(copy.knowsSolution)
    28   {}
    29   /// Assign an OsiTMINLPInterface
    30   void assignInterface(OsiTMINLPInterface * si);
    31   /// heuristic method
    32   virtual int solution(double &solutionValue, double *betterSolution);
    33   virtual int solution(double &solutionValue, double *betterSolution, OsiCuts & cs)
     17  class  DummyHeuristic : public CbcHeuristic
    3418  {
    35     return solution(solutionValue, betterSolution);
    36   }
    37   virtual CbcHeuristic * clone()const
    38   {
    39     return new DummyHeuristic(*this);
    40   }
    41   virtual void resetModel(CbcModel*)
    42   {}
    43 private:
    44   /// Pointer to the Ipopt interface
    45   OsiTMINLPInterface * nlp_;
    46   /// Do I have a solution?
    47   bool knowsSolution;
    48 };
     19  public:
     20    /// Default constructor
     21    DummyHeuristic(OsiTMINLPInterface * si = NULL);
     22    /// Usefull constructor
     23    DummyHeuristic(CbcModel &model, OsiTMINLPInterface * si = NULL);
     24    ///Copy constructor
     25    DummyHeuristic( const DummyHeuristic &copy):
     26        CbcHeuristic(copy),
     27        nlp_(copy.nlp_),
     28        knowsSolution(copy.knowsSolution)
     29    {}
     30    /// Assign an OsiTMINLPInterface
     31    void assignInterface(OsiTMINLPInterface * si);
     32    /// heuristic method
     33    virtual int solution(double &solutionValue, double *betterSolution);
     34    virtual int solution(double &solutionValue, double *betterSolution, OsiCuts & cs)
     35    {
     36      return solution(solutionValue, betterSolution);
     37    }
     38    virtual CbcHeuristic * clone()const
     39    {
     40      return new DummyHeuristic(*this);
     41    }
     42    virtual void resetModel(CbcModel*)
     43    {}
     44  private:
     45    /// Pointer to the Ipopt interface
     46    OsiTMINLPInterface * nlp_;
     47    /// Do I have a solution?
     48    bool knowsSolution;
     49  };
    4950}
    5051#endif
  • branches/devel/Bonmin/src/OaInterface/BonOACutGenerator.cpp

    r57 r62  
    1111#include "OsiAuxInfo.hpp"
    1212
    13 namespace Bonmin{
     13namespace Bonmin
     14{
    1415/// Default constructor
    15 OACutGenerator::OACutGenerator(OsiTMINLPInterface * si,
    16     int maxDepth)
    17     :
    18     CglCutGenerator(),
    19     nlp_(si),
    20     maxDepth_(maxDepth),
    21     nSolve_(0)
    22 {
    23   handler_ = new CoinMessageHandler();
    24   handler_ -> setLogLevel(1);
    25   messages_ = OaMessages();
    26 }
     16  OACutGenerator::OACutGenerator(OsiTMINLPInterface * si,
     17      int maxDepth)
     18      :
     19      CglCutGenerator(),
     20      nlp_(si),
     21      maxDepth_(maxDepth),
     22      nSolve_(0)
     23  {
     24    handler_ = new CoinMessageHandler();
     25    handler_ -> setLogLevel(1);
     26    messages_ = OaMessages();
     27  }
    2728/// Assign an OsiTMINLPInterface
    28 void
    29 OACutGenerator::assignInterface(OsiTMINLPInterface * si)
     29  void
     30  OACutGenerator::assignInterface(OsiTMINLPInterface * si)
    3031
    31 {
    32   nlp_ = si;
    33 }
    34 static int nCalls = 0;
     32  {
     33    nlp_ = si;
     34  }
     35  static int nCalls = 0;
    3536/// cut generation method
    36 void
    37 OACutGenerator::generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
    38     const CglTreeInfo info) const
    39 {
    40   if(nlp_ == NULL) {
    41     std::cerr<<"Error in cut generator for outer approximation no ipopt NLP assigned"<<std::endl;
    42     throw -1;
    43   }
     37  void
     38  OACutGenerator::generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
     39      const CglTreeInfo info) const
     40  {
     41    if (nlp_ == NULL) {
     42      std::cerr<<"Error in cut generator for outer approximation no ipopt NLP assigned"<<std::endl;
     43      throw -1;
     44    }
    4445
    45   int numcols = nlp_->getNumCols();
     46    int numcols = nlp_->getNumCols();
    4647
    47   //Get the continuous solution
    48   //const double *colsol = si.getColSolution();
    49   //Check for integer feasibility
    50   nCalls++;
    51   if(info.level > maxDepth_ || info.pass > 0 || !info.inTree  )
    52     return;
    53   //Fix the variable which have to be fixed, after having saved the bounds
    54   double * saveColLb = new double[numcols];
    55   double * saveColUb = new double[numcols];
    56   CoinCopyN(nlp_->getColLower(), numcols , saveColLb);
    57   CoinCopyN(nlp_->getColUpper(), numcols , saveColUb);
    58   for(int i = 0; i < numcols ; i++) {
    59     if(nlp_->isInteger(i)) {
    60       nlp_->setColBounds(i,si.getColLower()[i],si.getColUpper()[i]);
     48    //Get the continuous solution
     49    //const double *colsol = si.getColSolution();
     50    //Check for integer feasibility
     51    nCalls++;
     52    if (info.level > maxDepth_ || info.pass > 0 || !info.inTree  )
     53      return;
     54    //Fix the variable which have to be fixed, after having saved the bounds
     55    double * saveColLb = new double[numcols];
     56    double * saveColUb = new double[numcols];
     57    CoinCopyN(nlp_->getColLower(), numcols , saveColLb);
     58    CoinCopyN(nlp_->getColUpper(), numcols , saveColUb);
     59    for (int i = 0; i < numcols ; i++) {
     60      if (nlp_->isInteger(i)) {
     61        nlp_->setColBounds(i,si.getColLower()[i],si.getColUpper()[i]);
     62      }
    6163    }
    62   }
    6364
    6465#if 0
    65  //Add tight cuts at LP optimum
    66  int numberCuts = si.getNumRows() - nlp_->getNumRows();
    67  const OsiRowCut ** cuts = new const OsiRowCut*[numberCuts];
    68  int begin = nlp_->getNumRows();
    69  numberCuts = 0;
    70  int end = si.getNumRows();
    71  const double * rowLower = si.getRowLower();
    72  const double * rowUpper = si.getRowUpper();
    73  const CoinPackedMatrix * mat = si.getMatrixByRow();     
    74  const CoinBigIndex * starts = mat->getVectorStarts();
    75  const int * lengths = mat->getVectorLengths();
    76  const double * elements = mat->getElements();
    77  const int * indices = mat->getIndices();
    78  
    79  for(int i = begin ; i < end ; i++, numberCuts++)
    80  {
    81    bool nnzExists=false;
    82    for(int k = starts[i] ; k < starts[i]+lengths[i] ; k++)
    83    {
    84      if(indices[k] == nlp_->getNumCols())
    85      {
    86        nnzExists = true;
    87        char sign = (elements[k]>0.)?'+':'-';
    88        char type='<';
    89        if(rowLower[i]>-1e20) type='>';
    90        std::cout<<"Non zero with sign: "<<sign<<", type: "<<type<<std::endl;
    91      }
    92    }
    93    if(nnzExists)
    94    {
    95       numberCuts--;
    96       continue;
    97    }
    98    else
    99       std::cout<<"No nonzero element"<<std::endl;
    100    int * indsCopy = CoinCopyOfArray(&indices[starts[i]], lengths[i]);
    101    double * elemsCopy = CoinCopyOfArray(&elements[starts[i]], lengths[i]);
    102    cuts[numberCuts] = new OsiRowCut(rowLower[i], rowUpper[i], lengths[i], lengths[i],
    103                            indsCopy, elemsCopy);
    104  }
    105  nlp_->applyRowCuts(numberCuts,cuts);
     66//Add tight cuts at LP optimum
     67    int numberCuts = si.getNumRows() - nlp_->getNumRows();
     68    const OsiRowCut ** cuts = new const OsiRowCut*[numberCuts];
     69    int begin = nlp_->getNumRows();
     70    numberCuts = 0;
     71    int end = si.getNumRows();
     72    const double * rowLower = si.getRowLower();
     73    const double * rowUpper = si.getRowUpper();
     74    const CoinPackedMatrix * mat = si.getMatrixByRow();
     75    const CoinBigIndex * starts = mat->getVectorStarts();
     76    const int * lengths = mat->getVectorLengths();
     77    const double * elements = mat->getElements();
     78    const int * indices = mat->getIndices();
     79
     80    for (int i = begin ; i < end ; i++, numberCuts++) {
     81      bool nnzExists=false;
     82      for (int k = starts[i] ; k < starts[i]+lengths[i] ; k++) {
     83        if (indices[k] == nlp_->getNumCols()) {
     84          nnzExists = true;
     85          char sign = (elements[k]>0.)?'+':'-';
     86          char type='<';
     87          if (rowLower[i]>-1e20) type='>';
     88          std::cout<<"Non zero with sign: "<<sign<<", type: "<<type<<std::endl;
     89        }
     90      }
     91      if (nnzExists) {
     92        numberCuts--;
     93        continue;
     94      }
     95      else
     96        std::cout<<"No nonzero element"<<std::endl;
     97      int * indsCopy = CoinCopyOfArray(&indices[starts[i]], lengths[i]);
     98      double * elemsCopy = CoinCopyOfArray(&elements[starts[i]], lengths[i]);
     99      cuts[numberCuts] = new OsiRowCut(rowLower[i], rowUpper[i], lengths[i], lengths[i],
     100          indsCopy, elemsCopy);
     101    }
     102    nlp_->applyRowCuts(numberCuts,cuts);
    106103#endif
    107   //Now solve the NLP get the cuts, reset bounds and get out
     104    //Now solve the NLP get the cuts, reset bounds and get out
    108105
    109   //  nlp_->turnOnIpoptOutput();
    110   nSolve_++;
    111   nlp_->resolve();
    112   nlp_->getOuterApproximation(cs);
    113   if(nlp_->isProvenOptimal()) {
    114     handler_->message(LP_ERROR,messages_)
    115     <<nlp_->getObjValue()-si.getObjValue()<<CoinMessageEol;
    116     bool feasible = 1;
    117     const double * colsol2 = nlp_->getColSolution();
    118     for(int i = 0 ; i < numcols && feasible; i++) {
    119       if(nlp_->isInteger(i)) {
    120         if(fabs(colsol2[i] - floor(colsol2[i] + 0.5) ) > 1e-07)
    121           feasible = 0;
     106    //  nlp_->turnOnIpoptOutput();
     107    nSolve_++;
     108    nlp_->resolve();
     109    nlp_->getOuterApproximation(cs);
     110    if (nlp_->isProvenOptimal()) {
     111      handler_->message(LP_ERROR,messages_)
     112      <<nlp_->getObjValue()-si.getObjValue()<<CoinMessageEol;
     113      bool feasible = 1;
     114      const double * colsol2 = nlp_->getColSolution();
     115      for (int i = 0 ; i < numcols && feasible; i++) {
     116        if (nlp_->isInteger(i)) {
     117          if (fabs(colsol2[i] - floor(colsol2[i] + 0.5) ) > 1e-07)
     118            feasible = 0;
     119        }
     120      }
     121      if (feasible ) {
     122#if 1
     123        // Also store into solver
     124        OsiAuxInfo * auxInfo = si.getAuxiliaryInfo();
     125        OsiBabSolver * auxiliaryInfo = dynamic_cast<OsiBabSolver *> (auxInfo);
     126        if (auxiliaryInfo) {
     127          double * lpSolution = new double[numcols + 1];
     128          CoinCopyN(colsol2, numcols, lpSolution);
     129          lpSolution[numcols] = nlp_->getObjValue();
     130          auxiliaryInfo->setSolution(lpSolution, numcols + 1, lpSolution[numcols]);
     131          delete [] lpSolution;
     132        }
     133        else
     134          printf("No auxiliary info in nlp solve!\n");
     135#endif
     136
    122137      }
    123138    }
    124     if(feasible ) {
    125 #if 1
    126       // Also store into solver
    127       OsiAuxInfo * auxInfo = si.getAuxiliaryInfo();
    128       OsiBabSolver * auxiliaryInfo = dynamic_cast<OsiBabSolver *> (auxInfo);
    129       if (auxiliaryInfo) {
    130         double * lpSolution = new double[numcols + 1];
    131         CoinCopyN(colsol2, numcols, lpSolution);
    132         lpSolution[numcols] = nlp_->getObjValue();
    133         auxiliaryInfo->setSolution(lpSolution, numcols + 1, lpSolution[numcols]);
    134         delete [] lpSolution;
     139    else if (nlp_->isAbandoned() || nlp_->isIterationLimitReached()) {
     140      std::cerr<<"Unsolved NLP ... exit"<<std::endl;
     141      //    nlp_->turnOnIpoptOutput();
     142      nlp_->resolve();
     143      throw -1;
     144    }
     145    else {
     146      //   std::cout<<"Infeasible NLP => Infeasible node"<<std::endl;
     147      //       //Add an infeasibility local constraint
     148      //       CoinPackedVector v;
     149      //       double rhs = 1.;
     150      //       for(int i = 0; i < numcols ; i++)
     151      //        {
     152      //          if(nlp_->isInteger(i) && (si.getColUpper()[i] - si.getColLower()[i] < 0.9))
     153      //            {
     154      //              double value = floor(colsol[i] + 0.5);
     155      //              assert(fabs(colsol[i]-value)<1e-8 && value >= -1e-08 && value <= 1+ 1e08);
     156      //              v.insert(i, -(2*value - 1));
     157      //              rhs -= value;
     158      //            }
     159      //        }
     160      //       OsiRowCut cut;
     161      //       cut.setRow(v);
     162      //       cut.setLb(rhs);
     163      //       cut.setUb(1e300);
     164      //       cut.setGloballyValid();
     165      //       cs.insert(cut);
     166    }
     167    for (int i = 0; i < numcols ; i++) {
     168      if (nlp_->isInteger(i)) {
     169        nlp_->setColBounds(i,saveColLb[i],saveColUb[i]);
    135170      }
    136       else
    137         printf("No auxiliary info in nlp solve!\n");
     171    }
     172#if 0
     173    nlp_->deleteLastRows(numberCuts);
    138174#endif
    139 
    140     }
     175    delete [] saveColLb;
     176    delete [] saveColUb;
    141177  }
    142   else if(nlp_->isAbandoned() || nlp_->isIterationLimitReached()) {
    143     std::cerr<<"Unsolved NLP ... exit"<<std::endl;
    144     //    nlp_->turnOnIpoptOutput();
    145     nlp_->resolve();
    146     throw -1;
    147   }
    148   else {
    149     //   std::cout<<"Infeasible NLP => Infeasible node"<<std::endl;
    150     //       //Add an infeasibility local constraint
    151     //       CoinPackedVector v;
    152     //       double rhs = 1.;
    153     //       for(int i = 0; i < numcols ; i++)
    154     //  {
    155     //    if(nlp_->isInteger(i) && (si.getColUpper()[i] - si.getColLower()[i] < 0.9))
    156     //      {
    157     //        double value = floor(colsol[i] + 0.5);
    158     //        assert(fabs(colsol[i]-value)<1e-8 && value >= -1e-08 && value <= 1+ 1e08);
    159     //        v.insert(i, -(2*value - 1));
    160     //        rhs -= value;
    161     //      }
    162     //  }
    163     //       OsiRowCut cut;
    164     //       cut.setRow(v);
    165     //       cut.setLb(rhs);
    166     //       cut.setUb(1e300);
    167     //       cut.setGloballyValid();
    168     //       cs.insert(cut);
    169   }
    170   for(int i = 0; i < numcols ; i++) {
    171     if(nlp_->isInteger(i)) {
    172       nlp_->setColBounds(i,saveColLb[i],saveColUb[i]);
    173     }
    174   }
    175 #if 0
    176   nlp_->deleteLastRows(numberCuts);
    177 #endif
    178   delete [] saveColLb;
    179   delete [] saveColUb;
    180178}
    181 }
  • branches/devel/Bonmin/src/OaInterface/BonOACutGenerator.hpp

    r58 r62  
    1313#include "BonOsiTMINLPInterface.hpp"
    1414#include "BonOAMessages.hpp"
    15 namespace Bonmin{
    16 class OACutGenerator : public CglCutGenerator
     15namespace Bonmin
    1716{
    18 public:
    19   /// Default constructor
    20   OACutGenerator(OsiTMINLPInterface * si = NULL,
    21       int maxDepth = 10);
    22   /// Copy constructor
    23   OACutGenerator(const OACutGenerator &copy)
    24       :
    25       nlp_(copy.nlp_),
    26       maxDepth_(copy.maxDepth_)
     17  class OACutGenerator : public CglCutGenerator
    2718  {
    28     handler_ = new CoinMessageHandler();
    29     handler_ -> setLogLevel(copy.handler_->logLevel());
    30     messages_ = OaMessages();
    31   }
     19  public:
     20    /// Default constructor
     21    OACutGenerator(OsiTMINLPInterface * si = NULL,
     22        int maxDepth = 10);
     23    /// Copy constructor
     24    OACutGenerator(const OACutGenerator &copy)
     25        :
     26        nlp_(copy.nlp_),
     27        maxDepth_(copy.maxDepth_)
     28    {
     29      handler_ = new CoinMessageHandler();
     30      handler_ -> setLogLevel(copy.handler_->logLevel());
     31      messages_ = OaMessages();
     32    }
    3233
    33   ///Abstract constructor
    34   virtual CglCutGenerator * clone() const
    35   {
    36     return new OACutGenerator(*this);
    37   }
     34    ///Abstract constructor
     35    virtual CglCutGenerator * clone() const
     36    {
     37      return new OACutGenerator(*this);
     38    }
    3839
    39   /** Desctructor */
    40   virtual ~OACutGenerator()
    41   {
    42     delete handler_;
    43   }
     40    /** Desctructor */
     41    virtual ~OACutGenerator()
     42    {
     43      delete handler_;
     44    }
    4445
    45   /// Assign an OsiTMINLPInterface
    46   void assignInterface(OsiTMINLPInterface * si);
    47   /// cut generation method
    48   virtual void generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
    49       const CglTreeInfo info) const;
     46    /// Assign an OsiTMINLPInterface
     47    void assignInterface(OsiTMINLPInterface * si);
     48    /// cut generation method
     49    virtual void generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
     50        const CglTreeInfo info) const;
    5051
    5152
    5253
    53   void setMaxDepth(int value)
    54   {
    55     maxDepth_ = value;
    56   }
    57   inline int getNSolve()
    58   {
    59     return nSolve_;
    60   }
    61   /**set log level */
    62   void setLogLevel(int value)
    63   {
    64     handler_->setLogLevel(value);
    65   }
    66 private:
    67   /// Pointer to the Ipopt interface
    68   OsiTMINLPInterface * nlp_;
     54    void setMaxDepth(int value)
     55    {
     56      maxDepth_ = value;
     57    }
     58    inline int getNSolve()
     59    {
     60      return nSolve_;
     61    }
     62    /**set log level */
     63    void setLogLevel(int value)
     64    {
     65      handler_->setLogLevel(value);
     66    }
     67  private:
     68    /// Pointer to the Ipopt interface
     69    OsiTMINLPInterface * nlp_;
    6970
    70   /** maximum depth at which generate cuts*/
    71   int maxDepth_;
     71    /** maximum depth at which generate cuts*/
     72    int maxDepth_;
    7273
    73   ///Number of NLP resolution done
    74   mutable int nSolve_;
    75   /** messages handler. */
    76   CoinMessageHandler * handler_;
    77   /** handler */
    78   CoinMessages messages_;
    79 };
     74    ///Number of NLP resolution done
     75    mutable int nSolve_;
     76    /** messages handler. */
     77    CoinMessageHandler * handler_;
     78    /** handler */
     79    CoinMessages messages_;
     80  };
    8081}
    8182#endif
  • branches/devel/Bonmin/src/OaInterface/BonOACutGenerator2.cpp

    r57 r62  
    2323
    2424extern CbcModel * OAModel;
    25 namespace Bonmin{
     25namespace Bonmin
     26{
    2627/// Default constructor
    27 OACutGenerator2::OACutGenerator2():
    28     CglCutGenerator(),
    29     nlp_(NULL),
    30     nSolve_(0),
    31     si_(NULL),
    32     cbcCutoffIncrement_(1e-06),
    33     cbcIntegerTolerance_(1e-05),
    34     localSearchNodeLimit_(0),
    35     maxLocalSearchPerNode_(0),
    36     maxLocalSearch_(0),
    37     maxLocalSearchTime_(3600),
    38     nLocalSearch_(0),
    39     solveAuxiliaryProblem_(0),
    40     handler_(NULL),
    41     subMilpLogLevel_(0),
    42     leaveSiUnchanged_(0),
    43     strategy_(NULL),
    44     timeBegin_(0.),
    45     logFrequency_(1000.)
    46 {
    47   handler_ = new CoinMessageHandler();
    48   handler_ -> setLogLevel(2);
    49   messages_ = OaMessages();
    50   timeBegin_ = CoinCpuTime();
    51 }
    52 
    53 
    54 
    55 OACutGenerator2::OACutGenerator2
    56 (OsiTMINLPInterface * nlp,
    57  OsiSolverInterface * si,
    58  CbcStrategy * strategy,
    59  double cbcCutoffIncrement,
    60  double cbcIntegerTolerance,
    61  bool solveAuxiliaryProblem,
    62  bool leaveSiUnchanged
    63 )
    64     :
    65     CglCutGenerator(),
    66     nlp_(nlp),
    67     nSolve_(0),
    68     si_(si),
    69     cbcCutoffIncrement_(cbcCutoffIncrement),
    70     cbcIntegerTolerance_(cbcIntegerTolerance),
    71     localSearchNodeLimit_(0),
    72     maxLocalSearchPerNode_(0),
    73     maxLocalSearch_(0),
    74     maxLocalSearchTime_(3600),
    75     nLocalSearch_(0),
    76     solveAuxiliaryProblem_(solveAuxiliaryProblem),
    77     handler_(NULL),
    78     subMilpLogLevel_(0),
    79     leaveSiUnchanged_(leaveSiUnchanged),
    80     strategy_(NULL),
    81     timeBegin_(0),
    82     logFrequency_(1000.)
    83 {
    84   handler_ = new CoinMessageHandler();
    85   handler_ -> setLogLevel(2);
    86   messages_ = OaMessages();
    87   if(strategy)
    88     strategy_ = strategy->clone();
    89   timeBegin_ = CoinCpuTime();
    90 }
    91 
    92 OACutGenerator2::~OACutGenerator2()
    93 {
    94   delete handler_;
    95   if(strategy_)
    96     delete strategy_;
    97 }
     28  OACutGenerator2::OACutGenerator2():
     29      CglCutGenerator(),
     30      nlp_(NULL),
     31      nSolve_(0),
     32      si_(NULL),
     33      cbcCutoffIncrement_(1e-06),
     34      cbcIntegerTolerance_(1e-05),
     35      localSearchNodeLimit_(0),
     36      maxLocalSearchPerNode_(0),
     37      maxLocalSearch_(0),
     38      maxLocalSearchTime_(3600),
     39      nLocalSearch_(0),
     40      solveAuxiliaryProblem_(0),
     41      handler_(NULL),
     42      subMilpLogLevel_(0),
     43      leaveSiUnchanged_(0),
     44      strategy_(NULL),
     45      timeBegin_(0.),
     46      logFrequency_(1000.)
     47  {
     48    handler_ = new CoinMessageHandler();
     49    handler_ -> setLogLevel(2);
     50    messages_ = OaMessages();
     51    timeBegin_ = CoinCpuTime();
     52  }
     53
     54
     55
     56  OACutGenerator2::OACutGenerator2
     57  (OsiTMINLPInterface * nlp,
     58   OsiSolverInterface * si,
     59   CbcStrategy * strategy,
     60   double cbcCutoffIncrement,
     61   double cbcIntegerTolerance,
     62   bool solveAuxiliaryProblem,
     63   bool leaveSiUnchanged
     64  )
     65      :
     66      CglCutGenerator(),
     67      nlp_(nlp),
     68      nSolve_(0),
     69      si_(si),
     70      cbcCutoffIncrement_(cbcCutoffIncrement),
     71      cbcIntegerTolerance_(cbcIntegerTolerance),
     72      localSearchNodeLimit_(0),
     73      maxLocalSearchPerNode_(0),
     74      maxLocalSearch_(0),
     75      maxLocalSearchTime_(3600),
     76      nLocalSearch_(0),
     77      solveAuxiliaryProblem_(solveAuxiliaryProblem),
     78      handler_(NULL),
     79      subMilpLogLevel_(0),
     80      leaveSiUnchanged_(leaveSiUnchanged),
     81      strategy_(NULL),
     82      timeBegin_(0),
     83      logFrequency_(1000.)
     84  {
     85    handler_ = new CoinMessageHandler();
     86    handler_ -> setLogLevel(2);
     87    messages_ = OaMessages();
     88    if (strategy)
     89      strategy_ = strategy->clone();
     90    timeBegin_ = CoinCpuTime();
     91  }
     92
     93  OACutGenerator2::~OACutGenerator2()
     94  {
     95    delete handler_;
     96    if (strategy_)
     97      delete strategy_;
     98  }
    9899/// Assign an OsiTMINLPInterface
    99 void
    100 OACutGenerator2::assignNlpInterface(OsiTMINLPInterface * nlp)
    101 {
    102   nlp_ = nlp;
    103 }
     100  void
     101  OACutGenerator2::assignNlpInterface(OsiTMINLPInterface * nlp)
     102  {
     103    nlp_ = nlp;
     104  }
    104105
    105106/// Assign an OsiTMINLPInterface
    106 void
    107 OACutGenerator2::assignLpInterface(OsiSolverInterface * si)
    108 {
    109   si_ = si;
    110   if(maxLocalSearch_>0) {
    111     setTheNodeLimit();
     107  void
     108  OACutGenerator2::assignLpInterface(OsiSolverInterface * si)
     109  {
     110    si_ = si;
     111    if (maxLocalSearch_>0) {
     112      setTheNodeLimit();
     113    }
    112114  }
    113 }
    114 
    115 double OACutGenerator2::siBestObj(CbcModel * model) const
    116 {
    117   if(model == NULL) {
     115
     116  double OACutGenerator2::siBestObj(CbcModel * model) const
     117  {
     118    if (model == NULL) {
     119      //Check solver name to see if local searches can be performed
     120      std::string solverName;
     121      si_->getStrParam(OsiSolverName,solverName);
     122      //for cbc needs to get the first three letter of solver name
     123      std::string shortSolverName(solverName,0,3);
     124      if (shortSolverName == "cbc") {
     125        throw CoinError("OsiCbc is not supported for doing local searches use OsiClpSolverInterface instead",
     126            "OACutGenerator2","setTheNodeLimit");
     127      }
     128      else if (solverName == "cplex") {
     129#ifdef COIN_HAS_CPX
     130        OsiCpxSolverInterface * cpx = dynamic_cast<OsiCpxSolverInterface *>(si_);
     131        double value;
     132        int status = CPXgetbestobjval(cpx->getEnvironmentPtr(),cpx->getLpPtr(OsiCpxSolverInterface::KEEPCACHED_ALL), &value);
     133        if (status)
     134          throw CoinError("Error in getting CPLEX best bound","OACutGenerator2","siBestObj");
     135        return value;
     136#else
     137
     138        throw CoinError("You have to define COIN_HAS_CPX at compilation to be able to use cplex for local searches",
     139            "OACutGenerator2","siBestObj");
     140#endif
     141
     142      }
     143      else {
     144        std::string mesg="Unsuported solver";
     145        mesg += solverName;
     146        mesg +=" for local searches, you should use Cbc or Cplex";
     147        throw CoinError(mesg,
     148            "OACutGenerator2","assignLpInterface");
     149      }
     150    }
     151    else
     152      return model->getBestPossibleObjValue();
     153  }
     154  void OACutGenerator2::setTheNodeLimit()
     155  {
     156    //Check solver name to see if local searches can be performed
     157    std::string solverName;
     158    si_->getStrParam(OsiSolverName,solverName);
     159
     160    //for cbc needs to get the first three letter of solver name
     161    std::string shortSolverName(solverName,0,3);
     162    if (shortSolverName == "cbc") {
     163      throw CoinError("OsiCbc is not supported for doing local searches use OsiClpSolverInterface instead",
     164          "OACutGenerator2","setTheNodeLimit");
     165    }
     166    else if (solverName == "cplex") {
     167#ifdef COIN_HAS_CPX
     168      OsiCpxSolverInterface * cpx = dynamic_cast<OsiCpxSolverInterface *>(si_);
     169      CPXsetintparam(cpx->getEnvironmentPtr(),CPX_PARAM_NODELIM, localSearchNodeLimit_);
     170#else
     171
     172      throw CoinError("You have to define COIN_HAS_CPX at compilation to be able to use cplex for local searches",
     173          "OACutGenerator2","setTheNodeLimit");
     174#endif
     175
     176    }
     177    else if (solverName == "clp") {
     178      //do nothing will set up node limit when creating a CbcModel
     179    }
     180    else {
     181      std::string mesg="Unsuported solver";
     182      mesg += solverName;
     183      mesg +=" for local searches, you should use Cbc or Cplex";
     184      throw CoinError(mesg,
     185          "OACutGenerator2","setTheNodeLimit");
     186    }
     187  }
     188
     189
     190  void OACutGenerator2::setTimeLimit(double time) const
     191  {
    118192    //Check solver name to see if local searches can be performed
    119193    std::string solverName;
     
    121195    //for cbc needs to get the first three letter of solver name
    122196    std::string shortSolverName(solverName,0,3);
    123     if(shortSolverName == "cbc") {
     197    if (shortSolverName == "cbc") {
    124198      throw CoinError("OsiCbc is not supported for doing local searches use OsiClpSolverInterface instead",
    125199          "OACutGenerator2","setTheNodeLimit");
    126200    }
    127     else if(solverName == "cplex") {
     201    else if (solverName == "cplex") {
    128202#ifdef COIN_HAS_CPX
    129203      OsiCpxSolverInterface * cpx = dynamic_cast<OsiCpxSolverInterface *>(si_);
    130       double value;
    131       int status = CPXgetbestobjval(cpx->getEnvironmentPtr(),cpx->getLpPtr(OsiCpxSolverInterface::KEEPCACHED_ALL), &value);
    132       if(status)
    133         throw CoinError("Error in getting CPLEX best bound","OACutGenerator2","siBestObj");
    134       return value;
     204      CPXsetdblparam(cpx->getEnvironmentPtr(),CPX_PARAM_TILIM, time);
    135205#else
    136206
    137207      throw CoinError("You have to define COIN_HAS_CPX at compilation to be able to use cplex for local searches",
    138           "OACutGenerator2","siBestObj");
    139 #endif
    140 
     208          "OACutGenerator2","setTheNodeLimit");
     209#endif
     210
     211    }
     212    else if (solverName == "clp") {
     213      //do nothing will set up node limit when creating a CbcModel
    141214    }
    142215    else {
     
    145218      mesg +=" for local searches, you should use Cbc or Cplex";
    146219      throw CoinError(mesg,
    147           "OACutGenerator2","assignLpInterface");
     220          "OACutGenerator2","setTheNodeLimit");
    148221    }
    149222  }
    150   else
    151     return model->getBestPossibleObjValue();
    152 }
    153 void OACutGenerator2::setTheNodeLimit()
    154 {
    155   //Check solver name to see if local searches can be performed
    156   std::string solverName;
    157   si_->getStrParam(OsiSolverName,solverName);
    158 
    159   //for cbc needs to get the first three letter of solver name
    160   std::string shortSolverName(solverName,0,3);
    161   if(shortSolverName == "cbc") {
    162     throw CoinError("OsiCbc is not supported for doing local searches use OsiClpSolverInterface instead",
    163         "OACutGenerator2","setTheNodeLimit");
    164   }
    165   else if(solverName == "cplex") {
     223
     224  void OACutGenerator2::setCutoff(double bestKnown) const
     225  {
     226    //Check solver name to see if local searches can be performed
     227    std::string solverName;
     228    si_->getStrParam(OsiSolverName,solverName);
     229
     230    //for cbc needs to get the first three letter of solver name
     231    std::string shortSolverName(solverName,0,3);
     232    if (shortSolverName == "cbc") {
     233      throw CoinError("OsiCbc is not supported for doing local searches use OsiClpSolverInterface instead",
     234          "OACutGenerator2","setTheNodeLimit");
     235    }
     236    else if (solverName == "cplex") {
    166237#ifdef COIN_HAS_CPX
    167     OsiCpxSolverInterface * cpx = dynamic_cast<OsiCpxSolverInterface *>(si_);
    168     CPXsetintparam(cpx->getEnvironmentPtr(),CPX_PARAM_NODELIM, localSearchNodeLimit_);
     238      OsiCpxSolverInterface * cpx = dynamic_cast<OsiCpxSolverInterface *>(si_);
     239      CPXsetdblparam(cpx->getEnvironmentPtr(),CPX_PARAM_CUTUP, bestKnown);
    169240#else
    170241
    171     throw CoinError("You have to define COIN_HAS_CPX at compilation to be able to use cplex for local searches",
    172         "OACutGenerator2","setTheNodeLimit");
    173 #endif
    174 
    175   }
    176   else if(solverName == "clp") {
    177     //do nothing will set up node limit when creating a CbcModel
    178   }
    179   else {
    180     std::string mesg="Unsuported solver";
    181     mesg += solverName;
    182     mesg +=" for local searches, you should use Cbc or Cplex";
    183     throw CoinError(mesg,
    184         "OACutGenerator2","setTheNodeLimit");
    185   }
    186 }
    187 
    188 
    189 void OACutGenerator2::setTimeLimit(double time) const
    190 {
    191   //Check solver name to see if local searches can be performed
    192   std::string solverName;
    193   si_->getStrParam(OsiSolverName,solverName);
    194   //for cbc needs to get the first three letter of solver name
    195   std::string shortSolverName(solverName,0,3);
    196   if(shortSolverName == "cbc") {
    197     throw CoinError("OsiCbc is not supported for doing local searches use OsiClpSolverInterface instead",
    198         "OACutGenerator2","setTheNodeLimit");
    199   }
    200   else if(solverName == "cplex") {
    201 #ifdef COIN_HAS_CPX
    202     OsiCpxSolverInterface * cpx = dynamic_cast<OsiCpxSolverInterface *>(si_);
    203     CPXsetdblparam(cpx->getEnvironmentPtr(),CPX_PARAM_TILIM, time);
     242      throw CoinError("You have to define COIN_HAS_CPX at compilation to be able to use cplex for local searches",
     243          "OACutGenerator2","setTheNodeLimit");
     244#endif
     245
     246    }
     247    else if (solverName == "clp") {
     248      //do nothing will set up node limit when creating a CbcModel
     249    }
     250    else {
     251      std::string mesg="Unsuported solver";
     252      mesg += solverName;
     253      mesg +=" for local searches, you should use Cbc or Cplex";
     254      throw CoinError(mesg,
     255          "OACutGenerator2","setTheNodeLimit");
     256    }
     257  }/// cut generation method
     258  void
     259  OACutGenerator2::generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
     260      const CglTreeInfo info) const
     261  {
     262    CbcStrategy * strategy = strategy_;
     263    double lastPeriodicLog= CoinCpuTime();
     264
     265    if (nlp_ == NULL) {
     266      std::cerr<<"Error in cut generator for outer approximation no NLP ipopt assigned"<<std::endl;
     267      throw -1;
     268    }
     269
     270    //This node may already be fathomed by a previous call to this
     271    // this information is stored in babInfo
     272    OsiBabSolver * babInfo = dynamic_cast<OsiBabSolver *> (si.getAuxiliaryInfo());
     273#if 1
     274    //if algorithms would converge this should never happen and it seems very dangerous if somebody forgot to reset the bound
     275    if (babInfo)
     276      if (!babInfo->mipFeasible())
     277        return;
     278
     279#endif
     280
     281    const int numcols = nlp_->getNumCols();
     282
     283    //Get the continuous solution
     284    const double *colsol = si.getColSolution();
     285
     286    bool doLocalSearch = 0;
     287    bool isInteger = 1;
     288    //   nlp_->setMilpBound(-1e100);
     289    //   nlp_->setMilpFeasible(true);
     290
     291
     292    //Check integer infeasibility
     293    for (int i = 0 ; i < numcols ; i++) {
     294      if (nlp_->isInteger(i)) {
     295        if (fabs(colsol[i] - floor(colsol[i] + 0.5) ) >
     296            cbcIntegerTolerance_) {
     297          isInteger = 0;
     298          break;
     299        }
     300      }
     301    }
     302
     303    if (!isInteger) {
     304      if (nLocalSearch_<maxLocalSearch_ &&
     305          localSearchNodeLimit_ > 0 &&
     306          CoinCpuTime() - timeBegin_ < maxLocalSearchTime_)//do a local search
     307      {
     308        doLocalSearch = 1;
     309      }
     310      else {
     311        //        nlp_->setMilpBound(-1e100);
     312        //        nlp_->setMilpFeasible(true);
     313        if (strategy && ! strategy_)
     314          delete strategy;
     315        return;
     316      }
     317    }
     318
     319
     320    //We are going to generate some cuts copy LP information
     321
     322
     323    //get the current cutoff
     324    double cutoff;
     325    si.getDblParam(OsiDualObjectiveLimit, cutoff);
     326    double saveCutoff=cutoff;
     327
     328    // Save column bounds and basis
     329    double * saveColLb = new double[numcols];
     330    double * saveColUb = new double[numcols];
     331    CoinCopyN(nlp_->getColLower(), numcols , saveColLb);
     332    CoinCopyN(nlp_->getColUpper(), numcols , saveColUb);
     333    int originalRowNumber = (si_!=NULL) ?si_->getNumRows() : -1;
     334    CoinWarmStart * saveWarmStart = NULL;
     335    bool milpOptimal = 1;
     336
     337#ifdef NO_NULL_SI
     338    if (si_ == NULL) {
     339      std::cerr<<"Error in cut generator for outer approximation no lp solver interface assigned"<<std::endl;
     340      throw -1;
     341    }
    204342#else
    205343
    206     throw CoinError("You have to define COIN_HAS_CPX at compilation to be able to use cplex for local searches",
    207         "OACutGenerator2","setTheNodeLimit");
    208 #endif
    209 
    210   }
    211   else if(solverName == "clp") {
    212     //do nothing will set up node limit when creating a CbcModel
    213   }
    214   else {
    215     std::string mesg="Unsuported solver";
    216     mesg += solverName;
    217     mesg +=" for local searches, you should use Cbc or Cplex";
    218     throw CoinError(mesg,
    219         "OACutGenerator2","setTheNodeLimit");
    220   }
    221 }
    222 
    223 void OACutGenerator2::setCutoff(double bestKnown) const
    224 {
    225   //Check solver name to see if local searches can be performed
    226   std::string solverName;
    227   si_->getStrParam(OsiSolverName,solverName);
    228 
    229   //for cbc needs to get the first three letter of solver name
    230   std::string shortSolverName(solverName,0,3);
    231   if(shortSolverName == "cbc") {
    232     throw CoinError("OsiCbc is not supported for doing local searches use OsiClpSolverInterface instead",
    233         "OACutGenerator2","setTheNodeLimit");
    234   }
    235   else if(solverName == "cplex") {
    236 #ifdef COIN_HAS_CPX
    237     OsiCpxSolverInterface * cpx = dynamic_cast<OsiCpxSolverInterface *>(si_);
    238     CPXsetdblparam(cpx->getEnvironmentPtr(),CPX_PARAM_CUTUP, bestKnown);
    239 #else
    240 
    241     throw CoinError("You have to define COIN_HAS_CPX at compilation to be able to use cplex for local searches",
    242         "OACutGenerator2","setTheNodeLimit");
    243 #endif
    244 
    245   }
    246   else if(solverName == "clp") {
    247     //do nothing will set up node limit when creating a CbcModel
    248   }
    249   else {
    250     std::string mesg="Unsuported solver";
    251     mesg += solverName;
    252     mesg +=" for local searches, you should use Cbc or Cplex";
    253     throw CoinError(mesg,
    254         "OACutGenerator2","setTheNodeLimit");
    255   }
    256 }/// cut generation method
    257 void
    258 OACutGenerator2::generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
    259     const CglTreeInfo info) const
    260 {
    261   CbcStrategy * strategy = strategy_;
    262   double lastPeriodicLog= CoinCpuTime();
    263 
    264   if(nlp_ == NULL) {
    265     std::cerr<<"Error in cut generator for outer approximation no NLP ipopt assigned"<<std::endl;
    266     throw -1;
    267   }
    268 
    269   //This node may already be fathomed by a previous call to this
    270   // this information is stored in babInfo
    271   OsiBabSolver * babInfo = dynamic_cast<OsiBabSolver *> (si.getAuxiliaryInfo());
    272 #if 1
    273   //if algorithms would converge this should never happen and it seems very dangerous if somebody forgot to reset the bound
    274   if(babInfo)
    275     if(!babInfo->mipFeasible())
    276       return;
    277 
    278 #endif
    279 
    280   const int numcols = nlp_->getNumCols();
    281 
    282   //Get the continuous solution
    283   const double *colsol = si.getColSolution();
    284 
    285   bool doLocalSearch = 0;
    286   bool isInteger = 1;
    287   //   nlp_->setMilpBound(-1e100);
    288   //   nlp_->setMilpFeasible(true);
    289 
    290 
    291   //Check integer infeasibility
    292   for(int i = 0 ; i < numcols ; i++) {
    293     if(nlp_->isInteger(i)) {
    294       if(fabs(colsol[i] - floor(colsol[i] + 0.5) ) >
    295           cbcIntegerTolerance_) {
    296         isInteger = 0;
    297         break;
    298       }
    299     }
    300   }
    301 
    302   if(!isInteger) {
    303     if(nLocalSearch_<maxLocalSearch_ &&
    304         localSearchNodeLimit_ > 0 &&
    305         CoinCpuTime() - timeBegin_ < maxLocalSearchTime_)//do a local search
     344    bool deleteSi = false;
     345    if (si_ == NULL) {
     346      si_ = si.clone();
     347      deleteSi = true;
     348    }
     349    else
     350#endif
     351    if (si_!=&si)//We may have the same lp as the one passed by the model or a local copy
    306352    {
    307       doLocalSearch = 1;
     353
     354      //Install current active cuts into local solver
     355      int numberCutsToAdd = si.getNumRows();
     356      numberCutsToAdd -= si_->getNumRows();
     357      if (numberCutsToAdd > 0)//Have to install some cuts
     358      {
     359        CoinPackedVector * * addCuts = new CoinPackedVector *[numberCutsToAdd];
     360        for (int i = 0 ; i < numberCutsToAdd ; i++)
     361        {
     362          addCuts[i] = new CoinPackedVector;
     363        }
     364        //Get the current matrix and fill the addCuts
     365        const CoinPackedMatrix * mat = si.getMatrixByCol();
     366        const CoinBigIndex * start = mat->getVectorStarts();
     367        const int * length = mat->getVectorLengths();
     368        const double * elements = mat->getElements();
     369        const int * indices = mat->getIndices();
     370        for (int i = 0 ; i <= numcols ; i++)
     371          for (int k = start[i] ; k < start[i] + length[i] ; k++)
     372          {
     373            if (indices[k] >= si_->getNumRows()) {
     374              addCuts[ indices[k] - si_->getNumRows() ]->insert(i, elements[k]);
     375            }
     376          }
     377        si_->addRows(numberCutsToAdd, (const CoinPackedVectorBase * const *) addCuts, &si.getRowLower()[si_->getNumRows()],
     378            &si.getRowUpper()[si_->getNumRows()]);
     379      }
     380      else if (numberCutsToAdd < 0)//Oups some error
     381      {
     382        std::cerr<<"Internal error in OACutGenerator2 : number of cuts wrong"<<std::endl;
     383      }
     384
     385      //Set the bounds on columns
     386      for (int i = 0 ; i <= numcols ; i++)
     387      {
     388        si_->setColBounds(i, si.getColLower()[i], si.getColUpper()[i]);
     389      }
     390      //Install basis in problem
     391      CoinWarmStart * warm = si.getWarmStart();
     392      if (si_->setWarmStart(warm)==false)
     393      {
     394        delete warm;
     395        throw CoinError("Fail installing the warm start in the subproblem",
     396            "generateCuts","OACutGenerator2") ;
     397      }
     398      delete warm;
     399      //put the cutoff
     400      si_->setDblParam(OsiDualObjectiveLimit, cutoff);
     401      si_->resolve();
     402
     403#ifdef OA_DEBUG
     404
     405      std::cout<<"Resolve with hotstart :"<<std::endl
     406      <<"number of iterations(should be 0) : "<<si_->getIterationCount()<<std::endl
     407      <<"Objective value and diff to original : "<<si_->getObjValue()<<", "
     408      <<fabs(si_->getObjValue() - si.getObjValue())<<std::endl;
     409      for (int i = 0 ; i <= numcols ; i++)
     410      {
     411        if (fabs(si.getColSolution()[i]-si_->getColSolution()[i])>1e-08) {
     412          std::cout<<"Diff between solution at node and solution with local solver : "<<fabs(si.getColSolution()[i]-si_->getColSolution()[i])<<std::endl;
     413        }
     414      }
     415#endif
    308416    }
    309417    else {
    310       //          nlp_->setMilpBound(-1e100);
    311       //          nlp_->setMilpFeasible(true);
    312       if(strategy && ! strategy_)
    313         delete strategy;
    314       return;
    315     }
    316   }
    317 
    318 
    319   //We are going to generate some cuts copy LP information
    320 
    321 
    322   //get the current cutoff
    323   double cutoff;
    324   si.getDblParam(OsiDualObjectiveLimit, cutoff);
    325   double saveCutoff=cutoff;
    326 
    327   // Save column bounds and basis
    328   double * saveColLb = new double[numcols];
    329   double * saveColUb = new double[numcols];
    330   CoinCopyN(nlp_->getColLower(), numcols , saveColLb);
    331   CoinCopyN(nlp_->getColUpper(), numcols , saveColUb);
    332   int originalRowNumber = (si_!=NULL) ?si_->getNumRows() : -1;
    333   CoinWarmStart * saveWarmStart = NULL;
    334   bool milpOptimal = 1;
    335 
    336418#ifdef NO_NULL_SI
    337   if(si_ == NULL) {
    338     std::cerr<<"Error in cut generator for outer approximation no lp solver interface assigned"<<std::endl;
    339     throw -1;
    340   }
    341 #else
    342 
    343   bool deleteSi = false;
    344   if(si_ == NULL) {
    345     si_ = si.clone();
    346     deleteSi = true;
    347   }
    348   else
    349 #endif
    350   if(si_!=&si)//We may have the same lp as the one passed by the model or a local copy
    351   {
    352 
    353     //Install current active cuts into local solver
    354     int numberCutsToAdd = si.getNumRows();
    355     numberCutsToAdd -= si_->getNumRows();
    356     if(numberCutsToAdd > 0)//Have to install some cuts
     419      throw CoinError("Not allowed to modify si in a cutGenerator",
     420          "OACutGenerator2","generateCuts");
     421#else //Seems that nobody wants to allow me to do this
     422      if (leaveSiUnchanged_)
     423        saveWarmStart = si.getWarmStart();
     424#endif
     425    }
     426
     427    OsiClpSolverInterface * clp = dynamic_cast<OsiClpSolverInterface *>(si_);
     428    CbcModel * model = NULL;//We will need the model through all the function
     429    double milpBound = -DBL_MAX;
     430    bool milpFeasible = 1;
     431    //double milpBound=si_->getObjValue();
     432    bool feasible = 1;
     433
     434    if (feasible && doLocalSearch)//Perform a local search
    357435    {
    358       CoinPackedVector * * addCuts = new CoinPackedVector *[numberCutsToAdd];
    359       for(int i = 0 ; i < numberCutsToAdd ; i++)
     436      if (clp)//Clp does not do branch-and-bound have to create a CbcModel
    360437      {
    361         addCuts[i] = new CoinPackedVector;
    362       }
    363       //Get the current matrix and fill the addCuts
    364       const CoinPackedMatrix * mat = si.getMatrixByCol();
    365       const CoinBigIndex * start = mat->getVectorStarts();
    366       const int * length = mat->getVectorLengths();
    367       const double * elements = mat->getElements();
    368       const int * indices = mat->getIndices();
    369       for(int i = 0 ; i <= numcols ; i++)
    370         for(int k = start[i] ; k < start[i] + length[i] ; k++)
     438        OsiBabSolver empty;
     439        model = new CbcModel(*clp); // which clones
     440        OAModel = model;
     441        model->solver()->setAuxiliaryInfo(&empty);
     442
     443        //Change Cbc messages prefixes
     444        strcpy(model->messagesPointer()->source_,"OaCbc");
     445
     446        if (!strategy)
     447          strategy = new CbcStrategyDefault(1,0,0,subMilpLogLevel_);
     448
     449        clp->resolve();
     450        model->setLogLevel(subMilpLogLevel_);
     451        model->solver()->messageHandler()->setLogLevel(0);
     452        model->setStrategy(*strategy);
     453        model->setMaximumNodes(localSearchNodeLimit_);
     454        model->setMaximumSeconds(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
     455        model->setCutoff(cutoff);
     456        model->branchAndBound();
     457        milpBound = siBestObj(model);
     458        if (model->isProvenOptimal())
    371459        {
    372           if(indices[k] >= si_->getNumRows()) {
    373             addCuts[ indices[k] - si_->getNumRows() ]->insert(i, elements[k]);
    374           }
    375         }
    376       si_->addRows(numberCutsToAdd, (const CoinPackedVectorBase * const *) addCuts, &si.getRowLower()[si_->getNumRows()],
    377           &si.getRowUpper()[si_->getNumRows()]);
    378     }
    379     else if (numberCutsToAdd < 0)//Oups some error
    380     {
    381       std::cerr<<"Internal error in OACutGenerator2 : number of cuts wrong"<<std::endl;
    382     }
    383 
    384     //Set the bounds on columns
    385     for(int i = 0 ; i <= numcols ; i++)
    386     {
    387       si_->setColBounds(i, si.getColLower()[i], si.getColUpper()[i]);
    388     }
    389     //Install basis in problem
    390     CoinWarmStart * warm = si.getWarmStart();
    391     if(si_->setWarmStart(warm)==false)
    392     {
    393       delete warm;
    394       throw CoinError("Fail installing the warm start in the subproblem",
    395           "generateCuts","OACutGenerator2") ;
    396     }
    397     delete warm;
    398     //put the cutoff
    399     si_->setDblParam(OsiDualObjectiveLimit, cutoff);
    400     si_->resolve();
    401 
    402 #ifdef OA_DEBUG
    403 
    404     std::cout<<"Resolve with hotstart :"<<std::endl
    405     <<"number of iterations(should be 0) : "<<si_->getIterationCount()<<std::endl
    406     <<"Objective value and diff to original : "<<si_->getObjValue()<<", "
    407     <<fabs(si_->getObjValue() - si.getObjValue())<<std::endl;
    408     for(int i = 0 ; i <= numcols ; i++)
    409     {
    410       if(fabs(si.getColSolution()[i]-si_->getColSolution()[i])>1e-08) {
    411         std::cout<<"Diff between solution at node and solution with local solver : "<<fabs(si.getColSolution()[i]-si_->getColSolution()[i])<<std::endl;
    412       }
    413     }
    414 #endif
    415   }
    416   else {
    417 #ifdef NO_NULL_SI
    418     throw CoinError("Not allowed to modify si in a cutGenerator",
    419         "OACutGenerator2","generateCuts");
    420 #else //Seems that nobody wants to allow me to do this
    421     if(leaveSiUnchanged_)
    422       saveWarmStart = si.getWarmStart();
    423 #endif
    424   }
    425 
    426   OsiClpSolverInterface * clp = dynamic_cast<OsiClpSolverInterface *>(si_);
    427   CbcModel * model = NULL;//We will need the model through all the function
    428   double milpBound = -DBL_MAX;
    429   bool milpFeasible = 1;
    430   //double milpBound=si_->getObjValue();
    431   bool feasible = 1;
    432 
    433   if(feasible && doLocalSearch)//Perform a local search
    434   {
    435     if(clp)//Clp does not do branch-and-bound have to create a CbcModel
    436     {
    437       OsiBabSolver empty;
    438       model = new CbcModel(*clp); // which clones
    439       OAModel = model;
    440       model->solver()->setAuxiliaryInfo(&empty);
    441 
    442       //Change Cbc messages prefixes
    443       strcpy(model->messagesPointer()->source_,"OaCbc");
    444 
    445       if(!strategy)
    446         strategy = new CbcStrategyDefault(1,0,0,subMilpLogLevel_);
    447 
    448       clp->resolve();
    449       model->setLogLevel(subMilpLogLevel_);
    450       model->solver()->messageHandler()->setLogLevel(0);
    451       model->setStrategy(*strategy);
    452       model->setMaximumNodes(localSearchNodeLimit_);
    453       model->setMaximumSeconds(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
    454       model->setCutoff(cutoff);
    455       model->branchAndBound();
    456       milpBound = siBestObj(model);
    457       if(model->isProvenOptimal())
    458       {
    459         milpOptimal = 1;
    460       }
    461       else
    462         milpOptimal = 0;
    463       feasible = milpBound < cutoff;
    464       milpFeasible = feasible;
    465       isInteger = model->getSolutionCount();
    466       nLocalSearch_++;
    467 
    468       if(milpOptimal)
    469         handler_->message(SOLVED_LOCAL_SEARCH, messages_)<<model->getNodeCount()<<model->getIterationCount()<<CoinMessageEol;
    470       else
    471       {
    472         handler_->message(LOCAL_SEARCH_ABORT, messages_)<<model->getNodeCount()<<model->getIterationCount()<<CoinMessageEol;
    473         if(isInteger)
    474           std::cout<<"Integer feasible solution found"<<std::endl;
    475       }
    476     }
    477     else//use OsiSolverInterface::branchAndBound
    478     {
    479       setTimeLimit(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
    480       si_->messageHandler()->setLogLevel(subMilpLogLevel_);
    481       si_->branchAndBound();
    482       nLocalSearch_++;
    483       //Did we find any integer feasible solution
    484       isInteger = si_->getFractionalIndices().size() == 0;
    485       milpBound = siBestObj();
    486       feasible = milpBound < cutoff;
    487       milpFeasible = feasible;
    488     }
    489   }
    490   int numberPasses = 0;
    491   bool foundSolution = 0;
    492   while(isInteger && feasible ) {
    493     numberPasses++;
    494 
    495     //eventually give some information to user
    496     double time = CoinCpuTime();
    497     if(time - lastPeriodicLog > logFrequency_) {
    498       double lb = (model == NULL) ?si_->getObjValue():model->getBestPossibleObjValue();
    499       handler_->message(PERIODIC_MSG,messages_)
    500       <<time - timeBegin_<<cutoff
    501       <<lb
    502       <<CoinMessageEol;
    503       lastPeriodicLog = CoinCpuTime();
    504     }
    505 
    506 
    507     //setup the nlp
    508     int numberCutsBefore = cs.sizeRowCuts();
    509 
    510     bool fixed = true;
    511 
    512 #ifdef OA_DEBUG
    513   std::cout<<"FX_P   : ";
    514 #endif
    515   //Fix the variable which have to be fixed, after having saved the bounds
    516   for(int i = 0; i < numcols ; i++) {
    517       if(nlp_->isInteger(i)) {
    518         double value =  (model == NULL) ? si_->getColSolution()[i] : model->bestSolution()[i];
    519         if(saveColUb[i] < saveColLb[i] + cbcIntegerTolerance_)
    520           fixed = false;
    521       value = floor(value+0.5);
    522         value = max(saveColLb[i],value);
    523         value = min(value, saveColUb[i]);
    524         if(fabs(value) > 1e10) { std::cerr<<"FATAL ERROR: Variable taking a big value ("<<value
    525                                  <<") at optimium of LP relaxation, can not construct outer approximation. You should try running the problem with B-BB"<<std::endl;
    526          throw -1;
    527         }
    528 #ifdef OA_DEBUG
    529         //         printf("xx %d at %g (bounds %g, %g)",i,value,nlp_->getColLower()[i],
    530         //                nlp_->getColUpper()[i]);
    531         std::cout<<(int)value;
    532 #endif
    533         nlp_->setColLower(i,value);
    534         nlp_->setColUpper(i,value);
    535       }
    536     }
    537 #ifdef OA_DEBUG
    538     std::cout<<std::endl;
    539 #endif
    540     //Now solve the NLP get the cuts, and intall them in the local LP
    541 
    542     //  nlp_->turnOnIpoptOutput();
    543     nSolve_++;
    544     nlp_->resolve();
    545     if(nlp_->isProvenOptimal()) {
    546       nlp_->getOuterApproximation(cs);
    547       handler_->message(FEASIBLE_NLP, messages_)
    548       <<nlp_->getIterationCount()
    549       <<nlp_->getObjValue()<<CoinMessageEol;
    550 
    551 
    552 #ifdef OA_DEBUG
    553 
    554       const double * colsol2 = nlp_->getColSolution();
    555       for(int i = 0 ; i < numcols; i++) {
    556         if(nlp_->isInteger(i)) {
    557           if(fabs(colsol2[i] - floor(colsol2[i] + 0.5) ) >
    558               cbcIntegerTolerance_) {
    559             std::cerr<<"Integer infeasible point (should not be), integer infeasibility for variable "<<i
    560             <<" is, "<<fabs(colsol2[i] - floor(colsol2[i] + 0.5))<<std::endl;
    561             //              integerFeasible = 0;
    562           }
    563         }
    564       }
    565 #endif
    566 
    567       if((nlp_->getObjValue() < cutoff) ) {
    568         handler_->message(UPDATE_UB, messages_)
    569         <<nlp_->getObjValue()
    570         <<CoinCpuTime()-timeBegin_
    571         <<CoinMessageEol;
    572 
    573         foundSolution = 1;
    574 #if 1
    575         // Also store into solver
    576         if(babInfo) {
    577           double * lpSolution = new double[numcols + 1];
    578           CoinCopyN(nlp_->getColSolution(), numcols, lpSolution);
    579           lpSolution[numcols] = nlp_->getObjValue();
    580           babInfo->setSolution(lpSolution,
    581               numcols + 1, lpSolution[numcols]);
    582           delete [] lpSolution;
    583         }
    584         else {
    585           printf("No auxiliary info in nlp solve!\n");
    586           throw -1;
    587         }
    588 #endif
    589         // Update the cutoff
    590         cutoff = nlp_->getObjValue() *(1 - cbcCutoffIncrement_);
    591         // Update the lp solver cutoff
    592         si_->setDblParam(OsiDualObjectiveLimit, cutoff);
    593       }
    594     }
    595     else if(nlp_->isAbandoned() || nlp_->isIterationLimitReached()) {
    596       std::cerr<<"Unsolved NLP... exit"<<std::endl;
    597     }
    598     else {
    599       handler_->message(INFEASIBLE_NLP, messages_)
    600       <<nlp_->getIterationCount()
    601       <<CoinMessageEol;
    602       if(solveAuxiliaryProblem_)  //solve feasibility NLP and add corresponding outer approximation constraints
    603       {
    604         double *x = new double[numcols];
    605         int * ind = new int[numcols];
    606         int nInd = 0;
    607         for(int i = 0; i < numcols ; i++)
    608         {
    609           if(nlp_->isInteger(i)) {
    610             ind[nInd] = i;
    611             x[nInd++] = (model == NULL) ? si_->getColSolution()[i] : model->bestSolution()[i];
    612             //reset the bounds
    613             nlp_->setColBounds(i,saveColLb[i],saveColUb[i]);
    614           }
    615         }
    616         nlp_->getFeasibilityOuterApproximation(nInd, x, ind,cs);
    617         if(nlp_->isProvenOptimal())
    618         {
    619           assert((nlp_->getObjValue() > cbcIntegerTolerance_) );
    620           std::cout<<"Solved auxiliary infeasibility problem"<<std::endl;
    621         }
     460          milpOptimal = 1;
     461        }
     462        else
     463          milpOptimal = 0;
     464        feasible = milpBound < cutoff;
     465        milpFeasible = feasible;
     466        isInteger = model->getSolutionCount();
     467        nLocalSearch_++;
     468
     469        if (milpOptimal)
     470          handler_->message(SOLVED_LOCAL_SEARCH, messages_)<<model->getNodeCount()<<model->getIterationCount()<<CoinMessageEol;
    622471        else
    623472        {
    624           std::cout<<"Failed to solve auxiliary infeasibility problem"<<std::endl;
    625           bool * s = const_cast<bool *> (&solveAuxiliaryProblem_);
    626           *s =0;
    627         }
    628         delete []x;
    629         delete[]ind;
    630       }
    631       else
     473          handler_->message(LOCAL_SEARCH_ABORT, messages_)<<model->getNodeCount()<<model->getIterationCount()<<CoinMessageEol;
     474          if (isInteger)
     475            std::cout<<"Integer feasible solution found"<<std::endl;
     476        }
     477      }
     478      else//use OsiSolverInterface::branchAndBound
     479      {
     480        setTimeLimit(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
     481        si_->messageHandler()->setLogLevel(subMilpLogLevel_);
     482        si_->branchAndBound();
     483        nLocalSearch_++;
     484        //Did we find any integer feasible solution
     485        isInteger = si_->getFractionalIndices().size() == 0;
     486        milpBound = siBestObj();
     487        feasible = milpBound < cutoff;
     488        milpFeasible = feasible;
     489      }
     490    }
     491    int numberPasses = 0;
     492    bool foundSolution = 0;
     493    while (isInteger && feasible ) {
     494      numberPasses++;
     495
     496      //eventually give some information to user
     497      double time = CoinCpuTime();
     498      if (time - lastPeriodicLog > logFrequency_) {
     499        double lb = (model == NULL) ?si_->getObjValue():model->getBestPossibleObjValue();
     500        handler_->message(PERIODIC_MSG,messages_)
     501        <<time - timeBegin_<<cutoff
     502        <<lb
     503        <<CoinMessageEol;
     504        lastPeriodicLog = CoinCpuTime();
     505      }
     506
     507
     508      //setup the nlp
     509      int numberCutsBefore = cs.sizeRowCuts();
     510
     511      bool fixed = true;
     512
     513#ifdef OA_DEBUG
     514    std::cout<<"FX_P   : ";
     515#endif
     516    //Fix the variable which have to be fixed, after having saved the bounds
     517    for (int i = 0; i < numcols ; i++) {
     518        if (nlp_->isInteger(i)) {
     519          double value =  (model == NULL) ? si_->getColSolution()[i] : model->bestSolution()[i];
     520          if (saveColUb[i] < saveColLb[i] + cbcIntegerTolerance_)
     521            fixed = false;
     522        value = floor(value+0.5);
     523          value = max(saveColLb[i],value);
     524          value = min(value, saveColUb[i]);
     525          if (fabs(value) > 1e10) {
     526            std::cerr<<"FATAL ERROR: Variable taking a big value ("<<value
     527            <<") at optimium of LP relaxation, can not construct outer approximation. You should try running the problem with B-BB"<<std::endl;
     528            throw -1;
     529          }
     530#ifdef OA_DEBUG
     531          //         printf("xx %d at %g (bounds %g, %g)",i,value,nlp_->getColLower()[i],
     532          //                nlp_->getColUpper()[i]);
     533          std::cout<<(int)value;
     534#endif
     535          nlp_->setColLower(i,value);
     536          nlp_->setColUpper(i,value);
     537        }
     538      }
     539#ifdef OA_DEBUG
     540      std::cout<<std::endl;
     541#endif
     542      //Now solve the NLP get the cuts, and intall them in the local LP
     543
     544      //  nlp_->turnOnIpoptOutput();
     545      nSolve_++;
     546      nlp_->resolve();
     547      if (nlp_->isProvenOptimal()) {
    632548        nlp_->getOuterApproximation(cs);
    633     }
    634 
    635     //install the cuts in si_ reoptimize and check for integer feasibility
    636     // Code taken and adapted from CbcModel::solveWithCuts
    637     int numberCuts = cs.sizeRowCuts() - numberCutsBefore;
    638     if (numberCuts > 0) {
    639       CoinWarmStartBasis * basis
    640       = dynamic_cast<CoinWarmStartBasis*>(si_->getWarmStart()) ;
    641       assert(basis != NULL); // make sure not volume
    642       basis->resize(si_->getNumRows()+numberCuts,numcols + 1) ;
    643       for (int i = 0 ; i < numberCuts ; i++) {
    644         basis->setArtifStatus(si_->getNumRows()+i,
    645             CoinWarmStartBasis::basic) ;
    646       }
    647 
    648       const OsiRowCut ** addCuts = new const OsiRowCut * [numberCuts] ;
    649       for (int i = 0 ; i < numberCuts ; i++) {
    650         addCuts[i] = &cs.rowCut(i + numberCutsBefore) ;
    651       }
    652       si_->applyRowCuts(numberCuts,addCuts) ;
    653 
    654       delete [] addCuts ;
    655       if (si_->setWarmStart(basis) == false) {
     549        handler_->message(FEASIBLE_NLP, messages_)
     550        <<nlp_->getIterationCount()
     551        <<nlp_->getObjValue()<<CoinMessageEol;
     552
     553
     554#ifdef OA_DEBUG
     555
     556        const double * colsol2 = nlp_->getColSolution();
     557        for (int i = 0 ; i < numcols; i++) {
     558          if (nlp_->isInteger(i)) {
     559            if (fabs(colsol2[i] - floor(colsol2[i] + 0.5) ) >
     560                cbcIntegerTolerance_) {
     561              std::cerr<<"Integer infeasible point (should not be), integer infeasibility for variable "<<i
     562              <<" is, "<<fabs(colsol2[i] - floor(colsol2[i] + 0.5))<<std::endl;
     563              //                    integerFeasible = 0;
     564            }
     565          }
     566        }
     567#endif
     568
     569        if ((nlp_->getObjValue() < cutoff) ) {
     570          handler_->message(UPDATE_UB, messages_)
     571          <<nlp_->getObjValue()
     572          <<CoinCpuTime()-timeBegin_
     573          <<CoinMessageEol;
     574
     575          foundSolution = 1;
     576#if 1
     577          // Also store into solver
     578          if (babInfo) {
     579            double * lpSolution = new double[numcols + 1];
     580            CoinCopyN(nlp_->getColSolution(), numcols, lpSolution);
     581            lpSolution[numcols] = nlp_->getObjValue();
     582            babInfo->setSolution(lpSolution,
     583                numcols + 1, lpSolution[numcols]);
     584            delete [] lpSolution;
     585          }
     586          else {
     587            printf("No auxiliary info in nlp solve!\n");
     588            throw -1;
     589          }
     590#endif
     591          // Update the cutoff
     592          cutoff = nlp_->getObjValue() *(1 - cbcCutoffIncrement_);
     593          // Update the lp solver cutoff
     594          si_->setDblParam(OsiDualObjectiveLimit, cutoff);
     595        }
     596      }
     597      else if (nlp_->isAbandoned() || nlp_->isIterationLimitReached()) {
     598        std::cerr<<"Unsolved NLP... exit"<<std::endl;
     599      }
     600      else {
     601        handler_->message(INFEASIBLE_NLP, messages_)
     602        <<nlp_->getIterationCount()
     603        <<CoinMessageEol;
     604        if (solveAuxiliaryProblem_) //solve feasibility NLP and add corresponding outer approximation constraints
     605        {
     606          double *x = new double[numcols];
     607          int * ind = new int[numcols];
     608          int nInd = 0;
     609          for (int i = 0; i < numcols ; i++)
     610          {
     611            if (nlp_->isInteger(i)) {
     612              ind[nInd] = i;
     613              x[nInd++] = (model == NULL) ? si_->getColSolution()[i] : model->bestSolution()[i];
     614              //reset the bounds
     615              nlp_->setColBounds(i,saveColLb[i],saveColUb[i]);
     616            }
     617          }
     618          nlp_->getFeasibilityOuterApproximation(nInd, x, ind,cs);
     619          if (nlp_->isProvenOptimal())
     620          {
     621            assert((nlp_->getObjValue() > cbcIntegerTolerance_) );
     622            std::cout<<"Solved auxiliary infeasibility problem"<<std::endl;
     623          }
     624          else
     625          {
     626            std::cout<<"Failed to solve auxiliary infeasibility problem"<<std::endl;
     627            bool * s = const_cast<bool *> (&solveAuxiliaryProblem_);
     628            *s =0;
     629          }
     630          delete []x;
     631          delete[]ind;
     632        }
     633        else
     634          nlp_->getOuterApproximation(cs);
     635      }
     636
     637      //install the cuts in si_ reoptimize and check for integer feasibility
     638      // Code taken and adapted from CbcModel::solveWithCuts
     639      int numberCuts = cs.sizeRowCuts() - numberCutsBefore;
     640      if (numberCuts > 0) {
     641        CoinWarmStartBasis * basis
     642        = dynamic_cast<CoinWarmStartBasis*>(si_->getWarmStart()) ;
     643        assert(basis != NULL); // make sure not volume
     644        basis->resize(si_->getNumRows()+numberCuts,numcols + 1) ;
     645        for (int i = 0 ; i < numberCuts ; i++) {
     646          basis->setArtifStatus(si_->getNumRows()+i,
     647              CoinWarmStartBasis::basic) ;
     648        }
     649
     650        const OsiRowCut ** addCuts = new const OsiRowCut * [numberCuts] ;
     651        for (int i = 0 ; i < numberCuts ; i++) {
     652          addCuts[i] = &cs.rowCut(i + numberCutsBefore) ;
     653        }
     654        si_->applyRowCuts(numberCuts,addCuts) ;
     655
     656        delete [] addCuts ;
     657        if (si_->setWarmStart(basis) == false) {
     658          delete basis;
     659          throw CoinError("Fail setWarmStart() after cut installation.",
     660              "generateCuts","OACutGenerator2") ;
     661        }
    656662        delete basis;
    657         throw CoinError("Fail setWarmStart() after cut installation.",
    658             "generateCuts","OACutGenerator2") ;
    659       }
    660       delete basis;
    661       si_->resolve();
    662       double objvalue = si_->getObjValue();
    663       //milpBound = max(milpBound, si_->getObjValue());
    664       feasible = (si_->isProvenOptimal() &&
    665           !si_->isDualObjectiveLimitReached() && (objvalue<cutoff)) ;
    666       //if value of integers are unchanged then we have to get out
    667       bool changed = //!nlp_->isProvenOptimal()//if nlp_ is infeasible solution has necessarily changed
     663        si_->resolve();
     664        double objvalue = si_->getObjValue();
     665        //milpBound = max(milpBound, si_->getObjValue());
     666        feasible = (si_->isProvenOptimal() &&
     667            !si_->isDualObjectiveLimitReached() && (objvalue<cutoff)) ;
     668        //if value of integers are unchanged then we have to get out
     669        bool changed = //!nlp_->isProvenOptimal()//if nlp_ is infeasible solution has necessarily changed
    668670          !feasible;//if lp is infeasible we don't have to check anything
    669       const double * nlpSol = nlp_->getColSolution();
    670       const double * lpSol = si_->getColSolution();
    671       for(int i = 0; i < numcols && !changed; i++) {
    672         if(nlp_->isInteger(i) && fabs(nlpSol[i] - lpSol[i])>0.001)
    673           changed = 1;
    674       }
    675       if(changed) {
    676         isInteger = 1;
    677         for(int i = 0 ; i < numcols ; i++) {
    678           if(nlp_->isInteger(i)) {
    679             if(fabs(lpSol[i] - floor(lpSol[i] + 0.5) ) > cbcIntegerTolerance_ ) {
    680               isInteger = 0;
     671        const double * nlpSol = nlp_->getColSolution();
     672        const double * lpSol = si_->getColSolution();
     673        for (int i = 0; i < numcols && !changed; i++) {
     674          if (nlp_->isInteger(i) && fabs(nlpSol[i] - lpSol[i])>0.001)
     675            changed = 1;
     676        }
     677        if (changed) {
     678          isInteger = 1;
     679          for (int i = 0 ; i < numcols ; i++) {
     680            if (nlp_->isInteger(i)) {
     681              if (fabs(lpSol[i] - floor(lpSol[i] + 0.5) ) > cbcIntegerTolerance_ ) {
     682                isInteger = 0;
     683                break;
     684              }
     685            }
     686          }
     687        }
     688        else {
     689          isInteger = 0;
     690          //      if(!fixed)//fathom on bounds
     691          milpBound = 1e200;
     692        }
     693#ifdef OA_DEBUG
     694
     695        printf("Obj value after cuts %g %d rows\n",si_->getObjValue(),
     696            numberCuts) ;
     697#endif
     698        //do we perform a new local search ?
     699        if (milpOptimal && feasible && !isInteger &&
     700            nLocalSearch_ < maxLocalSearch_ &&
     701            numberPasses < maxLocalSearchPerNode_ &&
     702            localSearchNodeLimit_ > 0 &&
     703            CoinCpuTime() - timeBegin_ < maxLocalSearchTime_) {
     704          std::cout<<"Perform new local search"<<std::endl;
     705          if (clp==NULL) {
     706            nLocalSearch_++;
     707
     708            setTimeLimit(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
     709            setCutoff(cutoff);
     710            si_->branchAndBound();
     711            //Did we find any integer feasible solution
     712            milpBound = siBestObj();
     713            //If integer solution is the same as nlp solution problem is solved
     714            changed = !nlp_->isProvenOptimal();
     715            for (int i = 0; i < numcols && !changed; i++) {
     716              if (nlp_->isInteger(i) && fabs(nlp_->getColSolution()[i] - si_->getColSolution()[i])>cbcIntegerTolerance_)
     717                changed = 1;
     718            }
     719            if (changed) {
     720              feasible = (milpBound < cutoff);
     721              std::cout<<"milp bound "<<milpBound<<" cutoff "<<cutoff<<std::endl;
     722            }
     723            else {
     724              feasible = 0;
     725              milpBound = 1e50;
     726            }
     727            isInteger = si_->getFractionalIndices().size() == 0;
     728          }/** endif solved by branchAndBound capable OsiInterface*/
     729          else {
     730            if (model) {
     731              OAModel = NULL;
     732              delete model;
     733            }
     734            model = new CbcModel(*clp); // which clones
     735            OAModel = model;
     736            OsiBabSolver empty;
     737            model->solver()->setAuxiliaryInfo(&empty);
     738            //Change Cbc messages prefixes
     739            strcpy(model->messagesPointer()->source_,"OaCbc");
     740            model->solver()->messageHandler()->setLogLevel(0);
     741
     742            if (!strategy)
     743              strategy = new CbcStrategyDefault(1,0,0, subMilpLogLevel_);
     744            model->setLogLevel(subMilpLogLevel_);
     745            model->setStrategy(*strategy);
     746            model->setMaximumNodes(localSearchNodeLimit_);
     747            model->setMaximumSeconds(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
     748            model->setCutoff(cutoff);
     749            model->branchAndBound();
     750            nLocalSearch_++;
     751            milpBound = siBestObj(model);
     752            handler_->message(SOLVED_LOCAL_SEARCH, messages_)<<model->getNodeCount()<<model->getIterationCount()<<CoinMessageEol;
     753            feasible =  (milpBound < cutoff);
     754            isInteger = model->getSolutionCount();
     755            if (model->isProvenOptimal() || model->isProvenInfeasible()) {
     756              bool changed = 0;           //If integer solution is the same as nlp solution problem is solved
     757              for (int i = 0; feasible && isInteger && i < numcols && !changed; i++) {
     758                if (nlp_->isInteger(i) && fabs(nlp_->getColSolution()[i] - model->bestSolution()[i])>cbcIntegerTolerance_)
     759                  changed = 1;
     760              }
     761              if (!changed) {
     762                feasible = 0;
     763                milpBound = 1e50;
     764              }
     765              milpFeasible = feasible;
     766            }
     767            else {
     768              std::cout<<"Exiting on time limit"<<std::endl;
     769              milpOptimal = 0;
     770              //feasible = 1;
    681771              break;
    682772            }
    683           }
    684         }
    685       }
    686       else {
    687         isInteger = 0;
    688         //        if(!fixed)//fathom on bounds
    689         milpBound = 1e200;
    690       }
    691 #ifdef OA_DEBUG
    692 
    693       printf("Obj value after cuts %g %d rows\n",si_->getObjValue(),
    694           numberCuts) ;
    695 #endif
    696       //do we perform a new local search ?
    697       if(milpOptimal && feasible && !isInteger &&
    698           nLocalSearch_ < maxLocalSearch_ &&
    699           numberPasses < maxLocalSearchPerNode_ &&
    700           localSearchNodeLimit_ > 0 &&
    701           CoinCpuTime() - timeBegin_ < maxLocalSearchTime_) {
    702          std::cout<<"Perform new local search"<<std::endl;
    703         if(clp==NULL) {
    704           nLocalSearch_++;
    705 
    706           setTimeLimit(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
    707           setCutoff(cutoff);
    708           si_->branchAndBound();
    709           //Did we find any integer feasible solution
    710           milpBound = siBestObj();
    711           //If integer solution is the same as nlp solution problem is solved
    712           changed = !nlp_->isProvenOptimal();
    713           for(int i = 0; i < numcols && !changed; i++) {
    714             if(nlp_->isInteger(i) && fabs(nlp_->getColSolution()[i] - si_->getColSolution()[i])>cbcIntegerTolerance_)
    715               changed = 1;
    716           }
    717           if(changed) {
    718             feasible = (milpBound < cutoff);
    719             std::cout<<"milp bound "<<milpBound<<" cutoff "<<cutoff<<std::endl;
    720           }
    721           else
    722            {
     773
     774          }/** endif solved by clp/cbc*/
     775
     776          if (milpBound < cutoff)
     777            handler_->message(UPDATE_LB, messages_)
     778            <<milpBound<<CoinCpuTime() - timeBegin_
     779            <<CoinMessageEol;
     780          else {
     781            milpBound = 1e50;
    723782            feasible = 0;
    724             milpBound = 1e50;
    725            }
    726           isInteger = si_->getFractionalIndices().size() == 0;
    727         }/** endif solved by branchAndBound capable OsiInterface*/
    728         else {
    729           if(model)
    730             {
    731               OAModel = NULL;       
    732               delete model;
    733             }
    734           model = new CbcModel(*clp); // which clones
    735           OAModel = model;
    736           OsiBabSolver empty;
    737           model->solver()->setAuxiliaryInfo(&empty);
    738           //Change Cbc messages prefixes
    739           strcpy(model->messagesPointer()->source_,"OaCbc");
    740           model->solver()->messageHandler()->setLogLevel(0);
    741 
    742           if(!strategy)
    743             strategy = new CbcStrategyDefault(1,0,0, subMilpLogLevel_);
    744           model->setLogLevel(subMilpLogLevel_);
    745           model->setStrategy(*strategy);
    746           model->setMaximumNodes(localSearchNodeLimit_);
    747           model->setMaximumSeconds(maxLocalSearchTime_ + timeBegin_ - CoinCpuTime());
    748           model->setCutoff(cutoff);
    749           model->branchAndBound();
    750           nLocalSearch_++;
    751           milpBound = siBestObj(model);
    752           handler_->message(SOLVED_LOCAL_SEARCH, messages_)<<model->getNodeCount()<<model->getIterationCount()<<CoinMessageEol;
    753           feasible =  (milpBound < cutoff);
    754           isInteger = model->getSolutionCount();
    755           if(model->isProvenOptimal() || model->isProvenInfeasible()) {
    756             bool changed = 0;             //If integer solution is the same as nlp solution problem is solved
    757             for(int i = 0; feasible && isInteger && i < numcols && !changed; i++) {
    758               if(nlp_->isInteger(i) && fabs(nlp_->getColSolution()[i] - model->bestSolution()[i])>cbcIntegerTolerance_)
    759                 changed = 1;
    760             }
    761           if(!changed) {
    762             feasible = 0;
    763             milpBound = 1e50;
    764            }
    765             milpFeasible = feasible;
    766           }
    767           else {
    768             std::cout<<"Exiting on time limit"<<std::endl;
    769             milpOptimal = 0;
    770             //feasible = 1;
    771             break;
    772           }
    773 
    774         }/** endif solved by clp/cbc*/
    775 
    776         if(milpBound < cutoff)
    777           handler_->message(UPDATE_LB, messages_)
    778           <<milpBound<<CoinCpuTime() - timeBegin_
    779           <<CoinMessageEol;
    780         else
     783            handler_->message(OASUCCESS, messages_)
     784            <<CoinCpuTime() - timeBegin_ <<CoinMessageEol;
     785          }
     786        }/** endif localSearch*/
     787        else if (model!=NULL)/** have to delete model for next iteration*/
    781788        {
    782           milpBound = 1e50;
    783           feasible = 0;
    784           handler_->message(OASUCCESS, messages_)
    785           <<CoinCpuTime() - timeBegin_ <<CoinMessageEol;
    786         }
    787       }/** endif localSearch*/
    788       else if(model!=NULL)/** have to delete model for next iteration*/
    789       {
    790         delete model;
    791         OAModel = NULL;
    792         model=NULL;
    793       }
    794 
    795     }
    796 
    797 
    798 
    799   }
     789          delete model;
     790          OAModel = NULL;
     791          model=NULL;
     792        }
     793
     794      }
     795
     796
     797
     798    }
    800799#ifdef OA_DEBUG
    801800    std::cout<<"-------------------------------------------------------------------------------------------------------------------------"<<std::endl;
    802801    std::cout<<"OA cut generation finished"<<std::endl;
    803802    std::cout<<"Generated "<<cs.sizeRowCuts()<<std::endl;
    804     if(foundSolution)
     803    if (foundSolution)
    805804      std::cout <<"Found NLP-integer feasible solution of  value : "<<cutoff<<std::endl;
    806805    std::cout<<"Current MILP lower bound is : "<<milpBound<<std::endl;
     
    810809    //Transmit the bound found by the milp
    811810    {
    812       if(milpBound>-1e100)
     811      if (milpBound>-1e100)
    813812      {
    814813#if 1
     
    821820    }  //Clean everything :
    822821
    823   //free model
    824   if(model!= NULL) {
    825     delete model;
     822    //free model
     823    if (model!= NULL) {
     824      delete model;
     825    }
     826
     827
     828
     829    //  Reset bounds in the NLP
     830
     831    for (int i = 0; i < numcols ; i++) {
     832      if (nlp_->isInteger(i)) {
     833        nlp_->setColBounds(i,saveColLb[i],saveColUb[i]);
     834      }
     835    }
     836#ifndef NO_NULL_SI
     837    if (deleteSi) {
     838      delete si_;
     839      si_ = NULL;
     840    }
     841    else
     842#endif
     843{
     844      if (leaveSiUnchanged_) {
     845        int nRowsToDelete = si_->getNumRows() - originalRowNumber;
     846        int * rowsToDelete = new int[nRowsToDelete];
     847        for (int i = 0 ; i < nRowsToDelete ; i++) {
     848          rowsToDelete[i] = i + originalRowNumber;
     849        }
     850        si_->deleteRows(nRowsToDelete, rowsToDelete);
     851        delete [] rowsToDelete;
     852        if (si_==&si) {
     853          si_->setDblParam(OsiDualObjectiveLimit, saveCutoff);
     854          if (si_->setWarmStart(saveWarmStart)==false) {
     855            throw CoinError("Fail restoring the warm start at the end of procedure",
     856                "generateCuts","OACutGenerator2") ;
     857          }
     858          delete saveWarmStart;
     859        }
     860      }
    826861  }
    827862
    828 
    829 
    830   //  Reset bounds in the NLP
    831 
    832   for(int i = 0; i < numcols ; i++) {
    833     if(nlp_->isInteger(i)) {
    834       nlp_->setColBounds(i,saveColLb[i],saveColUb[i]);
    835     }
    836   }
    837 #ifndef NO_NULL_SI
    838   if(deleteSi) {
    839     delete si_;
    840     si_ = NULL;
    841   }
    842   else
    843 #endif
    844    {
    845     if(leaveSiUnchanged_) {
    846       int nRowsToDelete = si_->getNumRows() - originalRowNumber;
    847       int * rowsToDelete = new int[nRowsToDelete];
    848       for(int i = 0 ; i < nRowsToDelete ; i++) {
    849         rowsToDelete[i] = i + originalRowNumber;
    850       }
    851       si_->deleteRows(nRowsToDelete, rowsToDelete);
    852       delete [] rowsToDelete;
    853       if(si_==&si) {
    854         si_->setDblParam(OsiDualObjectiveLimit, saveCutoff);
    855         if(si_->setWarmStart(saveWarmStart)==false) {
    856           throw CoinError("Fail restoring the warm start at the end of procedure",
    857               "generateCuts","OACutGenerator2") ;
    858         }
    859         delete saveWarmStart;
    860       }
    861     }
    862 }
    863 
    864 delete [] saveColLb;
    865 delete [] saveColUb;
    866 if(strategy && ! strategy_)
    867   delete strategy;
     863  delete [] saveColLb;
     864  delete [] saveColUb;
     865  if (strategy && ! strategy_)
     866    delete strategy;
    868867}
    869868}
  • branches/devel/Bonmin/src/OaInterface/BonOACutGenerator2.hpp

    r58 r62  
    2020#include "CoinTime.hpp"
    2121
    22 namespace Bonmin{
    23 class OACutGenerator2 : public CglCutGenerator
     22namespace Bonmin
    2423{
    25 public:
    26   typedef enum subSolver {Clp, Cbc, Cplex, Other};
    27   /// Default constructor
    28   OACutGenerator2();
    29   /// Usefull constructor
    30   OACutGenerator2(OsiTMINLPInterface * nlp = NULL,
    31       OsiSolverInterface * si = NULL,
    32       CbcStrategy * strategy = NULL,
    33       double cbcCutoffIncrement_=1e-07,
    34       double cbcIntegerTolerance = 1e-05,
    35       bool solveAuxiliaryProblem = 1,
    36       bool leaveSiUnchanged = 0
    37                       );
     24  class OACutGenerator2 : public CglCutGenerator
     25  {
     26  public:
     27    typedef enum subSolver {Clp, Cbc, Cplex, Other};
     28    /// Default constructor
     29    OACutGenerator2();
     30    /// Usefull constructor
     31    OACutGenerator2(OsiTMINLPInterface * nlp = NULL,
     32        OsiSolverInterface * si = NULL,
     33        CbcStrategy * strategy = NULL,
     34        double cbcCutoffIncrement_=1e-07,
     35        double cbcIntegerTolerance = 1e-05,
     36        bool solveAuxiliaryProblem = 1,
     37        bool leaveSiUnchanged = 0
     38                   );
    3839
    39   /// Copy constructor
    40   OACutGenerator2(const OACutGenerator2 &copy)
    41       :nlp_(copy.nlp_),
    42       si_(copy.si_),
    43       cbcCutoffIncrement_(copy.cbcCutoffIncrement_),
    44       cbcIntegerTolerance_(copy.cbcIntegerTolerance_),
    45       localSearchNodeLimit_(copy.localSearchNodeLimit_),
    46       maxLocalSearchPerNode_(copy.maxLocalSearchPerNode_),
    47       maxLocalSearch_(copy.maxLocalSearch_),
    48       maxLocalSearchTime_(copy.maxLocalSearchTime_),
    49       nLocalSearch_(copy.nLocalSearch_),
    50       solveAuxiliaryProblem_(copy.solveAuxiliaryProblem_),
    51       handler_(NULL), messages_(copy.messages_),
    52       subMilpLogLevel_(copy.subMilpLogLevel_),
    53       leaveSiUnchanged_(copy.leaveSiUnchanged_),
    54       strategy_(NULL),
    55       timeBegin_(0.),
    56       logFrequency_(copy.logFrequency_)
    57   {
    58     handler_ = new CoinMessageHandler();
    59     handler_->setLogLevel(copy.handler_->logLevel());
    60     if(copy.strategy_)
    61       strategy_ = copy.strategy_->clone();
    62     timeBegin_ = CoinCpuTime();
    63   }
    64   /// Destructor
    65   ~OACutGenerator2();
     40    /// Copy constructor
     41    OACutGenerator2(const OACutGenerator2 &copy)
     42        :nlp_(copy.nlp_),
     43        si_(copy.si_),
     44        cbcCutoffIncrement_(copy.cbcCutoffIncrement_),
     45        cbcIntegerTolerance_(copy.cbcIntegerTolerance_),
     46        localSearchNodeLimit_(copy.localSearchNodeLimit_),
     47        maxLocalSearchPerNode_(copy.maxLocalSearchPerNode_),
     48        maxLocalSearch_(copy.maxLocalSearch_),
     49        maxLocalSearchTime_(copy.maxLocalSearchTime_),
     50        nLocalSearch_(copy.nLocalSearch_),
     51        solveAuxiliaryProblem_(copy.solveAuxiliaryProblem_),
     52        handler_(NULL), messages_(copy.messages_),
     53        subMilpLogLevel_(copy.subMilpLogLevel_),
     54        leaveSiUnchanged_(copy.leaveSiUnchanged_),
     55        strategy_(NULL),
     56        timeBegin_(0.),
     57        logFrequency_(copy.logFrequency_)
     58    {
     59      handler_ = new CoinMessageHandler();
     60      handler_->setLogLevel(copy.handler_->logLevel());
     61      if (copy.strategy_)
     62        strategy_ = copy.strategy_->clone();
     63      timeBegin_ = CoinCpuTime();
     64    }
     65    /// Destructor
     66    ~OACutGenerator2();
    6667
    67   /// Assign an OsiTMINLPInterface
    68   void assignNlpInterface(OsiTMINLPInterface * nlp);
     68    /// Assign an OsiTMINLPInterface
     69    void assignNlpInterface(OsiTMINLPInterface * nlp);
    6970
    70   /// Assign an OsiTMINLPInterface
    71   void assignLpInterface(OsiSolverInterface * si);
     71    /// Assign an OsiTMINLPInterface
     72    void assignLpInterface(OsiSolverInterface * si);
    7273
    73   void setStrategy(const CbcStrategy & strategy)
    74   {
    75     if(strategy_)
    76       delete strategy_;
    77     strategy_ = strategy.clone();
    78   }
    79   /// cut generation method
    80   virtual void generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
    81       const CglTreeInfo info = CglTreeInfo()) const;
     74    void setStrategy(const CbcStrategy & strategy)
     75    {
     76      if (strategy_)
     77        delete strategy_;
     78      strategy_ = strategy.clone();
     79    }
     80    /// cut generation method
     81    virtual void generateCuts( const OsiSolverInterface & si, OsiCuts & cs,
     82        const CglTreeInfo info = CglTreeInfo()) const;
    8283
    83   virtual CglCutGenerator * clone() const
    84   {
    85     return new OACutGenerator2(*this);
    86   }
     84    virtual CglCutGenerator * clone() const
     85    {
     86      return new OACutGenerator2(*this);
     87    }
    8788
    88   inline int getNSolve()
    89   {
    90     return nSolve_;
    91   }
    92   /// Set value for cutoff increment
    93   void setcbcCutoffIncrement (double value)
    94   {
    95     cbcCutoffIncrement_ = value;
    96   }
    97   /// Set value for integer tolerance
    98   void setcbcIntegerTolerance (double value)
    99   {
    100     cbcIntegerTolerance_ = value;
    101   }
    102   ///set max number of nodes for local search
    103   void setLocalSearchNodeLimit(int value)
    104   {
    105     localSearchNodeLimit_ = value;
    106     if(si_)
    107       setTheNodeLimit();
    108   }
    109   ///set max number of local searches per node
    110   void setMaxLocalSearchPerNode(int value)
    111   {
    112     maxLocalSearchPerNode_ = value;
    113   }
    114   ///set total max number of local searches
    115   void setMaxLocalSearch(int value)
    116   {
    117     maxLocalSearch_ = value;
    118   }
     89    inline int getNSolve()
     90    {
     91      return nSolve_;
     92    }
     93    /// Set value for cutoff increment
     94    void setcbcCutoffIncrement (double value)
     95    {
     96      cbcCutoffIncrement_ = value;
     97    }
     98    /// Set value for integer tolerance
     99    void setcbcIntegerTolerance (double value)
     100    {
     101      cbcIntegerTolerance_ = value;
     102    }
     103    ///set max number of nodes for local search
     104    void setLocalSearchNodeLimit(int value)
     105    {
     106      localSearchNodeLimit_ = value;
     107      if (si_)
     108        setTheNodeLimit();
     109    }
     110    ///set max number of local searches per node
     111    void setMaxLocalSearchPerNode(int value)
     112    {
     113      maxLocalSearchPerNode_ = value;
     114    }
     115    ///set total max number of local searches
     116    void setMaxLocalSearch(int value)
     117    {
     118      maxLocalSearch_ = value;
     119    }
    119120
    120   void setMaxLocalSearchTime(double time)
    121   {
    122     maxLocalSearchTime_ = time;
    123   }
    124   /**set log level */
    125   void setLogLevel(int value)
    126   {
    127     handler_->setLogLevel(value);
    128   }
    129   /** Set log frequency.*/
    130   void setLogFrequency(double value)
    131   {
    132     logFrequency_ = value;
    133   }
    134   /**set log level */
    135   void setSubMilpLogLevel(int value)
    136   {
    137     subMilpLogLevel_ = value;
    138   }
    139 private:
    140   /// Set the node limit to the interface
    141   void setTheNodeLimit();
    142   /// Set the time limit for b&b
    143   void setTimeLimit(double time) const;
    144   /// Set the cutoff for b&b
    145   void setCutoff(double cutoff) const;
    146   /// Get bound on the solution value after doing partial local search
    147   double siBestObj(CbcModel * model=NULL) const;
    148   /// Pointer to the Ipopt interface
    149   OsiTMINLPInterface * nlp_;
    150   ///Number of NLP resolution done
    151   mutable int nSolve_;
    152   /// A linear solver
    153   mutable OsiSolverInterface * si_;
    154   /// cutoff min increase (has to be intialized trhough Cbc)
    155   double cbcCutoffIncrement_;
    156   /// integer tolerance (has to be the same as Cbc's)
    157   double cbcIntegerTolerance_;
    158   ///Max number of nodes for local search
    159   int localSearchNodeLimit_;
    160   ///Max number of local searches per node
    161   int maxLocalSearchPerNode_;
    162   ///Total max number of local searches
    163   int maxLocalSearch_;
    164   /// maximum time for local searches
    165   double maxLocalSearchTime_;
    166   ///number of local searches performed
    167   mutable int nLocalSearch_;
    168   ///set to 1 to solve  an auxiliary NLP when infeasible assignment is encountered
    169   bool solveAuxiliaryProblem_;
    170   /** messages handler. */
    171   CoinMessageHandler * handler_;
    172   /** handler */
    173   CoinMessages messages_;
    174   /** sub milp log level.*/
    175   int subMilpLogLevel_;
    176   /** Wether or not we should remove cuts at the end of the procedure */
    177   bool leaveSiUnchanged_;
    178   /** Strategy to apply when using Cbc as MILP sub-solver.*/
    179   CbcStrategy * strategy_;
    180   /** time of construction*/
    181   double timeBegin_;
    182   /** Frequency of log. */
    183   double logFrequency_;
    184 };
     121    void setMaxLocalSearchTime(double time)
     122    {
     123      maxLocalSearchTime_ = time;
     124    }
     125    /**set log level */
     126    void setLogLevel(int value)
     127    {
     128      handler_->setLogLevel(value);
     129    }
     130    /** Set log frequency.*/
     131    void setLogFrequency(double value)
     132    {
     133      logFrequency_ = value;
     134    }
     135    /**set log level */
     136    void setSubMilpLogLevel(int value)
     137    {
     138      subMilpLogLevel_ = value;
     139    }
     140  private:
     141    /// Set the node limit to the interface
     142    void setTheNodeLimit();
     143    /// Set the time limit for b&b
     144    void setTimeLimit(double time) const;
     145    /// Set the cutoff for b&b
     146    void setCutoff(double cutoff) const;
     147    /// Get bound on the solution value after doing partial local search
     148    double siBestObj(CbcModel * model=NULL) const;
     149    /// Pointer to the Ipopt interface
     150    OsiTMINLPInterface * nlp_;
     151    ///Number of NLP resolution done
     152    mutable int nSolve_;
     153    /// A linear solver
     154    mutable OsiSolverInterface * si_;
     155    /// cutoff min increase (has to be intialized trhough Cbc)
     156    double cbcCutoffIncrement_;
     157    /// integer tolerance (has to be the same as Cbc's)
     158    double cbcIntegerTolerance_;
     159    ///Max number of nodes for local search
     160    int localSearchNodeLimit_;
     161    ///Max number of local searches per node
     162    int maxLocalSearchPerNode_;
     163    ///Total max number of local searches
     164    int maxLocalSearch_;
     165    /// maximum time for local searches
     166    double maxLocalSearchTime_;
     167    ///number of local searches performed
     168    mutable int nLocalSearch_;
     169    ///set to 1 to solve  an auxiliary NLP when infeasible assignment is encountered
     170    bool solveAuxiliaryProblem_;
     171    /** messages handler. */
     172    CoinMessageHandler * handler_;
     173    /** handler */
     174    CoinMessages messages_;
     175    /** sub milp log level.*/
     176    int subMilpLogLevel_;
     177    /** Wether or not we should remove cuts at the end of the procedure */
     178    bool leaveSiUnchanged_;
     179    /** Strategy to apply when using Cbc as MILP sub-solver.*/
     180    CbcStrategy * strategy_;
     181    /** time of construction*/
     182    double timeBegin_;
     183    /** Frequency of log. */
     184    double logFrequency_;
     185  };
    185186}
    186187#endif
  • branches/devel/Bonmin/src/OaInterface/BonOAMessages.cpp

    r58 r62  
    1111#include "BonOAMessages.hpp"
    1212
    13 namespace Bonmin{
     13namespace Bonmin
     14{
    1415
    15 OaMessages::OaMessages():
    16     CoinMessages(DUMMY_END)
    17 {
    18   strcpy(source_,"OA");
    19   addMessage(FEASIBLE_NLP,CoinOneMessage( 1, 2,"Solved NLP in %d iterations, found a feasible solution of value %f."));
    20   addMessage(INFEASIBLE_NLP, CoinOneMessage(2,2,"Solved NLP in %d iterations, problem is infeasible in subspace."));
    21   addMessage(UPDATE_UB, CoinOneMessage(3,1,"New best feasible of %g found after %g sec."));
    22   addMessage(SOLVED_LOCAL_SEARCH, CoinOneMessage(4,2,"Local search solved to optimality in %d nodes and %d lp iterations."));
    23   addMessage(LOCAL_SEARCH_ABORT, CoinOneMessage(5,2,"Local search aborted : %d nodes and %d lp iterations."));
    24   addMessage(UPDATE_LB, CoinOneMessage(6,2,"Updating lower bound to %g elapsed time %g sec"));
    25   addMessage(ABORT,CoinOneMessage(7,1,"Oa aborted on %s limit, time spent %g"));
    26   addMessage(OASUCCESS, CoinOneMessage(8,1,"Oa converged in %g seconds"));
    27   addMessage(LP_ERROR,CoinOneMessage(9,2,"Error of LP approximation %g"));
    28   addMessage(PERIODIC_MSG, CoinOneMessage(10,1,"After %7.1f seconds, upper bound %10g, lower bound %10g"));
    29 }
     16  OaMessages::OaMessages():
     17      CoinMessages(DUMMY_END)
     18  {
     19    strcpy(source_,"OA");
     20    addMessage(FEASIBLE_NLP,CoinOneMessage( 1, 2,"Solved NLP in %d iterations, found a feasible solution of value %f."));
     21    addMessage(INFEASIBLE_NLP, CoinOneMessage(2,2,"Solved NLP in %d iterations, problem is infeasible in subspace."));
     22    addMessage(UPDATE_UB, CoinOneMessage(3,1,"New best feasible of %g found after %g sec."));
     23    addMessage(SOLVED_LOCAL_SEARCH, CoinOneMessage(4,2,"Local search solved to optimality in %d nodes and %d lp iterations."));
     24    addMessage(LOCAL_SEARCH_ABORT, CoinOneMessage(5,2,"Local search aborted : %d nodes and %d lp iterations."));
     25    addMessage(UPDATE_LB, CoinOneMessage(6,2,"Updating lower bound to %g elapsed time %g sec"));
     26    addMessage(ABORT,CoinOneMessage(7,1,"Oa aborted on %s limit, time spent %g"));
     27    addMessage(OASUCCESS, CoinOneMessage(8,1,"Oa converged in %g seconds"));
     28    addMessage(LP_ERROR,CoinOneMessage(9,2,"Error of LP approximation %g"));
     29    addMessage(PERIODIC_MSG, CoinOneMessage(10,1,"After %7.1f seconds, upper bound %10g, lower bound %10g"));
     30  }
    3031
    3132}//end namespace Bonmin
  • branches/devel/Bonmin/src/OaInterface/BonOAMessages.hpp

    r58 r62  
    1212#include "CoinMessage.hpp"
    1313
    14 namespace Bonmin {
    15 enum OA_Message{
    16   FEASIBLE_NLP,
    17   INFEASIBLE_NLP,
    18   UPDATE_UB,
    19   SOLVED_LOCAL_SEARCH,
    20   LOCAL_SEARCH_ABORT,
    21   UPDATE_LB,
    22   ABORT,
    23   OASUCCESS,
    24   LP_ERROR,
    25   PERIODIC_MSG,
    26   DUMMY_END
    27 };
     14namespace Bonmin
     15{
     16  enum OA_Message{
     17    FEASIBLE_NLP,
     18    INFEASIBLE_NLP,
     19    UPDATE_UB,
     20    SOLVED_LOCAL_SEARCH,
     21    LOCAL_SEARCH_ABORT,
     22    UPDATE_LB,
     23    ABORT,
     24    OASUCCESS,
     25    LP_ERROR,
     26    PERIODIC_MSG,
     27    DUMMY_END
     28  };
    2829
    29 /** Output messages for Outer approximation cutting planes */
    30 class OaMessages : public CoinMessages
    31 {
    32 public:
    33   OaMessages();
    34 };
     30  /** Output messages for Outer approximation cutting planes */
     31  class OaMessages : public CoinMessages
     32  {
     33  public:
     34    OaMessages();
     35  };
    3536
    3637} //end namespace Bonmin
Note: See TracChangeset for help on using the changeset viewer.