Scippy

SCIP

Solving Constraint Integer Programs

heur_twoopt.c
Go to the documentation of this file.
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2 /* */
3 /* This file is part of the program and library */
4 /* SCIP --- Solving Constraint Integer Programs */
5 /* */
6 /* Copyright (C) 2002-2014 Konrad-Zuse-Zentrum */
7 /* fuer Informationstechnik Berlin */
8 /* */
9 /* SCIP is distributed under the terms of the ZIB Academic License. */
10 /* */
11 /* You should have received a copy of the ZIB Academic License */
12 /* along with SCIP; see the file COPYING. If not email to scip@zib.de. */
13 /* */
14 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
15 
16 /**@file heur_twoopt.c
17  * @brief primal heuristic to improve incumbent solution by flipping pairs of variables
18  * @author Timo Berthold
19  * @author Gregor Hendel
20  */
21 
22 /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
23 
24 #include <assert.h>
25 #include <string.h>
26 #include "scip/heur_twoopt.h"
27 
28 #define HEUR_NAME "twoopt"
29 #define HEUR_DESC "primal heuristic to improve incumbent solution by flipping pairs of variables"
30 #define HEUR_DISPCHAR 'B'
31 #define HEUR_PRIORITY -20100
32 #define HEUR_FREQ -1
33 #define HEUR_FREQOFS 0
34 #define HEUR_MAXDEPTH -1
35 
36 #define HEUR_TIMING SCIP_HEURTIMING_AFTERNODE
37 #define HEUR_USESSUBSCIP FALSE /**< does the heuristic use a secondary SCIP instance? */
38 
39 /* default parameter values */
40 #define DEFAULT_INTOPT FALSE /**< optional integer optimization is applied by default */
41 #define DEFAULT_WAITINGNODES 0 /**< default number of nodes to wait after current best solution before calling heuristic */
42 #define DEFAULT_MATCHINGRATE 0.5 /**< default percentage by which two variables have to match in their LP-row set to be
43  * associated as pair by heuristic */
44 #define DEFAULT_MAXNSLAVES 199 /**< default number of slave candidates for a master variable */
45 #define DEFAULT_ARRAYSIZE 10 /**< the default array size for temporary arrays */
46 
47 
48 /*
49  * Data structures
50  */
51 
52 /** primal heuristic data */
53 struct SCIP_HeurData
54 {
55  int lastsolindex; /**< index of last solution for which heuristic was performed */
56  SCIP_Real matchingrate; /**< percentage by which two variables have have to match in their LP-row
57  * set to be associated as pair by heuristic */
58  SCIP_VAR** binvars; /**< Array of binary variables which are sorted with respect to their occurrence
59  * in the LP-rows */
60  int nbinvars; /**< number of binary variables stored in heuristic array */
61  int waitingnodes; /**< user parameter to determine number of nodes to wait after last best solution
62  * before calling heuristic */
63  SCIP_Bool presolved; /**< flag to indicate whether presolving has already been executed */
64  int* binblockstart; /**< array to store the start indices of each binary block */
65  int* binblockend; /**< array to store the end indices of each binary block */
66  int nbinblocks; /**< number of blocks */
67 
68  /* integer variable twoopt data */
69  SCIP_Bool intopt; /**< parameter to determine if integer 2-opt should be applied */
70  SCIP_VAR** intvars; /**< array to store the integer variables in non-decreasing order
71  * with respect to their objective coefficient */
72  int nintvars; /**< the number of integer variables stored in array intvars */
73  int* intblockstart; /**< array to store the start indices of each binary block */
74  int* intblockend; /**< array to store the end indices of each binary block */
75  int nintblocks; /**< number of blocks */
76 
77  SCIP_Bool execute; /**< has presolveTwoOpt detected
78  * necessary structure for execution of heuristic? */
79  unsigned int randseed; /**< seed value for random number generator */
80  int maxnslaves; /**< delimits the maximum number of slave candidates for a master variable */
81 #ifdef SCIP_STATISTIC
82  /* statistics */
83  int ntotalbinvars; /**< total number of binary variables over all runs */
84  int ntotalintvars; /**< total number of Integer variables over all runs */
85  int nruns; /**< counts the number of runs, i.e. the number of initialized
86  * branch and bound processes */
87  int maxbinblocksize; /**< maximum size of a binary block */
88  int maxintblocksize; /**< maximum size of an integer block */
89  int binnblockvars; /**< number of binary variables that appear in blocks */
90  int binnblocks; /**< number of blocks with at least two variables */
91  int intnblockvars; /**< number of Integer variables that appear in blocks */
92  int intnblocks; /**< number of blocks with at least two variables */
93  int binnexchanges; /**< number of executed changes of binary solution values leading to
94  * improvement in objective function */
95  int intnexchanges; /**< number of executed changes of Integer solution values leading to improvement in
96  * objective function */
97 #endif
98 };
99 
100 enum Opttype
101  {
102  OPTTYPE_BINARY = 1,
104  };
105 typedef enum Opttype OPTTYPE;
107 enum Direction
108  {
109  DIRECTION_UP = 1,
112  };
113 typedef enum Direction DIRECTION;
115 /*
116  * Local methods
117  */
118 
119 /** tries to switch the values of two binary or integer variables and checks feasibility with respect to the LP.
120  * @todo adapt method not to copy entire activities array, but only the relevant region
121  */
122 static
124  SCIP* scip, /**< scip instance */
125  SCIP_VAR* master, /**< first variable of variable pair */
126  SCIP_VAR* slave, /**< second variable of pair */
127  SCIP_Real mastersolval, /**< current value of variable1 in solution */
128  DIRECTION masterdir, /**< the direction into which the master variable has to be shifted */
129  SCIP_Real slavesolval, /**< current value of variable2 in solution */
130  DIRECTION slavedir, /**< the direction into which the slave variable has to be shifted */
131  SCIP_Real shiftval, /**< the value that variables should be shifted by */
132  SCIP_Real* activities, /**< the LP-row activities */
133  int nrows, /**< size of activities array */
134  SCIP_Bool* feasible /**< set to true if method has successfully switched the variable values */
135  )
136 { /*lint --e{715}*/
137  SCIP_COL* col;
138  SCIP_ROW** masterrows;
139  SCIP_ROW** slaverows;
140  SCIP_Real* mastercolvals;
141  SCIP_Real* slavecolvals;
142  int ncolmasterrows;
143  int ncolslaverows;
144  int i;
145  int j;
146 
147  assert(scip != NULL);
148  assert(master != NULL);
149  assert(slave != NULL);
150  assert(activities != NULL);
151  assert(SCIPisFeasGT(scip, shiftval, 0.0));
152 
153  assert(SCIPisFeasGE(scip, mastersolval + (int)masterdir * shiftval, SCIPvarGetLbGlobal(master)));
154  assert(SCIPisFeasLE(scip, mastersolval + (int)masterdir * shiftval, SCIPvarGetUbGlobal(master)));
155 
156  assert(SCIPisFeasGE(scip, slavesolval + (int)slavedir * shiftval, SCIPvarGetLbGlobal(slave)));
157  assert(SCIPisFeasLE(scip, slavesolval + (int)slavedir * shiftval, SCIPvarGetUbGlobal(slave)));
158 
159  /* get variable specific rows and coefficients for both master and slave. */
160  col = SCIPvarGetCol(master);
161  masterrows = SCIPcolGetRows(col);
162  mastercolvals = SCIPcolGetVals(col);
163  ncolmasterrows = SCIPcolGetNNonz(col);
164  assert(ncolmasterrows == 0 || masterrows != NULL);
165 
166  col = SCIPvarGetCol(slave);
167  slaverows = SCIPcolGetRows(col);
168  slavecolvals = SCIPcolGetVals(col);
169  ncolslaverows = SCIPcolGetNNonz(col);
170  assert(ncolslaverows == 0 || slaverows != NULL);
171 
172  /* update the activities of the LP rows of the master variable */
173  for( i = 0; i < ncolmasterrows && SCIProwGetLPPos(masterrows[i]) >= 0; ++i )
174  {
175  int rowpos;
176 
177  rowpos = SCIProwGetLPPos(masterrows[i]);
178  assert(rowpos < nrows);
179 
180  if( rowpos >= 0 )
181  activities[rowpos] += mastercolvals[i] * (int)masterdir * shiftval;
182  }
183 
184  /* update the activities of the LP rows of the slave variable */
185  for( j = 0; j < ncolslaverows && SCIProwGetLPPos(slaverows[j]) >= 0; ++j )
186  {
187  int rowpos;
188 
189  rowpos = SCIProwGetLPPos(slaverows[j]);
190  assert(rowpos < nrows);
191 
192  if( rowpos >= 0 )
193  {
194  activities[rowpos] += slavecolvals[j] * (int)slavedir * shiftval;
195  assert(SCIPisFeasGE(scip, activities[rowpos], SCIProwGetLhs(slaverows[j])));
196  assert(SCIPisFeasLE(scip, activities[rowpos], SCIProwGetRhs(slaverows[j])));
197  }
198  }
199  /* in debug mode, the master rows are checked for feasibility which should be granted by the
200  * decision for a shift value */
201 #ifndef NDEBUG
202  for( i = 0; i < ncolmasterrows && SCIProwGetLPPos(masterrows[i]) >= 0; ++i )
203  {
204  assert(SCIPisFeasGE(scip, activities[SCIProwGetLPPos(masterrows[i])], SCIProwGetLhs(masterrows[i])));
205  assert(SCIPisFeasLE(scip, activities[SCIProwGetLPPos(masterrows[i])], SCIProwGetRhs(masterrows[i])));
206  }
207 #endif
208  *feasible = TRUE;
209 
210  return SCIP_OKAY;
211 }
212 
213 /** compare two variables with respect to their columns. Columns are treated as {0,1} vector, where every nonzero entry
214  * is treated as '1', and compared to each other lexicographically. I.e. var1 is < var2 if the corresponding column of
215  * var2 has the smaller single nonzero index of the two columns. This comparison costs O(constraints) in the worst
216  * case
217  */
218 static
219 int varColCompare(
220  SCIP_VAR* var1, /**< left argument of comparison */
221  SCIP_VAR* var2 /**< right argument of comparison */
222  )
223 {
224  SCIP_COL* col1;
225  SCIP_COL* col2;
226  SCIP_ROW** rows1;
227  SCIP_ROW** rows2;
228  int nnonzeros1;
229  int nnonzeros2;
230  int i;
231 
232  assert(var1 != NULL);
233  assert(var2 != NULL);
234 
235  /* get the necessary row and column data */
236  col1 = SCIPvarGetCol(var1);
237  col2 = SCIPvarGetCol(var2);
238  rows1 = SCIPcolGetRows(col1);
239  rows2 = SCIPcolGetRows(col2);
240  nnonzeros1 = SCIPcolGetNNonz(col1);
241  nnonzeros2 = SCIPcolGetNNonz(col2);
242 
243  assert(nnonzeros1 == 0 || rows1 != NULL);
244  assert(nnonzeros2 == 0 || rows2 != NULL);
245 
246  /* loop over the rows, stopped as soon as they differ in one index,
247  * or if counter reaches the end of a variables row set */
248  for( i = 0; i < nnonzeros1 && i < nnonzeros2; ++i )
249  {
250  if( SCIProwGetIndex(rows1[i]) != SCIProwGetIndex(rows2[i]) )
251  return SCIProwGetIndex(rows1[i]) - SCIProwGetIndex(rows2[i]);
252  }
253 
254  /* loop is finished, without differing in one of common row indices, due to loop invariant
255  * variable i reached either nnonzeros1 or nnonzeros2 or both.
256  * one can easily check that the difference of these two numbers always has the desired sign for comparison. */
257  return nnonzeros2 - nnonzeros1 ;
258 }
259 
260 /** implements a comparator to compare two variables with respect to their column entries */
261 static
262 SCIP_DECL_SORTPTRCOMP(SCIPvarcolComp)
263 {
264  return varColCompare((SCIP_VAR*) elem1, (SCIP_VAR*) elem2);
265 }
266 
267 /** checks if two given variables are contained in common LP rows,
268  * returns true if variables share the necessary percentage (matchingrate) of rows.
269  */
270 static
272  SCIP* scip, /**< current SCIP instance */
273  SCIP_VAR* var1, /**< first variable */
274  SCIP_VAR* var2, /**< second variable */
275  SCIP_Real matchingrate /**< determines the ratio of shared LP rows compared to the total number of
276  * LP-rows each variable appears in */
277  )
278 {
279  SCIP_COL* col1;
280  SCIP_COL* col2;
281  SCIP_ROW** rows1;
282  SCIP_ROW** rows2;
283  int nnonzeros1;
284  int nnonzeros2;
285  int i;
286  int j;
287  int nrows1not2; /* the number of LP-rows of variable 1 which variable 2 doesn't appear in */
288  int nrows2not1; /* vice versa */
289  int nrowmaximum;
290  int nrowabs;
291 
292  assert(var1 != NULL);
293  assert(var2 != NULL);
294 
295  /* get the necessary row and column data */
296  col1 = SCIPvarGetCol(var1);
297  col2 = SCIPvarGetCol(var2);
298  rows1 = SCIPcolGetRows(col1);
299  rows2 = SCIPcolGetRows(col2);
300  nnonzeros1 = SCIPcolGetNNonz(col1);
301  nnonzeros2 = SCIPcolGetNNonz(col2);
302 
303  assert(nnonzeros1 == 0 || rows1 != NULL);
304  assert(nnonzeros2 == 0 || rows2 != NULL);
305 
306  if( nnonzeros1 == 0 && nnonzeros2 == 0 )
307  return TRUE;
308 
309 
310  /* initialize the counters for the number of rows not shared. */
311  nrowmaximum = MAX(nnonzeros1, nnonzeros2);
312 
313  nrowabs = ABS(nnonzeros1 - nnonzeros2);
314  nrows1not2 = nrowmaximum - nnonzeros2;
315  nrows2not1 = nrowmaximum - nnonzeros1;
316 
317  /* if the numbers of nonzero rows differs too much, w.r.t.matching ratio, the more expensive check over the rows
318  * doesn't have to be applied anymore because the counters for not shared rows can only increase.
319  */
320  assert(nrowmaximum > 0);
321 
322  if( (nrowmaximum - nrowabs) / (SCIP_Real) nrowmaximum < matchingrate )
323  return FALSE;
324 
325  i = 0;
326  j = 0;
327 
328  /* loop over all rows and determine number of non-shared rows */
329  while( i < nnonzeros1 && j < nnonzeros2 )
330  {
331  /* variables share a common row */
332  if( SCIProwGetIndex(rows1[i]) == SCIProwGetIndex(rows2[j]) )
333  {
334  ++i;
335  ++j;
336  }
337  /* variable 1 appears in rows1[i], variable 2 doesn't */
338  else if( SCIProwGetIndex(rows1[i]) < SCIProwGetIndex(rows2[j]) )
339  {
340  ++i;
341  ++nrows1not2;
342  }
343  /* variable 2 appears in rows2[j], variable 1 doesn't */
344  else
345  {
346  ++j;
347  ++nrows2not1;
348  }
349  }
350  /* now apply the ratio based comparison, that is if the ratio of shared rows is greater or equal the matching rate
351  * for each variable
352  */
353  return ( SCIPisFeasLE(scip, matchingrate, (nnonzeros1 - nrows1not2) / (SCIP_Real)(nnonzeros1)) ||
354  SCIPisFeasLE(scip, matchingrate, (nnonzeros2 - nrows2not1) / (SCIP_Real)(nnonzeros2)) ); /*lint !e795 */
355 }
356 
357 /** determines a bound by which the absolute solution value of two integer variables can be shifted at most.
358  * the criterion is the maintenance of feasibility of any global LP row.
359  * first implementation only considers shifting proportion 1:1, i.e. if master value is shifted by a certain
360  * integer value k downwards, the value of slave is simultaneously shifted by k upwards.
361  */
362 static
364  SCIP* scip, /**< current scip instance */
365  SCIP_SOL* sol, /**< current incumbent */
366  SCIP_VAR* master, /**< current master variable */
367  DIRECTION masterdirection, /**< the shifting direction of the master variable */
368  SCIP_VAR* slave, /**< slave variable with same LP_row set as master variable */
369  DIRECTION slavedirection, /**< the shifting direction of the slave variable */
370  SCIP_Real* activities, /**< array of LP row activities */
371  int nrows /**< the number of rows in LP and the size of the activities array */
372  )
373 { /*lint --e{715}*/
374  SCIP_Real masterbound;
375  SCIP_Real slavebound;
376  SCIP_Real bound;
377 
378  SCIP_COL* col;
379  SCIP_ROW** slaverows;
380  SCIP_ROW** masterrows;
381  SCIP_Real* mastercolvals;
382  SCIP_Real* slavecolvals;
383  int nslaverows;
384  int nmasterrows;
385  int i;
386  int j;
387 
388  assert(scip != NULL);
389  assert(sol != NULL);
390  assert(master != NULL);
391  assert(slave != NULL);
392  assert(SCIPvarIsIntegral(master) && SCIPvarIsIntegral(slave));
393  assert(masterdirection == DIRECTION_UP || masterdirection == DIRECTION_DOWN);
394  assert(slavedirection == DIRECTION_UP || slavedirection == DIRECTION_DOWN);
395 
396  /* determine the trivial variable bounds for shift */
397  if( masterdirection == DIRECTION_UP )
398  masterbound = SCIPvarGetUbGlobal(master) - SCIPgetSolVal(scip, sol, master);
399  else
400  masterbound = SCIPgetSolVal(scip, sol, master) - SCIPvarGetLbGlobal(master);
401 
402  if( slavedirection == DIRECTION_UP )
403  slavebound = SCIPvarGetUbGlobal(slave) - SCIPgetSolVal(scip, sol, slave);
404  else
405  slavebound = SCIPgetSolVal(scip, sol, slave) - SCIPvarGetLbGlobal(slave);
406 
407  bound = MIN(slavebound, masterbound);
408  assert(!SCIPisInfinity(scip,bound));
409  if( SCIPisFeasZero(scip, bound) )
410  return 0.0;
411 
412  /* get the necessary row and and column data for each variable */
413  col = SCIPvarGetCol(slave);
414  slaverows = SCIPcolGetRows(col);
415  slavecolvals = SCIPcolGetVals(col);
416  nslaverows = SCIPcolGetNNonz(col);
417 
418  col = SCIPvarGetCol(master);
419  mastercolvals = SCIPcolGetVals(col);
420  masterrows = SCIPcolGetRows(col);
421  nmasterrows = SCIPcolGetNNonz(col);
422 
423  assert(nslaverows == 0 || slavecolvals != NULL);
424  assert(nmasterrows == 0 || mastercolvals != NULL);
425 
426  SCIPdebugMessage(" Master: %s with direction %d and %d rows, Slave: %s with direction %d and %d rows \n", SCIPvarGetName(master),
427  (int)masterdirection, nmasterrows, SCIPvarGetName(slave), (int)slavedirection, nslaverows);
428 
429  /* loop over all LP rows and determine the maximum integer bound by which both variables
430  * can be shifted without loss of feasibility
431  */
432  i = 0;
433  j = 0;
434  while( (i < nslaverows || j < nmasterrows) && SCIPisPositive(scip, bound) )
435  {
436  SCIP_ROW* row;
437  SCIP_Real effect;
438  SCIP_Real rhs;
439  SCIP_Real lhs;
440  SCIP_Real activity;
441  int rowpos;
442  int masterindex;
443  int slaveindex;
444  SCIP_Bool slaveincrement;
445  SCIP_Bool masterincrement;
446 
447  /* check if one pointer already reached the end of the respective array */
448  if( i < nslaverows && SCIProwGetLPPos(slaverows[i]) == -1 )
449  {
450  SCIPdebugMessage(" Slaverow %s is not in LP (i=%d, j=%d)\n", SCIProwGetName(slaverows[i]), i, j);
451  i = nslaverows;
452  continue;
453  }
454  if( j < nmasterrows && SCIProwGetLPPos(masterrows[j]) == -1 )
455  {
456  SCIPdebugMessage(" Masterrow %s is not in LP (i=%d, j=%d) \n", SCIProwGetName(masterrows[j]), i, j);
457  j = nmasterrows;
458  continue;
459  }
460 
461  slaveincrement = FALSE;
462  masterincrement = FALSE;
463  /* If one counter has already reached its limit, assign a huge number to the corresponding
464  * row index to simulate an always greater row position. */
465  if( i < nslaverows )
466  slaveindex = SCIProwGetIndex(slaverows[i]);
467  else
468  slaveindex = INT_MAX;
469 
470  if( j < nmasterrows )
471  masterindex = SCIProwGetIndex(masterrows[j]);
472  else
473  masterindex = INT_MAX;
474 
475  assert(0 <= slaveindex && 0 <= masterindex);
476 
477  assert(slaveindex < INT_MAX || masterindex < INT_MAX);
478 
479  /* the current row is the one with the smaller index */
480  if( slaveindex <= masterindex )
481  {
482  rowpos = SCIProwGetLPPos(slaverows[i]);
483  row = slaverows[i];
484  slaveincrement = TRUE;
485  masterincrement = (slaveindex == masterindex);
486  }
487  else
488  {
489  assert(j < nmasterrows);
490 
491  rowpos = SCIProwGetLPPos(masterrows[j]);
492  row = masterrows[j];
493  masterincrement = TRUE;
494  }
495  assert(row != NULL);
496 
497  /* local rows can be skipped */
498  if( !SCIProwIsLocal(row) )
499  {
500  /* effect is the effect on the row activity by shifting the variables by 1 in the respective directions */
501  effect = 0.0;
502  if( slaveindex <= masterindex )
503  effect += (slavecolvals[i] * (int)slavedirection);
504  if( masterindex <= slaveindex )
505  effect += (mastercolvals[j] * (int)masterdirection);
506 
507  /* get information about the current row */
508  if( rowpos >= 0 && !SCIPisFeasZero(scip, effect) )
509  {
510  /* effect does not equal zero, the bound is determined as minimum positive integer such that
511  * feasibility of this constraint is maintained.
512  * if constraint is an equality constraint, activity and lhs/rhs should be feasibly equal, which
513  * will cause the method to return zero.
514  */
515  assert(rowpos < nrows);
516 
517  activity = activities[rowpos];
518  rhs = SCIProwGetRhs(row);
519  lhs = SCIProwGetLhs(row);
520 
521  /* if the row is an equation, abort because of effect being nonzero */
522  if( SCIPisFeasEQ(scip, lhs, rhs) )
523  return 0.0;
524 
525  assert(SCIPisFeasLE(scip, lhs, activity) && SCIPisFeasLE(scip, activity, rhs));
526 
527  SCIPdebugMessage(" %g <= %g <= %g, bound = %g, effect = %g (%g * %d + %g * %d) (i=%d,j=%d)\n", lhs, activity, rhs, bound, effect,
528  slaveindex <= masterindex ? slavecolvals[i] : 0.0, (int)slavedirection, masterindex <= slaveindex ? mastercolvals[j] : 0.0,
529  (int)masterdirection, i, j);
530 
531  /* if the row has a left hand side, ensure that shifting preserves feasibility of this ">="-constraint */
532  if( !SCIPisInfinity(scip, -lhs) && SCIPisFeasLT(scip, activity + (effect * bound), lhs) )
533  {
534  SCIP_Real newval;
535 
536  assert(SCIPisNegative(scip, effect));
537 
538  newval = SCIPfeasFloor(scip, (lhs - activity)/effect); /*lint !e414*/
539 
540  bound = MIN(bound - 1.0, newval);
541  }
542 
543  /* if the row has an upper bound, ensure that shifting preserves feasibility of this "<="-constraint */
544  if( !SCIPisInfinity(scip, rhs) && SCIPisFeasGT(scip, activity + (effect * bound), rhs) )
545  {
546  SCIP_Real newval;
547 
548  assert(SCIPisPositive(scip, effect));
549 
550  newval = SCIPfeasFloor(scip, (rhs - activity)/effect); /*lint !e414*/
551  bound = MIN(bound - 1.0, newval);
552  }
553 
554  assert(SCIPisFeasLE(scip, lhs, activity + effect * bound) && SCIPisFeasGE(scip, rhs, activity + effect * bound));
555  assert(SCIPisFeasIntegral(scip, bound));
556  }
557  else
558  {
559  SCIPdebugMessage(" Zero effect on row %s, effect %g, master coeff: %g slave coeff: %g (i=%d, j=%d)\n",
560  SCIProwGetName(row), effect, mastercolvals[j], slavecolvals[i], i, j);
561  }
562 
563  }
564  else
565  {
566  SCIPdebugMessage(" Row %s is local.\n", SCIProwGetName(row));
567  }
568 
569  /* increase the counters which belong to the corresponding row. Both counters are increased by
570  * 1 iff rowpos1 <= rowpos2 <= rowpos1 */
571  if( slaveincrement )
572  ++i;
573  if( masterincrement )
574  ++j;
575  }
576 
577  /* due to numerical reasons, bound can be negative. A variable shift by a negative bound is not desired by
578  * by the heuristic -> Change the return value to zero */
579  if( !SCIPisPositive(scip, bound) )
580  bound = 0.0;
581 
582  return bound;
583 }
584 
585 /**
586  * disposes variable with no heuristic relevancy, e.g., due to a fixed solution value, from its neighborhood block.
587  * The affected neighborhood block is reduced by 1.
588  */
589 static
590 void disposeVariable(
591  SCIP_VAR** vars, /**< problem variables */
592  int* blockend, /**< contains end index of block */
593  int varindex /**< variable index */
594  )
595 {
596  assert(blockend != NULL);
597  assert(varindex <= *blockend);
598 
599  vars[varindex] = vars[*blockend];
600  --(*blockend);
601 
602 }
603 
604 /** realizes the presolve independently from type of variables it's applied to */
605 static
607  SCIP* scip, /**< current scip */
608  SCIP_VAR** vars, /**< problem vars */
609  SCIP_VAR*** varspointer, /**< pointer to heuristic specific variable memory */
610  int nvars, /**< the number of variables */
611  int* nblocks, /**< pointer to store the number of detected blocks */
612  int* maxblocksize, /**< maximum size of a block */
613  int* nblockvars, /**< pointer to store the number of block variables */
614  int** blockstart, /**< pointer to store the array of block start indices */
615  int** blockend, /**< pointer to store the array of block end indices */
616  SCIP_HEUR* heur, /**< the heuristic */
617  SCIP_HEURDATA* heurdata /**< the heuristic data */
618  )
619 {
620  int v;
621  int startindex;
622 
623  assert(scip != NULL);
624  assert(vars != NULL);
625  assert(nvars >= 2);
626  assert(nblocks != NULL);
627  assert(nblockvars != NULL);
628  assert(blockstart != NULL);
629  assert(blockend != NULL);
630  assert(heur != NULL);
631  assert(heurdata != NULL);
632 
633  /* allocate the heuristic specific variables */
634  SCIP_CALL( SCIPduplicateBlockMemoryArray(scip, varspointer, vars, nvars));
635 
636  /* sort the variables with respect to their columns */
637  SCIPsortPtr((void**)(*varspointer), SCIPvarcolComp, nvars);
638 
639  /* start determining blocks, i.e. a set of at least two variables which share most of their row set.
640  * If there is none, heuristic does not need to be executed.
641  */
642  startindex = 0;
643  *nblocks = 0;
644  *nblockvars = 0;
645 
646  SCIP_CALL( SCIPallocBlockMemoryArray(scip, blockstart, nvars/2) );
647  SCIP_CALL( SCIPallocBlockMemoryArray(scip, blockend, nvars/2) );
648 
649  /* loop over variables and compare neighbors */
650  for( v = 1; v < nvars; ++v )
651  {
652  if( !checkConstraintMatching(scip, (*varspointer)[startindex], (*varspointer)[v], heurdata->matchingrate) )
653  {
654  /* current block has its last variable at position v-1. If v differs from startindex by at least 2,
655  * a block is detected. Update the data correspondingly */
656  if( v - startindex >= 2 )
657  {
658  assert(*nblocks < nvars/2);
659  (*nblockvars) += v - startindex;
660  (*maxblocksize) = MAX((*maxblocksize), v - startindex);
661  (*blockstart)[*nblocks] = startindex;
662  (*blockend)[*nblocks] = v - 1;
663  (*nblocks)++;
664  }
665  startindex = v;
666  }
667  else if( v == nvars - 1 && v - startindex >= 1 )
668  {
669  assert(*nblocks < nvars/2);
670  (*nblockvars) += v - startindex + 1;
671  (*maxblocksize) = MAX((*maxblocksize), v - startindex + 1);
672  (*blockstart)[*nblocks] = startindex;
673  (*blockend)[*nblocks] = v;
674  (*nblocks)++;
675  }
676  }
677 
678  /* reallocate memory with respect to the number of found blocks; if there were none, free the memory */
679  if( *nblocks > 0 )
680  {
681  SCIP_CALL( SCIPreallocBlockMemoryArray(scip, blockstart, nvars/2, *nblocks) );
682  SCIP_CALL( SCIPreallocBlockMemoryArray(scip, blockend, nvars/2, *nblocks) );
683  }
684  else
685  {
686  SCIPfreeBlockMemoryArray(scip, blockstart, nvars/2);
687  SCIPfreeBlockMemoryArray(scip, blockend, nvars/2);
688 
689  *blockstart = NULL;
690  *blockend = NULL;
691  }
692 
693  return SCIP_OKAY;
694 }
695 
696 /** initializes the required structures for execution of heuristic.
697  * If objective coefficient functions are not all equal, each Binary and Integer variables are sorted
698  * into heuristic-specific arrays with respect to their lexicographical column order,
699  * where every zero in a column is interpreted as zero and every nonzero as '1'.
700  * After the sorting, the variables are compared with respect to user parameter matchingrate and
701  * the heuristic specific blocks are determined.
702  */
703 static
705  SCIP* scip, /**< current scip instance */
706  SCIP_HEUR* heur, /**< heuristic */
707  SCIP_HEURDATA* heurdata /**< the heuristic data */
708  )
709 {
710  int nbinvars;
711  int nintvars;
712  int nvars;
713  SCIP_VAR** vars;
714  int nbinblockvars;
715  int nintblockvars;
716  int maxbinblocksize;
717  int maxintblocksize;
718 
719  assert(scip != NULL);
720  assert(heurdata != NULL);
721 
722  maxbinblocksize = 0;
723  /* ensure that method is not executed if presolving was already applied once in current branch and bound process */
724  if( heurdata->presolved )
725  return SCIP_OKAY;
726 
727  /* get necessary variable information, i.e. number of binary and integer variables */
728  SCIP_CALL( SCIPgetVarsData(scip, &vars, &nvars, &nbinvars, &nintvars, NULL, NULL) );
729 
730  nbinblockvars = 0;
731 
732  /* if number of binary problem variables exceeds 2, they are subject to 2-optimization algorithm, hence heuristic
733  * calls innerPresolve method to detect necessary structures.
734  */
735  if( nbinvars >= 2 )
736  {
737  SCIP_CALL( innerPresolve(scip, vars, &(heurdata->binvars), nbinvars, &(heurdata->nbinblocks), &maxbinblocksize,
738  &nbinblockvars, &(heurdata->binblockstart), &(heurdata->binblockend), heur, heurdata) );
739  }
740 
741  heurdata->nbinvars = nbinvars;
742 
743  heurdata->execute = nbinvars > 1 && heurdata->nbinblocks > 0;
744 
745 #ifdef SCIP_STATISTIC
746  /* update statistics */
747  heurdata->binnblocks += (heurdata->nbinblocks);
748  heurdata->binnblockvars += nbinblockvars;
749  heurdata->ntotalbinvars += nbinvars;
750  heurdata->maxbinblocksize = MAX(maxbinblocksize, heurdata->maxbinblocksize);
751 
752  SCIPstatisticMessage(" Twoopt BINARY presolving finished with <%d> blocks, <%d> block variables \n",
753  heurdata->nbinblocks, nbinblockvars);
754 
755 #endif
756 
757  if( heurdata->intopt && nintvars > 1 )
758  {
759  SCIP_CALL( innerPresolve(scip, &(vars[nbinvars]), &(heurdata->intvars), nintvars, &(heurdata->nintblocks), &maxintblocksize,
760  &nintblockvars, &(heurdata->intblockstart), &(heurdata->intblockend),
761  heur, heurdata) );
762 
763  heurdata->execute = heurdata->execute || heurdata->nintblocks > 0;
764 
765 #ifdef SCIP_STATISTIC
766  /* update statistics */
767  heurdata->intnblocks += heurdata->nintblocks;
768  heurdata->intnblockvars += nintblockvars;
769  heurdata->ntotalintvars += nintvars;
770  heurdata->maxintblocksize = MAX(maxintblocksize, heurdata->maxintblocksize);
771  SCIPstatisticMessage(" Twoopt Integer presolving finished with <%d> blocks, <%d> block variables \n",
772  heurdata->nintblocks, nintblockvars);
773  SCIPstatisticMessage(" INTEGER coefficients are all equal \n");
774 #endif
775  }
776  heurdata->nintvars = nintvars;
777 
778  /* presolving is finished, heuristic data is updated*/
779  heurdata->presolved = TRUE;
780  SCIPheurSetData(heur, heurdata);
781 
782  return SCIP_OKAY;
783 }
784 
785 /*
786  * Callback methods of primal heuristic
787  */
788 
789 /** copy method for primal heuristic plugins (called when SCIP copies plugins) */
790 static
791 SCIP_DECL_HEURCOPY(heurCopyTwoopt)
792 { /*lint --e{715}*/
793  assert(scip != NULL);
794  assert(heur != NULL);
795  assert(strcmp(SCIPheurGetName(heur), HEUR_NAME) == 0);
796 
797  /* call inclusion method of primal heuristic */
799 
800  return SCIP_OKAY;
801 }
802 
803 /** destructor of primal heuristic to free user data (called when SCIP is exiting) */
804 static
805 SCIP_DECL_HEURFREE(heurFreeTwoopt)
806 { /*lint --e{715}*/
807  SCIP_HEURDATA* heurdata;
808 
809  assert(heur != NULL);
810  assert(strcmp(SCIPheurGetName(heur), HEUR_NAME) == 0);
811  assert(scip != NULL);
812 
813  /* free heuristic data */
814  heurdata = SCIPheurGetData(heur);
815  assert(heurdata != NULL);
816 
817  SCIPfreeMemory(scip, &heurdata);
818  SCIPheurSetData(heur, NULL);
819 
820  return SCIP_OKAY;
821 }
822 
823 /** initialization method of primal heuristic (called after problem was transformed) */
824 static
825 SCIP_DECL_HEURINIT(heurInitTwoopt)
826 {
827  SCIP_HEURDATA* heurdata;
828  assert(heur != NULL);
829  assert(strcmp(SCIPheurGetName(heur), HEUR_NAME) == 0);
830  assert(scip != NULL);
831 
832  heurdata = SCIPheurGetData(heur);
833  assert(heurdata != NULL);
834 
835  /* heuristic has not run yet, all heuristic specific data
836  * is set to initial values */
837  heurdata->nbinvars = 0;
838  heurdata->nintvars = 0;
839  heurdata->lastsolindex = -1;
840  heurdata->presolved = FALSE;
841  heurdata->nbinblocks = 0;
842  heurdata->nintblocks = 0;
843 
844  heurdata->randseed = 0;
845 
846 #ifdef SCIP_STATISTIC
847  /* initialize statistics */
848  heurdata->binnexchanges = 0;
849  heurdata->intnexchanges = 0;
850  heurdata->binnblockvars = 0;
851  heurdata->intnblockvars = 0;
852  heurdata->binnblocks = 0;
853  heurdata->intnblocks = 0;
854 
855  heurdata->maxbinblocksize = 0;
856  heurdata->maxintblocksize = 0;
857 
858  heurdata->ntotalbinvars = 0;
859  heurdata->ntotalintvars = 0;
860  heurdata->nruns = 0;
861 #endif
862 
863  /* all pointers are initially set to NULL. Since presolving
864  * of the heuristic requires a lot of calculation time on some instances,
865  * but might not be needed e.g. if problem is infeasible, presolving is applied
866  * when heuristic is executed for the first time
867  */
868  heurdata->binvars = NULL;
869  heurdata->intvars = NULL;
870  heurdata->binblockstart = NULL;
871  heurdata->binblockend = NULL;
872  heurdata->intblockstart = NULL;
873  heurdata->intblockend = NULL;
874 
875  SCIPheurSetData(heur, heurdata);
876 
877  return SCIP_OKAY;
878 }
879 
880 /* realizes the 2-optimization algorithm, which tries to improve incumbent solution
881  * by shifting pairs of variables which share a common row set.
882  */
883 static
885  SCIP* scip, /**< current SCIP instance */
886  SCIP_SOL* worksol, /**< working solution */
887  SCIP_VAR** vars, /**< binary or integer variables */
888  int* blockstart, /**< contains start indices of blocks */
889  int* blockend, /**< contains end indices of blocks */
890  int nblocks, /**< the number of blocks */
891  OPTTYPE opttype, /**< are binaries or integers optimized */
892  SCIP_Real* activities, /**< the LP-row activities */
893  int nrows, /**< the number of LP rows */
894  SCIP_Bool* improvement, /**< was there a successful shift? */
895  SCIP_Bool* varboundserr, /**< has the current incumbent already been cut off */
896  SCIP_HEURDATA* heurdata /**< the heuristic data */
897  )
898 { /*lint --e{715}*/
899  int b;
900  SCIP_Real* objchanges;
901  SCIP_VAR** bestmasters;
902  SCIP_VAR** bestslaves;
903  int* bestdirections;
904  int arraysize;
905  int npairs;
906 
907  assert(scip != NULL);
908  assert(nblocks > 0);
909  assert(blockstart != NULL && blockend != NULL);
910  assert(varboundserr != NULL);
911  assert(activities != NULL);
912  assert(worksol != NULL);
913  assert(improvement != NULL);
914 
915  *varboundserr = FALSE;
916 
917 
918  SCIP_CALL( SCIPallocBufferArray(scip, &bestmasters, DEFAULT_ARRAYSIZE) );
919  SCIP_CALL( SCIPallocBufferArray(scip, &bestslaves, DEFAULT_ARRAYSIZE) );
920  SCIP_CALL( SCIPallocBufferArray(scip, &objchanges, DEFAULT_ARRAYSIZE) );
921  SCIP_CALL( SCIPallocBufferArray(scip, &bestdirections, DEFAULT_ARRAYSIZE) );
922  arraysize = DEFAULT_ARRAYSIZE;
923  npairs = 0;
924 
925  /* iterate over blocks */
926  for( b = 0; b < nblocks; ++b )
927  {
928  int m;
929  int blocklen;
930 
931  blocklen = blockend[b] - blockstart[b] + 1;
932 
933  /* iterate over variables in current block */
934  for( m = 0; m < blocklen; ++m )
935  {
936  /* determine the new master variable for heuristic's optimization method */
937  SCIP_VAR* master;
938  SCIP_Real masterobj;
939  SCIP_Real mastersolval;
940  SCIP_Real bestimprovement;
941  SCIP_Real bestbound;
942  int bestslavepos;
943  int s;
944  int firstslave;
945  int nslaves;
946  int bestdirection;
947  DIRECTION bestmasterdir;
948  DIRECTION bestslavedir;
949 
950  master = vars[blockstart[b] + m]; /*lint !e679*/
951  masterobj = SCIPvarGetObj(master);
952  mastersolval = SCIPgetSolVal(scip, worksol, master);
953 
954  /* due to cuts or fixings of solution values, worksol might not be feasible w.r.t. its bounds.
955  * Exit method in that case. */
956  if( SCIPisFeasGT(scip, mastersolval, SCIPvarGetUbGlobal(master)) || SCIPisFeasLT(scip, mastersolval, SCIPvarGetLbGlobal(master)) )
957  {
958  *varboundserr = TRUE;
959  SCIPdebugMessage("Solution has violated variable bounds for var %s: %g <= %g <= %g \n",
960  SCIPvarGetName(master), SCIPvarGetLbGlobal(master), mastersolval, SCIPvarGetUbGlobal(master));
961  goto TERMINATE;
962  }
963 
964  /* if variable has fixed solution value, it is deleted from heuristic array */
965  if( SCIPisFeasEQ(scip, SCIPvarGetUbGlobal(master), SCIPvarGetLbGlobal(master)) )
966  {
967  disposeVariable(vars, &(blockend[b]), blockstart[b] + m);
968  --blocklen;
969  continue;
970  }
971  else if( SCIPvarGetStatus(master) != SCIP_VARSTATUS_COLUMN )
972  continue;
973 
974  assert(SCIPisFeasIntegral(scip, mastersolval));
975 
976  assert(opttype == OPTTYPE_INTEGER ||
977  (SCIPisFeasEQ(scip, mastersolval, 1.0) || SCIPisFeasEQ(scip, mastersolval, 0.0)));
978 
979  /* initialize the data of the best available shift */
980  bestimprovement = 0.0;
981  bestslavepos = -1;
982  bestbound = 0.0;
983  bestmasterdir = DIRECTION_NONE;
984  bestslavedir = DIRECTION_NONE;
985  bestdirection = -1;
986  /* in blocks with more than heurdata->maxnslaves variables, a slave candidate
987  * region is chosen */
988  if( heurdata->maxnslaves >= 0 && blocklen > heurdata->maxnslaves )
989  firstslave = SCIPgetRandomInt(blockstart[b] + m, blockend[b], &heurdata->randseed);
990  else
991  firstslave = blockstart[b] + m + 1;
992 
993  nslaves = MIN((heurdata->maxnslaves == -1 ? INT_MAX : heurdata->maxnslaves), blocklen);
994 
995  /* loop over block and determine a slave shift candidate for master variable.
996  * If more than one candidate is available, choose the shift which improves objective function
997  * the most.*/
998  for( s = 0; s < nslaves; ++s )
999  {
1000  SCIP_VAR* slave;
1001  SCIP_Real slaveobj;
1002  SCIP_Real slavesolval;
1003  SCIP_Real changedobj;
1004  SCIP_Real diffdirbound;
1005  SCIP_Real equaldirbound;
1006  int directions;
1007  int slaveindex;
1008 
1009  slaveindex = (firstslave + s - blockstart[b]) % blocklen;
1010  slaveindex += blockstart[b];
1011 
1012  /* in case of a small block, we do not want to try possible pairings twice */
1013  if( (blocklen <= heurdata->maxnslaves || heurdata->maxnslaves == -1) && slaveindex < blockstart[b] + m )
1014  break;
1015  /* master and slave should not be the same variable */
1016  if( slaveindex == blockstart[b] + m )
1017  continue;
1018 
1019  /* get the next slave variable */
1020  slave = vars[slaveindex];
1021  slaveobj = SCIPvarGetObj(slave);
1022  slavesolval = SCIPgetSolVal(scip, worksol, slave);
1023  changedobj = 0.0;
1024 
1025  assert(SCIPvarGetType(master) == SCIPvarGetType(slave));
1026  assert(SCIPisFeasIntegral(scip, slavesolval));
1027  assert(opttype == OPTTYPE_INTEGER ||
1028  (SCIPisFeasEQ(scip, slavesolval, 1.0) || SCIPisFeasEQ(scip, slavesolval, 0.0)));
1029 
1030  /* solution is not feasible w.r.t. the variable bounds, stop optimization in this case */
1031  if( SCIPisFeasGT(scip, slavesolval, SCIPvarGetUbGlobal(slave)) || SCIPisFeasLT(scip, slavesolval, SCIPvarGetLbGlobal(slave)) )
1032  {
1033  *varboundserr = TRUE;
1034  SCIPdebugMessage("Solution has violated variable bounds for var %s: %g <= %g <= %g \n",
1035  SCIPvarGetName(slave), SCIPvarGetLbGlobal(slave), slavesolval, SCIPvarGetUbGlobal(slave));
1036  goto TERMINATE;
1037  }
1038 
1039  /* if solution value of the variable is fixed, delete it from the remaining candidates in the block */
1040  if( SCIPisFeasEQ(scip, SCIPvarGetUbGlobal(slave), SCIPvarGetLbGlobal(slave) ) )
1041  {
1042  disposeVariable(vars, &(blockend[b]), slaveindex);
1043  --blocklen;
1044  continue;
1045  }
1046  else if( SCIPvarGetStatus(master) != SCIP_VARSTATUS_COLUMN )
1047  continue;
1048 
1049  /* determine the shifting direction to improve the objective function */
1050  /* assert(SCIPisFeasGT(scip, masterobj, slaveobj)); */
1051 
1052  /* the heuristic chooses the shifting direction and the corresponding maximum nonnegative
1053  * integer shift value for the two variables which preserves feasibility and improves
1054  * the objective function value.
1055  */
1056  directions = -1;
1057  diffdirbound = 0.0;
1058  equaldirbound = 0.0;
1059 
1060  if( SCIPisFeasLT(scip, masterobj - slaveobj, 0.0) )
1061  {
1062  diffdirbound = determineBound(scip, worksol, master, DIRECTION_UP, slave, DIRECTION_DOWN, activities, nrows);
1063  directions = 2;
1064  /* the improvement of objective function is calculated */
1065  changedobj = (masterobj - slaveobj) * diffdirbound;
1066  }
1067  else if( SCIPisFeasGT(scip, masterobj - slaveobj, 0.0) )
1068  {
1069  diffdirbound = determineBound(scip, worksol, master, DIRECTION_DOWN, slave, DIRECTION_UP, activities, nrows);
1070  directions = 1;
1071  changedobj = (slaveobj - masterobj) * diffdirbound;
1072  }
1073 
1074  if( SCIPisFeasLT(scip, masterobj + slaveobj, 0.0) )
1075  {
1076  equaldirbound = determineBound(scip, worksol, master, DIRECTION_UP, slave, DIRECTION_UP, activities, nrows);
1077  if( SCIPisFeasLT(scip, (slaveobj + masterobj) * equaldirbound, changedobj) )
1078  {
1079  changedobj = (slaveobj + masterobj) * equaldirbound;
1080  directions = 3;
1081  }
1082  }
1083  else if( SCIPisFeasGT(scip, masterobj + slaveobj, 0.0) )
1084  {
1085  equaldirbound = determineBound(scip, worksol, master, DIRECTION_DOWN, slave, DIRECTION_DOWN, activities, nrows);
1086  if( SCIPisFeasLT(scip, -(slaveobj + masterobj) * equaldirbound, changedobj) )
1087  {
1088  changedobj = -(slaveobj + masterobj) * equaldirbound;
1089  directions = 0;
1090  }
1091  }
1092  assert(SCIPisFeasIntegral(scip, equaldirbound));
1093  assert(SCIPisFeasIntegral(scip, diffdirbound));
1094  assert(SCIPisFeasGE(scip, equaldirbound, 0.0));
1095  assert(SCIPisFeasGE(scip, diffdirbound, 0.0));
1096 
1097  /* choose the candidate which improves the objective function the most */
1098  if( (SCIPisFeasGT(scip, equaldirbound, 0.0) || SCIPisFeasGT(scip, diffdirbound, 0.0))
1099  && SCIPisFeasLT(scip, changedobj, bestimprovement) )
1100  {
1101  bestimprovement = changedobj;
1102  bestslavepos = slaveindex;
1103  bestdirection = directions;
1104  /* the most promising shift, i.e., the one which can improve the objective
1105  * the most, is recorded by the integer 'directions'. It is recovered via the use
1106  * of a binary representation of the four different combinations for the shifting directions
1107  * of two variables */
1108  if( directions / 2 == 1 )
1109  bestmasterdir = DIRECTION_UP;
1110  else
1111  bestmasterdir = DIRECTION_DOWN;
1112 
1113  if( directions % 2 == 1 )
1114  bestslavedir = DIRECTION_UP;
1115  else
1116  bestslavedir = DIRECTION_DOWN;
1117 
1118  if( bestmasterdir == bestslavedir )
1119  bestbound = equaldirbound;
1120  else
1121  bestbound = diffdirbound;
1122  }
1123  }
1124 
1125  /* choose the most promising candidate, if one exists */
1126  if( bestslavepos >= 0 )
1127  {
1128  if( npairs == arraysize )
1129  {
1130  SCIP_CALL( SCIPreallocBufferArray(scip, &bestmasters, 2 * arraysize) );
1131  SCIP_CALL( SCIPreallocBufferArray(scip, &bestslaves, 2 * arraysize) );
1132  SCIP_CALL( SCIPreallocBufferArray(scip, &objchanges, 2 * arraysize) );
1133  SCIP_CALL( SCIPreallocBufferArray(scip, &bestdirections, 2 * arraysize) );
1134  arraysize = 2 * arraysize;
1135  }
1136 
1137  assert( npairs < arraysize );
1138 
1139  bestmasters[npairs] = master;
1140  bestslaves[npairs] = vars[bestslavepos];
1141  objchanges[npairs] = ((int)bestslavedir * SCIPvarGetObj(bestslaves[npairs]) + (int)bestmasterdir * masterobj) * bestbound;
1142  bestdirections[npairs] = bestdirection;
1143 
1144  assert(objchanges[npairs] < 0);
1145 
1146  SCIPdebugMessage(" Saved candidate pair {%s=%g, %s=%g} with objectives <%g>, <%g> to be set to {%g, %g} %d\n",
1147  SCIPvarGetName(master), mastersolval, SCIPvarGetName(bestslaves[npairs]), SCIPgetSolVal(scip, worksol, bestslaves[npairs]) ,
1148  masterobj, SCIPvarGetObj(bestslaves[npairs]), mastersolval + (int)bestmasterdir * bestbound, SCIPgetSolVal(scip, worksol, bestslaves[npairs])
1149  + (int)bestslavedir * bestbound, bestdirections[npairs]);
1150 
1151  ++npairs;
1152  }
1153  }
1154  }
1155 
1156  if( npairs == 0 )
1157  goto TERMINATE;
1158 
1159  SCIPsortRealPtrPtrInt(objchanges, (void**)bestmasters, (void**)bestslaves, bestdirections, npairs);
1160 
1161  for( b = 0; b < npairs; ++b )
1162  {
1163  SCIP_VAR* master;
1164  SCIP_VAR* slave;
1165  SCIP_Real mastersolval;
1166  SCIP_Real slavesolval;
1167  SCIP_Real masterobj;
1168  SCIP_Real slaveobj;
1169  SCIP_Real bound;
1170  DIRECTION masterdir;
1171  DIRECTION slavedir;
1172 
1173  master = bestmasters[b];
1174  slave = bestslaves[b];
1175  mastersolval = SCIPgetSolVal(scip, worksol, master);
1176  slavesolval = SCIPgetSolVal(scip, worksol, slave);
1177  masterobj =SCIPvarGetObj(master);
1178  slaveobj = SCIPvarGetObj(slave);
1179 
1180  assert(0 <= bestdirections[b] && bestdirections[b] < 4);
1181 
1182  if( bestdirections[b] / 2 == 1 )
1183  masterdir = DIRECTION_UP;
1184  else
1185  masterdir = DIRECTION_DOWN;
1186 
1187  if( bestdirections[b] % 2 == 1 )
1188  slavedir = DIRECTION_UP;
1189  else
1190  slavedir = DIRECTION_DOWN;
1191 
1192 
1193  bound = determineBound(scip, worksol, master, masterdir, slave, slavedir, activities, nrows);
1194 
1195  if( !SCIPisZero(scip, bound) )
1196  {
1197  SCIP_Bool feasible;
1198 #ifndef NDEBUG
1199  SCIP_Real changedobj;
1200 #endif
1201 
1202  SCIPdebugMessage(" Promising candidates {%s=%g, %s=%g} with objectives <%g>, <%g> to be set to {%g, %g}\n",
1203  SCIPvarGetName(master), mastersolval, SCIPvarGetName(slave), slavesolval,
1204  masterobj, slaveobj, mastersolval + (int)masterdir * bound, slavesolval + (int)slavedir * bound);
1205 
1206 #ifndef NDEBUG
1207  /* the improvement of objective function is calculated */
1208  changedobj = ((int)slavedir * slaveobj + (int)masterdir * masterobj) * bound;
1209  assert(SCIPisFeasLT(scip, changedobj, 0.0));
1210 #endif
1211 
1213  /* try to change the solution values of the variables */
1214  feasible = FALSE;
1215  SCIP_CALL( shiftValues(scip, master, slave, mastersolval, masterdir, slavesolval, slavedir, bound,
1216  activities, nrows, &feasible) );
1217 
1218  if( feasible )
1219  {
1220  /* The variables' solution values were successfully shifted and can hence be updated. */
1221  assert(SCIPisFeasIntegral(scip, mastersolval + ((int)masterdir * bound)));
1222  assert(SCIPisFeasIntegral(scip, slavesolval + ((int)slavedir * bound)));
1223 
1224  SCIP_CALL( SCIPsetSolVal(scip, worksol, master, mastersolval + (int)masterdir * bound) );
1225  SCIP_CALL( SCIPsetSolVal(scip, worksol, slave, slavesolval + (int)slavedir * bound) );
1226  SCIPdebugMessage(" Feasible shift: <%s>[%g, %g] (obj: %f) <%f> --> <%f>\n",
1227  SCIPvarGetName(master), SCIPvarGetLbGlobal(master), SCIPvarGetUbGlobal(master), masterobj, mastersolval, SCIPgetSolVal(scip, worksol, master));
1228  SCIPdebugMessage(" <%s>[%g, %g] (obj: %f) <%f> --> <%f>\n",
1229  SCIPvarGetName(slave), SCIPvarGetLbGlobal(slave), SCIPvarGetUbGlobal(slave), slaveobj, slavesolval, SCIPgetSolVal(scip, worksol, slave));
1230 
1231 #ifdef SCIP_STATISTIC
1232  /* update statistics */
1233  if( opttype == OPTTYPE_BINARY )
1234  ++(heurdata->binnexchanges);
1235  else
1236  ++(heurdata->intnexchanges);
1237 #endif
1238  *improvement = TRUE;
1239  }
1240  }
1241  }
1242  TERMINATE:
1243  SCIPfreeBufferArray(scip, &bestdirections);
1244  SCIPfreeBufferArray(scip, &objchanges);
1245  SCIPfreeBufferArray(scip, &bestslaves);
1246  SCIPfreeBufferArray(scip, &bestmasters);
1247 
1248  return SCIP_OKAY;
1249 }
1250 
1251 /** deinitialization method of primal heuristic (called before transformed problem is freed) */
1252 static
1253 SCIP_DECL_HEUREXIT(heurExitTwoopt)
1255  SCIP_HEURDATA* heurdata;
1256 
1257  heurdata = SCIPheurGetData(heur);
1258  assert(heurdata != NULL);
1259 
1260  /*ensure that initialization was successful */
1261  assert(heurdata->nbinvars <= 1 || heurdata->binvars != NULL);
1262 
1263 
1264 #ifdef SCIP_STATISTIC
1265  /* print relevant statistics to console */
1267  " Twoopt Binary Statistics : "
1268  "%6.2g %6.2g %4.2g %4.0g %6d (blocks/run, variables/run, varpercentage, avg. block size, max block size) \n",
1269  heurdata->nruns == 0 ? 0.0 : (SCIP_Real)heurdata->binnblocks/(heurdata->nruns),
1270  heurdata->nruns == 0 ? 0.0 : (SCIP_Real)heurdata->binnblockvars/(heurdata->nruns),
1271  heurdata->ntotalbinvars == 0 ? 0.0 : (SCIP_Real)heurdata->binnblockvars/(heurdata->ntotalbinvars) * 100.0,
1272  heurdata->binnblocks == 0 ? 0.0 : heurdata->binnblockvars/(SCIP_Real)(heurdata->binnblocks),
1273  heurdata->maxbinblocksize);
1274 
1276  " Twoopt Integer statistics : "
1277  "%6.2g %6.2g %4.2g %4.0g %6d (blocks/run, variables/run, varpercentage, avg block size, max block size) \n",
1278  heurdata->nruns == 0 ? 0.0 : (SCIP_Real)heurdata->intnblocks/(heurdata->nruns),
1279  heurdata->nruns == 0 ? 0.0 : (SCIP_Real)heurdata->intnblockvars/(heurdata->nruns),
1280  heurdata->ntotalintvars == 0 ? 0.0 : (SCIP_Real)heurdata->intnblockvars/(heurdata->ntotalintvars) * 100.0,
1281  heurdata->intnblocks == 0 ? 0.0 : heurdata->intnblockvars/(SCIP_Real)(heurdata->intnblocks),
1282  heurdata->maxintblocksize);
1283 
1285  " Twoopt results : "
1286  "%6d %6d %4d %4.2g (runs, binary exchanges, Integer shiftings, matching rate)\n",
1287  heurdata->nruns,
1288  heurdata->binnexchanges,
1289  heurdata->intnexchanges,
1290  heurdata->matchingrate);
1291 
1292  /* set statistics to initial values*/
1293  heurdata->binnblockvars = 0;
1294  heurdata->binnblocks = 0;
1295  heurdata->intnblocks = 0;
1296  heurdata->intnblockvars = 0;
1297  heurdata->binnexchanges = 0;
1298  heurdata->intnexchanges = 0;
1299 #endif
1300  /* free the allocated memory for the binary variables */
1301  if( heurdata->binvars != NULL )
1302  {
1303  SCIPfreeBlockMemoryArray(scip, &heurdata->binvars, heurdata->nbinvars);
1304  }
1305  if( heurdata->nbinblocks > 0 )
1306  {
1307  assert(heurdata->binblockstart != NULL);
1308  assert(heurdata->binblockend != NULL);
1309 
1310  SCIPfreeBlockMemoryArray(scip, &heurdata->binblockstart, heurdata->nbinblocks);
1311  SCIPfreeBlockMemoryArray(scip, &heurdata->binblockend, heurdata->nbinblocks);
1312  }
1313  heurdata->nbinvars = 0;
1314  heurdata->nbinblocks = 0;
1315 
1316  if( heurdata->nintblocks > 0 )
1317  {
1318  assert(heurdata->intblockstart != NULL);
1319  assert(heurdata->intblockend != NULL);
1320 
1321  SCIPfreeBlockMemoryArray(scip, &heurdata->intblockstart, heurdata->nintblocks);
1322  SCIPfreeBlockMemoryArray(scip, &heurdata->intblockend, heurdata->nintblocks);
1323  }
1324 
1325  /* free the allocated memory for the integers */
1326  if( heurdata->intvars != NULL )
1327  {
1328  SCIPfreeBlockMemoryArray(scip, &heurdata->intvars, heurdata->nintvars);
1329  }
1330 
1331  heurdata->nbinblocks = 0;
1332  heurdata->nintblocks = 0;
1333  heurdata->nbinvars = 0;
1334  heurdata->nintvars = 0;
1335 
1336  assert(heurdata->binvars == NULL);
1337  assert(heurdata->intvars == NULL);
1338 
1339  SCIPheurSetData(heur, heurdata);
1340 
1341  return SCIP_OKAY;
1342 }
1343 
1344 /** solving process initialization method of primal heuristic (called when branch and bound process is about to begin) */
1345 static
1346 SCIP_DECL_HEURINITSOL(heurInitsolTwoopt)
1348  SCIP_HEURDATA* heurdata;
1349  assert(heur != NULL);
1350  assert(strcmp(SCIPheurGetName(heur), HEUR_NAME) == 0);
1351  assert(scip != NULL);
1352 
1353  /* get heuristic data */
1354  heurdata = SCIPheurGetData(heur);
1355 
1356  assert(heurdata != NULL);
1357  assert(heurdata->binvars == NULL && heurdata->intvars == NULL);
1358  assert(heurdata->binblockstart == NULL && heurdata->binblockend == NULL);
1359  assert(heurdata->intblockstart == NULL && heurdata->intblockend == NULL);
1360 
1361  /* set heuristic data to initial values, but increase the total number of runs */
1362  heurdata->nbinvars = 0;
1363  heurdata->nintvars = 0;
1364  heurdata->lastsolindex = -1;
1365  heurdata->presolved = FALSE;
1366 
1367 #ifdef SCIP_STATISTIC
1368  ++(heurdata->nruns);
1369 #endif
1370 
1371  SCIPheurSetData(heur, heurdata);
1372 
1373  return SCIP_OKAY;
1374 }
1375 
1376 
1377 /** solving process deinitialization method of primal heuristic (called before branch and bound process data is freed) */
1378 static
1379 SCIP_DECL_HEUREXITSOL(heurExitsolTwoopt)
1381  SCIP_HEURDATA* heurdata;
1382  int nbinvars;
1383  int nintvars;
1384 
1385  assert(heur != NULL);
1386  assert(scip != NULL);
1387  assert(strcmp(SCIPheurGetName(heur), HEUR_NAME) == 0);
1388  assert(scip != NULL);
1389 
1390  /* get heuristic data */
1391  heurdata = SCIPheurGetData(heur);
1392 
1393  assert(heurdata != NULL);
1394 
1395  nbinvars = heurdata->nbinvars;
1396  nintvars = heurdata->nintvars;
1397 
1398  /* free the allocated memory for the binary variables */
1399  if( heurdata->binvars != NULL )
1400  {
1401  SCIPfreeBlockMemoryArray(scip, &heurdata->binvars, nbinvars);
1402  }
1403  if( heurdata->binblockstart != NULL )
1404  {
1405  assert(heurdata->binblockend != NULL);
1406 
1407  SCIPfreeBlockMemoryArray(scip, &heurdata->binblockstart, heurdata->nbinblocks);
1408  SCIPfreeBlockMemoryArray(scip, &heurdata->binblockend, heurdata->nbinblocks);
1409  }
1410  heurdata->nbinvars = 0;
1411  heurdata->nbinblocks = 0;
1412 
1413  if( heurdata->intblockstart != NULL )
1414  {
1415  assert(heurdata->intblockend != NULL);
1416 
1417  SCIPfreeBlockMemoryArray(scip, &heurdata->intblockstart, heurdata->nintblocks);
1418  SCIPfreeBlockMemoryArray(scip, &heurdata->intblockend, heurdata->nintblocks);
1419  }
1420  heurdata->nintblocks = 0;
1421 
1422  /* free the allocated memory for the integers */
1423  if( heurdata->intvars != NULL )
1424  {
1425  SCIPfreeBlockMemoryArray(scip, &heurdata->intvars, nintvars);
1426  }
1427 
1428  heurdata->nintvars = 0;
1429 
1430  assert(heurdata->binvars == NULL && heurdata->intvars == NULL);
1431  assert(heurdata->binblockstart == NULL && heurdata->binblockend == NULL);
1432  assert(heurdata->intblockstart == NULL && heurdata->intblockend == NULL);
1433 
1434  /* set heuristic data */
1435  SCIPheurSetData(heur, heurdata);
1436 
1437  return SCIP_OKAY;
1438 
1439 }
1440 
1441 /** execution method of primal heuristic */
1442 static
1443 SCIP_DECL_HEUREXEC(heurExecTwoopt)
1444 { /*lint --e{715}*/
1445  SCIP_HEURDATA* heurdata;
1446  SCIP_SOL* bestsol;
1447  SCIP_SOL* worksol;
1448  SCIP_ROW** lprows;
1449  SCIP_Real* activities;
1450  SCIP_COL** cols;
1451  int ncols;
1452  int nbinvars;
1453  int nintvars;
1454  int ndiscvars;
1455  int nlprows;
1456  int i;
1457  int ncolsforsorting;
1458  SCIP_Bool improvement;
1459  SCIP_Bool presolthiscall;
1460  SCIP_Bool varboundserr;
1461 
1462  assert(heur != NULL);
1463  assert(scip != NULL);
1464  assert(result != NULL);
1465 
1466  /* get heuristic data */
1467  heurdata = SCIPheurGetData(heur);
1468  assert(heurdata != NULL);
1469 
1470  *result = SCIP_DIDNOTRUN;
1471 
1472  /* we need an LP */
1473  if( SCIPgetNLPRows(scip) == 0 )
1474  return SCIP_OKAY;
1475 
1476  bestsol = SCIPgetBestSol(scip);
1477 
1478  /* ensure that heuristic has not already been processed on current incumbent */
1479  if( bestsol == NULL || heurdata->lastsolindex == SCIPsolGetIndex(bestsol) )
1480  return SCIP_OKAY;
1481 
1482  heurdata->lastsolindex = SCIPsolGetIndex(bestsol);
1483 
1484  /* we can only work on solutions valid in the transformed space */
1485  if( SCIPsolIsOriginal(bestsol) )
1486  return SCIP_OKAY;
1487 
1488 #ifdef SCIP_DEBUG
1489  SCIP_CALL( SCIPprintSol(scip, bestsol, NULL, TRUE) );
1490 #endif
1491 
1492  /* ensure that the user defined number of nodes after last best solution has been reached, return otherwise */
1493  if( (SCIPgetNNodes(scip) - SCIPsolGetNodenum(bestsol)) < heurdata->waitingnodes )
1494  return SCIP_OKAY;
1495 
1496  presolthiscall = FALSE;
1497  SCIP_CALL( SCIPgetLPColsData(scip,&cols, &ncols) );
1498  ndiscvars = SCIPgetNBinVars(scip) + SCIPgetNIntVars(scip);
1499  ncolsforsorting = MIN(ncols, ndiscvars);
1500 
1501  /* ensure that heuristic specific presolve is applied when heuristic is executed first */
1502  if( !heurdata->presolved )
1503  {
1504  SCIP_CALL( SCIPgetLPColsData(scip,&cols, &ncols) );
1505 
1506  for( i = 0; i < ncolsforsorting; ++i )
1507  SCIPcolSort(cols[i]);
1508 
1509  SCIP_CALL( presolveTwoOpt(scip, heur, heurdata) );
1510  presolthiscall = TRUE;
1511  }
1512 
1513  assert(heurdata->presolved);
1514 
1515  SCIPdebugMessage(" Twoopt heuristic is %sexecuting.\n", heurdata->execute ? "" : "not ");
1516  /* ensure that presolve has detected structures in the problem to which the 2-optimization can be applied.
1517  * That is if variables exist which share a common set of LP-rows. */
1518  if( !heurdata->execute )
1519  return SCIP_OKAY;
1520 
1521  nbinvars = heurdata->nbinvars;
1522  nintvars = heurdata->nintvars;
1523  ndiscvars = nbinvars + nintvars;
1524 
1525  /* we need to be able to start diving from current node in order to resolve the LP
1526  * with continuous or implicit integer variables
1527  */
1528  if( SCIPgetNVars(scip) > ndiscvars && ( !SCIPhasCurrentNodeLP(scip) || SCIPgetLPSolstat(scip) != SCIP_LPSOLSTAT_OPTIMAL ) )
1529  return SCIP_OKAY;
1530 
1531  /* problem satisfies all necessary conditions for 2-optimization heuristic, execute heuristic! */
1532  *result = SCIP_DIDNOTFIND;
1533 
1534  /* initialize a working solution as a copy of the current incumbent to be able to store
1535  * possible improvements obtained by 2-optimization */
1536  SCIP_CALL( SCIPcreateSolCopy(scip, &worksol, bestsol) );
1537  SCIPsolSetHeur(worksol, heur);
1538 
1539  /* get the LP row activities from current incumbent bestsol */
1540  SCIP_CALL( SCIPgetLPRowsData(scip, &lprows, &nlprows) );
1541  SCIP_CALL( SCIPallocBufferArray(scip, &activities, nlprows) );
1542 
1543  for( i = 0; i < nlprows; i++ )
1544  {
1545  SCIP_ROW* row;
1546 
1547  row = lprows[i];
1548  assert(row != NULL);
1549  assert(SCIProwGetLPPos(row) == i);
1550  SCIPdebugMessage(" Row <%d> is %sin LP: \n", i, SCIProwGetLPPos(row) >= 0 ? "" : "not ");
1551  SCIPdebug( SCIP_CALL( SCIPprintRow(scip, row, NULL) ) );
1552  activities[i] = SCIPgetRowSolActivity(scip, row, bestsol);
1553 
1554  /* Heuristic does not provide infeasibility recovery, thus if any constraint is violated,
1555  * execution has to be terminated.
1556  */
1557  if( !SCIProwIsLocal(row) && (SCIPisFeasLT(scip, activities[i], SCIProwGetLhs(row))
1558  || SCIPisFeasGT(scip, activities[i], SCIProwGetRhs(row))) )
1559  goto TERMINATE;
1560  }
1561 
1562  if( !presolthiscall )
1563  {
1564  for( i = 0; i < ncolsforsorting; ++i )
1565  {
1566  SCIPcolSort(cols[i]);
1567  }
1568  }
1569  SCIPdebugMessage(" Twoopt heuristic has initialized activities and sorted rows! \n");
1570 
1571  /* start with binary optimization */
1572  improvement = FALSE;
1573  varboundserr = FALSE;
1574 
1575  if( heurdata->nbinblocks > 0 )
1576  {
1577  SCIP_CALL( optimize(scip, worksol, heurdata->binvars, heurdata->binblockstart, heurdata->binblockend, heurdata->nbinblocks,
1578  OPTTYPE_BINARY, activities, nlprows, &improvement, &varboundserr, heurdata) );
1579 
1580  SCIPdebugMessage(" Binary Optimization finished!\n");
1581  }
1582 
1583  if( varboundserr )
1584  goto TERMINATE;
1585 
1586  /* ensure that their are at least two integer variables which do not have the same coefficient
1587  * in the objective function. In one of these cases, the heuristic will automatically skip the
1588  * integer variable optimization */
1589  if( heurdata->nintblocks > 0 )
1590  {
1591  assert(heurdata->intopt);
1592  SCIP_CALL( optimize(scip, worksol, heurdata->intvars, heurdata->intblockstart, heurdata->intblockend, heurdata->nintblocks,
1593  OPTTYPE_INTEGER, activities, nlprows, &improvement, &varboundserr, heurdata) );
1594 
1595  SCIPdebugMessage(" Integer Optimization finished!\n");
1596  }
1597 
1598  if( !improvement || varboundserr )
1599  goto TERMINATE;
1600 
1601  if( SCIPgetNVars(scip) == ndiscvars )
1602  {
1603  /* the problem is a pure IP, hence, no continuous or implicit variables are left for diving.
1604  * try if new working solution is feasible in original problem */
1605  SCIP_Bool success;
1606 #ifndef NDEBUG
1607  SCIP_CALL( SCIPtrySol(scip, worksol, FALSE, TRUE, TRUE, TRUE, &success) );
1608 #else
1609  SCIP_CALL( SCIPtrySol(scip, worksol, FALSE, FALSE, FALSE, TRUE, &success) );
1610 #endif
1611 
1612  if( success )
1613  {
1614  SCIPdebugMessage("found feasible shifted solution:\n");
1615  SCIPdebug( SCIP_CALL( SCIPprintSol(scip, worksol, NULL, FALSE) ) );
1616  heurdata->lastsolindex = SCIPsolGetIndex(bestsol);
1617  *result = SCIP_FOUNDSOL;
1618 
1619 #ifdef SCIP_STATISTIC
1620  SCIPstatisticMessage("***Twoopt improved solution found by %10s . \n",
1621  SCIPsolGetHeur(bestsol) != NULL ? SCIPheurGetName(SCIPsolGetHeur(bestsol)) :"Tree");
1622 
1623 #endif
1624  }
1625  }
1626  /* fix the integer variables and start diving to optimize continuous variables with respect to reduced domain */
1627  else
1628  {
1629  SCIP_VAR** allvars;
1630  SCIP_Bool lperror;
1631 #ifdef NDEBUG
1632  SCIP_RETCODE retstat;
1633 #endif
1634 
1635  SCIPdebugMessage("shifted solution should be feasible -> solve LP to fix continuous variables to best values\n");
1636 
1637  allvars = SCIPgetVars(scip);
1638 
1639 #ifdef SCIP_DEBUG
1640  for( i = ndiscvars; i < SCIPgetNVars(scip); ++i )
1641  {
1642  SCIPdebugMessage(" Cont. variable <%s>, status %d with bounds [%g <= %g <= x <= %g <= %g]\n",
1643  SCIPvarGetName(allvars[i]), SCIPvarGetStatus(allvars[i]), SCIPvarGetLbGlobal(allvars[i]), SCIPvarGetLbLocal(allvars[i]), SCIPvarGetUbLocal(allvars[i]),
1644  SCIPvarGetUbGlobal(allvars[i]));
1645  }
1646 #endif
1647  /* start diving to calculate the LP relaxation */
1648  SCIP_CALL( SCIPstartDive(scip) );
1649 
1650  /* set the bounds of the variables: fixed for integers, global bounds for continuous */
1651  for( i = 0; i < SCIPgetNVars(scip); ++i )
1652  {
1653  if( SCIPvarGetStatus(allvars[i]) == SCIP_VARSTATUS_COLUMN )
1654  {
1655  SCIP_CALL( SCIPchgVarLbDive(scip, allvars[i], SCIPvarGetLbGlobal(allvars[i])) );
1656  SCIP_CALL( SCIPchgVarUbDive(scip, allvars[i], SCIPvarGetUbGlobal(allvars[i])) );
1657  }
1658  }
1659 
1660  /* apply this after global bounds to not cause an error with intermediate empty domains */
1661  for( i = 0; i < ndiscvars; ++i )
1662  {
1663  if( SCIPvarGetStatus(allvars[i]) == SCIP_VARSTATUS_COLUMN )
1664  {
1665  SCIP_Real solval;
1666 
1667  solval = SCIPgetSolVal(scip, worksol, allvars[i]);
1668 
1669  assert(SCIPvarGetType(allvars[i]) != SCIP_VARTYPE_CONTINUOUS && SCIPisFeasIntegral(scip, solval));
1670 
1671  SCIP_CALL( SCIPchgVarLbDive(scip, allvars[i], solval) );
1672  SCIP_CALL( SCIPchgVarUbDive(scip, allvars[i], solval) );
1673  }
1674  }
1675  for( i = 0; i < ndiscvars; ++i )
1676  {
1677  assert( SCIPisFeasEQ(scip, SCIPgetVarLbDive(scip, allvars[i]), SCIPgetVarUbDive(scip, allvars[i])) );
1678  }
1679  /* solve LP */
1680  SCIPdebugMessage(" -> old LP iterations: %"SCIP_LONGINT_FORMAT"\n", SCIPgetNLPIterations(scip));
1681 
1682  /* Errors in the LP solver should not kill the overall solving process, if the LP is just needed for a heuristic.
1683  * Hence in optimized mode, the return code is caught and a warning is printed, only in debug mode, SCIP will stop.
1684  */
1685 #ifdef NDEBUG
1686  retstat = SCIPsolveDiveLP(scip, -1, &lperror, NULL);
1687  if( retstat != SCIP_OKAY )
1688  {
1689  SCIPwarningMessage(scip, "Error while solving LP in Twoopt heuristic; LP solve terminated with code <%d>\n",retstat);
1690  }
1691 #else
1692  SCIP_CALL( SCIPsolveDiveLP(scip, -1, &lperror, NULL) );
1693 #endif
1694 
1695  SCIPdebugMessage(" -> new LP iterations: %"SCIP_LONGINT_FORMAT"\n", SCIPgetNLPIterations(scip));
1696  SCIPdebugMessage(" -> error=%u, status=%d\n", lperror, SCIPgetLPSolstat(scip));
1697 
1698  /* check if this is a feasible solution */
1699  if( !lperror && SCIPgetLPSolstat(scip) == SCIP_LPSOLSTAT_OPTIMAL )
1700  {
1701  SCIP_Bool success;
1702 
1703  /* copy the current LP solution to the working solution */
1704  SCIP_CALL( SCIPlinkLPSol(scip, worksol) );
1705 
1706  /* check solution for feasibility */
1707 
1708 #ifndef NDEBUG
1709  SCIP_CALL( SCIPtrySol(scip, worksol, FALSE, TRUE, TRUE, TRUE, &success) );
1710 #else
1711  SCIP_CALL( SCIPtrySol(scip, worksol, FALSE, FALSE, FALSE, TRUE, &success) );
1712 #endif
1713  if( success )
1714  {
1715  SCIPdebugMessage("found feasible shifted solution:\n");
1716  SCIPdebug( SCIP_CALL( SCIPprintSol(scip, worksol, NULL, FALSE) ) );
1717  heurdata->lastsolindex = SCIPsolGetIndex(bestsol);
1718  *result = SCIP_FOUNDSOL;
1719 
1720 #ifdef SCIP_STATISTIC
1721  SCIPstatisticMessage("*** Twoopt improved solution found by %10s . \n",
1722  SCIPsolGetHeur(bestsol) != NULL ? SCIPheurGetName(SCIPsolGetHeur(bestsol)) :"Tree");
1723 #endif
1724  }
1725  }
1726 
1727  /* terminate the diving */
1728  SCIP_CALL( SCIPendDive(scip) );
1729  }
1730 
1731  TERMINATE:
1732  SCIPdebugMessage("Termination of Twoopt heuristic\n");
1733  SCIPfreeBufferArray(scip, &activities);
1734  SCIP_CALL( SCIPfreeSol(scip, &worksol) );
1735 
1736  return SCIP_OKAY;
1737 }
1738 
1739 /*
1740  * primal heuristic specific interface methods
1741  */
1742 
1743 /** creates the twoopt primal heuristic and includes it in SCIP */
1745  SCIP* scip /**< SCIP data structure */
1746  )
1747 {
1748  SCIP_HEURDATA* heurdata;
1749  SCIP_HEUR* heur;
1750 
1751  /* create Twoopt primal heuristic data */
1752  SCIP_CALL( SCIPallocMemory(scip, &heurdata) );
1753 
1754  /* include primal heuristic */
1755  SCIP_CALL( SCIPincludeHeurBasic(scip, &heur,
1757  HEUR_MAXDEPTH, HEUR_TIMING, HEUR_USESSUBSCIP, heurExecTwoopt, heurdata) );
1758 
1759  assert(heur != NULL);
1760 
1761  /* set non-NULL pointers to callback methods */
1762  SCIP_CALL( SCIPsetHeurCopy(scip, heur, heurCopyTwoopt) );
1763  SCIP_CALL( SCIPsetHeurFree(scip, heur, heurFreeTwoopt) );
1764  SCIP_CALL( SCIPsetHeurInit(scip, heur, heurInitTwoopt) );
1765  SCIP_CALL( SCIPsetHeurExit(scip, heur, heurExitTwoopt) );
1766  SCIP_CALL( SCIPsetHeurInitsol(scip, heur, heurInitsolTwoopt) );
1767  SCIP_CALL( SCIPsetHeurExitsol(scip, heur, heurExitsolTwoopt) );
1768 
1769  /* include boolean flag intopt */
1770  SCIP_CALL( SCIPaddBoolParam(scip, "heuristics/twoopt/intopt", " Should Integer-2-Optimization be applied or not?",
1771  &heurdata->intopt, TRUE, DEFAULT_INTOPT, NULL, NULL) );
1772 
1773  /* include parameter waitingnodes */
1774  SCIP_CALL( SCIPaddIntParam(scip, "heuristics/twoopt/waitingnodes", "user parameter to determine number of "
1775  "nodes to wait after last best solution before calling heuristic",
1776  &heurdata->waitingnodes, TRUE, DEFAULT_WAITINGNODES, 0, 10000, NULL, NULL));
1777 
1778  /* include parameter maxnslaves */
1779  SCIP_CALL( SCIPaddIntParam(scip, "heuristics/twoopt/maxnslaves", "maximum number of slaves for one master variable",
1780  &heurdata->maxnslaves, TRUE, DEFAULT_MAXNSLAVES, -1, 1000000, NULL, NULL) );
1781 
1782  /* include parameter matchingrate */
1783  SCIP_CALL( SCIPaddRealParam(scip, "heuristics/twoopt/matchingrate",
1784  "parameter to determine the percentage of rows two variables have to share before they are considered equal",
1785  &heurdata->matchingrate, TRUE, DEFAULT_MATCHINGRATE, 0.0, 1.0, NULL, NULL) );
1786 
1787  return SCIP_OKAY;
1788 }
SCIP_RETCODE SCIPsetHeurInitsol(SCIP *scip, SCIP_HEUR *heur, SCIP_DECL_HEURINITSOL((*heurinitsol)))
Definition: scip.c:7078
static SCIP_RETCODE shiftValues(SCIP *scip, SCIP_VAR *master, SCIP_VAR *slave, SCIP_Real mastersolval, DIRECTION masterdir, SCIP_Real slavesolval, DIRECTION slavedir, SCIP_Real shiftval, SCIP_Real *activities, int nrows, SCIP_Bool *feasible)
Definition: heur_twoopt.c:124
SCIP_Bool SCIPisZero(SCIP *scip, SCIP_Real val)
Definition: scip.c:38397
Primal heuristic to improve incumbent solution by flipping pairs of variables.
int SCIPgetNVars(SCIP *scip)
Definition: scip.c:10071
SCIP_HEUR * SCIPsolGetHeur(SCIP_SOL *sol)
Definition: sol.c:2192
const char * SCIPvarGetName(SCIP_VAR *var)
Definition: var.c:15788
SCIP_Real SCIPgetRowSolActivity(SCIP *scip, SCIP_ROW *row, SCIP_SOL *sol)
Definition: scip.c:25961
SCIP_Bool SCIPisInfinity(SCIP *scip, SCIP_Real val)
Definition: scip.c:38360
const char * SCIPheurGetName(SCIP_HEUR *heur)
Definition: heur.c:591
#define SCIPfreeBlockMemoryArray(scip, ptr, num)
Definition: scip.h:19206
static SCIP_DECL_HEURFREE(heurFreeTwoopt)
Definition: heur_twoopt.c:806
SCIP_RETCODE SCIPsetHeurCopy(SCIP *scip, SCIP_HEUR *heur, SCIP_DECL_HEURCOPY((*heurcopy)))
Definition: scip.c:7014
void SCIPsortRealPtrPtrInt(SCIP_Real *realarray, void **ptrarray1, void **ptrarray2, int *intarray, int len)
SCIP_RETCODE SCIPincludeHeurTwoopt(SCIP *scip)
Definition: heur_twoopt.c:1745
void SCIPwarningMessage(SCIP *scip, const char *formatstr,...)
Definition: scip.c:1206
SCIP_Bool SCIPisFeasLT(SCIP *scip, SCIP_Real val1, SCIP_Real val2)
Definition: scip.c:38667
SCIP_Longint SCIPgetNLPIterations(SCIP *scip)
Definition: scip.c:34147
SCIP_VAR ** SCIPgetVars(SCIP *scip)
Definition: scip.c:10026
#define NULL
Definition: lpi_spx.cpp:129
SCIP_Real SCIPvarGetLbLocal(SCIP_VAR *var)
Definition: var.c:16426
SCIP_Real SCIPfeasFloor(SCIP *scip, SCIP_Real val)
Definition: scip.c:38803
SCIP_Real SCIProwGetLhs(SCIP_ROW *row)
Definition: lp.c:18637
SCIP_Real SCIPvarGetUbGlobal(SCIP_VAR *var)
Definition: var.c:16380
SCIP_RETCODE SCIPsetSolVal(SCIP *scip, SCIP_SOL *sol, SCIP_VAR *var, SCIP_Real val)
Definition: scip.c:31639
#define DEFAULT_WAITINGNODES
Definition: heur_twoopt.c:41
SCIP_RETCODE SCIPincludeHeurBasic(SCIP *scip, SCIP_HEUR **heur, const char *name, const char *desc, char dispchar, int priority, int freq, int freqofs, int maxdepth, unsigned int timingmask, SCIP_Bool usessubscip, SCIP_DECL_HEUREXEC((*heurexec)), SCIP_HEURDATA *heurdata)
Definition: scip.c:6969
SCIP_RETCODE SCIPchgVarUbDive(SCIP *scip, SCIP_VAR *var, SCIP_Real newbound)
Definition: scip.c:29095
#define DEFAULT_MAXNSLAVES
Definition: heur_twoopt.c:45
#define DEFAULT_INTOPT
Definition: heur_twoopt.c:40
int SCIProwGetIndex(SCIP_ROW *row)
Definition: lp.c:18706
#define FALSE
Definition: def.h:52
static SCIP_RETCODE optimize(SCIP *scip, SCIP_SOL *worksol, SCIP_VAR **vars, int *blockstart, int *blockend, int nblocks, OPTTYPE opttype, SCIP_Real *activities, int nrows, SCIP_Bool *improvement, SCIP_Bool *varboundserr, SCIP_HEURDATA *heurdata)
Definition: heur_twoopt.c:885
int SCIPgetNBinVars(SCIP *scip)
Definition: scip.c:10116
#define HEUR_FREQ
Definition: heur_twoopt.c:32
#define TRUE
Definition: def.h:51
#define SCIPdebug(x)
Definition: pub_message.h:74
enum SCIP_Retcode SCIP_RETCODE
Definition: type_retcode.h:53
#define SCIPstatisticMessage
Definition: pub_message.h:104
void SCIPcolSort(SCIP_COL *col)
Definition: lp.c:3240
SCIP_Bool SCIPisFeasZero(SCIP *scip, SCIP_Real val)
Definition: scip.c:38743
struct SCIP_HeurData SCIP_HEURDATA
Definition: type_heur.h:44
SCIP_Bool SCIPisFeasIntegral(SCIP *scip, SCIP_Real val)
Definition: scip.c:38779
#define HEUR_FREQOFS
Definition: heur_twoopt.c:33
#define SCIPallocBlockMemoryArray(scip, ptr, num)
Definition: scip.h:19185
SCIP_LPSOLSTAT SCIPgetLPSolstat(SCIP *scip)
Definition: scip.c:24136
#define SCIPdebugMessage
Definition: pub_message.h:77
SCIP_Real SCIPgetSolVal(SCIP *scip, SCIP_SOL *sol, SCIP_VAR *var)
Definition: scip.c:31775
#define SCIPallocBufferArray(scip, ptr, num)
Definition: scip.h:19214
static SCIP_DECL_SORTPTRCOMP(SCIPvarcolComp)
Definition: heur_twoopt.c:263
SCIP_Real SCIPvarGetObj(SCIP_VAR *var)
Definition: var.c:16227
#define HEUR_NAME
Definition: heur_twoopt.c:28
#define HEUR_TIMING
Definition: heur_twoopt.c:36
#define SCIPreallocBufferArray(scip, ptr, num)
Definition: scip.h:19215
SCIP_RETCODE SCIPstartDive(SCIP *scip)
Definition: scip.c:28898
static SCIP_DECL_HEURINITSOL(heurInitsolTwoopt)
Definition: heur_twoopt.c:1347
SCIP_RETCODE SCIPgetLPColsData(SCIP *scip, SCIP_COL ***cols, int *ncols)
Definition: scip.c:24369
Direction
Definition: heur_twoopt.c:108
SCIP_RETCODE SCIPchgVarLbDive(SCIP *scip, SCIP_VAR *var, SCIP_Real newbound)
Definition: scip.c:29063
SCIP_RETCODE SCIPaddBoolParam(SCIP *scip, const char *name, const char *desc, SCIP_Bool *valueptr, SCIP_Bool isadvanced, SCIP_Bool defaultvalue, SCIP_DECL_PARAMCHGD((*paramchgd)), SCIP_PARAMDATA *paramdata)
Definition: scip.c:3388
SCIP_VARSTATUS SCIPvarGetStatus(SCIP_VAR *var)
Definition: var.c:15907
SCIP_RETCODE SCIPaddIntParam(SCIP *scip, const char *name, const char *desc, int *valueptr, SCIP_Bool isadvanced, int defaultvalue, int minvalue, int maxvalue, SCIP_DECL_PARAMCHGD((*paramchgd)), SCIP_PARAMDATA *paramdata)
Definition: scip.c:3414
SCIP_Bool SCIPvarIsIntegral(SCIP_VAR *var)
Definition: var.c:15979
static SCIP_DECL_HEURINIT(heurInitTwoopt)
Definition: heur_twoopt.c:826
static SCIP_DECL_HEUREXIT(heurExitTwoopt)
Definition: heur_twoopt.c:1254
static SCIP_RETCODE presolveTwoOpt(SCIP *scip, SCIP_HEUR *heur, SCIP_HEURDATA *heurdata)
Definition: heur_twoopt.c:705
SCIP_ROW ** SCIPcolGetRows(SCIP_COL *col)
Definition: lp.c:18506
SCIP_Bool SCIPisNegative(SCIP *scip, SCIP_Real val)
Definition: scip.c:38421
#define SCIPallocMemory(scip, ptr)
Definition: scip.h:19159
#define SCIPfreeBufferArray(scip, ptr)
Definition: scip.h:19221
SCIP_Real SCIProwGetRhs(SCIP_ROW *row)
Definition: lp.c:18647
void SCIPsolSetHeur(SCIP_SOL *sol, SCIP_HEUR *heur)
Definition: sol.c:2233
static SCIP_DECL_HEUREXEC(heurExecTwoopt)
Definition: heur_twoopt.c:1444
SCIP_Bool SCIPisFeasEQ(SCIP *scip, SCIP_Real val1, SCIP_Real val2)
Definition: scip.c:38648
SCIP_Bool SCIProwIsLocal(SCIP_ROW *row)
Definition: lp.c:18746
#define SCIPreallocBlockMemoryArray(scip, ptr, oldnum, newnum)
Definition: scip.h:19189
SCIP_COL * SCIPvarGetCol(SCIP_VAR *var)
Definition: var.c:16093
SCIP_RETCODE SCIPgetLPRowsData(SCIP *scip, SCIP_ROW ***rows, int *nrows)
Definition: scip.c:24447
static int varColCompare(SCIP_VAR *var1, SCIP_VAR *var2)
Definition: heur_twoopt.c:220
void SCIPsortPtr(void **ptrarray, SCIP_DECL_SORTPTRCOMP((*ptrcomp)), int len)
#define SCIP_CALL(x)
Definition: def.h:258
SCIP_Bool SCIPhasCurrentNodeLP(SCIP *scip)
Definition: scip.c:24051
SCIP_Real SCIPgetVarLbDive(SCIP *scip, SCIP_VAR *var)
Definition: scip.c:29260
const char * SCIProwGetName(SCIP_ROW *row)
Definition: lp.c:18696
SCIP_Bool SCIPisFeasGT(SCIP *scip, SCIP_Real val1, SCIP_Real val2)
Definition: scip.c:38705
void SCIPheurSetData(SCIP_HEUR *heur, SCIP_HEURDATA *heurdata)
Definition: heur.c:512
SCIP_Real SCIPvarGetUbLocal(SCIP_VAR *var)
Definition: var.c:16436
#define SCIP_Bool
Definition: def.h:49
#define DEFAULT_ARRAYSIZE
Definition: heur_twoopt.c:46
#define HEUR_DESC
Definition: heur_twoopt.c:29
SCIP_Longint SCIPsolGetNodenum(SCIP_SOL *sol)
Definition: sol.c:2172
#define MAX(x, y)
Definition: tclique_def.h:75
SCIP_RETCODE SCIPcreateSolCopy(SCIP *scip, SCIP_SOL **sol, SCIP_SOL *sourcesol)
Definition: scip.c:31124
static SCIP_RETCODE innerPresolve(SCIP *scip, SCIP_VAR **vars, SCIP_VAR ***varspointer, int nvars, int *nblocks, int *maxblocksize, int *nblockvars, int **blockstart, int **blockend, SCIP_HEUR *heur, SCIP_HEURDATA *heurdata)
Definition: heur_twoopt.c:607
enum Direction DIRECTION
Definition: heur_twoopt.c:114
Opttype
Definition: heur_twoopt.c:101
SCIP_RETCODE SCIPsetHeurExitsol(SCIP *scip, SCIP_HEUR *heur, SCIP_DECL_HEUREXITSOL((*heurexitsol)))
Definition: scip.c:7094
int SCIPsolGetIndex(SCIP_SOL *sol)
Definition: sol.c:2223
SCIP_RETCODE SCIPlinkLPSol(SCIP *scip, SCIP_SOL *sol)
Definition: scip.c:31444
SCIP_Bool SCIPsolIsOriginal(SCIP_SOL *sol)
Definition: sol.c:2119
#define DEFAULT_MATCHINGRATE
Definition: heur_twoopt.c:42
SCIP_RETCODE SCIPsetHeurExit(SCIP *scip, SCIP_HEUR *heur, SCIP_DECL_HEUREXIT((*heurexit)))
Definition: scip.c:7062
int SCIPgetRandomInt(int minrandval, int maxrandval, unsigned int *seedp)
Definition: misc.c:7212
SCIP_RETCODE SCIPsetHeurInit(SCIP *scip, SCIP_HEUR *heur, SCIP_DECL_HEURINIT((*heurinit)))
Definition: scip.c:7046
enum Opttype OPTTYPE
Definition: heur_twoopt.c:106
SCIP_VARTYPE SCIPvarGetType(SCIP_VAR *var)
Definition: var.c:15953
static SCIP_DECL_HEURCOPY(heurCopyTwoopt)
Definition: heur_twoopt.c:792
#define SCIPfreeMemory(scip, ptr)
Definition: scip.h:19176
SCIP_Real SCIPvarGetLbGlobal(SCIP_VAR *var)
Definition: var.c:16370
#define HEUR_MAXDEPTH
Definition: heur_twoopt.c:34
static void disposeVariable(SCIP_VAR **vars, int *blockend, int varindex)
Definition: heur_twoopt.c:591
SCIP_RETCODE SCIPendDive(SCIP *scip)
Definition: scip.c:28941
int SCIPgetNIntVars(SCIP *scip)
Definition: scip.c:10161
SCIP_Bool SCIPisFeasLE(SCIP *scip, SCIP_Real val1, SCIP_Real val2)
Definition: scip.c:38686
SCIP_RETCODE SCIPsetHeurFree(SCIP *scip, SCIP_HEUR *heur, SCIP_DECL_HEURFREE((*heurfree)))
Definition: scip.c:7030
#define SCIP_Real
Definition: def.h:123
#define HEUR_PRIORITY
Definition: heur_twoopt.c:31
#define MIN(x, y)
Definition: memory.c:59
SCIP_RETCODE SCIPprintRow(SCIP *scip, SCIP_ROW *row, FILE *file)
Definition: scip.c:26010
SCIP_Bool SCIPisFeasGE(SCIP *scip, SCIP_Real val1, SCIP_Real val2)
Definition: scip.c:38724
#define HEUR_USESSUBSCIP
Definition: heur_twoopt.c:37
#define SCIPduplicateBlockMemoryArray(scip, ptr, source, num)
Definition: scip.h:19198
int SCIProwGetLPPos(SCIP_ROW *row)
Definition: lp.c:18826
SCIP_HEURDATA * SCIPheurGetData(SCIP_HEUR *heur)
Definition: heur.c:502
SCIP_RETCODE SCIPgetVarsData(SCIP *scip, SCIP_VAR ***vars, int *nvars, int *nbinvars, int *nintvars, int *nimplvars, int *ncontvars)
Definition: scip.c:9945
SCIP_Bool SCIPisPositive(SCIP *scip, SCIP_Real val)
Definition: scip.c:38409
SCIP_RETCODE SCIPsolveDiveLP(SCIP *scip, int itlim, SCIP_Bool *lperror, SCIP_Bool *cutoff)
Definition: scip.c:29322
SCIP_SOL * SCIPgetBestSol(SCIP *scip)
Definition: scip.c:32531
SCIP_Real * SCIPcolGetVals(SCIP_COL *col)
Definition: lp.c:18516
SCIP_RETCODE SCIPaddRealParam(SCIP *scip, const char *name, const char *desc, SCIP_Real *valueptr, SCIP_Bool isadvanced, SCIP_Real defaultvalue, SCIP_Real minvalue, SCIP_Real maxvalue, SCIP_DECL_PARAMCHGD((*paramchgd)), SCIP_PARAMDATA *paramdata)
Definition: scip.c:3470
int SCIPcolGetNNonz(SCIP_COL *col)
Definition: lp.c:18481
#define HEUR_DISPCHAR
Definition: heur_twoopt.c:30
static SCIP_DECL_HEUREXITSOL(heurExitsolTwoopt)
Definition: heur_twoopt.c:1380
SCIP_Real SCIPgetVarUbDive(SCIP *scip, SCIP_VAR *var)
Definition: scip.c:29289
int SCIPgetNLPRows(SCIP *scip)
Definition: scip.c:24503
SCIP_RETCODE SCIPtrySol(SCIP *scip, SCIP_SOL *sol, SCIP_Bool printreason, SCIP_Bool checkbounds, SCIP_Bool checkintegrality, SCIP_Bool checklprows, SCIP_Bool *stored)
Definition: scip.c:32978
static SCIP_Bool checkConstraintMatching(SCIP *scip, SCIP_VAR *var1, SCIP_VAR *var2, SCIP_Real matchingrate)
Definition: heur_twoopt.c:272
SCIP_Longint SCIPgetNNodes(SCIP *scip)
Definition: scip.c:34065
SCIP_RETCODE SCIPprintSol(SCIP *scip, SCIP_SOL *sol, FILE *file, SCIP_Bool printzeros)
Definition: scip.c:32161
SCIP_RETCODE SCIPfreeSol(SCIP *scip, SCIP_SOL **sol)
Definition: scip.c:31403
static SCIP_Real determineBound(SCIP *scip, SCIP_SOL *sol, SCIP_VAR *master, DIRECTION masterdirection, SCIP_VAR *slave, DIRECTION slavedirection, SCIP_Real *activities, int nrows)
Definition: heur_twoopt.c:364