source: trunk/Clp/src/ClpModel.hpp @ 1150

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

try and make a bit faster

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 40.9 KB
Line 
1// Copyright (C) 2002, International Business Machines
2// Corporation and others.  All Rights Reserved.
3#ifndef ClpModel_H
4#define ClpModel_H
5
6#include "ClpConfig.h"
7
8#include <iostream>
9#include <cassert>
10#include <cmath>
11#include <vector>
12#include <string>
13//#ifndef COIN_USE_CLP
14//#define COIN_USE_CLP
15//#endif
16#include "ClpPackedMatrix.hpp"
17#include "CoinMessageHandler.hpp"
18#include "CoinHelperFunctions.hpp"
19#include "ClpParameters.hpp"
20#include "ClpObjective.hpp"
21class ClpEventHandler;
22
23// Plus infinity
24#ifndef COIN_DBL_MAX
25#define COIN_DBL_MAX DBL_MAX
26#endif
27
28/** This is the base class for Linear and quadratic Models
29    This knows nothing about the algorithm, but it seems to
30    have a reasonable amount of information
31
32    I would welcome suggestions for what should be in this and
33    how it relates to OsiSolverInterface.  Some methods look
34    very similar.
35
36*/
37class CoinBuild;
38class CoinModel;
39class ClpModel {
40
41public:
42
43  /**@name Constructors and destructor
44     Note - copy methods copy ALL data so can chew up memory
45     until other copy is freed
46   */
47  //@{
48    /// Default constructor
49    ClpModel (bool emptyMessages=false  );
50
51  /** Copy constructor. May scale depending on mode
52      -1 leave mode as is
53      0 -off, 1 equilibrium, 2 geometric, 3, auto, 4 auto-but-as-initialSolve-in-bab
54  */
55    ClpModel(const ClpModel & rhs, int scalingMode=-1);
56    /// Assignment operator. This copies the data
57    ClpModel & operator=(const ClpModel & rhs);
58  /** Subproblem constructor.  A subset of whole model is created from the
59      row and column lists given.  The new order is given by list order and
60      duplicates are allowed.  Name and integer information can be dropped
61  */
62    ClpModel (const ClpModel * wholeModel,
63      int numberRows, const int * whichRows,
64      int numberColumns, const int * whichColumns,
65              bool dropNames=true, bool dropIntegers=true);
66    /// Destructor
67    ~ClpModel (  );
68  //@}
69
70  /**@name Load model - loads some stuff and initializes others */
71  //@{
72    /** Loads a problem (the constraints on the
73        rows are given by lower and upper bounds). If a pointer is 0 then the
74        following values are the default:
75        <ul>
76          <li> <code>colub</code>: all columns have upper bound infinity
77          <li> <code>collb</code>: all columns have lower bound 0
78          <li> <code>rowub</code>: all rows have upper bound infinity
79          <li> <code>rowlb</code>: all rows have lower bound -infinity
80          <li> <code>obj</code>: all variables have 0 objective coefficient
81        </ul>
82    */
83  void loadProblem (  const ClpMatrixBase& matrix,
84                     const double* collb, const double* colub,   
85                     const double* obj,
86                     const double* rowlb, const double* rowub,
87                      const double * rowObjective=NULL);
88  void loadProblem (  const CoinPackedMatrix& matrix,
89                     const double* collb, const double* colub,   
90                     const double* obj,
91                     const double* rowlb, const double* rowub,
92                      const double * rowObjective=NULL);
93
94  /** Just like the other loadProblem() method except that the matrix is
95        given in a standard column major ordered format (without gaps). */
96  void loadProblem (  const int numcols, const int numrows,
97                     const CoinBigIndex* start, const int* index,
98                     const double* value,
99                     const double* collb, const double* colub,   
100                     const double* obj,
101                      const double* rowlb, const double* rowub,
102                      const double * rowObjective=NULL);
103  /** This loads a model from a coinModel object - returns number of errors.
104
105      modelObject not const as may be changed as part of process
106      If tryPlusMinusOne then will try adding as +-1 matrix
107  */
108  int loadProblem (  CoinModel & modelObject,bool tryPlusMinusOne=false);
109  /// This one is for after presolve to save memory
110  void loadProblem (  const int numcols, const int numrows,
111                     const CoinBigIndex* start, const int* index,
112                      const double* value,const int * length,
113                     const double* collb, const double* colub,   
114                     const double* obj,
115                      const double* rowlb, const double* rowub,
116                      const double * rowObjective=NULL);
117  /** Load up quadratic objective.  This is stored as a CoinPackedMatrix */
118  void loadQuadraticObjective(const int numberColumns, 
119                              const CoinBigIndex * start,
120                              const int * column, const double * element);
121  void loadQuadraticObjective (  const CoinPackedMatrix& matrix);
122  /// Get rid of quadratic objective
123  void deleteQuadraticObjective();
124  /// This just loads up a row objective
125  void setRowObjective(const double * rowObjective);
126  /// Read an mps file from the given filename
127  int readMps(const char *filename,
128              bool keepNames=false,
129              bool ignoreErrors = false);
130  /// Read GMPL files from the given filenames
131  int readGMPL(const char *filename,const char * dataName,
132               bool keepNames=false);
133  /// Copy in integer informations
134  void copyInIntegerInformation(const char * information);
135  /// Drop integer informations
136  void deleteIntegerInformation();
137  /** Set the index-th variable to be a continuous variable */
138  void setContinuous(int index);
139  /** Set the index-th variable to be an integer variable */
140  void setInteger(int index);
141  /** Return true if the index-th variable is an integer variable */
142  bool isInteger(int index) const;
143  /// Resizes rim part of model
144  void resize (int newNumberRows, int newNumberColumns);
145  /// Deletes rows
146  void deleteRows(int number, const int * which);
147  /// Add one row
148  void addRow(int numberInRow, const int * columns,
149               const double * elements, double rowLower=-COIN_DBL_MAX, 
150              double rowUpper=COIN_DBL_MAX);
151  /// Add rows
152  void addRows(int number, const double * rowLower, 
153               const double * rowUpper,
154               const CoinBigIndex * rowStarts, const int * columns,
155               const double * elements);
156  /// Add rows
157  void addRows(int number, const double * rowLower, 
158               const double * rowUpper,
159               const CoinBigIndex * rowStarts, const int * rowLengths,
160               const int * columns,
161               const double * elements);
162#ifndef CLP_NO_VECTOR
163  void addRows(int number, const double * rowLower, 
164               const double * rowUpper,
165               const CoinPackedVectorBase * const * rows);
166#endif
167  /** Add rows from a build object.
168      If tryPlusMinusOne then will try adding as +-1 matrix
169      if no matrix exists.
170      Returns number of errors e.g. duplicates
171  */
172  int addRows(const CoinBuild & buildObject,bool tryPlusMinusOne=false,
173               bool checkDuplicates=true);
174  /** Add rows from a model object.  returns
175      -1 if object in bad state (i.e. has column information)
176      otherwise number of errors.
177
178      modelObject non const as can be regularized as part of build
179      If tryPlusMinusOne then will try adding as +-1 matrix
180      if no matrix exists.
181  */
182  int addRows(CoinModel & modelObject,bool tryPlusMinusOne=false,
183              bool checkDuplicates=true);
184
185  /// Deletes columns
186  void deleteColumns(int number, const int * which);
187  /// Add one column
188  void addColumn(int numberInColumn,
189                 const int * rows,
190                 const double * elements,
191                 double columnLower=0.0, 
192                 double  columnUpper=COIN_DBL_MAX,
193                 double  objective=0.0);
194  /// Add columns
195  void addColumns(int number, const double * columnLower, 
196                  const double * columnUpper,
197                  const double * objective,
198                  const CoinBigIndex * columnStarts, const int * rows,
199                  const double * elements);
200  void addColumns(int number, const double * columnLower, 
201                  const double * columnUpper,
202                  const double * objective,
203                  const CoinBigIndex * columnStarts, const int * columnLengths,
204                  const int * rows,
205                  const double * elements);
206#ifndef CLP_NO_VECTOR
207  void addColumns(int number, const double * columnLower, 
208               const double * columnUpper,
209                  const double * objective,
210               const CoinPackedVectorBase * const * columns);
211#endif
212  /** Add columns from a build object
213      If tryPlusMinusOne then will try adding as +-1 matrix
214      if no matrix exists.
215      Returns number of errors e.g. duplicates
216  */
217  int addColumns(const CoinBuild & buildObject,bool tryPlusMinusOne=false,
218                  bool checkDuplicates=true);
219  /** Add columns from a model object.  returns
220      -1 if object in bad state (i.e. has row information)
221      otherwise number of errors
222      modelObject non const as can be regularized as part of build
223      If tryPlusMinusOne then will try adding as +-1 matrix
224      if no matrix exists.
225  */
226  int addColumns(CoinModel & modelObject,bool tryPlusMinusOne=false,
227                 bool checkDuplicates=true);
228  /// Modify one element of a matrix
229  inline void modifyCoefficient(int row, int column, double newElement,
230                           bool keepZero=false)
231        {matrix_->modifyCoefficient(row,column,newElement,keepZero);}
232  /** Change row lower bounds */
233  void chgRowLower(const double * rowLower);
234  /** Change row upper bounds */
235  void chgRowUpper(const double * rowUpper);
236  /** Change column lower bounds */
237  void chgColumnLower(const double * columnLower);
238  /** Change column upper bounds */
239  void chgColumnUpper(const double * columnUpper);
240  /** Change objective coefficients */
241  void chgObjCoefficients(const double * objIn); 
242  /** Borrow model.  This is so we don't have to copy large amounts
243      of data around.  It assumes a derived class wants to overwrite
244      an empty model with a real one - while it does an algorithm */
245  void borrowModel(ClpModel & otherModel);
246  /** Return model - nulls all arrays so can be deleted safely
247      also updates any scalars */
248  void returnModel(ClpModel & otherModel);
249
250  /// Create empty ClpPackedMatrix
251  void createEmptyMatrix();
252  /** Really clean up matrix (if ClpPackedMatrix).
253      a) eliminate all duplicate AND small elements in matrix
254      b) remove all gaps and set extraGap_ and extraMajor_ to 0.0
255      c) reallocate arrays and make max lengths equal to lengths
256      d) orders elements
257      returns number of elements eliminated or -1 if not ClpPackedMatrix
258  */
259  int cleanMatrix(double threshold=1.0e-20);
260  /// Copy contents - resizing if necessary - otherwise re-use memory
261  void copy(const ClpMatrixBase * from, ClpMatrixBase * & to);
262#ifndef CLP_NO_STD
263  /// Drops names - makes lengthnames 0 and names empty
264  void dropNames();
265  /// Copies in names
266  void copyNames(std::vector<std::string> & rowNames,
267                 std::vector<std::string> & columnNames);
268  /// Copies in Row names - modifies names first .. last-1
269  void copyRowNames(const std::vector<std::string> & rowNames,int first, int last);
270  /// Copies in Column names - modifies names first .. last-1
271  void copyColumnNames(const std::vector<std::string> & columnNames, int first, int last);
272  /// Copies in Row names - modifies names first .. last-1
273  void copyRowNames(const char * const * rowNames,int first, int last);
274  /// Copies in Column names - modifies names first .. last-1
275  void copyColumnNames(const char * const * columnNames, int first, int last);
276  /// Set name of row
277  void setRowName(int rowIndex, std::string & name) ;
278  /// Set name of col
279  void setColumnName(int colIndex, std::string & name) ;
280#endif
281  /** Find a network subset.
282      rotate array should be numberRows.  On output
283      -1 not in network
284       0 in network as is
285       1 in network with signs swapped
286      Returns number of network rows
287  */
288  int findNetwork(char * rotate, double fractionNeeded=0.75);
289  /** This creates a coinModel object
290  */
291  CoinModel * createCoinModel() const;
292
293    /** Write the problem in MPS format to the specified file.
294
295        Row and column names may be null.
296        formatType is
297        <ul>
298          <li> 0 - normal
299          <li> 1 - extra accuracy
300          <li> 2 - IEEE hex (later)
301        </ul>
302
303        Returns non-zero on I/O error
304    */
305    int writeMps(const char *filename, 
306                  int formatType=0,int numberAcross=2,
307                 double objSense=0.0) const ;
308  //@}
309  /**@name gets and sets */
310  //@{
311   /// Number of rows
312   inline int numberRows() const {
313      return numberRows_;
314   }
315   inline int getNumRows() const {
316      return numberRows_;
317   }
318   /// Number of columns
319   inline int getNumCols() const {
320      return numberColumns_;
321   }
322   inline int numberColumns() const {
323      return numberColumns_;
324   }
325   /// Primal tolerance to use
326   inline double primalTolerance() const {
327      return dblParam_[ClpPrimalTolerance];
328   }
329   void setPrimalTolerance( double value) ;
330   /// Dual tolerance to use
331   inline double dualTolerance() const  { return dblParam_[ClpDualTolerance]; }
332   void setDualTolerance( double value) ;
333  /// Primal objective limit
334  inline double primalObjectiveLimit() const { return dblParam_[ClpPrimalObjectiveLimit];}
335  void setPrimalObjectiveLimit(double value);
336  /// Dual objective limit
337  inline double dualObjectiveLimit() const { return dblParam_[ClpDualObjectiveLimit];}
338  void setDualObjectiveLimit(double value);
339  /// Objective offset
340  inline double objectiveOffset() const { return dblParam_[ClpObjOffset];}
341  void setObjectiveOffset(double value);
342  /// Presolve tolerance to use
343  inline double presolveTolerance() const
344  { return dblParam_[ClpPresolveTolerance];}
345#ifndef CLP_NO_STD
346  inline std::string problemName() const { return strParam_[ClpProbName]; }
347#endif
348   /// Number of iterations
349   inline int numberIterations() const  { return numberIterations_; }
350   inline int getIterationCount() const { return numberIterations_; }
351  inline void setNumberIterations(int numberIterations)
352  { numberIterations_ = numberIterations;}
353  /** Solve type - 1 simplex, 2 simplex interface, 3 Interior.*/
354  inline int solveType() const
355  { return solveType_;}
356  inline void setSolveType(int type)
357  { solveType_=type;}
358   /// Maximum number of iterations
359   inline int maximumIterations() const { return intParam_[ClpMaxNumIteration]; }
360   void setMaximumIterations(int value);
361  /// Maximum time in seconds (from when set called)
362   inline double maximumSeconds() const { return dblParam_[ClpMaxSeconds]; }
363   void setMaximumSeconds(double value);
364  /// Returns true if hit maximum iterations (or time)
365  bool hitMaximumIterations() const;
366   /** Status of problem:
367       -1 - unknown e.g. before solve or if postSolve says not optimal
368       0 - optimal
369       1 - primal infeasible
370       2 - dual infeasible
371       3 - stopped on iterations or time
372       4 - stopped due to errors
373       5 - stopped by event handler (virtual int ClpEventHandler::event())
374   */
375   inline int status() const            { return problemStatus_; }
376   inline int problemStatus() const            { return problemStatus_; }
377  /// Set problem status
378  inline void setProblemStatus(int problemStatus)
379  { problemStatus_ = problemStatus;}
380   /** Secondary status of problem - may get extended
381       0 - none
382       1 - primal infeasible because dual limit reached OR probably primal
383       infeasible but can't prove it (main status 4)
384       2 - scaled problem optimal - unscaled problem has primal infeasibilities
385       3 - scaled problem optimal - unscaled problem has dual infeasibilities
386       4 - scaled problem optimal - unscaled problem has primal and dual infeasibilities
387       5 - giving up in primal with flagged variables
388       6 - failed due to empty problem check
389       7 - postSolve says not optimal
390       8 - failed due to bad element check
391       9 - status was 3 and stopped on time
392       100 up - translation of enum from ClpEventHandler
393   */
394   inline int secondaryStatus() const            { return secondaryStatus_; }
395  inline void setSecondaryStatus(int status)
396  { secondaryStatus_ = status;}
397   /// Are there a numerical difficulties?
398   inline bool isAbandoned() const             { return problemStatus_==4; }
399   /// Is optimality proven?
400   inline bool isProvenOptimal() const         { return problemStatus_==0; }
401   /// Is primal infeasiblity proven?
402   inline bool isProvenPrimalInfeasible() const { return problemStatus_==1; }
403   /// Is dual infeasiblity proven?
404   inline bool isProvenDualInfeasible() const  { return problemStatus_==2; }
405   /// Is the given primal objective limit reached?
406   bool isPrimalObjectiveLimitReached() const ;
407   /// Is the given dual objective limit reached?
408   bool isDualObjectiveLimitReached() const ;
409   /// Iteration limit reached?
410   inline bool isIterationLimitReached() const { return problemStatus_==3; }
411   /// Direction of optimization (1 - minimize, -1 - maximize, 0 - ignore
412   inline double optimizationDirection() const {
413      return  optimizationDirection_;
414   }
415   inline double getObjSense() const    { return optimizationDirection_; }
416   void setOptimizationDirection(double value);
417   /// Primal row solution
418   inline double * primalRowSolution() const    { return rowActivity_; }
419   inline const double * getRowActivity() const { return rowActivity_; }
420   /// Primal column solution
421   inline double * primalColumnSolution() const { return columnActivity_; }
422   inline const double * getColSolution() const { return columnActivity_; }
423   inline void setColSolution(const double * input)
424   { memcpy(columnActivity_,input,numberColumns_*sizeof(double));}
425   /// Dual row solution
426   inline double * dualRowSolution() const      { return dual_; }
427   inline const double * getRowPrice() const    { return dual_; }
428   /// Reduced costs
429   inline double * dualColumnSolution() const   { return reducedCost_; }
430   inline const double * getReducedCost() const { return reducedCost_; }
431   /// Row lower
432   inline double* rowLower() const              { return rowLower_; }
433   inline const double* getRowLower() const     { return rowLower_; }
434   /// Row upper
435   inline double* rowUpper() const              { return rowUpper_; }
436   inline const double* getRowUpper() const     { return rowUpper_; }
437    //-------------------------------------------------------------------------
438    /**@name Changing bounds on variables and constraints */
439    //@{
440       /** Set an objective function coefficient */
441       void setObjectiveCoefficient( int elementIndex, double elementValue );
442       /** Set an objective function coefficient */
443       inline void setObjCoeff( int elementIndex, double elementValue )
444       { setObjectiveCoefficient( elementIndex, elementValue);}
445
446      /** Set a single column lower bound<br>
447          Use -DBL_MAX for -infinity. */
448       void setColumnLower( int elementIndex, double elementValue );
449     
450      /** Set a single column upper bound<br>
451          Use DBL_MAX for infinity. */
452       void setColumnUpper( int elementIndex, double elementValue );
453
454      /** Set a single column lower and upper bound */
455      void setColumnBounds( int elementIndex,
456        double lower, double upper );
457
458      /** Set the bounds on a number of columns simultaneously<br>
459          The default implementation just invokes setColLower() and
460          setColUpper() over and over again.
461          @param indexFirst,indexLast pointers to the beginning and after the
462                 end of the array of the indices of the variables whose
463                 <em>either</em> bound changes
464          @param boundList the new lower/upper bound pairs for the variables
465      */
466      void setColumnSetBounds(const int* indexFirst,
467                                   const int* indexLast,
468                                   const double* boundList);
469     
470      /** Set a single column lower bound<br>
471          Use -DBL_MAX for -infinity. */
472       inline void setColLower( int elementIndex, double elementValue )
473       { setColumnLower(elementIndex, elementValue);}
474      /** Set a single column upper bound<br>
475          Use DBL_MAX for infinity. */
476       inline void setColUpper( int elementIndex, double elementValue )
477       { setColumnUpper(elementIndex, elementValue);}
478
479      /** Set a single column lower and upper bound */
480      inline void setColBounds( int elementIndex,
481        double lower, double upper )
482       { setColumnBounds(elementIndex, lower, upper);}
483
484      /** Set the bounds on a number of columns simultaneously<br>
485          @param indexFirst,indexLast pointers to the beginning and after the
486                 end of the array of the indices of the variables whose
487                 <em>either</em> bound changes
488          @param boundList the new lower/upper bound pairs for the variables
489      */
490      inline void setColSetBounds(const int* indexFirst,
491                                   const int* indexLast,
492                                   const double* boundList)
493      { setColumnSetBounds(indexFirst, indexLast, boundList);}
494     
495      /** Set a single row lower bound<br>
496          Use -DBL_MAX for -infinity. */
497      void setRowLower( int elementIndex, double elementValue );
498     
499      /** Set a single row upper bound<br>
500          Use DBL_MAX for infinity. */
501      void setRowUpper( int elementIndex, double elementValue ) ;
502   
503      /** Set a single row lower and upper bound */
504      void setRowBounds( int elementIndex,
505                                 double lower, double upper ) ;
506   
507      /** Set the bounds on a number of rows simultaneously<br>
508          @param indexFirst,indexLast pointers to the beginning and after the
509                 end of the array of the indices of the constraints whose
510                 <em>either</em> bound changes
511          @param boundList the new lower/upper bound pairs for the constraints
512      */
513      void setRowSetBounds(const int* indexFirst,
514                                   const int* indexLast,
515                                   const double* boundList);
516   
517    //@}
518   /// Scaling
519   inline const double * rowScale() const {return rowScale_;}
520   inline const double * columnScale() const {return columnScale_;}
521   inline double * mutableRowScale() const {return rowScale_;}
522   inline double * mutableColumnScale() const {return columnScale_;}
523   void setRowScale(double * scale) ;
524   void setColumnScale(double * scale);
525  /// Scaling of objective
526  inline double objectiveScale() const 
527          { return objectiveScale_;} 
528  inline void setObjectiveScale(double value)
529          { objectiveScale_ = value;} 
530  /// Scaling of rhs and bounds
531  inline double rhsScale() const 
532          { return rhsScale_;} 
533  inline void setRhsScale(double value)
534          { rhsScale_ = value;} 
535   /// Sets or unsets scaling, 0 -off, 1 equilibrium, 2 geometric, 3 auto, 4 auto-but-as-initialSolve-in-bab
536   void scaling(int mode=1);
537  /** If we constructed a "really" scaled model then this reverses the operation.
538      Quantities may not be exactly as they were before due to rounding errors */
539  void unscale();
540   /// Gets scalingFlag
541   inline int scalingFlag() const {return scalingFlag_;}
542   /// Objective
543   inline double * objective() const           
544  {
545    if (objective_) {
546      double offset; 
547      return objective_->gradient(NULL,NULL,offset,false);
548    } else {
549      return NULL;
550    }
551  }
552   inline double * objective(const double * solution, double & offset,bool refresh=true) const           
553  {
554    offset=0.0;
555    if (objective_) {
556      return objective_->gradient(NULL,solution,offset,refresh);
557    } else {
558      return NULL;
559    }
560  }
561   inline const double * getObjCoefficients() const 
562  { 
563    if (objective_) {
564      double offset; 
565      return objective_->gradient(NULL,NULL,offset,false);
566    } else {
567      return NULL;
568    }
569  }
570   /// Row Objective
571   inline double * rowObjective() const         { return rowObjective_; }
572   inline const double * getRowObjCoefficients() const {
573      return rowObjective_;
574   }
575   /// Column Lower
576   inline double * columnLower() const          { return columnLower_; }
577   inline const double * getColLower() const    { return columnLower_; }
578   /// Column Upper
579   inline double * columnUpper() const          { return columnUpper_; }
580   inline const double * getColUpper() const    { return columnUpper_; }
581   /// Matrix (if not ClpPackedmatrix be careful about memory leak
582   inline CoinPackedMatrix * matrix() const {
583     if ( matrix_ == NULL ) return NULL;
584     else return matrix_->getPackedMatrix();
585   }
586   /// Number of elements in matrix
587   inline int getNumElements() const 
588     { return matrix_->getNumElements();}
589   /** Small element value - elements less than this set to zero,
590      default is 1.0e-20 */
591   inline double getSmallElementValue() const
592  { return smallElement_;}
593  inline void setSmallElementValue(double value)
594  { smallElement_=value;} 
595   /// Row Matrix
596   inline ClpMatrixBase * rowCopy() const       { return rowCopy_; }
597   /// Clp Matrix
598   inline ClpMatrixBase * clpMatrix() const     { return matrix_; }
599   /// Scaled ClpPackedMatrix
600   inline ClpPackedMatrix * clpScaledMatrix() const     { return scaledMatrix_; }
601   /// Sets pointer to scaled ClpPackedMatrix
602   inline void setClpScaledMatrix(ClpPackedMatrix * scaledMatrix)
603  { delete scaledMatrix_; scaledMatrix_=scaledMatrix; }
604  /** Replace Clp Matrix (current is not deleted unless told to
605      and new is used)
606      So up to user to delete current.  This was used where
607      matrices were being rotated. ClpModel takes ownership.
608  */
609   void replaceMatrix(ClpMatrixBase * matrix,bool deleteCurrent=false);
610  /** Replace Clp Matrix (current is not deleted unless told to
611      and new is used) So up to user to delete current.  This was used where
612      matrices were being rotated.  This version changes CoinPackedMatrix
613      to ClpPackedMatrix.  ClpModel takes ownership.
614  */
615   inline void replaceMatrix(CoinPackedMatrix * matrix,
616                             bool deleteCurrent=false)
617  { replaceMatrix(new ClpPackedMatrix(matrix),deleteCurrent);}
618   /// Objective value
619   inline double objectiveValue() const {
620      return objectiveValue_*optimizationDirection_ - dblParam_[ClpObjOffset];
621   }
622  inline void setObjectiveValue(double value) {
623    objectiveValue_ = (value+ dblParam_[ClpObjOffset])/optimizationDirection_;
624   }
625   inline double getObjValue() const {
626      return objectiveValue_*optimizationDirection_ - dblParam_[ClpObjOffset];
627   }
628   /// Integer information
629   inline char * integerInformation() const     { return integerType_; }
630   /** Infeasibility/unbounded ray (NULL returned if none/wrong)
631       Up to user to use delete [] on these arrays.  */
632   double * infeasibilityRay() const;
633   double * unboundedRay() const;
634  /// See if status (i.e. basis) array exists (partly for OsiClp)
635  inline bool statusExists() const
636  { return (status_!=NULL);}
637  /// Return address of status (i.e. basis) array (char[numberRows+numberColumns])
638  inline unsigned char *  statusArray() const
639  { return status_;}
640  /** Return copy of status (i.e. basis) array (char[numberRows+numberColumns]),
641      use delete [] */
642  unsigned char *  statusCopy() const;
643  /// Copy in status (basis) vector
644  void copyinStatus(const unsigned char * statusArray);
645
646  /// User pointer for whatever reason
647  inline void setUserPointer (void * pointer)
648  { userPointer_=pointer;}
649  inline void * getUserPointer () const
650  { return userPointer_;}
651  /// What has changed in model (only for masochistic users)
652  inline int whatsChanged() const 
653          { return whatsChanged_;} 
654  inline void setWhatsChanged(int value)
655          { whatsChanged_ = value;} 
656  /// Number of threads (not really being used)
657  inline int numberThreads() const 
658          { return numberThreads_;} 
659  inline void setNumberThreads(int value)
660          { numberThreads_ = value;} 
661  //@}
662  /**@name Message handling */
663  //@{
664   /// Pass in Message handler (not deleted at end)
665   void passInMessageHandler(CoinMessageHandler * handler);
666  /// Pass in Message handler (not deleted at end) and return current
667  CoinMessageHandler * pushMessageHandler(CoinMessageHandler * handler,
668                                          bool & oldDefault);
669  /// back to previous message handler
670  void popMessageHandler(CoinMessageHandler * oldHandler,bool oldDefault);
671   /// Set language
672   void newLanguage(CoinMessages::Language language);
673   inline void setLanguage(CoinMessages::Language language) { newLanguage(language); }
674   /// Return handler
675   inline CoinMessageHandler * messageHandler() const       { return handler_; }
676   /// Return messages
677   inline CoinMessages messages() const                     { return messages_; }
678   /// Return pointer to messages
679   inline CoinMessages * messagesPointer()                  { return & messages_; }
680   /// Return Coin messages
681   inline CoinMessages coinMessages() const                  { return coinMessages_; }
682   /// Return pointer to Coin messages
683   inline CoinMessages * coinMessagesPointer()                  { return & coinMessages_; }
684  /** Amount of print out:
685      0 - none
686      1 - just final
687      2 - just factorizations
688      3 - as 2 plus a bit more
689      4 - verbose
690      above that 8,16,32 etc just for selective debug
691  */
692   inline void setLogLevel(int value)    { handler_->setLogLevel(value); }
693   inline int logLevel() const           { return handler_->logLevel(); }
694   /// Return true if default handler
695   inline bool defaultHandler() const
696   { return defaultHandler_;}
697   /// Pass in Event handler (cloned and deleted at end)
698   void passInEventHandler(const ClpEventHandler * eventHandler);
699   /// Event handler
700   inline ClpEventHandler * eventHandler() const
701  { return eventHandler_;}
702  /// Thread specific random number generator
703  inline CoinThreadRandom * randomNumberGenerator() 
704  { return &randomNumberGenerator_;}
705  /// Thread specific random number generator
706  inline CoinThreadRandom & mutableRandomNumberGenerator()
707  { return randomNumberGenerator_;}
708  /// Set seed for thread specific random number generator
709  inline void setRandomSeed(int value)
710  { randomNumberGenerator_.setSeed(value);}
711   /// length of names (0 means no names0
712   inline int lengthNames() const { return lengthNames_; }
713#ifndef CLP_NO_STD
714   /// length of names (0 means no names0
715   inline void setLengthNames(int value) { lengthNames_=value; }
716   /// Row names
717   inline const std::vector<std::string> * rowNames() const {
718      return &rowNames_;
719   }
720   inline const std::string& rowName(int iRow) const {
721      return rowNames_[iRow];
722   }
723   /// Return name or Rnnnnnnn
724   std::string getRowName(int iRow) const;
725   /// Column names
726   inline const std::vector<std::string> * columnNames() const {
727      return &columnNames_;
728   }
729   inline const std::string& columnName(int iColumn) const {
730      return columnNames_[iColumn];
731   }
732   /// Return name or Cnnnnnnn
733   std::string getColumnName(int iColumn) const;
734#endif
735  /// Objective methods
736  inline ClpObjective * objectiveAsObject() const
737  { return objective_;}
738  void setObjective(ClpObjective * objective);
739  inline void setObjectivePointer(ClpObjective * objective)
740  { objective_ = objective;}
741  /** Solve a problem with no elements - return status and
742      dual and primal infeasibilites */
743  int emptyProblem(int * infeasNumber=NULL, double * infeasSum=NULL,bool printMessage=true);
744 
745  //@}
746
747  /**@name Matrix times vector methods
748     They can be faster if scalar is +- 1
749     These are covers so user need not worry about scaling
750     Also for simplex I am not using basic/non-basic split */
751  //@{
752    /** Return <code>y + A * x * scalar</code> in <code>y</code>.
753        @pre <code>x</code> must be of size <code>numColumns()</code>
754        @pre <code>y</code> must be of size <code>numRows()</code> */
755   void times(double scalar,
756                       const double * x, double * y) const;
757    /** Return <code>y + x * scalar * A</code> in <code>y</code>.
758        @pre <code>x</code> must be of size <code>numRows()</code>
759        @pre <code>y</code> must be of size <code>numColumns()</code> */
760    void transposeTimes(double scalar,
761                                const double * x, double * y) const ;
762  //@}
763
764
765  //---------------------------------------------------------------------------
766  /**@name Parameter set/get methods
767
768     The set methods return true if the parameter was set to the given value,
769     false otherwise. There can be various reasons for failure: the given
770     parameter is not applicable for the solver (e.g., refactorization
771     frequency for the volume algorithm), the parameter is not yet implemented
772     for the solver or simply the value of the parameter is out of the range
773     the solver accepts. If a parameter setting call returns false check the
774     details of your solver.
775
776     The get methods return true if the given parameter is applicable for the
777     solver and is implemented. In this case the value of the parameter is
778     returned in the second argument. Otherwise they return false.
779
780     ** once it has been decided where solver sits this may be redone
781  */
782  //@{
783    /// Set an integer parameter
784    bool setIntParam(ClpIntParam key, int value) ;
785    /// Set an double parameter
786    bool setDblParam(ClpDblParam key, double value) ;
787#ifndef CLP_NO_STD
788    /// Set an string parameter
789    bool setStrParam(ClpStrParam key, const std::string & value);
790#endif
791    // Get an integer parameter
792    inline bool getIntParam(ClpIntParam key, int& value) const {
793      if (key<ClpLastIntParam) {
794        value = intParam_[key];
795        return true;
796      } else {
797        return false;
798      }
799    }
800    // Get an double parameter
801    inline bool getDblParam(ClpDblParam key, double& value) const {
802      if (key<ClpLastDblParam) {
803        value = dblParam_[key];
804        return true;
805      } else {
806        return false;
807      }
808    }
809#ifndef CLP_NO_STD
810    // Get a string parameter
811    inline bool getStrParam(ClpStrParam key, std::string& value) const {
812      if (key<ClpLastStrParam) {
813        value = strParam_[key];
814        return true;
815      } else {
816        return false;
817      }
818    }
819#endif
820    /// Create C++ lines to get to current state
821    void generateCpp( FILE * fp);
822  /** For advanced options
823      1 - Don't keep changing infeasibility weight
824      2 - Keep nonLinearCost round solves
825      4 - Force outgoing variables to exact bound (primal)
826      8 - Safe to use dense initial factorization
827      16 -Just use basic variables for operation if column generation
828      32 -Clean up with primal before strong branching
829      64 -Treat problem as feasible until last minute (i.e. minimize infeasibilities)
830      128 - Switch off all matrix sanity checks
831      256 - No row copy
832      512 - If not in values pass, solution guaranteed, skip as much as possible
833      1024 - In branch and bound
834      2048 - Don't bother to re-factorize if < 20 iterations
835      4096 - Skip some optimality checks
836      8192 - Do Primal when cleaning up primal
837      16384 - In fast dual (so we can switch off things)
838      32768 - called from Osi
839      65536 - keep arrays around as much as possible (also use maximumR/C)
840      131072 - scale factor arrays have inverse values at end
841      262144 - extra copy of scaled matrix
842      NOTE - many applications can call Clp but there may be some short cuts
843             which are taken which are not guaranteed safe from all applications.
844             Vetted applications will have a bit set and the code may test this
845             At present I expect a few such applications - if too many I will
846             have to re-think.  It is up to application owner to change the code
847             if she/he needs these short cuts.  I will not debug unless in Coin
848             repository.  See COIN_CLP_VETTED comments.
849      0x01000000 is Cbc (and in branch and bound)
850      0x02000000 is in a different branch and bound
851  */
852#define COIN_CBC_USING_CLP 0x01000000
853  inline unsigned int specialOptions() const
854  { return specialOptions_;}
855  void setSpecialOptions(unsigned int value);
856  inline bool inCbcBranchAndBound() const
857  { return (specialOptions_&COIN_CBC_USING_CLP)!=0;}
858  //@}
859
860  /**@name private or protected methods */
861  //@{
862protected:
863  /// Does most of deletion (0 = all, 1 = most)
864  void gutsOfDelete(int type);
865  /** Does most of copying
866      If trueCopy 0 then just points to arrays
867      If -1 leaves as much as possible */
868  void gutsOfCopy(const ClpModel & rhs, int trueCopy=1);
869  /// gets lower and upper bounds on rows
870  void getRowBound(int iRow, double& lower, double& upper) const;
871  /// puts in format I like - 4 array matrix - may make row copy
872  void gutsOfLoadModel ( int numberRows, int numberColumns,
873                     const double* collb, const double* colub,   
874                     const double* obj,
875                     const double* rowlb, const double* rowub,
876                      const double * rowObjective=NULL);
877  /// Does much of scaling
878  void gutsOfScaling();
879  /// Objective value - always minimize
880  inline double rawObjectiveValue() const {
881    return objectiveValue_;
882  }
883  /// If we are using maximumRows_ and Columns_
884  inline bool permanentArrays() const
885  { return (specialOptions_&65536)!=0;}
886  /// Start using maximumRows_ and Columns_
887  void startPermanentArrays();
888  /// Stop using maximumRows_ and Columns_
889  void stopPermanentArrays();
890  /// Create row names as char **
891  const char * const * rowNamesAsChar() const;
892  /// Create column names as char **
893  const char * const * columnNamesAsChar() const;
894  /// Delete char * version of names
895  void deleteNamesAsChar(const char * const * names,int number) const;
896  /// On stopped - sets secondary status
897  void onStopped();
898  //@}
899
900
901////////////////// data //////////////////
902protected:
903
904  /**@name data */
905  //@{
906  /// Direction of optimization (1 - minimize, -1 - maximize, 0 - ignore
907  double optimizationDirection_;
908  /// Array of double parameters
909  double dblParam_[ClpLastDblParam];
910  /// Objective value
911  double objectiveValue_;
912  /// Small element value
913  double smallElement_;
914  /// Scaling of objective
915  double objectiveScale_;
916  /// Scaling of rhs and bounds
917  double rhsScale_;
918  /// Number of rows
919  int numberRows_;
920  /// Number of columns
921  int numberColumns_;
922  /// Row activities
923  double * rowActivity_;
924  /// Column activities
925  double * columnActivity_;
926  /// Duals
927  double * dual_;
928  /// Reduced costs
929  double * reducedCost_;
930  /// Row lower
931  double* rowLower_;
932  /// Row upper
933  double* rowUpper_;
934  /// Objective
935  ClpObjective * objective_;
936  /// Row Objective (? sign)  - may be NULL
937  double * rowObjective_;
938  /// Column Lower
939  double * columnLower_;
940  /// Column Upper
941  double * columnUpper_;
942  /// Packed matrix
943  ClpMatrixBase * matrix_;
944  /// Row copy if wanted
945  ClpMatrixBase * rowCopy_;
946  /// Scaled packed matrix
947  ClpPackedMatrix * scaledMatrix_;
948  /// Infeasible/unbounded ray
949  double * ray_;
950  /// Row scale factors for matrix
951  double * rowScale_;
952  /// Column scale factors
953  double * columnScale_;
954  /// Scale flag, 0 none, 1 equilibrium, 2 geometric, 3, auto, 4 dynamic
955  int scalingFlag_;
956  /** Status (i.e. basis) Region.  I know that not all algorithms need a status
957      array, but it made sense for things like crossover and put
958      all permanent stuff in one place.  No assumption is made
959      about what is in status array (although it might be good to reserve
960      bottom 3 bits (i.e. 0-7 numeric) for classic status).  This
961      is number of columns + number of rows long (in that order).
962  */
963  unsigned char * status_;
964  /// Integer information
965  char * integerType_;
966  /// User pointer for whatever reason
967  void * userPointer_;
968  /// Array of integer parameters
969  int intParam_[ClpLastIntParam];
970  /// Number of iterations
971  int numberIterations_;
972  /** Solve type - 1 simplex, 2 simplex interface, 3 Interior.*/
973  int solveType_;
974  /** Whats changed since last solve.  This is a work in progress
975      It is designed so careful people can make go faster.
976      It is only used when startFinishOptions used in dual or primal.
977      Bit 1 - number of rows/columns has not changed (so work arrays valid)
978          2 - matrix has not changed
979          4 - if matrix has changed only by adding rows
980          8 - if matrix has changed only by adding columns
981         16 - row lbs not changed
982         32 - row ubs not changed
983         64 - column objective not changed
984        128 - column lbs not changed
985        256 - column ubs not changed
986        512 - basis not changed (up to user to set this to 0)
987              top bits may be used internally
988  */
989  unsigned int whatsChanged_;
990  /// Status of problem
991  int problemStatus_;
992  /// Secondary status of problem
993  int secondaryStatus_;
994  /// length of names (0 means no names)
995  int lengthNames_;
996  /// Number of threads (not very operational)
997  int numberThreads_;
998  /** For advanced options
999      See get and set for meaning
1000  */
1001  unsigned int specialOptions_;
1002  /// Message handler
1003  CoinMessageHandler * handler_;
1004  /// Flag to say if default handler (so delete)
1005  bool defaultHandler_;
1006  /// Thread specific random number generator
1007  CoinThreadRandom randomNumberGenerator_;
1008  /// Event handler
1009  ClpEventHandler * eventHandler_;
1010#ifndef CLP_NO_STD
1011  /// Row names
1012  std::vector<std::string> rowNames_;
1013  /// Column names
1014  std::vector<std::string> columnNames_;
1015#endif
1016  /// Messages
1017  CoinMessages messages_;
1018  /// Coin messages
1019  CoinMessages coinMessages_;
1020  /// Maximum number of columns in model
1021  int maximumColumns_;
1022  /// Maximum number of rows in model
1023  int maximumRows_;
1024  /// Base packed matrix
1025  CoinPackedMatrix baseMatrix_;
1026  /// Base row copy
1027  CoinPackedMatrix baseRowCopy_;
1028  /// Saved row scale factors for matrix
1029  double * savedRowScale_;
1030  /// Saved column scale factors
1031  double * savedColumnScale_;
1032#ifndef CLP_NO_STD
1033  /// Array of string parameters
1034  std::string strParam_[ClpLastStrParam];
1035#endif
1036  //@}
1037};
1038/** This is a tiny class where data can be saved round calls.
1039 */
1040class ClpDataSave {
1041
1042public:
1043  /**@name Constructors and destructor
1044   */
1045  //@{
1046    /// Default constructor
1047    ClpDataSave (  );
1048
1049    /// Copy constructor.
1050    ClpDataSave(const ClpDataSave &);
1051    /// Assignment operator. This copies the data
1052    ClpDataSave & operator=(const ClpDataSave & rhs);
1053    /// Destructor
1054    ~ClpDataSave (  );
1055
1056  //@}
1057
1058////////////////// data //////////////////
1059public:
1060
1061  /**@name data - with same names as in other classes*/
1062  //@{
1063  double dualBound_;
1064  double infeasibilityCost_;
1065  double pivotTolerance_;
1066  double acceptablePivot_;
1067  double objectiveScale_;
1068  int sparseThreshold_;
1069  int perturbation_;
1070  int forceFactorization_;
1071  int scalingFlag_;
1072  //@}
1073};
1074
1075#endif
Note: See TracBrowser for help on using the repository browser.