Open
Graph Drawing
Framework

 v. 2020.02 (Catalpa)
 

LPRelaxationSER.h
Go to the documentation of this file.
1 
32 #pragma once
33 
34 #include <ogdf/external/coin.h>
38 
39 #include <coin/CoinPackedMatrix.hpp>
40 
41 //#define OGDF_STEINERTREE_LPRELAXATIONSER_LOGGING
42 //#define OGDF_STEINERTREE_LPRELAXATIONSER_OUTPUT_LP
43 #define OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_CONNECTED_COMPONENTS // this is faster
44 #define OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_YVAR_CONSTRAINTS // if not defined: generate all yvar constraints in the beginning
45 
46 namespace ogdf {
47 namespace steiner_tree {
48 
51 template<typename T>
53 {
58 
59  OsiSolverInterface *m_osiSolver;
60  CoinPackedMatrix *m_matrix;
61  double *m_objective;
62  double *m_lowerBounds;
63  double *m_upperBounds;
64 
65  const T m_upperBound;
67 #ifdef OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_CONNECTED_COMPONENTS
69 #endif
70 
71  const double m_eps;
72 
74  void generateProblem();
78  bool addSubsetCoverConstraint(const ArrayBuffer<node> &subset);
80  void addYConstraint(const node t);
81 
84  bool separateConnected(const ArrayBuffer<int> &activeComponents);
85 
88  bool separateMinCut(const ArrayBuffer<int> &activeComponents);
89 
92  bool separateCycles(const ArrayBuffer<int> &activeComponents);
93 
96  bool separate();
97 
100  double generateMinCutSeparationGraph(const ArrayBuffer<int> &activeComponents,
101  node &source, node &target,
102  GraphCopy &G,
103  EdgeArray<double> &capacity,
104  int &cutsFound)
105  {
106  G.createEmpty(m_G);
107  capacity.init(G);
108  source = G.newNode();
109  for (node t : m_terminals) { // generate all terminals
110  G.newNode(t);
111  }
112  target = G.newNode();
113  for (int j = 0; j < activeComponents.size(); ++j) {
114  const int i = activeComponents[j];
115  const double cap = m_fullCompStore.extra(i);
116  const Array<node> &terminals = m_fullCompStore.terminals(i);
117  // take the first terminal as root
118  // XXX: we may generate parallel edges but it's ok
119  const auto it0 = terminals.begin();
120  const node rC = G.copy(*it0);
121  capacity[G.newEdge(source, rC)] = cap;
122  if (terminals.size() > 2) {
123  const node v = G.newNode();
124  capacity[G.newEdge(rC, v)] = cap;
125  for (auto it = it0 + 1; it != terminals.end(); ++it) {
126  const node w = G.copy(*it);
127  capacity[G.newEdge(v, w)] = cap;
128  }
129  } else { // exactly two terminals: we do not need the inner Steiner node
130  capacity[G.newEdge(rC, G.copy(*terminals.rbegin()))] = cap;
131  }
132  }
133  double y_R = 0;
134  // TODO: perhaps better to compute y_v before
135  // add edges to target and compute y_R
136  for (node t : m_terminals) {
137  const node v = G.copy(t);
138  OGDF_ASSERT(v);
139  // compute y_v, simply the sum of all x_C where C contains v and then - 1
140  double y_v(-1);
141  for (adjEntry adj : v->adjEntries) {
142  if (adj->twinNode() != source) {
143  y_v += capacity[adj->theEdge()];
144  }
145  }
146 
147 #ifdef OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_YVAR_CONSTRAINTS
148  if (y_v < -m_eps) {
149  addYConstraint(t);
150  ++cutsFound;
151  }
152  else
153 #endif
154  if (y_v > 0) {
155  capacity[G.newEdge(v, target)] = y_v;
156  y_R += y_v;
157  }
158  }
159 #if 0
160  // just for output of blow-up graph
161  for (edge e : G.edges) {
162  if (G.original(e->source())) {
163  std::cout << " T:" << G.original(e->source());
164  } else {
165  std::cout << " " << e->source();
166  }
167  std::cout << " -> ";
168  if (G.original(e->target())) {
169  std::cout << "T:" << G.original(e->target());
170  } else {
171  std::cout << e->target();
172  }
173  std::cout << " " << capacity[e] << "\n";
174  }
175 #endif
176 
177  return y_R;
178  }
179 
180 public:
191  LPRelaxationSER(const EdgeWeightedGraph<T> &G, const List<node> &terminals, const NodeArray<bool> &isTerminal,
193  T upperBound = 0, int cliqueSize = 0, double eps = 1e-8)
194  : m_G(G)
195  , m_isTerminal(isTerminal)
196  , m_terminals(terminals)
197  , m_fullCompStore(fullCompStore)
198  , m_osiSolver(CoinManager::createCorrectOsiSolverInterface())
199  , m_matrix(new CoinPackedMatrix)
200  , m_objective(new double[m_fullCompStore.size()])
201  , m_lowerBounds(new double[m_fullCompStore.size()])
202  , m_upperBounds(new double[m_fullCompStore.size()])
203  , m_upperBound(upperBound)
204  , m_separateCliqueSize(cliqueSize)
206  , m_separationStage(0)
207 #endif
208  , m_eps(eps)
209  {
210  generateProblem();
212 
213 #ifndef OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_YVAR_CONSTRAINTS
214  for (node t : m_terminals) {
215  addYConstraint(t);
216  }
217 #endif
218  }
219 
221  {
222  delete[] m_objective;
223  delete m_matrix;
224  delete[] m_lowerBounds;
225  delete[] m_upperBounds;
226  delete m_osiSolver;
227  }
228 
231  bool solve();
232 };
233 
234 template<typename T>
235 void
237 {
238  const int n = m_fullCompStore.size();
239 
240  m_matrix->setDimensions(0, n);
241  for (int i = 0; i < n; ++i) {
242  m_lowerBounds[i] = 0;
243  m_upperBounds[i] = 1;
244  }
245  for (int i = 0; i < n; ++i) {
247  }
248  m_osiSolver->loadProblem(*m_matrix, m_lowerBounds, m_upperBounds, m_objective, nullptr, nullptr);
249 
250  if (m_upperBound > 0) { // add upper bound
251  CoinPackedVector row;
252  row.setFull(m_fullCompStore.size(), m_objective);
253  m_osiSolver->addRow(row, 0, m_upperBound);
254  }
255 }
256 
257 template<typename T>
258 void
260 {
261  CoinPackedVector row;
262 
263  for (int i = 0; i < m_fullCompStore.size(); ++i) {
264  if (m_fullCompStore.isTerminal(i, t)) { // component spans terminal
265  row.insert(i, 1);
266  }
267  }
268 
269  m_osiSolver->addRow(row, 1, m_osiSolver->getInfinity());
270 }
271 
272 // add constraint if necessary and return if necessary
273 template<typename T>
274 bool
276 {
277  CoinPackedVector row;
278  double test = 0;
279 
280  for (int i = 0; i < m_fullCompStore.size(); ++i) {
281  // compute the intersection cardinality (linear time because terminal sets are sorted by index)
282  int intersectionCard = 0;
283  auto terminals = m_fullCompStore.terminals(i);
284  node *it1 = terminals.begin();
285  auto it2 = subset.begin();
286  while (it1 != terminals.end()
287  && it2 != subset.end()) {
288  if ((*it1)->index() < (*it2)->index()) {
289  ++it1;
290  } else
291  if ((*it1)->index() > (*it2)->index()) {
292  ++it2;
293  } else { // ==
294  ++intersectionCard;
295  ++it1;
296  ++it2;
297  }
298  }
299  // and use it as a coefficient
300  if (intersectionCard > 1) {
301  row.insert(i, intersectionCard - 1);
302  test += (intersectionCard - 1) * m_fullCompStore.extra(i);
303  }
304  }
305  if (test > subset.size() - 1) {
306  m_osiSolver->addRow(row, 0, subset.size() - 1);
307  return true;
308  }
309  return false;
310 }
311 
312 template<typename T>
313 void
315 {
316  // we use the sum over all components C of (|C| - 1) * x_C = |R| - 1 constraint
317  // from the paper
318  CoinPackedVector row;
319 
320  for (int i = 0; i < m_fullCompStore.size(); ++i) {
321  row.insert(i, m_fullCompStore.terminals(i).size() - 1);
322  }
323 
324  int value = m_terminals.size() - 1;
325  m_osiSolver->addRow(row, value, value);
326 }
327 
328 template<typename T>
329 bool
331 {
332  bool initialIteration = true;
333 
334  do {
335  if (initialIteration) {
336  m_osiSolver->initialSolve();
337 #ifdef OGDF_STEINERTREE_LPRELAXATIONSER_LOGGING
338  std::cout << "Objective value " << m_osiSolver->getObjValue() << " of initial solution." << std::endl;
339 #endif
340  initialIteration = false;
341  } else {
342  m_osiSolver->resolve();
343 #ifdef OGDF_STEINERTREE_LPRELAXATIONSER_LOGGING
344  std::cout << "Objective value " << m_osiSolver->getObjValue() << " after resolve." << std::endl;
345 #endif
346  }
347 
348  if (!m_osiSolver->isProvenOptimal()) {
349  if (m_upperBound > 0) { // failed due to better upper bound
350  return false;
351  } else { // failed due to infeasibility
352  std::cerr << "Failed to optimize LP!" << std::endl;
353  throw(-1);
354  }
355  }
356  } while (separate());
357 
358  const double *constSol = m_osiSolver->getColSolution();
359  const int numberOfColumns = m_osiSolver->getNumCols();
360 
361  for (int i = 0; i < numberOfColumns; ++i) {
362  m_fullCompStore.extra(i) = constSol[i];
363  }
364 
365 #ifdef OGDF_STEINERTREE_LPRELAXATIONSER_OUTPUT_LP
366  m_osiSolver->writeLp(stderr);
367 #endif
368 
369  return true;
370 }
371 
372 template<typename T>
373 bool
375 {
376  const double *constSol = m_osiSolver->getColSolution();
377 
378  ArrayBuffer<int> activeComponents;
379  for (int i = 0; i < m_fullCompStore.size(); ++i) {
380  m_fullCompStore.extra(i) = constSol[i];
381  if (m_fullCompStore.extra(i) > m_eps) {
382  activeComponents.push(i);
383  }
384  }
385 
386 #ifdef OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_CONNECTED_COMPONENTS
387  if (!m_separationStage) {
388  if (separateConnected(activeComponents)) {
389  return true;
390  }
391  m_separationStage = 1;
392  }
393 #endif
394  if (separateMinCut(activeComponents)) {
395  return true;
396  }
397  return m_separateCliqueSize > 2 ? separateCycles(activeComponents) : false;
398 }
399 
400 template<typename T>
401 bool
403 {
404  NodeArray<int> setID(m_G, -1); // XXX: NodeArray over terminals only would be better
405  DisjointSets<> uf(m_terminals.size());
406  for (node t : m_terminals) {
407  setID[t] = uf.makeSet();
408  }
409 
410  // union all nodes within one component
411  for (int j = 0; j < activeComponents.size(); ++j) {
412  auto terminals = m_fullCompStore.terminals(activeComponents[j]);
413  auto it = terminals.begin();
414  const int s1 = setID[*it];
415  for (++it; it != terminals.end(); ++it) {
416  uf.link(uf.find(s1), uf.find(setID[*it]));
417  }
418  }
419 
420  if (uf.getNumberOfSets() == 1) { // solution is connected
421  return false;
422  }
423 
424  Array<ArrayBuffer<node>> components(m_terminals.size());
425  ArrayBuffer<int> usedComp;
426  for (node t : m_terminals) {
427  const int k = uf.find(setID[t]);
428  if (components[k].empty()) {
429  usedComp.push(k);
430  }
431  components[k].push(t);
432  }
433  int cutsFound = 0;
434  for (const int k : usedComp) {
435  cutsFound += addSubsetCoverConstraint(components[k]);
436  }
437  return true;
438 }
439 
440 template<typename T>
441 bool
443 {
444  int cutsFound = 0;
445  node source;
446  node pseudotarget;
447  GraphCopy auxG;
448  EdgeArray<double> capacity;
449  double y_R = generateMinCutSeparationGraph(activeComponents, source, pseudotarget, auxG, capacity, cutsFound);
450 
451 #ifdef OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_YVAR_CONSTRAINTS
452  if (cutsFound > 0) {
453  return true;
454  }
455 #endif
456 
457  node target = auxG.newNode();
458  capacity[auxG.newEdge(pseudotarget, target)] = y_R;
459 
460  EdgeArray<double> flow;
462  MinSTCutMaxFlow<double> minSTCut;
463  for (node t : m_terminals) {
464  const node v = auxG.copy(t);
465 
466  edge v_to_target = auxG.newEdge(v, target);
467  capacity[v_to_target] = std::numeric_limits<double>::max(); // XXX: smaller is better
468 
469  maxFlow.init(auxG, &flow);
470 
471  const double cutVal = maxFlow.computeValue(capacity, source, target);
472  if (cutVal - y_R < 1 - m_eps) {
473  minSTCut.call(auxG, capacity, flow, source, target);
474  ArrayBuffer<node> subset;
475  for (node tOrig : m_terminals) {
476  const node tCopy = auxG.copy(tOrig);
477  if (tCopy && minSTCut.isInBackCut(tCopy)) {
478  subset.push(tOrig);
479  }
480  }
481 
482  cutsFound += addSubsetCoverConstraint(subset);
483  }
484 
485  auxG.delEdge(v_to_target);
486  }
487  return cutsFound != 0;
488 }
489 
490 template<typename T>
491 bool
493 {
494  int count = 0;
495 
496  // generate auxiliary graph
497  Graph G;
498  NodeArray<int> id(G);
499  for (int i : activeComponents) {
500  id[G.newNode()] = i;
501  }
502  for (node u1 : G.nodes) {
503  const int i1 = id[u1];
504  const Array<node> &terminals1 = m_fullCompStore.terminals(i1);
505  for (node u2 = u1->succ(); u2; u2 = u2->succ()) {
506  const int i2 = id[u2];
507  const Array<node> &terminals2 = m_fullCompStore.terminals(i2);
508  // compute intersection cardinality (linear time because terminal sets are sorted by index)
509  int intersectionCard = 0;
510  const node *it1 = terminals1.begin();
511  const node *it2 = terminals2.begin();
512  while (it1 != terminals1.end()
513  && it2 != terminals2.end()) {
514  if ((*it1)->index() < (*it2)->index()) {
515  ++it1;
516  } else
517  if ((*it1)->index() > (*it2)->index()) {
518  ++it2;
519  } else { // ==
520  ++intersectionCard;
521  if (intersectionCard == 2) {
522  G.newEdge(u1, u2);
523  break;
524  }
525  ++it1;
526  ++it2;
527  }
528  }
529  }
530  }
531 
532  if (G.numberOfEdges() == 0) {
533  return false;
534  }
535 
536  // now find cliques
538  for (node v : G.nodes) {
539  int idx = v->degree();
540  if (idx == 0) { // ignore isolated nodes
541  continue;
542  }
543  if (idx >= m_separateCliqueSize) {
544  idx = m_separateCliqueSize - 1;
545  }
546  --idx;
547  degrees[idx].pushBack(v);
548  }
549  NodeArray<bool> test(G, false);
550  for (int k = degrees.size(); k >= 2; --k) {
551  degrees[k-2].conc(degrees[k-1]);
552  if (degrees[k-2].size() >= k) {
553  SubsetEnumerator<node> nodeSubset(degrees[k-2]);
554  for (nodeSubset.begin(k); nodeSubset.valid(); nodeSubset.next()) {
555  int countEdges = (k * (k-1)) / 2;
556  for (int j = 0; j < nodeSubset.size(); ++j) {
557  test[nodeSubset[j]] = true;
558  }
559  for (edge e : G.edges) {
560  if (test[e->source()]
561  && test[e->target()]) {
562  countEdges -= 1;
563  }
564  }
565  OGDF_ASSERT(countEdges >= 0);
566  if (countEdges == 0) {
567  // found clique, add constraint
568  double val(0);
569  CoinPackedVector row;
570 
571  for (int j = 0; j < nodeSubset.size(); ++j) {
572  int i = id[nodeSubset[j]];
573  val += m_fullCompStore.extra(i);
574  row.insert(i, 1);
575  }
576  if (val >= 1 + m_eps) {
577  m_osiSolver->addRow(row, 0, 1);
578  ++count;
579  }
580  }
581  for (int j = 0; j < nodeSubset.size(); ++j) {
582  test[nodeSubset[j]] = false;
583  }
584  }
585  }
586  }
587  return count > 0;
588 }
589 
590 }
591 }
node target() const
Returns the target node of the edge.
Definition: Graph_d.h:328
void addYConstraint(const node t)
Add constraint that the sum of x_C over all components C spanning terminal t is at least 1 to ensure ...
bool separateConnected(const ArrayBuffer< int > &activeComponents)
Separate to ensure that the solution is connected.
edge theEdge() const
Returns the edge associated with this adjacency entry.
Definition: Graph_d.h:96
node copy(node v) const
Returns the node in the graph copy corresponding to v.
Definition: GraphCopy.h:335
node newNode(node vOrig)
Creates a new node in the graph copy with original node vOrig.
Definition: GraphCopy.h:412
void init()
Reinitializes the array. Associates the array with no graph.
Definition: EdgeArray.h:283
Data type for general directed graphs (adjacency list representation).
Definition: Graph_d.h:492
If you use COIN-OR, you should use this class.
Definition: coin.h:42
virtual void init(const Graph &graph, EdgeArray< TCap > *flow=nullptr)
Initialize the problem with a graph and optional flow array. If no flow array is given, a new ("internal") array will be created. If a flow array is given, the algorithm uses this "external" array.
Definition: MaxFlowModule.h:93
int degree() const
Returns the degree of the node (indegree + outdegree).
Definition: Graph_d.h:210
const Array< node > & terminals(int id) const
Returns the list of terminals in the full component with given id.
Min-st-cut algorithm, that calculates the cut via maxflow.
void push(E e)
Puts a new element in the buffer.
Definition: ArrayBuffer.h:102
void createEmpty(const Graph &G)
Associates the graph copy with G, but does not create any nodes or edges.
bool separateCycles(const ArrayBuffer< int > &activeComponents)
Perform the separation algorithm for cycle constraints (to obtain stronger LP solution) ...
An array that keeps track of the number of inserted elements; also usable as an efficient stack...
Definition: Array.h:45
FullComponentWithExtraStore< T, double > & m_fullCompStore
all enumerated full components, with solution
bool valid() const
Checks if the current subset is valid. If not, the subset is either not initialized or all subsets ha...
const NodeArray< bool > & m_isTerminal
iterator begin()
Returns an iterator to the first element.
Definition: ArrayBuffer.h:134
node succ() const
Returns the successor in the list of all nodes.
Definition: Graph_d.h:218
reverse_iterator rbegin()
Returns an reverse iterator to the last element.
Definition: Array.h:328
bool solve()
Solve the LP. The solution will be written to the extra data of the full component store...
bool isTerminal(int id, node t) const
checks if a given node t is a terminal in the full component with given id
edge newEdge(edge eOrig)
Creates a new edge (v,w) with original edge eOrig.
virtual void delEdge(edge e) override
Removes edge e and clears the list of edges corresponding to e&#39;s original edge.
internal::GraphObjectContainer< EdgeElement > edges
The container containing all edge objects.
Definition: Graph_d.h:568
int numberOfEdges() const
Returns the number of edges in the graph.
Definition: Graph_d.h:601
bool separateMinCut(const ArrayBuffer< int > &activeComponents)
Perform the general cut-based separation algorithm.
void begin(int low, int high)
Initializes the SubsetEnumerator to enumerate subsets of cardinalities from low to high...
INDEX size() const
Returns the size (number of elements) of the array.
Definition: Array.h:282
double generateMinCutSeparationGraph(const ArrayBuffer< int > &activeComponents, node &source, node &target, GraphCopy &G, EdgeArray< double > &capacity, int &cutsFound)
Generates an auxiliary multi-graph for separation (during LP solving): directed, with special source ...
Enumerator for k-subsets of a given type.
Definition of the FullComponentStore class template.
Doubly linked lists (maintaining the length of the list).
Definition: List.h:40
edge newEdge(node v, node w)
Creates a new edge (v,w) and returns it.
TCap computeValue(const EdgeArray< TCap > &cap, const node &s, const node &t)
Compute only the value of the flow.
A Union/Find data structure for maintaining disjoint sets.
Definition: DisjointSets.h:81
node twinNode() const
Returns the associated node of the corresponding adjacency entry (shorthand for twin()->theNode()).
Definition: Graph_d.h:108
Class for the representation of edges.
Definition: Graph_d.h:292
Class managing the component-based subtour elimination LP relaxation for the Steiner tree problem and...
Copies of graphs supporting edge splitting.
Definition: GraphCopy.h:249
Class for the representation of nodes.
Definition: Graph_d.h:169
virtual bool call(const Graph &graph, const EdgeArray< TCost > &weight, node s, node t, List< edge > &edgeList, edge e_st=nullptr) override
The actual algorithm call.
INDEX size() const
Returns number of elements in the buffer.
Definition: ArrayBuffer.h:122
const Graph & original() const
Returns a reference to the original graph.
Definition: GraphCopy.h:286
#define OGDF_STEINERTREE_LPRELAXATIONSER_SEPARATE_CONNECTED_COMPONENTS
iterator begin()
Returns an iterator to the first element.
Definition: Array.h:310
bool separate()
Perform all available separation algorithms.
void generateProblem()
Generate the basic LP model.
ExtraDataType & extra(int i)
Returns a reference to the extra data of this full component.
const EdgeWeightedGraph< T > & m_G
iterator end()
Returns an iterator to one past the last element.
Definition: Array.h:319
void next()
Obtains the next subset if possible. The result should be checked using the valid() method...
bool addSubsetCoverConstraint(const ArrayBuffer< node > &subset)
Add subset cover constraints to the LP for a given subset of terminals.
const double m_eps
epsilon for double operations
iterator end()
Returns an iterator to one past the last element.
Definition: ArrayBuffer.h:140
node source() const
Returns the source node of the edge.
Definition: Graph_d.h:326
Definition of ogdf::CoinManager.
bool isInBackCut(const node v) const
Returns whether this node is part of the back cut.
int size() const
Returns the cardinality of the subset.
The namespace for all OGDF objects.
T cost(int i) const
Returns the sum of edge costs of this full component.
const List< node > & m_terminals
List of terminals.
node newNode()
Creates a new node and returns it.
int size() const
Returns the number of full components in the store.
internal::GraphObjectContainer< NodeElement > nodes
The container containing all node objects.
Definition: Graph_d.h:565
void addTerminalCoverConstraint()
Add terminal cover constraints to the LP.
A class that allows to enumerate k-subsets.
LPRelaxationSER(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal, FullComponentWithExtraStore< T, double > &fullCompStore, T upperBound=0, int cliqueSize=0, double eps=1e-8)
Initialize the LP.
Computes a max flow via Preflow-Push (global relabeling and gap relabeling heuristic).
Class for adjacency list elements.
Definition: Graph_d.h:79
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:41
Declaration of min-st-cut algorithms parameterized by max-flow alorithm.
internal::GraphObjectContainer< AdjElement > adjEntries
The container containing all entries in the adjacency list of this node.
Definition: Graph_d.h:200