Open
Graph Drawing
Framework

 v. 2020.02 (Catalpa)
 

FullComponentGeneratorDreyfusWagnerWithoutMatrix.h
Go to the documentation of this file.
1 
32 #pragma once
33 
34 #include <ogdf/basic/Hashing.h>
35 #include <ogdf/basic/Math.h>
39 
40 namespace ogdf {
41 namespace steiner_tree {
42 
54 template<typename T>
59 
68 
70 
71  public:
73  AuxiliaryGraph(const EdgeWeightedGraph<T>& orig, const List<node>& terminals)
74  : m_original(orig), m_copyOfNode(m_original),
75  m_origOfNode(m_copy, nullptr), m_origOfEdge(m_copy, nullptr),
76  m_isTerminal(m_copy, false) {
77  // copy nodes and edges
78  for (node v : m_original.nodes) {
79  node vCopy = m_copy.newNode();
80  m_copyOfNode[v] = vCopy;
81  m_origOfNode[vCopy] = v;
82  }
83  for (edge e : m_original.edges) {
84  edge eCopy = m_copy.newEdge(copy(e->source()), copy(e->target()), m_original.weight(e));
85  m_origOfEdge[eCopy] = e;
86  }
87 
88  // set terminals
89  for (node v : terminals) {
90  m_isTerminal[copy(v)] = true;
91  }
92 
93  // initialize source node and its edges to every other node
94  m_source = m_copy.newNode();
95  for (node w : m_original.nodes) {
96  m_copy.newEdge(m_source, copy(w), std::numeric_limits<T>::max());
97  }
98  }
99 
101  node copy(node v) const {
102  OGDF_ASSERT(v->graphOf() == &m_original);
103  return m_copyOfNode[v];
104  }
105 
107  node original(node v) const {
108  OGDF_ASSERT(v->graphOf() == &m_copy);
109  return m_origOfNode[v];
110  }
111 
113  edge original(edge e) const {
114  OGDF_ASSERT(e->graphOf() == &m_copy);
115  return m_origOfEdge[e];
116  }
117 
119  node source() const {
120  return m_source;
121  }
122 
124  const EdgeWeightedGraph<T>& graph() const {
125  return m_copy;
126  }
127 
130  return m_isTerminal;
131  }
132 
134  T weight(edge e) const {
135  OGDF_ASSERT(e->graphOf() == &m_copy);
136  return m_copy.weight(e);
137  }
138 
140  void setWeight(edge e, T value) {
141  OGDF_ASSERT(e->graphOf() == &m_copy);
142  m_copy.setWeight(e, value);
143  }
144  };
145 
148 
150  struct DWMData {
151  T cost;
154  DWMData(T _cost, ArrayBuffer<edge> _edges) : cost(_cost), edges(_edges) {}
155  explicit DWMData(T _cost = std::numeric_limits<T>::max()) : cost(_cost) {}
156 
158  void invalidate() {
159  edges.clear();
160  subgraphs.clear();
161  }
162 
164  bool valid() const {
165  return cost == 0 || !(edges.empty() && subgraphs.empty());
166  }
167 
169  void add(const DWMData* other) {
170  if (valid()) {
171  if (other->valid()) {
172  subgraphs.push(other);
173  } else {
174  invalidate();
175  }
176  }
177  cost += other->cost;
178  }
179 
181  void clear() {
182  invalidate();
183  cost = 0; // make it valid again
184  }
185 
187  void add(edge e, T c) {
188  if (valid()) {
189  edges.push(e);
190  }
191  cost += c;
192  }
193  };
194 
196  struct DWMSplit {
197  T cost = std::numeric_limits<T>::max();
198  const DWMData* subgraph1 = nullptr;
199  const DWMData* subgraph2 = nullptr;
200 
202  void set(const DWMData* s1, const DWMData* s2) {
203  subgraph1 = s1;
204  subgraph2 = s2;
205  cost = s1->cost + s2->cost;
206  }
207  };
208 
211 
214 
216  const DWMData* dataOf(const List<node>& key) const {
217  OGDF_ASSERT(key.size() > 1);
218  OGDF_ASSERT(m_map.member(key));
219  return &m_map.lookup(key)->info();
220  }
221 
223  T costOf(const List<node>& key) const {
224  OGDF_ASSERT(key.size() > 1);
225  return dataOf(key)->cost;
226  }
227 
229  bool safeIfSumSmaller(const T summand1, const T summand2, const T compareValue) const {
230 #ifdef OGDF_FULL_COMPONENT_GENERATION_ALWAYS_SAFE
231  return summand1 + summand2 < compareValue;
232 #else
233  return summand1 < std::numeric_limits<T>::max()
234  && summand2 < std::numeric_limits<T>::max()
235  && summand1 + summand2 < compareValue;
236 #endif
237  }
238 
250  static void sortedInserter(node w, List<node>& list, bool& inserted, node newNode) {
251  if (!inserted && w->index() > newNode->index()) {
252  list.pushBack(newNode);
253  inserted = true;
254  }
255  list.pushBack(w);
256  }
257 
259  void makeKey(List<node>& newSubset, node v) const {
260  bool inserted = false;
261  m_terminalSubset.forEachMember([&](node w) { sortedInserter(w, newSubset, inserted, v); });
262  if (!inserted) {
263  newSubset.pushBack(v);
264  }
265  }
266 
268  void makeKey(List<node>& newSubset, List<node>& newComplement, const SubsetEnumerator<node>& subset, node v) const {
269  bool insertedIntoSubset = false;
270  bool insertedIntoComplement = false;
271  // Interestingly std::bind is much slower than using lambdas (at least on g++ 6.3)
273  [&](node w) { sortedInserter(w, newSubset, insertedIntoSubset, v); },
274  [&](node w) { sortedInserter(w, newComplement, insertedIntoComplement, v); });
275  if (!insertedIntoSubset) {
276  newSubset.pushBack(v);
277  }
278  if (!insertedIntoComplement) {
279  newComplement.pushBack(v);
280  }
281  }
282 
289  OGDF_ASSERT(v->graphOf() == &m_G);
290  OGDF_ASSERT(split[v].subgraph1 == nullptr);
291  OGDF_ASSERT(split[v].subgraph2 == nullptr);
292 
293  DWMSplit& best = split[v];
294  for (subset.begin(1, subset.numberOfMembersAndNonmembers() / 2); subset.valid(); subset.next()) {
295  List<node> newSubset, newComplement;
296  makeKey(newSubset, newComplement, subset, v);
297 
298  if (safeIfSumSmaller(costOf(newSubset), costOf(newComplement), best.cost)) {
299  best.set(dataOf(newSubset), dataOf(newComplement));
300  }
301  }
302  }
303 
305  template<typename CONTAINER>
306  void computePartialSolutions(const CONTAINER& targets) {
307  OGDF_ASSERT(m_terminalSubset.size() >= 2);
308 
309  List<node> terminals;
310  m_terminalSubset.list(terminals);
311  SubsetEnumerator<node> subset(terminals); // done here because of linear running time
312  NodeArray<DWMSplit> split(m_G);
313 
314  // update auxiliary graph
315  updateAuxGraph(split, subset, costOf(terminals));
316 
317  // compute shortest-paths tree on graph
318  NodeArray<T> distance;
319  NodeArray<edge> pred;
320  MinSteinerTreeModule<T>::singleSourceShortestPaths(m_auxG.graph(), m_auxG.source(), m_auxG.terminalArray(), distance, pred);
321 
322  // insert best subtrees
323  insertBestSubtrees(targets, split, pred, distance, terminals);
324  }
325 
327  void initializeMap() {
328  for (node t : m_terminals) {
329  NodeArray<T> distance;
330  NodeArray<edge> pred;
331  MinSteinerTreeModule<T>::singleSourceShortestPaths(m_G, t, m_isTerminal, distance, pred);
332 
333  for (node v : m_G.nodes) {
334  // make key
335  List<node> key;
336  key.pushBack(t);
337  if (v->index() < t->index()) {
338  key.pushFront(v);
339  } else {
340  key.pushBack(v);
341  }
342 
343  // insert if not already defined
344  if (!m_map.member(key)) {
345  T dist = distance[v];
346  ArrayBuffer<edge> edges;
347  for (node curr = v; pred[curr] != nullptr; curr = pred[curr]->opposite(curr)) {
348  edges.push(pred[curr]);
349  }
350  m_map.fastInsert(key, DWMData(dist, edges));
351  }
352  }
353  }
354  }
355 
357  void updateAuxGraph(NodeArray<DWMSplit>& split, SubsetEnumerator<node>& subset, T oldCost) {
358  for (adjEntry adj : m_auxG.source()->adjEntries) {
359  node w = m_auxG.original(adj->twinNode());
360  T cost = oldCost;
361  if (!m_terminalSubset.hasMember(w)) {
362  computeSplit(split, w, subset);
363  cost = split[w].cost;
364  }
365  m_auxG.setWeight(adj->theEdge(), cost);
366  }
367  }
368 
371  edge addNewPath(DWMData& result, node curr, const NodeArray<edge>& pred) const {
372  edge e = nullptr;
373  while (curr != m_auxG.source()) {
374  e = pred[curr];
375  OGDF_ASSERT(e != nullptr);
376  node prev = e->opposite(curr);
377  OGDF_ASSERT(prev != curr);
378  if (prev != m_auxG.source()) {
379  edge eO = m_auxG.original(e);
380  OGDF_ASSERT(eO != nullptr);
381  result.add(eO, m_auxG.weight(e));
382  }
383  curr = prev;
384  }
385  OGDF_ASSERT(e != nullptr);
386  OGDF_ASSERT(e->source() == curr);
387  OGDF_ASSERT(curr == m_auxG.source());
388 
389  return e;
390  }
391 
393  void insertInvalidBestSubtree(node v, const NodeArray<T>& distance, const List<node>& newSubset) {
394  OGDF_ASSERT(v->graphOf() == &m_auxG.graph());
395  OGDF_ASSERT(v != m_auxG.source());
396  DWMData best(distance[v]);
397  best.invalidate();
398  m_map.fastInsert(newSubset, best);
399  }
400 
402  void insertValidBestSubtree(node v, const NodeArray<DWMSplit>& split, const NodeArray<edge>& pred, const List<node>& newSubset, const List<node>& terminals) {
403  OGDF_ASSERT(v->graphOf() == &m_auxG.graph());
404  OGDF_ASSERT(v != m_auxG.source());
405  DWMData best(0);
406 
407  edge e = addNewPath(best, v, pred);
408  // add best solution so far
409  node tO = m_auxG.original(e->target());
410  if (m_terminalSubset.hasMember(tO)) {
411  best.add(dataOf(terminals));
412  } else {
413  best.add(split[tO].subgraph1);
414  best.add(split[tO].subgraph2);
415  }
416 
417  m_map.fastInsert(newSubset, best);
418  }
419 
421  template<typename CONTAINER>
422  void insertBestSubtrees(const CONTAINER& targets, const NodeArray<DWMSplit>& split, const NodeArray<edge>& pred, const NodeArray<T>& distance, const List<node>& terminals) {
423  for (node v : targets) {
424  if (!m_terminalSubset.hasMember(v)) {
425  List<node> newSubset;
426  makeKey(newSubset, v);
427 
428  if (!m_map.member(newSubset)) { // not already defined
429  node vCopy = m_auxG.copy(v);
430  if (pred[m_auxG.copy(v)] == nullptr) { // path over terminal
431  insertInvalidBestSubtree(vCopy, distance, newSubset);
432  } else {
433  insertValidBestSubtree(vCopy, split, pred, newSubset, terminals);
434  }
435  }
436  }
437  }
438  }
439 
441  T getSteinerTreeFor(const DWMData& data, EdgeWeightedGraphCopy<T>& tree) const {
442  T cost(0);
443 
444  if (data.valid()) {
445  // add edges
446  for (edge e : data.edges) {
447  node uO = e->source();
448  node vO = e->target();
449  OGDF_ASSERT(uO != nullptr);
450  OGDF_ASSERT(vO != nullptr);
451  node uC = tree.copy(uO);
452  node vC = tree.copy(vO);
453  if (uC == nullptr) {
454  uC = tree.newNode(uO);
455  }
456  if (vC == nullptr) {
457  vC = tree.newNode(vO);
458  }
459  T dist = m_G.weight(e);
460  tree.newEdge(e, dist);
461  cost += dist;
462  }
463 
464  // recurse
465  for (const DWMData* subgraph : data.subgraphs) {
466  cost += getSteinerTreeFor(*subgraph, tree);
467  }
468 
470  }
471 
472  return cost;
473  }
474 
475 public:
481  : m_G(G),
482  m_terminals(terminals),
483  m_isTerminal(isTerminal),
484  m_auxG(m_G, m_terminals),
485  m_terminalSubset(m_terminals),
486  m_map(1 << 22) { // we initially allocate 4MB*sizeof(DWMData) for hashing
487  }
488 
489  void call(int restricted) {
490  OGDF_ASSERT(restricted >= 2);
491  Math::updateMin(restricted, m_terminals.size());
492  initializeMap();
493  for (m_terminalSubset.begin(2, restricted - 2); m_terminalSubset.valid(); m_terminalSubset.next()) {
495  }
496  // save time by only adding terminals instead of all nodes
497  for (m_terminalSubset.begin(restricted - 1); m_terminalSubset.valid(); m_terminalSubset.next()) {
498  computePartialSolutions(m_terminals);
499  }
500  }
501 
504  T getSteinerTreeFor(const List<node>& terminals, EdgeWeightedGraphCopy<T>& tree) const {
505  tree.createEmpty(m_G);
506  T cost(getSteinerTreeFor(*dataOf(terminals), tree));
507  OGDF_ASSERT(isTree(tree));
508  return cost;
509  }
510 
512  bool isValidComponent(const EdgeWeightedGraphCopy<T>& tree) const {
513  if (tree.empty()) {
514  return false;
515  }
516  for (node v : tree.nodes) {
517  OGDF_ASSERT(v->degree() > 1 || m_isTerminal[tree.original(v)]);
518  if (m_isTerminal[tree.original(v)] // is a terminal
519  && v->degree() > 1) { // but not a leaf
520  return false;
521  }
522  }
523  return true;
524  }
525 };
526 
527 template<typename T>
529  static const unsigned int c_prime = 0x7fffffff; // mersenne prime 2**31 - 1
530  // would be nicer: 0x1fffffffffffffff; // mersenne prime 2**61 - 1
531  const int m_random;
532 
533 public:
535  SortedNodeListHashFunc() : m_random(randomNumber(2, c_prime - 1)) {}
536 
538  unsigned int hash(const List<node>& key) const {
539  unsigned int hash = 0;
540  for (node v : key) {
541  hash = (hash * m_random + v->index()) % c_prime;
542  }
543  return hash;
544  }
545 };
546 
547 }
548 }
node target() const
Returns the target node of the edge.
Definition: Graph_d.h:328
HashElement< K, I > * lookup(const K &key) const
Returns the hash element with key key in the hash table; returns nullptr if no such element exists...
Definition: Hashing.h:296
bool member(const K &key) const
Returns true iff the hash table contains an element with key key.
Definition: Hashing.h:290
void makeKey(List< node > &newSubset, node v) const
Makes a list from the current terminal subset including an correctly inserted node v...
void clear()
Clears the buffer.
Definition: ArrayBuffer.h:94
static void sortedInserter(node w, List< node > &list, bool &inserted, node newNode)
Is being used as a callback to ogdf::SubsetEnumerator&#39;s forEach* methods to get the subset plus a cor...
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
iterator pushBack(const E &x)
Adds element x at the end of the list.
Definition: List.h:1373
const NodeArray< bool > & terminalArray() const
Returns a const reference to m_isTerminal.
int randomNumber(int low, int high)
Returns random integer between low and high (including).
int degree() const
Returns the degree of the node (indegree + outdegree).
Definition: Graph_d.h:210
edge newEdge(node u, node v, T weight)
Declaration of ogdf::MinSteinerTreeModule.
Declaration of classes used for hashing.
void setWeight(const edge e, T weight)
void push(E e)
Puts a new element in the buffer.
Definition: ArrayBuffer.h:102
Extends the GraphCopy concept to weighted graphs.
static void singleSourceShortestPaths(const EdgeWeightedGraph< T > &G, node source, const NodeArray< bool > &isTerminal, NodeArray< T > &distance, NodeArray< edge > &pred)
The default single-source-shortest-paths algorithm.
bool valid() const
Checks if the current subset is valid. If not, the subset is either not initialized or all subsets ha...
Dynamic arrays indexed with edges.
Definition: EdgeArray.h:112
bool isValidComponent(const EdgeWeightedGraphCopy< T > &tree) const
Checks if a given tree is a valid full component.
void set(const DWMData *s1, const DWMData *s2)
Sets subgraph1 and subgraph2 and computes cost.
T weight(const edge e) const
edge newEdge(node v, node w, T weight)
T getSteinerTreeFor(const List< node > &terminals, EdgeWeightedGraphCopy< T > &tree) const
Constructs a Steiner tree for the given set of terminals if it is valid, otherwise an empty tree is r...
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
void computePartialSolutions(const CONTAINER &targets)
Computes all partial solutions for given m_terminalSubset.
internal::GraphObjectContainer< EdgeElement > edges
The container containing all edge objects.
Definition: Graph_d.h:568
const DWMData * dataOf(const List< node > &key) const
Returns a pointer to the relevant data of the partial solution given by key.
bool isAcyclicUndirected(const Graph &G, List< edge > &backedges)
Returns true iff the undirected graph G is acyclic.
iterator pushFront(const E &x)
Adds element x at the beginning of the list.
Definition: List.h:1360
Mathematical Helpers.
void begin(int low, int high)
Initializes the SubsetEnumerator to enumerate subsets of cardinalities from low to high...
bool empty() const
Returns true if the buffer is empty, false otherwise.
Definition: ArrayBuffer.h:116
Enumerator for k-subsets of a given type.
Doubly linked lists (maintaining the length of the list).
Definition: List.h:40
A generator for restricted full components (for Steiner tree approximations) based on the Dreyfus-Wag...
Class for the representation of edges.
Definition: Graph_d.h:292
static uint32_t hash(uint32_t x)
Definition: Map.h:38
T costOf(const List< node > &key) const
Returns the cost of the partial solution given by key.
T getSteinerTreeFor(const DWMData &data, EdgeWeightedGraphCopy< T > &tree) const
Adds edges to construct a Steiner tree from the given data (recursively) if the data is valid...
void updateAuxGraph(NodeArray< DWMSplit > &split, SubsetEnumerator< node > &subset, T oldCost)
Updates the auxiliary graph.
Class for the representation of nodes.
Definition: Graph_d.h:169
FullComponentGeneratorDreyfusWagnerWithoutMatrix(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal)
The constructor.
Subgraphs (given by other subgraphs and additional edges) and their cost for a partial solution...
node opposite(node v) const
Returns the adjacent node different from v.
Definition: Graph_d.h:338
const Graph & original() const
Returns a reference to the original graph.
Definition: GraphCopy.h:286
const NodeArray< bool > & m_isTerminal
A reference to the terminal incidence vector.
bool hasMember(const T &element) const
Checks in O(subset cardinality) whether element is a member of the subset.
void forEachMemberAndNonmember(std::function< void(const T &)> funcIn, std::function< void(const T &)> funcNotIn) const
Calls funcIn for each subset member and funcNotIn for each other element of the set.
bool safeIfSumSmaller(const T summand1, const T summand2, const T compareValue) const
Checks overflow-safe if summand1 plus summand2 is less than compareValue.
int index() const
Returns the (unique) node index.
Definition: Graph_d.h:203
HashElement< K, I > * fastInsert(const K &key, const I &info)
Inserts a new element with key key and information info into the hash table.
Definition: Hashing.h:349
void list(List< T > &subset) const
Obtains (appends) a list of the subset members.
void next()
Obtains the next subset if possible. The result should be checked using the valid() method...
int size() const
Returns the number of elements in the list.
Definition: List.h:1312
edge addNewPath(DWMData &result, node curr, const NodeArray< edge > &pred) const
Adds the shortest path from the source to curr into result.
void forEachMember(std::function< void(const T &)> func) const
Calls func for each member in the subset.
void computeSplit(NodeArray< DWMSplit > &split, node v, SubsetEnumerator< node > &subset) const
Populates split that contains a partial solution for an included nonterminal v in m_G...
bool isTree(const Graph &G)
Returns true iff G is a tree, i.e. contains no undirected cycle and is connected. ...
node source() const
Returns the source node of the edge.
Definition: Graph_d.h:326
const List< node > & m_terminals
A reference to the index-sorted list of terminals.
Hashing with chaining and table doubling.
Definition: Hashing.h:264
int size() const
Returns the cardinality of the subset.
The namespace for all OGDF objects.
void insertBestSubtrees(const CONTAINER &targets, const NodeArray< DWMSplit > &split, const NodeArray< edge > &pred, const NodeArray< T > &distance, const List< node > &terminals)
Inserts the best subtrees into the hash map.
internal::GraphObjectContainer< NodeElement > nodes
The container containing all node objects.
Definition: Graph_d.h:565
int numberOfMembersAndNonmembers() const
Returns the cardinality of the (super-)set. This is the maximum size that can be used for a subset...
A class that allows to enumerate k-subsets.
AuxiliaryGraph(const EdgeWeightedGraph< T > &orig, const List< node > &terminals)
Constructs a copy of the original graph with an added source node having edges to all other nodes...
bool empty() const
Returns true iff the graph is empty, i.e., contains no nodes.
Definition: Graph_d.h:595
void insertInvalidBestSubtree(node v, const NodeArray< T > &distance, const List< node > &newSubset)
Inserts the invalid best subtree (based on the SSSP computation) into the hash map.
Class for adjacency list elements.
Definition: Graph_d.h:79
void makeKey(List< node > &newSubset, List< node > &newComplement, const SubsetEnumerator< node > &subset, node v) const
Makes a list from subset and its complement, each including an correctly inserted node v...
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:41
void insertValidBestSubtree(node v, const NodeArray< DWMSplit > &split, const NodeArray< edge > &pred, const List< node > &newSubset, const List< node > &terminals)
Inserts the valid best subtree (based on the SSSP computation) into the hash map. ...
Hashing< List< node >, DWMData, SortedNodeListHashFunc > m_map
A hash array for keys of size > 2.
internal::GraphObjectContainer< AdjElement > adjEntries
The container containing all entries in the adjacency list of this node.
Definition: Graph_d.h:200