Version: SMASH-1.8
grid.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2014-2019
4  * SMASH Team
5  *
6  * GNU General Public License (GPLv3 or later)
7  *
8  */
9 
10 #include "smash/grid.h"
11 
12 #include <stdexcept>
13 
14 #include "smash/algorithms.h"
15 #include "smash/fourvector.h"
16 #include "smash/logging.h"
17 #include "smash/particledata.h"
18 #include "smash/threevector.h"
19 
20 namespace std {
21 template <typename T>
22 static std::ostream &operator<<(std::ostream &out, const std::vector<T> &v) {
23  auto column = out.tellp();
24  out << "{ ";
25  for (const auto &x : v) {
26  if (out.tellp() - column >= 100) {
27  out << '\n';
28  column = out.tellp();
29  }
30  out << x << ' ';
31  }
32  return out << '}';
33 }
34 
35 template <typename T>
36 static std::ostream &operator<<(std::ostream &out,
37  const std::initializer_list<T> &v) {
38  auto column = out.tellp();
39  out << "{ ";
40  for (const auto &x : v) {
41  if (out.tellp() - column >= 100) {
42  out << '\n';
43  column = out.tellp();
44  }
45  out << x << ' ';
46  }
47  return out << '}';
48 }
49 
50 template <typename T, std::size_t N>
51 static std::ostream &operator<<(std::ostream &out, const std::array<T, N> &a) {
52  auto column = out.tellp();
53  out << "{ ";
54  for (const auto &x : a) {
55  if (out.tellp() - column >= 100) {
56  out << '\n';
57  column = out.tellp();
58  }
59  out << x << ' ';
60  }
61  return out << '}';
62 }
63 } // namespace std
64 
65 namespace smash {
66 static constexpr int LGrid = LogArea::Grid::id;
67 
69 // GridBase
70 
71 std::pair<std::array<double, 3>, std::array<double, 3>>
73  std::pair<std::array<double, 3>, std::array<double, 3>> r;
74  auto &min_position = r.first;
75  auto &length = r.second;
76 
77  // intialize min and max position arrays with the position of the first
78  // particle in the list
79  const auto &first_position = particles.front().position();
80  min_position = {{first_position[1], first_position[2], first_position[3]}};
81  auto max_position = min_position;
82  for (const auto &p : particles) {
83  const auto &pos = p.position();
84  min_position[0] = std::min(min_position[0], pos[1]);
85  min_position[1] = std::min(min_position[1], pos[2]);
86  min_position[2] = std::min(min_position[2], pos[3]);
87  max_position[0] = std::max(max_position[0], pos[1]);
88  max_position[1] = std::max(max_position[1], pos[2]);
89  max_position[2] = std::max(max_position[2], pos[3]);
90  }
91  length[0] = max_position[0] - min_position[0];
92  length[1] = max_position[1] - min_position[1];
93  length[2] = max_position[2] - min_position[2];
94  return r;
95 }
96 
98 // Grid
99 
100 template <GridOptions O>
101 Grid<O>::Grid(const std::pair<std::array<double, 3>, std::array<double, 3>>
102  &min_and_length,
103  const Particles &particles, double max_interaction_length,
104  double timestep_duration, CellSizeStrategy strategy)
105  : length_(min_and_length.second) {
106  const auto min_position = min_and_length.first;
107  const SizeType particle_count = particles.size();
108 
109  // very simple setup for non-periodic boundaries and largest cellsize strategy
110  if (O == GridOptions::Normal && strategy == CellSizeStrategy::Largest) {
111  number_of_cells_ = {1, 1, 1};
112  cell_volume_ = length_[0] * length_[1] * length_[2];
113  cells_.clear();
114  cells_.reserve(1);
115  cells_.emplace_back(particles.copy_to_vector());
116  return;
117  }
118 
119  // The number of cells is determined by the min and max coordinates where
120  // particles are positioned and the maximal interaction length (which equals
121  // the length of a cell).
122  // But don't let the number of cells exceed the actual number of particles.
123  // That would be overkill. Let max_cells³ ≤ particle_count (conversion to
124  // int truncates).
125  // Consider that particle placement into cells uses half-open intervals. Thus
126  // a cell includes particles in [0, a[. The next cell [a, 2a[. And so on. This
127  // is important for calculating the number of cells. If length * index_factor
128  // (equivalent to length / max_interaction_length) is integral, then
129  // length * index_factor + 1 determines the number of required cells. That's
130  // because the last cell will then store particles in the interval
131  // [length, length + max_interaction_length[. The code below achieves this
132  // effect by rounding down (floor) and adding 1 afterwards.
133  const int max_cells =
134  (O == GridOptions::Normal)
135  ? std::cbrt(particle_count)
136  : std::max(2, static_cast<int>(std::cbrt(particle_count)));
137 
138  // This normally equals 1/max_interaction_length, but if the number of cells
139  // is reduced (because of low density) then this value is smaller.
140  std::array<double, 3> index_factor = {1. / max_interaction_length,
141  1. / max_interaction_length,
142  1. / max_interaction_length};
143  for (std::size_t i = 0; i < number_of_cells_.size(); ++i) {
144  number_of_cells_[i] =
145  (strategy == CellSizeStrategy::Largest)
146  ? 2
147  : static_cast<int>(std::floor(length_[i] * index_factor[i])) +
148  // The last cell in each direction can be smaller than
149  // max_interaction_length. In that case periodic boundaries
150  // will not work correctly. Thus, we need to reduce the number
151  // of cells in that direction by one and make the last cell
152  // larger. This basically merges a smaller boundary cell into
153  // a full cell inside the grid. There's a ~0% chance that the
154  // given boundaries create an integral number of cells with
155  // length of max_interaction_length. Therefore, just make the
156  // default number of cells one less than for non-periodic
157  // boundaries.
158  (O == GridOptions::Normal ? 1 : 0);
159  if (number_of_cells_[i] == 0) {
160  throw std::runtime_error(
161  "Input error: Your Box is too small for the grid."
162  "\nThe minimal length of the box is given by:\n" +
163  std::to_string(max_interaction_length) +
164  " fm with your current timestep size dt.\n"
165  "If you have large timesteps please reduce them."
166  "\nPlease take a look at your config.");
167  }
168  // std::nextafter implements a safety margin so that no valid position
169  // inside the grid can reference an out-of-bounds cell
170  if (number_of_cells_[i] > max_cells) {
171  number_of_cells_[i] = max_cells;
172  index_factor[i] = number_of_cells_[i] / length_[i];
173  while (index_factor[i] * length_[i] >= number_of_cells_[i]) {
174  index_factor[i] = std::nextafter(index_factor[i], 0.);
175  }
176  assert(index_factor[i] * length_[i] < number_of_cells_[i]);
177  } else if (O == GridOptions::PeriodicBoundaries) {
178  if (number_of_cells_[i] == 1) {
179  number_of_cells_[i] = 2;
180  }
181  index_factor[i] = number_of_cells_[i] / length_[i];
182  while (index_factor[i] * length_[i] >= number_of_cells_[i]) {
183  index_factor[i] = std::nextafter(index_factor[i], 0.);
184  }
185  assert(index_factor[i] * length_[i] < number_of_cells_[i]);
186  }
187  }
188 
189  cell_volume_ = (length_[0] / number_of_cells_[0]) *
190  (length_[1] / number_of_cells_[1]) *
191  (length_[2] / number_of_cells_[2]);
192 
193  if (O == GridOptions::Normal &&
194  all_of(number_of_cells_, [](SizeType n) { return n <= 2; })) {
195  // dilute limit:
196  // the grid would have <= 2x2x2 cells, meaning every particle has to be
197  // compared with every other particle anyway. Then we can just as well
198  // fall back to not using the grid at all
199  // For a grid with periodic boundaries the situation is different and we
200  // never want to have a grid smaller than 2x2x2.
201  logg[LGrid].debug(
202  "There would only be ", number_of_cells_,
203  " cells. Therefore the Grid falls back to a single cell / "
204  "particle list.");
205  number_of_cells_ = {1, 1, 1};
206  cell_volume_ = length_[0] * length_[1] * length_[2];
207  cells_.resize(1);
208  cells_.front().reserve(particles.size());
209  std::copy_if(particles.begin(), particles.end(),
210  std::back_inserter(cells_.front()),
211  [&](const ParticleData &p) {
212  return p.xsec_scaling_factor(timestep_duration) > 0.0;
213  }); // filter out the particles that can not interact
214  } else {
215  // construct a normal grid
216  logg[LGrid].debug("min: ", min_position, "\nlength: ", length_,
217  "\ncell_volume: ", cell_volume_,
218  "\ncells: ", number_of_cells_,
219  "\nindex_factor: ", index_factor);
220 
221  // After the grid parameters are determined, we can start placing the
222  // particles in cells.
223  cells_.resize(number_of_cells_[0] * number_of_cells_[1] *
224  number_of_cells_[2]);
225 
226  // Returns the one-dimensional cell-index from the position vector inside
227  // the grid.
228  // This simply calculates the distance to min_position and multiplies it
229  // with index_factor to determine the 3 x,y,z indexes to pass to make_index.
230  auto &&cell_index_for = [&](const ParticleData &p) {
231  return make_index(
232  std::floor((p.position()[1] - min_position[0]) * index_factor[0]),
233  std::floor((p.position()[2] - min_position[1]) * index_factor[1]),
234  std::floor((p.position()[3] - min_position[2]) * index_factor[2]));
235  };
236 
237  for (const auto &p : particles) {
238  if (p.xsec_scaling_factor(timestep_duration) > 0.0) {
239  const auto idx = cell_index_for(p);
240 #ifndef NDEBUG
241  if (idx >= SizeType(cells_.size())) {
242  logg[LGrid].fatal(
244  "\nan out-of-bounds access would be necessary for the "
245  "particle ",
246  p, "\nfor a grid with the following parameters:\nmin: ",
247  min_position, "\nlength: ", length_,
248  "\ncells: ", number_of_cells_, "\nindex_factor: ", index_factor,
249  "\ncells_.size: ", cells_.size(), "\nrequested index: ", idx);
250  throw std::runtime_error("out-of-bounds grid access on construction");
251  }
252 #endif
253  cells_[idx].push_back(p);
254  }
255  }
256  }
257 
258  logg[LGrid].debug(cells_);
259 }
260 
261 template <GridOptions Options>
263  SizeType x, SizeType y, SizeType z) const {
264  return (z * number_of_cells_[1] + y) * number_of_cells_[0] + x;
265 }
266 
267 static const std::initializer_list<GridBase::SizeType> ZERO{0};
268 static const std::initializer_list<GridBase::SizeType> ZERO_ONE{0, 1};
269 static const std::initializer_list<GridBase::SizeType> MINUS_ONE_ZERO{-1, 0};
270 static const std::initializer_list<GridBase::SizeType> MINUS_ONE_ZERO_ONE{-1, 0,
271  1};
272 
273 template <>
276  const std::function<void(const ParticleList &)> &search_cell_callback,
277  const std::function<void(const ParticleList &, const ParticleList &)>
278  &neighbor_cell_callback) const {
279  std::array<SizeType, 3> search_index;
280  SizeType &x = search_index[0];
281  SizeType &y = search_index[1];
282  SizeType &z = search_index[2];
283  SizeType search_cell_index = 0;
284  for (z = 0; z < number_of_cells_[2]; ++z) {
285  for (y = 0; y < number_of_cells_[1]; ++y) {
286  for (x = 0; x < number_of_cells_[0]; ++x, ++search_cell_index) {
287  assert(search_cell_index == make_index(search_index));
288  assert(search_cell_index >= 0);
289  assert(search_cell_index < SizeType(cells_.size()));
290  const ParticleList &search = cells_[search_cell_index];
291  search_cell_callback(search);
292 
293  const auto &dz_list = z == number_of_cells_[2] - 1 ? ZERO : ZERO_ONE;
294  const auto &dy_list = number_of_cells_[1] == 1
295  ? ZERO
296  : y == 0 ? ZERO_ONE
297  : y == number_of_cells_[1] - 1
300  const auto &dx_list = number_of_cells_[0] == 1
301  ? ZERO
302  : x == 0 ? ZERO_ONE
303  : x == number_of_cells_[0] - 1
306  for (SizeType dz : dz_list) {
307  for (SizeType dy : dy_list) {
308  for (SizeType dx : dx_list) {
309  const auto di = make_index(dx, dy, dz);
310  if (di > 0) {
311  neighbor_cell_callback(search, cells_[search_cell_index + di]);
312  }
313  }
314  }
315  }
316  }
317  }
318  }
319 }
320 
330 
336  NeedsToWrap wrap = NeedsToWrap::No;
337 };
338 
339 template <>
342  const std::function<void(const ParticleList &)> &search_cell_callback,
343  const std::function<void(const ParticleList &, const ParticleList &)>
344  &neighbor_cell_callback) const {
345  std::array<SizeType, 3> search_index;
346  SizeType &x = search_index[0];
347  SizeType &y = search_index[1];
348  SizeType &z = search_index[2];
349  SizeType search_cell_index = 0;
350 
351  // defaults:
352  std::array<NeighborLookup, 2> dz_list;
353  std::array<NeighborLookup, 3> dy_list;
354  std::array<NeighborLookup, 3> dx_list;
355 
356  assert(number_of_cells_[2] >= 2);
357  assert(number_of_cells_[1] >= 2);
358  assert(number_of_cells_[0] >= 2);
359 
360  for (z = 0; z < number_of_cells_[2]; ++z) {
361  dz_list[0].index = z;
362  dz_list[1].index = z + 1;
363  if (dz_list[1].index == number_of_cells_[2]) {
364  dz_list[1].index = 0;
365  // last z in the loop, so no need to reset wrap again
366  dz_list[1].wrap = NeedsToWrap::MinusLength;
367  }
368  for (y = 0; y < number_of_cells_[1]; ++y) {
369  dy_list[0].index = y;
370  dy_list[1].index = y - 1;
371  dy_list[2].index = y + 1;
372  dy_list[2].wrap = NeedsToWrap::No;
373  if (y == 0) {
374  dy_list[1] = dy_list[2];
375  dy_list[2].index = number_of_cells_[1] - 1;
376  dy_list[2].wrap = NeedsToWrap::PlusLength;
377  } else if (dy_list[2].index == number_of_cells_[1]) {
378  dy_list[2].index = 0;
379  dy_list[2].wrap = NeedsToWrap::MinusLength;
380  }
381  for (x = 0; x < number_of_cells_[0]; ++x, ++search_cell_index) {
382  dx_list[0].index = x;
383  dx_list[1].index = x - 1;
384  dx_list[2].index = x + 1;
385  dx_list[2].wrap = NeedsToWrap::No;
386  if (x == 0) {
387  dx_list[1] = dx_list[2];
388  dx_list[2].index = number_of_cells_[0] - 1;
389  dx_list[2].wrap = NeedsToWrap::PlusLength;
390  } else if (dx_list[2].index == number_of_cells_[0]) {
391  dx_list[2].index = 0;
392  dx_list[2].wrap = NeedsToWrap::MinusLength;
393  }
394 
395  assert(search_cell_index == make_index(search_index));
396  assert(search_cell_index >= 0);
397  assert(search_cell_index < SizeType(cells_.size()));
398  ParticleList search = cells_[search_cell_index];
399  search_cell_callback(search);
400 
401  auto virtual_search_index = search_index;
402  ThreeVector wrap_vector = {}; // no change
403  auto current_wrap_vector = wrap_vector;
404 
405  for (const auto &dz : dz_list) {
406  if (dz.wrap == NeedsToWrap::MinusLength) {
407  // last dz in the loop, so no need to undo the wrap
408  wrap_vector[2] = -length_[2];
409  virtual_search_index[2] = -1;
410  }
411  for (const auto &dy : dy_list) {
412  // only the last dy in dy_list can wrap
413  if (dy.wrap == NeedsToWrap::MinusLength) {
414  wrap_vector[1] = -length_[1];
415  virtual_search_index[1] = -1;
416  } else if (dy.wrap == NeedsToWrap::PlusLength) {
417  wrap_vector[1] = length_[1];
418  virtual_search_index[1] = number_of_cells_[1];
419  }
420  for (const auto &dx : dx_list) {
421  // only the last dx in dx_list can wrap
422  if (dx.wrap == NeedsToWrap::MinusLength) {
423  wrap_vector[0] = -length_[0];
424  virtual_search_index[0] = -1;
425  } else if (dx.wrap == NeedsToWrap::PlusLength) {
426  wrap_vector[0] = length_[0];
427  virtual_search_index[0] = number_of_cells_[0];
428  }
429  assert(dx.index >= 0);
430  assert(dx.index < number_of_cells_[0]);
431  assert(dy.index >= 0);
432  assert(dy.index < number_of_cells_[1]);
433  assert(dz.index >= 0);
434  assert(dz.index < number_of_cells_[2]);
435  const auto neighbor_cell_index =
436  make_index(dx.index, dy.index, dz.index);
437  assert(neighbor_cell_index >= 0);
438  assert(neighbor_cell_index < SizeType(cells_.size()));
439  if (neighbor_cell_index <= make_index(virtual_search_index)) {
440  continue;
441  }
442 
443  if (wrap_vector != current_wrap_vector) {
444  logg[LGrid].debug("translating search cell by ",
445  wrap_vector - current_wrap_vector);
446  for_each(search, [&](ParticleData &p) {
447  p = p.translated(wrap_vector - current_wrap_vector);
448  });
449  current_wrap_vector = wrap_vector;
450  }
451  neighbor_cell_callback(search, cells_[neighbor_cell_index]);
452  }
453  virtual_search_index[0] = search_index[0];
454  wrap_vector[0] = 0;
455  }
456  virtual_search_index[1] = search_index[1];
457  wrap_vector[1] = 0;
458  }
459  }
460  }
461  }
462 }
463 
465  const std::pair<std::array<double, 3>, std::array<double, 3>>
466  &min_and_length,
467  const Particles &particles, double max_interaction_length,
468  double timestep_duration, CellSizeStrategy strategy);
470  const std::pair<std::array<double, 3>, std::array<double, 3>>
471  &min_and_length,
472  const Particles &particles, double max_interaction_length,
473  double timestep_duration, CellSizeStrategy strategy);
474 } // namespace smash
smash
Definition: action.h:24
smash::MINUS_ONE_ZERO_ONE
static const std::initializer_list< GridBase::SizeType > MINUS_ONE_ZERO_ONE
Definition: grid.cc:270
particledata.h
algorithms.h
smash::for_each
UnaryFunction for_each(Container &&c, UnaryFunction &&f)
Convenience wrapper for std::for_each that operates on a complete container.
Definition: algorithms.h:96
smash::Particles::size
size_t size() const
Definition: particles.h:87
smash::MINUS_ONE_ZERO
static const std::initializer_list< GridBase::SizeType > MINUS_ONE_ZERO
Definition: grid.cc:269
smash::ParticleData
Definition: particledata.h:52
smash::Particles::begin
iterator begin()
Definition: particles.h:380
grid.h
fourvector.h
smash::CellSizeStrategy
CellSizeStrategy
Indentifies the strategy of determining the cell size.
Definition: grid.h:33
smash::logg
std::array< einhard::Logger<>, std::tuple_size< LogArea::AreaTuple >::value > logg
An array that stores all pre-configured Logger objects.
Definition: logging.cc:39
smash::all_of
bool all_of(Container &&c, UnaryPredicate &&p)
Convenience wrapper for std::all_of that operates on a complete container.
Definition: algorithms.h:80
smash::Particles::end
iterator end()
Definition: particles.h:404
smash::ThreeVector
Definition: threevector.h:31
source_location
#define source_location
Hackery that is required to output the location in the source code where the log statement occurs.
Definition: logging.h:240
OutputOnlyFinal::No
Print initial, intermediate and final-state particles.
smash::Particles::copy_to_vector
ParticleList copy_to_vector() const
Definition: particles.h:44
smash::LGrid
static constexpr int LGrid
Definition: grid.cc:66
smash::ZERO
static const std::initializer_list< GridBase::SizeType > ZERO
Definition: grid.cc:267
smash::ParticleData::position
const FourVector & position() const
Get the particle's position in Minkowski space.
Definition: particledata.h:188
threevector.h
smash::Grid
Abstracts a list of cells that partition the particles in the experiment into regions of space that c...
Definition: grid.h:79
smash::NeedsToWrap::PlusLength
smash::GridBase::SizeType
int SizeType
A type to store the sizes.
Definition: grid.h:53
smash::NeighborLookup
A strust containing the informations needed to search the neighboring cell.
Definition: grid.cc:332
smash::Particles
Definition: particles.h:33
smash::NeedsToWrap
NeedsToWrap
The options determining what to do if a particle flies out of the grids PlusLength: Used if a periodi...
Definition: grid.cc:329
smash::ZERO_ONE
static const std::initializer_list< GridBase::SizeType > ZERO_ONE
Definition: grid.cc:268
logging.h
smash::Grid::Grid
Grid(const Particles &particles, double min_cell_length, double timestep_duration, CellSizeStrategy strategy=CellSizeStrategy::Optimal)
Constructs a grid from the given particle list particles.
Definition: grid.h:93
smash::Particles::front
ParticleData & front()
Definition: particles.h:359
smash::pdg::p
constexpr int p
Proton.
Definition: pdgcode_constants.h:28
smash::pdg::n
constexpr int n
Neutron.
Definition: pdgcode_constants.h:30
smash::GridBase::find_min_and_length
static std::pair< std::array< double, 3 >, std::array< double, 3 > > find_min_and_length(const Particles &particles)
Definition: grid.cc:72
smash::NeedsToWrap::MinusLength