Open
Graph Drawing
Framework

 v. 2020.02 (Catalpa)
 

FullComponentGeneratorDreyfusWagner.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>
38 
39 namespace ogdf {
40 namespace steiner_tree {
41 
50 template<typename T>
52 {
59 
61 
63  struct DWMData {
64  T cost;
67  DWMData(T _cost, NodePairs _nodepairs) : cost(_cost), nodepairs(_nodepairs) {}
68  explicit DWMData(T _cost = std::numeric_limits<T>::max()) : cost(_cost) {}
69 
71  void invalidate() {
72  nodepairs.clear();
73  subgraphs.clear();
74  }
75 
77  bool valid() const {
78  return cost == 0 || !(nodepairs.empty() && subgraphs.empty());
79  }
80 
82  void add(const DWMData* other) {
83  if (valid()) {
84  if (other->valid()) {
85  subgraphs.push(other);
86  } else {
87  invalidate();
88  }
89  }
90  cost += other->cost;
91  }
92 
94  void clear() {
95  invalidate();
96  cost = 0; // make it valid again
97  }
98 
100  void add(NodePair nodepair, T c) {
101  if (valid()) {
102  nodepairs.push(nodepair);
103  }
104  cost += c;
105  }
106  };
107 
109  struct DWMSplit {
110  T cost = std::numeric_limits<T>::max();
111  const DWMData* subgraph1 = nullptr;
112  const DWMData* subgraph2 = nullptr;
113 
115  void set(const DWMData* s1, const DWMData* s2) {
116  subgraph1 = s1;
117  subgraph2 = s2;
118  cost = s1->cost + s2->cost;
119  }
120  };
121 
124 
127 
129  const DWMData* dataOf(const List<node> &key) const {
130  OGDF_ASSERT(key.size() > 1);
131  OGDF_ASSERT(m_map.member(key));
132  return &m_map.lookup(key)->info();
133  }
134 
136  T costOf(const List<node> &key) const {
137  OGDF_ASSERT(key.size() > 1);
138  if (key.size() == 2) { // a shortcut to avoid using the hash table
139 #ifdef OGDF_FULL_COMPONENT_GENERATION_TERMINAL_SSSP_AWARE
140  if (m_isTerminal[key.front()]) {
141  return m_distance[key.front()][key.back()];
142  } else {
143  OGDF_ASSERT(m_isTerminal[key.back()]);
144  return m_distance[key.back()][key.front()];
145  }
146 #else
147  return m_distance[key.front()][key.back()];
148 #endif
149  }
150  return dataOf(key)->cost;
151  }
152 
154  bool safeIfSumSmaller(const T summand1, const T summand2, const T compareValue) const
155  {
156 #ifdef OGDF_FULL_COMPONENT_GENERATION_ALWAYS_SAFE
157  return summand1 + summand2 < compareValue;
158 #else
159  return summand1 < std::numeric_limits<T>::max()
160  && summand2 < std::numeric_limits<T>::max()
161  && summand1 + summand2 < compareValue;
162 #endif
163  }
164 
176  static void sortedInserter(node w, List<node> &list, bool &inserted, node newNode)
177  {
178  if (!inserted && w->index() > newNode->index()) {
179  list.pushBack(newNode);
180  inserted = true;
181  }
182  list.pushBack(w);
183  }
184 
186  void makeKey(List<node>& newSubset, node v) const
187  {
188  bool inserted = false;
189  m_terminalSubset.forEachMember([&](node w) { sortedInserter(w, newSubset, inserted, v); });
190  if (!inserted) {
191  newSubset.pushBack(v);
192  }
193  }
194 
196  void makeKey(List<node>& newSubset, List<node>& newComplement, const SubsetEnumerator<node>& subset, node v) const
197  {
198  bool insertedIntoSubset = false;
199  bool insertedIntoComplement = false;
200  // Interestingly std::bind is much slower than using lambdas (at least on g++ 6.3)
202  [&](node w) { sortedInserter(w, newSubset, insertedIntoSubset, v); },
203  [&](node w) { sortedInserter(w, newComplement, insertedIntoComplement, v); });
204  if (!insertedIntoSubset) {
205  newSubset.pushBack(v);
206  }
207  if (!insertedIntoComplement) {
208  newComplement.pushBack(v);
209  }
210  }
211 
218  if (split[v].subgraph1 != nullptr) { // already computed
219  return;
220  }
221 
222  DWMSplit& best = split[v];
223  for (subset.begin(1, subset.numberOfMembersAndNonmembers() / 2); subset.valid(); subset.next()) {
224  List<node> newSubset, newComplement;
225  makeKey(newSubset, newComplement, subset, v);
226 
227  if (safeIfSumSmaller(costOf(newSubset), costOf(newComplement), best.cost)) {
228  best.set(dataOf(newSubset), dataOf(newComplement));
229  }
230  }
231  }
232 
235  node v,
236  SubsetEnumerator<node> &subset,
237  const List<node> &terminals)
238  {
239  List<node> newSubset;
240  makeKey(newSubset, v);
241 
242  if (!m_map.member(newSubset)) { // not already defined
243  T oldCost = costOf(terminals);
244  DWMData best;
245  auto addPair = [&](node v1, node v2, T dist) {
246  best.add(NodePair(v1, v2), dist);
247  if (m_pred[v1][v2] == nullptr) {
248  best.invalidate();
249  }
250  };
251  for (node w : m_G.nodes) {
252  T dist = m_distance[v][w];
253  if (m_terminalSubset.hasMember(w)) {
254  // we attach edge vw to tree containing terminal w
255  if (safeIfSumSmaller(oldCost, dist, best.cost)) {
256  best.clear();
257  best.add(dataOf(terminals));
258  addPair(v, w, dist);
259  }
260  } else {
261  // we attach edge vw to tree split[w]
262  OGDF_ASSERT(!m_terminalSubset.hasMember(v));
263  computeSplit(split, w, subset);
264  if (safeIfSumSmaller(split[w].cost, dist, best.cost)) {
265  best.clear();
266  best.add(split[w].subgraph1);
267  best.add(split[w].subgraph2);
268  if (v != w) {
269  addPair(v, w, dist);
270  }
271  }
272  }
273  }
274  m_map.fastInsert(newSubset, best);
275  }
276  }
277 
279  template<typename CONTAINER>
280  void computePartialSolutions(const CONTAINER& nodeContainer) {
281  List<node> terminals;
282  m_terminalSubset.list(terminals);
283  SubsetEnumerator<node> subset(terminals); // done here because of linear running time
284  NodeArray<DWMSplit> split(m_G);
285  for (node v : nodeContainer) {
286  if (!m_terminalSubset.hasMember(v)) {
287  computePartialSolution(split, v, subset, terminals);
288  }
289  }
290  }
291 
293  void initializeMap() {
294  for (node v : m_G.nodes) {
295  for (node t : m_terminals) {
296  if (t != v) {
297  List<node> key;
298  key.pushBack(t);
299  if (v->index() < t->index()) {
300  key.pushFront(v);
301  } else {
302  key.pushBack(v);
303  }
304 
305  if (!m_map.member(key)) { // not already defined
306  if (m_pred[t][v] == nullptr) {
307  m_map.fastInsert(key, DWMData(m_distance[t][v]));
308  OGDF_ASSERT(!dataOf(key)->valid() || m_distance[t][v] == 0);
309  } else {
311  nodepairs.push(NodePair(key.front(), key.back()));
312  m_map.fastInsert(key, DWMData(m_distance[t][v], nodepairs));
313  OGDF_ASSERT(dataOf(key)->valid());
314  }
315  }
316  }
317  }
318  }
319  }
320 
322  T getSteinerTreeFor(const DWMData& data, EdgeWeightedGraphCopy<T>& tree) const {
323  T cost(0);
324  if (data.valid()) {
325  // add edges
326  for (auto nodepair : data.nodepairs) {
327  node uO = nodepair.source;
328  node vO = nodepair.target;
329  node uC = tree.copy(uO);
330  node vC = tree.copy(vO);
331  if (uC == nullptr) {
332  uC = tree.newNode(uO);
333  }
334  if (vC == nullptr) {
335  vC = tree.newNode(vO);
336  }
337 #ifdef OGDF_FULL_COMPONENT_GENERATION_TERMINAL_SSSP_AWARE
338  const T dist = m_isTerminal[uO] ? m_distance[uO][vO] : m_distance[vO][uO];
339 #else
340  const T dist = m_distance[uO][vO];
341 #endif
342  tree.newEdge(uC, vC, dist);
343  cost += dist;
344  }
345 
346  // recurse
347  for (const DWMData* subgraph : data.subgraphs) {
348  cost += getSteinerTreeFor(*subgraph, tree);
349  }
350  }
351 
353  return cost;
354  }
355 
356 public:
361  const List<node>& terminals, const NodeArray<bool>& isTerminal,
362  const NodeArray<NodeArray<T>>& distance, const NodeArray<NodeArray<edge>>& pred)
363  : m_G(G)
364  , m_terminals(terminals)
365  , m_isTerminal(isTerminal)
366  , m_distance(distance)
367  , m_pred(pred)
368  , m_terminalSubset(m_terminals)
369  , m_map(1 << 22) // we initially allocate 4MB*sizeof(DWMData) for hashing
370  {
371  initializeMap();
372  }
373 
374  void call(int restricted)
375  {
376  OGDF_ASSERT(restricted >= 2);
377  Math::updateMin(restricted, m_terminals.size());
378  for (m_terminalSubset.begin(2, restricted-1); m_terminalSubset.valid(); m_terminalSubset.next()) {
379  if (m_terminalSubset.size() != restricted - 1) {
381  } else { // maximal terminal subset
382  // save time by only adding terminals instead of all nodes
383  computePartialSolutions(m_terminals);
384  }
385  }
386  }
387 
390  T getSteinerTreeFor(const List<node>& terminals, EdgeWeightedGraphCopy<T>& tree) const {
391  tree.createEmpty(m_G);
392  T cost(getSteinerTreeFor(*dataOf(terminals), tree));
393  OGDF_ASSERT(isTree(tree));
394  return cost;
395  }
396 
398  bool isValidComponent(const EdgeWeightedGraphCopy<T>& graph) const {
399  if (graph.empty()) {
400  return false;
401  }
402  for (node v : graph.nodes) {
403  if (m_isTerminal[graph.original(v)] // is a terminal
404  && v->degree() > 1) { // but not a leaf
405  return false;
406  }
407  }
408  return true;
409  }
410 };
411 
412 template<typename T>
414 {
415  static const unsigned int c_prime = 0x7fffffff; // mersenne prime 2**31 - 1
416  // would be nicer: 0x1fffffffffffffff; // mersenne prime 2**61 - 1
417  const int m_random;
418 
419 public:
422  : m_random(randomNumber(2, c_prime - 1))
423  {
424  }
425 
427  unsigned int hash(const List<node> &key) const
428  {
429  unsigned int hash = 0;
430  for (node v : key) {
431  hash = (hash * m_random + v->index()) % c_prime;
432  }
433  return hash;
434  }
435 };
436 
437 }
438 }
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
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 clear()
Clears the buffer.
Definition: ArrayBuffer.h:94
void clear()
Remove all subgraphs and edges and set cost to zero.
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
bool safeIfSumSmaller(const T summand1, const T summand2, const T compareValue) const
Checks overflow-safe if summand1 plus summand2 is less than compareValue.
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 classes used for hashing.
void push(E e)
Puts a new element in the buffer.
Definition: ArrayBuffer.h:102
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...
Extends the GraphCopy concept to weighted graphs.
bool valid() const
Checks if the current subset is valid. If not, the subset is either not initialized or all subsets ha...
const NodeArray< bool > & m_isTerminal
A reference to the terminal incidence vector.
const EdgeWeightedGraph< T > & m_G
A reference to the graph instance.
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 costOf(const List< node > &key) const
Returns the cost of the partial solution given by key.
const List< node > & m_terminals
A reference to the index-sorted list of terminals.
void initializeMap()
Initializes the hash array with all node-terminal-pairs.
SubsetEnumerator< node > m_terminalSubset
Handling subsets of terminals.
void computePartialSolution(NodeArray< DWMSplit > &split, node v, SubsetEnumerator< node > &subset, const List< node > &terminals)
Computes a partial solution for given terminals and node v.
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
unsigned int hash(const List< node > &key) const
The actual hash function.
A generator for restricted full components (for Steiner tree approximations) based on the Dreyfus-Wag...
const_reference front() const
Returns a const reference to the first element.
Definition: List.h:274
Enumerator for k-subsets of a given type.
Doubly linked lists (maintaining the length of the list).
Definition: List.h:40
static uint32_t hash(uint32_t x)
Definition: Map.h:38
void makeKey(List< node > &newSubset, node v) const
Makes a list from the current terminal subset including an correctly inserted node v...
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...
Class for the representation of nodes.
Definition: Graph_d.h:169
const Graph & original() const
Returns a reference to the original graph.
Definition: GraphCopy.h:286
bool hasMember(const T &element) const
Checks in O(subset cardinality) whether element is a member of the subset.
const NodeArray< NodeArray< T > > & m_distance
A reference to the full distance matrix.
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.
void set(const DWMData *s1, const DWMData *s2)
Sets subgraph1 and subgraph2 and computes cost.
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...
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
Hashing< List< node >, DWMData, SortedNodeListHashFunc > m_map
A hash array for keys of size > 2.
void forEachMember(std::function< void(const T &)> func) const
Calls func for each member in the subset.
bool isTree(const Graph &G)
Returns true iff G is a tree, i.e. contains no undirected cycle and is connected. ...
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.
FullComponentGeneratorDreyfusWagner(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal, const NodeArray< NodeArray< T >> &distance, const NodeArray< NodeArray< edge >> &pred)
The constructor.
const NodeArray< NodeArray< edge > > & m_pred
A reference to the full predecessor matrix.
const DWMData * dataOf(const List< node > &key) const
Returns a pointer to the relevant data of the partial solution given by key.
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...
bool isValidComponent(const EdgeWeightedGraphCopy< T > &graph) const
Checks if a given graph is a valid full component.
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...
Subgraphs (given by other subgraphs and additional node pairs) and their cost for a partial solution...
void computePartialSolutions(const CONTAINER &nodeContainer)
Computes all partial solutions for given m_terminalSubset.
A class that allows to enumerate k-subsets.
bool empty() const
Returns true iff the graph is empty, i.e., contains no nodes.
Definition: Graph_d.h:595
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:41
const_reference back() const
Returns a const reference to the last element.
Definition: List.h:292