Open
Graph Drawing
Framework

 v. snapshot-2017-02-16
 

MinSteinerTreeGoemans139.h
Go to the documentation of this file.
1 
33 #pragma once
34 
35 #include <coin/CoinPackedVector.hpp>
36 #include <coin/OsiClpSolverInterface.hpp>
37 #include <ogdf/external/coin.h>
38 #include <ogdf/basic/Math.h>
39 #include <ogdf/basic/Stopwatch.h>
46 
47 #define OGDF_STEINERTREE_GOEMANS139_SEPARATE_CONNECTED_COMPONENTS // this is faster
48 #define OGDF_STEINERTREE_GOEMANS139_SEPARATE_YVAR_CONSTRAINTS // if not defined: generate all yvar constraints in the beginning
49 #define OGDF_STEINERTREE_GOEMANS139_LOSS_ON_METRIC_CLOSURE // faster and better
50 
51 namespace ogdf {
52 
70 template<typename T>
72 {
73 private:
74  class UFCR;
75 
76 protected:
77  int m_restricted;
81  int m_seed;
82 
83 public:
85  : m_restricted(3)
86  , m_use2approx(false)
87  , m_forceAPSP(false)
88  , m_separateCycles(false)
89  , m_seed(1337)
90  {
91  }
92 
94 
99  void setMaxComponentSize(int k)
100  {
101  m_restricted = k;
102  }
103 
108  void setSeed(int seed)
109  {
110  m_seed = seed;
111  }
112 
118  void use2Approximation(bool use2approx = true)
119  {
120  m_use2approx = use2approx;
121  }
122 
129  void forceAPSP(bool force = true)
130  {
131  m_forceAPSP = force;
132  }
133 
138  void separateCycles(bool separateCycles = true)
139  {
140  m_separateCycles = separateCycles;
141  }
142 
143 protected:
152  virtual T computeSteinerTree(
153  const EdgeWeightedGraph<T> &G,
154  const List<node> &terminals,
155  const NodeArray<bool> &isTerminal,
156  EdgeWeightedGraphCopy<T> *&finalSteinerTree) override;
157 };
158 
161 template<typename T>
163 {
169 
172 
173  OsiSolverInterface *m_osiSolver;
174  CoinPackedMatrix *m_matrix;
175  double *m_objective;
176  double *m_lowerBounds;
177  double *m_upperBounds;
178 
180  enum class Approx2State {
181  Off,
182  On,
183  JustUseIt,
184  };
188 #ifdef OGDF_STEINERTREE_GOEMANS139_SEPARATE_CONNECTED_COMPONENTS
190 #endif
191 
192  double m_eps; // epsilon for double operations
193 
194  std::minstd_rand m_rng;
195 
198 
201  {
202  std::minstd_rand &m_rng;
203 
205 
206  /* witness set (for some component and specified K (core edge set))
207  *
208  * W(e) = { e } if e is a core edge
209  * W(e) =
210  * take the path P of loss edges from u to e in the component
211  * add every incident core edge of u
212  * that is: if we root the loss connected component at the terminal,
213  * W(e) = all core edges incident to the subtree below e
214  *
215  * Need fast lookups for:
216  * (1) |W(f)|
217  * (2) all loss edges f such that given core edge e is in W(f)
218  * (3) all loss edges f such that W(f) is a subset of a given basis -> for each e \in B: do (2)
219  *
220  * Data Structures:
221  * - EdgeArray<int> witnessCard with witnessCard[e] = |W(e)|
222  * - NodeArray< List<edge> > witness with witness[v_e] = { f | e \in W(f) }
223  * (Note that core edges are given as nodes.)
224  * Also note that we can save it all much sparser.
225  */
228 
231  void addCore(node e)
232  {
233  m_coreEdges.pushBack(e);
234  }
235 
237  void addWitness(node e, edge f)
238  {
239  ++witnessCard[f];
240  witness[e].pushBack(f);
241  }
242 
245  const List<node> &terminals,
246  EdgeArray<bool> &isInTree)
247  {
248  // Let's do Kruskal's algorithm without weights but on a randomly permuted edge list.
249  // We virtually contract all terminals in the union-find data structure.
250  NodeArray<int> setID(G, -1);
251  isInTree.init(G, false);
252  DisjointSets<> uf(G.numberOfNodes() - terminals.size() + 1);
253 
254  int contractedID = uf.makeSet();
255  OGDF_ASSERT(contractedID >= 0);
256  for (node t : terminals) {
257  setID[t] = contractedID;
258  }
259  for (node v = G.firstNode(); v; v = v->succ()) {
260  if (setID[v] < 0) {
261  setID[v] = uf.makeSet();
262  }
263  }
264 
265  // obtain a random edge permutation
266  List<edge> edgePermutation;
267  for (edge e : G.edges) {
268  edgePermutation.pushBack(e);
269  }
270  edgePermutation.permute(m_rng);
271 
272  // add edges if we do not close a cycle
273  for (edge e : edgePermutation) {
274  const int v = setID[e->source()];
275  const int w = setID[e->target()];
276  if (uf.find(v) != uf.find(w)) {
277  isInTree[e] = true;
278  uf.link(uf.find(v), uf.find(w));
279  }
280  }
281  }
282 
283  public:
284  explicit CoreWitness(std::minstd_rand &rng)
285  : m_rng(rng)
286  {
287  }
288 
296  void init(EdgeWeightedGraphCopy<T> &blowupGraph,
297  EdgeArray<int> &capacity,
298  const List<node> &terminals)
299  {
300  witnessCard.init(blowupGraph, 0);
301  witness.init(blowupGraph);
302 
303  // compute set of core edges
304  EdgeArray<bool> isLossEdge;
305  computeRandomCoreEdges(blowupGraph, terminals, isLossEdge);
306 
307  // add nodes for core edges and be able to map them
308  EdgeArray<node> splitMap(blowupGraph, nullptr);
309  ArrayBuffer<edge> coreEdges;
310  for (edge e = blowupGraph.firstEdge(); e; e = e->succ()) {
311  if (!isLossEdge[e]) {
312  splitMap[e] = blowupGraph.newNode();
313  coreEdges.push(e);
314  }
315  }
316 
317  // traverse losses from all terminals to find witness sets
318  NodeArray<adjEntry> pred(blowupGraph, nullptr);
319  for (node t : terminals) {
320  ArrayBuffer<node> stack;
321  stack.push(t);
322  while (!stack.empty()) {
323  // for each node v "below" an edge e in the traversal:
324  // add all incident core edges vw to W(e)
325  const node v = stack.popRet();
326  for (adjEntry adj : v->adjEntries) {
327  const edge e = adj->theEdge();
328  const node w = adj->twinNode();
329  if (!pred[v] || w != pred[v]->theNode()) { // do not look at backward arcs in the tree
330  if (isLossEdge[e]) {
331  stack.push(w);
332  pred[w] = adj;
333  } else {
334  for (node x = v; pred[x]; x = pred[x]->theNode()) {
335  addWitness(splitMap[e], pred[x]->theEdge());
336  }
337  }
338  }
339  }
340  }
341  }
342 
343  // finally replace core edges by nodes
344  for (edge e : coreEdges) {
345  const T w = blowupGraph.weight(e);
346  const node x = splitMap[e];
347  const int cap = capacity[e];
348  OGDF_ASSERT(x);
349  capacity[blowupGraph.newEdge(e->source(), x, w)] = cap;
350  capacity[blowupGraph.newEdge(x, e->target(), w)] = cap;
351  // the cost of a core edge node is hence the weight of one incident edge; also keep capacity
352  blowupGraph.delEdge(e);
353  addCore(x);
354  }
355  }
356 
358  void makeCopy(const HashArray<edge,edge> &edgeMap)
359  {
360  for (HashConstIterator<edge,edge> pair = edgeMap.begin(); pair.valid(); ++pair) {
361  const edge eO = pair.key();
362  const edge eC = pair.info();
363  const node vO = eO->target();
364  const node vC = eC->target();
365  witnessCard[eC] = witnessCard[eO]; // copy witness cardinality
366  if (vC == vO) { // target is a terminal, so it cannot be a core edge
367  continue;
368  }
369  for (ListIterator<node> it = m_coreEdges.begin(); it.valid(); ++it) {
370  if (*it == vO) { // vO is a core edge
371  m_coreEdges.insertAfter(vC, it); // make vC a core edge
372 
373  // copy witness sets
374  // XXX: do we need this or are witness sets computed after the loop again?!
375  for (edge e : witness[vO]) {
376  witness[vC].pushBack(edgeMap[e]);
377  }
378  break;
379  }
380  }
381  }
382  }
383 
385  const List<node> &core() const
386  {
387  return m_coreEdges;
388  }
389 
392  void delCore(node e)
393  {
394  /* What happens when we remove a core edge?
395  * - loss edges are not affected
396  * - we have to remove a core edge e from W(f) for all f, which means:
397  * for all elements f of witness[v_e], decrease witnessCard[f], then remove witness[v_e]
398  */
399  for (edge f : witness[e]) {
400  --witnessCard[f];
401  }
402  // witness[e] is removed by removing the node from the graph
403  m_coreEdges.removeFirst(e);
404  }
405 
407  int numberOfWitnesses(edge e) const
408  {
409  return witnessCard[e];
410  }
411 
413  const List<edge> &witnessList(node e) const
414  {
415  return witness[e];
416  }
417  };
418 
421  {
422  protected:
423  // To represent Gamma(X) [the set of all components in the blowup graph], we give
424  // - terminals, source and target the component id 0
425  // - all other nodes a component id > 0. Nodes with same id belong to the same component.
426  // Note that this is also fine for 2-components with only one edge, since this
427  // is a core edge and hence a dummy node is inserted.
429  // We also save lists of terminals for each component in the specified array buffer.
431  // To efficiently traverse the found component, we save the edge from the root of the component
433  // Finally a component -> cost array.
435 
436  int maxId; // == the size of the arraybuffers
437 
439  void initializeComponent(edge rootEdge,
440  const EdgeWeightedGraphCopy<T> &blowupGraph,
441  const NodeArray<node> &bgOriginal)
442  {
443  List<node> queue;
444  const node start = rootEdge->target();
445  queue.pushBack(start);
446  componentRootEdge.push(rootEdge);
447  componentTerminals.push(List<node>());
448  List<node> &terms = componentTerminals[maxId];
449  if (!bgOriginal[start]) { // start node is a core edge
450  componentCost.push(blowupGraph.weight(rootEdge));
451  } else {
452  componentCost.push(0);
453  }
454  T &cost = componentCost[maxId];
455  ++maxId;
456  while (!queue.empty()) {
457  const node v = queue.popBackRet();
458  componentId[v] = maxId;
459  for (adjEntry adj : v->adjEntries) {
460  const node w = adj->twinNode();
461  if (componentId[w] < 0) {
462  // count coreEdge cost only once
463  if (bgOriginal[v]) { // v is no core edge
464  cost += blowupGraph.weight(adj->theEdge());
465  }
466  if (blowupGraph.original(w)) { // is terminal?
467  terms.pushBack(w);
468  } else {
469  queue.pushBack(w);
470  }
471  }
472  }
473  }
474  }
475 
476  public:
479  const List<node> &bgTerminals,
480  const std::vector<node> &ignores,
481  const NodeArray<node> &bgOriginal)
482  : componentId(blowupGraph, -1)
483  , maxId(0)
484  {
485  for (node v : ignores) {
486  componentId[v] = 0;
487  }
488 
489  for (node t : bgTerminals) {
490  for (adjEntry rootAdj : t->adjEntries) {
491  const edge rootEdge = rootAdj->theEdge();
492  if (rootEdge->source() != t) {
493  continue;
494  }
495  const node r = rootAdj->twinNode();
496  OGDF_ASSERT(r == rootEdge->target());
497  if (componentId[r] < 0) {
498  initializeComponent(rootEdge, blowupGraph, bgOriginal);
499  }
500  }
501  }
502 
503  // now set terminals to id 0 [XXX: why dont we keep -1?]
504  for (node t : bgTerminals) {
505  componentId[t] = 0;
506  }
507  }
508 
510  const List<node> &terminals(int id) const
511  {
512  OGDF_ASSERT(id > 0);
513  return componentTerminals[id-1];
514  }
515 
517  int id(node v) const
518  {
519  return componentId[v];
520  }
521 
523  const T &cost(int id) const
524  {
525  OGDF_ASSERT(id > 0);
526  return componentCost[id-1];
527  }
528 
530  int size() const
531  {
532  return maxId;
533  }
534 
536  edge rootEdge(int id) const
537  {
538  OGDF_ASSERT(id > 0);
539  return componentRootEdge[id-1];
540  }
541 
543  void setRootEdge(int id, edge e) // beware of using!
544  {
545  OGDF_ASSERT(id > 0);
546  componentRootEdge[id-1] = e;
547  OGDF_ASSERT(componentTerminals[id-1].search(e->source()).valid());
548  }
549  };
550 
553 
555  void findFull2Components(SubsetEnumerator<node> &terminalSubset);
557  void findFull3Components(SubsetEnumerator<node> &terminalSubset);
559  void findFullComponents();
560 
563  {
564  for (edge e : graph.edges) {
565  const node u = graph.original(e->source());
566  const node v = graph.original(e->target());
567  if (m_predAPSP[u][v] == nullptr) {
568  return false;
569  }
570  }
571  for (node v : graph.nodes) {
572  if (m_isTerminal[graph.original(v)] // is a terminal
573  && v->degree() > 1) { // but not a leaf
574  return false;
575  }
576  }
577  return true;
578  }
579 
583 
585  void generateProblem(bool perturb = false);
587  void generateObjective(bool perturb);
589  void addTerminalCoverConstraint();
591  bool addSubsetCoverConstraint(const List<node> &subset);
593  void addYConstraint(const node t);
594 
597  bool separateConnected(const ArrayBuffer<int> &activeComponents);
598 
601  bool separateMinCut(const ArrayBuffer<int> &activeComponents);
602 
605  bool separateCycles(const ArrayBuffer<int> &activeComponents);
606 
609  bool separate();
610 
613  double generateMinCutSeparationGraph(const ArrayBuffer<int> &activeComponents,
614  node &source, node &target,
615  GraphCopy &G,
616  EdgeArray<double> &capacity,
617  int &cutsFound)
618  {
619  G.createEmpty(m_G);
620  capacity.init(G);
621  source = G.newNode();
622  for (node t : m_terminals) { // generate all terminals
623  G.newNode(t);
624  }
625  target = G.newNode();
626  for (int j = 0; j < activeComponents.size(); ++j) {
627  const int i = activeComponents[j];
628  const double cap = m_fullCompStore.extra(i);
629  const Array<node> &terminals = m_fullCompStore.terminals(i);
630  // take the first terminal as root
631  // XXX: we may generate parallel edges but it's ok
632  const auto it0 = terminals.begin();
633  const node rC = G.copy(*it0);
634  capacity[G.newEdge(source, rC)] = cap;
635  if (terminals.size() > 2) {
636  const node v = G.newNode();
637  capacity[G.newEdge(rC, v)] = cap;
638  for (auto it = it0 + 1; it != terminals.end(); ++it) {
639  const node w = G.copy(*it);
640  capacity[G.newEdge(v, w)] = cap;
641  }
642  } else { // exactly two terminals: we do not need the inner Steiner node
643  capacity[G.newEdge(rC, G.copy(*terminals.rbegin()))] = cap;
644  }
645  }
646  double y_R = 0;
647  // TODO: perhaps better to compute y_v before
648  // add edges to target and compute y_R
649  for (node t : m_terminals) {
650  const node v = G.copy(t);
651  OGDF_ASSERT(v);
652  // compute y_v, simply the sum of all x_C where C contains v and then - 1
653  double y_v(-1);
654  for (adjEntry adj : v->adjEntries) {
655  if (adj->twinNode() != source) {
656  y_v += capacity[adj->theEdge()];
657  }
658  }
659 
660 #ifdef OGDF_STEINERTREE_GOEMANS139_SEPARATE_YVAR_CONSTRAINTS
661  if (y_v < -m_eps) {
662  addYConstraint(t);
663  ++cutsFound;
664  }
665  else
666 #endif
667  if (y_v > 0) {
668  capacity[G.newEdge(v, target)] = y_v;
669  y_R += y_v;
670  }
671  }
672 #if 0
673  // just for output of blow-up graph
674  for (edge e : G.edges) {
675  if (G.original(e->source())) {
676  cout << " T:" << G.original(e->source());
677  } else {
678  cout << " " << e->source();
679  }
680  cout << " -> ";
681  if (G.original(e->target())) {
682  cout << "T:" << G.original(e->target());
683  } else {
684  cout << e->target();
685  }
686  cout << " " << capacity[e] << "\n";
687  }
688 #endif
689 
690  return y_R;
691  }
692 
696 
699  {
700  // XXX: is it faster to do this backwards? (less copying)
701  int k = 0;
702  while (k < m_fullCompStore.size()) {
703  if (m_fullCompStore.extra(k) > m_eps) {
704  ++k;
705  } else {
706  m_fullCompStore.remove(k);
707  }
708  }
709  }
710 
713  {
714  ids.quicksort();
715  for (int i = ids.size() - 1; i >= 0; --i) {
716  m_fullCompStore.remove(ids[i]);
717  }
718  }
719 
721  void addComponent(NodeArray<bool> &isNewTerminal, int id)
722  {
723  m_fullCompStore.foreachNode(id, m_predAPSP, [&](node v) {
724  isNewTerminal[v] = true;
725  });
726  }
727 
730  void preprocess(NodeArray<bool> &isNewTerminal)
731  {
732  Graph H; // a graph where each component is a star
733  NodeArray<int> id(H); // ids each center of the star to the component id
734  NodeArray<node> copy(m_G, nullptr); // ids orig in m_G -> copy in H
735 
736  List<node> centers; // all centers
737  for (int i = 0; i < m_fullCompStore.size(); ++i) {
738  const node center = H.newNode();
739  centers.pushBack(center);
740  id[center] = i;
741 
742  for (node vG : m_fullCompStore.terminals(i)) {
743  node vH = copy[vG];
744  if (!vH) {
745  vH = H.newNode();
746  copy[vG] = vH;
747  }
748  H.newEdge(vH, center); // target is always center
749  }
750  }
751 
752  // find components to be inserted into the steinerTree and insert them
753  ArrayBuffer<int> inactive; // ids of components we insert; we have to remove them from the set of active components afterwards
754  bool changed;
755  do {
756  changed = false;
757  ListIterator<node> it2;
758  for (ListIterator<node> it = centers.begin(); it.valid(); it = it2) {
759  it2 = it.succ();
760  node c = *it;
761  int innerNodes = 0; // count inner nodes
762  for (adjEntry adj : c->adjEntries) {
763  innerNodes += (adj->twinNode()->degree() != 1);
764  }
765  if (innerNodes <= 1) { // this center represents a component to add to steinerTree
766  // insert component into steinerTree
767  addComponent(isNewTerminal, id[c]);
768 
769  // remove center from H (adjacent leaves can remain being isolated nodes)
770  inactive.push(id[c]);
771  H.delNode(c);
772  centers.del(it);
773 
774  changed = true;
775  }
776  }
777  } while (changed);
778 
779  removeComponents(inactive);
780  }
781 
785 
789  NodeArray<node> &bgOriginal,
790  EdgeArray<int> &capacity,
791  node s, node t,
792  const node vC, const node wC,
793  int cap)
794  {
795  if (m_ssspDistances
796  && !m_G.isTerminal(s)) {
797  swap(s, t);
798  OGDF_ASSERT(m_G.isTerminal(s));
799  }
800  node tC = wC;
801  for (edge e = m_predAPSP[s][t]; e; t = e->opposite(t), e = m_predAPSP[s][t]) {
802  const node x = e->opposite(t);
803  node xC = vC;
804  if (x != s) {
805  xC = blowupGraph.newNode();
806  OGDF_ASSERT(!bgOriginal[xC]);
807  bgOriginal[xC] = x;
808  }
809  capacity[blowupGraph.newEdge(xC, tC, m_G.weight(e))] = cap;
810  tC = xC;
811  }
812  }
813 
816  int generateGammoidGraph(node &source, node &target,
817  CoreWitness &cw,
818  EdgeWeightedGraphCopy<T> &blowupGraph,
819  NodeArray<node> &bgOriginal,
820  List<node> &bgTerminals,
821  EdgeArray<int> &capacity,
822  int &y_R) const
823  {
824  List<int> denominators;
825 
826  for (int i = 0; i < m_fullCompStore.size(); ++i) {
827  OGDF_ASSERT(m_fullCompStore.extra(i) <= 1.0 + m_eps);
828  OGDF_ASSERT(m_fullCompStore.extra(i) >= m_eps);
829  int num, denom;
830  Math::getFraction(m_fullCompStore.extra(i), num, denom);
831  OGDF_ASSERT(Math::gcd(num, denom) == 1);
832  denominators.pushBack(denom);
833  }
834  int lcm = 1;
835  for (int denom : denominators) {
836  lcm = Math::lcm(lcm, denom);
837  }
838 
839  blowupGraph.createEmpty(m_G);
840  bgOriginal.init(blowupGraph, nullptr);
841  for (node t : m_terminals) { // generate all terminals
842  const node v = blowupGraph.newNode(t);
843  bgTerminals.pushBack(v);
844  bgOriginal[v] = t;
845  }
846  y_R = 0;
847  List<node> roots;
848  List<int> rootCap;
849  capacity.init(blowupGraph);
850  for (int i = 0; i < m_fullCompStore.size(); ++i) {
851  int cap = int(lcm * m_fullCompStore.extra(i) + m_eps);
852  // do a bfs of the component tree to add *directed* components
853  // with the first terminal as root
854  adjEntry start = m_fullCompStore.start(i);
855  node v = m_fullCompStore.original(start->theNode());
856  roots.pushBack(blowupGraph.copy(v));
857  rootCap.pushBack(cap);
858  List<adjEntry> queueT;
859  List<node> queueC;
860  queueT.pushBack(start);
861  queueC.pushBack(blowupGraph.copy(v));
862  while (!queueT.empty()) {
863  const adjEntry inAdj = queueT.popFrontRet();
864  const node wT = inAdj->twinNode();
865  const node vC = queueC.popFrontRet();
866 
867  const node wO = m_fullCompStore.original(wT);
868  if (m_isTerminal[wO]) {
869 #ifdef OGDF_STEINERTREE_GOEMANS139_LOSS_ON_METRIC_CLOSURE
870  capacity[blowupGraph.newEdge(vC, blowupGraph.copy(wO), m_fullCompStore.graph().weight(inAdj->theEdge()))] = cap;
871 #else
872  insertShortestPathIntoBlowupGraph(blowupGraph, bgOriginal, capacity, m_fullCompStore.original(vT), wO, vC, blowupGraph.copy(wO), cap);
873 #endif
874  } else { // not a terminal
875  const node wC = blowupGraph.newNode();
876  bgOriginal[wC] = wO;
877 #ifdef OGDF_STEINERTREE_GOEMANS139_LOSS_ON_METRIC_CLOSURE
878  capacity[blowupGraph.newEdge(vC, wC, m_fullCompStore.graph().weight(inAdj->theEdge()))] = cap;
879 #else
880  insertShortestPathIntoBlowupGraph(blowupGraph, bgOriginal, capacity, m_fullCompStore.original(vT), wO, vC, wC, cap);
881 #endif
882  const adjEntry back = inAdj->twin();
883  for (adjEntry adj = back->cyclicSucc(); adj != back; adj = adj->cyclicSucc()) {
884  queueT.pushBack(adj);
885  queueC.pushBack(wC);
886  }
887  }
888  }
889  }
890 
891  // remove isolated terminals (can exist by preprocessing)
892  ListIterator<node> it2;
893  for (ListIterator<node> it = bgTerminals.begin(); it.valid(); it = it2) {
894  it2 = it.succ();
895  if ((*it)->degree() == 0) {
896  blowupGraph.delNode(*it);
897  bgTerminals.del(it);
898  }
899  }
900 
901  // compute core edges (and replace these edges by nodes)
902  // and witness sets
903  cw.init(blowupGraph, capacity, bgTerminals);
904 
905  // connect source to component roots
906  source = blowupGraph.newNode();
907  while (!roots.empty()) {
908  capacity[blowupGraph.newEdge(source, roots.popFrontRet(), 0)] = rootCap.popFrontRet();
909  }
910 
911  // connect target
912  target = blowupGraph.newNode();
913  for (node v : bgTerminals) {
914  OGDF_ASSERT(v);
915  int y_v = -lcm;
916  // compute y_v, the number of components containing v in the blow up graph - N
917  // NOTE: for the non-blowup variant this is simply the sum of all x_C where C contains v ... - 1
918  for (adjEntry adj : v->adjEntries) {
919  if (adj->twinNode() != source) {
920  y_v += capacity[adj->theEdge()];
921  }
922  }
923  OGDF_ASSERT(y_v >= 0);
924 
925  if (y_v > 0) {
926  capacity[blowupGraph.newEdge(v, target, 0)] = y_v;
927  y_R += y_v;
928  }
929  }
930  return lcm;
931  }
932 
935  EdgeArray<int> &capacity,
936  const node source, const node target) const
937  {
938  MaxFlowGoldbergTarjan<int> maxFlow(blowupGraph);
939  return maxFlow.computeValue(capacity, source, target);
940  }
941 
944  int findComponentAndMaxBasis(List<std::pair<node,int>> *&maxBasis,
945  EdgeWeightedGraphCopy<T> &blowupGraph,
946  const List<node> &bgTerminals,
947  const CoreWitness &cw,
948  EdgeArray<int> &capacity,
949  const BlowupComponents &gamma,
950  const int N,
951  const int y_R,
952  const node source,
953  const node target)
954  {
955  // there should always be saturated flow to the component roots
956  // (contracted matroid)
957  EdgeArray<int> lB(blowupGraph, 0);
958  for (adjEntry adj : source->adjEntries) {
959  const edge e = adj->theEdge();
960  lB[e] = capacity[e];
961  }
962 
963  // compute weights of core edges and add source->core edges
964  List<edge> sourceCoreEdges;
965  EdgeArray<double> cost(blowupGraph, 0);
966  for (ListConstIterator<node> it = cw.core().rbegin(); it.valid(); --it) { // XXX: why backwards?
967  // compute weight of core edge
968  const node v = *it;
969  edge tmp = v->firstAdj()->theEdge();
970  double weight = (double)blowupGraph.weight(tmp);
971  for (edge e : cw.witnessList(v)) {
972  OGDF_ASSERT(cw.numberOfWitnesses(e) > 0);
973  weight += (double)blowupGraph.weight(e) / cw.numberOfWitnesses(e);
974  }
975 
976  // add edges from source to core edges v
977  edge e = blowupGraph.newEdge(source, v, 0);
978  capacity[e] = capacity[tmp];
979  cost[e] = -weight;
980  sourceCoreEdges.pushBack(e);
981  }
982 
983  maxBasis = nullptr;
984  NodeArray<int> supply(blowupGraph, 0);
985  EdgeArray<int> flow(blowupGraph);
987 
988  for (int id = 1; id <= gamma.size(); ++id) {
989  /* We want to find maximum-weight basis B \in B^K_Q
990  * B_Q = minimal edge set to remove after contracting Q to obtain feasible solution (blowup graph)
991  * = bases of gammoid M_Q
992  * B^K_Q = { B \in B_Q | B \subseteq K } [K is the set of core edges]
993  * = bases of gammoid M^K_Q
994  * M^K_Q is gammoid "obtained by restricting M_Q to K"
995  * M_Q = M'_Q / X' (M'_Q contracted by X') is a gammoid
996  * M'_Q = gammoid from X \cup X' to Y in D' with arc-disjointness instead of vertex-disjointness
997  * D' is D like for separation but without source node and with interim node v_e for each edge e
998  * X = inserted nodes v_e in each edge in blowup graph
999  * X' = the (arbitrary) roots of each component
1000  * Y = Q \cup {t}
1001  * that means:
1002  * I (subset of X) is an independent set of M_Q
1003  * <=> (if X' is always an independent set in M'_Q ... which we assume here)
1004  * I \cup X' is an independent set of M'_Q
1005  * Restricting to K means:
1006  * only put v_e in X with e \in K (that is, we only need to *generate* v_e if e \in K)
1007  * Hence:
1008  * - we generate D'^K (this is blowupGraph)
1009  * - compute the max flow from X^K \cup X' to Q \cup {t}
1010  * - ASSERT that X' is "saturated"!
1011  * - check which subset of X is saturated -> these are the nodes representing the edge set we need
1012  */
1013  // add edges from component's terminals to target
1014  List<edge> Q_to_target;
1015  for (node t : gamma.terminals(id)) {
1016  const edge e = blowupGraph.newEdge(t, target, 0);
1017  capacity[e] = N * y_R; // upper bound for capacity
1018  Q_to_target.pushBack(e);
1019  }
1020 
1022 
1023  int rank = gammoidGetRank(blowupGraph, capacity, source, target);
1024  supply[source] = rank;
1025  supply[target] = -rank;
1026 
1027  // find maximum weight basis
1028 #ifdef OGDF_DEBUG
1029  bool feasible = mcf.call(blowupGraph, lB, capacity, cost, supply, flow);
1030  OGDF_ASSERT(feasible);
1031  double minCostVal;
1032  OGDF_ASSERT(mcf.checkComputedFlow(blowupGraph, lB, capacity, cost, supply, flow, minCostVal));
1033 #else
1034  mcf.call(blowupGraph, lB, capacity, cost, supply, flow);
1035 #endif
1036  double weight(0);
1037  for (edge e : sourceCoreEdges) {
1038  if (flow[e] > 0) {
1039  basis->pushBack(std::pair<node,int>(e->target(), flow[e]));
1040  weight -= flow[e] * cost[e];
1041  }
1042  }
1043 
1044  // remove temporary edges for multi-target max-flow again
1045  for (edge e : Q_to_target) {
1046  blowupGraph.delEdge(e);
1047  }
1048  // XXX/TODO: we could also keep target edges from all terminals to the target
1049  // and just change the capacity
1050 
1051  // we choose the component with max cost*N <= weight
1052  if (gamma.cost(id) * N <= weight + m_eps) {
1053  maxBasis = basis;
1054  for (edge e : sourceCoreEdges) { // clean up (XXX: check if necessary)
1055  blowupGraph.delEdge(e);
1056  }
1057  return id;
1058  }
1059  delete basis;
1060  }
1061  return 0; // no component chosen, fail
1062  }
1063 
1066  int findCheapestComponentAndRemainingBasis(List<std::pair<node,int>> *&maxBasis,
1067  const CoreWitness &cw,
1068  EdgeArray<int> &capacity,
1069  const BlowupComponents &gamma)
1070  {
1071  // find cheapest component
1072  int compId = 0;
1073  double cost = 0;
1074  for (int id = 1; id <= gamma.size(); ++id) {
1075  if (gamma.cost(id) > cost) {
1076  cost = gamma.cost(id);
1077  compId = id;
1078  }
1079  }
1080  // use all core edges as basis
1081  maxBasis = new List<std::pair<node,int>>();
1082  for (node v : cw.core()) {
1083  edge tmp = v->lastAdj()->theEdge();
1084  maxBasis->pushBack(std::pair<node,int>(v, capacity[tmp]));
1085  }
1086  return compId;
1087  }
1088 
1090  void addComponent(NodeArray<bool> &isNewTerminal,
1091  const EdgeWeightedGraphCopy<T> &blowupGraph,
1092  const NodeArray<node> &bgOriginal,
1093  const edge rootEdge)
1094  {
1095  OGDF_ASSERT(blowupGraph.original(rootEdge->source()));
1096  List<node> stack;
1097  stack.pushBack(rootEdge->target());
1098  while (!stack.empty()) {
1099  const node v = stack.popBackRet();
1100  if (blowupGraph.original(v)) { // v is terminal
1101  continue;
1102  }
1103  const node vO = bgOriginal[v];
1104  if (vO) {
1105  isNewTerminal[vO] = true;
1106  }
1107  for (adjEntry adj : v->adjEntries) {
1108  const node w = adj->theEdge()->target();
1109  if (v != w) { // outgoing edge
1110  stack.pushBack(w);
1111  }
1112  }
1113  }
1114  }
1115 
1118  EdgeArray<int> &capacity,
1119  CoreWitness &cw,
1120  NodeArray<node> &bgOriginal,
1121  const edge origEdge,
1122  const int origCap, const int copyCap)
1123  {
1124  if (copyCap == 0) {
1125  return;
1126  }
1127  List<edge> todo;
1128  List<node> origin;
1129  HashArray<edge,edge> edgeMap;
1130  todo.pushBack(origEdge);
1131  origin.pushBack(origEdge->source());
1132  while (!todo.empty()) {
1133  edge eO = todo.popFrontRet();
1134  node vC = origin.popFrontRet();
1135  node wO = eO->target();
1136  node wC = wO;
1137  if (!blowupGraph.original(wO)) { // is not a terminal
1138  wC = blowupGraph.newNode();
1139  bgOriginal[wC] = bgOriginal[wO]; // copy
1140  }
1141  edge eC = blowupGraph.newEdge(vC, wC, blowupGraph.weight(eO));
1142  capacity[eC] = copyCap;
1143  capacity[eO] = origCap;
1144  edgeMap[eO] = eC;
1145  if (!blowupGraph.original(wO)) { // is not a terminal
1146  for (adjEntry adj = eO->adjTarget()->cyclicSucc(); adj != eO->adjTarget(); adj = adj->cyclicSucc()) {
1147  OGDF_ASSERT(adj->theEdge()->target() != eO->target()); // outgoing edges
1148  origin.pushBack(wC);
1149  todo.pushBack(adj->theEdge());
1150  }
1151  }
1152  }
1153  cw.makeCopy(edgeMap);
1154  }
1155 
1158  BlowupComponents &gamma,
1159  node v,
1160  const node source,
1161  const node pseudotarget,
1162  const int N)
1163  {
1164  List<node> cleanup;
1165  cleanup.pushBack(v->firstAdj()->twinNode());
1166  cleanup.pushBack(v->lastAdj()->twinNode());
1167  OGDF_ASSERT(v->degree() == 2);
1168  OGDF_ASSERT(v->firstAdj()->twinNode() != v->lastAdj()->twinNode());
1169  blowupGraph.delNode(v);
1170 
1171  while (!cleanup.empty()) {
1172  v = cleanup.popBackRet();
1173  if (!blowupGraph.original(v)) { // is not a terminal
1174  OGDF_ASSERT(v->degree() >= 1);
1175  if (v->degree() == 1) { // v is a pendant node, delete
1176  cleanup.pushBack(v->firstAdj()->twinNode());
1177  blowupGraph.delNode(v);
1178  } else
1179  if (v->indeg() == 0) { // v has no incoming edge, fix
1180  const node w = v->firstAdj()->twinNode();
1181  const edge e = v->firstAdj()->theEdge();
1182  blowupGraph.reverseEdge(e);
1183  OGDF_ASSERT(e->source() == w);
1184  if (!blowupGraph.original(w)) { // is not a terminal
1185  cleanup.pushBack(w);
1186  // when w is cleaned up, it must not go back to v
1187  if (w->firstAdj()->theEdge() == e) {
1188  // move first adjacency entries of w away (w->v is not first anymore)
1189  blowupGraph.moveAdjAfter(w->firstAdj(), w->lastAdj());
1190  }
1191  } else { // w is a terminal
1192  // in this case we have just fixed the direction of the component,
1193  // so w is the new root of the component -> update gamma
1194  gamma.setRootEdge(gamma.id(v), e);
1195  }
1196  }
1197  }
1198  }
1199  }
1200 
1202  void removeFractionalBasisAndCleanup(List<std::pair<node,int>> &basis,
1203  EdgeWeightedGraphCopy<T> &blowupGraph,
1204  NodeArray<node> &bgOriginal,
1205  EdgeArray<int> &capacity,
1206  BlowupComponents &gamma,
1207  CoreWitness &cw,
1208  const node source,
1209  const node pseudotarget,
1210  const int N)
1211  {
1212  // remove B from K (K := K \ B) and from blowup graph (X := X - B)
1213  // and, while at it, remove cleanup edges from blowup graph (X := X - F)
1214  // and fix components that have no incoming edges
1215  List<Prioritized<node, int>> fractionalCoreEdges; // we defer fractional basis elements
1216  for (std::pair<node,int> p : basis) {
1217  const node v = p.first;
1218  const int count = p.second;
1219  OGDF_ASSERT(v->degree() == 2);
1220  int origCap = capacity[v->firstAdj()->theEdge()];
1221  OGDF_ASSERT(count <= origCap);
1222  if (count < origCap) { // only remove a fraction?
1223  fractionalCoreEdges.pushBack(Prioritized<node,int>(v, -count));
1224  } else {
1225  // we are deleting the core edge from the whole component
1226  cw.delCore(v);
1227  removeBasisAndCleanup(blowupGraph, gamma, v, source, pseudotarget, N);
1228  }
1229  }
1230  fractionalCoreEdges.quicksort(); // sort decreasing by flow value
1231  for (Prioritized<node,int> p : fractionalCoreEdges) {
1232  const node v = p.item();
1233  const int count = -p.priority();
1234  OGDF_ASSERT(v->degree() == 2);
1235  int origCap = capacity[v->firstAdj()->theEdge()];
1236  OGDF_ASSERT(count <= origCap);
1237  // copy (split) the component
1238  copyComponent(blowupGraph, capacity, cw, bgOriginal, gamma.rootEdge(gamma.id(v)), count, origCap - count);
1239  // we are deleting the core edge from the whole component
1240  cw.delCore(v);
1241  removeBasisAndCleanup(blowupGraph, gamma, v, source, pseudotarget, N);
1242  }
1243  }
1244 
1247  EdgeArray<int> &capacity,
1248  const node v,
1249  const node source,
1250  const node pseudotarget,
1251  const int N)
1252  {
1253  int delta = 0;
1254  int capSource = 0;
1255  int capTarget = -N;
1256  adjEntry adj2;
1257  for (adjEntry adj = v->firstAdj(); adj; adj = adj2) {
1258  adj2 = adj->succ();
1259  if (adj->twinNode() == source) {
1260  // remove arcs from the source
1261  blowupGraph.delEdge(adj->theEdge());
1262  }
1263  else
1264  if (adj->twinNode() == pseudotarget) {
1265  // remove arcs to the pseudotarget
1266  delta -= capacity[adj->theEdge()];
1267  blowupGraph.delEdge(adj->theEdge());
1268  }
1269  else {
1270  // compute y_v for the contraction node
1271  capTarget += capacity[adj->theEdge()];
1272  // compute s->v capacity
1273  if (v != adj->theEdge()->target()) { // outgoing edge
1274  capSource += capacity[adj->theEdge()];
1275  }
1276  }
1277  }
1278  OGDF_ASSERT(capTarget >= 0);
1279  if (capTarget > 0) {
1280  capacity[blowupGraph.newEdge(v, pseudotarget, 0)] = capTarget;
1281  }
1282  if (capSource > 0) {
1283  capacity[blowupGraph.newEdge(source, v, 0)] = capSource;
1284  }
1285 
1286  return delta + capTarget;
1287  }
1288 
1290  void doGoemansApproximation(NodeArray<bool> &isNewTerminal);
1291 
1293 
1294 public:
1296  UFCR(const EdgeWeightedGraph<T> &G, const List<node> &terminals, const NodeArray<bool> &isTerminal)
1297  : m_G(G)
1298  , m_isTerminal(isTerminal)
1299  , m_terminals(terminals)
1300  , m_nonterminals()
1301  , m_fullCompStore(G, m_terminals, isTerminal)
1302  , m_distance()
1303  , m_predAPSP()
1304  , m_osiSolver(CoinManager::createCorrectOsiSolverInterface())
1305  , m_matrix(nullptr)
1306  , m_objective(nullptr)
1307  , m_lowerBounds(nullptr)
1308  , m_upperBounds(nullptr)
1309  , m_restricted(3)
1310  , m_use2approx(Approx2State::Off)
1311  , m_ssspDistances(true)
1312  , m_separateCycles(false)
1314  , m_separationStage(0)
1315 #endif
1316  , m_eps(1e-8)
1317  , m_approx2SteinerTree(nullptr)
1318  {
1319  steiner_tree::sortTerminals(m_terminals);
1320  }
1321 
1323  {
1324  delete[] m_objective;
1325  delete m_matrix;
1326  delete[] m_lowerBounds;
1327  delete[] m_upperBounds;
1328  delete m_osiSolver;
1329  }
1330 
1332  void init(bool perturb = false)
1333  {
1334  if (m_use2approx != Approx2State::Off) { // add upper bound by 2-approximation
1336  m_approx2Weight = mstT.call(m_G, m_terminals, m_isTerminal, m_approx2SteinerTree, m_G.firstNode());
1337  }
1338 
1339  if (m_restricted > m_terminals.size()) {
1340  m_restricted = m_terminals.size();
1341  }
1342 
1343  for (node u : m_G.nodes) {
1344  if (!m_isTerminal[u]) {
1345  m_nonterminals.pushBack(u);
1346  }
1347  }
1348 
1349  m_distance.init(m_G);
1350  m_predAPSP.init(m_G);
1351  if (m_ssspDistances
1352  && m_restricted <= 3) {
1353  // for 2- and 3-restricted computations, it is ok to use SSSP from all terminals
1354  for (node u : m_terminals) {
1355 #ifndef DETOUR
1356  MinSteinerTreeModule<T>::singleSourceShortestPathsStrict(m_G, u, m_isTerminal, m_distance[u], m_predAPSP[u]);
1357 #else
1358  MinSteinerTreeModule<T>::singleSourceShortestPathsDetour(m_G, u, m_isTerminal, m_distance[u], m_predAPSP[u]);
1359 #endif
1360  }
1361  } else {
1362  m_ssspDistances = false;
1363 #ifndef DETOUR
1364  MinSteinerTreeModule<T>::allPairShortestPathsStrict(m_G, m_isTerminal, m_distance, m_predAPSP);
1365 #else
1366  MinSteinerTreeModule<T>::allPairShortestPathsDetour(m_G, m_nonterminals, m_distance, m_predAPSP);
1367 #endif
1368  }
1369 
1370  // fill m_fullCompStore
1371  findFullComponents();
1372 
1373  generateProblem(perturb);
1374  addTerminalCoverConstraint();
1375 
1376 #ifndef OGDF_STEINERTREE_GOEMANS139_SEPARATE_YVAR_CONSTRAINTS
1377  for (node t : m_terminals) {
1378  addYConstraint(t);
1379  }
1380 #endif
1381  }
1382 
1384  void setMaxComponentSize(int restricted)
1385  {
1386  m_restricted = restricted;
1387  }
1388 
1390  void use2Approximation(bool use2approx)
1391  {
1392  m_use2approx = use2approx ? Approx2State::On : Approx2State::Off;
1393  }
1394 
1396  void addCycleConstraints(bool add = true)
1397  {
1398  m_separateCycles = add;
1399  }
1400 
1402  void forceAPSP(bool force = true)
1403  {
1404  m_ssspDistances = !force;
1405  }
1406 
1408  void solve();
1409 
1411  T getApproximation(EdgeWeightedGraphCopy<T> *&finalSteinerTree, const std::minstd_rand &rng, const bool doPreprocessing = true);
1412 };
1413 
1414 template<typename T>
1415 void
1417 {
1418  node source;
1419  node pseudotarget;
1420  EdgeWeightedGraphCopy<T> blowupGraph;
1421  int y_R;
1422 
1423  CoreWitness cw(m_rng);
1424  EdgeArray<int> capacity;
1425  List<node> bgTerminals;
1426  NodeArray<node> bgOriginal; // original node of a node in blowupGraph (if contracted: just one of it); if nullptr: core edge or special node like source, pseudotarget or target
1427  const int N = generateGammoidGraph(source, pseudotarget, cw, blowupGraph, bgOriginal, bgTerminals, capacity, y_R);
1428  // Since we contract terminal nodes in the blow-up graph, the blowup graph
1429  // needs its own terminal data structures.
1430  // However, we do not need bgIsTerminal[]. We can just exploit the fact that
1431  // blowupGraph is a GraphCopy and the only "copied" nodes are terminals.
1432 
1433  node target = blowupGraph.newNode();
1434  capacity[blowupGraph.newEdge(pseudotarget, target, 0)] = y_R;
1435 
1436  while (bgTerminals.size() > 1) { // T is not a Steiner tree
1437  // TODO: maybe we should initially compute the blowup components when we *build*
1438  // the gammoid graph and update it on each delEdge/delNode
1439  BlowupComponents gamma(blowupGraph, bgTerminals, {source, pseudotarget, target}, bgOriginal); // Gamma(X)
1440 
1441  OGDF_ASSERT(isLoopFree(blowupGraph));
1442 
1443  // take a component Q in Gamma(X)
1444  List<std::pair<node,int>> *maxBasis;
1445  int compId = y_R > 0
1446  ? findComponentAndMaxBasis(maxBasis, blowupGraph, bgTerminals, cw,
1447  capacity, gamma, N, y_R, source, target)
1448  : findCheapestComponentAndRemainingBasis(maxBasis, cw, capacity, gamma);
1449  OGDF_ASSERT(compId);
1450 
1451  // add component Q to T
1452  addComponent(isNewTerminal, blowupGraph, bgOriginal, gamma.rootEdge(compId));
1453 
1454  // remove (maybe fractional) basis and do all the small things necessary for update
1455  removeFractionalBasisAndCleanup(*maxBasis, blowupGraph, bgOriginal, capacity, gamma, cw, source, pseudotarget, N);
1456  delete maxBasis;
1457 
1458  // contract (X := X / Q)
1459  ListConstIterator<node> it0 = gamma.terminals(compId).begin();
1460  node v = *it0;
1461  for (ListConstIterator<node> it = it0.succ(); it.valid(); ++it) {
1462  node t = *it;
1463  if (v->degree() == 0) {
1464  std::swap(v, t);
1465  }
1466  bgTerminals.removeFirst(t);
1467  if (t->degree() > 0) {
1468  v = blowupGraph.contract(blowupGraph.newEdge(v, t, 0));
1469  // the contract method ensures that capacities, weights, and everything is kept
1470  } else { // v->degree() == 0
1471  blowupGraph.delNode(t);
1472  }
1473  }
1474 
1475  if (bgTerminals.size() > 1) {
1476 #if 0
1477  y_R += updateSourceAndTargetArcCapacities(blowupGraph, capacity, v, source, pseudotarget, N);
1478 #endif
1479  // update capacities from source to terminals and terminals to pseudotarget
1480  for (node t : bgTerminals) {
1481  y_R += updateSourceAndTargetArcCapacities(blowupGraph, capacity, t, source, pseudotarget, N);
1482  }
1483  // XXX: doing it for v and all terminals we have met during cleanup would be sufficient
1484  OGDF_ASSERT(target->degree() == 1);
1485  capacity[target->firstAdj()->theEdge()] = y_R;
1486  }
1487  }
1488 }
1489 
1490 template<typename T>
1491 T
1492 MinSteinerTreeGoemans139<T>::UFCR::getApproximation(EdgeWeightedGraphCopy<T> *&finalSteinerTree, const std::minstd_rand &rng, const bool doPreprocessing)
1493 {
1494  if (m_use2approx == Approx2State::JustUseIt) {
1495  // no remaining components
1496  finalSteinerTree = m_approx2SteinerTree;
1497  return m_approx2Weight;
1498  }
1499  m_rng = rng;
1500 
1501  const double *constSol = m_osiSolver->getColSolution();
1502  const int numberOfColumns = m_osiSolver->getNumCols();
1503 
1504  for (int i = 0; i < numberOfColumns; i++) {
1505  m_fullCompStore.extra(i) = constSol[i];
1506  }
1507 
1508  removeInactiveComponents();
1509 
1510  NodeArray<bool> isNewTerminal(m_G, false);
1511  for (node v : m_terminals) {
1512  isNewTerminal[v] = true;
1513  }
1514 
1515  if (doPreprocessing) {
1516  preprocess(isNewTerminal);
1517  }
1518 
1519  if (!m_fullCompStore.isEmpty()) {
1520  doGoemansApproximation(isNewTerminal);
1521  }
1522 
1523  T cost = steiner_tree::obtainFinalSteinerTree(m_G, isNewTerminal, m_isTerminal, finalSteinerTree);
1524  if (m_use2approx != Approx2State::Off) {
1525  if (m_approx2Weight < cost) {
1526  delete finalSteinerTree;
1527  finalSteinerTree = m_approx2SteinerTree;
1528  } else {
1529  delete m_approx2SteinerTree;
1530  }
1531  }
1532 
1533  return cost;
1534 }
1535 
1536 template<typename T>
1537 void
1539 {
1540  int n = m_fullCompStore.size();
1541 
1542  m_matrix = new CoinPackedMatrix;
1543  m_matrix->setDimensions(0, n);
1544 
1545  m_lowerBounds = new double[n];
1546  m_upperBounds = new double[n];
1547  for (int i = 0; i < n; ++i) {
1548  m_lowerBounds[i] = 0;
1549  m_upperBounds[i] = 1;
1550  }
1551 
1552  generateObjective(perturb);
1553  m_osiSolver->loadProblem(*m_matrix, m_lowerBounds, m_upperBounds, m_objective, nullptr, nullptr);
1554 
1555  if (m_use2approx != Approx2State::Off) { // add upper bound by 2-approximation
1556  CoinPackedVector row;
1557  row.setFull(m_fullCompStore.size(), m_objective);
1558  m_osiSolver->addRow(row, 0, m_approx2Weight);
1559  }
1560 }
1561 
1562 template<typename T>
1563 void
1565 {
1566  int n = m_fullCompStore.size();
1567  m_objective = new double[n];
1568 
1569  for (int i = 0; i < n; ++i) {
1570  double w = m_fullCompStore.cost(i);
1571 
1572  if (perturb) {
1573  w += (rand() % 1000)*1e-9;
1574  }
1575 
1576  m_objective[i] = w;
1577  }
1578 }
1579 
1580 template<typename T>
1581 void
1583 {
1584  CoinPackedVector row;
1585 
1586  for (int i = 0; i < m_fullCompStore.size(); ++i) {
1587  if (m_fullCompStore.isTerminal(i, t)) { // component spans terminal
1588  row.insert(i, 1);
1589  }
1590  }
1591 
1592  m_osiSolver->addRow(row, 1, m_osiSolver->getInfinity());
1593 }
1594 
1595 // add constraint if necessary and return if necessary
1596 template<typename T>
1597 bool
1599 {
1600  CoinPackedVector row;
1601  double test = 0;
1602 
1603  for (int i = 0; i < m_fullCompStore.size(); ++i) {
1604  // compute the intersection cardinality (linear time because terminal sets are sorted by index)
1605  int intersectionCard = 0;
1606  auto terminals = m_fullCompStore.terminals(i);
1607  node *it1 = terminals.begin();
1608  auto it2 = subset.begin();
1609  while (it1 != terminals.end()
1610  && it2.valid()) {
1611  if ((*it1)->index() < (*it2)->index()) {
1612  ++it1;
1613  } else
1614  if ((*it1)->index() > (*it2)->index()) {
1615  ++it2;
1616  } else { // ==
1617  ++intersectionCard;
1618  ++it1;
1619  ++it2;
1620  }
1621  }
1622  // and use it as a coefficient
1623  if (intersectionCard > 1) {
1624  row.insert(i, intersectionCard - 1);
1625  test += (intersectionCard - 1) * m_fullCompStore.extra(i);
1626  }
1627  }
1628  if (test > (subset.size() - 1)) {
1629  m_osiSolver->addRow(row, 0, subset.size() - 1);
1630  return true;
1631  }
1632  return false;
1633 }
1634 
1635 template<typename T>
1636 void
1638 {
1639  // we use the sum over all components C of (|C| - 1) * x_C = |R| - 1 constraint
1640  // from the paper
1641  CoinPackedVector row;
1642 
1643  for (int i = 0; i < m_fullCompStore.size(); ++i) {
1644  row.insert(i, m_fullCompStore.terminals(i).size() - 1);
1645  }
1646 
1647  int value = m_terminals.size() - 1;
1648  m_osiSolver->addRow(row, value, value);
1649 }
1650 
1651 template<typename T>
1653 {
1654  // compute special case of 2-components (shortest paths between terminals)
1655  for (terminalSubset.begin(2); terminalSubset.valid(); terminalSubset.next()) {
1656  const node s = terminalSubset[0];
1657  const node t = terminalSubset[1];
1658  if (m_predAPSP[s][t]) {
1659  EdgeWeightedGraphCopy<T> minComp;
1660  minComp.createEmpty(m_G);
1661  minComp.newEdge(minComp.newNode(s), minComp.newNode(t), m_distance[s][t]);
1662  m_fullCompStore.insert(minComp);
1663  }
1664  }
1665 }
1666 
1667 template<typename T>
1669 {
1670  // compute special case of 3-components (3-stars)
1671  for (terminalSubset.begin(3); terminalSubset.valid(); terminalSubset.next()) {
1672  const node t0 = terminalSubset[0];
1673  const node t1 = terminalSubset[1];
1674  const node t2 = terminalSubset[2];
1675  OGDF_ASSERT(m_distance[t0][t1] < numeric_limits<T>::max());
1676  OGDF_ASSERT(m_distance[t0][t2] < numeric_limits<T>::max());
1677  OGDF_ASSERT(m_distance[t1][t2] < numeric_limits<T>::max());
1678  T minCost = // bounded by the sum of the 2-components
1679  min(m_distance[t0][t1] + m_distance[t0][t2],
1680  min(m_distance[t1][t0] + m_distance[t1][t2],
1681  m_distance[t2][t0] + m_distance[t2][t1]));
1682  node minCenter = nullptr;
1683  for (node center : m_nonterminals) {
1684  OGDF_ASSERT(m_distance[t0][center] < numeric_limits<T>::max());
1685  OGDF_ASSERT(m_distance[t1][center] < numeric_limits<T>::max());
1686  OGDF_ASSERT(m_distance[t2][center] < numeric_limits<T>::max());
1687  const T cost = m_distance[t0][center] + m_distance[t1][center] + m_distance[t2][center];
1688  if (cost < minCost) {
1689  minCenter = center;
1690  minCost = cost;
1691  }
1692  }
1693  if (minCenter
1694  && m_predAPSP[t0][minCenter]
1695  && m_predAPSP[t1][minCenter]
1696  && m_predAPSP[t2][minCenter]) {
1697  // create a full 3-component
1698  EdgeWeightedGraphCopy<T> minComp;
1699  minComp.createEmpty(m_G);
1700  node minCenterC = minComp.newNode(minCenter);
1701  minComp.newEdge(minComp.newNode(t0), minCenterC, m_distance[t0][minCenter]);
1702  minComp.newEdge(minComp.newNode(t1), minCenterC, m_distance[t1][minCenter]);
1703  minComp.newEdge(minComp.newNode(t2), minCenterC, m_distance[t2][minCenter]);
1704  m_fullCompStore.insert(minComp);
1705  }
1706  }
1707 }
1708 
1709 template<typename T>
1711 {
1712  SubsetEnumerator<node> terminalSubset(m_terminals);
1713  if (m_restricted >= 4) { // use Dreyfus-Wagner based full component generation
1714  steiner_tree::DreyfusWagnerFullComponentGenerator<T> fcg(m_G, m_terminals, m_distance);
1715  fcg.call(m_restricted);
1716  for (terminalSubset.begin(2, m_restricted); terminalSubset.valid(); terminalSubset.next()) {
1717  EdgeWeightedGraphCopy<T> component;
1718  List<node> terminals;
1719  terminalSubset.list(terminals);
1720  fcg.getSteinerTreeFor(terminals, component);
1721  if (isValidComponent(component)) {
1722  m_fullCompStore.insert(component);
1723  }
1724  }
1725  } else {
1726  findFull2Components(terminalSubset);
1727  if (m_restricted == 3) {
1728  findFull3Components(terminalSubset);
1729  }
1730  }
1731 }
1732 
1733 template<typename T>
1734 void
1736 {
1737  bool initialIteration = true;
1738 
1739  do {
1740  if (initialIteration) {
1741  m_osiSolver->initialSolve();
1742  initialIteration = false;
1743  } else {
1744  m_osiSolver->resolve();
1745  }
1746 
1747  if (!m_osiSolver->isProvenOptimal()) {
1748  // infeasible:
1749  if (m_use2approx != Approx2State::Off) {
1750  m_use2approx = Approx2State::JustUseIt;
1751  break;
1752  } else {
1753  cerr << "Failed to optimize LP!" << endl;
1754  throw(-1);
1755  }
1756  }
1757  } while (separate());
1758 }
1759 
1760 template<typename T>
1761 bool
1763 {
1764  const double *constSol = m_osiSolver->getColSolution();
1765 
1766  ArrayBuffer<int> activeComponents;
1767  for (int i = 0; i < m_fullCompStore.size(); ++i) {
1768  m_fullCompStore.extra(i) = constSol[i];
1769  if (m_fullCompStore.extra(i) > m_eps) {
1770  activeComponents.push(i);
1771  }
1772  }
1773 
1774 #ifdef OGDF_STEINERTREE_GOEMANS139_SEPARATE_CONNECTED_COMPONENTS
1775  if (!m_separationStage) {
1776  if (separateConnected(activeComponents)) {
1777  return true;
1778  }
1779  m_separationStage = 1;
1780  }
1781 #endif
1782  if (separateMinCut(activeComponents)) {
1783  return true;
1784  }
1785  return m_separateCycles && separateCycles(activeComponents);
1786 }
1787 
1788 template<typename T>
1789 bool
1791 {
1792  NodeArray<int> setID(m_G, -1); // XXX: NodeArray over terminals only would be better
1793  DisjointSets<> uf(m_terminals.size());
1794  for (node t : m_terminals) {
1795  setID[t] = uf.makeSet();
1796  }
1797 
1798  // union all nodes within one component
1799  for (int j = 0; j < activeComponents.size(); ++j) {
1800  auto terminals = m_fullCompStore.terminals(activeComponents[j]);
1801  auto it = terminals.begin();
1802  const int s1 = setID[*it];
1803  for (++it; it != terminals.end(); ++it) {
1804  uf.link(uf.find(s1), uf.find(setID[*it]));
1805  }
1806  }
1807 
1808  if (uf.getNumberOfSets() == 1) { // solution is connected
1809  return false;
1810  }
1811 
1812  Array< List<node> > components(m_terminals.size());
1813  List<int> usedComp;
1814  for (node t : m_terminals) {
1815  const int k = uf.find(setID[t]);
1816  if (components[k].empty()) {
1817  usedComp.pushBack(k);
1818  }
1819  components[k].pushBack(t);
1820  }
1821  int cutsFound = 0;
1822  for (ListConstIterator<int> it = usedComp.begin(); it.valid(); ++it) {
1823  const int k = *it;
1824  cutsFound += addSubsetCoverConstraint(components[k]);
1825  }
1826  return true;
1827 }
1828 
1829 template<typename T>
1830 bool
1832 {
1833  int cutsFound = 0;
1834  node source;
1835  node pseudotarget;
1836  GraphCopy auxG;
1837  EdgeArray<double> capacity;
1838  double y_R = generateMinCutSeparationGraph(activeComponents, source, pseudotarget, auxG, capacity, cutsFound);
1839 
1840 #ifdef OGDF_STEINERTREE_GOEMANS139_SEPARATE_YVAR_CONSTRAINTS
1841  if (cutsFound > 0) {
1842  return true;
1843  }
1844 #endif
1845 
1846  node target = auxG.newNode();
1847  capacity[auxG.newEdge(pseudotarget, target)] = y_R;
1848 
1849  EdgeArray<double> flow;
1851  MinSTCutMaxFlow<double> minSTCut;
1852  for (node t : m_terminals) {
1853  const node v = auxG.copy(t);
1854 
1855  edge v_to_target = auxG.newEdge(v, target);
1856  capacity[v_to_target] = numeric_limits<double>::max(); // XXX: smaller is better
1857 
1858  maxFlow.init(auxG, &flow);
1859 
1860  const double cutVal = maxFlow.computeValue(capacity, source, target);
1861  if (cutVal - y_R < 1 - m_eps) {
1862  minSTCut.call(auxG, capacity, flow, source, target);
1863  List<node> subset;
1864  for (node tOrig : m_terminals) {
1865  const node tCopy = auxG.copy(tOrig);
1866  if (tCopy && minSTCut.isInBackCut(tCopy)) {
1867  subset.pushBack(tOrig);
1868  }
1869  }
1870 
1871  cutsFound += addSubsetCoverConstraint(subset);
1872  }
1873 
1874  auxG.delEdge(v_to_target);
1875  }
1876  return cutsFound != 0;
1877 }
1878 
1879 template<typename T>
1880 bool
1882 {
1883  int count = 0;
1884 
1885  // generate auxiliary graph
1886  Graph G;
1887  NodeArray<int> id(G);
1888  for (int i : activeComponents) {
1889  id[G.newNode()] = i;
1890  }
1891  for (node u1 : G.nodes) {
1892  const int i1 = id[u1];
1893  const Array<node> &terminals1 = m_fullCompStore.terminals(i1);
1894  for (node u2 = u1->succ(); u2; u2 = u2->succ()) {
1895  const int i2 = id[u2];
1896  const Array<node> &terminals2 = m_fullCompStore.terminals(i2);
1897  // compute intersection cardinality (linear time because terminal sets are sorted by index)
1898  int intersectionCard = 0;
1899  const node *it1 = terminals1.begin();
1900  const node *it2 = terminals2.begin();
1901  while (it1 != terminals1.end()
1902  && it2 != terminals2.end()) {
1903  if ((*it1)->index() < (*it2)->index()) {
1904  ++it1;
1905  } else
1906  if ((*it1)->index() > (*it2)->index()) {
1907  ++it2;
1908  } else { // ==
1909  ++intersectionCard;
1910  if (intersectionCard == 2) {
1911  G.newEdge(u1, u2);
1912  break;
1913  }
1914  ++it1;
1915  ++it2;
1916  }
1917  }
1918  }
1919  }
1920 
1921  if (G.numberOfEdges() == 0) {
1922  return false;
1923  }
1924 
1925  const int maxClique = m_restricted + 1;
1926  // now find cliques
1927  Array<List<node>> degrees(maxClique);
1928  for (node v : G.nodes) {
1929  int idx = v->degree();
1930  if (idx == 0) { // ignore isolated nodes
1931  continue;
1932  }
1933  if (idx >= maxClique) {
1934  idx = maxClique - 1;
1935  }
1936  --idx;
1937  degrees[idx].pushBack(v);
1938  }
1939  NodeArray<bool> test(G, false);
1940  for (int k = degrees.size(); k >= 2; --k) {
1941  degrees[k-2].conc(degrees[k-1]);
1942  if (degrees[k-2].size() >= k) {
1943  SubsetEnumerator<node> nodeSubset(degrees[k-2]);
1944  for (nodeSubset.begin(k); nodeSubset.valid(); nodeSubset.next()) {
1945  int countEdges = (k * (k-1)) / 2;
1946  for (int j = 0; j < nodeSubset.size(); ++j) {
1947  test[nodeSubset[j]] = true;
1948  }
1949  for (edge e : G.edges) {
1950  if (test[e->source()]
1951  && test[e->target()]) {
1952  countEdges -= 1;
1953  }
1954  }
1955  OGDF_ASSERT(countEdges >= 0);
1956  if (countEdges == 0) {
1957  // found clique, add constraint
1958  double val(0);
1959  CoinPackedVector row;
1960 
1961  for (int j = 0; j < nodeSubset.size(); ++j) {
1962  int i = id[nodeSubset[j]];
1963  val += m_fullCompStore.extra(i);
1964  row.insert(i, 1);
1965  }
1966  if (val >= 1 + m_eps) {
1967  m_osiSolver->addRow(row, 0, 1);
1968  ++count;
1969  }
1970  }
1971  for (int j = 0; j < nodeSubset.size(); ++j) {
1972  test[nodeSubset[j]] = false;
1973  }
1974  }
1975  }
1976  }
1977  return count > 0;
1978 }
1979 
1980 template<typename T>
1982 {
1983  std::minstd_rand rng(m_seed);
1984  UFCR ufcr(G, terminals, isTerminal);
1988  if (m_forceAPSP) {
1989  ufcr.forceAPSP();
1990  }
1991  ufcr.init(false);
1992  ufcr.solve();
1993  return ufcr.getApproximation(finalSteinerTree, rng, true);
1994 }
1995 
1996 } // end namespace
int gammoidGetRank(EdgeWeightedGraphCopy< T > &blowupGraph, EdgeArray< int > &capacity, const node source, const node target) const
Computes the rank of the gammoid (given by the blowup graph)
node target() const
Returns the target node of the edge.
Definition: Graph_d.h:327
const List< node > & core() const
Return list of core edges (implemented by nodes)
EdgeWeightedGraphCopy< T > * m_approx2SteinerTree
static void allPairShortestPathsDetour(const EdgeWeightedGraph< T > &G, const List< node > &nonterminals, NodeArray< NodeArray< T > > &distance, NodeArray< NodeArray< edge > > &pred)
A generator for full components (for Steiner tree approximations) based on the Dreyfus-Wagner algorit...
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:95
bool addSubsetCoverConstraint(const List< node > &subset)
Add subset cover constraints to the LP for a given subset of terminals.
node copy(node v) const
Returns the node in the graph copy corresponding to v.
Definition: GraphCopy.h:336
NodeArray< NodeArray< edge > > m_predAPSP
Declaration of min-cost-flow algorithm (class MinCostFlowReinelt)
node newNode(node vOrig)
Creates a new node in the graph copy with original node vOrig.
Definition: GraphCopy.h:413
void init()
Reinitializes the array. Associates the array with no graph.
Definition: EdgeArray.h:320
iterator pushBack(const E &x)
Adds element x at the end of the list.
Definition: List.h:1316
bool separateMinCut(const ArrayBuffer< int > &activeComponents)
Perform the general cut-based separation algorithm.
Data type for general directed graphs (adjacency list representation).
Definition: Graph_d.h:472
T getSteinerTreeFor(const List< node > &terminals, EdgeWeightedGraphCopy< T > &tree)
Construct a Steiner tree for the given set of terminals.
void preprocess(NodeArray< bool > &isNewTerminal)
Preprocess LP solution.
virtual void delNode(node v)
Removes node v and all incident edges from the graph.
Declaration of stopwatch classes.
void init()
Reinitializes the array. Associates the array with no graph.
Definition: NodeArray.h:292
void forceAPSP(bool force=true)
Force full APSP algorithm even if consecutive SSSP algorithms may work.
void addComponent(NodeArray< bool > &isNewTerminal, int id)
Add a full component to the final solution (by changing nonterminals to terminals) ...
This class serves as an interface for various methods to compute minimum or approximations of minimum...
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
Indexed arrays using hashing for element access.
Definition: HashArray.h:94
int degree() const
Returns the degree of the node (indegree + outdegree).
Definition: Graph_d.h:208
edge newEdge(node u, node v, T weight)
void insertShortestPathIntoBlowupGraph(EdgeWeightedGraphCopy< T > &blowupGraph, NodeArray< node > &bgOriginal, EdgeArray< int > &capacity, node s, node t, const node vC, const node wC, int cap)
Inserts (based on m_distance and m_predAPSP) a shortest path from a component, directed, into the blowupGraph and sets weights and capacity accordingly.
List< node > m_terminals
List of terminals.
int indeg() const
Returns the indegree of the node.
Definition: Graph_d.h:204
iterator begin()
Returns an iterator to the first element of the list.
Definition: List.h:332
const Array< node > & terminals(int id) const
Returns the list of terminals in the full component with given id.
static void sortTerminals(List< node > &terminals)
Sort terminals by index.
Class managing LP and LP-based approximation.
iterator insertAfter(const E &x, iterator it)
Inserts element x after it.
Definition: List.h:1341
int generateGammoidGraph(node &source, node &target, CoreWitness &cw, EdgeWeightedGraphCopy< T > &blowupGraph, NodeArray< node > &bgOriginal, List< node > &bgTerminals, EdgeArray< int > &capacity, int &y_R) const
Generates a special-purpose blowup graph for gammoid computation: directed, with special source and t...
node firstNode() const
Returns the first node in the list of all nodes.
Definition: Graph_d.h:598
Min-st-cut algorithm, that calculates the cut via maxflow.
void push(E e)
Puts a new element in the buffer.
Definition: ArrayBuffer.h:95
bool separate()
Perform all available separation algorithms.
E popBackRet()
Removes the last element from the list and returns it.
Definition: List.h:1373
void createEmpty(const Graph &G)
Associates the graph copy with G, but does not create any nodes or edges.
void findFullComponents()
Find full components.
An array that keeps track of the number of inserted elements; also usable as an efficient stack...
Definition: Array.h:44
List< node > m_nonterminals
List of non-terminals.
bool valid() const
Is the current subset valid? If not, all subsets have already been enumerated.
node succ() const
Returns the successor in the list of all nodes.
Definition: Graph_d.h:216
void quicksort()
Sorts buffer using Quicksort.
Definition: ArrayBuffer.h:281
void init(EdgeWeightedGraphCopy< T > &blowupGraph, EdgeArray< int > &capacity, const List< node > &terminals)
Find a "random" set of core edges and "replace" found edges by nodes, also find the witness sets for ...
int findComponentAndMaxBasis(List< std::pair< node, int >> *&maxBasis, EdgeWeightedGraphCopy< T > &blowupGraph, const List< node > &bgTerminals, const CoreWitness &cw, EdgeArray< int > &capacity, const BlowupComponents &gamma, const int N, const int y_R, const node source, const node target)
Finds the best component and its maximum-weight basis in the given blowup graph with given core and w...
int id(node v) const
Return the component id a given node is contained in.
adjEntry cyclicSucc() const
Returns the cyclic successor in the adjacency list.
Definition: Graph_d.h:278
void removeFractionalBasisAndCleanup(List< std::pair< node, int >> &basis, EdgeWeightedGraphCopy< T > &blowupGraph, NodeArray< node > &bgOriginal, EdgeArray< int > &capacity, BlowupComponents &gamma, CoreWitness &cw, const node source, const node pseudotarget, const int N)
Remove a given basis and cleanup, the basis may be given fractionally.
Augments any data elements of type X with keys of type Priority. This class is also its own Comparer...
Definition: comparer.h:278
Declaration and implementation of Goldberg-Tarjan max-flow algorithm with global relabeling and gap r...
const List< edge > & witnessList(node e) const
Return list of loss edges f in W(e)
ListIteratorBase< E, isConst > succ() const
Returns successor iterator.
Definition: List.h:133
static void getFraction(double d, int &num, int &denom, const double epsilon=5e-10, const int count=10)
Converts a double to a fraction.
Definition: Math.h:147
void makeCopy(const HashArray< edge, edge > &edgeMap)
Copy witness sets and core edges for a given copy map.
void del(iterator it)
Removes it from the list.
Definition: List.h:1380
T weight(const edge e) const
void use2Approximation(bool use2approx)
Define if we want to use a 2-approximation as bound.
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.
void reverseEdge(edge e)
Reverses the edge e, i.e., exchanges source and target node.
const List< node > & terminals(int id) const
Return list of terminals for a given component.
void moveAdjAfter(adjEntry adjMove, adjEntry adjAfter)
Moves adjacency entry adjMove after adjAfter.
Definition: Graph_d.h:1068
iterator rbegin()
Returns an iterator to the last element.
Definition: Array.h:180
BlowupComponents(const EdgeWeightedGraphCopy< T > &blowupGraph, const List< node > &bgTerminals, const std::vector< node > &ignores, const NodeArray< node > &bgOriginal)
Find all components in the blowup graph and initialize information them.
void createEmpty(const Graph &wG)
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 ...
internal::GraphObjectContainer< EdgeElement > edges
The container containing all edge objects.
Definition: Graph_d.h:548
int numberOfEdges() const
Returns the number of edges in the graph.
Definition: Graph_d.h:581
virtual T computeSteinerTree(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal, EdgeWeightedGraphCopy< T > *&finalSteinerTree) override
Builds a minimum Steiner tree for a given weighted graph with terminals.
void findFull2Components(SubsetEnumerator< node > &terminalSubset)
Find full components of size 2.
void quicksort()
Sorts the list using Quicksort.
Definition: List.h:1097
void initializeComponent(edge rootEdge, const EdgeWeightedGraphCopy< T > &blowupGraph, const NodeArray< node > &bgOriginal)
Initialize all information about the component starting with rootEdge in the blowup graph...
virtual T call(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal, EdgeWeightedGraphCopy< T > *&finalSteinerTree, const node startNode)
An extended call method with specific start node.
Iterators for hash tables.
Definition: Hashing.h:208
Mathematical Helpers.
void begin(int low, int high)
Initialize the SubsetEnumerator to enumerate subsets of cardinalities from low to high...
bool empty() const
Returns true if the buffer is empty, false otherwise.
Definition: ArrayBuffer.h:111
edge firstEdge() const
Returns the first edge in the list of all edges.
Definition: Graph_d.h:603
static void copy(const T &from, T &to)
Definition: Alg.h:61
INDEX size() const
Returns the size (number of elements) of the array.
Definition: Array.h:134
int numberOfWitnesses(edge e) const
Return the number of witnesses of an edge.
node contract(edge e)
Contracts edge e while preserving the order of adjacency entries.
Enumerator for k-subsets of a given type.
Definition and implementation of FullComponentStore, a data structure to store full components...
Manage witness set and core edges of a blowup graph.
T getApproximation(EdgeWeightedGraphCopy< T > *&finalSteinerTree, const std::minstd_rand &rng, const bool doPreprocessing=true)
Obtain an (1.39+epsilon)-approximation based on the LP solution.
Doubly linked lists (maintaining the length of the list).
Definition: List.h:39
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.
bool separateCycles(const ArrayBuffer< int > &activeComponents)
Perform the separation algorithm for cycle constraints (to obtain stronger LP solution) ...
void copyComponent(EdgeWeightedGraphCopy< T > &blowupGraph, EdgeArray< int > &capacity, CoreWitness &cw, NodeArray< node > &bgOriginal, const edge origEdge, const int origCap, const int copyCap)
Copy a component in the blowup graph and set original capacity to origCap and capacity of copy to cop...
A Union/Find data structure for maintaining disjoint sets.
Definition: DisjointSets.h:81
bool isLoopFree(const Graph &G)
Returns true iff G contains no self-loop.
static T gcd(T a, T b)
Returns the greatest common divisor of two numbers.
Definition: Math.h:117
void setMaxComponentSize(int restricted)
Set the maximum full component size to generate.
const T & cost(int id) const
Return total cost of a given component.
node twinNode() const
Returns the associated node of the corresponding adjacency entry (shorthand for twin()->theNode()).
Definition: Graph_d.h:105
Class for the representation of edges.
Definition: Graph_d.h:291
void addCycleConstraints(bool add=true)
Define if we want to use cycle constraints for a stronger LP.
adjEntry twin() const
Returns the corresponding adjacency element associated with the same edge.
Definition: Graph_d.h:102
void generateObjective(bool perturb)
Generate the LP objective.
E popFrontRet()
Removes the first element from the list and returns it.
Definition: List.h:1360
steiner_tree::FullComponentWithExtraStore< T, double > m_fullCompStore
all enumerated full components, with solution
Copies of graphs supporting edge splitting.
Definition: GraphCopy.h:250
void addTerminalCoverConstraint()
Add terminal cover constraints to the LP.
adjEntry lastAdj() const
Returns the last entry in the adjacency list.
Definition: Graph_d.h:213
Class for the representation of nodes.
Definition: Graph_d.h:167
Obtain and provides information about components in a given blowup graph.
Encapsulates a pointer to a list element.
Definition: List.h:41
void generateProblem(bool perturb=false)
Generate the LP model.
T obtainFinalSteinerTree(const EdgeWeightedGraph< T > &G, const NodeArray< bool > &isTerminal, const NodeArray< bool > &isOriginalTerminal, EdgeWeightedGraphCopy< T > *&finalSteinerTree)
edge rootEdge(int id) const
Return the edge coming from the root of a given component.
bool isValidComponent(const EdgeWeightedGraphCopy< T > &graph)
Check if a given (sub)graph is a valid full component.
INDEX size() const
Returns number of elements in the buffer.
Definition: ArrayBuffer.h:117
const Graph & original() const
Returns a reference to the original graph.
Definition: GraphCopy.h:287
static void singleSourceShortestPathsDetour(const EdgeWeightedGraph< T > &G, node source, const NodeArray< bool > &isTerminal, NodeArray< T > &distance, NodeArray< edge > &pred)
iterator begin()
Returns an iterator to the first element.
Definition: Array.h:162
This class implements the minimum Steiner tree 2-approximation algorithm by Takahashi and Matsuyama w...
int makeSet()
Initializes a singleton set.
Definition: DisjointSets.h:172
static T lcm(T a, T b)
Returns the least common multipler of two numbers.
Definition: Math.h:140
void computeRandomCoreEdges(const EdgeWeightedGraphCopy< T > &G, const List< node > &terminals, EdgeArray< bool > &isInTree)
Compute a random set of core edges.
void setMaxComponentSize(int k)
Sets the maximal number of terminals in a full component.
E popRet()
Removes the newest element from the buffer and returns it.
Definition: ArrayBuffer.h:108
ExtraDataType & extra(int i)
Returns a reference to the extra data of this full component.
void init(bool perturb=false)
Perform basic initialization algorithms: find shortest paths, find the full components, generate the LP model.
bool removeFirst(const E &x)
Removes the first occurrence of x (if any) from the list.
Definition: List.h:1386
iterator end()
Returns an iterator to one past the last element.
Definition: Array.h:171
void doGoemansApproximation(NodeArray< bool > &isNewTerminal)
Perform the actual approximation algorithm on the LP solution.
void list(List< T > &list) const
Obtain (append) a list of the elements in the subset.
void next()
Obtain the next subset if possible. The result should be checked using the valid() method...
adjEntry succ() const
Returns the successor in the adjacency list.
Definition: Graph_d.h:145
int size() const
Returns the number of elements in the list.
Definition: List.h:1255
void removeInactiveComponents()
Remove inactive components from m_fullCompStore (since we do not need them any longer) ...
void setRootEdge(int id, edge e)
Set the edge coming from the root for a given component.
iterator begin()
Returns an iterator to the first entry in the node array.
Definition: NodeArray.h:215
void addComponent(NodeArray< bool > &isNewTerminal, const EdgeWeightedGraphCopy< T > &blowupGraph, const NodeArray< node > &bgOriginal, const edge rootEdge)
Add a component of the blowup graph to the final solution (by changing nonterminals to terminals) ...
int findCheapestComponentAndRemainingBasis(List< std::pair< node, int >> *&maxBasis, const CoreWitness &cw, EdgeArray< int > &capacity, const BlowupComponents &gamma)
For the end of the algorithm: find cheapest component and choose all remaining core edges as basis...
virtual bool call(const Graph &graph, const EdgeArray< TCost > &weight, node s, node t, List< edge > &edgeList, edge e_st) override
The actual algorithm call.
HashConstIterator< I, E, H > begin() const
Returns an iterator to the first element in the list of all elements.
Definition: HashArray.h:113
static bool checkComputedFlow(const Graph &G, EdgeArray< int > &lowerBound, EdgeArray< int > &upperBound, EdgeArray< TCost > &cost, NodeArray< int > &supply, EdgeArray< int > &flow, TCost &value)
checks if a computed flow is a feasible solution to the given problem instance.
node source() const
Returns the source node of the edge.
Definition: Graph_d.h:325
#define OGDF_STEINERTREE_GOEMANS139_SEPARATE_CONNECTED_COMPONENTS
Handles connection to the COIN library, by offering helper classes.
Algorithms used by at least two functions of Steiner tree code or its internal helpers.
void findFull3Components(SubsetEnumerator< node > &terminalSubset)
Find full components of size 3.
const EdgeWeightedGraph< T > & graph() const
bool isInBackCut(const node v) const
Returns whether this node is part of the back cut.
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 ...
int size() const
Return the cardinality of the subset.
The namespace for all OGDF objects.
static void allPairShortestPathsStrict(const EdgeWeightedGraph< T > &G, const NodeArray< bool > &isTerminal, NodeArray< NodeArray< T > > &distance, NodeArray< NodeArray< edge > > &pred)
void removeComponents(ArrayBuffer< int > &ids)
Remove the full components with the given ids.
Computes a min-cost flow using a network simplex method.
UFCR(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal)
Initialize all attributes, sort the terminal list.
virtual bool call(const Graph &G, const EdgeArray< int > &lowerBound, const EdgeArray< int > &upperBound, const EdgeArray< TCost > &cost, const NodeArray< int > &supply, EdgeArray< int > &flow, NodeArray< TCost > &dual) override
Computes a min-cost flow in the directed graph G using a network simplex method.
int numberOfNodes() const
Returns the number of nodes in the graph.
Definition: Graph_d.h:578
node newNode()
Creates a new node and returns it.
virtual void delNode(node v) override
Removes node v and all its adjacent edges cleaning-up their corresponding lists of original edges...
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:545
adjEntry firstAdj() const
Returns the first entry in the adjaceny list.
Definition: Graph_d.h:211
This class implements the (1.39+epsilon)-approximation algorithm for the Steiner tree problem by Goem...
Definition and implementation of a full component generator based on the Dreyfus-Wagner algorithm...
void forceAPSP(bool force=true)
Define if APSP shortest path algorithm should be used even if SSSP can be used.
static void singleSourceShortestPathsStrict(const EdgeWeightedGraph< T > &G, node source, const NodeArray< bool > &isTerminal, NodeArray< T > &distance, NodeArray< edge > &pred)
adjEntry adjTarget() const
Returns the corresponding adjacancy entry at target node.
Definition: Graph_d.h:332
void setSeed(int seed)
Set seed for the random number generation.
bool empty() const
Returns true iff the list is empty.
Definition: List.h:236
Computes a max flow via Preflow-Push (global relabeling and gap relabeling heuristic).
void use2Approximation(bool use2approx=true)
Use Takahashi-Matsuyama 2-approximation as upper bounds.
Class for adjacency list elements.
Definition: Graph_d.h:78
void separateCycles(bool separateCycles=true)
Use stronger LP relaxation (not recommended in general)
void permute()
Randomly permutes the elements in the list.
Definition: List.h:1171
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:41
int updateSourceAndTargetArcCapacities(EdgeWeightedGraphCopy< T > &blowupGraph, EdgeArray< int > &capacity, const node v, const node source, const node pseudotarget, const int N)
Update arc capacities s->v and v->t.
void removeBasisAndCleanup(EdgeWeightedGraphCopy< T > &blowupGraph, BlowupComponents &gamma, node v, const node source, const node pseudotarget, const int N)
Remove basis (given by v, a core edge node of the maximum basis) and cleanup.
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:198