source: branches/devel/Cbc/src/CbcModel.hpp @ 587

Last change on this file since 587 was 587, checked in by forrest, 13 years ago

for lou and callable cbcmain

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 69.3 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#include <string>
6#include <vector>
7#include "CoinFinite.hpp"
8#include "CoinMessageHandler.hpp"
9#include "OsiSolverInterface.hpp"
10#include "OsiBranchingObject.hpp"
11#include "OsiCuts.hpp"
12#include "CoinWarmStartBasis.hpp"
13#include "CbcCompareBase.hpp"
14#include "CbcMessage.hpp"
15
16//class OsiSolverInterface;
17
18class CbcCutGenerator;
19class OsiRowCut;
20class OsiBabSolver;
21class OsiRowCutDebugger;
22class CglCutGenerator;
23class CbcCutModifier;
24class CglTreeProbingInfo;
25class CbcHeuristic;
26class OsiObject;
27class CbcTree;
28class CbcStrategy;
29class CbcFeasibilityBase;
30class CbcStatistics;
31class CbcEventHandler ;
32class CglPreProcess;
33
34// #define CBC_CHECK_BASIS 1
35
36//#############################################################################
37
38/** Simple Branch and bound class
39
40  The initialSolve() method solves the initial LP relaxation of the MIP
41  problem. The branchAndBound() method can then be called to finish using
42  a branch and cut algorithm.
43
44  <h3>Search Tree Traversal</h3>
45
46  Subproblems (aka nodes) requiring additional evaluation are stored using
47  the CbcNode and CbcNodeInfo objects. Ancestry linkage is maintained in the
48  CbcNodeInfo object. Evaluation of a subproblem within branchAndBound()
49  proceeds as follows:
50  <ul>
51    <li> The node representing the most promising parent subproblem is popped
52         from the heap which holds the set of subproblems requiring further
53         evaluation.
54    <li> Using branching instructions stored in the node, and information in
55         its ancestors, the model and solver are adjusted to create the
56         active subproblem.
57    <li> If the parent subproblem will require further evaluation
58         (<i>i.e.</i>, there are branches remaining) its node is pushed back
59         on the heap. Otherwise, the node is deleted.  This may trigger
60         recursive deletion of ancestors.
61    <li> The newly created subproblem is evaluated.
62    <li> If the subproblem requires further evaluation, a node is created.
63         All information needed to recreate the subproblem (branching
64         information, row and column cuts) is placed in the node and the node
65         is added to the set of subproblems awaiting further evaluation.
66  </ul>
67  Note that there is never a node representing the active subproblem; the model
68  and solver represent the active subproblem.
69
70  <h3>Row (Constraint) Cut Handling</h3>
71
72  For a typical subproblem, the sequence of events is as follows:
73  <ul>
74    <li> The subproblem is rebuilt for further evaluation: One result of a
75         call to addCuts() is a traversal of ancestors, leaving a list of all
76         cuts used in the ancestors in #addedCuts_. This list is then scanned
77         to construct a basis that includes only tight cuts. Entries for
78         loose cuts are set to NULL.
79    <li> The subproblem is evaluated: One result of a call to solveWithCuts()
80         is the return of a set of newly generated cuts for the subproblem.
81         #addedCuts_ is also kept up-to-date as old cuts become loose.
82    <li> The subproblem is stored for further processing: A call to
83         CbcNodeInfo::addCuts() adds the newly generated cuts to the
84         CbcNodeInfo object associated with this node.
85  </ul>
86  See CbcCountRowCut for details of the bookkeeping associated with cut
87  management.
88*/
89
90class CbcModel  {
91 
92public:
93
94enum CbcIntParam {
95  /** The maximum number of nodes before terminating */
96  CbcMaxNumNode=0,
97  /** The maximum number of solutions before terminating */
98  CbcMaxNumSol,
99  /** Fathoming discipline
100
101    Controls objective function comparisons for purposes of fathoming by bound
102    or determining monotonic variables.
103
104    If 1, action is taken only when the current objective is strictly worse
105    than the target. Implementation is handled by adding a small tolerance to
106    the target.
107  */
108  CbcFathomDiscipline,
109  /** Adjusts printout
110      1 does different node message with number unsatisfied on last branch
111  */
112  CbcPrinting,
113  /** Just a marker, so that a static sized array can store parameters. */
114  CbcLastIntParam
115};
116
117enum CbcDblParam {
118  /** The maximum amount the value of an integer variable can vary from
119      integer and still be considered feasible. */
120  CbcIntegerTolerance=0,
121  /** The objective is assumed to worsen by this amount for each
122      integer infeasibility. */
123  CbcInfeasibilityWeight,
124  /** The amount by which to tighten the objective function cutoff when
125      a new solution is discovered. */
126  CbcCutoffIncrement,
127  /** Stop when the gap between the objective value of the best known solution
128    and the best bound on the objective of any solution is less than this.
129 
130    This is an absolute value. Conversion from a percentage is left to the
131    client.
132  */
133  CbcAllowableGap,
134  /** Stop when the gap between the objective value of the best known solution
135    and the best bound on the objective of any solution is less than this
136    fraction of of the absolute value of best known solution.
137 
138    Code stops if either this test or CbcAllowableGap test succeeds
139  */
140  CbcAllowableFractionGap,
141  /** \brief The maximum number of seconds before terminating.
142             A double should be adequate! */
143  CbcMaximumSeconds,
144  /// Cutoff - stored for speed
145  CbcCurrentCutoff,
146  /// Optimization direction - stored for speed
147  CbcOptimizationDirection,
148  /// Current objective value
149  CbcCurrentObjectiveValue,
150  /// Current minimization objective value
151  CbcCurrentMinimizationObjectiveValue,
152  /** \brief The time at start of model.
153             So that other pieces of code can access */
154  CbcStartSeconds,
155  /** Just a marker, so that a static sized array can store parameters. */
156  CbcLastDblParam
157};
158
159  //---------------------------------------------------------------------------
160
161public:
162  ///@name Solve methods
163  //@{
164    /** \brief Solve the initial LP relaxation
165
166      Invoke the solver's %initialSolve() method.
167    */
168    void initialSolve(); 
169
170    /** \brief Invoke the branch \& cut algorithm
171
172      The method assumes that initialSolve() has been called to solve the
173      LP relaxation. It processes the root node, then proceeds to explore the
174      branch & cut search tree. The search ends when the tree is exhausted or
175      one of several execution limits is reached.
176      If doStatistics is 1 summary statistics are printed
177      if 2 then also the path to best solution (if found by branching)
178      if 3 then also one line per node
179    */
180     void branchAndBound(int doStatistics=0);
181
182    /** \brief create a clean model from partially fixed problem
183
184      The method creates a new model with given bounds and with no tree.
185    */
186     CbcModel *  cleanModel(const double * lower, const double * upper);
187    /** \brief Invoke the branch \& cut algorithm on partially fixed problem
188
189      The method presolves the given model and does branch and cut. The search
190      ends when the tree is exhausted or maximum nodes is reached.
191
192      If better solution found then it is saved.
193
194      Returns 0 if search completed and solution, 1 if not completed and solution,
195      2 if completed and no solution, 3 if not completed and no solution.
196
197      Normally okay to do cleanModel immediately followed by subBranchandBound
198      (== other form of subBranchAndBound)
199      but may need to get at model for advanced features.
200
201      Deletes model2
202    */
203     int subBranchAndBound(CbcModel * model2,
204                           CbcModel * presolvedModel,
205                           int maximumNodes);
206    /** \brief Invoke the branch \& cut algorithm on partially fixed problem
207
208      The method creates a new model with given bounds, presolves it
209      then proceeds to explore the branch & cut search tree. The search
210      ends when the tree is exhausted or maximum nodes is reached.
211
212      If better solution found then it is saved.
213
214      Returns 0 if search completed and solution, 1 if not completed and solution,
215      2 if completed and no solution, 3 if not completed and no solution.
216
217      This is just subModel immediately followed by other version of
218      subBranchandBound.
219
220    */
221     int subBranchAndBound(const double * lower, const double * upper,
222                            int maximumNodes);
223
224    /** \brief Process root node and return a strengthened model
225
226      The method assumes that initialSolve() has been called to solve the
227      LP relaxation. It processes the root node and then returns a pointer
228      to the strengthened model (or NULL if infeasible)
229    */
230     OsiSolverInterface *  strengthenedModel();
231  /** preProcess problem - replacing solver
232      If makeEquality true then <= cliques converted to ==.
233      Presolve will be done numberPasses times.
234
235      Returns NULL if infeasible
236
237      If makeEquality is 1 add slacks to get cliques,
238      if 2 add slacks to get sos (but only if looks plausible) and keep sos info
239  */
240  CglPreProcess * preProcess( int makeEquality=0, int numberPasses=5,
241                  int tuning=5);
242  /** Does postprocessing - original solver back.
243      User has to delete process */
244  void postProcess(CglPreProcess * process);
245private:
246    /** \brief Evaluate a subproblem using cutting planes and heuristics
247
248      The method invokes a main loop which generates cuts, applies heuristics,
249      and reoptimises using the solver's native %resolve() method.
250      It returns true if the subproblem remains feasible at the end of the
251      evaluation.
252    */
253  bool solveWithCuts(OsiCuts & cuts, int numberTries,CbcNode * node);
254  /** Input one node output N nodes to put on tree and optional solution update
255      This should be able to operate in parallel so is given a solver and is const(ish)
256      However we will need to keep an array of solver_ and bases and more
257      status is 0 for normal, 1 if solution
258      Calling code should always push nodes back on tree
259  */
260  CbcNode ** solveOneNode(int whichSolver,CbcNode * node, 
261                          int & numberNodesOutput, int & status) ;
262  /// Update size of whichGenerator
263  void resizeWhichGenerator(int numberNow, int numberAfter);
264public:
265    /** \brief Reoptimise an LP relaxation
266   
267      Invoke the solver's %resolve() method.
268      whereFrom -
269      0 - initial continuous
270      1 - resolve on branch (before new cuts)
271      2 - after new cuts
272      3  - obsolete code or something modified problem in unexpected way
273      10 - after strong branching has fixed variables at root
274      11 - after strong branching has fixed variables in tree
275
276      returns 1 feasible, 0 infeasible, -1 feasible but skip cuts
277    */
278    int resolve(CbcNodeInfo * parent, int whereFrom);
279    /// Make given rows (L or G) into global cuts and remove from lp
280    void makeGlobalCuts(int numberRows,const int * which); 
281    /// Make given cut into a global cut
282    void makeGlobalCut(const OsiRowCut * cut); 
283    /// Make given cut into a global cut
284    void makeGlobalCut(const OsiRowCut & cut); 
285  //@}
286
287  /** \name Presolve methods */
288  //@{
289
290  /** Identify cliques and construct corresponding objects.
291
292      Find cliques with size in the range
293      [\p atLeastThisMany, \p lessThanThis] and construct corresponding
294      CbcClique objects.
295      If \p makeEquality is true then a new model may be returned if
296      modifications had to be made, otherwise \c this is returned.
297      If the problem is infeasible #numberObjects_ is set to -1.
298      A client must use deleteObjects() before a second call to findCliques().
299      If priorities exist, clique priority is set to the default.
300  */
301  CbcModel * findCliques(bool makeEquality, int atLeastThisMany,
302                         int lessThanThis, int defaultValue=1000);
303
304  /** Do integer presolve, creating a new (presolved) model.
305
306    Returns the new model, or NULL if feasibility is lost.
307    If weak is true then just does a normal presolve
308 
309    \todo It remains to work out the cleanest way of getting a solution to
310          the original problem at the end. So this is very preliminary.
311   */
312  CbcModel * integerPresolve(bool weak=false);
313
314  /** Do integer presolve, modifying the current model.
315
316      Returns true if the model remains feasible after presolve.
317  */
318  bool integerPresolveThisModel(OsiSolverInterface * originalSolver,bool weak=false);
319
320
321  /// Put back information into the original model after integer presolve.
322  void originalModel(CbcModel * presolvedModel,bool weak);
323
324  /** \brief For variables involved in VUB constraints, see if we can tighten
325             bounds by solving lp's
326
327      Returns false if feasibility is lost.
328      If CglProbing is available, it will be tried as well to see if it can
329      tighten bounds.
330      This routine is just a front end for tightenVubs(int,const int*,double).
331
332      If <tt>type = -1</tt> all variables are processed (could be very slow).
333      If <tt>type = 0</tt> only variables involved in VUBs are processed.
334      If <tt>type = n > 0</tt>, only the n most expensive VUB variables
335      are processed, where it is assumed that x is at its maximum so delta
336      would have to go to 1 (if x not at bound).
337
338      If \p allowMultipleBinary is true, then a VUB constraint is a row with
339      one continuous variable and any number of binary variables.
340
341      If <tt>useCutoff < 1.0e30</tt>, the original objective is installed as a
342      constraint with \p useCutoff as a bound.
343  */
344  bool tightenVubs(int type,bool allowMultipleBinary=false,
345                   double useCutoff=1.0e50);
346 
347  /** \brief For variables involved in VUB constraints, see if we can tighten
348             bounds by solving lp's
349
350    This version is just handed a list of variables to be processed.
351  */
352  bool tightenVubs(int numberVubs, const int * which,
353                   double useCutoff=1.0e50);
354  /**
355    Analyze problem to find a minimum change in the objective function.
356  */
357  void analyzeObjective();
358
359
360  //@}
361
362  /** \name Object manipulation routines
363 
364    See OsiObject for an explanation of `object' in the context of CbcModel.
365  */
366  //@{
367
368  /// Get the number of objects
369  inline int numberObjects() const { return numberObjects_;};
370  /// Set the number of objects
371  inline void setNumberObjects(int number) 
372  {  numberObjects_=number;};
373
374  /// Get the array of objects
375  inline OsiObject ** objects() const { return object_;};
376
377  /// Get the specified object
378  const inline OsiObject * object(int which) const { return object_[which];};
379  /// Get the specified object
380  inline OsiObject * modifiableObject(int which) const { return object_[which];};
381
382  /// Delete all object information (and just back to integers if true)
383  void deleteObjects(bool findIntegers=true);
384
385  /** Add in object information.
386 
387    Objects are cloned; the owner can delete the originals.
388  */
389  void addObjects(int numberObjects, OsiObject ** objects);
390
391  /** Add in object information.
392 
393    Objects are cloned; the owner can delete the originals.
394  */
395  void addObjects(int numberObjects, CbcObject ** objects);
396
397  /// Ensure attached objects point to this model.
398  void synchronizeModel() ;
399
400  /** \brief Identify integer variables and create corresponding objects.
401 
402    Record integer variables and create an CbcSimpleInteger object for each
403    one.
404    If \p startAgain is true, a new scan is forced, overwriting any existing
405    integer variable information.
406    If type > 0 then 1==PseudoCost
407  */
408
409  void findIntegers(bool startAgain,int type=0);
410
411  //@}
412
413  //---------------------------------------------------------------------------
414
415  /**@name Parameter set/get methods
416
417     The set methods return true if the parameter was set to the given value,
418     false if the value of the parameter is out of range.
419
420     The get methods return the value of the parameter.
421
422  */
423  //@{
424  /// Set an integer parameter
425  inline bool setIntParam(CbcIntParam key, int value) {
426    intParam_[key] = value;
427    return true;
428  }
429  /// Set a double parameter
430  inline bool setDblParam(CbcDblParam key, double value) {
431    dblParam_[key] = value;
432    return true;
433  }
434  /// Get an integer parameter
435  inline int getIntParam(CbcIntParam key) const {
436    return intParam_[key];
437  }
438  /// Get a double parameter
439  inline double getDblParam(CbcDblParam key) const {
440    return dblParam_[key];
441  }
442  /*! \brief Set cutoff bound on the objective function.
443
444    When using strict comparison, the bound is adjusted by a tolerance to
445    avoid accidentally cutting off the optimal solution.
446  */
447  void setCutoff(double value) ;
448
449  /// Get the cutoff bound on the objective function - always as minimize
450  inline double getCutoff() const
451  { //double value ;
452    //solver_->getDblParam(OsiDualObjectiveLimit,value) ;
453    //assert( dblParam_[CbcCurrentCutoff]== value * solver_->getObjSense());
454    return dblParam_[CbcCurrentCutoff];
455  }
456
457  /// Set the \link CbcModel::CbcMaxNumNode maximum node limit \endlink
458  inline bool setMaximumNodes( int value)
459  { return setIntParam(CbcMaxNumNode,value); }
460
461  /// Get the \link CbcModel::CbcMaxNumNode maximum node limit \endlink
462  inline int getMaximumNodes() const
463  { return getIntParam(CbcMaxNumNode); }
464
465  /** Set the
466      \link CbcModel::CbcMaxNumSol maximum number of solutions \endlink
467      desired.
468  */
469  inline bool setMaximumSolutions( int value) {
470    return setIntParam(CbcMaxNumSol,value);
471  }
472  /** Get the
473      \link CbcModel::CbcMaxNumSol maximum number of solutions \endlink
474      desired.
475  */
476  inline int getMaximumSolutions() const {
477    return getIntParam(CbcMaxNumSol);
478  }
479  /// Set the printing mode
480  inline bool setPrintingMode( int value)
481  { return setIntParam(CbcPrinting,value); }
482
483  /// Get the printing mode
484  inline int getPrintingMode() const
485  { return getIntParam(CbcPrinting); }
486
487  /** Set the
488      \link CbcModel::CbcMaximumSeconds maximum number of seconds \endlink
489      desired.
490  */
491  inline bool setMaximumSeconds( double value) {
492    return setDblParam(CbcMaximumSeconds,value);
493  }
494  /** Get the
495      \link CbcModel::CbcMaximumSeconds maximum number of seconds \endlink
496      desired.
497  */
498  inline double getMaximumSeconds() const {
499    return getDblParam(CbcMaximumSeconds);
500  }
501  /// Current time since start of branchAndbound
502  double getCurrentSeconds() const ;
503
504  /** Set the
505    \link CbcModel::CbcIntegerTolerance integrality tolerance \endlink
506  */
507  inline bool setIntegerTolerance( double value) {
508    return setDblParam(CbcIntegerTolerance,value);
509  }
510  /** Get the
511    \link CbcModel::CbcIntegerTolerance integrality tolerance \endlink
512  */
513  inline double getIntegerTolerance() const {
514    return getDblParam(CbcIntegerTolerance);
515  }
516
517  /** Set the
518      \link CbcModel::CbcInfeasibilityWeight
519            weight per integer infeasibility \endlink
520  */
521  inline bool setInfeasibilityWeight( double value) {
522    return setDblParam(CbcInfeasibilityWeight,value);
523  }
524  /** Get the
525      \link CbcModel::CbcInfeasibilityWeight
526            weight per integer infeasibility \endlink
527  */
528  inline double getInfeasibilityWeight() const {
529    return getDblParam(CbcInfeasibilityWeight);
530  }
531
532  /** Set the \link CbcModel::CbcAllowableGap allowable gap \endlink
533      between the best known solution and the best possible solution.
534  */
535  inline bool setAllowableGap( double value) {
536    return setDblParam(CbcAllowableGap,value);
537  }
538  /** Get the \link CbcModel::CbcAllowableGap allowable gap \endlink
539      between the best known solution and the best possible solution.
540  */
541  inline double getAllowableGap() const {
542    return getDblParam(CbcAllowableGap);
543  }
544
545  /** Set the \link CbcModel::CbcAllowableFractionGap fraction allowable gap \endlink
546      between the best known solution and the best possible solution.
547  */
548  inline bool setAllowableFractionGap( double value) {
549    return setDblParam(CbcAllowableFractionGap,value);
550  }
551  /** Get the \link CbcModel::CbcAllowableFractionGap fraction allowable gap \endlink
552      between the best known solution and the best possible solution.
553  */
554  inline double getAllowableFractionGap() const {
555    return getDblParam(CbcAllowableFractionGap);
556  }
557  /** Set the \link CbcModel::CbcAllowableFractionGap percentage allowable gap \endlink
558      between the best known solution and the best possible solution.
559  */
560  inline bool setAllowablePercentageGap( double value) {
561    return setDblParam(CbcAllowableFractionGap,value*0.01);
562  }
563  /** Get the \link CbcModel::CbcAllowableFractionGap percentage allowable gap \endlink
564      between the best known solution and the best possible solution.
565  */
566  inline double getAllowablePercentageGap() const {
567    return 100.0*getDblParam(CbcAllowableFractionGap);
568  }
569  /** Set the
570      \link CbcModel::CbcCutoffIncrement  \endlink
571      desired.
572  */
573  inline bool setCutoffIncrement( double value) {
574    return setDblParam(CbcCutoffIncrement,value);
575  }
576  /** Get the
577      \link CbcModel::CbcCutoffIncrement  \endlink
578      desired.
579  */
580  inline double getCutoffIncrement() const {
581    return getDblParam(CbcCutoffIncrement);
582  }
583
584  /** Pass in target solution and optional priorities.
585      If priorities then >0 means only branch if incorrect
586      while <0 means branch even if correct. +1 or -1 are
587      highest priority */
588  void setHotstartSolution(const double * solution, const int * priorities=NULL) ;
589 
590  /// Set the minimum drop to continue cuts
591  inline void setMinimumDrop(double value)
592  {minimumDrop_=value;};
593  /// Get the minimum drop to continue cuts
594  inline double getMinimumDrop() const
595  { return minimumDrop_;};
596
597  /** Set the maximum number of cut passes at root node (default 20)
598      Minimum drop can also be used for fine tuning */
599  inline void setMaximumCutPassesAtRoot(int value)
600  {maximumCutPassesAtRoot_=value;};
601  /** Get the maximum number of cut passes at root node */
602  inline int getMaximumCutPassesAtRoot() const
603  { return maximumCutPassesAtRoot_;};
604
605  /** Set the maximum number of cut passes at other nodes (default 10)
606      Minimum drop can also be used for fine tuning */
607  inline void setMaximumCutPasses(int value)
608  {maximumCutPasses_=value;};
609  /** Get the maximum number of cut passes at other nodes (default 10) */
610  inline int getMaximumCutPasses() const
611  { return maximumCutPasses_;};
612  /** Get current cut pass number in this round of cuts.
613      (1 is first pass) */
614  inline int getCurrentPassNumber() const
615  { return currentPassNumber_;};
616
617  /** Set the maximum number of candidates to be evaluated for strong
618    branching.
619
620    A value of 0 disables strong branching.
621  */
622  void setNumberStrong(int number);
623  /** Get the maximum number of candidates to be evaluated for strong
624    branching.
625  */
626  inline int numberStrong() const
627  { return numberStrong_;};
628  /** Set global preferred way to branch
629      -1 down, +1 up, 0 no preference */
630  inline void setPreferredWay(int value)
631  {preferredWay_=value;};
632  /** Get the preferred way to branch (default 0) */
633  inline int getPreferredWay() const
634  { return preferredWay_;};
635  /** Set size of mini - tree.  If > 1 then does total enumeration of
636      tree given by this best variables to branch on
637  */
638  inline void setSizeMiniTree(int value)
639  { sizeMiniTree_=value;};
640  inline int sizeMiniTree() const
641  { return sizeMiniTree_;};
642
643  /** Set the number of branches before pseudo costs believed
644      in dynamic strong branching.
645
646    A value of 0 disables dynamic strong branching.
647  */
648  void setNumberBeforeTrust(int number);
649  /** get the number of branches before pseudo costs believed
650      in dynamic strong branching. */
651  inline int numberBeforeTrust() const
652  { return numberBeforeTrust_;};
653  /** Set the number of variables for which to compute penalties
654      in dynamic strong branching.
655
656    A value of 0 disables penalties.
657  */
658  void setNumberPenalties(int number);
659  /** get the number of variables for which to compute penalties
660      in dynamic strong branching. */
661  inline int numberPenalties() const
662  { return numberPenalties_;};
663  /// Number of analyze iterations to do
664  inline void setNumberAnalyzeIterations(int number)
665  { numberAnalyzeIterations_=number;};
666  inline int numberAnalyzeIterations() const
667  { return numberAnalyzeIterations_;};
668  /** Get scale factor to make penalties match strong.
669      Should/will be computed */
670  inline double penaltyScaleFactor() const
671  { return penaltyScaleFactor_;};
672  /** Set scale factor to make penalties match strong.
673      Should/will be computed */
674  void setPenaltyScaleFactor(double value);
675  /** Problem type as set by user or found by analysis.  This will be extended
676      0 - not known
677      1 - Set partitioning <=
678      2 - Set partitioning ==
679      3 - Set covering
680      4 - all +- 1 or all +1 and odd
681  */
682  void inline setProblemType(int number)
683  { problemType_=number;};
684  inline int problemType() const
685  { return problemType_;};
686
687  /// Set how often to scan global cuts
688  void setHowOftenGlobalScan(int number);
689  /// Get how often to scan global cuts
690  inline int howOftenGlobalScan() const
691  { return howOftenGlobalScan_;};
692  /// Original columns as created by integerPresolve
693  inline int * originalColumns() const
694  { return originalColumns_;};
695
696  /** Set the print frequency.
697 
698    Controls the number of nodes evaluated between status prints.
699    If <tt>number <=0</tt> the print frequency is set to 100 nodes for large
700    problems, 1000 for small problems.
701    Print frequency has very slight overhead if small.
702  */
703  inline void setPrintFrequency(int number)
704  { printFrequency_=number;};
705  /// Get the print frequency
706  inline int printFrequency() const
707  { return printFrequency_;};
708  //@}
709
710  //---------------------------------------------------------------------------
711  ///@name Methods returning info on how the solution process terminated
712  //@{
713    /// Are there a numerical difficulties?
714    bool isAbandoned() const;
715    /// Is optimality proven?
716    bool isProvenOptimal() const;
717    /// Is  infeasiblity proven (or none better than cutoff)?
718    bool isProvenInfeasible() const;
719    /// Was continuous solution unbounded
720    bool isContinuousUnbounded() const;
721    /// Was continuous solution unbounded
722    bool isProvenDualInfeasible() const;
723    /// Node limit reached?
724    bool isNodeLimitReached() const;
725    /// Time limit reached?
726    bool isSecondsLimitReached() const;
727    /// Solution limit reached?
728    bool isSolutionLimitReached() const;
729    /// Get how many iterations it took to solve the problem.
730    inline int getIterationCount() const
731    { return numberIterations_;};
732    /// Get how many Nodes it took to solve the problem.
733    inline int getNodeCount() const
734    { return numberNodes_;};
735    /** Final status of problem
736        Some of these can be found out by is...... functions
737        -1 before branchAndBound
738        0 finished - check isProvenOptimal or isProvenInfeasible to see if solution found
739        (or check value of best solution)
740        1 stopped - on maxnodes, maxsols, maxtime
741        2 difficulties so run was abandoned
742        (5 event user programmed event occurred)
743    */
744    inline int status() const
745    { return status_;};
746    inline void setProblemStatus(int value)
747    { status_=value;};
748    /** Secondary status of problem
749        -1 unset (status_ will also be -1)
750        0 search completed with solution
751        1 linear relaxation not feasible (or worse than cutoff)
752        2 stopped on gap
753        3 stopped on nodes
754        4 stopped on time
755        5 stopped on user event
756        6 stopped on solutions
757        7 linear relaxation unbounded
758    */
759    inline int secondaryStatus() const
760    { return secondaryStatus_;};
761    inline void setSecondaryStatus(int value)
762    { secondaryStatus_=value;};
763    /// Are there numerical difficulties (for initialSolve) ?
764    bool isInitialSolveAbandoned() const ;
765    /// Is optimality proven (for initialSolve) ?
766    bool isInitialSolveProvenOptimal() const ;
767    /// Is primal infeasiblity proven (for initialSolve) ?
768    bool isInitialSolveProvenPrimalInfeasible() const ;
769    /// Is dual infeasiblity proven (for initialSolve) ?
770    bool isInitialSolveProvenDualInfeasible() const ;
771
772  //@}
773
774  //---------------------------------------------------------------------------
775  /**@name Problem information methods
776     
777     These methods call the solver's query routines to return
778     information about the problem referred to by the current object.
779     Querying a problem that has no data associated with it result in
780     zeros for the number of rows and columns, and NULL pointers from
781     the methods that return vectors.
782     
783     Const pointers returned from any data-query method are valid as
784     long as the data is unchanged and the solver is not called.
785  */
786  //@{
787  /// Number of rows in continuous (root) problem.
788  inline int numberRowsAtContinuous() const
789  { return numberRowsAtContinuous_;};
790
791  /// Get number of columns
792  inline int getNumCols() const
793  { return solver_->getNumCols();};
794 
795  /// Get number of rows
796  inline int getNumRows() const
797  { return solver_->getNumRows();};
798 
799  /// Get number of nonzero elements
800  inline CoinBigIndex getNumElements() const
801  { return solver_->getNumElements();};
802
803  /// Number of integers in problem
804  inline int numberIntegers() const
805  { return numberIntegers_;};
806  // Integer variables
807  inline const int * integerVariable() const 
808  { return integerVariable_;};
809  /// Whether or not integer
810  inline const char integerType(int i) const
811  { return integerInfo_[i];};
812  /// Whether or not integer
813  inline const char * integerType() const
814  { return integerInfo_;};
815
816  /// Get pointer to array[getNumCols()] of column lower bounds
817  inline const double * getColLower() const
818  { return solver_->getColLower();};
819 
820  /// Get pointer to array[getNumCols()] of column upper bounds
821  inline const double * getColUpper() const
822  { return solver_->getColUpper();};
823 
824  /** Get pointer to array[getNumRows()] of row constraint senses.
825      <ul>
826      <li>'L': <= constraint
827      <li>'E': =  constraint
828      <li>'G': >= constraint
829      <li>'R': ranged constraint
830      <li>'N': free constraint
831      </ul>
832  */
833  inline const char * getRowSense() const
834  { return solver_->getRowSense();};
835 
836  /** Get pointer to array[getNumRows()] of rows right-hand sides
837      <ul>
838      <li> if rowsense()[i] == 'L' then rhs()[i] == rowupper()[i]
839      <li> if rowsense()[i] == 'G' then rhs()[i] == rowlower()[i]
840      <li> if rowsense()[i] == 'R' then rhs()[i] == rowupper()[i]
841      <li> if rowsense()[i] == 'N' then rhs()[i] == 0.0
842      </ul>
843  */
844  inline const double * getRightHandSide() const
845  { return solver_->getRightHandSide();};
846 
847  /** Get pointer to array[getNumRows()] of row ranges.
848      <ul>
849      <li> if rowsense()[i] == 'R' then
850      rowrange()[i] == rowupper()[i] - rowlower()[i]
851      <li> if rowsense()[i] != 'R' then
852      rowrange()[i] is 0.0
853      </ul>
854  */
855  inline const double * getRowRange() const
856  { return solver_->getRowRange();};
857 
858  /// Get pointer to array[getNumRows()] of row lower bounds
859  inline const double * getRowLower() const
860  { return solver_->getRowLower();};
861 
862  /// Get pointer to array[getNumRows()] of row upper bounds
863  inline const double * getRowUpper() const
864  { return solver_->getRowUpper();};
865 
866  /// Get pointer to array[getNumCols()] of objective function coefficients
867  inline const double * getObjCoefficients() const
868  { return solver_->getObjCoefficients();};
869 
870  /// Get objective function sense (1 for min (default), -1 for max)
871  inline double getObjSense() const
872  {
873    //assert (dblParam_[CbcOptimizationDirection]== solver_->getObjSense());
874    return dblParam_[CbcOptimizationDirection];};
875 
876  /// Return true if variable is continuous
877  inline bool isContinuous(int colIndex) const
878  { return solver_->isContinuous(colIndex);};
879 
880  /// Return true if variable is binary
881  inline bool isBinary(int colIndex) const
882  { return solver_->isBinary(colIndex);};
883 
884  /** Return true if column is integer.
885      Note: This function returns true if the the column
886      is binary or a general integer.
887  */
888  inline bool isInteger(int colIndex) const
889  { return solver_->isInteger(colIndex);};
890 
891  /// Return true if variable is general integer
892  inline bool isIntegerNonBinary(int colIndex) const
893  { return solver_->isIntegerNonBinary(colIndex);};
894 
895  /// Return true if variable is binary and not fixed at either bound
896  inline bool isFreeBinary(int colIndex) const
897  { return solver_->isFreeBinary(colIndex) ;};
898 
899  /// Get pointer to row-wise copy of matrix
900  inline const CoinPackedMatrix * getMatrixByRow() const
901  { return solver_->getMatrixByRow();};
902 
903  /// Get pointer to column-wise copy of matrix
904  inline const CoinPackedMatrix * getMatrixByCol() const
905  { return solver_->getMatrixByCol();};
906 
907  /// Get solver's value for infinity
908  inline double getInfinity() const
909  { return solver_->getInfinity();};
910  /// Get pointer to array[getNumCols()] (for speed) of column lower bounds
911  inline const double * getCbcColLower() const
912  { return cbcColLower_;};
913  /// Get pointer to array[getNumCols()] (for speed) of column upper bounds
914  inline const double * getCbcColUpper() const
915  { return cbcColUpper_;};
916  /// Get pointer to array[getNumRows()] (for speed) of row lower bounds
917  inline const double * getCbcRowLower() const
918  { return cbcRowLower_;};
919  /// Get pointer to array[getNumRows()] (for speed) of row upper bounds
920  inline const double * getCbcRowUpper() const
921  { return cbcRowUpper_;};
922  /// Get pointer to array[getNumCols()] (for speed) of primal solution vector
923  inline const double * getCbcColSolution() const
924  { return cbcColSolution_;};
925  /// Get pointer to array[getNumRows()] (for speed) of dual prices
926  inline const double * getCbcRowPrice() const
927  { return cbcRowPrice_;};
928  /// Get a pointer to array[getNumCols()] (for speed) of reduced costs
929  inline const double * getCbcReducedCost() const
930  { return cbcReducedCost_;};
931  /// Get pointer to array[getNumRows()] (for speed) of row activity levels.
932  inline const double * getCbcRowActivity() const
933  { return cbcRowActivity_;};
934  //@}
935 
936 
937  /**@name Methods related to querying the solution */
938  //@{
939  /// Holds solution at continuous (after cuts if branchAndBound called)
940  inline double * continuousSolution() const
941  { return continuousSolution_;};
942  /** Array marked whenever a solution is found if non-zero.
943      Code marks if heuristic returns better so heuristic
944      need only mark if it wants to on solutions which
945      are worse than current */
946  inline int * usedInSolution() const
947  { return usedInSolution_;};
948  /// Increases usedInSolution for nonzeros
949  void incrementUsed(const double * solution);
950  /// Record a new incumbent solution and update objectiveValue
951  void setBestSolution(CBC_Message how,
952                       double & objectiveValue, const double *solution,
953                       bool fixVariables=false);
954  /// Just update objectiveValue
955  void setBestObjectiveValue( double objectiveValue);
956
957  /** Call this to really test if a valid solution can be feasible
958      Solution is number columns in size.
959      If fixVariables true then bounds of continuous solver updated.
960      Returns objective value (worse than cutoff if not feasible)
961      Previously computed objective value is now passed in (in case user does not do solve)
962 */
963  double checkSolution(double cutoff, const double * solution,
964                       bool fixVariables, double originalObjValue);
965  /** Test the current solution for feasiblility.
966
967    Scan all objects for indications of infeasibility. This is broken down
968    into simple integer infeasibility (\p numberIntegerInfeasibilities)
969    and all other reports of infeasibility (\p numberObjectInfeasibilities).
970  */
971  bool feasibleSolution(int & numberIntegerInfeasibilities,
972                        int & numberObjectInfeasibilities) const;
973
974  /** Solution to the most recent lp relaxation.
975
976    The solver's solution to the most recent lp relaxation.
977  */
978   
979  inline double * currentSolution() const
980  { return currentSolution_;};
981  /** For testing infeasibilities - will point to
982      currentSolution_ or solver-->getColSolution()
983  */
984  inline const double * testSolution() const
985  { return testSolution_;};
986  inline void setTestSolution(const double * solution)
987  { testSolution_ = solution;};
988  /// Make sure region there and optionally copy solution
989  void reserveCurrentSolution(const double * solution=NULL);
990
991  /// Get pointer to array[getNumCols()] of primal solution vector
992  inline const double * getColSolution() const
993  { return solver_->getColSolution();};
994 
995  /// Get pointer to array[getNumRows()] of dual prices
996  inline const double * getRowPrice() const
997  { return solver_->getRowPrice();};
998 
999  /// Get a pointer to array[getNumCols()] of reduced costs
1000  inline const double * getReducedCost() const
1001  { return solver_->getReducedCost();};
1002 
1003  /// Get pointer to array[getNumRows()] of row activity levels.
1004  inline const double * getRowActivity() const
1005  { return solver_->getRowActivity();};
1006 
1007  /// Get current objective function value
1008  inline double getCurrentObjValue() const
1009  { return dblParam_[CbcCurrentObjectiveValue]; }
1010  /// Get current minimization objective function value
1011  inline double getCurrentMinimizationObjValue() const
1012  { return dblParam_[CbcCurrentMinimizationObjectiveValue];}
1013 
1014  /// Get best objective function value as minimization
1015  inline double getMinimizationObjValue() const
1016  { return bestObjective_;};
1017  /// Set best objective function value as minimization
1018  inline void setMinimizationObjValue(double value) 
1019  { bestObjective_=value;};
1020 
1021  /// Get best objective function value
1022  inline double getObjValue() const
1023  { return bestObjective_ * solver_->getObjSense() ; } ;
1024  /** Get best possible objective function value.
1025      This is better of best possible left on tree
1026      and best solution found.
1027      If called from within branch and cut may be optimistic.
1028  */
1029  double getBestPossibleObjValue() const;
1030  /// Set best objective function value
1031  inline void setObjValue(double value) 
1032  { bestObjective_=value * solver_->getObjSense() ;};
1033 
1034  /** The best solution to the integer programming problem.
1035
1036    The best solution to the integer programming problem found during
1037    the search. If no solution is found, the method returns null.
1038  */
1039
1040  inline double * bestSolution() const
1041  { return bestSolution_;};
1042 
1043  /// Get number of solutions
1044  inline int getSolutionCount() const
1045  { return numberSolutions_;};
1046 
1047  /// Set number of solutions (so heuristics will be different)
1048  inline void setSolutionCount(int value) 
1049  { numberSolutions_=value;};
1050  /** Current phase (so heuristics etc etc can find out).
1051      0 - initial solve
1052      1 - solve with cuts at root
1053      2 - solve with cuts
1054      3 - other e.g. strong branching
1055      4 - trying to validate a solution
1056      5 - at end of search
1057  */
1058  inline int phase() const
1059  { return phase_;};
1060 
1061  /// Get number of heuristic solutions
1062  inline int getNumberHeuristicSolutions() const { return numberHeuristicSolutions_;};
1063
1064  /// Set objective function sense (1 for min (default), -1 for max,)
1065  inline void setObjSense(double s) { dblParam_[CbcOptimizationDirection]=s;
1066  solver_->setObjSense(s);};
1067
1068  /// Value of objective at continuous
1069  inline double getContinuousObjective() const
1070  { return originalContinuousObjective_;};
1071  inline void setContinuousObjective(double value)
1072  { originalContinuousObjective_=value;};
1073  /// Number of infeasibilities at continuous
1074  inline int getContinuousInfeasibilities() const
1075  { return continuousInfeasibilities_;};
1076  inline void setContinuousInfeasibilities(int value)
1077  { continuousInfeasibilities_=value;};
1078  /// Value of objective after root node cuts added
1079  inline double rootObjectiveAfterCuts() const
1080  { return continuousObjective_;};
1081  /// Sum of Changes to objective by first solve
1082  inline double sumChangeObjective() const
1083  { return sumChangeObjective1_;};
1084  /** Number of times global cuts violated.  When global cut pool then this
1085      should be kept for each cut and type of cut */
1086  inline int numberGlobalViolations() const
1087  { return numberGlobalViolations_;};
1088  inline void clearNumberGlobalViolations()
1089  { numberGlobalViolations_=0;};
1090  /// Whether to force a resolve after takeOffCuts
1091  inline bool resolveAfterTakeOffCuts() const
1092  { return resolveAfterTakeOffCuts_;};
1093  inline void setResolveAfterTakeOffCuts(bool yesNo)
1094  { resolveAfterTakeOffCuts_=yesNo;};
1095  //@}
1096
1097  /** \name Node selection */
1098  //@{
1099  // Comparison functions (which may be overridden by inheritance)
1100  inline CbcCompareBase * nodeComparison() const
1101  { return nodeCompare_;};
1102  void setNodeComparison(CbcCompareBase * compare);
1103  void setNodeComparison(CbcCompareBase & compare);
1104  //@}
1105
1106  /** \name Problem feasibility checking */
1107  //@{
1108  // Feasibility functions (which may be overridden by inheritance)
1109  inline CbcFeasibilityBase * problemFeasibility() const
1110  { return problemFeasibility_;};
1111  void setProblemFeasibility(CbcFeasibilityBase * feasibility);
1112  void setProblemFeasibility(CbcFeasibilityBase & feasibility);
1113  //@}
1114
1115  /** \name Tree methods and subtree methods */
1116  //@{
1117  /// Tree method e.g. heap (which may be overridden by inheritance)
1118  inline CbcTree * tree() const
1119  { return tree_;};
1120  /// For modifying tree handling (original is cloned)
1121  void passInTreeHandler(CbcTree & tree);
1122  /** For passing in an CbcModel to do a sub Tree (with derived tree handlers).
1123      Passed in model must exist for duration of branch and bound
1124  */
1125  void passInSubTreeModel(CbcModel & model);
1126  /** For retrieving a copy of subtree model with given OsiSolver.
1127      If no subtree model will use self (up to user to reset cutoff etc).
1128      If solver NULL uses current
1129  */
1130  CbcModel * subTreeModel(OsiSolverInterface * solver=NULL) const;
1131  /// Returns number of times any subtree stopped on nodes, time etc
1132  inline int numberStoppedSubTrees() const
1133  { return numberStoppedSubTrees_;}
1134  /// Says a sub tree was stopped
1135  inline void incrementSubTreeStopped()
1136  { numberStoppedSubTrees_++;};
1137  /** Whether to automatically do presolve before branch and bound (subTrees).
1138      0 - no
1139      1 - ordinary presolve
1140      2 - integer presolve (dodgy)
1141  */
1142  inline int typePresolve() const
1143  { return presolve_;};
1144  inline void setTypePresolve(int value)
1145  { presolve_=value;};
1146  //@}
1147
1148  /** \name Branching Decisions
1149 
1150    See the CbcBranchDecision class for additional information.
1151  */
1152  //@{
1153
1154  /// Get the current branching decision method.
1155  inline CbcBranchDecision * branchingMethod() const
1156  { return branchingMethod_;};
1157  /// Set the branching decision method.
1158  inline void setBranchingMethod(CbcBranchDecision * method)
1159  { delete branchingMethod_; branchingMethod_ = method->clone();};
1160  /** Set the branching method
1161 
1162    \overload
1163  */
1164  inline void setBranchingMethod(CbcBranchDecision & method)
1165  { delete branchingMethod_; branchingMethod_ = method.clone();};
1166  /// Get the current cut modifier method
1167  inline CbcCutModifier * cutModifier() const
1168  { return cutModifier_;};
1169  /// Set the cut modifier method
1170  void setCutModifier(CbcCutModifier * modifier);
1171  /** Set the cut modifier method
1172 
1173    \overload
1174  */
1175  void setCutModifier(CbcCutModifier & modifier);
1176  //@}
1177
1178  /** \name Row (constraint) and Column (variable) cut generation */
1179  //@{
1180
1181  /** State of search
1182      0 - no solution
1183      1 - only heuristic solutions
1184      2 - branched to a solution
1185      3 - no solution but many nodes
1186  */
1187  inline int stateOfSearch() const
1188  { return stateOfSearch_;};
1189  inline void setStateOfSearch(int state)
1190  { stateOfSearch_=state;};
1191  /// Strategy worked out - mainly at root node for use by CbcNode
1192  inline int searchStrategy() const
1193  { return searchStrategy_;};
1194  /// Set strategy worked out - mainly at root node for use by CbcNode
1195  inline void setSearchStrategy(int value)
1196  { searchStrategy_ = value; };
1197
1198  /// Get the number of cut generators
1199  inline int numberCutGenerators() const
1200  { return numberCutGenerators_;};
1201  /// Get the list of cut generators
1202  inline CbcCutGenerator ** cutGenerators() const
1203  { return generator_;};
1204  ///Get the specified cut generator
1205  inline CbcCutGenerator * cutGenerator(int i) const
1206  { return generator_[i];};
1207  ///Get the specified cut generator before any changes
1208  inline CbcCutGenerator * virginCutGenerator(int i) const
1209  { return virginGenerator_[i];};
1210  /** Add one generator - up to user to delete generators.
1211      howoften affects how generator is used. 0 or 1 means always,
1212      >1 means every that number of nodes.  Negative values have same
1213      meaning as positive but they may be switched off (-> -100) by code if
1214      not many cuts generated at continuous.  -99 is just done at root.
1215      Name is just for printout.
1216      If depth >0 overrides how often generator is called (if howOften==-1 or >0).
1217  */
1218  void addCutGenerator(CglCutGenerator * generator,
1219                       int howOften=1, const char * name=NULL,
1220                       bool normal=true, bool atSolution=false, 
1221                       bool infeasible=false,int howOftenInSub=-100,
1222                       int whatDepth=-1, int whatDepthInSub=-1);
1223//@}
1224  /** \name Strategy and sub models
1225 
1226    See the CbcStrategy class for additional information.
1227  */
1228  //@{
1229
1230  /// Get the current strategy
1231  inline CbcStrategy * strategy() const
1232  { return strategy_;};
1233  /// Set the strategy. Clones
1234  void setStrategy(CbcStrategy & strategy);
1235  /// Get the current parent model
1236  inline CbcModel * parentModel() const
1237  { return parentModel_;};
1238  /// Set the parent model
1239  inline void setParentModel(CbcModel & parentModel)
1240  { parentModel_ = &parentModel;};
1241  //@}
1242
1243
1244  /** \name Heuristics and priorities */
1245  //@{
1246  /// Add one heuristic - up to user to delete
1247  void addHeuristic(CbcHeuristic * generator);
1248  ///Get the specified heuristic
1249  inline CbcHeuristic * heuristic(int i) const
1250  { return heuristic_[i];};
1251  /// Get the number of heuristics
1252  inline int numberHeuristics() const
1253  { return numberHeuristics_;};
1254  /// Pointer to heuristic solver which found last solution (or NULL)
1255  inline CbcHeuristic * lastHeuristic() const
1256  { return lastHeuristic_;};
1257  /// set last heuristic which found a solution
1258  inline void setLastHeuristic(CbcHeuristic * last)
1259  { lastHeuristic_=last;};
1260
1261  /** Pass in branching priorities.
1262 
1263      If ifClique then priorities are on cliques otherwise priorities are
1264      on integer variables. 
1265      Other type (if exists set to default)
1266      1 is highest priority. (well actually -INT_MAX is but that's ugly)
1267      If hotstart > 0 then branches are created to force
1268      the variable to the value given by best solution.  This enables a
1269      sort of hot start.  The node choice should be greatest depth
1270      and hotstart should normally be switched off after a solution.
1271
1272      If ifNotSimpleIntegers true then appended to normal integers
1273
1274      This is now deprecated except for simple usage.  If user
1275      creates Cbcobjects then set priority in them
1276
1277      \internal Added for Kurt Spielberg.
1278  */
1279  void passInPriorities(const int * priorities, bool ifNotSimpleIntegers);
1280
1281  /// Returns priority level for an object (or 1000 if no priorities exist)
1282  inline int priority(int sequence) const
1283  { return object_[sequence]->priority();}; 
1284
1285  /*! \brief Set an event handler
1286 
1287    A clone of the handler passed as a parameter is stored in CbcModel.
1288  */
1289  void passInEventHandler(const CbcEventHandler *eventHandler) ;
1290
1291  /*! \brief Retrieve a pointer to the event handler */
1292  inline CbcEventHandler* getEventHandler() const
1293  { return (eventHandler_) ; } ;
1294
1295  //@}
1296   
1297  /**@name Setting/Accessing application data */
1298  //@{
1299    /** Set application data.
1300
1301        This is a pointer that the application can store into and
1302        retrieve from the solver interface.
1303        This field is available for the application to optionally
1304        define and use.
1305    */
1306    void setApplicationData (void * appData);
1307
1308    /// Get application data
1309    void * getApplicationData() const;
1310  /**
1311      For advanced applications you may wish to modify the behavior of Cbc
1312      e.g. if the solver is a NLP solver then you may not have an exact
1313      optimum solution at each step.  Information could be built into
1314      OsiSolverInterface but this is an alternative so that that interface
1315      does not have to be changed.  If something similar is useful to
1316      enough solvers then it could be migrated
1317      You can also pass in by using solver->setAuxiliaryInfo.
1318      You should do that if solver is odd - if solver is normal simplex
1319      then use this.
1320      NOTE - characteristics are not cloned
1321  */
1322  void passInSolverCharacteristics(OsiBabSolver * solverCharacteristics);
1323  /// Get solver characteristics
1324  inline const OsiBabSolver * solverCharacteristics() const
1325  { return solverCharacteristics_;};
1326  //@}
1327 
1328  //---------------------------------------------------------------------------
1329
1330  /**@name Message handling */
1331  //@{
1332  /// Pass in Message handler (not deleted at end)
1333  void passInMessageHandler(CoinMessageHandler * handler);
1334  /// Set language
1335  void newLanguage(CoinMessages::Language language);
1336  inline void setLanguage(CoinMessages::Language language)
1337  {newLanguage(language);};
1338  /// Return handler
1339  inline CoinMessageHandler * messageHandler() const
1340  {return handler_;};
1341  /// Return messages
1342  inline CoinMessages & messages() 
1343  {return messages_;};
1344  /// Return pointer to messages
1345  inline CoinMessages * messagesPointer() 
1346  {return &messages_;};
1347  /// Set log level
1348  void setLogLevel(int value);
1349  /// Get log level
1350  inline int logLevel() const
1351  { return handler_->logLevel();};
1352  //@}
1353  //---------------------------------------------------------------------------
1354  ///@name Specialized
1355  //@{
1356
1357  /**
1358      Set special options
1359      0 bit (1) - check if cuts valid (if on debugger list)
1360      1 bit (2) - use current basis to check integer solution (rather than all slack)
1361      2 bit (4) - don't check integer solution (by solving LP)
1362      3 bit (8) - fast analyze
1363      4 bit (16) - non-linear model - so no well defined CoinPackedMatrix
1364      5 bit (32) - keep names
1365      6 bit (64) - try for dominated columns
1366  */
1367  /// Set special options
1368  inline void setSpecialOptions(int value)
1369  { specialOptions_=value;};
1370  /// Get special options
1371  inline int specialOptions() const
1372  { return specialOptions_;};
1373  /// Says if normal solver i.e. has well defined CoinPackedMatrix
1374  inline bool normalSolver() const
1375  { return (specialOptions_&16)==0;};
1376  /// Now we may not own objects - just point to solver's objects
1377  inline bool ownObjects() const
1378  { return ownObjects_;};
1379  //@}
1380  //---------------------------------------------------------------------------
1381
1382  ///@name Constructors and destructors etc
1383  //@{
1384    /// Default Constructor
1385    CbcModel(); 
1386   
1387    /// Constructor from solver
1388    CbcModel(const OsiSolverInterface &);
1389 
1390    /** Assign a solver to the model (model assumes ownership)
1391
1392      On return, \p solver will be NULL.
1393      If deleteSolver then current solver deleted (if model owned)
1394
1395      \note Parameter settings in the outgoing solver are not inherited by
1396            the incoming solver.
1397    */
1398    void assignSolver(OsiSolverInterface *&solver,bool deleteSolver=true);
1399
1400    /** \brief Set ownership of solver
1401
1402      A parameter of false tells CbcModel it does not own the solver and
1403      should not delete it. Once you claim ownership of the solver, you're
1404      responsible for eventually deleting it. Note that CbcModel clones
1405      solvers with abandon.  Unless you have a deep understanding of the
1406      workings of CbcModel, the only time you want to claim ownership is when
1407      you're about to delete the CbcModel object but want the solver to
1408      continue to exist (as, for example, when branchAndBound has finished
1409      and you want to hang on to the answer).
1410    */
1411    inline void setModelOwnsSolver (bool ourSolver)
1412    { ourSolver_ = ourSolver ; } ;
1413
1414    /*! \brief Get ownership of solver
1415   
1416      A return value of true means that CbcModel owns the solver and will
1417      take responsibility for deleting it when that becomes necessary.
1418    */
1419    inline bool modelOwnsSolver () { return (ourSolver_) ; } ;
1420 
1421    /** Copy constructor .
1422      If noTree is true then tree and cuts are not copied
1423    */ 
1424    CbcModel(const CbcModel & rhs, bool noTree=false);
1425 
1426    /// Assignment operator
1427    CbcModel & operator=(const CbcModel& rhs);
1428 
1429    /// Destructor
1430     ~CbcModel ();
1431
1432    /// Returns solver - has current state
1433    inline OsiSolverInterface * solver() const
1434    { return solver_;};
1435
1436    /// Returns solver with continuous state
1437    inline OsiSolverInterface * continuousSolver() const
1438    { return continuousSolver_;};
1439
1440  /// A copy of the solver, taken at constructor or by saveReferenceSolver
1441  inline OsiSolverInterface * referenceSolver() const
1442  { return referenceSolver_;};
1443
1444  /// Save a copy of the current solver so can be reset to
1445  void saveReferenceSolver();
1446
1447  /** Uses a copy of reference solver to be current solver.
1448      Because of possible mismatches all exotic integer information is loat
1449      (apart from normal information in OsiSolverInterface)
1450      so SOS etc and priorities will have to be redone
1451  */
1452  void resetToReferenceSolver();
1453
1454  /// Clears out as much as possible (except solver)
1455  void gutsOfDestructor();
1456  /** Clears out enough to reset CbcModel as if no branch and bound done
1457   */
1458  void gutsOfDestructor2();
1459  //@}
1460
1461  ///@semi-private i.e. users should not use
1462  //@{
1463    /// Get how many Nodes it took to solve the problem.
1464    int getNodeCount2() const
1465    { return numberNodes2_;};
1466  /// Set pointers for speed
1467  void setPointers(const OsiSolverInterface * solver);
1468  /** Perform reduced cost fixing
1469
1470    Fixes integer variables at their current value based on reduced cost
1471    penalties.  Returns number fixed
1472  */
1473  int reducedCostFix() ;
1474  /// Encapsulates solver resolve
1475  int resolve(OsiSolverInterface * solver);
1476
1477  /** Encapsulates choosing a variable -
1478      anyAction -2, infeasible (-1 round again), 0 done
1479  */
1480  int chooseBranch(CbcNode * newNode, int numberPassesLeft,
1481                   CbcNode * oldNode, OsiCuts & cuts,
1482                   bool & resolved, CoinWarmStartBasis *lastws,
1483                   const double * lowerBefore,const double * upperBefore,
1484                   OsiSolverBranch * & branches);
1485  int chooseBranch(CbcNode * newNode, int numberPassesLeft, bool & resolved);
1486
1487  /** Return an empty basis object of the specified size
1488
1489    A useful utility when constructing a basis for a subproblem from scratch.
1490    The object returned will be of the requested capacity and appropriate for
1491    the solver attached to the model.
1492  */
1493  CoinWarmStartBasis *getEmptyBasis(int ns = 0, int na = 0) const ;
1494
1495  /** Remove inactive cuts from the model
1496
1497    An OsiSolverInterface is expected to maintain a valid basis, but not a
1498    valid solution, when loose cuts are deleted. Restoring a valid solution
1499    requires calling the solver to reoptimise. If it's certain the solution
1500    will not be required, set allowResolve to false to suppress
1501    reoptimisation.
1502    If saveCuts then slack cuts will be saved
1503  */
1504  void takeOffCuts(OsiCuts &cuts, 
1505                     bool allowResolve,OsiCuts * saveCuts) ;
1506
1507  /** Determine and install the active cuts that need to be added for
1508    the current subproblem
1509
1510    The whole truth is a bit more complicated. The first action is a call to
1511    addCuts1(). addCuts() then sorts through the list, installs the tight
1512    cuts in the model, and does bookkeeping (adjusts reference counts).
1513    The basis returned from addCuts1() is adjusted accordingly.
1514   
1515    If it turns out that the node should really be fathomed by bound,
1516    addCuts() simply treats all the cuts as loose as it does the bookkeeping.
1517
1518    canFix true if extra information being passed
1519  */
1520  int addCuts(CbcNode * node, CoinWarmStartBasis *&lastws,bool canFix);
1521
1522  /** Traverse the tree from node to root and prep the model
1523
1524    addCuts1() begins the job of prepping the model to match the current
1525    subproblem. The model is stripped of all cuts, and the search tree is
1526    traversed from node to root to determine the changes required. Appropriate
1527    bounds changes are installed, a list of cuts is collected but not
1528    installed, and an appropriate basis (minus the cuts, but big enough to
1529    accommodate them) is constructed.
1530
1531    \todo addCuts1() is called in contexts where it's known in advance that
1532          all that's desired is to determine a list of cuts and do the
1533          bookkeeping (adjust the reference counts). The work of installing
1534          bounds and building a basis goes to waste.
1535  */
1536  void addCuts1(CbcNode * node, CoinWarmStartBasis *&lastws);
1537  /** Set objective value in a node.  This is separated out so that
1538     odd solvers can use.  It may look at extra information in
1539     solverCharacteriscs_ and will also use bound from parent node
1540  */
1541  void setObjectiveValue(CbcNode * thisNode, const CbcNode * parentNode) const;
1542
1543  /** If numberBeforeTrust >0 then we are going to use CbcBranchDynamic.
1544      Scan and convert CbcSimpleInteger objects
1545  */
1546  void convertToDynamic();
1547  /// Use cliques for pseudocost information - return nonzero if infeasible
1548  int cliquePseudoCosts(int doStatistics);
1549  /// Fill in useful estimates
1550  void pseudoShadow(double * down, double * up);
1551
1552  /// Get the hotstart solution
1553  inline const double * hotstartSolution() const
1554  { return hotstartSolution_;};
1555  /// Get the hotstart priorities
1556  inline const int * hotstartPriorities() const
1557  { return hotstartPriorities_;};
1558
1559  /// Return the list of cuts initially collected for this subproblem
1560  inline CbcCountRowCut ** addedCuts() const
1561  { return addedCuts_;};
1562  /// Number of entries in the list returned by #addedCuts()
1563  inline int currentNumberCuts() const
1564  { return currentNumberCuts_;};
1565  /// Global cuts
1566  inline OsiCuts * globalCuts() 
1567  { return &globalCuts_;};
1568  /// Copy and set a pointer to a row cut which will be added instead of normal branching.
1569  void setNextRowCut(const OsiRowCut & cut);
1570  /// Get a pointer to current node (be careful)
1571  inline CbcNode * currentNode() const
1572  { return currentNode_;};
1573  /// Get a pointer to probing info
1574  inline CglTreeProbingInfo * probingInfo() const
1575  { return probingInfo_;};
1576  /// Set the number of iterations done in strong branching.
1577  inline void setNumberStrongIterations(int number)
1578  { numberStrongIterations_ = number;};
1579  /// Get the number of iterations done in strong branching.
1580  inline int numberStrongIterations() const
1581  { return numberStrongIterations_;};
1582  /// Increment strong info
1583  void incrementStrongInfo(int numberTimes, int numberIterations,
1584                           int numberFixed, bool ifInfeasible);
1585  /// Create C++ lines to get to current state
1586  void generateCpp( FILE * fp,int options);
1587  /// Generate an OsiBranchingInformation object
1588  OsiBranchingInformation usefulInformation() const;
1589  //@}
1590
1591//---------------------------------------------------------------------------
1592
1593private:
1594  ///@name Private member data
1595  //@{
1596
1597  /// The solver associated with this model.
1598  OsiSolverInterface * solver_;
1599
1600  /** Ownership of the solver object
1601
1602    The convention is that CbcModel owns the null solver. Currently there
1603    is no public method to give CbcModel a solver without giving ownership,
1604    but the hook is here.
1605  */
1606  bool ourSolver_ ;
1607
1608  /// A copy of the solver, taken at the continuous (root) node.
1609  OsiSolverInterface * continuousSolver_;
1610
1611  /// A copy of the solver, taken at constructor or by saveReferenceSolver
1612  OsiSolverInterface * referenceSolver_;
1613
1614   /// Message handler
1615  CoinMessageHandler * handler_;
1616
1617  /** Flag to say if handler_ is the default handler.
1618 
1619    The default handler is deleted when the model is deleted. Other
1620    handlers (supplied by the client) will not be deleted.
1621  */
1622  bool defaultHandler_;
1623
1624  /// Cbc messages
1625  CoinMessages messages_;
1626
1627  /// Array for integer parameters
1628  int intParam_[CbcLastIntParam];
1629
1630  /// Array for double parameters
1631  double dblParam_[CbcLastDblParam];
1632
1633  /** Pointer to an empty warm start object
1634
1635    It turns out to be useful to have this available as a base from
1636    which to build custom warm start objects. This is typed as CoinWarmStart
1637    rather than CoinWarmStartBasis to allow for the possibility that a
1638    client might want to apply a solver that doesn't use a basis-based warm
1639    start. See getEmptyBasis for an example of how this field can be used.
1640  */
1641  mutable CoinWarmStart *emptyWarmStart_ ;
1642
1643  /// Best objective
1644  double bestObjective_;
1645  /// Best possible objective
1646  double bestPossibleObjective_;
1647  /// Sum of Changes to objective by first solve
1648  double sumChangeObjective1_;
1649  /// Sum of Changes to objective by subsequent solves
1650  double sumChangeObjective2_;
1651
1652  /// Array holding the incumbent (best) solution.
1653  double * bestSolution_;
1654
1655  /** Array holding the current solution.
1656
1657    This array is used more as a temporary.
1658  */
1659  double * currentSolution_;
1660  /** For testing infeasibilities - will point to
1661      currentSolution_ or solver-->getColSolution()
1662  */
1663  mutable const double * testSolution_;
1664  /// Global cuts
1665  OsiCuts globalCuts_;
1666
1667  /// Minimum degradation in objective value to continue cut generation
1668  double minimumDrop_;
1669  /// Number of solutions
1670  int numberSolutions_;
1671  /** State of search
1672      0 - no solution
1673      1 - only heuristic solutions
1674      2 - branched to a solution
1675      3 - no solution but many nodes
1676  */
1677  int stateOfSearch_;
1678  /// Hotstart solution
1679  double * hotstartSolution_;
1680  /// Hotstart priorities
1681  int * hotstartPriorities_;
1682  /// Number of heuristic solutions
1683  int numberHeuristicSolutions_;
1684  /// Cumulative number of nodes
1685  int numberNodes_;
1686  /** Cumulative number of nodes for statistics.
1687      Must fix to match up
1688  */
1689  int numberNodes2_;
1690  /// Cumulative number of iterations
1691  int numberIterations_;
1692  /// Status of problem - 0 finished, 1 stopped, 2 difficulties
1693  int status_;
1694  /** Secondary status of problem
1695      -1 unset (status_ will also be -1)
1696      0 search completed with solution
1697      1 linear relaxation not feasible (or worse than cutoff)
1698      2 stopped on gap
1699      3 stopped on nodes
1700      4 stopped on time
1701      5 stopped on user event
1702      6 stopped on solutions
1703   */
1704  int secondaryStatus_;
1705  /// Number of integers in problem
1706  int numberIntegers_;
1707  /// Number of rows at continuous
1708  int numberRowsAtContinuous_;
1709  /// Maximum number of cuts
1710  int maximumNumberCuts_;
1711  /** Current phase (so heuristics etc etc can find out).
1712      0 - initial solve
1713      1 - solve with cuts at root
1714      2 - solve with cuts
1715      3 - other e.g. strong branching
1716      4 - trying to validate a solution
1717      5 - at end of search
1718  */
1719  int phase_;
1720
1721  /// Number of entries in #addedCuts_
1722  int currentNumberCuts_;
1723
1724  /** Current limit on search tree depth
1725
1726    The allocated size of #walkback_. Increased as needed.
1727  */
1728  int maximumDepth_;
1729  /** Array used to assemble the path between a node and the search tree root
1730
1731    The array is resized when necessary. #maximumDepth_  is the current
1732    allocated size.
1733  */
1734  CbcNodeInfo ** walkback_;
1735
1736  /** The list of cuts initially collected for this subproblem
1737
1738    When the subproblem at this node is rebuilt, a set of cuts is collected
1739    for inclusion in the constraint system. If any of these cuts are
1740    subsequently removed because they have become loose, the corresponding
1741    entry is set to NULL.
1742  */
1743  CbcCountRowCut ** addedCuts_;
1744
1745  /** A pointer to a row cut which will be added instead of normal branching.
1746      After use it should be set to NULL.
1747  */
1748  OsiRowCut * nextRowCut_;
1749
1750  /// Current node so can be used elsewhere
1751  CbcNode * currentNode_;
1752
1753  /// Indices of integer variables
1754  int * integerVariable_;
1755  /// Whether of not integer
1756  char * integerInfo_;
1757  /// Holds solution at continuous (after cuts)
1758  double * continuousSolution_;
1759  /// Array marked whenever a solution is found if non-zero
1760  int * usedInSolution_;
1761  /**
1762      0 bit (1) - check if cuts valid (if on debugger list)
1763      1 bit (2) - use current basis to check integer solution (rather than all slack)
1764      2 bit (4) - don't check integer solution
1765      3 bit (8) - Strong is doing well - keep on
1766  */
1767  int specialOptions_;
1768  /// User node comparison function
1769  CbcCompareBase * nodeCompare_;
1770  /// User feasibility function (see CbcFeasibleBase.hpp)
1771  CbcFeasibilityBase * problemFeasibility_;
1772  /// Tree
1773  CbcTree * tree_;
1774  /// A pointer to model to be used for subtrees
1775  CbcModel * subTreeModel_;
1776  /// Number of times any subtree stopped on nodes, time etc
1777  int numberStoppedSubTrees_;
1778  /// Variable selection function
1779  CbcBranchDecision * branchingMethod_;
1780  /// Cut modifier function
1781  CbcCutModifier * cutModifier_;
1782  /// Strategy
1783  CbcStrategy * strategy_;
1784  /// Parent model
1785  CbcModel * parentModel_;
1786  /** Whether to automatically do presolve before branch and bound.
1787      0 - no
1788      1 - ordinary presolve
1789      2 - integer presolve (dodgy)
1790  */
1791  /// Pointer to array[getNumCols()] (for speed) of column lower bounds
1792  const double * cbcColLower_;
1793  /// Pointer to array[getNumCols()] (for speed) of column upper bounds
1794  const double * cbcColUpper_;
1795  /// Pointer to array[getNumRows()] (for speed) of row lower bounds
1796  const double * cbcRowLower_;
1797  /// Pointer to array[getNumRows()] (for speed) of row upper bounds
1798  const double * cbcRowUpper_;
1799  /// Pointer to array[getNumCols()] (for speed) of primal solution vector
1800  const double * cbcColSolution_;
1801  /// Pointer to array[getNumRows()] (for speed) of dual prices
1802  const double * cbcRowPrice_;
1803  /// Get a pointer to array[getNumCols()] (for speed) of reduced costs
1804  const double * cbcReducedCost_;
1805  /// Pointer to array[getNumRows()] (for speed) of row activity levels.
1806  const double * cbcRowActivity_;
1807  /// Pointer to user-defined data structure
1808  void * appData_;
1809  /// Pointer to
1810  int presolve_;
1811  /** Maximum number of candidates to consider for strong branching.
1812    To disable strong branching, set this to 0.
1813  */
1814  int numberStrong_;
1815  /** \brief The number of branches before pseudo costs believed
1816             in dynamic strong branching.
1817     
1818    A value of 0 is  off.
1819  */
1820  int numberBeforeTrust_;
1821  /** \brief The number of variables for which to compute penalties
1822             in dynamic strong branching.
1823  */
1824  int numberPenalties_;
1825  /** Scale factor to make penalties match strong.
1826      Should/will be computed */
1827  double penaltyScaleFactor_;
1828  /// Number of analyze iterations to do
1829  int numberAnalyzeIterations_;
1830  /// Arrays with analysis results
1831  double * analyzeResults_;
1832  /// Number of nodes infeasible by normal branching (before cuts)
1833  int numberInfeasibleNodes_;
1834  /** Problem type as set by user or found by analysis.  This will be extended
1835      0 - not known
1836      1 - Set partitioning <=
1837      2 - Set partitioning ==
1838      3 - Set covering
1839  */
1840  int problemType_;
1841  /// Print frequency
1842  int printFrequency_;
1843  /// Number of cut generators
1844  int numberCutGenerators_;
1845  // Cut generators
1846  CbcCutGenerator ** generator_;
1847  // Cut generators before any changes
1848  CbcCutGenerator ** virginGenerator_;
1849  /// Number of heuristics
1850  int numberHeuristics_;
1851  /// Heuristic solvers
1852  CbcHeuristic ** heuristic_;
1853  /// Pointer to heuristic solver which found last solution (or NULL)
1854  CbcHeuristic * lastHeuristic_;
1855  /*! Pointer to the event handler */
1856# ifdef CBC_ONLY_CLP
1857  ClpEventHandler *eventHandler_ ;
1858# else
1859  CbcEventHandler *eventHandler_ ;
1860# endif
1861
1862  /// Total number of objects
1863  int numberObjects_;
1864
1865  /** \brief Integer and Clique and ... information
1866
1867    \note The code assumes that the first objects on the list will be
1868          SimpleInteger objects for each integer variable, followed by
1869          Clique objects. Portions of the code that understand Clique objects
1870          will fail if they do not immediately follow the SimpleIntegers.
1871          Large chunks of the code will fail if the first objects are not
1872          SimpleInteger. As of 2003.08, SimpleIntegers and Cliques are the only
1873          objects.
1874  */
1875  OsiObject ** object_;
1876  /// Now we may not own objects - just point to solver's objects
1877  bool ownObjects_;
1878 
1879  /// Original columns as created by integerPresolve
1880  int * originalColumns_;
1881  /// How often to scan global cuts
1882  int howOftenGlobalScan_;
1883  /** Number of times global cuts violated.  When global cut pool then this
1884      should be kept for each cut and type of cut */
1885  int numberGlobalViolations_;
1886  /** Value of objective at continuous
1887      (Well actually after initial round of cuts)
1888  */
1889  double continuousObjective_;
1890  /** Value of objective before root node cuts added
1891  */
1892  double originalContinuousObjective_;
1893  /// Number of infeasibilities at continuous
1894  int continuousInfeasibilities_;
1895  /// Maximum number of cut passes at root
1896  int maximumCutPassesAtRoot_;
1897  /// Maximum number of cut passes
1898  int maximumCutPasses_;
1899  /// Preferred way of branching
1900  int preferredWay_;
1901  /// Current cut pass number
1902  int currentPassNumber_;
1903  /// Maximum number of cuts (for whichGenerator_)
1904  int maximumWhich_;
1905  /// Which cut generator generated this cut
1906  int * whichGenerator_;
1907  /// Maximum number of statistics
1908  int maximumStatistics_;
1909  /// statistics
1910  CbcStatistics ** statistics_;
1911  /// Maximum depth reached
1912  int maximumDepthActual_;
1913  /// Number of reduced cost fixings
1914  double numberDJFixed_;
1915  /// Probing info
1916  CglTreeProbingInfo * probingInfo_;
1917  /// Number of fixed by analyze at root
1918  int numberFixedAtRoot_;
1919  /// Number fixed by analyze so far
1920  int numberFixedNow_;
1921  /// Whether stopping on gap
1922  bool stoppedOnGap_;
1923  /// Whether event happened
1924  bool eventHappened_;
1925  /// Number of long strong goes
1926  int numberLongStrong_;
1927  /// Number of old active cuts
1928  int numberOldActiveCuts_;
1929  /// Number of new cuts
1930  int numberNewCuts_;
1931  /// Size of mini - tree
1932  int sizeMiniTree_;
1933  /// Strategy worked out - mainly at root node
1934  int searchStrategy_;
1935  /// Number of iterations in strong branching
1936  int numberStrongIterations_;
1937  /** 0 - number times strong branching done, 1 - number fixed, 2 - number infeasible */
1938  int strongInfo_[3];
1939  /**
1940      For advanced applications you may wish to modify the behavior of Cbc
1941      e.g. if the solver is a NLP solver then you may not have an exact
1942      optimum solution at each step.  This gives characteristics - just for one BAB.
1943      For actually saving/restoring a solution you need the actual solver one.
1944  */
1945  OsiBabSolver * solverCharacteristics_;
1946  /// Whether to force a resolve after takeOffCuts
1947  bool resolveAfterTakeOffCuts_;
1948 //@}
1949};
1950/// So we can use osiObject or CbcObject during transition
1951void getIntegerInformation(const OsiObject * object, double & originalLower,
1952                           double & originalUpper) ;
1953// So we can call from other programs
1954// Real main program
1955class OsiClpSolverInterface;
1956int CbcMain (int argc, const char *argv[],OsiClpSolverInterface & solver,CbcModel ** babSolver);
1957// four ways of calling
1958int callCbc(const char * input2, OsiClpSolverInterface& solver1); 
1959int callCbc(const char * input2);
1960int callCbc(const std::string input2, OsiClpSolverInterface& solver1); 
1961int callCbc(const std::string input2) ;
1962#endif
Note: See TracBrowser for help on using the repository browser.