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

Last change on this file since 1304 was 1267, checked in by forrest, 12 years ago

changes for mahdi's heuristics

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