source: stable/1.7/Clp/src/ClpModel.hpp @ 1213

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

for Lou Hafer to update Osi stable

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.6 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
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 const double * inverseRowScale() const {return inverseRowScale_;}
522   inline const double * inverseColumnScale() const {return inverseColumnScale_;}
523   inline double * mutableRowScale() const {return rowScale_;}
524   inline double * mutableColumnScale() const {return columnScale_;}
525   inline double * mutableInverseRowScale() const {return inverseRowScale_;}
526   inline double * mutableInverseColumnScale() const {return inverseColumnScale_;}
527   void setRowScale(double * scale) ;
528   void setColumnScale(double * scale);
529  /// Scaling of objective
530  inline double objectiveScale() const 
531          { return objectiveScale_;} 
532  inline void setObjectiveScale(double value)
533          { objectiveScale_ = value;} 
534  /// Scaling of rhs and bounds
535  inline double rhsScale() const 
536          { return rhsScale_;} 
537  inline void setRhsScale(double value)
538          { rhsScale_ = value;} 
539   /// Sets or unsets scaling, 0 -off, 1 equilibrium, 2 geometric, 3 auto, 4 auto-but-as-initialSolve-in-bab
540   void scaling(int mode=1);
541  /** If we constructed a "really" scaled model then this reverses the operation.
542      Quantities may not be exactly as they were before due to rounding errors */
543  void unscale();
544   /// Gets scalingFlag
545   inline int scalingFlag() const {return scalingFlag_;}
546   /// Objective
547   inline double * objective() const           
548  {
549    if (objective_) {
550      double offset; 
551      return objective_->gradient(NULL,NULL,offset,false);
552    } else {
553      return NULL;
554    }
555  }
556   inline double * objective(const double * solution, double & offset,bool refresh=true) const           
557  {
558    offset=0.0;
559    if (objective_) {
560      return objective_->gradient(NULL,solution,offset,refresh);
561    } else {
562      return NULL;
563    }
564  }
565   inline const double * getObjCoefficients() const 
566  { 
567    if (objective_) {
568      double offset; 
569      return objective_->gradient(NULL,NULL,offset,false);
570    } else {
571      return NULL;
572    }
573  }
574   /// Row Objective
575   inline double * rowObjective() const         { return rowObjective_; }
576   inline const double * getRowObjCoefficients() const {
577      return rowObjective_;
578   }
579   /// Column Lower
580   inline double * columnLower() const          { return columnLower_; }
581   inline const double * getColLower() const    { return columnLower_; }
582   /// Column Upper
583   inline double * columnUpper() const          { return columnUpper_; }
584   inline const double * getColUpper() const    { return columnUpper_; }
585   /// Matrix (if not ClpPackedmatrix be careful about memory leak
586   inline CoinPackedMatrix * matrix() const {
587     if ( matrix_ == NULL ) return NULL;
588     else return matrix_->getPackedMatrix();
589   }
590   /// Number of elements in matrix
591   inline int getNumElements() const 
592     { return matrix_->getNumElements();}
593   /** Small element value - elements less than this set to zero,
594      default is 1.0e-20 */
595   inline double getSmallElementValue() const
596  { return smallElement_;}
597  inline void setSmallElementValue(double value)
598  { smallElement_=value;} 
599   /// Row Matrix
600   inline ClpMatrixBase * rowCopy() const       { return rowCopy_; }
601   /// Clp Matrix
602   inline ClpMatrixBase * clpMatrix() const     { return matrix_; }
603   /// Scaled ClpPackedMatrix
604   inline ClpPackedMatrix * clpScaledMatrix() const     { return scaledMatrix_; }
605   /// Sets pointer to scaled ClpPackedMatrix
606   inline void setClpScaledMatrix(ClpPackedMatrix * scaledMatrix)
607  { delete scaledMatrix_; scaledMatrix_=scaledMatrix; }
608  /** Replace Clp Matrix (current is not deleted unless told to
609      and new is used)
610      So up to user to delete current.  This was used where
611      matrices were being rotated. ClpModel takes ownership.
612  */
613   void replaceMatrix(ClpMatrixBase * matrix,bool deleteCurrent=false);
614  /** Replace Clp Matrix (current is not deleted unless told to
615      and new is used) So up to user to delete current.  This was used where
616      matrices were being rotated.  This version changes CoinPackedMatrix
617      to ClpPackedMatrix.  ClpModel takes ownership.
618  */
619   inline void replaceMatrix(CoinPackedMatrix * matrix,
620                             bool deleteCurrent=false)
621  { replaceMatrix(new ClpPackedMatrix(matrix),deleteCurrent);}
622   /// Objective value
623   inline double objectiveValue() const {
624      return objectiveValue_*optimizationDirection_ - dblParam_[ClpObjOffset];
625   }
626  inline void setObjectiveValue(double value) {
627    objectiveValue_ = (value+ dblParam_[ClpObjOffset])/optimizationDirection_;
628   }
629   inline double getObjValue() const {
630      return objectiveValue_*optimizationDirection_ - dblParam_[ClpObjOffset];
631   }
632   /// Integer information
633   inline char * integerInformation() const     { return integerType_; }
634   /** Infeasibility/unbounded ray (NULL returned if none/wrong)
635       Up to user to use delete [] on these arrays.  */
636   double * infeasibilityRay() const;
637   double * unboundedRay() const;
638  /// See if status (i.e. basis) array exists (partly for OsiClp)
639  inline bool statusExists() const
640  { return (status_!=NULL);}
641  /// Return address of status (i.e. basis) array (char[numberRows+numberColumns])
642  inline unsigned char *  statusArray() const
643  { return status_;}
644  /** Return copy of status (i.e. basis) array (char[numberRows+numberColumns]),
645      use delete [] */
646  unsigned char *  statusCopy() const;
647  /// Copy in status (basis) vector
648  void copyinStatus(const unsigned char * statusArray);
649
650  /// User pointer for whatever reason
651  inline void setUserPointer (void * pointer)
652  { userPointer_=pointer;}
653  inline void * getUserPointer () const
654  { return userPointer_;}
655  /// What has changed in model (only for masochistic users)
656  inline int whatsChanged() const 
657          { return whatsChanged_;} 
658  inline void setWhatsChanged(int value)
659          { whatsChanged_ = value;} 
660  /// Number of threads (not really being used)
661  inline int numberThreads() const 
662          { return numberThreads_;} 
663  inline void setNumberThreads(int value)
664          { numberThreads_ = value;} 
665  //@}
666  /**@name Message handling */
667  //@{
668   /// Pass in Message handler (not deleted at end)
669   void passInMessageHandler(CoinMessageHandler * handler);
670  /// Pass in Message handler (not deleted at end) and return current
671  CoinMessageHandler * pushMessageHandler(CoinMessageHandler * handler,
672                                          bool & oldDefault);
673  /// back to previous message handler
674  void popMessageHandler(CoinMessageHandler * oldHandler,bool oldDefault);
675   /// Set language
676   void newLanguage(CoinMessages::Language language);
677   inline void setLanguage(CoinMessages::Language language) { newLanguage(language); }
678   /// Return handler
679   inline CoinMessageHandler * messageHandler() const       { return handler_; }
680   /// Return messages
681   inline CoinMessages messages() const                     { return messages_; }
682   /// Return pointer to messages
683   inline CoinMessages * messagesPointer()                  { return & messages_; }
684   /// Return Coin messages
685   inline CoinMessages coinMessages() const                  { return coinMessages_; }
686   /// Return pointer to Coin messages
687   inline CoinMessages * coinMessagesPointer()                  { return & coinMessages_; }
688  /** Amount of print out:
689      0 - none
690      1 - just final
691      2 - just factorizations
692      3 - as 2 plus a bit more
693      4 - verbose
694      above that 8,16,32 etc just for selective debug
695  */
696   inline void setLogLevel(int value)    { handler_->setLogLevel(value); }
697   inline int logLevel() const           { return handler_->logLevel(); }
698   /// Return true if default handler
699   inline bool defaultHandler() const
700   { return defaultHandler_;}
701   /// Pass in Event handler (cloned and deleted at end)
702   void passInEventHandler(const ClpEventHandler * eventHandler);
703   /// Event handler
704   inline ClpEventHandler * eventHandler() const
705  { return eventHandler_;}
706  /// Thread specific random number generator
707  inline CoinThreadRandom * randomNumberGenerator() 
708  { return &randomNumberGenerator_;}
709  /// Thread specific random number generator
710  inline CoinThreadRandom & mutableRandomNumberGenerator()
711  { return randomNumberGenerator_;}
712  /// Set seed for thread specific random number generator
713  inline void setRandomSeed(int value)
714  { randomNumberGenerator_.setSeed(value);}
715   /// length of names (0 means no names0
716   inline int lengthNames() const { return lengthNames_; }
717#ifndef CLP_NO_STD
718   /// length of names (0 means no names0
719   inline void setLengthNames(int value) { lengthNames_=value; }
720   /// Row names
721   inline const std::vector<std::string> * rowNames() const {
722      return &rowNames_;
723   }
724   inline const std::string& rowName(int iRow) const {
725      return rowNames_[iRow];
726   }
727   /// Return name or Rnnnnnnn
728   std::string getRowName(int iRow) const;
729   /// Column names
730   inline const std::vector<std::string> * columnNames() const {
731      return &columnNames_;
732   }
733   inline const std::string& columnName(int iColumn) const {
734      return columnNames_[iColumn];
735   }
736   /// Return name or Cnnnnnnn
737   std::string getColumnName(int iColumn) const;
738#endif
739  /// Objective methods
740  inline ClpObjective * objectiveAsObject() const
741  { return objective_;}
742  void setObjective(ClpObjective * objective);
743  inline void setObjectivePointer(ClpObjective * objective)
744  { objective_ = objective;}
745  /** Solve a problem with no elements - return status and
746      dual and primal infeasibilites */
747  int emptyProblem(int * infeasNumber=NULL, double * infeasSum=NULL,bool printMessage=true);
748 
749  //@}
750
751  /**@name Matrix times vector methods
752     They can be faster if scalar is +- 1
753     These are covers so user need not worry about scaling
754     Also for simplex I am not using basic/non-basic split */
755  //@{
756    /** Return <code>y + A * x * scalar</code> in <code>y</code>.
757        @pre <code>x</code> must be of size <code>numColumns()</code>
758        @pre <code>y</code> must be of size <code>numRows()</code> */
759   void times(double scalar,
760                       const double * x, double * y) const;
761    /** Return <code>y + x * scalar * A</code> in <code>y</code>.
762        @pre <code>x</code> must be of size <code>numRows()</code>
763        @pre <code>y</code> must be of size <code>numColumns()</code> */
764    void transposeTimes(double scalar,
765                                const double * x, double * y) const ;
766  //@}
767
768
769  //---------------------------------------------------------------------------
770  /**@name Parameter set/get methods
771
772     The set methods return true if the parameter was set to the given value,
773     false otherwise. There can be various reasons for failure: the given
774     parameter is not applicable for the solver (e.g., refactorization
775     frequency for the volume algorithm), the parameter is not yet implemented
776     for the solver or simply the value of the parameter is out of the range
777     the solver accepts. If a parameter setting call returns false check the
778     details of your solver.
779
780     The get methods return true if the given parameter is applicable for the
781     solver and is implemented. In this case the value of the parameter is
782     returned in the second argument. Otherwise they return false.
783
784     ** once it has been decided where solver sits this may be redone
785  */
786  //@{
787    /// Set an integer parameter
788    bool setIntParam(ClpIntParam key, int value) ;
789    /// Set an double parameter
790    bool setDblParam(ClpDblParam key, double value) ;
791#ifndef CLP_NO_STD
792    /// Set an string parameter
793    bool setStrParam(ClpStrParam key, const std::string & value);
794#endif
795    // Get an integer parameter
796    inline bool getIntParam(ClpIntParam key, int& value) const {
797      if (key<ClpLastIntParam) {
798        value = intParam_[key];
799        return true;
800      } else {
801        return false;
802      }
803    }
804    // Get an double parameter
805    inline bool getDblParam(ClpDblParam key, double& value) const {
806      if (key<ClpLastDblParam) {
807        value = dblParam_[key];
808        return true;
809      } else {
810        return false;
811      }
812    }
813#ifndef CLP_NO_STD
814    // Get a string parameter
815    inline bool getStrParam(ClpStrParam key, std::string& value) const {
816      if (key<ClpLastStrParam) {
817        value = strParam_[key];
818        return true;
819      } else {
820        return false;
821      }
822    }
823#endif
824    /// Create C++ lines to get to current state
825    void generateCpp( FILE * fp);
826  /** For advanced options
827      1 - Don't keep changing infeasibility weight
828      2 - Keep nonLinearCost round solves
829      4 - Force outgoing variables to exact bound (primal)
830      8 - Safe to use dense initial factorization
831      16 -Just use basic variables for operation if column generation
832      32 -Clean up with primal before strong branching
833      64 -Treat problem as feasible until last minute (i.e. minimize infeasibilities)
834      128 - Switch off all matrix sanity checks
835      256 - No row copy
836      512 - If not in values pass, solution guaranteed, skip as much as possible
837      1024 - In branch and bound
838      2048 - Don't bother to re-factorize if < 20 iterations
839      4096 - Skip some optimality checks
840      8192 - Do Primal when cleaning up primal
841      16384 - In fast dual (so we can switch off things)
842      32768 - called from Osi
843      65536 - keep arrays around as much as possible (also use maximumR/C)
844      131072 - scale factor arrays have inverse values at end
845      262144 - extra copy of scaled matrix
846      524288 - Clp fast dual
847      NOTE - many applications can call Clp but there may be some short cuts
848             which are taken which are not guaranteed safe from all applications.
849             Vetted applications will have a bit set and the code may test this
850             At present I expect a few such applications - if too many I will
851             have to re-think.  It is up to application owner to change the code
852             if she/he needs these short cuts.  I will not debug unless in Coin
853             repository.  See COIN_CLP_VETTED comments.
854      0x01000000 is Cbc (and in branch and bound)
855      0x02000000 is in a different branch and bound
856  */
857#define COIN_CBC_USING_CLP 0x01000000
858  inline unsigned int specialOptions() const
859  { return specialOptions_;}
860  void setSpecialOptions(unsigned int value);
861  inline bool inCbcBranchAndBound() const
862  { return (specialOptions_&COIN_CBC_USING_CLP)!=0;}
863  //@}
864
865  /**@name private or protected methods */
866  //@{
867protected:
868  /// Does most of deletion (0 = all, 1 = most)
869  void gutsOfDelete(int type);
870  /** Does most of copying
871      If trueCopy 0 then just points to arrays
872      If -1 leaves as much as possible */
873  void gutsOfCopy(const ClpModel & rhs, int trueCopy=1);
874  /// gets lower and upper bounds on rows
875  void getRowBound(int iRow, double& lower, double& upper) const;
876  /// puts in format I like - 4 array matrix - may make row copy
877  void gutsOfLoadModel ( int numberRows, int numberColumns,
878                     const double* collb, const double* colub,   
879                     const double* obj,
880                     const double* rowlb, const double* rowub,
881                      const double * rowObjective=NULL);
882  /// Does much of scaling
883  void gutsOfScaling();
884  /// Objective value - always minimize
885  inline double rawObjectiveValue() const {
886    return objectiveValue_;
887  }
888  /// If we are using maximumRows_ and Columns_
889  inline bool permanentArrays() const
890  { return (specialOptions_&65536)!=0;}
891  /// Start using maximumRows_ and Columns_
892  void startPermanentArrays();
893  /// Stop using maximumRows_ and Columns_
894  void stopPermanentArrays();
895  /// Create row names as char **
896  const char * const * rowNamesAsChar() const;
897  /// Create column names as char **
898  const char * const * columnNamesAsChar() const;
899  /// Delete char * version of names
900  void deleteNamesAsChar(const char * const * names,int number) const;
901  /// On stopped - sets secondary status
902  void onStopped();
903  //@}
904
905
906////////////////// data //////////////////
907protected:
908
909  /**@name data */
910  //@{
911  /// Direction of optimization (1 - minimize, -1 - maximize, 0 - ignore
912  double optimizationDirection_;
913  /// Array of double parameters
914  double dblParam_[ClpLastDblParam];
915  /// Objective value
916  double objectiveValue_;
917  /// Small element value
918  double smallElement_;
919  /// Scaling of objective
920  double objectiveScale_;
921  /// Scaling of rhs and bounds
922  double rhsScale_;
923  /// Number of rows
924  int numberRows_;
925  /// Number of columns
926  int numberColumns_;
927  /// Row activities
928  double * rowActivity_;
929  /// Column activities
930  double * columnActivity_;
931  /// Duals
932  double * dual_;
933  /// Reduced costs
934  double * reducedCost_;
935  /// Row lower
936  double* rowLower_;
937  /// Row upper
938  double* rowUpper_;
939  /// Objective
940  ClpObjective * objective_;
941  /// Row Objective (? sign)  - may be NULL
942  double * rowObjective_;
943  /// Column Lower
944  double * columnLower_;
945  /// Column Upper
946  double * columnUpper_;
947  /// Packed matrix
948  ClpMatrixBase * matrix_;
949  /// Row copy if wanted
950  ClpMatrixBase * rowCopy_;
951  /// Scaled packed matrix
952  ClpPackedMatrix * scaledMatrix_;
953  /// Infeasible/unbounded ray
954  double * ray_;
955  /// Row scale factors for matrix
956  double * rowScale_;
957  /// Column scale factors
958  double * columnScale_;
959  /// Inverse row scale factors for matrix (end of rowScale_)
960  double * inverseRowScale_;
961  /// Inverse column scale factors for matrix (end of columnScale_)
962  double * inverseColumnScale_;
963  /// Scale flag, 0 none, 1 equilibrium, 2 geometric, 3, auto, 4 dynamic
964  int scalingFlag_;
965  /** Status (i.e. basis) Region.  I know that not all algorithms need a status
966      array, but it made sense for things like crossover and put
967      all permanent stuff in one place.  No assumption is made
968      about what is in status array (although it might be good to reserve
969      bottom 3 bits (i.e. 0-7 numeric) for classic status).  This
970      is number of columns + number of rows long (in that order).
971  */
972  unsigned char * status_;
973  /// Integer information
974  char * integerType_;
975  /// User pointer for whatever reason
976  void * userPointer_;
977  /// Array of integer parameters
978  int intParam_[ClpLastIntParam];
979  /// Number of iterations
980  int numberIterations_;
981  /** Solve type - 1 simplex, 2 simplex interface, 3 Interior.*/
982  int solveType_;
983  /** Whats changed since last solve.  This is a work in progress
984      It is designed so careful people can make go faster.
985      It is only used when startFinishOptions used in dual or primal.
986      Bit 1 - number of rows/columns has not changed (so work arrays valid)
987          2 - matrix has not changed
988          4 - if matrix has changed only by adding rows
989          8 - if matrix has changed only by adding columns
990         16 - row lbs not changed
991         32 - row ubs not changed
992         64 - column objective not changed
993        128 - column lbs not changed
994        256 - column ubs not changed
995        512 - basis not changed (up to user to set this to 0)
996              top bits may be used internally
997  */
998  unsigned int whatsChanged_;
999  /// Status of problem
1000  int problemStatus_;
1001  /// Secondary status of problem
1002  int secondaryStatus_;
1003  /// length of names (0 means no names)
1004  int lengthNames_;
1005  /// Number of threads (not very operational)
1006  int numberThreads_;
1007  /** For advanced options
1008      See get and set for meaning
1009  */
1010  unsigned int specialOptions_;
1011  /// Message handler
1012  CoinMessageHandler * handler_;
1013  /// Flag to say if default handler (so delete)
1014  bool defaultHandler_;
1015  /// Thread specific random number generator
1016  CoinThreadRandom randomNumberGenerator_;
1017  /// Event handler
1018  ClpEventHandler * eventHandler_;
1019#ifndef CLP_NO_STD
1020  /// Row names
1021  std::vector<std::string> rowNames_;
1022  /// Column names
1023  std::vector<std::string> columnNames_;
1024#endif
1025  /// Messages
1026  CoinMessages messages_;
1027  /// Coin messages
1028  CoinMessages coinMessages_;
1029  /// Maximum number of columns in model
1030  int maximumColumns_;
1031  /// Maximum number of rows in model
1032  int maximumRows_;
1033  /// Maximum number of columns (internal arrays) in model
1034  int maximumInternalColumns_;
1035  /// Maximum number of rows (internal arrays) in model
1036  int maximumInternalRows_;
1037  /// Base packed matrix
1038  CoinPackedMatrix baseMatrix_;
1039  /// Base row copy
1040  CoinPackedMatrix baseRowCopy_;
1041  /// Saved row scale factors for matrix
1042  double * savedRowScale_;
1043  /// Saved column scale factors
1044  double * savedColumnScale_;
1045#ifndef CLP_NO_STD
1046  /// Array of string parameters
1047  std::string strParam_[ClpLastStrParam];
1048#endif
1049  //@}
1050};
1051/** This is a tiny class where data can be saved round calls.
1052 */
1053class ClpDataSave {
1054
1055public:
1056  /**@name Constructors and destructor
1057   */
1058  //@{
1059    /// Default constructor
1060    ClpDataSave (  );
1061
1062    /// Copy constructor.
1063    ClpDataSave(const ClpDataSave &);
1064    /// Assignment operator. This copies the data
1065    ClpDataSave & operator=(const ClpDataSave & rhs);
1066    /// Destructor
1067    ~ClpDataSave (  );
1068
1069  //@}
1070
1071////////////////// data //////////////////
1072public:
1073
1074  /**@name data - with same names as in other classes*/
1075  //@{
1076  double dualBound_;
1077  double infeasibilityCost_;
1078  double pivotTolerance_;
1079  double acceptablePivot_;
1080  double objectiveScale_;
1081  int sparseThreshold_;
1082  int perturbation_;
1083  int forceFactorization_;
1084  int scalingFlag_;
1085  unsigned int specialOptions_;
1086  //@}
1087};
1088
1089#endif
Note: See TracBrowser for help on using the repository browser.