Version: SMASH-2.2
grid.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2014-2022
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 {
26 template <typename T>
27 static std::ostream &operator<<(std::ostream &out, const std::vector<T> &v) {
28  auto column = out.tellp();
29  out << "{ ";
30  for (const auto &x : v) {
31  if (out.tellp() - column >= 100) {
32  out << '\n';
33  column = out.tellp();
34  }
35  out << x << ' ';
36  }
37  return out << '}';
38 }
39 
45 template <typename T>
46 static std::ostream &operator<<(std::ostream &out,
47  const std::initializer_list<T> &v) {
48  auto column = out.tellp();
49  out << "{ ";
50  for (const auto &x : v) {
51  if (out.tellp() - column >= 100) {
52  out << '\n';
53  column = out.tellp();
54  }
55  out << x << ' ';
56  }
57  return out << '}';
58 }
59 
65 template <typename T, std::size_t N>
66 static std::ostream &operator<<(std::ostream &out, const std::array<T, N> &a) {
67  auto column = out.tellp();
68  out << "{ ";
69  for (const auto &x : a) {
70  if (out.tellp() - column >= 100) {
71  out << '\n';
72  column = out.tellp();
73  }
74  out << x << ' ';
75  }
76  return out << '}';
77 }
78 } // namespace std
79 
80 namespace smash {
81 static constexpr int LGrid = LogArea::Grid::id;
82 
84 // GridBase
85 
86 std::pair<std::array<double, 3>, std::array<double, 3>>
88  std::pair<std::array<double, 3>, std::array<double, 3>> r;
89  auto &min_position = r.first;
90  auto &length = r.second;
91 
92  // intialize min and max position arrays with the position of the first
93  // particle in the list
94  const auto &first_position = particles.front().position();
95  min_position = {{first_position[1], first_position[2], first_position[3]}};
96  auto max_position = min_position;
97  for (const auto &p : particles) {
98  const auto &pos = p.position();
99  min_position[0] = std::min(min_position[0], pos[1]);
100  min_position[1] = std::min(min_position[1], pos[2]);
101  min_position[2] = std::min(min_position[2], pos[3]);
102  max_position[0] = std::max(max_position[0], pos[1]);
103  max_position[1] = std::max(max_position[1], pos[2]);
104  max_position[2] = std::max(max_position[2], pos[3]);
105  }
106  length[0] = max_position[0] - min_position[0];
107  length[1] = max_position[1] - min_position[1];
108  length[2] = max_position[2] - min_position[2];
109  return r;
110 }
111 
113 // Grid
114 
115 template <GridOptions O>
116 Grid<O>::Grid(const std::pair<std::array<double, 3>, std::array<double, 3>>
117  &min_and_length,
118  const Particles &particles, double max_interaction_length,
119  double timestep_duration, CellNumberLimitation limit,
120  const bool include_unformed_particles, CellSizeStrategy strategy)
121  : length_(min_and_length.second) {
122  const auto min_position = min_and_length.first;
123  const SizeType particle_count = particles.size();
124 
125  // very simple setup for non-periodic boundaries and largest cellsize strategy
126  if (O == GridOptions::Normal && strategy == CellSizeStrategy::Largest) {
127  number_of_cells_ = {1, 1, 1};
128  cell_volume_ = length_[0] * length_[1] * length_[2];
129  cells_.clear();
130  cells_.reserve(1);
131  cells_.emplace_back(particles.copy_to_vector());
132  return;
133  }
134 
135  // The number of cells is determined by the min and max coordinates where
136  // particles are positioned and the maximal interaction length (which equals
137  // the length of a cell).
138  // But don't let the number of cells exceed the actual number of particles.
139  // That would be overkill. Let max_cells³ ≤ particle_count (conversion to
140  // int truncates). Limit only applied for geometric criteiron, where grid
141  // is an optimisation and cells can be made larger.
142  const int max_cells =
143  (O == GridOptions::Normal)
144  ? std::cbrt(particle_count)
145  : std::max(2, static_cast<int>(std::cbrt(particle_count)));
146 
147  // This normally equals 1/max_interaction_length. If the number of cells
148  // is reduced (because of low density) then this value is smaller. If only
149  // one cell is used than this value might also be larger.
150  std::array<double, 3> index_factor = {1. / max_interaction_length,
151  1. / max_interaction_length,
152  1. / max_interaction_length};
153  for (std::size_t i = 0; i < number_of_cells_.size(); ++i) {
154  number_of_cells_[i] =
155  (strategy == CellSizeStrategy::Largest)
156  ? 2
157  : static_cast<int>(std::floor(length_[i] * index_factor[i]));
158 
159  if (number_of_cells_[i] == 0) {
160  // In case of zero cells, make at least one cell that is then smaller than
161  // the minimal cell length. This is ok for all setups, since all particles
162  // are inside the same cell, except for the box with peroidic boundary
163  // conditions, where we need a 2x2x2 grid.
164  number_of_cells_[i] = 1;
165  } else if (number_of_cells_[i] < 2 &&
167  // Double the minimal cell length exceeds the length of the box, but we
168  // need at least 2x2x2 cells for periodic boundaries.
169  std::string error_box_too_small =
170  "Input error: Your box is too small for the grid.\n"
171  "The minimal length of the box is given by: " +
172  std::to_string(2 * max_interaction_length) +
173  " fm with the given timestep size.\n"
174  "If you have large timesteps please reduce them.\n"
175  "A larger box or the use of testparticles also helps.\n"
176  "Please take a look at your config.";
177  throw std::runtime_error(error_box_too_small);
178  } else if (limit == CellNumberLimitation::ParticleNumber &&
179  number_of_cells_[i] > max_cells) {
180  number_of_cells_[i] = max_cells;
181  }
182  // Only bother rescaling the index_factor if the grid length is large enough
183  // for 1 full min. cell length, since all particles are anyway placed in the
184  // first cell along the i-th axis
185  if (length_[i] >= max_interaction_length) {
186  index_factor[i] = number_of_cells_[i] / length_[i];
187  // std::nextafter implements a safety margin so that no valid position
188  // inside the grid can reference an out-of-bounds cell
189  while (index_factor[i] * length_[i] >= number_of_cells_[i]) {
190  index_factor[i] = std::nextafter(index_factor[i], 0.);
191  }
192  assert(index_factor[i] * length_[i] < number_of_cells_[i]);
193  }
194  }
195 
196  if (O == GridOptions::Normal &&
197  all_of(number_of_cells_, [](SizeType n) { return n <= 2; })) {
198  // dilute limit:
199  // the grid would have <= 2x2x2 cells, meaning every particle has to be
200  // compared with every other particle anyway. Then we can just as well
201  // fall back to not using the grid at all
202  // For a grid with periodic boundaries the situation is different and we
203  // never want to have a grid smaller than 2x2x2.
204  logg[LGrid].debug(
205  "There would only be ", number_of_cells_,
206  " cells. Therefore the Grid falls back to a single cell / "
207  "particle list.");
208  number_of_cells_ = {1, 1, 1};
209  cell_volume_ = length_[0] * length_[1] * length_[2];
210  if (include_unformed_particles) {
211  cells_.clear();
212  cells_.reserve(1);
213  cells_.emplace_back(particles.copy_to_vector());
214  } else {
215  // filter out the particles that can not interact
216  cells_.resize(1);
217  cells_.front().reserve(particles.size());
218  std::copy_if(particles.begin(), particles.end(),
219  std::back_inserter(cells_.front()),
220  [&](const ParticleData &p) {
221  return p.xsec_scaling_factor(timestep_duration) > 0.0;
222  });
223  }
224  } else {
225  // construct a normal grid
226 
228  (length_[1] / number_of_cells_[1]) *
229  (length_[2] / number_of_cells_[2]);
230 
231  logg[LGrid].debug("min: ", min_position, "\nlength: ", length_,
232  "\ncell_volume: ", cell_volume_,
233  "\ncells: ", number_of_cells_,
234  "\nindex_factor: ", index_factor);
235 
236  // After the grid parameters are determined, we can start placing the
237  // particles in cells.
238  cells_.resize(number_of_cells_[0] * number_of_cells_[1] *
239  number_of_cells_[2]);
240 
241  // Returns the one-dimensional cell-index from the position vector inside
242  // the grid.
243  // This simply calculates the distance to min_position and multiplies it
244  // with index_factor to determine the 3 x,y,z indexes to pass to make_index.
245  auto &&cell_index_for = [&](const ParticleData &p) {
246  return make_index(
247  std::floor((p.position()[1] - min_position[0]) * index_factor[0]),
248  std::floor((p.position()[2] - min_position[1]) * index_factor[1]),
249  std::floor((p.position()[3] - min_position[2]) * index_factor[2]));
250  };
251  for (const auto &p : particles) {
252  if (!include_unformed_particles &&
253  (p.xsec_scaling_factor(timestep_duration) <= 0.0)) {
254  continue;
255  }
256  const auto idx = cell_index_for(p);
257 #ifndef NDEBUG
258  if (idx >= SizeType(cells_.size())) {
259  logg[LGrid].fatal(
261  "\nan out-of-bounds access would be necessary for the "
262  "particle ",
263  p,
264  "\nfor a grid with the following parameters:\nmin: ", min_position,
265  "\nlength: ", length_, "\ncells: ", number_of_cells_,
266  "\nindex_factor: ", index_factor, "\ncells_.size: ", cells_.size(),
267  "\nrequested index: ", idx);
268  throw std::runtime_error("out-of-bounds grid access on construction");
269  }
270 #endif
271  cells_[idx].push_back(p);
272  }
273  }
274 
275  logg[LGrid].debug(cells_);
276 }
277 
278 template <GridOptions Options>
280  SizeType x, SizeType y, SizeType z) const {
281  return (z * number_of_cells_[1] + y) * number_of_cells_[0] + x;
282 }
283 
284 static const std::initializer_list<GridBase::SizeType> ZERO{0};
285 static const std::initializer_list<GridBase::SizeType> ZERO_ONE{0, 1};
286 static const std::initializer_list<GridBase::SizeType> MINUS_ONE_ZERO{-1, 0};
287 static const std::initializer_list<GridBase::SizeType> MINUS_ONE_ZERO_ONE{-1, 0,
288  1};
289 
290 template <>
293  const std::function<void(const ParticleList &)> &search_cell_callback,
294  const std::function<void(const ParticleList &, const ParticleList &)>
295  &neighbor_cell_callback) const {
296  std::array<SizeType, 3> search_index;
297  SizeType &x = search_index[0];
298  SizeType &y = search_index[1];
299  SizeType &z = search_index[2];
300  SizeType search_cell_index = 0;
301  for (z = 0; z < number_of_cells_[2]; ++z) {
302  for (y = 0; y < number_of_cells_[1]; ++y) {
303  for (x = 0; x < number_of_cells_[0]; ++x, ++search_cell_index) {
304  assert(search_cell_index == make_index(search_index));
305  assert(search_cell_index >= 0);
306  assert(search_cell_index < SizeType(cells_.size()));
307  const ParticleList &search = cells_[search_cell_index];
308  search_cell_callback(search);
309 
310  const auto &dz_list = z == number_of_cells_[2] - 1 ? ZERO : ZERO_ONE;
311  const auto &dy_list = number_of_cells_[1] == 1
312  ? ZERO
313  : y == 0 ? ZERO_ONE
314  : y == number_of_cells_[1] - 1
317  const auto &dx_list = number_of_cells_[0] == 1
318  ? ZERO
319  : x == 0 ? ZERO_ONE
320  : x == number_of_cells_[0] - 1
323  for (SizeType dz : dz_list) {
324  for (SizeType dy : dy_list) {
325  for (SizeType dx : dx_list) {
326  const auto di = make_index(dx, dy, dz);
327  if (di > 0) {
328  neighbor_cell_callback(search, cells_[search_cell_index + di]);
329  }
330  }
331  }
332  }
333  }
334  }
335  }
336 }
337 
347 
354 };
355 
356 template <>
359  const std::function<void(const ParticleList &)> &search_cell_callback,
360  const std::function<void(const ParticleList &, const ParticleList &)>
361  &neighbor_cell_callback) const {
362  std::array<SizeType, 3> search_index;
363  SizeType &x = search_index[0];
364  SizeType &y = search_index[1];
365  SizeType &z = search_index[2];
366  SizeType search_cell_index = 0;
367 
368  // defaults:
369  std::array<NeighborLookup, 2> dz_list;
370  std::array<NeighborLookup, 3> dy_list;
371  std::array<NeighborLookup, 3> dx_list;
372 
373  assert(number_of_cells_[2] >= 2);
374  assert(number_of_cells_[1] >= 2);
375  assert(number_of_cells_[0] >= 2);
376 
377  for (z = 0; z < number_of_cells_[2]; ++z) {
378  dz_list[0].index = z;
379  dz_list[1].index = z + 1;
380  if (dz_list[1].index == number_of_cells_[2]) {
381  dz_list[1].index = 0;
382  // last z in the loop, so no need to reset wrap again
383  dz_list[1].wrap = NeedsToWrap::MinusLength;
384  }
385  for (y = 0; y < number_of_cells_[1]; ++y) {
386  dy_list[0].index = y;
387  dy_list[1].index = y - 1;
388  dy_list[2].index = y + 1;
389  dy_list[2].wrap = NeedsToWrap::No;
390  if (y == 0) {
391  dy_list[1] = dy_list[2];
392  dy_list[2].index = number_of_cells_[1] - 1;
393  dy_list[2].wrap = NeedsToWrap::PlusLength;
394  } else if (dy_list[2].index == number_of_cells_[1]) {
395  dy_list[2].index = 0;
396  dy_list[2].wrap = NeedsToWrap::MinusLength;
397  }
398  for (x = 0; x < number_of_cells_[0]; ++x, ++search_cell_index) {
399  dx_list[0].index = x;
400  dx_list[1].index = x - 1;
401  dx_list[2].index = x + 1;
402  dx_list[2].wrap = NeedsToWrap::No;
403  if (x == 0) {
404  dx_list[1] = dx_list[2];
405  dx_list[2].index = number_of_cells_[0] - 1;
406  dx_list[2].wrap = NeedsToWrap::PlusLength;
407  } else if (dx_list[2].index == number_of_cells_[0]) {
408  dx_list[2].index = 0;
409  dx_list[2].wrap = NeedsToWrap::MinusLength;
410  }
411 
412  assert(search_cell_index == make_index(search_index));
413  assert(search_cell_index >= 0);
414  assert(search_cell_index < SizeType(cells_.size()));
415  ParticleList search = cells_[search_cell_index];
416  search_cell_callback(search);
417 
418  auto virtual_search_index = search_index;
419  ThreeVector wrap_vector = {}; // no change
420  auto current_wrap_vector = wrap_vector;
421 
422  for (const auto &dz : dz_list) {
423  if (dz.wrap == NeedsToWrap::MinusLength) {
424  // last dz in the loop, so no need to undo the wrap
425  wrap_vector[2] = -length_[2];
426  virtual_search_index[2] = -1;
427  }
428  for (const auto &dy : dy_list) {
429  // only the last dy in dy_list can wrap
430  if (dy.wrap == NeedsToWrap::MinusLength) {
431  wrap_vector[1] = -length_[1];
432  virtual_search_index[1] = -1;
433  } else if (dy.wrap == NeedsToWrap::PlusLength) {
434  wrap_vector[1] = length_[1];
435  virtual_search_index[1] = number_of_cells_[1];
436  }
437  for (const auto &dx : dx_list) {
438  // only the last dx in dx_list can wrap
439  if (dx.wrap == NeedsToWrap::MinusLength) {
440  wrap_vector[0] = -length_[0];
441  virtual_search_index[0] = -1;
442  } else if (dx.wrap == NeedsToWrap::PlusLength) {
443  wrap_vector[0] = length_[0];
444  virtual_search_index[0] = number_of_cells_[0];
445  }
446  assert(dx.index >= 0);
447  assert(dx.index < number_of_cells_[0]);
448  assert(dy.index >= 0);
449  assert(dy.index < number_of_cells_[1]);
450  assert(dz.index >= 0);
451  assert(dz.index < number_of_cells_[2]);
452  const auto neighbor_cell_index =
453  make_index(dx.index, dy.index, dz.index);
454  assert(neighbor_cell_index >= 0);
455  assert(neighbor_cell_index < SizeType(cells_.size()));
456  if (neighbor_cell_index <= make_index(virtual_search_index)) {
457  continue;
458  }
459 
460  if (wrap_vector != current_wrap_vector) {
461  logg[LGrid].debug("translating search cell by ",
462  wrap_vector - current_wrap_vector);
463  for_each(search, [&](ParticleData &p) {
464  p = p.translated(wrap_vector - current_wrap_vector);
465  });
466  current_wrap_vector = wrap_vector;
467  }
468  neighbor_cell_callback(search, cells_[neighbor_cell_index]);
469  }
470  virtual_search_index[0] = search_index[0];
471  wrap_vector[0] = 0;
472  }
473  virtual_search_index[1] = search_index[1];
474  wrap_vector[1] = 0;
475  }
476  }
477  }
478  }
479 }
480 
482  const std::pair<std::array<double, 3>, std::array<double, 3>>
483  &min_and_length,
484  const Particles &particles, double max_interaction_length,
485  double timestep_duration, CellNumberLimitation limit,
486  const bool include_unformed_particles, CellSizeStrategy strategy);
488  const std::pair<std::array<double, 3>, std::array<double, 3>>
489  &min_and_length,
490  const Particles &particles, double max_interaction_length,
491  double timestep_duration, CellNumberLimitation limit,
492  const bool include_unformed_particles, CellSizeStrategy strategy);
493 } // namespace smash
Generic algorithms on containers and ranges.
int SizeType
A type to store the sizes.
Definition: grid.h:70
static std::pair< std::array< double, 3 >, std::array< double, 3 > > find_min_and_length(const Particles &particles)
Definition: grid.cc:87
const std::array< double, 3 > length_
The 3 lengths of the complete grid. Used for periodic boundary wrapping.
Definition: grid.h:190
std::array< int, 3 > number_of_cells_
The number of cells in x, y, and z direction.
Definition: grid.h:196
double cell_volume_
The volume of a single cell.
Definition: grid.h:193
std::vector< ParticleList > cells_
The cell storage.
Definition: grid.h:199
Grid(const Particles &particles, double min_cell_length, double timestep_duration, CellNumberLimitation limit, const bool include_unformed_particles=false, CellSizeStrategy strategy=CellSizeStrategy::Optimal)
Constructs a grid from the given particle list particles.
Definition: grid.h:113
void iterate_cells(const std::function< void(const ParticleList &)> &search_cell_callback, const std::function< void(const ParticleList &, const ParticleList &)> &neighbor_cell_callback) const
Iterates over all cells in the grid and calls the callback arguments with a search cell and 0 to 13 n...
SizeType make_index(SizeType x, SizeType y, SizeType z) const
Definition: grid.cc:279
ParticleData contains the dynamic information of a certain particle.
Definition: particledata.h:58
const FourVector & position() const
Get the particle's position in Minkowski space.
Definition: particledata.h:204
The Particles class abstracts the storage and manipulation of particles.
Definition: particles.h:33
size_t size() const
Definition: particles.h:87
ParticleList copy_to_vector() const
Definition: particles.h:44
ParticleData & front()
Definition: particles.h:359
iterator begin()
Definition: particles.h:380
iterator end()
Definition: particles.h:404
The ThreeVector class represents a physical three-vector with the components .
Definition: threevector.h:31
#define SMASH_SOURCE_LOCATION
Hackery that is required to output the location in the source code where the log statement occurs.
Definition: logging.h:243
std::array< einhard::Logger<>, std::tuple_size< LogArea::AreaTuple >::value > logg
An array that stores all pre-configured Logger objects.
Definition: logging.cc:39
constexpr int p
Proton.
constexpr int n
Neutron.
Definition: action.h:24
static const std::initializer_list< GridBase::SizeType > ZERO_ONE
Definition: grid.cc:285
UnaryFunction for_each(Container &&c, UnaryFunction &&f)
Convenience wrapper for std::for_each that operates on a complete container.
Definition: algorithms.h:96
NeedsToWrap
The options determining what to do if a particle flies out of the grids PlusLength: Used if a periodi...
Definition: grid.cc:346
CellNumberLimitation
Identifies whether the number of cells should be limited.
Definition: grid.h:55
@ ParticleNumber
Limit the number of cells to the number of particles.
bool all_of(Container &&c, UnaryPredicate &&p)
Convenience wrapper for std::all_of that operates on a complete container.
Definition: algorithms.h:80
@ Normal
Without ghost cells.
@ PeriodicBoundaries
With ghost cells for periodic boundaries.
static const std::initializer_list< GridBase::SizeType > MINUS_ONE_ZERO
Definition: grid.cc:286
static const std::initializer_list< GridBase::SizeType > ZERO
Definition: grid.cc:284
static constexpr int LGrid
Definition: grid.cc:81
CellSizeStrategy
Indentifies the strategy of determining the cell size.
Definition: grid.h:33
@ Largest
Make cells as large as possible.
static const std::initializer_list< GridBase::SizeType > MINUS_ONE_ZERO_ONE
Definition: grid.cc:287
A strust containing the informations needed to search the neighboring cell.
Definition: grid.cc:349
Grid< GridOptions::PeriodicBoundaries >::SizeType index
Index of the cell.
Definition: grid.cc:351
NeedsToWrap wrap
Option to determine the neighbors of the cells on the boundary.
Definition: grid.cc:353