source: trunk/CbcHeuristicFPump.cpp @ 181

Last change on this file since 181 was 181, checked in by forrest, 16 years ago

prettier messages

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 10.9 KB
Line 
1// Copyright (C) 2004, International Business Machines
2// Corporation and others.  All Rights Reserved.
3#if defined(_MSC_VER)
4// Turn off compiler warning about long names
5#  pragma warning(disable:4786)
6#endif
7#include <cassert>
8#include <cmath>
9#include <cfloat>
10
11#include "OsiSolverInterface.hpp"
12#include "CbcModel.hpp"
13#include "CbcMessage.hpp"
14#include "CbcHeuristicFPump.hpp"
15#include "CbcBranchActual.hpp"
16#include "CoinHelperFunctions.hpp"
17#include "CoinTime.hpp"
18
19
20// Default Constructor
21CbcHeuristicFPump::CbcHeuristicFPump() 
22  :CbcHeuristic(),
23   startTime_(0.0),
24   maximumTime_(0.0),
25   maximumPasses_(100),
26   downValue_(0.5),
27   roundExpensive_(false)
28{
29  setWhen(1);
30}
31
32// Constructor from model
33CbcHeuristicFPump::CbcHeuristicFPump(CbcModel & model,
34                                     double downValue,bool roundExpensive)
35  :CbcHeuristic(model),
36   startTime_(0.0),
37   maximumTime_(0.0),
38   maximumPasses_(100),
39   downValue_(downValue),
40   roundExpensive_(roundExpensive)
41{
42  setWhen(1);
43}
44
45// Destructor
46CbcHeuristicFPump::~CbcHeuristicFPump ()
47{
48}
49
50// Clone
51CbcHeuristic *
52CbcHeuristicFPump::clone() const
53{
54  return new CbcHeuristicFPump(*this);
55}
56
57// Copy constructor
58CbcHeuristicFPump::CbcHeuristicFPump(const CbcHeuristicFPump & rhs)
59:
60  CbcHeuristic(rhs),
61  startTime_(rhs.startTime_),
62  maximumTime_(rhs.maximumTime_),
63  maximumPasses_(rhs.maximumPasses_),
64  downValue_(rhs.downValue_),
65  roundExpensive_(rhs.roundExpensive_)
66{
67  setWhen(rhs.when());
68}
69// Resets stuff if model changes
70void 
71CbcHeuristicFPump::resetModel(CbcModel * model)
72{
73}
74
75/**************************BEGIN MAIN PROCEDURE ***********************************/
76
77// See if feasibility pump will give better solution
78// Sets value of solution
79// Returns 1 if solution, 0 if not
80int
81CbcHeuristicFPump::solution(double & solutionValue,
82                         double * betterSolution)
83{
84  if (!when()||(when()==1&&model_->phase()!=1))
85    return 0; // switched off
86  // See if at root node
87  bool atRoot = model_->getNodeCount()==0;
88  int passNumber = model_->getCurrentPassNumber();
89  // just do once
90  if (!atRoot||passNumber!=1)
91    return 0;
92  // probably a good idea
93  if (model_->getSolutionCount()) return 0;
94  // Clone solver - otherwise annoys root node computations
95  OsiSolverInterface * solver = model_->solver()->clone();
96 
97  solver->resolve();
98  const double * lower = solver->getColLower();
99  const double * upper = solver->getColUpper();
100  const double * solution = solver->getColSolution();
101  double primalTolerance;
102  solver->getDblParam(OsiPrimalTolerance,primalTolerance);
103 
104  int numberColumns = model_->getNumCols();
105  int numberIntegers = model_->numberIntegers();
106  const int * integerVariable = model_->integerVariable();
107
108// 1. initially check 0-1
109  int i,j;
110  bool zeroOne=true;
111  for (i=0;i<numberIntegers;i++) {
112    int iColumn = integerVariable[i];
113    const CbcObject * object = model_->object(i);
114    const CbcSimpleInteger * integerObject = 
115      dynamic_cast<const  CbcSimpleInteger *> (object);
116    assert(integerObject);
117    if (upper[iColumn]-lower[iColumn]>1.000001) {
118      zeroOne=false;
119      break;
120    }
121  }
122  if (!zeroOne) {
123    delete solver;
124    return 0;
125  }
126
127// 2. space for rounded solution
128  double * newSolution = new double [numberColumns];
129  // space for last rounded solutions
130#define NUMBER_OLD 4
131  double ** oldSolution = new double * [NUMBER_OLD];
132  for (j=0;j<NUMBER_OLD;j++) {
133    oldSolution[j]= new double[numberColumns];
134    for (i=0;i<numberColumns;i++) oldSolution[j][i]=-COIN_DBL_MAX;
135  }
136
137// 3. Replace objective with an initial 0-valued objective
138  double * saveObjective = new double [numberColumns];
139  memcpy(saveObjective,solver->getObjCoefficients(),numberColumns*sizeof(double));
140  for (i=0;i<numberColumns;i++) {
141    solver->setObjCoeff(i,0.0);
142  }
143  bool finished=false;
144  double direction = solver->getObjSense();
145  int returnCode=0;
146  bool takeHint;
147  OsiHintStrength strength;
148  solver->getHintParam(OsiDoDualInResolve,takeHint,strength);
149  solver->setHintParam(OsiDoDualInResolve,false);
150  solver->messageHandler()->setLogLevel(0);
151
152// 4. Save objective offset so we can see progress
153  double saveOffset;
154  solver->getDblParam(OsiObjOffset,saveOffset);
155
156// 5. MAIN WHILE LOOP
157  int numberPasses=0;
158  bool newLineNeeded=false;
159  while (!finished) {
160    returnCode=0;
161    if (numberPasses>=maximumPasses_) {
162      break;
163    }
164    if (maximumTime_>0.0&&CoinCpuTime()>=startTime_+maximumTime_) break;
165    numberPasses++;
166    memcpy(newSolution,solution,numberColumns*sizeof(double));
167    int flip;
168    returnCode = rounds(newSolution,saveObjective,roundExpensive_,downValue_,&flip);
169    if (returnCode) {
170      // SOLUTION IS INTEGER
171      // Put back correct objective
172      printf("\n");
173      newLineNeeded=false;
174      for (i=0;i<numberColumns;i++)
175        solver->setObjCoeff(i,saveObjective[i]);
176      // solution - but may not be better
177      // Compute using dot product
178      double newSolutionValue = direction*solver->OsiSolverInterface::getObjValue();
179      if (newSolutionValue<solutionValue) {
180        memcpy(betterSolution,newSolution,numberColumns*sizeof(double));
181      } else {
182        returnCode=0;
183      }     
184      break;
185    } else {
186      // SOLUTION IS not INTEGER
187      // 1. check for loop
188      bool matched;
189      for (int k = NUMBER_OLD-1; k > 0; k--) {
190          double * b = oldSolution[k];
191          matched = true;
192          for (i = 0; i <numberIntegers; i++) {
193              int iColumn = integerVariable[i];
194              if (newSolution[iColumn]!=b[iColumn]) {
195                matched=false;
196                break;
197              }
198          }
199          if (matched) break;
200      }
201      if (matched || numberPasses%100 == 0) {
202         // perturbation
203         printf("Perturbation applied");
204         newLineNeeded=true;
205         for (i=0;i<numberIntegers;i++) {
206             int iColumn = integerVariable[i];
207             double value = max(0.0,CoinDrand48()-0.3);
208             double difference = fabs(solution[iColumn]-newSolution[iColumn]);
209             if (difference+value>0.5) {
210                if (newSolution[iColumn]<lower[iColumn]+primalTolerance) newSolution[iColumn] += 1.0;
211             else if (newSolution[iColumn]>upper[iColumn]-primalTolerance) newSolution[iColumn] -= 1.0;
212                  else abort();
213             }
214         }
215      } else {
216         for (j=NUMBER_OLD-1;j>0;j--) {
217             for (i = 0; i < numberColumns; i++) oldSolution[j][i]=oldSolution[j-1][i];
218         }
219         for (j = 0; j < numberColumns; j++) oldSolution[0][j] = newSolution[j];
220      }
221
222      // 2. update the objective function based on the new rounded solution
223      double offset=0.0;
224      for (i=0;i<numberIntegers;i++) {
225        int iColumn = integerVariable[i];
226        double costValue = 1.0;
227        // deal with fixed variables (i.e., upper=lower)
228        if (fabs(lower[iColumn]-upper[iColumn]) < primalTolerance) {
229           if (lower[iColumn] > 1. - primalTolerance) solver->setObjCoeff(iColumn,-costValue);
230           else                                       solver->setObjCoeff(iColumn,costValue);
231           continue;
232        }
233        if (newSolution[iColumn]<lower[iColumn]+primalTolerance) {
234          solver->setObjCoeff(iColumn,costValue);
235        } else {
236          if (newSolution[iColumn]>upper[iColumn]-primalTolerance) {
237            solver->setObjCoeff(iColumn,-costValue);
238          } else {
239            abort();
240          }
241        }
242        offset += costValue*newSolution[iColumn];
243      }
244      solver->setDblParam(OsiObjOffset,-offset);
245      solver->resolve();
246      printf("\npass %3d: obj. %10.5lf --> ", numberPasses,solver->getObjValue());
247      newLineNeeded=true;
248
249    }
250  } // END WHILE
251  if (newLineNeeded)
252    printf(" - no solution found\n");
253  delete solver;
254  delete [] newSolution;
255  for ( j=0;j<NUMBER_OLD;j++) 
256    delete [] oldSolution[j];
257  delete [] oldSolution;
258  delete [] saveObjective;
259  return returnCode;
260}
261
262/**************************END MAIN PROCEDURE ***********************************/
263
264// update model
265void CbcHeuristicFPump::setModel(CbcModel * model)
266{
267  model_ = model;
268}
269
270/* Rounds solution - down if < downValue
271   returns 1 if current is a feasible solution
272*/
273int 
274CbcHeuristicFPump::rounds(double * solution,
275                          const double * objective,
276                          bool roundExpensive, double downValue, int *flip)
277{
278  OsiSolverInterface * solver = model_->solver();
279  double integerTolerance = model_->getDblParam(CbcModel::CbcIntegerTolerance);
280  double primalTolerance ;
281  solver->getDblParam(OsiPrimalTolerance,primalTolerance) ;
282  int numberIntegers = model_->numberIntegers();
283  const int * integerVariable = model_->integerVariable();
284
285  int i;
286
287  static int iter = 0;
288  int numberColumns = model_->getNumCols();
289  // tmp contains the current obj coefficients
290  double * tmp = new double [numberColumns];
291  memcpy(tmp,solver->getObjCoefficients(),numberColumns*sizeof(double));
292  int flip_up = 0;
293  int flip_down  = 0;
294  double  v = CoinDrand48() * 20;
295  int nn = 10 + (int) v;
296  int nnv = 0;
297  int * list = new int [nn];
298  double * val = new double [nn];
299  for (i = 0; i < nn; i++) val[i] = .001;
300
301  // return rounded solution
302  for (i=0;i<numberIntegers;i++) {
303    int iColumn = integerVariable[i];
304    const CbcObject * object = model_->object(i);
305    const CbcSimpleInteger * integerObject = 
306      dynamic_cast<const  CbcSimpleInteger *> (object);
307    assert(integerObject);
308    double value=solution[iColumn];
309    double round = floor(value+primalTolerance);
310    if (value-round > .5) round += 1.;
311    if (round < integerTolerance && tmp[iColumn] < -1. + integerTolerance) flip_down++;
312    if (round > 1. - integerTolerance && tmp[iColumn] > 1. - integerTolerance) flip_up++;
313    if (flip_up + flip_down == 0) { 
314       for (int k = 0; k < nn; k++) {
315           if (fabs(value-round) > val[k]) {
316              nnv++;
317              for (int j = nn-2; j >= k; j--) {
318                  val[j+1] = val[j];
319                  list[j+1] = list[j];
320              } 
321              val[k] = fabs(value-round);
322              list[k] = iColumn;
323              break;
324           }
325       }
326    }
327    solution[iColumn] = round;
328  }
329
330  if (nnv > nn) nnv = nn;
331  if (iter != 0) printf("up = %5d , down = %5d", flip_up, flip_down); fflush(stdout);
332  *flip = flip_up + flip_down;
333  delete [] tmp;
334
335  if (*flip == 0 && iter != 0) {
336     printf(" -- rand = %4d (%4d) ", nnv, nn);
337     for (i = 0; i < nnv; i++) solution[list[i]] = 1. - solution[list[i]];
338     *flip = nnv;
339  } else printf(" ");
340  delete [] list; delete [] val;
341  iter++;
342   
343  const double * rowLower = solver->getRowLower();
344  const double * rowUpper = solver->getRowUpper();
345
346  int numberRows = solver->getNumRows();
347  // get row activities
348  double * rowActivity = new double[numberRows];
349  memset(rowActivity,0,numberRows*sizeof(double));
350  solver->getMatrixByCol()->times(solution,rowActivity) ;
351  double largestInfeasibility =0.0;
352  for (i=0 ; i < numberRows ; i++) {
353    largestInfeasibility = max(largestInfeasibility,
354                               rowLower[i]-rowActivity[i]);
355    largestInfeasibility = max(largestInfeasibility,
356                               rowActivity[i]-rowUpper[i]);
357  }
358  delete [] rowActivity;
359  return (largestInfeasibility>primalTolerance) ? 0 : 1;
360}
361// Set maximum Time (default off) - also sets starttime to current
362void 
363CbcHeuristicFPump::setMaximumTime(double value)
364{
365  startTime_=CoinCpuTime();
366  maximumTime_=value;
367}
368
369 
Note: See TracBrowser for help on using the repository browser.