source: trunk/include/CbcModel.hpp @ 97

Last change on this file since 97 was 97, checked in by forrest, 15 years ago

for OsiCbc?

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 45.9 KB
Line 
1// Copyright (C) 2002, International Business Machines
2// Corporation and others.  All Rights Reserved.
3#ifndef CbcModel_H
4#define CbcModel_H
5
6#include <string>
7#include <vector>
8
9#include "CoinFinite.hpp"
10#include "CoinMessageHandler.hpp"
11#include "OsiSolverInterface.hpp"
12#include "OsiCuts.hpp"
13#include "CoinWarmStartBasis.hpp"
14#include "CbcCompareBase.hpp"
15#include "CbcMessage.hpp"
16
17//class OsiSolverInterface;
18
19class CbcCutGenerator;
20class OsiRowCut;
21class OsiRowCutDebugger;
22class CglCutGenerator;
23class CbcHeuristic;
24class CbcObject;
25class CbcTree;
26class CbcStrategy;
27
28//#############################################################################
29
30/** Simple Branch and bound class
31
32  The initialSolve() method solves the initial LP relaxation of the MIP
33  problem. The branchAndBound() method can then be called to finish using
34  a branch and cut algorithm.
35
36  <h3>Search Tree Traversal</h3>
37
38  Subproblems (aka nodes) requiring additional evaluation are stored using
39  the CbcNode and CbcNodeInfo objects. Ancestry linkage is maintained in the
40  CbcNodeInfo object. Evaluation of a subproblem within branchAndBound()
41  proceeds as follows:
42  <ul>
43    <li> The node representing the most promising parent subproblem is popped
44         from the heap which holds the set of subproblems requiring further
45         evaluation.
46    <li> Using branching instructions stored in the node, and information in
47         its ancestors, the model and solver are adjusted to create the
48         active subproblem.
49    <li> If the parent subproblem will require further evaluation
50         (<i>i.e.</i>, there are branches remaining) its node is pushed back
51         on the heap. Otherwise, the node is deleted.  This may trigger
52         recursive deletion of ancestors.
53    <li> The newly created subproblem is evaluated.
54    <li> If the subproblem requires further evaluation, a node is created.
55         All information needed to recreate the subproblem (branching
56         information, row and column cuts) is placed in the node and the node
57         is added to the set of subproblems awaiting further evaluation.
58  </ul>
59  Note that there is never a node representing the active subproblem; the model
60  and solver represent the active subproblem.
61
62  <h3>Row (Constraint) Cut Handling</h3>
63
64  For a typical subproblem, the sequence of events is as follows:
65  <ul>
66    <li> The subproblem is rebuilt for further evaluation: One result of a
67         call to addCuts() is a traversal of ancestors, leaving a list of all
68         cuts used in the ancestors in #addedCuts_. This list is then scanned
69         to construct a basis that includes only tight cuts. Entries for
70         loose cuts are set to NULL.
71    <li> The subproblem is evaluated: One result of a call to solveWithCuts()
72         is the return of a set of newly generated cuts for the subproblem.
73         #addedCuts_ is also kept up-to-date as old cuts become loose.
74    <li> The subproblem is stored for further processing: A call to
75         CbcNodeInfo::addCuts() adds the newly generated cuts to the
76         CbcNodeInfo object associated with this node.
77  </ul>
78  See CbcCountRowCut for details of the bookkeeping associated with cut
79  management.
80*/
81
82class CbcModel  {
83 
84public:
85
86enum CbcIntParam {
87  /** The maximum number of nodes before terminating */
88  CbcMaxNumNode=0,
89  /** The maximum number of solutions before terminating */
90  CbcMaxNumSol,
91  /** Fathoming discipline
92
93    Controls objective function comparisons for purposes of fathoming by bound
94    or determining monotonic variables.
95
96    If 1, action is taken only when the current objective is strictly worse
97    than the target. Implementation is handled by adding a small tolerance to
98    the target.
99  */
100  CbcFathomDiscipline,
101  /** Just a marker, so that a static sized array can store parameters. */
102  CbcLastIntParam
103};
104
105enum CbcDblParam {
106  /** The maximum amount the value of an integer variable can vary from
107      integer and still be considered feasible. */
108  CbcIntegerTolerance=0,
109  /** The objective is assumed to worsen by this amount for each
110      integer infeasibility. */
111  CbcInfeasibilityWeight,
112  /** The amount by which to tighten the objective function cutoff when
113      a new solution is discovered. */
114  CbcCutoffIncrement,
115  /** Stop when the gap between the objective value of the best known solution
116    and the best bound on the objective of any solution is less than this.
117 
118    This is an absolute value. Conversion from a percentage is left to the
119    client.
120  */
121  CbcAllowableGap,
122  /** Stop when the gap between the objective value of the best known solution
123    and the best bound on the objective of any solution is less than this
124    fraction of of the absolute value of best known solution.
125 
126    Code stops if either this test or CbcAllowableGap test succeeds
127  */
128  CbcAllowableFractionGap,
129  /** \brief The maximum number of seconds before terminating.
130             A double should be adequate! */
131  CbcMaximumSeconds,
132  /** \brief The time at start of model.
133             So that other pieces of code can access */
134  CbcStartSeconds,
135  /** Just a marker, so that a static sized array can store parameters. */
136  CbcLastDblParam
137};
138
139  //---------------------------------------------------------------------------
140
141public:
142  ///@name Solve methods
143  //@{
144    /** \brief Solve the initial LP relaxation
145
146      Invoke the solver's %initialSolve() method.
147    */
148    void initialSolve(); 
149
150    /** \brief Invoke the branch \& cut algorithm
151
152      The method assumes that initialSolve() has been called to solve the
153      LP relaxation. It processes the root node, then proceeds to explore the
154      branch & cut search tree. The search ends when the tree is exhausted or
155      one of several execution limits is reached.
156    */
157     void branchAndBound();
158
159    /** \brief create a clean model from partially fixed problem
160
161      The method creates a new model with given bounds and with no tree.
162    */
163     CbcModel *  cleanModel(const double * lower, const double * upper);
164    /** \brief Invoke the branch \& cut algorithm on partially fixed problem
165
166      The method presolves the given model and does branch and cut. The search
167      ends when the tree is exhausted or maximum nodes is reached.
168
169      If better solution found then it is saved.
170
171      Returns 0 if search completed and solution, 1 if not completed and solution,
172      2 if completed and no solution, 3 if not completed and no solution.
173
174      Normally okay to do cleanModel immediately followed by subBranchandBound
175      (== other form of subBranchAndBound)
176      but may need to get at model for advanced features.
177
178      Deletes model2
179    */
180     int subBranchAndBound(CbcModel * model2,
181                           CbcModel * presolvedModel,
182                           int maximumNodes);
183    /** \brief Invoke the branch \& cut algorithm on partially fixed problem
184
185      The method creates a new model with given bounds, presolves it
186      then proceeds to explore the branch & cut search tree. The search
187      ends when the tree is exhausted or maximum nodes is reached.
188
189      If better solution found then it is saved.
190
191      Returns 0 if search completed and solution, 1 if not completed and solution,
192      2 if completed and no solution, 3 if not completed and no solution.
193
194      This is just subModel immediately followed by other version of
195      subBranchandBound.
196
197    */
198     int subBranchAndBound(const double * lower, const double * upper,
199                            int maximumNodes);
200
201    /** \brief Process root node and return a strengthened model
202
203      The method assumes that initialSolve() has been called to solve the
204      LP relaxation. It processes the root node and then returns a pointer
205      to the strengthened model (or NULL if infeasible)
206    */
207     OsiSolverInterface *  strengthenedModel();
208    /** \brief Evaluate a subproblem using cutting planes and heuristics
209
210      The method invokes a main loop which generates cuts, applies heuristics,
211      and reoptimises using the solver's native %resolve() method.
212      It returns true if the subproblem remains feasible at the end of the
213      evaluation.
214    */
215    bool solveWithCuts(OsiCuts & cuts, int numberTries,CbcNode * node,
216                       int & numberOldActiveCuts, int & numberNewCuts,
217                       int & maximumWhich, int * & whichGenerator);
218
219    /** \brief Reoptimise an LP relaxation
220   
221      Invoke the solver's %resolve() method.
222    */
223    bool resolve();
224  /// Make given rows (L or G) into global cuts and remove from lp
225  void makeGlobalCuts(int numberRows,const int * which); 
226  //@}
227
228  /** \name Presolve methods */
229  //@{
230
231  /** Identify cliques and construct corresponding objects.
232
233      Find cliques with size in the range
234      [\p atLeastThisMany, \p lessThanThis] and construct corresponding
235      CbcClique objects.
236      If \p makeEquality is true then a new model may be returned if
237      modifications had to be made, otherwise \c this is returned.
238      If the problem is infeasible #numberObjects_ is set to -1.
239      A client must use deleteObjects() before a second call to findCliques().
240      If priorities exist, clique priority is set to the default.
241  */
242  CbcModel * findCliques(bool makeEquality, int atLeastThisMany,
243                         int lessThanThis, int defaultValue=1000);
244
245  /** Do integer presolve, creating a new (presolved) model.
246
247    Returns the new model, or NULL if feasibility is lost.
248    If weak is true then just does a normal presolve
249 
250    \todo It remains to work out the cleanest way of getting a solution to
251          the original problem at the end. So this is very preliminary.
252   */
253  CbcModel * integerPresolve(bool weak=false);
254
255  /** Do integer presolve, modifying the current model.
256
257      Returns true if the model remains feasible after presolve.
258  */
259  bool integerPresolveThisModel(OsiSolverInterface * originalSolver,bool weak=false);
260
261
262  /// Put back information into the original model after integer presolve.
263  void originalModel(CbcModel * presolvedModel,bool weak);
264
265  /** \brief For variables involved in VUB constraints, see if we can tighten
266             bounds by solving lp's
267
268      Returns false if feasibility is lost.
269      If CglProbing is available, it will be tried as well to see if it can
270      tighten bounds.
271      This routine is just a front end for tightenVubs(int,const int*,double).
272
273      If <tt>type = -1</tt> all variables are processed (could be very slow).
274      If <tt>type = 0</tt> only variables involved in VUBs are processed.
275      If <tt>type = n > 0</tt>, only the n most expensive VUB variables
276      are processed, where it is assumed that x is at its maximum so delta
277      would have to go to 1 (if x not at bound).
278
279      If \p allowMultipleBinary is true, then a VUB constraint is a row with
280      one continuous variable and any number of binary variables.
281
282      If <tt>useCutoff < 1.0e30</tt>, the original objective is installed as a
283      constraint with \p useCutoff as a bound.
284  */
285  bool tightenVubs(int type,bool allowMultipleBinary=false,
286                   double useCutoff=1.0e50);
287 
288  /** \brief For variables involved in VUB constraints, see if we can tighten
289             bounds by solving lp's
290
291    This version is just handed a list of variables to be processed.
292  */
293  bool tightenVubs(int numberVubs, const int * which,
294                   double useCutoff=1.0e50);
295  /**
296    Analyze problem to find a minimum change in the objective function.
297  */
298  void analyzeObjective();
299
300
301  //@}
302
303  /** \name Object manipulation routines
304 
305    See CbcObject for an explanation of `object' in the context of CbcModel.
306  */
307  //@{
308
309  /// Get the number of objects
310  inline int numberObjects() const { return numberObjects_;};
311  /// Set the number of objects
312  inline void setNumberObjects(int number) 
313  {  numberObjects_=number;};
314
315  /// Get the array of objects
316  inline CbcObject ** objects() const { return object_;};
317
318  /// Get the specified object
319  const inline CbcObject * object(int which) const { return object_[which];};
320
321  /// Delete all object information
322  void deleteObjects();
323
324  /** Add in object information.
325 
326    Objects are cloned; the owner can delete the originals.
327  */
328  void addObjects(int numberObjects, CbcObject ** objects);
329
330  /// Ensure attached objects point to this model.
331  void synchronizeModel() ;
332
333  /** \brief Identify integer variables and create corresponding objects.
334 
335    Record integer variables and create an CbcSimpleInteger object for each
336    one.
337    If \p startAgain is true, a new scan is forced, overwriting any existing
338    integer variable information.
339  */
340
341  void findIntegers(bool startAgain);
342 
343  //@}
344
345  //---------------------------------------------------------------------------
346
347  /**@name Parameter set/get methods
348
349     The set methods return true if the parameter was set to the given value,
350     false if the value of the parameter is out of range.
351
352     The get methods return the value of the parameter.
353
354  */
355  //@{
356  /// Set an integer parameter
357  inline bool setIntParam(CbcIntParam key, int value) {
358    intParam_[key] = value;
359    return true;
360  }
361  /// Set a double parameter
362  inline bool setDblParam(CbcDblParam key, double value) {
363    dblParam_[key] = value;
364    return true;
365  }
366  /// Get an integer parameter
367  inline int getIntParam(CbcIntParam key) const {
368    return intParam_[key];
369  }
370  /// Get a double parameter
371  inline double getDblParam(CbcDblParam key) const {
372    return dblParam_[key];
373  }
374  /*! \brief Set cutoff bound on the objective function.
375
376    When using strict comparison, the bound is adjusted by a tolerance to
377    avoid accidentally cutting off the optimal solution.
378  */
379  void setCutoff(double value) ;
380
381  /// Get the cutoff bound on the objective function - always as minimize
382  inline double getCutoff() const
383  { double value ;
384    solver_->getDblParam(OsiDualObjectiveLimit,value) ;
385    return value * solver_->getObjSense() ; } ;
386
387  /// Set the \link CbcModel::CbcMaxNumNode maximum node limit \endlink
388  inline bool setMaximumNodes( int value)
389  { return setIntParam(CbcMaxNumNode,value); }
390
391  /// Get the \link CbcModel::CbcMaxNumNode maximum node limit \endlink
392  inline int getMaximumNodes() const
393  { return getIntParam(CbcMaxNumNode); }
394
395  /** Set the
396      \link CbcModel::CbcMaxNumSol maximum number of solutions \endlink
397      desired.
398  */
399  inline bool setMaximumSolutions( int value) {
400    return setIntParam(CbcMaxNumSol,value);
401  }
402  /** Get the
403      \link CbcModel::CbcMaxNumSol maximum number of solutions \endlink
404      desired.
405  */
406  inline int getMaximumSolutions() const {
407    return getIntParam(CbcMaxNumSol);
408  }
409
410  /** Set the
411      \link CbcModel::CbcMaximumSeconds maximum number of seconds \endlink
412      desired.
413  */
414  inline bool setMaximumSeconds( double value) {
415    return setDblParam(CbcMaximumSeconds,value);
416  }
417  /** Get the
418      \link CbcModel::CbcMaximumSeconds maximum number of seconds \endlink
419      desired.
420  */
421  inline double getMaximumSeconds() const {
422    return getDblParam(CbcMaximumSeconds);
423  }
424
425  /** Set the
426    \link CbcModel::CbcIntegerTolerance integrality tolerance \endlink
427  */
428  inline bool setIntegerTolerance( double value) {
429    return setDblParam(CbcIntegerTolerance,value);
430  }
431  /** Get the
432    \link CbcModel::CbcIntegerTolerance integrality tolerance \endlink
433  */
434  inline double getIntegerTolerance() const {
435    return getDblParam(CbcIntegerTolerance);
436  }
437
438  /** Set the
439      \link CbcModel::CbcInfeasibilityWeight
440            weight per integer infeasibility \endlink
441  */
442  inline bool setInfeasibilityWeight( double value) {
443    return setDblParam(CbcInfeasibilityWeight,value);
444  }
445  /** Get the
446      \link CbcModel::CbcInfeasibilityWeight
447            weight per integer infeasibility \endlink
448  */
449  inline double getInfeasibilityWeight() const {
450    return getDblParam(CbcInfeasibilityWeight);
451  }
452
453  /** Set the \link CbcModel::CbcAllowableGap allowable gap \endlink
454      between the best known solution and the best possible solution.
455  */
456  inline bool setAllowableGap( double value) {
457    return setDblParam(CbcAllowableGap,value);
458  }
459  /** Get the \link CbcModel::CbcAllowableGap allowable gap \endlink
460      between the best known solution and the best possible solution.
461  */
462  inline double getAllowableGap() const {
463    return getDblParam(CbcAllowableGap);
464  }
465
466  /** Set the \link CbcModel::CbcAllowableFractionGap fraction allowable gap \endlink
467      between the best known solution and the best possible solution.
468  */
469  inline bool setAllowableFractionGap( double value) {
470    return setDblParam(CbcAllowableFractionGap,value);
471  }
472  /** Get the \link CbcModel::CbcAllowableFractionGap fraction allowable gap \endlink
473      between the best known solution and the best possible solution.
474  */
475  inline double getAllowableFractionGap() const {
476    return getDblParam(CbcAllowableFractionGap);
477  }
478  /** Set the \link CbcModel::CbcAllowableFractionGap percentage allowable gap \endlink
479      between the best known solution and the best possible solution.
480  */
481  inline bool setAllowablePercentageGap( double value) {
482    return setDblParam(CbcAllowableFractionGap,value*0.01);
483  }
484  /** Get the \link CbcModel::CbcAllowableFractionGap percentage allowable gap \endlink
485      between the best known solution and the best possible solution.
486  */
487  inline double getAllowablePercentageGap() const {
488    return 100.0*getDblParam(CbcAllowableFractionGap);
489  }
490
491  /// Set the hotstart strategy
492  void setHotstartStrategy(int value) 
493  { hotstartStrategy_=value;};
494  /// Get the hotstart strategy
495  int getHotstartStrategy() const
496  { return hotstartStrategy_;};
497 
498  /// Set the minimum drop to continue cuts
499  inline void setMinimumDrop(double value)
500  {minimumDrop_=value;};
501  /// Get the minimum drop to continue cuts
502  inline double getMinimumDrop() const
503  { return minimumDrop_;};
504
505  /** Set the maximum number of cut passes at root node (default 20)
506      Minimum drop can also be used for fine tuning */
507  inline void setMaximumCutPassesAtRoot(int value)
508  {maximumCutPassesAtRoot_=value;};
509  /** Get the maximum number of cut passes at root node */
510  inline int getMaximumCutPassesAtRoot() const
511  { return maximumCutPassesAtRoot_;};
512
513  /** Set the maximum number of cut passes at other nodes (default 10)
514      Minimum drop can also be used for fine tuning */
515  inline void setMaximumCutPasses(int value)
516  {maximumCutPasses_=value;};
517  /** Get the maximum number of cut passes at other nodes (default 10) */
518  inline int getMaximumCutPasses() const
519  { return maximumCutPasses_;};
520  /** Get current cut pass number in this round of cuts.
521      (1 is first pass) */
522  inline int getCurrentPassNumber() const
523  { return currentPassNumber_;};
524
525  /** Set the maximum number of candidates to be evaluated for strong
526    branching.
527
528    A value of 0 disables strong branching.
529  */
530  void setNumberStrong(int number);
531  /** Get the maximum number of candidates to be evaluated for strong
532    branching.
533  */
534  inline int numberStrong() const
535  { return numberStrong_;};
536
537  /// Set how often to scan global cuts
538  void setHowOftenGlobalScan(int number);
539  /// Get how often to scan global cuts
540  inline int howOftenGlobalScan() const
541  { return howOftenGlobalScan_;};
542
543  /** Set the print frequency.
544 
545    Controls the number of nodes evaluated between status prints.
546    If <tt>number <=0</tt> the print frequency is set to 100 nodes for large
547    problems, 1000 for small problems.
548    Print frequency has very slight overhead if small.
549  */
550  void setPrintFrequency(int number)
551  { printFrequency_=number;};
552  /// Get the print frequency
553  inline int printFrequency() const
554  { return printFrequency_;};
555  //@}
556
557  //---------------------------------------------------------------------------
558  ///@name Methods returning info on how the solution process terminated
559  //@{
560    /// Are there a numerical difficulties?
561    bool isAbandoned() const;
562    /// Is optimality proven?
563    bool isProvenOptimal() const;
564    /// Is  infeasiblity proven (or none better than cutoff)?
565    bool isProvenInfeasible() const;
566    /// Node limit reached?
567    bool isNodeLimitReached() const;
568    /// Solution limit reached?
569    bool isSolutionLimitReached() const;
570    /// Get how many iterations it took to solve the problem.
571    int getIterationCount() const
572    { return solver_->getIterationCount();};
573    /// Get how many Nodes it took to solve the problem.
574    int getNodeCount() const
575    { return numberNodes_;};
576    /** Final status of problem
577   
578      0 finished, 1 stopped, 2 difficulties
579    */
580    inline int status() const
581    { return status_;};
582 
583  //@}
584
585  //---------------------------------------------------------------------------
586  /**@name Problem information methods
587     
588     These methods call the solver's query routines to return
589     information about the problem referred to by the current object.
590     Querying a problem that has no data associated with it result in
591     zeros for the number of rows and columns, and NULL pointers from
592     the methods that return vectors.
593     
594     Const pointers returned from any data-query method are valid as
595     long as the data is unchanged and the solver is not called.
596  */
597  //@{
598  /// Number of rows in continuous (root) problem.
599  int numberRowsAtContinuous() const
600  { return numberRowsAtContinuous_;};
601
602  /// Get number of columns
603  int getNumCols() const
604  { return solver_->getNumCols();};
605 
606  /// Get number of rows
607  int getNumRows() const
608  { return solver_->getNumRows();};
609 
610  /// Get number of nonzero elements
611  int getNumElements() const
612  { return solver_->getNumElements();};
613
614  /// Number of integers in problem
615  inline int numberIntegers() const
616  { return numberIntegers_;};
617  // Integer variables
618  inline const int * integerVariable() const 
619  { return integerVariable_;};
620 
621  /// Get pointer to array[getNumCols()] of column lower bounds
622  const double * getColLower() const
623  { return solver_->getColLower();};
624 
625  /// Get pointer to array[getNumCols()] of column upper bounds
626  const double * getColUpper() const
627  { return solver_->getColUpper();};
628 
629  /** Get pointer to array[getNumRows()] of row constraint senses.
630      <ul>
631      <li>'L': <= constraint
632      <li>'E': =  constraint
633      <li>'G': >= constraint
634      <li>'R': ranged constraint
635      <li>'N': free constraint
636      </ul>
637  */
638  const char * getRowSense() const
639  { return solver_->getRowSense();};
640 
641  /** Get pointer to array[getNumRows()] of rows right-hand sides
642      <ul>
643      <li> if rowsense()[i] == 'L' then rhs()[i] == rowupper()[i]
644      <li> if rowsense()[i] == 'G' then rhs()[i] == rowlower()[i]
645      <li> if rowsense()[i] == 'R' then rhs()[i] == rowupper()[i]
646      <li> if rowsense()[i] == 'N' then rhs()[i] == 0.0
647      </ul>
648  */
649  const double * getRightHandSide() const
650  { return solver_->getRightHandSide();};
651 
652  /** Get pointer to array[getNumRows()] of row ranges.
653      <ul>
654      <li> if rowsense()[i] == 'R' then
655      rowrange()[i] == rowupper()[i] - rowlower()[i]
656      <li> if rowsense()[i] != 'R' then
657      rowrange()[i] is 0.0
658      </ul>
659  */
660  const double * getRowRange() const
661  { return solver_->getRowRange();};
662 
663  /// Get pointer to array[getNumRows()] of row lower bounds
664  const double * getRowLower() const
665  { return solver_->getRowLower();};
666 
667  /// Get pointer to array[getNumRows()] of row upper bounds
668  const double * getRowUpper() const
669  { return solver_->getRowUpper();};
670 
671  /// Get pointer to array[getNumCols()] of objective function coefficients
672  const double * getObjCoefficients() const
673  { return solver_->getObjCoefficients();};
674 
675  /// Get objective function sense (1 for min (default), -1 for max)
676  double getObjSense() const
677  { return solver_->getObjSense();};
678 
679  /// Return true if variable is continuous
680  bool isContinuous(int colIndex) const
681  { return solver_->isContinuous(colIndex);};
682 
683  /// Return true if variable is binary
684  bool isBinary(int colIndex) const
685  { return solver_->isBinary(colIndex);};
686 
687  /** Return true if column is integer.
688      Note: This function returns true if the the column
689      is binary or a general integer.
690  */
691  bool isInteger(int colIndex) const
692  { return solver_->isInteger(colIndex);};
693 
694  /// Return true if variable is general integer
695  bool isIntegerNonBinary(int colIndex) const
696  { return solver_->isIntegerNonBinary(colIndex);};
697 
698  /// Return true if variable is binary and not fixed at either bound
699  bool isFreeBinary(int colIndex) const
700  { return solver_->isFreeBinary(colIndex) ;};
701 
702  /// Get pointer to row-wise copy of matrix
703  const CoinPackedMatrix * getMatrixByRow() const
704  { return solver_->getMatrixByRow();};
705 
706  /// Get pointer to column-wise copy of matrix
707  const CoinPackedMatrix * getMatrixByCol() const
708  { return solver_->getMatrixByCol();};
709 
710  /// Get solver's value for infinity
711  double getInfinity() const
712  { return solver_->getInfinity();};
713  //@}
714 
715 
716  /**@name Methods related to querying the solution */
717  //@{
718  /// Record a new incumbent solution and update objectiveValue
719  void setBestSolution(CBC_Message how,
720                       double & objectiveValue, const double *solution,
721                       bool fixVariables=false);
722  /// Just update objectiveValue
723  void setBestObjectiveValue( double objectiveValue);
724
725  /** Call this to really test if a valid solution can be feasible
726      Solution is number columns in size.
727      If fixVariables true then bounds of continuous solver updated.
728      Returns objective value (worse than cutoff if not feasible)
729 */
730  double checkSolution(double cutoff, const double * solution,
731                       bool fixVariables);
732  /** Test the current solution for feasiblility.
733
734    Scan all objects for indications of infeasibility. This is broken down
735    into simple integer infeasibility (\p numberIntegerInfeasibilities)
736    and all other reports of infeasibility (\p numberObjectInfeasibilities).
737  */
738  bool feasibleSolution(int & numberIntegerInfeasibilities,
739                        int & numberObjectInfeasibilities) const;
740
741  /** Solution to the most recent lp relaxation.
742
743    The solver's solution to the most recent lp relaxation.
744  */
745   
746  inline double * currentSolution() const
747  { return currentSolution_;};
748  /// Make sure region there
749  void reserveCurrentSolution();
750
751  /// Get pointer to array[getNumCols()] of primal solution vector
752  inline const double * getColSolution() const
753  { return solver_->getColSolution();};
754 
755  /// Get pointer to array[getNumRows()] of dual prices
756  inline const double * getRowPrice() const
757  { return solver_->getRowPrice();};
758 
759  /// Get a pointer to array[getNumCols()] of reduced costs
760  inline const double * getReducedCost() const
761  { return solver_->getReducedCost();};
762 
763  /// Get pointer to array[getNumRows()] of row activity levels.
764  inline const double * getRowActivity() const
765  { return solver_->getRowActivity();};
766 
767  /// Get current objective function value
768  inline double getCurrentObjValue() const
769  { return solver_->getObjValue();};
770 
771  /// Get best objective function value as minimization
772  inline double getMinimizationObjValue() const
773  { return bestObjective_;};
774  /// Set best objective function value as minimization
775  inline void setMinimizationObjValue(double value) 
776  { bestObjective_=value;};
777 
778  /// Get best objective function value
779  inline double getObjValue() const
780  { return bestObjective_ * solver_->getObjSense() ; } ;
781  /** Get best possible objective function value.
782      This is better of best possible left on tree
783      and best solution found.
784      If called from within branch and cut may be optimistic.
785  */
786  double getBestPossibleObjValue() const;
787  /// Set best objective function value
788  inline void setObjValue(double value) 
789  { bestObjective_=value * solver_->getObjSense() ;};
790 
791  /** The best solution to the integer programming problem.
792
793    The best solution to the integer programming problem found during
794    the search. If no solution is found, the method returns null.
795  */
796
797  double * bestSolution() const
798  { return bestSolution_;};
799 
800  /// Get number of solutions
801  int getSolutionCount() const
802  { return numberSolutions_;};
803 
804  /// Set number of solutions (so heuristics will be different)
805  void setSolutionCount(int value) 
806  { numberSolutions_=value;};
807  /** Current phase (so heuristics etc etc can find out).
808      0 - initial solve
809      1 - solve with cuts at root
810      2 - solve with cuts
811      3 - other e.g. strong branching
812      4 - trying to validate a solution
813      5 - at end of search
814  */
815  inline int phase() const
816  { return phase_;};
817 
818  /// Get number of heuristic solutions
819  int getNumberHeuristicSolutions() const { return numberHeuristicSolutions_;};
820
821  /// Set objective function sense (1 for min (default), -1 for max,)
822  void setObjSense(double s) { solver_->setObjSense(s);};
823
824  /// Value of objective at continuous
825  inline double getContinuousObjective() const
826  { return originalContinuousObjective_;};
827  inline void setContinuousObjective(double value)
828  { originalContinuousObjective_=value;};
829  /// Number of infeasibilities at continuous
830  inline int getContinuousInfeasibilities() const
831  { return continuousInfeasibilities_;};
832  inline void setContinuousInfeasibilities(int value)
833  { continuousInfeasibilities_=value;};
834  /// Value of objective after root node cuts added
835  inline double rootObjectiveAfterCuts() const
836  { return continuousObjective_;};
837  /** Number of times global cuts violated.  When global cut pool then this
838      should be kept for each cut and type of cut */
839  inline int numberGlobalViolations() const
840  { return numberGlobalViolations_;};
841  inline void clearNumberGlobalViolations()
842  { numberGlobalViolations_=0;};
843  /// Whether to force a resolve after takeOffCuts
844  inline bool resolveAfterTakeOffCuts() const
845  { return resolveAfterTakeOffCuts_;};
846  inline void setResolveAfterTakeOffCuts(bool yesNo)
847  { resolveAfterTakeOffCuts_=yesNo;};
848  //@}
849
850  /** \name Node selection */
851  //@{
852  // Comparison functions (which may be overridden by inheritance)
853  inline CbcCompareBase * nodeComparison() const
854  { return nodeCompare_;};
855  void setNodeComparison(CbcCompareBase * compare);
856  void setNodeComparison(CbcCompareBase & compare);
857  //@}
858
859  /** \name Tree methods and subtree methods */
860  //@{
861  /// Tree method e.g. heap (which may be overridden by inheritance)
862  inline CbcTree * tree() const
863  { return tree_;};
864  /// For modifying tree handling (original is cloned)
865  void passInTreeHandler(CbcTree & tree);
866  /** For passing in an CbcModel to do a sub Tree (with derived tree handlers).
867      Passed in model must exist for duration of branch and bound
868  */
869  void passInSubTreeModel(CbcModel & model);
870  /** For retrieving a copy of subtree model with given OsiSolver.
871      If no subtree model will use self (up to user to reset cutoff etc).
872      If solver NULL uses current
873  */
874  CbcModel * subTreeModel(OsiSolverInterface * solver=NULL) const;
875  /// Returns number of times any subtree stopped on nodes, time etc
876  inline int numberStoppedSubTrees() const
877  { return numberStoppedSubTrees_;}
878  /// Says a sub tree was stopped
879  inline void incrementSubTreeStopped()
880  { numberStoppedSubTrees_++;};
881  /** Whether to automatically do presolve before branch and bound (subTrees).
882      0 - no
883      1 - ordinary presolve
884      2 - integer presolve (dodgy)
885  */
886  inline int typePresolve() const
887  { return presolve_;};
888  inline void setTypePresolve(int value)
889  { presolve_=value;};
890  //@}
891
892  /** \name Branching Decisions
893 
894    See the CbcBranchDecision class for additional information.
895  */
896  //@{
897
898  /// Get the current branching decision method.
899  inline CbcBranchDecision * branchingMethod() const
900  { return branchingMethod_;};
901  /// Set the branching decision method.
902  inline void setBranchingMethod(CbcBranchDecision * method)
903  { branchingMethod_ = method;};
904  /** Set the branching method
905 
906    \overload
907  */
908  inline void setBranchingMethod(CbcBranchDecision & method)
909  { branchingMethod_ = &method;};
910  //@}
911
912  /** \name Row (constraint) and Column (variable) cut generation */
913  //@{
914
915  /** Perform reduced cost fixing
916
917    Fixes integer variables at their current value based on reduced cost
918    penalties.
919  */
920  void reducedCostFix() ;
921
922  /** Return an empty basis object of the specified size
923
924    A useful utility when constructing a basis for a subproblem from scratch.
925    The object returned will be of the requested capacity and appropriate for
926    the solver attached to the model.
927  */
928  CoinWarmStartBasis *getEmptyBasis(int ns = 0, int na = 0) const ;
929
930  /** Remove inactive cuts from the model
931
932    An OsiSolverInterface is expected to maintain a valid basis, but not a
933    valid solution, when loose cuts are deleted. Restoring a valid solution
934    requires calling the solver to reoptimise. If it's certain the solution
935    will not be required, set allowResolve to false to suppress
936    reoptimisation.
937  */
938  void takeOffCuts(OsiCuts &cuts, int *whichGenerator,
939                     int &numberOldActiveCuts, int &numberNewCuts,
940                     bool allowResolve) ;
941
942  /** Determine and install the active cuts that need to be added for
943    the current subproblem
944
945    The whole truth is a bit more complicated. The first action is a call to
946    addCuts1(). addCuts() then sorts through the list, installs the tight
947    cuts in the model, and does bookkeeping (adjusts reference counts).
948    The basis returned from addCuts1() is adjusted accordingly.
949   
950    If it turns out that the node should really be fathomed by bound,
951    addCuts() simply treats all the cuts as loose as it does the bookkeeping.
952  */
953  int addCuts(CbcNode * node, CoinWarmStartBasis *&lastws);
954
955  /** Traverse the tree from node to root and prep the model
956
957    addCuts1() begins the job of prepping the model to match the current
958    subproblem. The model is stripped of all cuts, and the search tree is
959    traversed from node to root to determine the changes required. Appropriate
960    bounds changes are installed, a list of cuts is collected but not
961    installed, and an appropriate basis (minus the cuts, but big enough to
962    accommodate them) is constructed.
963
964    \todo addCuts1() is called in contexts where it's known in advance that
965          all that's desired is to determine a list of cuts and do the
966          bookkeeping (adjust the reference counts). The work of installing
967          bounds and building a basis goes to waste.
968  */
969  void addCuts1(CbcNode * node, CoinWarmStartBasis *&lastws);
970
971  /// Return the list of cuts initially collected for this subproblem
972  CbcCountRowCut ** addedCuts() const
973  { return addedCuts_;};
974  /// Number of entries in the list returned by #addedCuts()
975  int currentNumberCuts() const
976  { return currentNumberCuts_;};
977  /// Global cuts
978  inline OsiCuts * globalCuts() 
979  { return &globalCuts_;};
980  /// Copy and set a pointer to a row cut which will be added instead of normal branching.
981  void setNextRowCut(const OsiRowCut & cut);
982  /// Get a pointer to current node (be careful)
983  inline CbcNode * currentNode() const
984  { return currentNode_;};
985
986  /// Get the number of cut generators
987  inline int numberCutGenerators() const
988  { return numberCutGenerators_;};
989  /// Get the list of cut generators
990  inline CbcCutGenerator ** cutGenerators() const
991  { return generator_;};
992  ///Get the specified cut generator
993  inline CbcCutGenerator * cutGenerator(int i) const
994  { return generator_[i];};
995  ///Get the specified cut generator before any changes
996  inline CbcCutGenerator * virginCutGenerator(int i) const
997  { return virginGenerator_[i];};
998  /** Add one generator - up to user to delete generators.
999      howoften affects how generator is used. 0 or 1 means always,
1000      >1 means every that number of nodes.  Negative values have same
1001      meaning as positive but they may be switched off (-> -100) by code if
1002      not many cuts generated at continuous.  -99 is just done at root.
1003      Name is just for printout.
1004      If depth >0 overrides how often generator is called (if howOften==-1 or >0).
1005  */
1006  void addCutGenerator(CglCutGenerator * generator,
1007                       int howOften=1, const char * name=NULL,
1008                       bool normal=true, bool atSolution=false, 
1009                       bool infeasible=false,int howOftenInSub=-100,
1010                       int whatDepth=-1, int whatDepthInSub=-1);
1011//@}
1012  /** \name Strategy and sub models
1013 
1014    See the CbcStrategy class for additional information.
1015  */
1016  //@{
1017
1018  /// Get the current strategy
1019  inline CbcStrategy * strategy() const
1020  { return strategy_;};
1021  /// Set the strategy. Clones
1022  void setStrategy(CbcStrategy & strategy);
1023  /// Get the current parent model
1024  inline CbcModel * parentModel() const
1025  { return parentModel_;};
1026  /// Set the parent model
1027  inline void setParentModel(CbcModel & parentModel)
1028  { parentModel_ = &parentModel;};
1029  //@}
1030
1031
1032  /** \name Heuristics and priorities */
1033  //@{
1034  /// Add one heuristic - up to user to delete
1035  void addHeuristic(CbcHeuristic * generator);
1036  ///Get the specified heuristic
1037  inline CbcHeuristic * heuristic(int i) const
1038  { return heuristic_[i];};
1039
1040  /** Pass in branching priorities.
1041 
1042      If ifClique then priorities are on cliques otherwise priorities are
1043      on integer variables. 
1044      Other type (if exists set to default)
1045      1 is highest priority. (well actually -INT_MAX is but that's ugly)
1046      If hotstart > 0 then branches are created to force
1047      the variable to the value given by best solution.  This enables a
1048      sort of hot start.  The node choice should be greatest depth
1049      and hotstart should normally be switched off after a solution.
1050
1051      If ifNotSimpleIntegers true then appended to normal integers
1052
1053      \internal Added for Kurt Spielberg.
1054  */
1055  void passInPriorities(const int * priorities, bool ifNotSimpleIntegers,
1056                        int defaultValue=1000);
1057
1058  /// Priorities
1059  inline const int * priority() const { return priority_;};
1060
1061  /// Returns priority level for an object (or 1000 if no priorities exist)
1062  inline int priority(int sequence) const
1063  { 
1064    if (priority_)
1065      return priority_[sequence];
1066    else
1067      return 1000;
1068  };
1069  //@}
1070   
1071  /**@name Setting/Accessing application data */
1072  //@{
1073    /** Set application data.
1074
1075        This is a pointer that the application can store into and
1076        retrieve from the solver interface.
1077        This field is available for the application to optionally
1078        define and use.
1079    */
1080    void setApplicationData (void * appData);
1081
1082    /// Get application data
1083    void * getApplicationData() const;
1084  //@}
1085 
1086  //---------------------------------------------------------------------------
1087
1088  /**@name Message handling */
1089  //@{
1090  /// Pass in Message handler (not deleted at end)
1091  void passInMessageHandler(CoinMessageHandler * handler);
1092  /// Set language
1093  void newLanguage(CoinMessages::Language language);
1094  inline void setLanguage(CoinMessages::Language language)
1095  {newLanguage(language);};
1096  /// Return handler
1097  inline CoinMessageHandler * messageHandler() const
1098  {return handler_;};
1099  /// Return messages
1100  inline CoinMessages messages() 
1101  {return messages_;};
1102  /// Return pointer to messages
1103  inline CoinMessages * messagesPointer() 
1104  {return &messages_;};
1105  /// Set log level
1106  inline void setLogLevel(int value)
1107  { handler_->setLogLevel(value);};
1108  /// Get log level
1109  inline int logLevel() const
1110  { return handler_->logLevel();};
1111  //@}
1112  //---------------------------------------------------------------------------
1113
1114
1115  ///@name Constructors and destructors etc
1116  //@{
1117    /// Default Constructor
1118    CbcModel(); 
1119   
1120    /// Constructor from solver
1121    CbcModel(const OsiSolverInterface &);
1122 
1123    /** Assign a solver to the model (model assumes ownership)
1124
1125      On return, \p solver will be NULL.
1126
1127      \note Parameter settings in the outgoing solver are not inherited by
1128            the incoming solver.
1129    */
1130    void assignSolver(OsiSolverInterface *&solver);
1131 
1132    /** Copy constructor .
1133      If noTree is true then tree and cuts are not copied
1134    */ 
1135    CbcModel(const CbcModel & rhs, bool noTree=false);
1136 
1137    /// Assignment operator
1138    CbcModel & operator=(const CbcModel& rhs);
1139 
1140    /// Destructor
1141     ~CbcModel ();
1142
1143    /// Returns solver - has current state
1144    OsiSolverInterface * solver() const
1145    { return solver_;};
1146
1147    /// Returns solver with continuous state
1148    OsiSolverInterface * continuousSolver() const
1149    { return continuousSolver_;};
1150  /// Clears out as much as possible (except solver)
1151  void gutsOfDestructor();
1152  //@}
1153
1154//---------------------------------------------------------------------------
1155
1156private:
1157  ///@name Private member data
1158  //@{
1159
1160  /// The solver associated with this model.
1161  OsiSolverInterface * solver_;
1162
1163  /** Ownership of the solver object
1164
1165    The convention is that CbcModel owns the null solver. Currently there
1166    is no public method to give CbcModel a solver without giving ownership,
1167    but the hook is here.
1168  */
1169  bool ourSolver_ ;
1170
1171  /// A copy of the solver, taken at the continuous (root) node.
1172  OsiSolverInterface * continuousSolver_;
1173
1174   /// Message handler
1175  CoinMessageHandler * handler_;
1176
1177  /** Flag to say if handler_ is the default handler.
1178 
1179    The default handler is deleted when the model is deleted. Other
1180    handlers (supplied by the client) will not be deleted.
1181  */
1182  bool defaultHandler_;
1183
1184  /// Cbc messages
1185  CoinMessages messages_;
1186
1187  /// Array for integer parameters
1188  int intParam_[CbcLastIntParam];
1189
1190  /// Array for double parameters
1191  double dblParam_[CbcLastDblParam];
1192
1193  /** Pointer to an empty warm start object
1194
1195    It turns out to be useful to have this available as a base from
1196    which to build custom warm start objects. This is typed as CoinWarmStart
1197    rather than CoinWarmStartBasis to allow for the possibility that a
1198    client might want to apply a solver that doesn't use a basis-based warm
1199    start. See getEmptyBasis for an example of how this field can be used.
1200  */
1201  mutable CoinWarmStart *emptyWarmStart_ ;
1202
1203  /** Pointer to a warm start basis.  */
1204  CoinWarmStartBasis *basis_;
1205
1206  /// Best objective
1207  double bestObjective_;
1208  /// Best possible objective
1209  double bestPossibleObjective_;
1210
1211  /// Array holding the incumbent (best) solution.
1212  double * bestSolution_;
1213
1214  /** Array holding the current solution.
1215
1216    This array is used more as a temporary.
1217  */
1218  double * currentSolution_;
1219
1220  /// Global cuts
1221  OsiCuts globalCuts_;
1222
1223  /// Minimum degradation in objective value to continue cut generation
1224  double minimumDrop_;
1225  /// Number of solutions
1226  int numberSolutions_;
1227  /// Hotstart strategy 0 =off, 1=branch if incorrect,2=branch even if correct, ....
1228  int hotstartStrategy_;
1229  /// Number of heuristic solutions
1230  int numberHeuristicSolutions_;
1231  /// Cumulative number of nodes
1232  int numberNodes_;
1233  /// Cumulative number of iterations
1234  int numberIterations_;
1235  /// Status of problem - 0 finished, 1 stopped, 2 difficulties
1236  int status_;
1237  /// Number of integers in problem
1238  int numberIntegers_;
1239  /// Number of rows at continuous
1240  int numberRowsAtContinuous_;
1241  /// Maximum number of cuts
1242  int maximumNumberCuts_;
1243  /** Current phase (so heuristics etc etc can find out).
1244      0 - initial solve
1245      1 - solve with cuts at root
1246      2 - solve with cuts
1247      3 - other e.g. strong branching
1248      4 - trying to validate a solution
1249      5 - at end of search
1250  */
1251  int phase_;
1252
1253  /// Number of entries in #addedCuts_
1254  int currentNumberCuts_;
1255
1256  /** Current limit on search tree depth
1257
1258    The allocated size of #walkback_. Increased as needed.
1259  */
1260  int maximumDepth_;
1261  /** Array used to assemble the path between a node and the search tree root
1262
1263    The array is resized when necessary. #maximumDepth_  is the current
1264    allocated size.
1265  */
1266  CbcNodeInfo ** walkback_;
1267
1268  /** The list of cuts initially collected for this subproblem
1269
1270    When the subproblem at this node is rebuilt, a set of cuts is collected
1271    for inclusion in the constraint system. If any of these cuts are
1272    subsequently removed because they have become loose, the corresponding
1273    entry is set to NULL.
1274  */
1275  CbcCountRowCut ** addedCuts_;
1276
1277  /** A pointer to a row cut which will be added instead of normal branching.
1278      After use it should be set to NULL.
1279  */
1280  OsiRowCut * nextRowCut_;
1281
1282  /// Current node so can be used elsewhere
1283  CbcNode * currentNode_;
1284
1285  /// Indices of integer variables
1286  int * integerVariable_;
1287  /// 0 bit - check if cuts valid (if on list)
1288  int specialOptions_;
1289  /// User node comparison function
1290  CbcCompareBase * nodeCompare_;
1291  /// Tree
1292  CbcTree * tree_;
1293  /// A pointer to model to be used for subtrees
1294  CbcModel * subTreeModel_;
1295  /// Number of times any subtree stopped on nodes, time etc
1296  int numberStoppedSubTrees_;
1297  /// Variable selection function
1298  CbcBranchDecision * branchingMethod_;
1299  /// Strategy
1300  CbcStrategy * strategy_;
1301  /// Parent model
1302  CbcModel * parentModel_;
1303  /** Whether to automatically do presolve before branch and bound.
1304      0 - no
1305      1 - ordinary presolve
1306      2 - integer presolve (dodgy)
1307  */
1308  /// Pointer to user-defined data structure
1309  void * appData_;
1310  int presolve_;
1311  /** Maximum number of candidates to consider for strong branching.
1312
1313    To disable strong branching, set this to 0.
1314  */
1315  int numberStrong_;
1316
1317  /// Print frequency
1318  int printFrequency_;
1319  /// Number of cut generators
1320  int numberCutGenerators_;
1321  // Cut generators
1322  CbcCutGenerator ** generator_;
1323  // Cut generators before any changes
1324  CbcCutGenerator ** virginGenerator_;
1325  /// Number of heuristics
1326  int numberHeuristics_;
1327  // Heuristic solvers
1328  CbcHeuristic ** heuristic_;
1329
1330  /// Total number of objects
1331  int numberObjects_;
1332
1333  /** \brief Integer and Clique and ... information
1334
1335    \note The code assumes that the first objects on the list will be
1336          SimpleInteger objects for each integer variable, followed by
1337          Clique objects. Portions of the code that understand Clique objects
1338          will fail if they do not immediately follow the SimpleIntegers.
1339          Large chunks of the code will fail if the first objects are not
1340          SimpleInteger. As of 2003.08, SimpleIntegers and Cliques are the only
1341          objects.
1342  */
1343  CbcObject ** object_;
1344
1345 
1346  /// Original columns as created by integerPresolve
1347  int * originalColumns_;
1348  /// Priorities
1349  int * priority_;
1350  /// How often to scan global cuts
1351  int howOftenGlobalScan_;
1352  /** Number of times global cuts violated.  When global cut pool then this
1353      should be kept for each cut and type of cut */
1354  int numberGlobalViolations_;
1355  /** Value of objective at continuous
1356      (Well actually after initial round of cuts)
1357  */
1358  double continuousObjective_;
1359  /** Value of objective before root node cuts added
1360  */
1361  double originalContinuousObjective_;
1362  /// Number of infeasibilities at continuous
1363  int continuousInfeasibilities_;
1364  /// Maximum number of cut passes at root
1365  int maximumCutPassesAtRoot_;
1366  /// Maximum number of cut passes
1367  int maximumCutPasses_;
1368  /// Current cut pass number
1369  int currentPassNumber_;
1370  /// Whether to force a resolve after takeOffCuts
1371  bool resolveAfterTakeOffCuts_;
1372 //@}
1373};
1374
1375#endif
Note: See TracBrowser for help on using the repository browser.