NuTo
Numerics Tool
NaturalCoordinateMemoizer.h
Go to the documentation of this file.
1 #pragma once
2 #include <Eigen/Core>
3 #include <map>
4 namespace NuTo
5 {
6 
7 template <typename TVector>
9 {
10 
14  bool operator()(const TVector& l, const TVector& r) const
15  {
16  assert(l.rows() == r.rows());
17  switch (l.rows())
18  {
19  case 1:
20  return l[0] < r[0];
21  case 2:
22  return std::tie(l[0], l[1]) < std::tie(r[0], r[1]);
23  case 3:
24  return std::tie(l[0], l[1], l[2]) < std::tie(r[0], r[1], r[2]);
25  default:
26  throw;
27  }
28  }
29 };
30 
31 // https://en.wikipedia.org/wiki/Memoization: Not to be confused with Memorization.
32 template <typename TResult, typename TNaturalCoords, typename TCompare = CompareVector<TNaturalCoords>>
34 {
35 public:
38  NaturalCoordinateMemoizerMap(std::function<TResult(TNaturalCoords)> function)
39  : mFunction(function)
40  {
41  }
42 
48  const TResult& Get(const TNaturalCoords& v) const
49  {
50  auto it = mCache.find(v);
51  if (it == mCache.end())
52  {
53 // The memoizer is shared between all threads in the parallel assembly.
54 // If it is still empty, all threads want to calculate and emplace the values
55 // into the cache. This will cause problems like infinite recursions, segfaults
56 // during map::rebalancing and so on. Thus: omp critical.
57 // The 'hot' path however, this the code above, which is hopefully not
58 // affected by the performance loss of omp critical.
59 #ifdef _OPENMP
60 #pragma omp critical
61 #endif
62  it = mCache.emplace_hint(it, v, mFunction(v));
63  }
64 
65  return it->second;
66  }
67 
68  void ClearCache() const
69  {
70  mCache.clear();
71  }
72 
73 private:
75  mutable std::map<TNaturalCoords, TResult, TCompare> mCache;
76 
77  std::function<TResult(TNaturalCoords)> mFunction;
78 };
79 
80 
81 } /* NuTo */
const TResult & Get(const TNaturalCoords &v) const
returns the value of the function for the given arguments.
Definition: NaturalCoordinateMemoizer.h:48
bool operator()(const TVector &l, const TVector &r) const
defines a compare operator, following the compare concept http://en.cppreference.com/w/cpp/concept/Co...
Definition: NaturalCoordinateMemoizer.h:14
NaturalCoordinateMemoizerMap(std::function< TResult(TNaturalCoords)> function)
ctor
Definition: NaturalCoordinateMemoizer.h:38
Definition: NaturalCoordinateMemoizer.h:8
int v
Definition: Quad2DPatchTest.py:9
Definition: Exception.h:6
Definition: NaturalCoordinateMemoizer.h:33
void ClearCache() const
Definition: NaturalCoordinateMemoizer.h:68