Open
Graph Drawing
Framework

 v. 2020.02 (Catalpa)
 

MinSteinerTreeShore.h
Go to the documentation of this file.
1 
33 #pragma once
34 
35 // enable this to print messages
36 // for all branches (edge inclusion or exclusion)
37 // additionally a SVG image is generated for each
38 // recursion depth
39 //#define OGDF_MINSTEINERTREE_SHORE_LOGGING
40 
41 #include <memory>
42 
43 #include <ogdf/basic/List.h>
44 #include <ogdf/basic/EdgeArray.h>
45 #include <ogdf/basic/NodeArray.h>
46 #include <ogdf/basic/NodeSet.h>
49 
50 namespace ogdf {
51 
62 template<typename T>
64 public:
65 
66  MinSteinerTreeShore() : MAX_WEIGHT(std::numeric_limits<T>::max()) {};
67  virtual ~MinSteinerTreeShore() {};
68 
69 protected:
85  virtual T computeSteinerTree(const EdgeWeightedGraph<T> &G, const List<node> &terminals, const NodeArray<bool> &isTerminal,
86  EdgeWeightedGraphCopy<T> *&finalSteinerTree) override;
87 
88  const T MAX_WEIGHT;
89 private:
92 
94  std::unique_ptr<NodeSet<>> m_terminals;
100 
109  bool validateMapping() const;
110 
119  T weightOf(edge e) const;
120 
137  T bnbInternal(T prevCost, List<edge> &currentEdges);
138 
146  edge deleteEdge(edge e);
147 
158  edge newEdge(node source, node target, const edge originalEdge);
159 
168  void moveSource(edge e, node v);
169 
178  void moveTarget(edge e, node v);
179 
191  void setTerminal(const node v, bool makeTerminal);
192 
205  bool isTerminal(const node v) const;
206 
219  void setEdgeLookup(const node u, const node v, const edge e);
220 
233  edge lookupEdge(const node u, const node v) const;
234 
248  edge determineBranchingEdge(T prevCost) const;
249 
257  T solve(List<edge> &chosenEdges);
258 
263  void printSVG();
264 };
265 
266 template<typename T>
268 {
269  m_originalGraph = &G;
270  m_originalTerminals = &terminals;
271 
273  m_graph = Graph();
274  m_mapping.init(m_graph);
275  m_terminals.reset(new NodeSet<>(m_graph));
276  int nodeCount = m_originalGraph->numberOfNodes();
277  m_edges = Array2D<edge>(0, nodeCount, 0, nodeCount, nullptr);
278 
279  NodeArray<node> copiedNodes(*m_originalGraph);
280 
281  for(node v : m_originalGraph->nodes) {
282  node copiedNode = m_graph.newNode();
283  copiedNodes[v] = copiedNode;
284  }
285 
286  for(edge e : m_originalGraph->edges) {
287  node source = copiedNodes[e->source()],
288  target = copiedNodes[e->target()];
289 
290  newEdge(source, target, e);
291  }
292 
293  for(node v : *m_originalTerminals) {
294  setTerminal(copiedNodes[v], true);
295  }
296 
297  List<edge> chosenEdges;
298  T result = solve(chosenEdges);
299 
300  finalSteinerTree = new EdgeWeightedGraphCopy<T>();
301  finalSteinerTree->createEmpty(*m_originalGraph);
302 
303  for(edge e : chosenEdges) {
304  node v = e->source();
305  node w = e->target();
306 
307  OGDF_ASSERT(v != nullptr);
308  OGDF_ASSERT(w != nullptr);
309  OGDF_ASSERT(e->graphOf() == m_originalGraph);
310  OGDF_ASSERT(v->graphOf() == m_originalGraph);
311  OGDF_ASSERT(w->graphOf() == m_originalGraph);
312 
313  if(finalSteinerTree->copy(v) == nullptr) {
314  finalSteinerTree->newNode(v);
315  }
316  if(finalSteinerTree->copy(w) == nullptr) {
317  finalSteinerTree->newNode(w);
318  }
319  finalSteinerTree->newEdge(e, m_originalGraph->weight(e));
320  }
321 
322  return result;
323 }
324 
325 template<typename T>
327 {
328  T result = MAX_WEIGHT;
329 
330  if(e != nullptr) {
331  OGDF_ASSERT(e->graphOf() == &m_graph);
332  OGDF_ASSERT(m_mapping[e] != nullptr);
333  OGDF_ASSERT(m_mapping[e]->graphOf() == m_originalGraph);
334  result = m_originalGraph->weight(m_mapping[e]);
335  }
336 
337  return result;
338 }
339 
340 template<typename T>
342 {
343  for (edge e : m_graph.edges) {
344  OGDF_ASSERT(m_mapping[e] != nullptr);
345  OGDF_ASSERT(m_mapping[e]->graphOf() == m_originalGraph);
346  }
347  return true;
348 }
349 
350 template<typename T>
352 {
353  return m_edges(u->index(), v->index());
354 }
355 
356 template<typename T>
357 void MinSteinerTreeShore<T>::setEdgeLookup(const node u, const node v, const edge e)
358 {
359  m_edges(u->index(), v->index()) =
360  m_edges(v->index(), u->index()) = e;
361 }
362 
363 template<typename T>
365 {
366  edge result = m_mapping[e];
367  setEdgeLookup(e->source(), e->target(), nullptr);
368  m_graph.delEdge(e);
369  e->~EdgeElement();
370 
371  return result;
372 }
373 
374 template<typename T>
376 {
377  edge result = m_graph.newEdge(source, target);
378  m_mapping[result] = e;
379  setEdgeLookup(source, target, result);
380 
381  return result;
382 }
383 
384 template<typename T>
386 {
387  OGDF_ASSERT(e != nullptr);
388  setEdgeLookup(e->source(), e->target(), nullptr);
389  setEdgeLookup(v, e->target(), e);
390  m_graph.moveSource(e, v);
391 }
392 
393 template<typename T>
395 {
396  OGDF_ASSERT(e != nullptr);
397  setEdgeLookup(e->source(), e->target(), nullptr);
398  setEdgeLookup(e->source(), v, e);
399  m_graph.moveTarget(e, v);
400 }
401 
402 template<typename T>
404 {
405  return m_terminals->isMember(v);
406 }
407 
408 template<typename T>
409 void MinSteinerTreeShore<T>::setTerminal(const node v, bool makeTerminal)
410 {
411  if (makeTerminal) {
412  m_terminals->insert(v);
413  } else {
414  m_terminals->remove(v);
415  }
416 }
417 
418 template<typename T>
420 {
422 
423  m_recursionDepth = 0;
424  List<edge> tmp;
425  T result = bnbInternal(0, tmp);
426 
427  for(edge e : m_chosenEdges) {
428  chosenEdges.pushFront(e);
429  }
430 
431  return result;
432 }
433 
434 template<typename T>
436 {
437  edge result = nullptr;
438  T maxPenalty = -1;
439 
440  // calculate penalties for nodes
441  T sumOfMinWeights = 0; // b
442  T sumOfMinTermWeights = 0; // c
443  T absoluteMinTermWeight = MAX_WEIGHT;
444  for(ListConstIterator<node> it = m_terminals->nodes().begin();
445  sumOfMinWeights < MAX_WEIGHT && it.valid();
446  ++it) {
447  const node t = *it;
448  T minTermWeight = MAX_WEIGHT,
449  minWeight = MAX_WEIGHT,
450  secondMinWeight = MAX_WEIGHT;
451  edge minEdge = nullptr;
452 
453  // investigate all edges of each terminal
454  // calculate lower boundary and find branching edge
455  for(adjEntry adj = t->firstAdj(); adj; adj = adj->succ()) {
456  edge e = adj->theEdge();
457  if(weightOf(e) < minWeight) {
458  secondMinWeight = minWeight;
459  minWeight = weightOf(e);
460  minEdge = e;
461  }
462  else {
463  if(weightOf(e) < secondMinWeight) {
464  secondMinWeight = weightOf(e);
465  }
466  }
467 
468  if(isTerminal(adj->twinNode()) && weightOf(e) < minTermWeight) {
469  minTermWeight = weightOf(e);
470  if(minTermWeight < absoluteMinTermWeight) {
471  absoluteMinTermWeight = minTermWeight;
472  }
473  }
474  }
475 
476  if(sumOfMinTermWeights < MAX_WEIGHT && minTermWeight < MAX_WEIGHT) {
477  sumOfMinTermWeights += minTermWeight;
478  }
479  else {
480  sumOfMinTermWeights = MAX_WEIGHT;
481  }
482  OGDF_ASSERT(absoluteMinTermWeight <= sumOfMinTermWeights);
483 
484  // is terminal isolated or has only one edge?
485  // if so we can break here
486  if(minWeight == MAX_WEIGHT ||
487  secondMinWeight == MAX_WEIGHT) {
488  result = minEdge;
489  if(minWeight == MAX_WEIGHT) {
490  sumOfMinWeights = MAX_WEIGHT;
491  }
492  } else {
493  sumOfMinWeights += minWeight;
494  // update branching edge if need be
495  T penalty = secondMinWeight - minWeight;
496  if(penalty > maxPenalty) {
497  maxPenalty = penalty;
498  result = minEdge;
499  }
500  }
501  }
502 
503  // compare bounds for this graph
504  if(result != nullptr) {
505  T maxCost = m_upperBound - prevCost;
506  if(sumOfMinTermWeights < MAX_WEIGHT) {
507  sumOfMinTermWeights -= absoluteMinTermWeight;
508  }
509  if(maxCost <= sumOfMinWeights && maxCost <= sumOfMinTermWeights) {
510  result = nullptr;
511  }
512  }
513 
514  return result;
515 }
516 
517 template<typename T>
519 {
520  T result = MAX_WEIGHT;
522 
523 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
524  printSVG();
525 #endif
526 
527  if(prevCost <= m_upperBound) {
528  if(m_terminals->size() < 2) {
529  // update currently chosen edges
530  if(prevCost != m_upperBound || m_chosenEdges.empty()) {
531 
532  m_chosenEdges = List<edge>(currentEdges);
533  }
534  // all terminals are connected
535  m_upperBound = prevCost;
536  result = prevCost;
537  }
538  else {
539  edge branchingEdge = determineBranchingEdge(prevCost);
540  T branchingEdgeWeight = weightOf(branchingEdge);
541 
542 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
543  for(int i = 0; i < m_recursionDepth; i++) std::cout << " ";
544  std::cout << "branching on edge: " << branchingEdge << std::endl;
545 #endif
546  // branching edge has been found or there is no feasible solution
547  if(branchingEdgeWeight < MAX_WEIGHT) {
548  // chose node to remove
549  node nodeToRemove = branchingEdge->source();
550  node targetNode = branchingEdge->target();
551 
552  // This seems to speed up things.
553  if(nodeToRemove->degree() < targetNode->degree()) {
554  nodeToRemove = branchingEdge->target();
555  targetNode = branchingEdge->source();
556  }
557 
558  // remove branching edge
559  edge origBranchingEdge = deleteEdge(branchingEdge);
560 
561  List<node> delEdges, movedEdges;
562  List<edge> origDelEdges;
563 
564  // first branch: Inclusion of the edge
565  // remove source node of edge and calculate new edge weights
566  OGDF_ASSERT(targetNode != nullptr);
567  OGDF_ASSERT(nodeToRemove != nullptr);
568 
569  // remove edges in case of multigraph
570  while(m_graph.searchEdge(targetNode, nodeToRemove) != nullptr) {
571  edge e = m_graph.searchEdge(targetNode, nodeToRemove);
572  delEdges.pushFront(e->target());
573  delEdges.pushFront(e->source());
574  origDelEdges.pushFront(m_mapping[e]);
575  deleteEdge(e);
576  }
577  while(m_graph.searchEdge(nodeToRemove, targetNode) != nullptr) {
578  edge e = m_graph.searchEdge(targetNode, nodeToRemove);
579  delEdges.pushFront(e->target());
580  delEdges.pushFront(e->source());
581  origDelEdges.pushFront(m_mapping[e]);
582  deleteEdge(e);
583  }
584 
585  OGDF_ASSERT(m_graph.searchEdge(targetNode, nodeToRemove) == nullptr);
586  OGDF_ASSERT(m_graph.searchEdge(nodeToRemove, targetNode) == nullptr);
587 
588  adjEntry adjNext;
589  for(adjEntry adj = nodeToRemove->firstAdj(); adj; adj = adjNext) {
590  adjNext = adj->succ();
591  edge e = adj->theEdge();
592 
593  OGDF_ASSERT(e != branchingEdge);
594  OGDF_ASSERT(e->target() == nodeToRemove || e->source() == nodeToRemove);
595  OGDF_ASSERT(adj->twinNode() != targetNode);
596 
597  edge f = lookupEdge(targetNode, adj->twinNode());
598  bool deletedEdgeE = false;
599  if(f != nullptr) {
600  if(weightOf(f) < weightOf(e)) {
601  delEdges.pushFront(e->target());
602  delEdges.pushFront(e->source());
603  origDelEdges.pushFront(m_mapping[e]);
604  deleteEdge(e);
605 
606  deletedEdgeE = true;
607  }
608  else {
609  delEdges.pushFront(f->target());
610  delEdges.pushFront(f->source());
611  origDelEdges.pushFront(m_mapping[f]);
612  deleteEdge(f);
613  }
614  }
615  if(!deletedEdgeE) {
616  if(e->target() == nodeToRemove) {
617  OGDF_ASSERT(e->source() != targetNode);
618  movedEdges.pushFront(e->source());
619  moveTarget(e, targetNode);
620  }
621  else {
622  OGDF_ASSERT(e->source() == nodeToRemove);
623  OGDF_ASSERT(e->target() != targetNode);
624  movedEdges.pushFront(e->target());
625  moveSource(e, targetNode);
626  }
627  }
628  }
629  // nodeToRemove is isolated at this point
630  // thus no need to actually remove it
631  // (easier to keep track of CopyGraph mapping)
632 
633  // remove node from terminals too
634  bool targetNodeIsTerminal = isTerminal(targetNode),
635  nodeToRemoveIsTerminal = isTerminal(nodeToRemove);
636 
637  OGDF_ASSERT(targetNodeIsTerminal || nodeToRemoveIsTerminal);
638  setTerminal(nodeToRemove, false);
639  setTerminal(targetNode, true);
640 
641 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
642  for(int i = 0; i < m_recursionDepth; i++) std::cout << " ";
643  std::cout << "inclusion branch" << std::endl;
644 #endif
645  // calculate result on modified graph
646  currentEdges.pushFront(origBranchingEdge);
647  result = bnbInternal(branchingEdgeWeight + prevCost, currentEdges);
648  OGDF_ASSERT(currentEdges.front() == origBranchingEdge);
649  currentEdges.popFront();
650 
651  // restore previous graph
652 
653  // restore terminals
654  setTerminal(nodeToRemove, nodeToRemoveIsTerminal);
655  setTerminal(targetNode, targetNodeIsTerminal);
656 
657  // restore moved edges
658  while(!movedEdges.empty()) {
659  node v = movedEdges.popFrontRet();
660 
661  edge e = lookupEdge(v, targetNode);
662  OGDF_ASSERT(e != nullptr);
663  OGDF_ASSERT(e->opposite(targetNode) != nodeToRemove);
664 
665  if(e->source() == v) {
666  moveTarget(e, nodeToRemove);
667  }
668  else {
669  moveSource(e, nodeToRemove);
670  }
671  }
672 
673  // restore deleted edges
674  while(!delEdges.empty()) {
675  OGDF_ASSERT(!origDelEdges.empty());
676 
677  node source = delEdges.popFrontRet();
678  node target = delEdges.popFrontRet();
679 
680  newEdge(source, target, origDelEdges.popFrontRet());
681  }
682  OGDF_ASSERT(origDelEdges.empty());
683 
684 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
685  for(int i = 0; i < m_recursionDepth; i++) std::cout << " ";
686  std::cout << "exclusion branch" << std::endl;
687 #endif
688  // sencond branch: Exclusion of the edge
689  T exEdgeResult = bnbInternal(prevCost, currentEdges);
690 
691  // decide which branch returned best result
692  if(exEdgeResult < result) {
693  result = exEdgeResult;
694  }
695 
696  // finally: restore the branching edge
697  newEdge(nodeToRemove, targetNode, origBranchingEdge);
698  }
699  }
701  }
703  return result;
704 }
705 
706 template<typename T>
708  EdgeWeightedGraphCopy<T> copiedGraph;
709  copiedGraph.createEmpty(m_graph);
710  List<node> nodes;
711  m_graph.allNodes(nodes);
712  NodeArray<bool> copiedIsTerminal(m_graph);
713  for(node v : nodes) {
714  copiedGraph.newNode(v);
715  copiedIsTerminal[v] = isTerminal(v);
716  }
717  List<edge> edges;
718  m_graph.allEdges(edges);
719  for(edge e : edges) {
720  copiedGraph.newEdge(e, weightOf(e));
721  }
722  std::stringstream filename;
723  filename << "bnb_internal_" << m_recursionDepth << ".svg";
724  this->drawSteinerTreeSVG(copiedGraph, copiedIsTerminal, filename.str().c_str());
725 }
726 
727 }
node target() const
Returns the target node of the edge.
Definition: Graph_d.h:328
void clear()
Removes all elements from the list.
Definition: List.h:1451
node copy(node v) const
Returns the node in the graph copy corresponding to v.
Definition: GraphCopy.h:335
node newNode(node vOrig)
Creates a new node in the graph copy with original node vOrig.
Definition: GraphCopy.h:412
void moveTarget(edge e, node w)
Moves the target node of edge e to node w.
Data type for general directed graphs (adjacency list representation).
Definition: Graph_d.h:492
void popFront()
Removes the first element from the list.
Definition: List.h:1411
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
virtual T computeSteinerTree(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal, EdgeWeightedGraphCopy< T > *&finalSteinerTree) override
Builds a minimum Steiner tree given a weighted graph and a list of terminals.
edge newEdge(node u, node v, T weight)
Declaration of ogdf::MinSteinerTreeModule.
T bnbInternal(T prevCost, List< edge > &currentEdges)
Calculates the optimal Steinter tree recursivly.
virtual void delEdge(edge e)
Removes edge e from the graph.
Definition: GML.h:110
Extends the GraphCopy concept to weighted graphs.
void setEdgeLookup(const node u, const node v, const edge e)
Sets the edge incident to both node u and v.
Dynamic arrays indexed with edges.
Definition: EdgeArray.h:112
edge newEdge(node source, node target, const edge originalEdge)
Creates a new edge.
void moveSource(edge e, node v)
Moves the source of the edge to the specified node.
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 )))...
void moveTarget(edge e, node v)
Moves the target of the edge to the specified node.
bool isTerminal(const node v) const
Returns whether this node is a terminal or a Steiner node.
void createEmpty(const Graph &wG)
internal::GraphObjectContainer< EdgeElement > edges
The container containing all edge objects.
Definition: Graph_d.h:568
iterator pushFront(const E &x)
Adds element x at the beginning of the list.
Definition: List.h:1360
Declaration and implementation of EdgeArray class.
T weightOf(edge e) const
Returns the cost of the specified edge.
const_reference front() const
Returns a const reference to the first element.
Definition: List.h:274
bool validateMapping() const
Used to validate the current mapping of edges to orignal edges Used solely for debugging.
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.
edge lookupEdge(const node u, const node v) const
Retrieves the edge incident to both node u and v.
const List< node > * m_originalTerminals
Class for the representation of edges.
Definition: Graph_d.h:292
E popFrontRet()
Removes the first element from the list and returns it.
Definition: List.h:1417
The parameterized class Array2D implements dynamic two-dimensional arrays.
Definition: Array2D.h:46
Class for the representation of nodes.
Definition: Graph_d.h:169
Declaration and implementation of NodeArray class.
Encapsulates a pointer to a list element.
Definition: List.h:42
void setTerminal(const node v, bool makeTerminal)
Updates the status of the given node to either terminal or Steiner node.
node opposite(node v) const
Returns the adjacent node different from v.
Definition: Graph_d.h:338
edge determineBranchingEdge(T prevCost) const
Decides which edge to branch on.
std::unique_ptr< NodeSet<> > m_terminals
void moveSource(edge e, node w)
Moves the source node of edge e to node w.
Implementation of Shore, Foulds and Gibbons exact branch and bound algorithm for solving Steiner tree...
edge deleteEdge(edge e)
Removes the specified edge from the graph.
int index() const
Returns the (unique) node index.
Definition: Graph_d.h:203
adjEntry succ() const
Returns the successor in the adjacency list.
Definition: Graph_d.h:148
Node sets.
Definition: NodeSet.h:54
void allNodes(CONTAINER &nodeContainer) const
Returns a container with all nodes of the graph.
Definition: Graph_d.h:651
node source() const
Returns the source node of the edge.
Definition: Graph_d.h:326
The namespace for all OGDF objects.
void allEdges(CONTAINER &edgeContainer) const
Returns a container with all edges of the graph.
Definition: Graph_d.h:661
static void drawSteinerTreeSVG(const EdgeWeightedGraphCopy< T > &steinerTree, const NodeArray< bool > &isTerminal, const char *filename)
Writes a SVG that shows only the given Steiner tree.
node newNode()
Creates a new node and returns it.
Declaration and implementation of ogdf::NodeSet.
adjEntry firstAdj() const
Returns the first entry in the adjaceny list.
Definition: Graph_d.h:213
const EdgeWeightedGraph< T > * m_originalGraph
bool empty() const
Returns true iff the list is empty.
Definition: List.h:256
Class for adjacency list elements.
Definition: Graph_d.h:79
void printSVG()
Prints the current recursion status as a SVG image of the current reduced STP.
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:41
Declaration of doubly linked lists and iterators.
T solve(List< edge > &chosenEdges)
Solves the current STP instance.