Open
Graph Drawing
Framework

 v. 2020.02 (Catalpa)
 

SteinerTreePreprocessing.h
Go to the documentation of this file.
1 
32 #pragma once
33 
34 #include <forward_list>
35 #include <memory>
36 #include <set>
37 #include <unordered_map>
38 
45 
46 namespace ogdf {
47 
48 // Helpers:
49 namespace steiner_tree {
55 public:
56  int operator() (NodePair const &v) const
57  {
58  return static_cast<int>((static_cast<long long>(
59  min(v.source->index(), v.target->index())+11) * (max(v.source->index(), v.target->index())+73)) % 700001);
60  }
61 };
62 
68 public:
69  bool operator() (NodePair const &pair1, NodePair const &pair2) const
70  {
71  return (pair1.source == pair2.source && pair1.target == pair2.target)
72  || (pair1.source == pair2.target && pair1.target == pair2.source);
73  }
74 };
75 
76 }
77 
89 template<typename T>
91 protected:
96 
100 
102 
111  std::vector<std::vector<int>> m_sonsList;
112 
113  std::unique_ptr<MinSteinerTreeModule<T>> m_costUpperBoundAlgorithm;
114 
115 public:
121  SteinerTreePreprocessing(const EdgeWeightedGraph<T> &wg, const List<node> &terminals, const NodeArray<bool> &isTerminal);
122 
131  {
132  finalSteinerTree = new EdgeWeightedGraphCopy<T>;
133  // reductions generate new nodes and edges, which may inflate the internal structure
134  if (m_copyGraph.maxNodeIndex() <= m_copyGraph.numberOfNodes() + 5
135  && m_copyGraph.maxEdgeIndex() <= m_copyGraph.numberOfEdges() + 10) { // within inflate tolerance
136  EdgeWeightedGraphCopy<T> *reducedSolution = nullptr;
137  T cost = mst.call(m_copyGraph, m_copyTerminals, m_copyIsTerminal, reducedSolution);
138  cost += costEdgesAlreadyInserted();
139  computeOriginalSolution(*reducedSolution, *finalSteinerTree);
140  delete reducedSolution;
141  return cost;
142  }
143 
144  // make a compact copy
145  EdgeWeightedGraph<T> ccGraph;
146  NodeArray<node> nCopy(m_copyGraph, nullptr);
147  EdgeArray<edge> eCopy(m_copyGraph, nullptr);
148  List<node> ccTerminals;
149  NodeArray<bool> ccIsTerminal(ccGraph, false);
150  for (node v : m_copyGraph.nodes) {
151  nCopy[v] = ccGraph.newNode();
152  }
153  for (edge e : m_copyGraph.edges) {
154  eCopy[e] = ccGraph.newEdge(nCopy[e->source()], nCopy[e->target()], m_copyGraph.weight(e));
155  }
156  for (node t : m_copyTerminals) {
157  const node tC = nCopy[t];
158  ccTerminals.pushBack(tC);
159  ccIsTerminal[tC] = true;
160  }
161 
162  // solve compact copy
163  EdgeWeightedGraphCopy<T> *ccSolution = nullptr;
164  T cost = mst.call(ccGraph, ccTerminals, ccIsTerminal, ccSolution);
165  cost += costEdgesAlreadyInserted();
166 
167  // get reduced and original solution from compact copy solution
168  EdgeWeightedGraphCopy<T> reducedSolution;
169  reducedSolution.createEmpty(m_copyGraph);
170  for (node v : m_copyGraph.nodes) {
171  if (ccSolution->copy(nCopy[v]) != nullptr) { // is in solution
172  reducedSolution.newNode(v);
173  }
174  }
175  for (edge e : m_copyGraph.edges) {
176  if (ccSolution->copy(eCopy[e]) != nullptr) { // is in solution
177  reducedSolution.newEdge(e, m_copyGraph.weight(e));
178  }
179  }
180  delete ccSolution;
181 
182  computeOriginalSolution(reducedSolution, *finalSteinerTree);
183  return cost;
184  }
185 
191  inline const EdgeWeightedGraph<T>& getReducedGraph() const { return m_copyGraph; }
193 
195  inline const List<node>& getReducedTerminals() const { return m_copyTerminals; }
196 
198  inline void shuffleReducedTerminals() { m_copyTerminals.permute(); }
199 
201  inline const NodeArray<bool>& getReducedIsTerminal() const { return m_copyIsTerminal; }
203 
209  inline T costEdgesAlreadyInserted() const { return m_costAlreadyInserted; }
211 
217  void computeOriginalSolution(const EdgeWeightedGraphCopy<T> &reducedGraphSolution, EdgeWeightedGraphCopy<T> &correspondingOriginalSolution);
219 
225 
228  {
229  return repeat([this]() {
230  bool changed = false;
231  changed |= degree2Test();
232  changed |= makeSimple();
233  changed |= deleteLeaves();
234  return changed;
235  });
236  }
237 
239  bool reduceFast() {
240  int k = 5; // for PTmTest
241  // comment wrt. Apple Clang 10: making k const, results in compiler error while binding it in lambda
242  // comment wrt. MSVC 19: not binding the const k would result in compiler error
243 
244  bool changed = deleteComponentsWithoutTerminals();
245  bool triviallyChanged = false;
246  changed |= repeat([this, &triviallyChanged, k]() {
247  bool innerChanged = false;
248  triviallyChanged = reduceTrivial();
249  // graph guaranteed to be simple and connected
250 
251  if (nearestVertexTest()) {
252  makeSimple();
253  innerChanged = true;
254  }
255 
256  // precond: connected
257  if (terminalDistanceTest()) {
258  // can occur: disconnected
259  deleteComponentsWithoutTerminals();
260  innerChanged = true;
261  }
262 
263  // precond: simple, connected
264  innerChanged |= NTDkTest(10, k);
265  // can occur: parallel edges
266 
267  // precond: connected
268  innerChanged |= shortLinksTest();
269  // can occur: parallel edges, self-loops
270 
271  // precond: connected
272  innerChanged |= lowerBoundBasedTest();
273 
274  // is not thaaat good but helps a little:
275  innerChanged |= PTmTest(k);
276  // can occur: parallel edges
277 
278  return innerChanged;
279  });
280  return changed | triviallyChanged;
281  }
282 
285  return repeat([this] {
286  bool changed = reduceFast();
287  changed |= dualAscentBasedTest();
288  return changed;
289  });
290  }
291 
293 
299 
307  bool deleteLeaves();
308 
315  bool makeSimple();
316 
323  bool deleteComponentsWithoutTerminals();
324 
331  bool leastCostTest();
332 
339  bool degree2Test();
340 
348  bool PTmTest(const int k = 3);
349 
358  bool terminalDistanceTest();
359 
366  bool longEdgesTest();
367 
378  bool NTDkTest(const int maxTestedDegree = 5, const int k = 3);
379 
388  bool nearestVertexTest();
389 
398  bool shortLinksTest();
399 
410  bool lowerBoundBasedTest(T upperBound);
411 
416  inline bool lowerBoundBasedTest() {
417  return lowerBoundBasedTest(computeMinSteinerTreeUpperBound());
418  }
419 
429  bool dualAscentBasedTest(int repetitions, T upperBound);
430 
435  inline bool dualAscentBasedTest(int repetitions = 1) {
436  return dualAscentBasedTest(repetitions, computeMinSteinerTreeUpperBound());
437  }
438 
449  bool reachabilityTest(int maxDegreeTest = 0, const int k = 3);
450 
459  bool cutReachabilityTest();
460 
462 
468  inline void setCostUpperBoundAlgorithm(MinSteinerTreeModule<T> *pMinSteinerTreeModule) {
470  m_costUpperBoundAlgorithm.reset(pMinSteinerTreeModule);
471  }
472 
474 
476  static bool repeat(std::function<bool()> f) {
477  bool changed = false;
478  while (f()) {
479  changed = true;
480  }
481  return changed;
482  }
483 
484 protected:
493  template<typename TWhat, typename TWhatArray>
494  void addNew(TWhat x, const std::vector<node> &replacedNodes, const std::vector<edge> &replacedEdges, bool deleteReplacedElements,
495  TWhatArray &whatSonsListIndex);
496 
498  inline void addNewNode(node v, const std::vector<node> &replacedNodes, const std::vector<edge> &replacedEdges, bool deleteReplacedElements)
499  {
500  addNew(v, replacedNodes, replacedEdges, deleteReplacedElements, m_nodeSonsListIndex);
501  }
502 
504  inline void addNewEdge(edge e, const std::vector<node> &replacedNodes, const std::vector<edge> &replacedEdges, bool deleteReplacedElements)
505  {
506  addNew(e, replacedNodes, replacedEdges, deleteReplacedElements, m_edgeSonsListIndex);
507  }
508 
515  bool addEdgesToSolution(const List<edge> &edgesToBeAddedInSolution);
516 
518  void recomputeTerminalsList();
519 
521  void computeShortestPathMatrix(NodeArray<NodeArray<T>> &shortestPath) const;
522 
524  void floydWarshall(NodeArray<NodeArray<T>> &shortestPath) const;
525 
527  {
528  finalSteinerTree = nullptr;
529  return m_costUpperBoundAlgorithm->call(m_copyGraph, m_copyTerminals, m_copyIsTerminal, finalSteinerTree);
530  }
531 
532  // for convenience:
534  {
535  EdgeWeightedGraphCopy<T> *finalSteinerTree;
536  T treeCostUpperBound = computeMinSteinerTreeUpperBound(finalSteinerTree);
537  delete finalSteinerTree;
538  return treeCostUpperBound;
539  }
540 
542  void addToSolution(const int listIndex, Array<bool, int> &isInSolution) const;
543 
545  bool deleteNodesAboveUpperBound(const NodeArray<T> &lowerBoundWithNode, const T upperBound);
547  bool deleteEdgesAboveUpperBound(const EdgeArray<T> &lowerBoundWithEdge, const T upperBound);
548 
550  void deleteSteinerDegreeTwoNode(node v,
551  const EdgeWeightedGraphCopy<T>& tprime,
553  const NodeArray<List<std::pair<node,T>>>& closestTerminals);
554 
564  void findClosestNonTerminals(node source, List<node> &reachedNodes, NodeArray<T> &distance, T maxDistance, int expandedEdges) const;
565 
570  T computeBottleneckDistance(node x, node y,
571  const EdgeWeightedGraphCopy<T>& tprime,
573  const NodeArray<List<std::pair<node,T>>>& closestTerminals) const;
574 
580  void computeClosestKTerminals(const int k, NodeArray<List<std::pair<node,T>>> &closestTerminals) const;
581 
583  void computeRadiusOfTerminals(NodeArray<T> &terminalRadius) const;
584 
586  T computeRadiusSum() const;
587 
589  template<typename LAMBDA>
590  void computeOptimalTerminals(node v, LAMBDA dist, node &optimalTerminal1, node &optimalTerminal2, NodeArray<T> &distance) const;
591 
593  void markSuccessors(node currentNode, const Voronoi<T> &voronoiRegions, NodeArray<bool> &isSuccessorOfMinCostEdge) const;
594 
596  void findTwoMinimumCostEdges(node v, edge& first, edge& second) const;
597 };
598 
599 template<typename T>
601  : m_origGraph(wg)
602  , m_origTerminals(terminals)
603  , m_origIsTerminal(isTerminal)
604  , m_eps(1e-6)
605 {
606  OGDF_ASSERT(!m_origGraph.empty());
607 
608  // make the initial graph copy
609  m_copyGraph.clear();
610  NodeArray<node> nCopy(m_origGraph);
611  EdgeArray<edge> eCopy(m_origGraph);
612 
613  for (node v : m_origGraph.nodes) {
614  nCopy[v] = m_copyGraph.newNode();
615  }
616  for (edge e : m_origGraph.edges) {
617  eCopy[e] = m_copyGraph.newEdge(nCopy[e->source()], nCopy[e->target()], m_origGraph.weight(e));
618  }
619 
620  // create the terminals and isTerminal arrays for the copyGraph
621  m_copyTerminals.clear();
622  m_copyIsTerminal.init(m_copyGraph, false);
623  for (node v : m_origGraph.nodes) {
624  if (m_origIsTerminal(v)) {
625  const node vC = nCopy[v];
626  m_copyTerminals.pushBack(vC);
627  m_copyIsTerminal[vC] = true;
628  }
629  }
630  m_costAlreadyInserted = 0;
631 
632  // map every node and edge to a negative number for m_(node/edge)_m_sonsListIndex
633  m_nodeSonsListIndex.init(m_copyGraph);
634  m_edgeSonsListIndex.init(m_copyGraph);
635  int nextIndex = 1;
636  for (node v : m_origGraph.nodes) {
637  m_nodeSonsListIndex[nCopy[v]] = -(nextIndex++);
638  }
639  for (edge e : m_origGraph.edges) {
640  m_edgeSonsListIndex[eCopy[e]] = -(nextIndex++);
641  }
642 
643  // set the default approximation algorithm for computing the upper bound cost of the solution
644  m_costUpperBoundAlgorithm.reset(new MinSteinerTreeTakahashi<T>);
645 }
646 
647 template<typename T>
648 template<typename TWhat, typename TWhatArray>
650  const std::vector<node> &replacedNodes,
651  const std::vector<edge> &replacedEdges,
652  bool deleteReplacedElements,
653  TWhatArray &whatSonsListIndex)
654 {
655  std::vector<int> sonsIndexList;
656  for (node replacedNode : replacedNodes) {
657  sonsIndexList.push_back(m_nodeSonsListIndex[replacedNode]);
658  }
659  for (edge replacedEdge : replacedEdges) {
660  sonsIndexList.push_back(m_edgeSonsListIndex[replacedEdge]);
661  }
662 
663  m_sonsList.emplace_back(sonsIndexList);
664  whatSonsListIndex[x] = (int)m_sonsList.size() - 1;
665 
666  if (deleteReplacedElements) {
667  for (edge e : replacedEdges) {
668  m_copyGraph.delEdge(e);
669  }
670  for (node v :replacedNodes) {
671  m_copyGraph.delNode(v);
672  }
673  }
674 }
675 
676 template<typename T>
677 void SteinerTreePreprocessing<T>::addToSolution(const int listIndex, Array<bool, int>& isInSolution) const
678 {
679  if (listIndex < 0) { // is starting node or edge
680  isInSolution[listIndex] = true;
681  return;
682  }
683  // is further added node or edge
684  for (int son : m_sonsList[listIndex]) {
685  addToSolution(son, isInSolution);
686  }
687 }
688 
689 template<typename T>
690 void SteinerTreePreprocessing<T>::computeOriginalSolution(const EdgeWeightedGraphCopy<T> &reducedGraphSolution, EdgeWeightedGraphCopy<T> &correspondingOriginalSolution)
691 {
692  correspondingOriginalSolution.createEmpty(m_origGraph); // note that it is not cleared!
693 
694  Array<bool, int> isInSolution(-(m_origGraph.numberOfNodes() + m_origGraph.numberOfEdges()), -1, false);
695 
696  // make the indices of original nodes/edge true in isInSolution
697  for (node v : reducedGraphSolution.nodes) {
698  addToSolution(m_nodeSonsListIndex[reducedGraphSolution.original(v)], isInSolution);
699  }
700  for (edge e : reducedGraphSolution.edges) {
701  addToSolution(m_edgeSonsListIndex[reducedGraphSolution.original(e)], isInSolution);
702  }
703 
704  // insert nodes and edges
705  int nextIndex = 1;
706  for (node v : m_origGraph.nodes) {
707  if (isInSolution[-(nextIndex++)]) {
708  correspondingOriginalSolution.newNode(v);
709  }
710  }
711  for (edge e : m_origGraph.edges) {
712  if (isInSolution[-(nextIndex++)]) {
713  correspondingOriginalSolution.newEdge(e, m_origGraph.weight(e));
714  }
715  }
716 }
717 
718 template<typename T>
720  const EdgeWeightedGraphCopy<T> &tprime,
722  const NodeArray<List<std::pair<node,T>>> &closestTerminals)
723 {
724  struct NewEdgeData {
725  edge e1; // new edge replaces this...
726  edge e2; // ...and this
727  edge already; // but is it already there?
728  T weight;
729  };
730  std::forward_list<NewEdgeData> newEdges;
731  for (adjEntry adj1 : v->adjEntries) {
732  const edge e1 = adj1->theEdge();
733  const node adjacentNode1 = adj1->twinNode();
734 
735  for (adjEntry adj2 = adj1->succ(); adj2 ; adj2 = adj2->succ()) {
736  const edge e2 = adj2->theEdge();
737  const node adjacentNode2 = adj2->twinNode();
738 
739  T edgeWeight = m_copyGraph.weight(e1) + m_copyGraph.weight(e2);
740 
741  const edge f = m_copyGraph.searchEdge(adjacentNode1, adjacentNode2);
742  if (f && m_copyGraph.weight(f) <= edgeWeight) {
743  continue; // check whether there is already a lower cost edge connecting the two adjacent nodes
744  }
745 
746  T bottleneckDistance = computeBottleneckDistance(adjacentNode1, adjacentNode2, tprime, tprimeHPD, closestTerminals);
747  if (m_eps.greater(edgeWeight, bottleneckDistance)) {
748  continue; // the PTm test
749  }
750 
751  newEdges.emplace_front(NewEdgeData{e1, e2, f, edgeWeight});
752  }
753  }
754 
755  for (const auto &newEdge : newEdges) {
756  // delete the old edge (do not generate parallel edges)
757  edge newEdgeInGraph;
758  if (newEdge.already) {
759  OGDF_ASSERT(m_copyGraph.weight(newEdge.already) > newEdge.weight);
760  m_copyGraph.setWeight(newEdge.already, newEdge.weight);
761  newEdgeInGraph = newEdge.already;
762  } else {
763  newEdgeInGraph = m_copyGraph.newEdge(newEdge.e1->opposite(v), newEdge.e2->opposite(v), newEdge.weight);
764  }
765  addNewEdge(newEdgeInGraph, {v}, {newEdge.e1, newEdge.e2}, false);
766  }
767 
768  m_copyGraph.delNode(v);
769 }
770 
771 template<typename T>
773 {
774  m_copyTerminals.clear();
775  for (node v : m_copyGraph.nodes) {
776  if (m_copyIsTerminal[v]) {
777  m_copyTerminals.pushBack(v);
778  }
779  }
780 }
781 
782 template<typename T>
784  const EdgeWeightedGraphCopy<T> &tprime,
786  const NodeArray<List<std::pair<node, T>>> &closestTerminals) const
787 {
788  T bottleneckDistance = std::numeric_limits<T>::max();
789 
790  for (auto &xCloseTerminalDistancePair : closestTerminals[x]) {
791  for (auto &yCloseTerminalDistancePair : closestTerminals[y]) {
792  T possibleBottleneckDistance = xCloseTerminalDistancePair.second + yCloseTerminalDistancePair.second;
793 
794  node xTprimeCopy = tprime.copy(xCloseTerminalDistancePair.first);
795  node yTprimeCopy = tprime.copy(yCloseTerminalDistancePair.first);
796  possibleBottleneckDistance += tprimeHPD.getBottleneckSteinerDistance(xTprimeCopy, yTprimeCopy);
797 
798  Math::updateMin(bottleneckDistance, possibleBottleneckDistance);
799  }
800  }
801 
802  return bottleneckDistance;
803 }
804 
805 template<typename T>
807 {
808  // exceptional case: only one terminal
809  auto deleteAll = [this]() {
810  if (m_copyGraph.numberOfNodes() > 1) {
811  const node w = m_copyTerminals.front();
812  // just remove all other nodes
813  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
814  nextV = v->succ();
815  if (v != w) {
816  m_copyGraph.delNode(v);
817  }
818  }
819  return true;
820  }
821  return false;
822  };
823  if (m_copyTerminals.size() == 1) {
824  return deleteAll();
825  }
826  // general case: at least 2 terminals
827  BoundedQueue<node> eraseQueue(m_copyGraph.numberOfNodes());
828 
829  for (node v : m_copyGraph.nodes) {
830  if (v->degree() == 1) {
831  eraseQueue.append(v);
832  }
833  }
834 
835  if (eraseQueue.empty()) {
836  return false;
837  }
838 
839  for (; !eraseQueue.empty(); eraseQueue.pop()) {
840  node v = eraseQueue.top();
841  if (v->degree() == 0) {
842  continue;
843  }
844  OGDF_ASSERT(v->degree() == 1);
845  const node w = v->firstAdj()->twinNode();
846  if (m_copyIsTerminal[v]) { // v is a terminal
847  // add edge to solution and contract v into w
848  edge e = v->firstAdj()->theEdge();
849  if (!m_copyIsTerminal[w]) {
850  m_copyIsTerminal[w] = true;
851  m_copyTerminals.pushBack(w);
852  }
853  m_copyTerminals.del(m_copyTerminals.search(v));
854  m_costAlreadyInserted += m_copyGraph.weight(e);
855  int cur = m_nodeSonsListIndex[w];
856  if (cur < 0) { // w is an original (copied) node
857  m_sonsList.emplace_back(std::vector<int>{cur, m_nodeSonsListIndex[v], m_edgeSonsListIndex[e]});
858  m_nodeSonsListIndex[w] = (int)m_sonsList.size() - 1;
859  } else { // w contains already sons
860  m_sonsList[cur].push_back(m_nodeSonsListIndex[v]);
861  m_sonsList[cur].push_back(m_edgeSonsListIndex[e]);
862  }
863  } else { // v is not a terminal
864  if (w->degree() == 2) {
865  eraseQueue.append(w);
866  }
867  }
868  m_copyGraph.delNode(v);
869  if (m_copyTerminals.size() == 1) {
870  deleteAll();
871  return true;
872  }
873  }
874  return true;
875 }
876 
877 template<typename T>
879 {
880  bool changed = false;
881  NodeArray<edge> minCostEdge(m_copyGraph, nullptr);
882  for (node v : m_copyGraph.nodes) {
883  for (adjEntry adj = v->firstAdj(), nextAdj; adj; adj = nextAdj) {
884  nextAdj = adj->succ();
885 
886  edge e = adj->theEdge();
887  node adjNode = adj->twinNode();
888  if (adjNode == v) { // found a self-loop
889  if (nextAdj == adj->twin()) {
890  nextAdj = nextAdj->succ();
891  }
892  m_copyGraph.delEdge(e);
893  changed = true;
894  } else {
895  if (minCostEdge[adjNode] == nullptr
896  || m_copyGraph.weight(minCostEdge[adjNode]) > m_copyGraph.weight(e)) {
897  if (minCostEdge[adjNode] != nullptr) {
898  m_copyGraph.delEdge(minCostEdge[adjNode]);
899  changed = true;
900  }
901  minCostEdge[adjNode] = e;
902  } else {
903  m_copyGraph.delEdge(e);
904  changed = true;
905  }
906  }
907  }
908 
909  for(adjEntry adj : v->adjEntries) {
910  minCostEdge[adj->twinNode()] = nullptr;
911  }
912  }
913  return changed;
914 }
915 
916 template<typename T>
918 {
919  for (node v1 : m_copyGraph.nodes) {
920  for(adjEntry adj : v1->adjEntries) {
921  node v2 = adj->twinNode();
922  shortestPath[v1][v2] = shortestPath[v2][v1] = min(shortestPath[v1][v2], m_copyGraph.weight(adj->theEdge()));
923  }
924  }
925 
926  for (node pivot : m_copyGraph.nodes) {
927  for (node v1 : m_copyGraph.nodes) {
928  for (node v2 : m_copyGraph.nodes) {
929  if (shortestPath[v1][pivot] == std::numeric_limits<T>::max()
930  || shortestPath[pivot][v2] == std::numeric_limits<T>::max()) {
931  continue;
932  }
933 
934  Math::updateMin(shortestPath[v1][v2], shortestPath[v1][pivot] + shortestPath[pivot][v2]);
935  }
936  }
937  }
938 }
939 
940 template<typename T>
942 {
943  shortestPath.init(m_copyGraph);
944  for (node v : m_copyGraph.nodes) {
945  shortestPath[v].init(m_copyGraph, std::numeric_limits<T>::max());
946  }
947 
948  floydWarshall(shortestPath);
949 }
950 
951 template<typename T>
953  OGDF_ASSERT(!m_copyGraph.empty());
954  bool changed = false;
955  NodeArray<NodeArray<T>> shortestPath;
956  computeShortestPathMatrix(shortestPath);
957 
958  for (node v : m_copyGraph.nodes) {
959  for (adjEntry adj = v->firstAdj(), nextAdj; adj; adj = nextAdj) {
960  nextAdj = adj->succ();
961 
962  edge e = adj->theEdge();
963  node adjNode = adj->twinNode();
964  if (adjNode != v
965  && shortestPath[v][adjNode] < m_copyGraph.weight(e)) {
966  m_copyGraph.delEdge(e);
967  changed = true;
968  }
969  }
970  }
971  return changed;
972 }
973 
974 template<typename T>
976  OGDF_ASSERT(!m_copyGraph.empty());
977  bool changed = false;
978  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
979  nextV = v->succ();
980 
981  if (m_copyIsTerminal[v]
982  || v->degree() != 2 ) {
983  continue;
984  }
985 
986  // get left and right adjacent nodes
987  edge eLeft = v->firstAdj()->theEdge();
988  edge eRight = v->lastAdj()->theEdge();
989 
990  node vLeft = v->firstAdj()->twinNode();
991  node vRight = v->lastAdj()->twinNode();
992  if (vLeft != vRight) {
993  T weight = m_copyGraph.weight(eLeft) + m_copyGraph.weight(eRight);
994  edge newEdge = m_copyGraph.newEdge(vLeft, vRight, weight);
995  addNewEdge(newEdge, {v}, {eLeft, eRight}, true);
996  changed = true;
997  } else { // v is leaf with parallel edges or self-loop component
998  m_copyGraph.delNode(v);
999  }
1000  }
1001  return changed;
1002 }
1003 
1004 template<typename T>
1006 {
1007  NodeArray<int> hisConnectedComponent(m_copyGraph, -1);
1008  bool changed = connectedComponents(m_copyGraph, hisConnectedComponent) > 1;
1009  if (changed) {
1010  int componentWithTerminals = -1;
1011  for (node v : m_copyTerminals) {
1012  if (componentWithTerminals != -1
1013  && hisConnectedComponent[v] != componentWithTerminals) {
1014  std::cerr << "terminals in different connected components!\n";
1015  OGDF_ASSERT(false);
1016  }
1017  componentWithTerminals = hisConnectedComponent[v];
1018  }
1019 
1020  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1021  nextV = v->succ();
1022  if (hisConnectedComponent[v] != componentWithTerminals) {
1023  m_copyGraph.delNode(v);
1024  }
1025  }
1026  }
1027  return changed;
1028 }
1029 
1030 template<typename T>
1032  OGDF_ASSERT(!m_copyGraph.empty());
1033  OGDF_ASSERT(isConnected(m_copyGraph));
1034  bool changed = false;
1035 
1036  EdgeWeightedGraphCopy<T> tprime;
1037  steiner_tree::constructTerminalSpanningTreeUsingVoronoiRegions(tprime, m_copyGraph, m_copyTerminals);
1038  T maxBottleneck(0);
1039  for (edge e : tprime.edges) {
1040  Math::updateMax(maxBottleneck, tprime.weight(e));
1041  }
1042 
1043  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1044  nextE = e->succ();
1045 
1046  if (m_eps.greater(m_copyGraph.weight(e), maxBottleneck)) {
1047  m_copyGraph.delEdge(e);
1048  changed = true;
1049  }
1050  }
1051 
1052  return changed;
1053 }
1054 
1055 template<typename T>
1056 void SteinerTreePreprocessing<T>::findClosestNonTerminals(node source, List<node> &reachedNodes, NodeArray<T> &distance, T maxDistance, int expandedEdges) const
1057 {
1058  PrioritizedMapQueue<node, T> queue(m_copyGraph);
1059 
1060  // initialization
1061  distance[source] = 0;
1062  queue.push(source, distance[source]);
1063 
1064  while (!queue.empty()) {
1065  node currentNode = queue.topElement();
1066  queue.pop();
1067 
1068  reachedNodes.pushBack(currentNode);
1069 
1070  for(adjEntry adj : currentNode->adjEntries) {
1071  edge e = adj->theEdge();
1072  if (expandedEdges <= 0) {
1073  break;
1074  }
1075  --expandedEdges;
1076 
1077  node adjacentNode = e->opposite(currentNode);
1078  T possibleDistance = distance[currentNode] + m_copyGraph.weight(e);
1079 
1080  if (m_eps.geq(possibleDistance, maxDistance)
1081  || m_copyIsTerminal[adjacentNode]) {
1082  continue;
1083  }
1084 
1085  if (possibleDistance < distance[adjacentNode]) {
1086  distance[adjacentNode] = possibleDistance;
1087  if (queue.contains(adjacentNode)) { // is already in the queue
1088  queue.decrease(adjacentNode, possibleDistance);
1089  } else {
1090  queue.push(adjacentNode, distance[adjacentNode]);
1091  }
1092  }
1093  }
1094  }
1095 }
1096 
1097 template<typename T>
1099  OGDF_ASSERT(!m_copyGraph.empty());
1100  bool changed = false;
1101  NodeArray<T> xDistance(m_copyGraph, std::numeric_limits<T>::max()),
1102  yDistance(m_copyGraph, std::numeric_limits<T>::max());
1103 
1104  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1105  nextE = e->succ();
1106  List<node> xReachedNodes, yReachedNodes;
1107 
1108  findClosestNonTerminals(e->source(), xReachedNodes, xDistance, m_copyGraph.weight(e), 200);
1109  findClosestNonTerminals(e->target(), yReachedNodes, yDistance, m_copyGraph.weight(e), 200);
1110 
1111  for (node commonNode : xReachedNodes) {
1112  if (yDistance[commonNode] == std::numeric_limits<T>::max()) { // is not common
1113  continue;
1114  }
1115  if (m_eps.less(xDistance[commonNode] + yDistance[commonNode], m_copyGraph.weight(e))) {
1116  m_copyGraph.delEdge(e);
1117  changed = true;
1118  break;
1119  }
1120  }
1121 
1122  for (node reachedNode : xReachedNodes) {
1123  xDistance[reachedNode] = std::numeric_limits<T>::max();
1124  }
1125  for (node reachedNode : yReachedNodes) {
1126  yDistance[reachedNode] = std::numeric_limits<T>::max();
1127  }
1128  }
1129  return changed;
1130 }
1131 
1132 template<typename T>
1133 void SteinerTreePreprocessing<T>::computeClosestKTerminals(const int k, NodeArray<List<std::pair<node,T>>> &closestTerminals) const
1134 {
1135  using NodePairQueue = PrioritizedQueue<NodePair, T>;
1136 
1137  closestTerminals.init(m_copyGraph);
1138  NodePairQueue queue;
1139  std::unordered_map<NodePair, typename NodePairQueue::Handle, steiner_tree::UnorderedNodePairHasher, steiner_tree::UnorderedNodePairEquality> qpos;
1140 
1141  // initialization
1142  for (node v : m_copyTerminals) {
1143  closestTerminals[v].pushBack(std::make_pair(v, 0));
1144  qpos[NodePair(v, v)] = queue.push(NodePair(v, v), closestTerminals[v].front().second);
1145  }
1146 
1147  auto getCurrentDist = [&closestTerminals](const node currentNode, const node sourceTerminal) {
1148  for (std::pair<node,T> currentPair : closestTerminals[currentNode]) {
1149  if (currentPair.first == sourceTerminal) {
1150  return currentPair.second;
1151  }
1152  }
1153  return static_cast<T>(-1);
1154  };
1155 
1156  auto setNewDist = [&closestTerminals, k](const node currentNode, const node sourceTerminal, const T newDist) {
1157  List<std::pair<node, T>> &currentList = closestTerminals[currentNode];
1158 
1159  // delete the old distance
1160  for (ListIterator<std::pair<node, T>> it = currentList.begin(); it.valid(); ++it) {
1161  if ((*it).first == sourceTerminal) {
1162  currentList.del(it);
1163  break;
1164  }
1165  }
1166 
1167  if (currentList.size() == k) { // the list is full
1168  currentList.popBack(); // delete the largest cost element
1169  }
1170 
1171  // add the new distance such that the list remains sorted
1172  if (currentList.empty()
1173  || (*currentList.begin()).second >= newDist) { // if the list is empty
1174  currentList.pushFront(std::make_pair(sourceTerminal, newDist));
1175  return;
1176  }
1177 
1178  ListIterator<std::pair<node, T>> it = closestTerminals[currentNode].begin();
1179  while (it.succ() != closestTerminals[currentNode].end()
1180  && (*it.succ()).second < newDist) {
1181  ++it;
1182  }
1183  closestTerminals[currentNode].insertAfter(std::make_pair(sourceTerminal, newDist), it);
1184  };
1185 
1186  while (!queue.empty()) {
1187  NodePair minDistPair = queue.topElement();
1188  queue.pop();
1189  node currentNode = minDistPair.source;
1190  node sourceTerminal = minDistPair.target;
1191 
1192  T currentDist = getCurrentDist(currentNode, sourceTerminal);
1193  if (currentDist == -1) { // source terminal not found
1194  continue; // check if the current path needs to be expanded
1195  }
1196 
1197  for(adjEntry adj : currentNode->adjEntries) {
1198  edge e = adj->theEdge();
1199  node adjacentNode = e->opposite(currentNode);
1200 
1201  if (m_copyIsTerminal[adjacentNode]) {
1202  continue;
1203  }
1204 
1205  T possibleNewDistance = currentDist + m_copyGraph.weight(e);
1206 
1207  // try to insert the new path from sourceTerminal to adjacentNode
1208  T currentDistToAdjacentNode = getCurrentDist(adjacentNode, sourceTerminal);
1209  if (currentDistToAdjacentNode != -1) { // there is already one path from sourceTerminal to adjNode
1210  if (possibleNewDistance < currentDistToAdjacentNode) {
1211  queue.decrease(qpos[NodePair(adjacentNode, sourceTerminal)], possibleNewDistance);
1212  setNewDist(adjacentNode, sourceTerminal, possibleNewDistance);
1213  }
1214  } else {
1215  if (closestTerminals[adjacentNode].size() < k
1216  || closestTerminals[adjacentNode].back().second > possibleNewDistance) {
1217  qpos[NodePair(adjacentNode, sourceTerminal)] = queue.push(NodePair(adjacentNode, sourceTerminal), possibleNewDistance);
1218  setNewDist(adjacentNode, sourceTerminal, possibleNewDistance);
1219  }
1220  }
1221  }
1222  }
1223 }
1224 
1225 template<typename T>
1227  OGDF_ASSERT(!m_copyGraph.empty());
1228  OGDF_ASSERT(isConnected(m_copyGraph));
1229  bool changed = false;
1230 
1231  EdgeWeightedGraphCopy<T> tprime;
1232  steiner_tree::constructTerminalSpanningTreeUsingVoronoiRegions(tprime, m_copyGraph, m_copyTerminals);
1233 
1234  NodeArray<List<std::pair<node,T>>> closestTerminals;
1235  computeClosestKTerminals(k, closestTerminals);
1236 
1237  steiner_tree::HeavyPathDecomposition<T> tprimeHPD(tprime);
1238 
1239  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1240  nextE = e->succ();
1241 
1242  T bottleneckDistance = computeBottleneckDistance(e->source(), e->target(), tprime, tprimeHPD, closestTerminals);
1243 
1244  if (m_eps.greater(m_copyGraph.weight(e), bottleneckDistance)) {
1245  m_copyGraph.delEdge(e);
1246  changed = true;
1247  }
1248  }
1249 
1250  return changed;
1251 }
1252 
1253 template<typename T>
1254 bool SteinerTreePreprocessing<T>::NTDkTest(const int maxTestedDegree, const int k) {
1255  OGDF_ASSERT(!m_copyGraph.empty());
1256  if (m_copyTerminals.size() <= 2) {
1257  return false;
1258  }
1259 
1260  bool changed = false;
1261  OGDF_ASSERT(isSimpleUndirected(m_copyGraph));
1262  OGDF_ASSERT(isConnected(m_copyGraph));
1263 
1264  EdgeWeightedGraphCopy<T> tprime;
1265  steiner_tree::constructTerminalSpanningTreeUsingVoronoiRegions(tprime, m_copyGraph, m_copyTerminals);
1266 
1267  NodeArray<List<std::pair<node,T>>> closestTerminals;
1268  computeClosestKTerminals(k, closestTerminals);
1269 
1270  steiner_tree::HeavyPathDecomposition<T> tprimeHPD(tprime);
1271 
1272  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1273  nextV = v->succ();
1274 
1275  if (m_copyIsTerminal[v]) {
1276  continue;
1277  }
1278  if (v->degree() <= 2
1279  || v->degree() > maxTestedDegree) {
1280  continue;
1281  }
1282 
1283  // collect neighbors
1284  List<adjEntry> outgoingAdjs;
1285  for (adjEntry adj : v->adjEntries) {
1286  outgoingAdjs.pushBack(adj);
1287  }
1288  SubsetEnumerator<adjEntry> neighborSubset(outgoingAdjs);
1289 
1290  bool deleteNode = true;
1291  for (neighborSubset.begin(3, v->degree()); neighborSubset.valid() && deleteNode; neighborSubset.next()) {
1292  Graph auxGraph;
1293  std::unordered_map<node, node> initNodeToAuxGraph;
1294  std::unordered_map<node, node> auxGraphToInitNode;
1295 
1296  T sumToSelectedAdjacentNodes = 0;
1297 
1298  for (int i = 0; i < neighborSubset.size(); ++i) {
1299  const adjEntry adj = neighborSubset[i];
1300  const node adjacentNode = adj->twinNode();
1301  sumToSelectedAdjacentNodes += m_copyGraph.weight(adj->theEdge());
1302 
1303  OGDF_ASSERT(initNodeToAuxGraph.find(adjacentNode) == initNodeToAuxGraph.end());
1304 
1305  node newAuxGraphNode = auxGraph.newNode();
1306  initNodeToAuxGraph[adjacentNode] = newAuxGraphNode;
1307  auxGraphToInitNode[newAuxGraphNode] = adjacentNode;
1308  }
1309 
1310  EdgeArray<T> weight(auxGraph, 0);
1311  for (node auxGraphNode1 : auxGraph.nodes) {
1312  for (node auxGraphNode2 = auxGraphNode1->succ(); auxGraphNode2; auxGraphNode2 = auxGraphNode2->succ()) {
1313  edge e = auxGraph.newEdge(auxGraphNode1, auxGraphNode2);
1314  weight[e] = computeBottleneckDistance(
1315  auxGraphToInitNode[auxGraphNode1],
1316  auxGraphToInitNode[auxGraphNode2],
1317  tprime, tprimeHPD, closestTerminals);
1318  }
1319  }
1320 
1321  // the auxGraph is now created; run MST on it
1322  EdgeArray<bool> isInTree(auxGraph, false);
1323  T mstCost = computeMinST(auxGraph, weight, isInTree);
1324 
1325  if (sumToSelectedAdjacentNodes < mstCost) {
1326  deleteNode = false;
1327  }
1328  }
1329 
1330  if (deleteNode) {
1331  deleteSteinerDegreeTwoNode(v, tprime, tprimeHPD, closestTerminals);
1332  changed = true;
1333  }
1334  }
1335 
1336  return changed;
1337 }
1338 
1339 template<typename T>
1340 void SteinerTreePreprocessing<T>::markSuccessors(node currentNode, const Voronoi<T> &voronoiRegions, NodeArray<bool> &isSuccessorOfMinCostEdge) const
1341 {
1342  isSuccessorOfMinCostEdge[currentNode] = true;
1343 
1344  OGDF_ASSERT(voronoiRegions.seed(currentNode) != currentNode);
1345 
1346  // recurse for every successor
1347  for (adjEntry adj : currentNode->adjEntries) {
1348  edge e = adj->theEdge();
1349  node adjacentNode = e->opposite(currentNode);
1350 
1351  if (voronoiRegions.predecessor(adjacentNode) == currentNode) {
1352  markSuccessors(adjacentNode, voronoiRegions, isSuccessorOfMinCostEdge);
1353  }
1354  }
1355 }
1356 
1357 template<typename T>
1359  /* This is a simple problem, however, there is a weird case that can occur
1360  * in nearestVertexTest(): Imagine a triangle of three terminals where the three edges
1361  * have all equal costs. It can happen that each terminal chooses its first edge to
1362  * be unique, so in the end we add all three edges of the triangle except only two of it.
1363  * We tackle this problem at *this* stage by choosing the edge with smallest index
1364  * in case of a tie in the costs. It is sufficient to do that for the first only
1365  * because this is the edge that will be put into the solution. */
1366  for (adjEntry adj : v->adjEntries) {
1367  edge e = adj->theEdge();
1368  if (first == nullptr // not set or
1369  || m_eps.less(m_copyGraph.weight(e), m_copyGraph.weight(first)) // smaller cost or
1370  || (m_eps.equal(m_copyGraph.weight(e), m_copyGraph.weight(first)) // cost tie but...
1371  && e->index() < first->index())) { // cost tie but smaller index
1372  second = first;
1373  first = e;
1374  } else {
1375  if (second == nullptr
1376  || m_eps.less(m_copyGraph.weight(e), m_copyGraph.weight(second))) {
1377  second = e;
1378  }
1379  }
1380  }
1381  OGDF_ASSERT(first != second);
1382 }
1383 
1384 template<typename T>
1386 {
1387  if (edgesToBeAddedInSolution.empty()) {
1388  return false;
1389  }
1390  for (edge e : edgesToBeAddedInSolution) {
1391  node x = e->source(), y = e->target();
1392  m_sonsList.emplace_back(std::vector<int>{m_nodeSonsListIndex[x], m_nodeSonsListIndex[y], m_edgeSonsListIndex[e]});
1393  m_costAlreadyInserted += m_copyGraph.weight(e);
1394  node newNode = m_copyGraph.contract(e);
1395  m_nodeSonsListIndex[newNode] = (int)m_sonsList.size() - 1;
1396  m_copyIsTerminal[newNode] = true;
1397  }
1398 
1400  return true;
1401 }
1402 
1403 template<typename T>
1405  OGDF_ASSERT(!m_copyGraph.empty());
1406  OGDF_ASSERT(isLoopFree(m_copyGraph));
1407  OGDF_ASSERT(isConnected(m_copyGraph));
1408 
1409  Voronoi<T> voronoiRegions(m_copyGraph, m_copyGraph.edgeWeights(), m_copyTerminals);
1410 
1411  NodeArray<edge> minCostIncidentEdge1(m_copyGraph, nullptr);
1412  NodeArray<edge> minCostIncidentEdge2(m_copyGraph, nullptr);
1413 
1414  // find the first and second minimum-cost edges incident to terminals
1415  for (node terminal : m_copyTerminals) {
1416  if (terminal->degree() >= 2) {
1417  findTwoMinimumCostEdges(terminal, minCostIncidentEdge1[terminal], minCostIncidentEdge2[terminal]);
1418  }
1419  }
1420 
1421  // for each Voronoi region, mark successors (recursively) of the minimum-cost edge
1422  NodeArray<bool> isSuccessorOfMinCostEdge(m_copyGraph, false);
1423  for (node terminal : m_copyTerminals) {
1424  if (terminal->degree() >= 2) {
1425  node closestNode = minCostIncidentEdge1[terminal]->opposite(terminal);
1426 
1427  if (voronoiRegions.seed(closestNode) == terminal) {
1428  markSuccessors(closestNode, voronoiRegions, isSuccessorOfMinCostEdge);
1429  }
1430  }
1431  }
1432 
1433  // compute for every terminal the distance to the closest terminal
1434  NodeArray<T> distanceToClosestTerminal(m_copyGraph, std::numeric_limits<T>::max());
1435  for (edge e : m_copyGraph.edges) {
1436  node x = e->source(), y = e->target();
1437  node seedX = voronoiRegions.seed(x), seedY = voronoiRegions.seed(y);
1438  if (seedX != seedY) {
1439  // update distanceToClosestTerminal for seed(x)
1440  T distanceThroughE = voronoiRegions.distance(x) + m_copyGraph.weight(e) + voronoiRegions.distance(y);
1441 
1442  if (isSuccessorOfMinCostEdge[x]) {
1443  Math::updateMin(distanceToClosestTerminal[seedX], distanceThroughE);
1444  }
1445  if (isSuccessorOfMinCostEdge[y]) {
1446  Math::updateMin(distanceToClosestTerminal[seedY], distanceThroughE);
1447  }
1448  }
1449  }
1450 
1451  // see what edges can be added in solution (Observation 3.2)
1452  List<edge> edgesToBeAddedInSolution;
1453  EdgeArray<bool> willBeAddedInSolution(m_copyGraph, false);
1454  for (node terminal : m_copyTerminals) {
1455  if (terminal->degree() >= 2) {
1456  const edge e = minCostIncidentEdge1[terminal];
1457  const node closestAdjacentNode = e->opposite(terminal);
1458  T distance{voronoiRegions.seed(closestAdjacentNode) == terminal
1459  ? distanceToClosestTerminal[terminal]
1460  : m_copyGraph.weight(e) + voronoiRegions.distance(closestAdjacentNode)};
1461 
1462  if (m_eps.geq(m_copyGraph.weight(minCostIncidentEdge2[terminal]), distance)
1463  && !willBeAddedInSolution[e]) {
1464  edgesToBeAddedInSolution.pushBack(e);
1465  willBeAddedInSolution[e] = true;
1466  }
1467  }
1468  }
1469 
1470  return addEdgesToSolution(edgesToBeAddedInSolution);
1471 }
1472 
1473 template<typename T>
1475  OGDF_ASSERT(!m_copyGraph.empty());
1476  OGDF_ASSERT(isConnected(m_copyGraph));
1477 
1478  Voronoi<T> voronoiRegions(m_copyGraph, m_copyGraph.edgeWeights(), m_copyTerminals);
1479 
1480  NodeArray<edge> minCostLeavingRegionEdge1(m_copyGraph, nullptr);
1481  NodeArray<edge> minCostLeavingRegionEdge2(m_copyGraph, nullptr);
1482 
1483  // populate minCostLeavingRegions{1,2}
1484  for (edge e : m_copyGraph.edges) {
1485  auto updateMinCostLeavingRegionsFor = [&](node seed) {
1486  if (minCostLeavingRegionEdge1[seed] == nullptr
1487  || m_copyGraph.weight(minCostLeavingRegionEdge1[seed]) > m_copyGraph.weight(e)) {
1488  minCostLeavingRegionEdge2[seed] = minCostLeavingRegionEdge1[seed];
1489  minCostLeavingRegionEdge1[seed] = e;
1490  } else
1491  if (minCostLeavingRegionEdge2[seed] == nullptr
1492  || m_copyGraph.weight(minCostLeavingRegionEdge2[seed]) > m_copyGraph.weight(e)) {
1493  minCostLeavingRegionEdge2[seed] = e;
1494  }
1495  };
1496  const node x = e->source(), y = e->target();
1497  const node seedX = voronoiRegions.seed(x), seedY = voronoiRegions.seed(y);
1498  if (seedX != seedY) { // e is a link between Voronoi regions
1499  // update minCostLeavingRegions for both x and y
1500  updateMinCostLeavingRegionsFor(seedX);
1501  updateMinCostLeavingRegionsFor(seedY);
1502  }
1503  }
1504 
1505  List<edge> edgesToBeAddedInSolution;
1506  EdgeArray<bool> willBeAddedInSolution(m_copyGraph, false);
1507  for (node terminal : m_copyTerminals) {
1508  if (minCostLeavingRegionEdge2[terminal] == nullptr) {
1509  continue;
1510  }
1511  // XXX: hm, is that smart? If there is no second shortest edge, then the first shortest edge belongs to the solution, doesn't it?
1512 
1513  const edge e1 = minCostLeavingRegionEdge1[terminal];
1514  const node x = e1->source(), y = e1->target();
1515  if (m_eps.geq(m_copyGraph.weight(minCostLeavingRegionEdge2[terminal]),
1516  voronoiRegions.distance(x) + m_copyGraph.weight(e1) + voronoiRegions.distance(y))
1517  && !willBeAddedInSolution[e1]) {
1518  edgesToBeAddedInSolution.pushBack(e1);
1519  willBeAddedInSolution[e1] = true;
1520  }
1521  }
1522 
1523  return addEdgesToSolution(edgesToBeAddedInSolution);
1524 }
1525 
1526 template<typename T>
1528 {
1529  OGDF_ASSERT(m_copyTerminals.size() > 1);
1530 
1531  // compute the Voronoi regions
1532  Voronoi<T> voronoiRegions(m_copyGraph, m_copyGraph.edgeWeights(), m_copyTerminals);
1533 
1534  // compute the radius for each terminal
1535  terminalRadius.init(m_copyGraph, std::numeric_limits<T>::max());
1536  for (node v : m_copyGraph.nodes) {
1537  node seedV = voronoiRegions.seed(v);
1538  T distanceToSeedV = voronoiRegions.distance(v);
1539 
1540  for(adjEntry adj : v->adjEntries) {
1541  edge e = adj->theEdge();
1542  node adjacentNode = e->opposite(v);
1543 
1544  if (voronoiRegions.seed(adjacentNode) != seedV) {
1545  Math::updateMin(terminalRadius[seedV], distanceToSeedV + m_copyGraph.weight(e));
1546  }
1547  }
1548  }
1549 }
1550 
1551 template<typename T>
1552 bool SteinerTreePreprocessing<T>::deleteNodesAboveUpperBound(const NodeArray<T> &lowerBoundWithNode, const T upperBound)
1553 {
1554  bool changed = false;
1555  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1556  nextV = v->succ();
1557  if (m_eps.greater(lowerBoundWithNode[v], upperBound)) {
1558  OGDF_ASSERT(!m_copyIsTerminal[v]);
1559  m_copyGraph.delNode(v);
1560  changed = true;
1561  }
1562  }
1563  return changed;
1564 }
1565 
1566 template<typename T>
1568  OGDF_ASSERT(!m_copyGraph.empty());
1569  if (m_copyTerminals.size() <= 1) {
1570  return false;
1571  }
1572 
1573  OGDF_ASSERT(isConnected(m_copyGraph));
1574 
1575  NodeArray<T> lowerBoundWithNode(m_copyGraph, std::numeric_limits<T>::lowest());
1576 
1577  NodeArray<List<std::pair<node, T>>> closestTerminals;
1578  computeClosestKTerminals(3, closestTerminals);
1579 
1580  // Update the lowerbound of the cost of a Steiner tree containing one particular node
1581  // as explained in [PV01, page 278, Observation 3.5]
1582  const T radiusSum = computeRadiusSum();
1583  for (node v : m_copyGraph.nodes) {
1584  if (m_copyIsTerminal[v]) {
1585  continue;
1586  }
1587 
1588  if (closestTerminals[v].size() < 2) {
1589  lowerBoundWithNode[v] = std::numeric_limits<T>::max();
1590  continue;
1591  }
1592 
1593  std::pair<node, T> closestTerminalPair1 = *(closestTerminals[v].get(0)), closestTerminalPair2 = *(closestTerminals[v].get(1));
1594  T distanceToClosestTerminal1 = closestTerminalPair1.second, distanceToClosestTerminal2 = closestTerminalPair2.second;
1595 
1596  Math::updateMax(lowerBoundWithNode[v], distanceToClosestTerminal1 + distanceToClosestTerminal2 + radiusSum);
1597  }
1598 
1599  // Compute lower bound for edges, see [PV01, page 278, Observation 3.5]
1600  EdgeArray<T> lowerBoundWithEdge(m_copyGraph, 0);
1601  for (edge e : m_copyGraph.edges) {
1602  node x = e->source(), y = e->target();
1603 
1604  T distanceToClosestTerminalX = (*closestTerminals[x].begin()).second;
1605  T distanceToClosestTerminalY = (*closestTerminals[y].begin()).second;
1606 
1607  Math::updateMax(lowerBoundWithEdge[e], m_copyGraph.weight(e) + distanceToClosestTerminalX + distanceToClosestTerminalY + radiusSum);
1608  }
1609 
1610  // Update the lowerbound of the cost of a Steiner tree containing one particular node
1611  // as explained in [PV01, pages 279-280, Observation 3.8]
1612  Graph auxiliaryGraph;
1613  NodeArray<node> terminalInAuxiliaryGraph(m_copyGraph, nullptr);
1614  for (node terminal : m_copyTerminals) {
1615  node newAuxiliaryNode = auxiliaryGraph.newNode();
1616  terminalInAuxiliaryGraph[terminal] = newAuxiliaryNode;
1617  }
1618 
1619  EdgeArray<T> initialEdgeWeight(m_copyGraph);
1620  for (edge e : m_copyGraph.edges) {
1621  initialEdgeWeight[e] = m_copyGraph.weight(e);
1622  }
1623  Voronoi<T> voronoiRegions(m_copyGraph, initialEdgeWeight, m_copyTerminals);
1624 
1625  std::unordered_map<NodePair, edge, steiner_tree::UnorderedNodePairHasher, steiner_tree::UnorderedNodePairEquality> edgeBetweenNodes;
1626  EdgeArray<T> edgeWeight(auxiliaryGraph, std::numeric_limits<T>::max());
1627  for (edge e : m_copyGraph.edges) {
1628  node x = e->source(), y = e->target();
1629  node seedX = voronoiRegions.seed(x), seedY = voronoiRegions.seed(y);
1630  if (seedX == seedY) {
1631  continue;
1632  }
1633 
1634  auto pair = NodePair(terminalInAuxiliaryGraph[seedX], terminalInAuxiliaryGraph[seedY]);
1635  if (edgeBetweenNodes.find(pair) == edgeBetweenNodes.end()) {
1636  edgeBetweenNodes[pair] = auxiliaryGraph.newEdge(terminalInAuxiliaryGraph[seedX], terminalInAuxiliaryGraph[seedY]);
1637  }
1638  edge auxiliaryEdge = edgeBetweenNodes[pair];
1639  Math::updateMin(edgeWeight[auxiliaryEdge], min(voronoiRegions.distance(x), voronoiRegions.distance(y)) + m_copyGraph.weight(e));
1640  }
1641 
1642  EdgeArray<bool> isInTree(auxiliaryGraph, false);
1643  T minimumSpanningTreeCost = computeMinST(auxiliaryGraph, edgeWeight, isInTree);
1644  T longestEdgeCost = std::numeric_limits<T>::lowest();
1645  for (edge e : auxiliaryGraph.edges) {
1646  if (isInTree[e]) {
1647  Math::updateMax(longestEdgeCost, edgeWeight[e]);
1648  }
1649  }
1650 
1651  for (node v : m_copyGraph.nodes) {
1652  if (m_copyIsTerminal[v] || closestTerminals[v].size() < 2) {
1653  continue;
1654  }
1655 
1656  std::pair<node, T> closestTerminalPair1 = *(closestTerminals[v].get(0)), closestTerminalPair2 = *(closestTerminals[v].get(1));
1657  T distanceToClosestTerminal1 = closestTerminalPair1.second, distanceToClosestTerminal2 = closestTerminalPair2.second;
1658 
1659  Math::updateMax(lowerBoundWithNode[v], minimumSpanningTreeCost - longestEdgeCost + distanceToClosestTerminal1 + distanceToClosestTerminal2);
1660  }
1661 
1662  return deleteNodesAboveUpperBound(lowerBoundWithNode, upperBound)
1663  || deleteEdgesAboveUpperBound(lowerBoundWithEdge, upperBound);
1664 }
1665 
1666 template<typename T>
1667 bool SteinerTreePreprocessing<T>::dualAscentBasedTest(int repetitions, T upperBound) {
1668  OGDF_ASSERT(!m_copyGraph.empty());
1669  bool changed = false;
1670  if (m_copyTerminals.size() > 1) {
1671  NodeArray<T> lowerBoundNodes;
1672  EdgeArray<T> lowerBoundEdges;
1674  alg.setRepetitions(repetitions);
1675  alg.call(m_copyGraph, m_copyTerminals, lowerBoundNodes, lowerBoundEdges);
1676 
1677  changed |= deleteNodesAboveUpperBound(lowerBoundNodes, upperBound);
1678  changed |= deleteEdgesAboveUpperBound(lowerBoundEdges, upperBound);
1679  }
1680  return changed;
1681 }
1682 
1683 template<typename T>
1684 bool SteinerTreePreprocessing<T>::deleteEdgesAboveUpperBound(const EdgeArray<T> &lowerBoundWithEdge, const T upperBound)
1685 {
1686  bool changed = false;
1687  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1688  nextE = e->succ();
1689  if (m_eps.greater(lowerBoundWithEdge[e], upperBound)) {
1690  m_copyGraph.delEdge(e);
1691  changed = true;
1692  }
1693  }
1694  return changed;
1695 }
1696 
1697 template<typename T>
1699 {
1700  NodeArray<T> terminalRadius;
1701  computeRadiusOfTerminals(terminalRadius);
1702 
1703  // instead of sorting, we can simply ignore the two largest radii
1704  T radiusSum = T();
1705  T largestRadius1 = std::numeric_limits<T>::lowest(), largestRadius2 = std::numeric_limits<T>::lowest();
1706  for (node terminal : m_copyTerminals) {
1707  radiusSum += terminalRadius[terminal];
1708 
1709  if (terminalRadius[terminal] > largestRadius1) {
1710  largestRadius2 = largestRadius1;
1711  largestRadius1 = terminalRadius[terminal];
1712  } else {
1713  if (terminalRadius[terminal] > largestRadius2) {
1714  largestRadius2 = terminalRadius[terminal];
1715  }
1716  }
1717  }
1718  radiusSum -= largestRadius1 + largestRadius2;
1719  return radiusSum;
1720 }
1721 
1722 template<typename T>
1723 bool SteinerTreePreprocessing<T>::reachabilityTest(int maxDegreeTest, const int k) {
1724  OGDF_ASSERT(!m_copyGraph.empty());
1725  OGDF_ASSERT(isSimpleUndirected(m_copyGraph));
1726  OGDF_ASSERT(isConnected(m_copyGraph));
1727  bool changed = false;
1728  if (maxDegreeTest <= 0) {
1729  maxDegreeTest = m_copyGraph.numberOfNodes();
1730  }
1731 
1732  EdgeWeightedGraphCopy<T> *approximatedSteinerTree;
1733  T upperBoundCost = computeMinSteinerTreeUpperBound(approximatedSteinerTree);
1734 
1735  NodeArray<bool> isInUpperBoundTree(m_copyGraph, false);
1736  for (node v : approximatedSteinerTree->nodes) {
1737  isInUpperBoundTree[approximatedSteinerTree->original(v)] = true;
1738  }
1739  delete approximatedSteinerTree;
1740 
1741  // Initialize tprime and its hpd decomposition used for partially not adding useless edges during nodes' deletion
1742  EdgeWeightedGraphCopy<T> tprime;
1743  steiner_tree::constructTerminalSpanningTreeUsingVoronoiRegions(tprime, m_copyGraph, m_copyTerminals);
1744  OGDF_ASSERT(!tprime.empty());
1745 
1746  NodeArray<List<std::pair<node,T>>> closestTerminals;
1747  computeClosestKTerminals(k, closestTerminals);
1748 
1749  steiner_tree::HeavyPathDecomposition<T> tprimeHPD(tprime);
1750 
1751  // check which nodes can be deleted
1752  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1753  nextV = v->succ();
1754 
1755  if (isInUpperBoundTree[v]
1756  || v->degree() > maxDegreeTest) {
1757  continue;
1758  }
1759 
1760  // compute v's farthest and closest terminals
1761  Dijkstra<T> dijkstra;
1762 
1763  NodeArray<T> distance(m_copyGraph);
1764  NodeArray<edge> predecessor(m_copyGraph, nullptr);
1765  dijkstra.call(m_copyGraph, m_copyGraph.edgeWeights(), v, predecessor, distance);
1766 
1767  // compute first, second nearest terminals and farthest terminal
1768  node farthestTerminal = nullptr;
1769  T distanceToFarthestTerminal(0);
1770  T distanceToClosestTerminal1 = std::numeric_limits<T>::max(),
1771  distanceToClosestTerminal2 = std::numeric_limits<T>::max();
1772  for (node terminal : m_copyTerminals) {
1773  if (distanceToFarthestTerminal < distance[terminal]) {
1774  farthestTerminal = terminal;
1775  distanceToFarthestTerminal = distance[terminal];
1776  }
1777 
1778  if (distanceToClosestTerminal1 > distance[terminal]) {
1779  distanceToClosestTerminal2 = distanceToClosestTerminal1;
1780  distanceToClosestTerminal1 = distance[terminal];
1781  } else {
1782  if (distanceToClosestTerminal2 > distance[terminal]) {
1783  distanceToClosestTerminal2 = distance[terminal];
1784  }
1785  }
1786  }
1787 
1788  if (predecessor[farthestTerminal] == nullptr // is not in the same component with the terminals
1789  || distanceToClosestTerminal2 == std::numeric_limits<T>::max() // cannot reach at least 2 terminals, must be deleted
1790  || m_eps.geq(distanceToFarthestTerminal + distanceToClosestTerminal1 + distanceToClosestTerminal2, upperBoundCost)) {
1791  changed = true;
1792  // delete the node
1793  if (predecessor[farthestTerminal] != nullptr
1794  && distanceToClosestTerminal2 != std::numeric_limits<T>::max()
1795  && m_eps.less(distanceToFarthestTerminal + distanceToClosestTerminal1, upperBoundCost)) {
1796  // the deleted node has degree 2 -> replace it with edges
1797  deleteSteinerDegreeTwoNode(v, tprime, tprimeHPD, closestTerminals);
1798  } else {
1799  // just delete the node
1800  m_copyGraph.delNode(v);
1801  }
1802  }
1803  }
1804 
1805  return changed;
1806 }
1807 
1808 template<typename T>
1809 template<typename LAMBDA>
1810 void SteinerTreePreprocessing<T>::computeOptimalTerminals(node v, LAMBDA dist, node &optimalTerminal1, node &optimalTerminal2, NodeArray<T> &distance) const
1811 {
1812  // run Dijkstra starting from v
1813  Dijkstra<T> dijkstra;
1814 
1815  distance.init(m_copyGraph);
1816  NodeArray<edge> predecessor(m_copyGraph, nullptr);
1817  dijkstra.call(m_copyGraph, m_copyGraph.edgeWeights(), v, predecessor, distance);
1818 
1819  for (node terminal : m_copyTerminals) {
1820  if (predecessor[terminal] == nullptr) {
1821  continue;
1822  }
1823 
1824  if (optimalTerminal1 == nullptr
1825  || dist(optimalTerminal1, distance) > dist(terminal, distance)) {
1826  optimalTerminal2 = optimalTerminal1;
1827  optimalTerminal1 = terminal;
1828  } else {
1829  if (optimalTerminal2 == nullptr
1830  || dist(optimalTerminal2, distance) > dist(terminal, distance)) {
1831  optimalTerminal2 = terminal;
1832  }
1833  }
1834  }
1835  OGDF_ASSERT(optimalTerminal1 != nullptr);
1836  OGDF_ASSERT(optimalTerminal2 != nullptr);
1837  OGDF_ASSERT(optimalTerminal1 != optimalTerminal2);
1838 }
1839 
1840 template<typename T>
1842  OGDF_ASSERT(!m_copyGraph.empty());
1843  if (m_copyTerminals.size() <= 2) {
1844  return false;
1845  }
1846 
1847  // get the upper bound
1848  EdgeWeightedGraphCopy<T> *approximatedSteinerTree;
1849  const T upperBoundCost = computeMinSteinerTreeUpperBound(approximatedSteinerTree);
1850 
1851  NodeArray<bool> isInUpperBoundTree(m_copyGraph, false);
1852  for (node v : approximatedSteinerTree->nodes) {
1853  isInUpperBoundTree[approximatedSteinerTree->original(v)] = true;
1854  }
1855  delete approximatedSteinerTree;
1856 
1857  T cK = T();
1858  NodeArray<T> minCostOfAdjacentEdge(m_copyGraph, std::numeric_limits<T>::max());
1859  for (node terminal : m_copyTerminals) {
1860  for (adjEntry adj : terminal->adjEntries) {
1861  Math::updateMin(minCostOfAdjacentEdge[terminal], m_copyGraph.weight(adj->theEdge()));
1862  }
1863  cK += minCostOfAdjacentEdge[terminal];
1864  }
1865  auto dist = [&minCostOfAdjacentEdge](node terminal, const NodeArray<T> &distance) {
1866  return distance[terminal] - minCostOfAdjacentEdge[terminal];
1867  };
1868 
1869  List<node> delNodes;
1870  std::set<edge> delEdges;
1871  NodeArray<T> vDistance;
1872  NodeArray<T> wDistance;
1873  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1874  nextV = v->succ();
1875 
1876  if (isInUpperBoundTree[v]) {
1877  continue;
1878  }
1879 
1880  // compute its optimal terminals
1881  node vOptimalTerminal1 = nullptr, vOptimalTerminal2 = nullptr;
1882  computeOptimalTerminals(v, dist, vOptimalTerminal1, vOptimalTerminal2, vDistance);
1883 
1884  // check whether it can be deleted
1885  if (m_eps.geq(cK + dist(vOptimalTerminal1, vDistance) + dist(vOptimalTerminal2, vDistance), upperBoundCost)) {
1886  delNodes.pushBack(v);
1887  } else { // it is not deleted, perform the edge test
1888  for (adjEntry adj = v->firstAdj(), adjNext; adj; adj = adjNext) {
1889  adjNext = adj->succ();
1890  node w = adj->twinNode();
1891  if (m_copyIsTerminal[w]) {
1892  continue;
1893  }
1894  node wOptimalTerminal1 = nullptr, wOptimalTerminal2 = nullptr;
1895  computeOptimalTerminals(w, dist, wOptimalTerminal1, wOptimalTerminal2, wDistance);
1896 
1897  node vOptimalTerminal = vOptimalTerminal1;
1898  node wOptimalTerminal = wOptimalTerminal1;
1899  if (vOptimalTerminal == wOptimalTerminal) {
1900  // the nearest terminals to v and w are the same, but they have to be
1901  // different. Obtain the minimum choice such that they are different.
1902  if (m_eps.leq(
1903  dist(vOptimalTerminal1, vDistance) + dist(wOptimalTerminal2, wDistance),
1904  dist(vOptimalTerminal2, vDistance) + dist(wOptimalTerminal1, wDistance))) {
1905  wOptimalTerminal = wOptimalTerminal2;
1906  } else {
1907  vOptimalTerminal = vOptimalTerminal2;
1908  }
1909  }
1910  OGDF_ASSERT(vOptimalTerminal != wOptimalTerminal);
1911  if (m_eps.geq(cK + dist(vOptimalTerminal, vDistance) + dist(wOptimalTerminal, wDistance) + m_copyGraph.weight(adj->theEdge()), upperBoundCost)) {
1912  delEdges.insert(adj->theEdge());
1913  }
1914  }
1915  }
1916  }
1917 
1918  bool changed = false;
1919  for (edge e : delEdges) {
1920  m_copyGraph.delEdge(e);
1921  changed = true;
1922  }
1923  for (node v : delNodes) {
1924  m_copyGraph.delNode(v);
1925  changed = true;
1926  }
1927  return changed;
1928 }
1929 
1930 }
node target() const
Returns the target node of the edge.
Definition: Graph_d.h:328
void findClosestNonTerminals(node source, List< node > &reachedNodes, NodeArray< T > &distance, T maxDistance, int expandedEdges) const
Heuristic approach to computing the closest non-terminals for one node, such that there is no termina...
void clear()
Removes all elements from the list.
Definition: List.h:1451
static bool repeat(std::function< bool()> f)
Auxiliary function: Repeats a function until it returns false (used for iteratively applying reductio...
The parameterized class Array implements dynamic arrays of type E.
Definition: Array.h:200
T call(const EdgeWeightedGraph< T > &graph, const List< node > &terminals)
Calls the algorithm and returns the lower bound.
edge theEdge() const
Returns the edge associated with this adjacency entry.
Definition: Graph_d.h:96
std::enable_if< std::is_integral< T >::value, bool >::type leq(const T &x, const T &y) const
Compare if x is LEQ than y for integral types.
Definition: EpsilonTest.h:85
bool deleteNodesAboveUpperBound(const NodeArray< T > &lowerBoundWithNode, const T upperBound)
Deletes the nodes whose lowerBoundWithNode exceeds upperBound.
node copy(node v) const
Returns the node in the graph copy corresponding to v.
Definition: GraphCopy.h:335
ListIteratorBase< E, isConst, isReverse > succ() const
Returns successor iterator.
Definition: List.h:145
Dijkstra&#39;s single source shortest path algorithm.
Definition: Dijkstra.h:52
virtual void clear()
Removes all nodes and all edges from the graph.
node newNode(node vOrig)
Creates a new node in the graph copy with original node vOrig.
Definition: GraphCopy.h:412
SteinerTreePreprocessing(const EdgeWeightedGraph< T > &wg, const List< node > &terminals, const NodeArray< bool > &isTerminal)
Implementation of a dual-ascent-based lower bound heuristic for Steiner tree problems.
void init()
Reinitializes the array. Associates the array with no graph.
Definition: EdgeArray.h:283
std::enable_if< std::is_integral< T >::value, bool >::type equal(const T &x, const T &y) const
Compare if x is EQUAL to y for integral types.
Definition: EpsilonTest.h:113
iterator pushBack(const E &x)
Adds element x at the end of the list.
Definition: List.h:1373
Data type for general directed graphs (adjacency list representation).
Definition: Graph_d.h:492
virtual void delNode(node v)
Removes node v and all incident edges from the graph.
void markSuccessors(node currentNode, const Voronoi< T > &voronoiRegions, NodeArray< bool > &isSuccessorOfMinCostEdge) const
Mark successors of currentNode in its shortest-path tree in voronoiRegions.
void init()
Reinitializes the array. Associates the array with no graph.
Definition: NodeArray.h:255
T computeMinST(const Graph &G, const EdgeArray< T > &weight, EdgeArray< bool > &isInTree)
Computes a minimum spanning tree using Prim&#39;s algorithm.
bool leastCostTest()
Performs a least cost test [DV89] computing the whole shortest path matrix.
void findTwoMinimumCostEdges(node v, edge &first, edge &second) const
Finds the first and second smallest edges incident to v.
virtual T call(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal, EdgeWeightedGraphCopy< T > *&finalSteinerTree)
Calls the Steiner tree algorithm for nontrivial cases but handles trivial cases directly.
Serves as an interface for various methods to compute or approximate minimum Steiner trees on undirec...
int degree() const
Returns the degree of the node (indegree + outdegree).
Definition: Graph_d.h:210
void call(const Graph &G, const EdgeArray< T > &weight, const List< node > &sources, NodeArray< edge > &predecessor, NodeArray< T > &distance, bool directed=false)
Calculates, based on the graph G with corresponding edge costs and source nodes, the shortest paths a...
Definition: Dijkstra.h:61
edge newEdge(node u, node v, T weight)
Definition of the ogdf::steiner_tree:HeavyPathDecomposition class template.
iterator begin()
Returns an iterator to the first element of the list.
Definition: List.h:352
This class implements preprocessing strategies for the Steiner tree problem.
void setWeight(const edge e, T weight)
const EdgeArray< T > & edgeWeights() const
node firstNode() const
Returns the first node in the list of all nodes.
Definition: Graph_d.h:618
void computeClosestKTerminals(const int k, NodeArray< List< std::pair< node, T >>> &closestTerminals) const
Computes for every non-terminal the closest k terminals such that there is no other terminal on the p...
virtual void delEdge(edge e)
Removes edge e from the graph.
Implementation of Mehlhorn&#39;s minimum Steiner tree 2(1-1/l)-approximation algorithm.
int index() const
Returns the index of the edge.
Definition: Graph_d.h:324
Implementation of the 2(1-1/l)-approximation algorithm for the minimum Steiner tree problem by Matsuy...
void makeSimple(Graph &G)
Removes all self-loops and all but one edge of each bundle of parallel edges.
void addNewEdge(edge e, const std::vector< node > &replacedNodes, const std::vector< edge > &replacedEdges, bool deleteReplacedElements)
The function is called after a new edge is added to the copy graph during the reductions.
bool deleteLeaves()
Deletes the leaves of the graph.
List< node > m_copyTerminals
The reduced form of terminals.
bool valid() const
Checks if the current subset is valid. If not, the subset is either not initialized or all subsets ha...
A class used by the unordered_maps inside the reductions.
void addNewNode(node v, const std::vector< node > &replacedNodes, const std::vector< edge > &replacedEdges, bool deleteReplacedElements)
Calls addNew() for a node.
node succ() const
Returns the successor in the list of all nodes.
Definition: Graph_d.h:218
int connectedComponents(const Graph &G, NodeArray< int > &component, List< node > *isolated=nullptr)
Computes the connected components of G and optionally generates a list of isolated nodes...
void computeOptimalTerminals(node v, LAMBDA dist, node &optimalTerminal1, node &optimalTerminal2, NodeArray< T > &distance) const
Compute first and second best terminals according to function dist.
Defines a queue for handling prioritized elements.
void deleteSteinerDegreeTwoNode(node v, const EdgeWeightedGraphCopy< T > &tprime, const steiner_tree::HeavyPathDecomposition< T > &tprimeHPD, const NodeArray< List< std::pair< node, T >>> &closestTerminals)
Deletes a node that is known to have degree 2 in at least one minimum Steiner tree.
Prioritized queue interface wrapper for heaps.
std::unique_ptr< MinSteinerTreeModule< T > > m_costUpperBoundAlgorithm
Algorithm used for computing the upper bound for the cost of a minimum Steiner tree.
void popBack()
Removes the last element from the list.
Definition: List.h:1424
bool nearestVertexTest()
Nearest vertex test using Voronoi regions [DV89, PV01].
bool longEdgesTest()
Long-Edges test from [DV89].
std::enable_if< std::is_integral< T >::value, bool >::type less(const T &x, const T &y) const
Compare if x is LESS than y for integral types.
Definition: EpsilonTest.h:57
edge searchEdge(node v, node w, bool directed=false) const
Searches and returns an edge connecting nodes v and w in time O( min(deg(v ), deg(w )))...
NodeArray< int > m_nodeSonsListIndex
It contains for each node an index i.
void del(iterator it)
Removes it from the list.
Definition: List.h:1437
T weight(const edge e) const
const List< node > & getReducedTerminals() const
Returns the list of the terminals corresponding to the reduced graph.
bool dualAscentBasedTest(int repetitions=1)
Like dualAscentBasedTest(int repetitions, T upperBound) but the upper bound is computed by computeMin...
const List< node > & m_origTerminals
Const reference to the original list of terminals.
edge newEdge(node v, node w, T weight)
bool reduceFast()
Apply fast reductions iteratively (includes trivial reductions).
void append(const E &x)
Adds x at the end of queue.
Definition: BoundedQueue.h:177
void createEmpty(const Graph &wG)
void updateMin(T &min, const T &newValue)
Stores the minimum of min and newValue in min.
Definition: Math.h:101
T computeMinSteinerTreeUpperBound(EdgeWeightedGraphCopy< T > *&finalSteinerTree) const
An implementation of the heavy path decomposition on trees.
internal::GraphObjectContainer< EdgeElement > edges
The container containing all edge objects.
Definition: Graph_d.h:568
const NodeArray< bool > & getReducedIsTerminal() const
Returns the NodeArray<bool> isTerminal corresponding to the reduced graph.
int numberOfEdges() const
Returns the number of edges in the graph.
Definition: Graph_d.h:601
Definition of the ogdf::SteinerTreeLowerBoundDualAscent class template.
Computes Voronoi regions in an edge-weighted graph.
Definition: Voronoi.h:45
const E & topElement() const
Returns the topmost element in the queue.
A class used by the unordered_maps inside the reductions.
iterator pushFront(const E &x)
Adds element x at the beginning of the list.
Definition: List.h:1360
EdgeWeightedGraph< T > m_copyGraph
Copy of the original graph; this copy will actually be reduced.
void begin(int low, int high)
Initializes the SubsetEnumerator to enumerate subsets of cardinalities from low to high...
void addToSolution(const int listIndex, Array< bool, int > &isInSolution) const
Helper method for computeOriginalSolution.
edge firstEdge() const
Returns the first edge in the list of all edges.
Definition: Graph_d.h:623
INDEX size() const
Returns the size (number of elements) of the array.
Definition: Array.h:282
void computeRadiusOfTerminals(NodeArray< T > &terminalRadius) const
Compute radius of terminals.
const_reference front() const
Returns a const reference to the first element.
Definition: List.h:274
bool terminalDistanceTest()
Simple terminal distance test [PV01].
bool shortLinksTest()
Short links test using Voronoi regions [PV01].
node contract(edge e)
Contracts edge e while preserving the order of adjacency entries.
Enumerator for k-subsets of a given type.
bool lowerBoundBasedTest()
Like lowerBoundBasedTest(T upperBound) but the upper bound is computed by computeMinSteinerTreeUpperB...
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.
node seed(node v) const
Returns the Voronoi seed of node v.
Definition: Voronoi.h:103
T m_costAlreadyInserted
The cost of the already inserted in solution edges.
bool addEdgesToSolution(const List< edge > &edgesToBeAddedInSolution)
The function adds a set of edges in the solution.
T getBottleneckSteinerDistance(node x, node y) const
computes in the bottleneck distance between terminals x and y
bool PTmTest(const int k=3)
"Paths with many terminals" test, efficient on paths with many terminals.
bool isLoopFree(const Graph &G)
Returns true iff G contains no self-loop.
bool reduceFastAndDualAscent()
Apply fast reductions and the dual-ascent-based tests iteratively.
bool NTDkTest(const int maxTestedDegree=5, const int k=3)
Non-terminals of degree k test [DV89, PV01].
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
bool reduceTrivial()
Apply trivial (hence amazingly fast) reductions iteratively, that is degree2Test(), makeSimple(), deleteLeaves().
T computeRadiusSum() const
Compute the sum of all radii except the two largest.
T distance(node v) const
Returns the distance between v and its Voronoi seed.
Definition: Voronoi.h:97
adjEntry lastAdj() const
Returns the last entry in the adjacency list.
Definition: Graph_d.h:215
void setRepetitions(int num)
Sets the number of repeated calls to the lower bound algorithm (runs with different roots) ...
Class for the representation of nodes.
Definition: Graph_d.h:169
void computeOriginalSolution(const EdgeWeightedGraphCopy< T > &reducedGraphSolution, EdgeWeightedGraphCopy< T > &correspondingOriginalSolution)
Computes the solution for the original graph, given a solution on the reduction.
Encapsulates a pointer to a list element.
Definition: List.h:42
std::enable_if< std::is_integral< T >::value, bool >::type greater(const T &x, const T &y) const
Compare if x is GREATER than y for integral types.
Definition: EpsilonTest.h:169
bool reachabilityTest(int maxDegreeTest=0, const int k=3)
Performs a reachability test [DV89].
node opposite(node v) const
Returns the adjacent node different from v.
Definition: Graph_d.h:338
const NodeArray< bool > & m_origIsTerminal
Const reference to the original isTerminal.
void addNew(TWhat x, const std::vector< node > &replacedNodes, const std::vector< edge > &replacedEdges, bool deleteReplacedElements, TWhatArray &whatSonsListIndex)
Update internal data structures to let a (new) node or edge represent replaced nodes and/or edges...
const Graph & original() const
Returns a reference to the original graph.
Definition: GraphCopy.h:286
bool degree2Test()
deletes degree-2 nodes and replaces them with one edge with the adjacent edges&#39; sum ...
void floydWarshall(NodeArray< NodeArray< T >> &shortestPath) const
Applies the Floyd-Warshall algorithm on the m_copyGraph. The shortestPath matrix has to be already in...
This class implements the minimum Steiner tree 2-approximation algorithm by Takahashi and Matsuyama w...
bool isSimpleUndirected(const Graph &G)
Returns true iff G contains neither self-loops nor undirected parallel edges.
NodeArray< bool > m_copyIsTerminal
The reduced form of isTerminal.
const EdgeWeightedGraph< T > & m_origGraph
Const reference to the original graph.
std::vector< std::vector< int > > m_sonsList
List with lists (corresponding to nodes and containing the indexes of their sons) ...
int index() const
Returns the (unique) node index.
Definition: Graph_d.h:203
EdgeArray< int > m_edgeSonsListIndex
See m_nodeSonsListIndex but for edges.
edge succ() const
Returns the successor in the list of all edges.
Definition: Graph_d.h:353
bool empty() const
Checks whether the queue is empty.
bool deleteComponentsWithoutTerminals()
Deletes connected components with no terminals.
void next()
Obtains 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:148
int size() const
Returns the number of elements in the list.
Definition: List.h:1312
bool makeSimple()
Deletes parallel edges keeping only the minimum cost one, and deletes self-loops. ...
T constructTerminalSpanningTreeUsingVoronoiRegions(EdgeWeightedGraphCopy< T > &terminalSpanningTree, const EdgeWeightedGraph< T > &graph, const List< node > &terminals)
iterator begin()
Returns an iterator to the first entry in the node array.
Definition: NodeArray.h:215
int maxNodeIndex() const
Returns the largest used node index.
Definition: Graph_d.h:604
void recomputeTerminalsList()
Used by reductions to recompute the m_copyTerminals list, according to m_copyIsTerminal; useful when ...
node predecessor(node v) const
Returns the nearest node to v on the shortest path to its Voronoi seed.
Definition: Voronoi.h:90
node source() const
Returns the source node of the edge.
Definition: Graph_d.h:326
T solve(MinSteinerTreeModule< T > &mst, EdgeWeightedGraphCopy< T > *&finalSteinerTree)
A shortcut to get the solution of a reduced instance.
bool cutReachabilityTest()
Performs a cut reachability test [DV89].
T computeBottleneckDistance(node x, node y, const EdgeWeightedGraphCopy< T > &tprime, const steiner_tree::HeavyPathDecomposition< T > &tprimeHPD, const NodeArray< List< std::pair< node, T >>> &closestTerminals) const
Heuristic computation [PV01] of the bottleneck Steiner distance between two nodes in a graph...
int size() const
Returns the cardinality of the subset.
The namespace for all OGDF objects.
Declaration and implementation of bounded queue class.
int maxEdgeIndex() const
Returns the largest used edge index.
Definition: Graph_d.h:606
std::enable_if< std::is_integral< T >::value, bool >::type geq(const T &x, const T &y) const
Compare if x is GEQ to y for integral types.
Definition: EpsilonTest.h:141
bool deleteEdgesAboveUpperBound(const EdgeArray< T > &lowerBoundWithEdge, const T upperBound)
Deletes the edges whose lowerBoundWithEdge exceeds upperBound.
int numberOfNodes() const
Returns the number of nodes in the graph.
Definition: Graph_d.h:598
Handle push(const E &element, const P &priority)
Pushes a new element with the respective priority to the queue.
node newNode()
Creates a new node and returns it.
void updateMax(T &max, const T &newValue)
Stores the maximum of max and newValue in max.
Definition: Math.h:93
internal::GraphObjectContainer< NodeElement > nodes
The container containing all node objects.
Definition: Graph_d.h:565
adjEntry firstAdj() const
Returns the first entry in the adjaceny list.
Definition: Graph_d.h:213
bool isConnected(const Graph &G)
Returns true iff G is connected.
ListConstIterator< E > search(const E &e) const
Scans the list for the specified element and returns an iterator to the first occurrence in the list...
Definition: List.h:1118
void computeShortestPathMatrix(NodeArray< NodeArray< T >> &shortestPath) const
Computes the shortest path matrix corresponding to the m_copyGraph.
void shuffleReducedTerminals()
Shuffles the list of reduced terminals. This can have an effect on some tests.
A class that allows to enumerate k-subsets.
bool empty() const
Returns true iff the list is empty.
Definition: List.h:256
bool empty() const
Returns true iff the graph is empty, i.e., contains no nodes.
Definition: Graph_d.h:595
The parameterized class BoundedQueue implements queues with bounded size.
Definition: BoundedQueue.h:46
Class for adjacency list elements.
Definition: Graph_d.h:79
void permute()
Randomly permutes the elements in the list.
Definition: List.h:1226
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:41
bool dualAscentBasedTest(int repetitions, T upperBound)
Like lowerBoundBasedTest(T upperBound) but uses ogdf::SteinerTreeLowerBoundDualAscent to compute lowe...
internal::GraphObjectContainer< AdjElement > adjEntries
The container containing all entries in the adjacency list of this node.
Definition: Graph_d.h:200