Tpetra Matrix/Vector Services  Version of the Day
Tpetra_Details_FixedHashTable_def.hpp
1 /*
2 // @HEADER
3 // ***********************************************************************
4 //
5 // Tpetra: Templated Linear Algebra Services Package
6 // Copyright (2008) Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
39 //
40 // ************************************************************************
41 // @HEADER
42 */
43 
44 #ifndef TPETRA_DETAILS_FIXEDHASHTABLE_DEF_HPP
45 #define TPETRA_DETAILS_FIXEDHASHTABLE_DEF_HPP
46 
47 #ifdef DOXYGEN_USE_ONLY
48  #include "Tpetra_Details_FixedHashTable_decl.hpp"
49 #endif
50 
51 #include <Teuchos_as.hpp>
52 #include "MurmurHash3.hpp"
53 
54 
55 namespace Tpetra {
56 namespace Details {
57 
58 template<typename KeyType, typename ValueType>
59 int FixedHashTable<KeyType, ValueType>::hashFunc (const KeyType key) const {
60 #ifdef TPETRA_USE_MURMUR_HASH
61  uint32_t k;
62  MurmurHash3_x86_32 ((void *) &key, sizeof (KeyType), 1, (void *) &k);
63  return (int) (k % size_);
64 #else
65  // We are using Epetra's hash function by default, as we have
66  // observed that it is much faster than the Murmur hash
67  // function. However, this is not a good hash function for general
68  // sets of keys. For our typical use case, this is good. Use
69  // Murmur hash if the maps are sparse.
70  const unsigned int seed = (2654435761U);
71 
72 #ifdef HAVE_TPETRA_DEBUG
74  size_ == 0, std::logic_error, "Tpetra::Details::FixedHashTable::hashFunc: "
75  "size_ == 0. Please report this bug to the Tpetra developers.");
76 #endif // HAVE_TPETRA_DEBUG
77 
78  const int intkey = (int) ((key & 0x000000007fffffffLL) +
79  ((key & 0x7fffffff80000000LL) >> 31));
80  return (int) ((seed ^ intkey) % size_);
81 #endif
82 }
83 
84 template<typename KeyType, typename ValueType>
85 int
86 FixedHashTable<KeyType, ValueType>::getRecommendedSize (const int size)
87 {
88  // A large list of prime numbers.
89  // Based on a recommendation by Andres Valloud in hash forums.
90  // There are only enough primes here so that between any number N and 2*N,
91  // there will be at least about 8 to choose from (except the first 10).
92  // This is a balance between a small list of primes, and getting a
93  // collection size that doesn't waste too much space. In addition,
94  // the primes in this table were chosen so that they do not divide
95  // 256^k +- a, for 1<=k<=8, and -32<=a<=32. This is so that
96  // using them as a modulo will not have a tendency to just throw away
97  // the most significant bits of the object's hash. The primes (except the
98  // first ten) or not close to any power of two to avoid aliasing
99  // between hash functions based on bit manipulation and the moduli.
100  int primes [ ] = {
101  3, 7, 13, 23, 53, 97, 193, 389, 769, 1543,
102  2237, 2423, 2617, 2797, 2999, 3167, 3359, 3539,
103  3727, 3911, 4441 , 4787 , 5119 , 5471 , 5801 , 6143 , 6521 , 6827
104  , 7177 , 7517 , 7853 , 8887 , 9587 , 10243 , 10937 , 11617 , 12289
105  , 12967 , 13649 , 14341 , 15013 , 15727
106  , 17749 , 19121 , 20479 , 21859 , 23209 , 24593 , 25939 , 27329
107  , 28669 , 30047 , 31469 , 35507 , 38231 , 40961 , 43711 , 46439
108  , 49157 , 51893 , 54617 , 57347 , 60077 , 62801 , 70583 , 75619
109  , 80669 , 85703 , 90749 , 95783 , 100823 , 105871 , 110909 , 115963
110  , 120997 , 126031 , 141157 , 151237 , 161323 , 171401 , 181499 , 191579
111  , 201653 , 211741 , 221813 , 231893 , 241979 , 252079
112  , 282311 , 302483 , 322649 , 342803 , 362969 , 383143 , 403301 , 423457
113  , 443629 , 463787 , 483953 , 504121 , 564617 , 604949 , 645313 , 685609
114  , 725939 , 766273 , 806609 , 846931 , 887261 , 927587 , 967919 , 1008239
115  , 1123477 , 1198397 , 1273289 , 1348177 , 1423067 , 1497983 , 1572869
116  , 1647761 , 1722667 , 1797581 , 1872461 , 1947359 , 2022253
117  , 2246953 , 2396759 , 2546543 , 2696363 , 2846161 , 2995973 , 3145739
118  , 3295541 , 3445357 , 3595117 , 3744941 , 3894707 , 4044503
119  , 4493921 , 4793501 , 5093089 , 5392679 , 5692279 , 5991883 , 6291469
120  , 6591059 , 6890641 , 7190243 , 7489829 , 7789447 , 8089033
121  , 8987807 , 9586981 , 10186177 , 10785371 , 11384539 , 11983729
122  , 12582917 , 13182109 , 13781291 , 14380469 , 14979667 , 15578861
123  , 16178053 , 17895707 , 19014187 , 20132683 , 21251141 , 22369661
124  , 23488103 , 24606583 , 25725083 , 26843549 , 27962027 , 29080529
125  , 30198989 , 31317469 , 32435981 , 35791397 , 38028379 , 40265327
126  , 42502283 , 44739259 , 46976221 , 49213237 , 51450131 , 53687099
127  , 55924061 , 58161041 , 60397993 , 62634959 , 64871921
128  , 71582857 , 76056727 , 80530643 , 85004567 , 89478503 , 93952427
129  , 98426347 , 102900263 , 107374217 , 111848111 , 116322053 , 120795971
130  , 125269877 , 129743807 , 143165587 , 152113427 , 161061283 , 170009141
131  , 178956983 , 187904819 , 196852693 , 205800547 , 214748383 , 223696237
132  , 232644089 , 241591943 , 250539763 , 259487603 , 268435399 };
133 
134  int hsize = primes[220] ;
135  for (int i = 0; i < 221; ++i) {
136  if (size <= primes[i]) {
137  hsize = primes[i];
138  break;
139  }
140  }
141  return hsize;
142 }
143 
144 template<typename KeyType, typename ValueType>
147  size_ (0),
148  rawPtr_ (NULL),
149  rawVal_ (NULL)
150 {
151  init (keys, Teuchos::as<ValueType> (0));
152 }
153 
154 template<typename KeyType, typename ValueType>
157  const ValueType startingValue) :
158  size_ (0),
159  rawPtr_ (NULL),
160  rawVal_ (NULL)
161 {
162  init (keys, startingValue);
163 }
164 
165 template<typename KeyType, typename ValueType>
168  const ArrayView<const ValueType>& vals) :
169  size_ (0),
170  rawPtr_ (NULL),
171  rawVal_ (NULL)
172 {
173  init (keys, vals);
174 }
175 
176 template<typename KeyType, typename ValueType>
177 void
179 init (const ArrayView<const KeyType>& keys,
180  const ValueType startingValue)
181 {
182  using Teuchos::arcp;
183  using Teuchos::arcp_const_cast;
184  using Teuchos::ArrayRCP;
185  using Teuchos::as;
186 
187  const size_type numKeys = keys.size ();
188  const size_type size = getRecommendedSize (as<int> (numKeys));
189 #ifdef HAVE_TPETRA_DEBUG
191  size == 0 && numKeys != 0, std::logic_error,
192  "Tpetra::Details::FixedHashTable constructor: "
193  "getRecommendedSize(" << numKeys << ") returned zero, "
194  "even though the number of keys " << numKeys << " is nonzero. "
195  "Please report this bug to the Tpetra developers.");
196 #endif // HAVE_TPETRA_DEBUG
197 
198  // We have to set the size_ internal state before calling the hash
199  // function, since the hash function uses it.
200  size_ = as<KeyType> (size);
201 
202  ArrayRCP<size_type> ptr (size + 1, 0);
203  // The constructor that takes just a size argument automatically
204  // fills the data. We don't need to waste time filling it here
205  // because we will do so below. The try/catch block isn't strictly
206  // necessary; we could just give "new std::pair<...> [numKeys]" to
207  // the ArrayRCP constructor, since no other arguments of the
208  // constructor might throw before entering the constructor.
210  std::pair<KeyType, ValueType>* rawVal = NULL;
211  try {
212  rawVal = new std::pair<KeyType, ValueType> [numKeys];
213  val = arcp<std::pair<KeyType, ValueType> > (rawVal, 0, numKeys, true);
214  } catch (...) {
215  if (rawVal != NULL) {
216  delete [] rawVal;
217  }
218  throw;
219  }
220 
221  // Compute number of entries in each hash table position.
222  for (size_type k = 0; k < numKeys; ++k) {
223  const int hashVal = hashFunc (keys[k]);
224  // Shift over one, so that counts[j] = ptr[j+1]. See below.
225  ++ptr[hashVal+1];
226  }
227 
228  // Compute row offsets via prefix sum:
229  //
230  // ptr[i+1] = \sum_{j=0}^{i} counts[j].
231  //
232  // Thus, ptr[i+1] - ptr[i] = counts[i], so that ptr[i+1] = ptr[i] +
233  // counts[i]. If we stored counts[i] in ptr[i+1] on input, then the
234  // formula is ptr[i+1] += ptr[i].
235  for (size_type i = 0; i < size; ++i) {
236  ptr[i+1] += ptr[i];
237  }
238  //ptr[0] = 0; // We've already done this when initializing ptr above.
239 
240  // curRowStart[i] is the offset of the next element in row i.
241  ArrayRCP<size_type> curRowStart (size, 0);
242 
243  // Fill in the hash table.
244  for (size_type k = 0; k < numKeys; ++k) {
245  const KeyType key = keys[k];
246  const ValueType theVal = startingValue + as<ValueType> (k);
247  const int hashVal = hashFunc (key);
248 
249  const size_type offset = curRowStart[hashVal];
250  const size_type curPos = ptr[hashVal] + offset;
251 
252  val[curPos].first = key;
253  val[curPos].second = theVal;
254  ++curRowStart[hashVal];
255  }
256 
257  // "Commit" the computed arrays.
258  ptr_ = arcp_const_cast<const size_type> (ptr);
259 
260  // FIXME (mfh 25 Apr 2013) arcp_const_cast on val_ and
261  // val_.getRawPtr() both cause a hang with MPI for some reason. Not
262  // sure what's going on. Anyway, calling val.release(), recreating
263  // val_ by hand, and using the released raw pointer as rawVal_,
264  // seems to fix the problem.
265 
266  //val_ = arcp_const_cast<const std::pair<KeyType, ValueType> > (val);
267  const std::pair<KeyType, ValueType>* valRaw = val.release ();
268  val_ = ArrayRCP<const std::pair<KeyType, ValueType> > (valRaw, 0, numKeys, true);
269  //val_ = arcp<const std::pair<KeyType, ValueType> > (valRaw, 0, numKeys, true);
270  rawPtr_ = ptr_.getRawPtr ();
271  // rawVal_ = val_.getRawPtr ();
272  rawVal_ = valRaw;
273 }
274 
275 
276 template<typename KeyType, typename ValueType>
277 void
279 init (const ArrayView<const KeyType>& keys,
280  const ArrayView<const ValueType>& vals)
281 {
282  using Teuchos::arcp;
283  using Teuchos::arcp_const_cast;
284  using Teuchos::ArrayRCP;
285  using Teuchos::as;
286 
287  const size_type numKeys = keys.size ();
288  const size_type size = getRecommendedSize (as<int> (numKeys));
289 #ifdef HAVE_TPETRA_DEBUG
291  size == 0 && numKeys != 0, std::logic_error,
292  "Tpetra::Details::FixedHashTable constructor: "
293  "getRecommendedSize(" << numKeys << ") returned zero, "
294  "even though the number of keys " << numKeys << " is nonzero. "
295  "Please report this bug to the Tpetra developers.");
296 #endif // HAVE_TPETRA_DEBUG
297 
298  // We have to set the size_ internal state before calling the hash
299  // function, since the hash function uses it.
300  size_ = as<KeyType> (size);
301 
302  ArrayRCP<size_type> ptr (size + 1, 0);
303  // The constructor that takes just a size argument automatically
304  // fills the data. We don't need to waste time filling it here
305  // because we will do so below. The try/catch block isn't strictly
306  // necessary; we could just give "new std::pair<...> [numKeys]" to
307  // the ArrayRCP constructor, since no other arguments of the
308  // constructor might throw before entering the constructor.
310  std::pair<KeyType, ValueType>* rawVal = NULL;
311  try {
312  rawVal = new std::pair<KeyType, ValueType> [numKeys];
313  val = arcp<std::pair<KeyType, ValueType> > (rawVal, 0, numKeys, true);
314  } catch (...) {
315  if (rawVal != NULL) {
316  delete [] rawVal;
317  }
318  throw;
319  }
320 
321  // Compute number of entries in each hash table position.
322  for (size_type k = 0; k < numKeys; ++k) {
323  const int hashVal = hashFunc (keys[k]);
324  // Shift over one, so that counts[j] = ptr[j+1]. See below.
325  ++ptr[hashVal+1];
326  }
327 
328  // Compute row offsets via prefix sum:
329  //
330  // ptr[i+1] = \sum_{j=0}^{i} counts[j].
331  //
332  // Thus, ptr[i+1] - ptr[i] = counts[i], so that ptr[i+1] = ptr[i] +
333  // counts[i]. If we stored counts[i] in ptr[i+1] on input, then the
334  // formula is ptr[i+1] += ptr[i].
335  for (size_type i = 0; i < size; ++i) {
336  ptr[i+1] += ptr[i];
337  }
338  //ptr[0] = 0; // We've already done this when initializing ptr above.
339 
340  // curRowStart[i] is the offset of the next element in row i.
341  ArrayRCP<size_type> curRowStart (size, 0);
342 
343  // Fill in the hash table.
344  for (size_type k = 0; k < numKeys; ++k) {
345  const KeyType key = keys[k];
346  const ValueType theVal = vals[k];
347  const int hashVal = hashFunc (key);
348 
349  const size_type offset = curRowStart[hashVal];
350  const size_type curPos = ptr[hashVal] + offset;
351 
352  val[curPos].first = key;
353  val[curPos].second = theVal;
354  ++curRowStart[hashVal];
355  }
356 
357  // "Commit" the computed arrays.
358  ptr_ = arcp_const_cast<const size_type> (ptr);
359 
360  // FIXME (mfh 25 Apr 2013) arcp_const_cast on val_ and
361  // val_.getRawPtr() both cause a hang with MPI for some reason. Not
362  // sure what's going on. Anyway, calling val.release(), recreating
363  // val_ by hand, and using the released raw pointer as rawVal_,
364  // seems to fix the problem.
365 
366  //val_ = arcp_const_cast<const std::pair<KeyType, ValueType> > (val);
367  const std::pair<KeyType, ValueType>* valRaw = val.release ();
368  val_ = ArrayRCP<const std::pair<KeyType, ValueType> > (valRaw, 0, numKeys, true);
369  //val_ = arcp<const std::pair<KeyType, ValueType> > (valRaw, 0, numKeys, true);
370  rawPtr_ = ptr_.getRawPtr ();
371  // rawVal_ = val_.getRawPtr ();
372  rawVal_ = valRaw;
373 }
374 
375 
376 template<typename KeyType, typename ValueType>
379  size_ (obj.size_),
380  ptr_ (obj.ptr_),
381  val_ (obj.val_),
382  rawPtr_ (obj.rawPtr_),
383  rawVal_ (obj.rawVal_)
384 {}
385 
386 template<typename KeyType, typename ValueType>
387 ValueType
389 get (const KeyType key) const
390 {
391  const int hashVal = hashFunc (key);
392 #ifdef HAVE_TPETRA_DEBUG
393 
394  const size_type start = ptr_[hashVal];
395  const size_type end = ptr_[hashVal+1];
396  for (size_type k = start; k < end; ++k) {
397  if (val_[k].first == key) {
398  return val_[k].second;
399  }
400  }
401 #else
402  const size_type start = rawPtr_[hashVal];
403  const size_type end = rawPtr_[hashVal+1];
404  for (size_type k = start; k < end; ++k) {
405  if (rawVal_[k].first == key) {
406  return rawVal_[k].second;
407  }
408  }
409 #endif // HAVE_TPETRA_DEBUG
411 }
412 
413 template <typename KeyType, typename ValueType>
415  std::ostringstream oss;
416  oss << "FixedHashTable<"
419  << "{ numKeys: " << val_.size ()
420  << ", tableSize: " << ptr_.size () << " }";
421  return oss.str();
422 }
423 
424 template <typename KeyType, typename ValueType>
425 void
428  const Teuchos::EVerbosityLevel verbLevel) const
429 {
430  using std::endl;
431  using std::setw;
432  using Teuchos::OSTab;
433  using Teuchos::rcpFromRef;
435  using Teuchos::VERB_DEFAULT;
436  using Teuchos::VERB_NONE;
437  using Teuchos::VERB_LOW;
438  using Teuchos::VERB_EXTREME;
439 
440  Teuchos::EVerbosityLevel vl = verbLevel;
441  if (vl == VERB_DEFAULT) vl = VERB_LOW;
442 
443  if (vl == VERB_NONE) {
444  // do nothing
445  }
446  else if (vl == VERB_LOW) {
447  out << this->description() << endl;
448  }
449  else { // MEDIUM, HIGH or EXTREME
450  out << "FixedHashTable:" << endl;
451  {
452  OSTab tab1 (rcpFromRef (out));
453 
454  const std::string label = this->getObjectLabel ();
455  if (label != "") {
456  out << "label: " << label << endl;
457  }
458  out << "Template parameters:" << endl;
459  {
460  OSTab tab2 (rcpFromRef (out));
461  out << "KeyType: " << TypeNameTraits<KeyType>::name () << endl
462  << "ValueType: " << TypeNameTraits<ValueType>::name () << endl;
463  }
464 
465  const size_type tableSize = size_;
466  const size_type numKeys = val_.size ();
467 
468  out << "Table parameters:" << endl;
469  {
470  OSTab tab2 (rcpFromRef (out));
471  out << "numKeys: " << numKeys << endl
472  << "tableSize: " << tableSize << endl;
473  }
474 
475  if (vl >= VERB_EXTREME) {
476  out << "Contents: ";
477  if (tableSize == 0 || numKeys == 0) {
478  out << "[]" << endl;
479  } else {
480  out << "[ " << endl;
481  {
482  OSTab tab2 (rcpFromRef (out));
483  for (size_type i = 0; i < tableSize; ++i) {
484  OSTab tab3 (rcpFromRef (out));
485  out << "[";
486  for (size_type k = ptr_[i]; k < ptr_[i+1]; ++k) {
487  out << "(" << val_[k].first << "," << val_[k].second << ")";
488  if (k + 1 < ptr_[i+1]) {
489  out << ", ";
490  }
491  }
492  out << "]" << endl;
493  } // for each table position i
494  }
495  out << "]" << endl;
496  } // The table contains entries
497  } // vl >= VERB_EXTREME
498  }
499  out << endl;
500  } // if vl > VERB_LOW
501 }
502 
503 } // namespace Details
504 } // namespace Tpetra
505 
506 // Macro that explicitly instantiates FixedHashTable for the given local
507 // ordinal (LO) and global ordinal (GO) types. Note that FixedHashTable's
508 // template parameters occur in the opposite order of most Tpetra
509 // classes. This is because FixedHashTable performs global-to-local
510 // lookup, and the convention in templated C++ lookup tables (such as
511 // std::map) is <KeyType, ValueType>.
512 //
513 // This macro must be explanded within the Tpetra::Details namespace.
514 #define TPETRA_DETAILS_FIXEDHASHTABLE_INSTANT_DEFAULTNODE(LO,GO) \
515  template class FixedHashTable< GO , LO >; \
516 
517 #endif // TPETRA_DETAILS_FIXEDHASHTABLE_DEF_HPP
Namespace Tpetra contains the class and methods constituting the Tpetra library.
virtual std::string getObjectLabel() const
basic_OSTab< char > OSTab
ValueType get(const KeyType key) const
Get the value corresponding to the given key.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
T * getRawPtr() const
size_type size() const
std::string description() const
Implementation of Teuchos::Describable.
size_type size() const
Implementation details of Tpetra.
FixedHashTable(const ArrayView< const KeyType > &keys)
Constructor for arbitrary keys and contiguous values starting with zero.
void describe(Teuchos::FancyOStream &out, const Teuchos::EVerbosityLevel verbLevel=Teuchos::Describable::verbLevel_default) const
Print this object with the given verbosity to the output stream.
TypeTo as(const TypeFrom &t)
static std::string name()