Utopia 2
Framework for studying models of complex & adaptive systems.
Loading...
Searching...
No Matches
Public Types | Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes | List of all members
Utopia::CellManager< CellTraits, Model > Class Template Reference

Manages a physical space, its grid discretization, and cells on that grid. More...

#include <cell_manager.hh>

Public Types

using Self = CellManager< CellTraits, Model >
 The type of this CellManager.
 
using Cell = Utopia::Cell< CellTraits >
 Type of the managed cells.
 
using Entity = Cell
 Alias for entity type; part of the shared interface of entity managers.
 
using CellState = typename CellTraits::State
 Type of the cell state.
 
using Space = typename Model::Space
 The space type this cell manager maps to.
 
using GridType = Grid< Space >
 Grid type; this refers to the base type of the stored (derived) object.
 
using SpaceVec = SpaceVecType< dim >
 Type of vectors that represent a physical quantity.
 
using MultiIndex = typename GridType::MultiIndex
 Type of multi-index like arrays.
 
using RNG = typename Model::RNG
 Random number generator type.
 
using Config = typename Model::Config
 Configuration node type.
 
using NBFuncCell = std::function< CellContainer< Cell >(const Cell &)>
 Neighborhood function used in public interface (with cell as argument)
 
using RuleFunc = typename std::function< CellState(const std::shared_ptr< Cell > &)>
 The type of a rule function acting on cells of this cell manager.
 
using VoidRuleFunc = typename std::function< void(const std::shared_ptr< Cell > &)>
 The type of a void rule function acting on cells of this cell manager.
 

Public Member Functions

 CellManager (const Model &model, const Config &custom_cfg={})
 Construct a cell manager.
 
 CellManager (const Model &model, const CellState initial_state, const Config &custom_cfg={})
 Construct a cell manager explicitly passing an initial cell state.
 
const autolog () const
 
const Configcfg () const
 Return the configuration used for building this cell manager.
 
const std::shared_ptr< RNG > & rng () const
 Return a reference to the shared random number generator.
 
const std::shared_ptr< Space > & space () const
 Return pointer to the space, for convenience.
 
const std::shared_ptr< GridType > & grid () const
 Return const reference to the grid.
 
const CellContainer< Cell > & cells () const
 Return const reference to the managed CA cells.
 
const CellContainer< Cell > & entities () const
 Return const reference to the entities managed by this manager: cells.
 
MultiIndex midx_of (const Cell &cell) const
 Returns the multi-index of the given cell.
 
MultiIndex midx_of (const std::shared_ptr< Cell > &cell) const
 Returns the multi-index of the given cell.
 
SpaceVec barycenter_of (const Cell &cell) const
 Returns the barycenter of the given cell.
 
SpaceVec barycenter_of (const std::shared_ptr< Cell > &cell) const
 Returns the barycenter of the given cell.
 
SpaceVec extent_of (const Cell &cell) const
 Returns the physical extent of the given cell.
 
SpaceVec extent_of (const std::shared_ptr< Cell > &cell) const
 Returns the physical extent of the given cell.
 
std::vector< SpaceVecvertices_of (const Cell &cell) const
 Returns a container of vertices of the given cell.
 
std::vector< SpaceVecvertices_of (const std::shared_ptr< Cell > &cell) const
 Returns a container of vertices of the given cell.
 
const std::shared_ptr< Cell > & cell_at (const SpaceVec &pos) const
 Return the cell covering the given point in physical space.
 
CellContainer< Cellboundary_cells (const std::string &select="all") const
 Retrieve a container of cells that are at a specified boundary.
 
template<SelectionMode mode, class... Args>
CellContainer< Cellselect_cells (Args &&... args) const
 Select cells using the Utopia::select_entities interface.
 
CellContainer< Cellselect_cells (const Config &sel_cfg) const
 Select entities according to parameters specified in a configuration.
 
template<class ElementT = double, class SetterFunc >
void set_cell_states (const std::string &hdf5_file, const std::string &dset_path, const SetterFunc &setter_func)
 Set all cell states using information from a HDF5 file.
 
const NBModenb_mode () const
 Return the currently selected neighborhood mode.
 
auto nb_size () const
 Return the (maximum) size of the currently selected neighborhood.
 
CellContainer< Cellneighbors_of (const Cell &cell) const
 Retrieve the given cell's neighbors.
 
CellContainer< Cellneighbors_of (const std::shared_ptr< Cell > &cell) const
 Retrieve the given cell's neighbors.
 
void select_neighborhood (const Config &nb_cfg)
 Select the neighborhood and all parameters fully from a config node.
 
void select_neighborhood (const std::string &nb_mode, const bool compute_and_store=true, const Config &nb_params={})
 Select the neighborhood mode using a string for the mode argument.
 
void select_neighborhood (const NBMode &nb_mode, const bool compute_and_store=true, const Config &nb_params={})
 Set the neighborhood mode.
 
void compute_cell_neighbors ()
 Compute (and store) all cells' neighbors.
 
template<class IndexContainer >
CellContainer< Cellentity_pointers_from_ids (IndexContainer &&ids) const
 Given a container IDs, convert it to container of entity pointers.
 

Public Attributes

bool _empty_nb_warning_emitted = false
 Whether a warning about an empty neighbourhood was already emitted.
 

Static Public Attributes

static constexpr DimType dim = Model::Space::dim
 Dimensionality of the space this cell manager is to discretize.
 

Private Member Functions

Config setup_cfg (const Model &model, const Config &custom_cfg) const
 Set up the cell manager configuration member.
 
std::shared_ptr< GridTypesetup_grid () const
 Set up the grid discretization.
 
CellContainer< Cellsetup_cells (const CellState &initial_state) const
 Set up the cells container using an explicitly passed initial state.
 
CellContainer< Cellsetup_cells () const
 Set up cells container via config or default constructor.
 
void setup_nb_funcs ()
 Setup the neighborhood functions using config entries.
 

Private Attributes

const std::shared_ptr< spdlog::logger > _log
 The logger (same as the model this manager resides in)
 
const Config _cfg
 Cell manager configuration node.
 
const std::shared_ptr< RNG_rng
 The model's random number generator, used e.g. for cell construction.
 
const std::shared_ptr< Space_space
 The physical space the cells are to reside in.
 
const std::shared_ptr< GridType_grid
 The grid that discretely maps cells into space.
 
CellContainer< Cell_cells
 Storage container for cells.
 
std::vector< CellContainer< Cell > > _cell_neighbors
 Storage container for pre-calculated (!) cell neighbors.
 
NBFuncCell _nb_func
 The currently chosen neighborhood function (working directly on cells)
 
NBFuncCell _nb_from_cache
 Return the pre-computed neighbors of the given cell.
 
NBFuncCell _nb_compute_each_time
 Compute the neighbors for the given cell using the grid.
 
NBFuncCell _nb_compute_each_time_empty
 Compute the neighbors for the given cell using the grid.
 

Detailed Description

template<class CellTraits, class Model>
class Utopia::CellManager< CellTraits, Model >

Manages a physical space, its grid discretization, and cells on that grid.

This class implements a common interface for working with cells as a representation of volumes of physical space. A typical use case is the cellular automaton.

To that end, a discretization of space is needed: the grid. This spatial discretization is handled by concrete classes derived from Utopia::Grid. The CellManager communicates with these objects solely via cell indices (which are the indices within the container of cells), making the grid implementation independent of the type of cells used.

Template Parameters
CellTraitsType traits of the cells used
ModelType of the model using this manager

Member Typedef Documentation

◆ Cell

Type of the managed cells.

◆ CellState

Type of the cell state.

◆ Config

Configuration node type.

◆ Entity

Alias for entity type; part of the shared interface of entity managers.

◆ GridType

Grid type; this refers to the base type of the stored (derived) object.

◆ MultiIndex

Type of multi-index like arrays.

◆ NBFuncCell

template<class CellTraits , class Model >
using Utopia::CellManager< CellTraits, Model >::NBFuncCell = std::function<CellContainer<Cell>(const Cell&)>

Neighborhood function used in public interface (with cell as argument)

◆ RNG

Random number generator type.

◆ RuleFunc

template<class CellTraits , class Model >
using Utopia::CellManager< CellTraits, Model >::RuleFunc = typename std::function<CellState(const std::shared_ptr<Cell>&)>

The type of a rule function acting on cells of this cell manager.

This is a convenience type def that models can use to easily have this type available.

◆ Self

The type of this CellManager.

◆ Space

The space type this cell manager maps to.

◆ SpaceVec

Type of vectors that represent a physical quantity.

◆ VoidRuleFunc

template<class CellTraits , class Model >
using Utopia::CellManager< CellTraits, Model >::VoidRuleFunc = typename std::function<void(const std::shared_ptr<Cell>&)>

The type of a void rule function acting on cells of this cell manager.

This is a convenience type def that models can use to easily have this type available. Void rule functions are only possible for asynchronous updates.

Constructor & Destructor Documentation

◆ CellManager() [1/2]

template<class CellTraits , class Model >
Utopia::CellManager< CellTraits, Model >::CellManager ( const Model model,
const Config custom_cfg = {} 
)
inline

Construct a cell manager.

With the model available, the CellManager can extract the required information from the model without the need to pass it explicitly. Furthermore, this constructor differs to the one with the initial_state parameter such that the way the initial state of the cells is determined can be controlled via the configuration.

Parameters
modelThe model this CellManager belongs to
custom_cfgA custom config node to use to use for grid and cell setup. If not given, the model's configuration is used to extract the required entries.
142 {})
143 :
144 _log(model.get_logger()),
146 _rng(model.get_rng()),
147 _space(model.get_space()),
148 _grid(setup_grid()),
151 {
152 // Set default value for _nb_func
154
155 // Use setup function to set up neighborhood from configuration
157
158 _log->info("CellManager is all set up.");
159 }
Config setup_cfg(const Model &model, const Config &custom_cfg) const
Set up the cell manager configuration member.
Definition cell_manager.hh:657
const Config _cfg
Cell manager configuration node.
Definition cell_manager.hh:101
std::vector< CellContainer< Cell > > _cell_neighbors
Storage container for pre-calculated (!) cell neighbors.
Definition cell_manager.hh:116
CellContainer< Cell > setup_cells() const
Set up cells container via config or default constructor.
Definition cell_manager.hh:752
NBFuncCell _nb_compute_each_time_empty
Compute the neighbors for the given cell using the grid.
Definition cell_manager.hh:638
void setup_nb_funcs()
Setup the neighborhood functions using config entries.
Definition cell_manager.hh:831
CellContainer< Cell > _cells
Storage container for cells.
Definition cell_manager.hh:113
NBFuncCell _nb_func
The currently chosen neighborhood function (working directly on cells)
Definition cell_manager.hh:119
const std::shared_ptr< spdlog::logger > _log
The logger (same as the model this manager resides in)
Definition cell_manager.hh:98
const std::shared_ptr< Space > _space
The physical space the cells are to reside in.
Definition cell_manager.hh:107
std::shared_ptr< GridType > setup_grid() const
Set up the grid discretization.
Definition cell_manager.hh:680
const std::shared_ptr< GridType > _grid
The grid that discretely maps cells into space.
Definition cell_manager.hh:110
const std::shared_ptr< RNG > _rng
The model's random number generator, used e.g. for cell construction.
Definition cell_manager.hh:104
Container select_entities(const Manager &mngr, const DataIO::Config &sel_cfg)
Select entities according to parameters specified in a configuration.
Definition select.hh:213

◆ CellManager() [2/2]

template<class CellTraits , class Model >
Utopia::CellManager< CellTraits, Model >::CellManager ( const Model model,
const CellState  initial_state,
const Config custom_cfg = {} 
)
inline

Construct a cell manager explicitly passing an initial cell state.

Parameters
modelThe model this CellManager belongs to
initial_stateThe initial state of the cells
custom_cfgA custom config node to use to use for grid and cell setup. If not given, the model's configuration is used to extract the required entries.
172 {})
173 :
174 _log(model.get_logger()),
176 _rng(model.get_rng()),
177 _space(model.get_space()),
178 _grid(setup_grid()),
181 {
182 // Set default value for _nb_func
184
185 // Use setup function to set up neighborhood from configuration
187
188 _log->info("CellManager is all set up.");
189 }

Member Function Documentation

◆ barycenter_of() [1/2]

template<class CellTraits , class Model >
SpaceVec Utopia::CellManager< CellTraits, Model >::barycenter_of ( const Cell cell) const
inline

Returns the barycenter of the given cell.

249 {
250 return _grid->barycenter_of(cell.id());
251 }

◆ barycenter_of() [2/2]

template<class CellTraits , class Model >
SpaceVec Utopia::CellManager< CellTraits, Model >::barycenter_of ( const std::shared_ptr< Cell > &  cell) const
inline

Returns the barycenter of the given cell.

254 {
255 return _grid->barycenter_of(cell->id());
256 }

◆ boundary_cells()

template<class CellTraits , class Model >
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::boundary_cells ( const std::string &  select = "all") const
inline

Retrieve a container of cells that are at a specified boundary.

Lets the grid compute the set of cell IDs at the boundary and then converts them into pointers to cells. As the set is sorted by cell IDs, the returned container is also sorted.

Warning
For a periodic space, an empty container is returned; no error or warning is emitted!
Parameters

parblock Select which boundary to return the cell IDs of. If 'all', all boundary cells are returned. Other available values depend on the dimensionality of the grid:

  • 1D: left, right
  • 2D: bottom, top
  • 3D: back, front
323 {
324 if (_space->periodic) {
325 _log->warn("Selecting boundary cells (mode '{}') of a periodic "
326 "space will always return an empty container!", select);
327 }
328
329 return entity_pointers_from_ids(_grid->boundary_cells(select));
330 }
CellContainer< Cell > entity_pointers_from_ids(IndexContainer &&ids) const
Given a container IDs, convert it to container of entity pointers.
Definition cell_manager.hh:607

◆ cell_at()

template<class CellTraits , class Model >
const std::shared_ptr< Cell > & Utopia::CellManager< CellTraits, Model >::cell_at ( const SpaceVec pos) const
inline

Return the cell covering the given point in physical space.

Cells are interpreted as covering half-open intervals in space, i.e., including their low-value edges and excluding their high-value edges. The special case of points on high-value edges for non-periodic space behaves such that these points are associated with the cells at the boundary.

Note
For non-periodic space, a check is performed whether the given point is inside the physical space associated with the grid. If that is not the case, an error is raised. For periodic space, the given position is mapped back into the physical space, thus always returning a valid cell.
302 {
303 return _cells[_grid->cell_at(pos)];
304 }

◆ cells()

template<class CellTraits , class Model >
const CellContainer< Cell > & Utopia::CellManager< CellTraits, Model >::cells ( ) const
inline

Return const reference to the managed CA cells.

219 {
220 return _cells;
221 }

◆ cfg()

template<class CellTraits , class Model >
const Config & Utopia::CellManager< CellTraits, Model >::cfg ( ) const
inline

Return the configuration used for building this cell manager.

199 {
200 return _cfg;
201 }

◆ compute_cell_neighbors()

template<class CellTraits , class Model >
void Utopia::CellManager< CellTraits, Model >::compute_cell_neighbors ( )
inline

Compute (and store) all cells' neighbors.

After this function was called, the cell neighbors will be returned from the storage container rather than re-calculated for every access.

582 {
583 _log->info("Computing and storing '{}' neighbors of all {} cells ...",
584 nb_mode_to_string(_grid->nb_mode()), _cells.size());
585
586 // Clear cell neighbors container and pre-allocate space
587 _cell_neighbors.clear();
588 _cell_neighbors.reserve(_cells.size());
589
590 // Compute cell neighbors and store them
591 for (const auto& cell : _cells) {
593 }
594
595 // Change access function to access the storage directly. Done.
597 _log->info("Computed and stored cell neighbors.");
598 }
CellContainer< Cell > neighbors_of(const Cell &cell) const
Retrieve the given cell's neighbors.
Definition cell_manager.hh:458
NBFuncCell _nb_from_cache
Return the pre-computed neighbors of the given cell.
Definition cell_manager.hh:626
std::string nb_mode_to_string(const NBMode &nb_mode)
Given an NBMode enum value, return the corresponding string key.
Definition base.hh:78

◆ entities()

template<class CellTraits , class Model >
const CellContainer< Cell > & Utopia::CellManager< CellTraits, Model >::entities ( ) const
inline

Return const reference to the entities managed by this manager: cells.

224 {
225 return cells();
226 }
const CellContainer< Cell > & cells() const
Return const reference to the managed CA cells.
Definition cell_manager.hh:219

◆ entity_pointers_from_ids()

template<class CellTraits , class Model >
template<class IndexContainer >
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::entity_pointers_from_ids ( IndexContainer &&  ids) const
inline

Given a container IDs, convert it to container of entity pointers.

Todo:
TODO This should move into a common manager base class
607 {
609 ret.reserve(ids.size());
610
611 for (const auto& id : ids) {
612 ret.emplace_back(std::shared_ptr<Cell>(_cells[id]));
613 }
614
615 return ret;
616 }

◆ extent_of() [1/2]

template<class CellTraits , class Model >
SpaceVec Utopia::CellManager< CellTraits, Model >::extent_of ( const Cell cell) const
inline

Returns the physical extent of the given cell.

259 {
260 return _grid->extent_of(cell.id());
261 }

◆ extent_of() [2/2]

template<class CellTraits , class Model >
SpaceVec Utopia::CellManager< CellTraits, Model >::extent_of ( const std::shared_ptr< Cell > &  cell) const
inline

Returns the physical extent of the given cell.

264 {
265 return _grid->extent_of(cell->id());
266 }

◆ grid()

template<class CellTraits , class Model >
const std::shared_ptr< GridType > & Utopia::CellManager< CellTraits, Model >::grid ( ) const
inline

Return const reference to the grid.

214 {
215 return _grid;
216 }

◆ log()

template<class CellTraits , class Model >
const auto & Utopia::CellManager< CellTraits, Model >::log ( ) const
inline

– Getters ---------------------------------------------------------— Return the CellManager logger

194 {
195 return _log;
196 }

◆ midx_of() [1/2]

template<class CellTraits , class Model >
MultiIndex Utopia::CellManager< CellTraits, Model >::midx_of ( const Cell cell) const
inline

Returns the multi-index of the given cell.

Note
Consult the documentation of the selected grid discretization to learn about the interpretation of the returned values.
236 {
237 return _grid->midx_of(cell.id());
238 }

◆ midx_of() [2/2]

template<class CellTraits , class Model >
MultiIndex Utopia::CellManager< CellTraits, Model >::midx_of ( const std::shared_ptr< Cell > &  cell) const
inline

Returns the multi-index of the given cell.

Note
Consult the documentation of the selected grid discretization to learn about the interpretation of the returned values.
244 {
245 return _grid->midx_of(cell->id());
246 }

◆ nb_mode()

template<class CellTraits , class Model >
const NBMode & Utopia::CellManager< CellTraits, Model >::nb_mode ( ) const
inline

Return the currently selected neighborhood mode.

Note
This is a shortcut that accesses the value set in the grid.
443 {
444 return _grid->nb_mode();
445 }

◆ nb_size()

template<class CellTraits , class Model >
auto Utopia::CellManager< CellTraits, Model >::nb_size ( ) const
inline

Return the (maximum) size of the currently selected neighborhood.

Note
This is a shortcut that accesses the value computed in the grid.
450 {
451 return _grid->nb_size();
452 }

◆ neighbors_of() [1/2]

template<class CellTraits , class Model >
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::neighbors_of ( const Cell cell) const
inline

Retrieve the given cell's neighbors.

The behaviour of this method is different depending on the choice of neighborhood.

458 {
459 return _nb_func(cell);
460 }

◆ neighbors_of() [2/2]

template<class CellTraits , class Model >
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::neighbors_of ( const std::shared_ptr< Cell > &  cell) const
inline

Retrieve the given cell's neighbors.

The behaviour of this method is different depending on the choice of neighborhood.

466 {
467 return _nb_func(*cell);
468 }

◆ rng()

template<class CellTraits , class Model >
const std::shared_ptr< RNG > & Utopia::CellManager< CellTraits, Model >::rng ( ) const
inline

Return a reference to the shared random number generator.

204 {
205 return _rng;
206 }

◆ select_cells() [1/2]

template<class CellTraits , class Model >
template<SelectionMode mode, class... Args>
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::select_cells ( Args &&...  args) const
inline

Select cells using the Utopia::select_entities interface.

Returns a container of cells that were selected according to a certain selection mode. This is done via the Utopia::select_entities interface.

Template Parameters
modeThe selection mode

\args args Forwarded to Utopia::select_entities

342 {
343 return select_entities<mode>(*this, std::forward<Args>(args)...);
344 }

◆ select_cells() [2/2]

template<class CellTraits , class Model >
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::select_cells ( const Config sel_cfg) const
inline

Select entities according to parameters specified in a configuration.

Via the mode key, one of the selection modes can be chosen; for available oens, see Utopia::SelectionMode.

Depending on that mode, the other parameters are extracted from the configuration. See Utopia::select_entities for more info.

Parameters
sel_cfgThe configuration node containing the expected key-value pairs specifying the selection.
356 {
357 return select_entities(*this, sel_cfg);
358 }

◆ select_neighborhood() [1/3]

template<class CellTraits , class Model >
void Utopia::CellManager< CellTraits, Model >::select_neighborhood ( const Config nb_cfg)
inline

Select the neighborhood and all parameters fully from a config node.

If this method is used to set up the neighborhood, the following keys will be read and parsed:

- ``mode`` (required): the neighborhood mode
- ``compute_and_store`` (optional, default: ``true``): whether to
  directly compute all neighbors and henceforth use the buffer to
  get these neighbors.

Subsequently, these values are passed to the appropriate overload of the select_neighborhood function.

Parameters
nb_cfgThe neighborhood configuration node. Apart from the keys that are parsed here, the full config node is passed along further.
486 {
487 // Extract the desired values
488 if (not nb_cfg["mode"]) {
489 throw KeyError("mode", nb_cfg, "Could not select neighborhood!");
490 }
491 const auto nb_mode = get_as<std::string>("mode", nb_cfg);
492 const bool compute = get_as<bool>("compute_and_store", nb_cfg, true);
493
494 // Call the string-based selection function, passing through the whole
495 // config node. The fact that the above two keys are also present in
496 // the node is not a problem.
498 }
void select_neighborhood(const Config &nb_cfg)
Select the neighborhood and all parameters fully from a config node.
Definition cell_manager.hh:486
const NBMode & nb_mode() const
Return the currently selected neighborhood mode.
Definition cell_manager.hh:443

◆ select_neighborhood() [2/3]

template<class CellTraits , class Model >
void Utopia::CellManager< CellTraits, Model >::select_neighborhood ( const NBMode nb_mode,
const bool  compute_and_store = true,
const Config nb_params = {} 
)
inline

Set the neighborhood mode.

Parameters
nb_modeThe name of the neighborhood to select
compute_and_storeWhether to directly compute all neighbors and henceforth use the buffer to get these neighbors. Default: true.
nb_paramsPassed on to the Grid::select_neighborhood method, carrying additional parameters.
537 {})
538 {
539 // Only change the neighborhood if it is different to the one already
540 // set in the grid or if it is set to be empty
541 if ((nb_mode != _grid->nb_mode()) or (nb_mode == NBMode::empty)) {
542 _log->info("Selecting '{}' neighborhood ...",
544
545 // Tell the grid which mode to use
546 _grid->select_neighborhood(nb_mode, nb_params);
547
548 // Adjust function object that the public interface calls
549 if (nb_mode == NBMode::empty) {
550 // Issue a warning alongside the neighborhood calculation
552 }
553 else {
554 // Compute the cell neighbors each time
556 }
557
558 // Clear the no-longer valid neighborhood relationships
559 if (_cell_neighbors.size() > 0) {
560 _cell_neighbors.clear();
561 _log->debug("Cleared cell neighborhood cache.");
562 }
563
564 _log->debug("Successfully selected '{}' neighborhood (size: {}).",
565 nb_mode_to_string(_grid->nb_mode()), nb_size());
566 }
567 else {
568 _log->debug("Neighborhood was already set to '{}'; not changing.",
569 nb_mode_to_string(_grid->nb_mode()));
570 }
571
572 // Still allow to compute the neighbors, regardless of all the above
573 if (compute_and_store) {
575 }
576 }
auto nb_size() const
Return the (maximum) size of the currently selected neighborhood.
Definition cell_manager.hh:450
NBFuncCell _nb_compute_each_time
Compute the neighbors for the given cell using the grid.
Definition cell_manager.hh:631
void compute_cell_neighbors()
Compute (and store) all cells' neighbors.
Definition cell_manager.hh:582
@ empty
Every entity is utterly alone in the world.

◆ select_neighborhood() [3/3]

template<class CellTraits , class Model >
void Utopia::CellManager< CellTraits, Model >::select_neighborhood ( const std::string &  nb_mode,
const bool  compute_and_store = true,
const Config nb_params = {} 
)
inline

Select the neighborhood mode using a string for the mode argument.

Resolves a string-type nb_mode to NBmode, then invokes the appropriate overload.

Parameters
nb_modeThe name of the neighborhood to select
compute_and_storeWhether to directly compute all neighbors and henceforth use the buffer to get these neighbors. Default: true.
nb_paramsPassed on to the Grid::select_neighborhood method, carrying additional parameters.
513 {})
514 {
515 // Check if the string is valid
516 if (not nb_mode_map.count(nb_mode)) {
517 throw std::invalid_argument("Got unexpected neighborhood mode '"
518 + nb_mode + "'! Available modes: empty, vonNeumann, Moore, "
519 "hexagonal.");
520 }
521
522 // Translate string; pass all other arguments through
524 compute_and_store, nb_params);
525 }
const std::map< std::string, NBMode > nb_mode_map
A map from strings to neighborhood enum values.
Definition base.hh:67

◆ set_cell_states()

template<class CellTraits , class Model >
template<class ElementT = double, class SetterFunc >
void Utopia::CellManager< CellTraits, Model >::set_cell_states ( const std::string &  hdf5_file,
const std::string &  dset_path,
const SetterFunc setter_func 
)
inline

Set all cell states using information from a HDF5 file.

Using armadillo functionality, this loads the data from the given HDF5 file into an array of ElementT. It then iterates over all cells, looks up the multi index, and passes it to the setter_func, which has the responsibility of setting the cell state accordingly.

The setter_func should accept as first argument a reference to the cell (more accurately: const std::shared_ptr<Cell>&) and as second argument the value from the loaded dataset.

Note
Currently only supports 2D grids and cells with Update::manual.
Template Parameters
ElemenTThe type that armadillo should load the data as. Need be supported by armadillo.
SetterFuncType of the setter function, e.g. std::function<…>
Parameters
hdf5_fileThe hdf5 file to load the data from. Can be an absolute path or relative to the working directory.
dset_pathThe path within the HDF5 file that points to the dataset to load data from.
setter_funcThe void(cell, value) function that sets the cell state given the value from the loaded dataset corresponding to the cells' multi-index.
391 {
392 static_assert(dim == 2, "Loading cell state is only supported in 2D!");
393 static_assert(CellTraits::mode == Update::manual,
394 "Setting cell states for cell update modes other than "
395 "Update::manual is currently not supported.");
396 // TODO Once passing of additional arguments to rule functions becomes
397 // possible, remove this restriction and use apply_rule below!
398
399 _log->debug("Setting cell states using HDF5 data ...");
400 _log->debug(" File: {}", hdf5_file);
401 _log->debug(" Dataset path: {}", dset_path);
402
403 // Load the array data
404 arma::Mat<ElementT> data;
405 data.load(arma::hdf5_name(hdf5_file, dset_path,
406 arma::hdf5_opts::trans));
407 // NOTE Need to load transposed; otherwise the index-access below would
408 // be reversed. This is to account for the different ordering
409 // between armadillo and CellManager coordinates.
410 // Thus: n_rows corresponds to N_x, n_cols to N_y!
411
412 // Check that data was loaded
413 if (not data.size()) {
414 throw std::runtime_error("Failed loading HDF5 data! Is the file "
415 "used by another program?");
416 }
417
418 // Check against grid shape
419 const auto grid_shape = _grid->shape();
420 if (data.n_rows != grid_shape[0] or data.n_cols != grid_shape[1]) {
421 throw std::invalid_argument("Shape mismatch between loaded data ("
422 + std::to_string(data.n_rows) + ", "
423 + std::to_string(data.n_cols) + ") and grid ("
424 + std::to_string(grid_shape[0]) + ", "
425 + std::to_string(grid_shape[1]) + ")!");
426 }
427
428 // Go over all cells, extract multi index, and let the setter function
429 // set the cell state.
430 for (const auto& cell : _cells) {
431 const auto midx = this->midx_of(cell);
432 setter_func(cell, data(midx[0], midx[1]));
433 }
434
435 _log->debug("Cell states set successfully.");
436 }
static constexpr DimType dim
Dimensionality of the space this cell manager is to discretize.
Definition cell_manager.hh:59
MultiIndex midx_of(const Cell &cell) const
Returns the multi-index of the given cell.
Definition cell_manager.hh:236
@ manual
User chooses update type when calling apply_rule()
static constexpr Update mode
Whether the entitys should be synchronously updated.
Definition entity.hh:54

◆ setup_cells() [1/2]

template<class CellTraits , class Model >
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::setup_cells ( ) const
inlineprivate

Set up cells container via config or default constructor.

If no explicit initial state is given, this setup function is called. There are three modes: If the CellTraits are set such that the default constructor of the cell state is to be used, that constructor is required and is called for each cell.

Otherwise, the CellState needs to be constructible via a const Config& argument, which gets passed the config entry cell_params from the CellManager's configuration. If a constructor with the signature (const Config&, const std::shared_ptr<RNG>&) is supported, that constructor is called instead.

Note
If the constructor for the cell state has an RNG available it is called anew for each cell; otherwise, an initial state is constructed once and used for all cells.
752 {
753 // Distinguish depending on constructor.
754 // Is the default constructor to be used?
756 static_assert(
757 std::is_default_constructible<CellState>(),
758 "CellTraits were configured to use the default constructor to "
759 "create cell states, but the CellState is not "
760 "default-constructible! Either implement such a constructor, "
761 "unset the flag in the CellTraits, or pass an explicit "
762 "initial cell state to the CellManager."
763 );
764
765 _log->info("Setting up cells using default constructor ...");
766
767 // Create the initial state (same for all cells)
768 return setup_cells(CellState());
769 }
770
771 // Is there a constructor available that allows passing the RNG?
772 else if constexpr (std::is_constructible<CellState,
773 const Config&,
774 const std::shared_ptr<RNG>&
775 >())
776 {
777 _log->info("Setting up cells using config constructor (with RNG) "
778 "...");
779
780 // Extract the configuration parameter
781 if (not _cfg["cell_params"]) {
782 throw std::invalid_argument("CellManager is missing the "
783 "configuration entry 'cell_params' to set up the cells' "
784 "initial states!");
785 }
786 const auto cell_params = _cfg["cell_params"];
787
788 // The cell container to be populated
790
791 // Populate the container, creating the cell state anew each time
792 for (IndexType i=0; i<_grid->num_cells(); i++) {
793 cont.emplace_back(
794 std::make_shared<Cell>(i, CellState(cell_params, _rng))
795 );
796 }
797 // Done. Shrink it.
798 cont.shrink_to_fit();
799 _log->info("Populated cell container with {:d} cells.",
800 cont.size());
801 return cont;
802 }
803
804 // As default, require a Config constructor
805 else {
806 static_assert(
807 std::is_constructible<CellState, const Config&>(),
808 "CellManager::CellState needs to be constructible using "
809 "const Config& as only argument. Either implement "
810 "such a constructor, pass an explicit initial cell state to "
811 "the CellManager, or set the CellTraits such that a default "
812 "constructor is to be used."
813 );
814
815 _log->info("Setting up cells using config constructor ...");
816
817 // Extract the configuration parameter
818 if (not _cfg["cell_params"]) {
819 throw std::invalid_argument("CellManager is missing the "
820 "configuration entry 'cell_params' to set up the cells' "
821 "initial states!");
822 }
823
824 // Create the initial state (same for all cells)
825 return setup_cells(CellState(_cfg["cell_params"]));
826 }
827 // This point is never reached.
828 }
typename Model::Config Config
Configuration node type.
Definition cell_manager.hh:74
typename CellTraits::State CellState
Type of the cell state.
Definition cell_manager.hh:53
std::size_t IndexType
Type for indices, i.e. values used for container indexing, agent IDs, ...
Definition types.hh:40
static constexpr bool use_default_state_constructor
Whether to use the default constructor for constructing a entity state.
Definition entity.hh:57

◆ setup_cells() [2/2]

template<class CellTraits , class Model >
CellContainer< Cell > Utopia::CellManager< CellTraits, Model >::setup_cells ( const CellState initial_state) const
inlineprivate

Set up the cells container using an explicitly passed initial state.

720 {
722
723 // Construct all the cells
724 for (IndexType i=0; i<_grid->num_cells(); i++) {
725 cont.emplace_back(std::make_shared<Cell>(i, initial_state));
726 }
727
728 // Done. Shrink it.
729 cont.shrink_to_fit();
730 _log->info("Populated cell container with {:d} cells.", cont.size());
731
732 return cont;
733 }

◆ setup_cfg()

template<class CellTraits , class Model >
Config Utopia::CellManager< CellTraits, Model >::setup_cfg ( const Model model,
const Config custom_cfg 
) const
inlineprivate

Set up the cell manager configuration member.

This function determines whether to use a custom configuration or the one provided by the model this CellManager belongs to

657 {
658 Config cfg;
659
660 if (custom_cfg.size() > 0) {
661 _log->debug("Using custom config for cell manager setup ...");
662 cfg = custom_cfg;
663 }
664 else {
665 _log->debug("Using '{}' model's configuration for cell manager "
666 "setup ... ", model.get_name());
667
668 if (not model.get_cfg()["cell_manager"]) {
669 throw std::invalid_argument("Missing config entry "
670 "'cell_manager' in model configuration! Either specify "
671 "that key or pass a custom configuration node to the "
672 "CellManager constructor.");
673 }
674 cfg = model.get_cfg()["cell_manager"];
675 }
676 return cfg;
677 }
const Config & cfg() const
Return the configuration used for building this cell manager.
Definition cell_manager.hh:199

◆ setup_grid()

template<class CellTraits , class Model >
std::shared_ptr< GridType > Utopia::CellManager< CellTraits, Model >::setup_grid ( ) const
inlineprivate

Set up the grid discretization.

680 {
681 // Check if the required parameter nodes are available
682 // TODO Throw KeyErrors here instead!
683 if (not _cfg["grid"]) {
684 throw std::invalid_argument("Missing entry 'grid' in the "
685 "configuration node supplied to the CellManager! Check that "
686 "the model configuration includes such an entry.");
687 }
688 else if (not _cfg["grid"]["structure"]) {
689 throw std::invalid_argument("Missing required grid configuration "
690 "entry 'structure'!");
691 }
692
693 // Get the structure parameter
694 auto structure = get_as<std::string>("structure", _cfg["grid"]);
695
696 _log->info("Setting up grid discretization with '{}' cells ...",
697 structure);
698
699 // Create the respective grids, distinguishing by structure
700 if (structure == "triangular") {
702 return std::make_shared<GridSpec>(_space, _cfg["grid"]);
703 }
704 else if (structure == "square") {
706 return std::make_shared<GridSpec>(_space, _cfg["grid"]);
707 }
708 else if (structure == "hexagonal") {
710 return std::make_shared<GridSpec>(_space, _cfg["grid"]);
711 }
712 else {
713 throw std::invalid_argument("Invalid value for grid "
714 "'structure' argument: '" + structure + "'! Allowed "
715 "values: 'square', 'hexagonal', 'triangular'");
716 }
717 }

◆ setup_nb_funcs()

template<class CellTraits , class Model >
void Utopia::CellManager< CellTraits, Model >::setup_nb_funcs ( )
inlineprivate

Setup the neighborhood functions using config entries.

831 {
832 // If there is a neighborhood key, use it to set up the neighborhood
833 if (_cfg["neighborhood"]) {
834 _log->debug("Setting up neighborhood from config entry ...");
835 select_neighborhood(_cfg["neighborhood"]);
836 return;
837 }
838 // else: Use empty.
839
840 _log->debug("No neighborhood configuration given; using empty.");
842 }

◆ space()

template<class CellTraits , class Model >
const std::shared_ptr< Space > & Utopia::CellManager< CellTraits, Model >::space ( ) const
inline

Return pointer to the space, for convenience.

209 {
210 return _space;
211 }

◆ vertices_of() [1/2]

template<class CellTraits , class Model >
std::vector< SpaceVec > Utopia::CellManager< CellTraits, Model >::vertices_of ( const Cell cell) const
inline

Returns a container of vertices of the given cell.

The vertices are the absolute coordinates that define the cell. For example, a 2D square cell is the surface of a polygon defined by four points.

Note
Consult the documentation of the selected grid discretization to learn about the order of the returned values.
276 {
277 return _grid->vertices_of(cell.id());
278 }

◆ vertices_of() [2/2]

template<class CellTraits , class Model >
std::vector< SpaceVec > Utopia::CellManager< CellTraits, Model >::vertices_of ( const std::shared_ptr< Cell > &  cell) const
inline

Returns a container of vertices of the given cell.

Note
Consult the documentation of the selected grid discretization to learn about the order of the returned values.
285 {
286 return _grid->vertices_of(cell->id());
287 }

Member Data Documentation

◆ _cell_neighbors

template<class CellTraits , class Model >
std::vector<CellContainer<Cell> > Utopia::CellManager< CellTraits, Model >::_cell_neighbors
private

Storage container for pre-calculated (!) cell neighbors.

◆ _cells

Storage container for cells.

◆ _cfg

Cell manager configuration node.

◆ _empty_nb_warning_emitted

template<class CellTraits , class Model >
bool Utopia::CellManager< CellTraits, Model >::_empty_nb_warning_emitted = false

Whether a warning about an empty neighbourhood was already emitted.

This is to prevent a gigantic amount of warnings being logged

◆ _grid

template<class CellTraits , class Model >
const std::shared_ptr<GridType> Utopia::CellManager< CellTraits, Model >::_grid
private

The grid that discretely maps cells into space.

◆ _log

template<class CellTraits , class Model >
const std::shared_ptr<spdlog::logger> Utopia::CellManager< CellTraits, Model >::_log
private

The logger (same as the model this manager resides in)

◆ _nb_compute_each_time

template<class CellTraits , class Model >
NBFuncCell Utopia::CellManager< CellTraits, Model >::_nb_compute_each_time
private
Initial value:
= [this](const Cell& cell) {
return
this->_grid->neighbors_of(cell.id()));
}
Utopia::Cell< CellTraits > Cell
Type of the managed cells.
Definition cell_manager.hh:47

Compute the neighbors for the given cell using the grid.

631 {
632 return
634 this->_grid->neighbors_of(cell.id()));
635 };

◆ _nb_compute_each_time_empty

template<class CellTraits , class Model >
NBFuncCell Utopia::CellManager< CellTraits, Model >::_nb_compute_each_time_empty
private
Initial value:
= [this](const Cell& cell) {
this->_log->warn("No neighborhood selected! Calls to the "
"CellManager::neighbors_of method will always return an empty "
"container. There will be no further warning.");
this->_empty_nb_warning_emitted = true;
}
return
this->_grid->neighbors_of(cell.id()));
}
bool _empty_nb_warning_emitted
Whether a warning about an empty neighbourhood was already emitted.
Definition cell_manager.hh:125

Compute the neighbors for the given cell using the grid.

638 {
639 if (not this->_empty_nb_warning_emitted) {
640 this->_log->warn("No neighborhood selected! Calls to the "
641 "CellManager::neighbors_of method will always return an empty "
642 "container. There will be no further warning.");
643 this->_empty_nb_warning_emitted = true;
644 }
645 return
647 this->_grid->neighbors_of(cell.id()));
648 };

◆ _nb_from_cache

template<class CellTraits , class Model >
NBFuncCell Utopia::CellManager< CellTraits, Model >::_nb_from_cache
private
Initial value:
= [this](const Cell& cell) {
return this->_cell_neighbors[cell.id()];
}

Return the pre-computed neighbors of the given cell.

626 {
627 return this->_cell_neighbors[cell.id()];
628 };

◆ _nb_func

The currently chosen neighborhood function (working directly on cells)

◆ _rng

template<class CellTraits , class Model >
const std::shared_ptr<RNG> Utopia::CellManager< CellTraits, Model >::_rng
private

The model's random number generator, used e.g. for cell construction.

◆ _space

template<class CellTraits , class Model >
const std::shared_ptr<Space> Utopia::CellManager< CellTraits, Model >::_space
private

The physical space the cells are to reside in.

◆ dim

template<class CellTraits , class Model >
constexpr DimType Utopia::CellManager< CellTraits, Model >::dim = Model::Space::dim
staticconstexpr

Dimensionality of the space this cell manager is to discretize.


The documentation for this class was generated from the following file: