Open
Graph Drawing
Framework

 v. snapshot-2017-02-16
 

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 <ogdf/basic/List.h>
42 #include <ogdf/basic/EdgeArray.h>
43 #include <ogdf/basic/NodeArray.h>
46 
47 namespace ogdf {
48 
59 template<typename T>
61 public:
62 
63  MinSteinerTreeShore() : MAX_WEIGHT(std::numeric_limits<T>::max())
64  {};
65  virtual ~MinSteinerTreeShore() {};
66 
67 protected:
83  virtual T computeSteinerTree(const EdgeWeightedGraph<T> &G, const List<node> &terminals, const NodeArray<bool> &isTerminal,
84  EdgeWeightedGraphCopy<T> *&finalSteinerTree) override;
85 
86  const T MAX_WEIGHT;
87 private:
90 
99 
108  bool validateMapping() const;
109 
118  T weightOf(edge e) const;
119 
136  T bnbInternal(T prevCost, List<edge> &currentEdges);
137 
145  edge deleteEdge(edge e);
146 
157  edge newEdge(node source, node target, const edge originalEdge);
158 
167  void moveSource(edge e, node v);
168 
177  void moveTarget(edge e, node v);
178 
190  void setTerminal(const node v, bool makeTerminal);
191 
204  bool isTerminal(const node v) const;
205 
218  void setEdgeLookup(const node u, const node v, const edge e);
219 
232  edge lookupEdge(const node u, const node v) const;
233 
247  edge determineBranchingEdge(T prevCost) const;
248 
256  T solve(List<edge> &chosenEdges);
257 
262  void printSVG();
263 };
264 
265 template<typename T>
267 {
268  m_originalGraph = &G;
269  m_originalTerminals = &terminals;
270  m_terminals.clear();
271 
273  m_graph = Graph();
274  m_mapping.init(m_graph);
275  m_isTerminal.init(m_graph, nullptr);
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>
403 void MinSteinerTreeShore<T>::setTerminal(const node v, bool makeTerminal)
404 {
405  if(makeTerminal && !isTerminal(v)){
406  m_isTerminal[v] = m_terminals.pushFront(v);
407  }
408  else {
409  if(!makeTerminal && isTerminal(v)) {
410  m_terminals.del(m_isTerminal[v]);
411  m_isTerminal[v] = nullptr;
412  }
413  }
414 }
415 
416 template<typename T>
418 {
419  return m_isTerminal[v].valid();
420 }
421 
422 template<typename T>
424 {
426 
427  m_recursionDepth = 0;
428  List<edge> tmp;
429  T result = bnbInternal(0, tmp);
430 
431  for(edge e : m_chosenEdges) {
432  chosenEdges.pushFront(e);
433  }
434 
435  return result;
436 }
437 
438 template<typename T>
440 {
441  edge result = nullptr;
442  T maxPenalty = -1;
443 
444  // calculate penalties for nodes
445  T sumOfMinWeights = 0; // b
446  T sumOfMinTermWeights = 0; // c
447  T absoluteMinTermWeight = MAX_WEIGHT;
448  for(ListConstIterator<node> it = m_terminals.begin();
449  sumOfMinWeights < MAX_WEIGHT && it.valid();
450  ++it) {
451  const node t = *it;
452  T minTermWeight = MAX_WEIGHT,
453  minWeight = MAX_WEIGHT,
454  secondMinWeight = MAX_WEIGHT;
455  edge minEdge = nullptr;
456 
457  // investigate all edges of each terminal
458  // calculate lower boundary and find branching edge
459  for(adjEntry adj = t->firstAdj(); adj; adj = adj->succ()) {
460  edge e = adj->theEdge();
461  if(weightOf(e) < minWeight) {
462  secondMinWeight = minWeight;
463  minWeight = weightOf(e);
464  minEdge = e;
465  }
466  else {
467  if(weightOf(e) < secondMinWeight) {
468  secondMinWeight = weightOf(e);
469  }
470  }
471 
472  if(isTerminal(adj->twinNode()) && weightOf(e) < minTermWeight) {
473  minTermWeight = weightOf(e);
474  if(minTermWeight < absoluteMinTermWeight) {
475  absoluteMinTermWeight = minTermWeight;
476  }
477  }
478  }
479 
480  if(sumOfMinTermWeights < MAX_WEIGHT && minTermWeight < MAX_WEIGHT) {
481  sumOfMinTermWeights += minTermWeight;
482  }
483  else {
484  sumOfMinTermWeights = MAX_WEIGHT;
485  }
486  OGDF_ASSERT(absoluteMinTermWeight <= sumOfMinTermWeights);
487 
488  // is terminal isolated or has only one edge?
489  // if so we can break here
490  if(minWeight == MAX_WEIGHT ||
491  secondMinWeight == MAX_WEIGHT) {
492  result = minEdge;
493  if(minWeight == MAX_WEIGHT) {
494  sumOfMinWeights = MAX_WEIGHT;
495  }
496  } else {
497  sumOfMinWeights += minWeight;
498  // update branching edge if need be
499  T penalty = secondMinWeight - minWeight;
500  if(penalty > maxPenalty) {
501  maxPenalty = penalty;
502  result = minEdge;
503  }
504  }
505  }
506 
507  // compare bounds for this graph
508  if(result != nullptr) {
509  T maxCost = m_upperBound - prevCost;
510  if(sumOfMinTermWeights < MAX_WEIGHT) {
511  sumOfMinTermWeights -= absoluteMinTermWeight;
512  }
513  if(maxCost <= sumOfMinWeights && maxCost <= sumOfMinTermWeights) {
514  result = nullptr;
515  }
516  }
517 
518  return result;
519 }
520 
521 template<typename T>
523 {
524  T result = MAX_WEIGHT;
526 
527 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
528  printSVG();
529 #endif
530 
531  if(prevCost <= m_upperBound) {
532  if(m_terminals.size() < 2) {
533  // update currently chosen edges
534  if(prevCost != m_upperBound || m_chosenEdges.empty()) {
535 
536  m_chosenEdges = List<edge>(currentEdges);
537  }
538  // all terminals are connected
539  m_upperBound = prevCost;
540  result = prevCost;
541  }
542  else {
543  edge branchingEdge = determineBranchingEdge(prevCost);
544  T branchingEdgeWeight = weightOf(branchingEdge);
545 
546 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
547  for(int i = 0; i < m_recursionDepth; i++) cout << " ";
548  cout << "branching on edge: " << branchingEdge << std::endl;
549 #endif
550  // branching edge has been found or there is no feasible solution
551  if(branchingEdgeWeight < MAX_WEIGHT) {
552  // chose node to remove
553  node nodeToRemove = branchingEdge->source();
554  node targetNode = branchingEdge->target();
555 
556  // This seems to speed up things.
557  if(nodeToRemove->degree() < targetNode->degree()) {
558  nodeToRemove = branchingEdge->target();
559  targetNode = branchingEdge->source();
560  }
561 
562  // remove branching edge
563  edge origBranchingEdge = deleteEdge(branchingEdge);
564 
565  List<node> delEdges, movedEdges;
566  List<edge> origDelEdges;
567 
568  // first branch: Inclusion of the edge
569  // remove source node of edge and calculate new edge weights
570  OGDF_ASSERT(targetNode != nullptr);
571  OGDF_ASSERT(nodeToRemove != nullptr);
572 
573  // remove edges in case of multigraph
574  while(m_graph.searchEdge(targetNode, nodeToRemove) != nullptr) {
575  edge e = m_graph.searchEdge(targetNode, nodeToRemove);
576  delEdges.pushFront(e->target());
577  delEdges.pushFront(e->source());
578  origDelEdges.pushFront(m_mapping[e]);
579  deleteEdge(e);
580  }
581  while(m_graph.searchEdge(nodeToRemove, targetNode) != nullptr) {
582  edge e = m_graph.searchEdge(targetNode, nodeToRemove);
583  delEdges.pushFront(e->target());
584  delEdges.pushFront(e->source());
585  origDelEdges.pushFront(m_mapping[e]);
586  deleteEdge(e);
587  }
588 
589  OGDF_ASSERT(m_graph.searchEdge(targetNode, nodeToRemove) == nullptr);
590  OGDF_ASSERT(m_graph.searchEdge(nodeToRemove, targetNode) == nullptr);
591 
592  adjEntry adjNext;
593  for(adjEntry adj = nodeToRemove->firstAdj(); adj; adj = adjNext) {
594  adjNext = adj->succ();
595  edge e = adj->theEdge();
596 
597  OGDF_ASSERT(e != branchingEdge);
598  OGDF_ASSERT(e->target() == nodeToRemove || e->source() == nodeToRemove);
599  OGDF_ASSERT(adj->twinNode() != targetNode);
600 
601  edge f = lookupEdge(targetNode, adj->twinNode());
602  bool deletedEdgeE = false;
603  if(f != nullptr) {
604  if(weightOf(f) < weightOf(e)) {
605  delEdges.pushFront(e->target());
606  delEdges.pushFront(e->source());
607  origDelEdges.pushFront(m_mapping[e]);
608  deleteEdge(e);
609 
610  deletedEdgeE = true;
611  }
612  else {
613  delEdges.pushFront(f->target());
614  delEdges.pushFront(f->source());
615  origDelEdges.pushFront(m_mapping[f]);
616  deleteEdge(f);
617  }
618  }
619  if(!deletedEdgeE) {
620  if(e->target() == nodeToRemove) {
621  OGDF_ASSERT(e->source() != targetNode);
622  movedEdges.pushFront(e->source());
623  moveTarget(e, targetNode);
624  }
625  else {
626  OGDF_ASSERT(e->source() == nodeToRemove);
627  OGDF_ASSERT(e->target() != targetNode);
628  movedEdges.pushFront(e->target());
629  moveSource(e, targetNode);
630  }
631  }
632  }
633  // nodeToRemove is isolated at this point
634  // thus no need to actually remove it
635  // (easier to keep track of CopyGraph mapping)
636 
637  // remove node from terminals too
638  bool targetNodeIsTerminal = isTerminal(targetNode),
639  nodeToRemoveIsTerminal = isTerminal(nodeToRemove);
640 
641  OGDF_ASSERT(targetNodeIsTerminal || nodeToRemoveIsTerminal);
642  setTerminal(nodeToRemove, false);
643  setTerminal(targetNode, true);
644 
645 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
646  for(int i = 0; i < m_recursionDepth; i++) cout << " ";
647  cout << "inclusion branch" << std::endl;
648 #endif
649  // calculate result on modified graph
650  currentEdges.pushFront(origBranchingEdge);
651  result = bnbInternal(branchingEdgeWeight + prevCost, currentEdges);
652  OGDF_ASSERT(currentEdges.front() == origBranchingEdge);
653  currentEdges.popFront();
654 
655  // restore previous graph
656 
657  // restore terminals
658  setTerminal(nodeToRemove, nodeToRemoveIsTerminal);
659  setTerminal(targetNode, targetNodeIsTerminal);
660 
661  // restore moved edges
662  while(!movedEdges.empty()) {
663  node v = movedEdges.popFrontRet();
664 
665  edge e = lookupEdge(v, targetNode);
666  OGDF_ASSERT(e != nullptr);
667  OGDF_ASSERT(e->opposite(targetNode) != nodeToRemove);
668 
669  if(e->source() == v) {
670  moveTarget(e, nodeToRemove);
671  }
672  else {
673  moveSource(e, nodeToRemove);
674  }
675  }
676 
677  // restore deleted edges
678  while(!delEdges.empty()) {
679  OGDF_ASSERT(!origDelEdges.empty());
680 
681  node source = delEdges.popFrontRet();
682  node target = delEdges.popFrontRet();
683 
684  newEdge(source, target, origDelEdges.popFrontRet());
685  }
686  OGDF_ASSERT(origDelEdges.empty());
687 
688 #ifdef OGDF_MINSTEINERTREE_SHORE_LOGGING
689  for(int i = 0; i < m_recursionDepth; i++) cout << " ";
690  cout << "exclusion branch" << std::endl;
691 #endif
692  // sencond branch: Exclusion of the edge
693  T exEdgeResult = bnbInternal(prevCost, currentEdges);
694 
695  // decide which branch returned best result
696  if(exEdgeResult < result) {
697  result = exEdgeResult;
698  }
699 
700  // finally: restore the branching edge
701  newEdge(nodeToRemove, targetNode, origBranchingEdge);
702  }
703  }
705  }
707  return result;
708 }
709 
710 template<typename T>
712  EdgeWeightedGraphCopy<T> copiedGraph;
713  copiedGraph.createEmpty(m_graph);
714  List<node> nodes;
715  m_graph.allNodes(nodes);
716  NodeArray<bool> copiedIsTerminal(m_graph);
717  for(node v : nodes) {
718  copiedGraph.newNode(v);
719  copiedIsTerminal[v] = isTerminal(v);
720  }
721  List<edge> edges;
722  m_graph.allEdges(edges);
723  for(edge e : edges) {
724  copiedGraph.newEdge(e, weightOf(e));
725  }
726  std::stringstream filename;
727  filename << "bnb_internal_" << m_recursionDepth << ".svg";
728  this->drawSteinerTreeSVG(copiedGraph, copiedIsTerminal, filename.str().c_str());
729 }
730 
731 } // end namespace ogdf
node target() const
Returns the target node of the edge.
Definition: Graph_d.h:327
void clear()
Removes all elements from the list.
Definition: List.h:1394
NodeArray< ListIterator< node > > m_isTerminal
node copy(node v) const
Returns the node in the graph copy corresponding to v.
Definition: GraphCopy.h:336
node newNode(node vOrig)
Creates a new node in the graph copy with original node vOrig.
Definition: GraphCopy.h:413
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:472
edge searchEdge(node v, node w) const
Searches and returns an edge connecting nodes v and w in time O( min(deg(v ), deg(w )))...
static const int Graph
Definition: GmlParser.h:59
void popFront()
Removes the first element from the list.
Definition: List.h:1354
This class serves as an interface for various methods to compute minimum or approximations of minimum...
int degree() const
Returns the degree of the node (indegree + outdegree).
Definition: Graph_d.h:208
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)
Interface of Minimum Steiner Tree Algorithms.
T bnbInternal(T prevCost, List< edge > &currentEdges)
Calculates the optimal Steinter tree recursivly.
virtual void delEdge(edge e)
Removes edge e from the graph.
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.
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:548
iterator pushFront(const E &x)
Adds element x at the beginning of the list.
Definition: List.h:1303
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:254
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:39
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:291
void allEdges(EDGELIST &edgeList) const
Returns a list with all edges of the graph.
Definition: Graph_d.h:643
E popFrontRet()
Removes the first element from the list and returns it.
Definition: List.h:1360
The parameterized class Array2D implements dynamic two-dimensional arrays.
Definition: Array2D.h:46
Class for the representation of nodes.
Definition: Graph_d.h:167
Declaration and implementation of NodeArray class.
Encapsulates a pointer to a list element.
Definition: List.h:41
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:335
edge determineBranchingEdge(T prevCost) const
Decides which edge to branch on.
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:201
adjEntry succ() const
Returns the successor in the adjacency list.
Definition: Graph_d.h:145
void allNodes(NODELIST &nodeList) const
Returns a list with all nodes of the graph.
Definition: Graph_d.h:631
node source() const
Returns the source node of the edge.
Definition: Graph_d.h:325
The namespace for all OGDF objects.
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.
adjEntry firstAdj() const
Returns the first entry in the adjaceny list.
Definition: Graph_d.h:211
const EdgeWeightedGraph< T > * m_originalGraph
bool empty() const
Returns true iff the list is empty.
Definition: List.h:236
Class for adjacency list elements.
Definition: Graph_d.h:78
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.