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

Last change on this file since 1376 was 1376, checked in by forrest, 10 years ago

chnages for speed and alternate factorization

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