1 #ifndef UTOPIA_CORE_CELL_MANAGER_HH
2 #define UTOPIA_CORE_CELL_MANAGER_HH
7 #include <unordered_set>
40 template<
class CellTraits,
class Model>
84 typename std::function<
CellState(
const std::shared_ptr<Cell>&)>;
92 typename std::function<void(
const std::shared_ptr<Cell>&)>;
98 const std::shared_ptr<spdlog::logger>
_log;
104 const std::shared_ptr<RNG>
_rng;
110 const std::shared_ptr<GridType>
_grid;
142 const Config& custom_cfg = {})
158 _log->info(
"CellManager is all set up.");
172 const Config& custom_cfg = {})
188 _log->info(
"CellManager is all set up.");
194 const auto&
log ()
const {
204 const std::shared_ptr<RNG>&
rng ()
const {
209 const std::shared_ptr<Space>&
space ()
const {
214 const std::shared_ptr<GridType>&
grid ()
const {
237 return _grid->midx_of(cell.
id());
245 return _grid->midx_of(cell->id());
250 return _grid->barycenter_of(cell.
id());
255 return _grid->barycenter_of(cell->id());
260 return _grid->extent_of(cell.
id());
265 return _grid->extent_of(cell->id());
277 return _grid->vertices_of(cell.
id());
284 std::vector<SpaceVec>
vertices_of(
const std::shared_ptr<Cell>& cell)
const
286 return _grid->vertices_of(cell->id());
325 _log->warn(
"Selecting boundary cells (mode '{}') of a periodic "
326 "space will always return an empty container!", select);
343 return select_entities<mode>(*
this, std::forward<Args>(args)...);
387 template<
class ElementT=
double,
class SetterFunc>
389 const std::string& dset_path,
390 const SetterFunc& setter_func)
392 static_assert(
dim == 2,
"Loading cell state is only supported in 2D!");
394 "Setting cell states for cell update modes other than "
395 "Update::manual is currently not supported.");
399 _log->debug(
"Setting cell states using HDF5 data ...");
400 _log->debug(
" File: {}", hdf5_file);
401 _log->debug(
" Dataset path: {}", dset_path);
404 arma::Mat<ElementT> data;
405 data.load(arma::hdf5_name(hdf5_file, dset_path,
406 arma::hdf5_opts::trans));
413 if (not data.size()) {
414 throw std::runtime_error(
"Failed loading HDF5 data! Is the file "
415 "used by another program?");
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 ("
430 for (
const auto& cell :
_cells) {
431 const auto midx = this->
midx_of(cell);
432 setter_func(cell, data(midx[0], midx[1]));
435 _log->debug(
"Cell states set successfully.");
444 return _grid->nb_mode();
451 return _grid->nb_size();
488 if (not nb_cfg[
"mode"]) {
489 throw KeyError(
"mode", nb_cfg,
"Could not select neighborhood!");
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);
512 const bool compute_and_store =
true,
513 const Config& nb_params = {})
517 throw std::invalid_argument(
"Got unexpected neighborhood mode '"
518 +
nb_mode +
"'! Available modes: empty, vonNeumann, Moore, "
524 compute_and_store, nb_params);
536 const bool compute_and_store =
true,
537 const Config& nb_params = {})
542 _log->info(
"Selecting '{}' neighborhood ...",
561 _log->debug(
"Cleared cell neighborhood cache.");
564 _log->debug(
"Successfully selected '{}' neighborhood (size: {}).",
568 _log->debug(
"Neighborhood was already set to '{}'; not changing.",
573 if (compute_and_store) {
583 _log->info(
"Computing and storing '{}' neighbors of all {} cells ...",
591 for (
const auto& cell :
_cells) {
597 _log->info(
"Computed and stored cell neighbors.");
606 template<
class IndexContainer>
609 ret.reserve(ids.size());
611 for (
const auto&
id : ids) {
612 ret.emplace_back(std::shared_ptr<Cell>(
_cells[
id]));
627 return this->_cell_neighbors[cell.id()];
634 this->_grid->neighbors_of(cell.id()));
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;
647 this->_grid->neighbors_of(cell.id()));
660 if (custom_cfg.size() > 0) {
661 _log->debug(
"Using custom config for cell manager setup ...");
665 _log->debug(
"Using '{}' model's configuration for cell manager "
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.");
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.");
688 else if (not
_cfg[
"grid"][
"structure"]) {
689 throw std::invalid_argument(
"Missing required grid configuration "
690 "entry 'structure'!");
694 auto structure = get_as<std::string>(
"structure",
_cfg[
"grid"]);
696 _log->info(
"Setting up grid discretization with '{}' cells ...",
700 if (structure ==
"triangular") {
702 return std::make_shared<GridSpec>(
_space,
_cfg[
"grid"]);
704 else if (structure ==
"square") {
706 return std::make_shared<GridSpec>(
_space,
_cfg[
"grid"]);
708 else if (structure ==
"hexagonal") {
710 return std::make_shared<GridSpec>(
_space,
_cfg[
"grid"]);
713 throw std::invalid_argument(
"Invalid value for grid "
714 "'structure' argument: '" + structure +
"'! Allowed "
715 "values: 'square', 'hexagonal', 'triangular'");
725 cont.emplace_back(std::make_shared<Cell>(i, initial_state));
729 cont.shrink_to_fit();
730 _log->info(
"Populated cell container with {:d} cells.", cont.size());
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."
765 _log->info(
"Setting up cells using default constructor ...");
772 else if constexpr (std::is_constructible<
CellState,
774 const std::shared_ptr<RNG>&
777 _log->info(
"Setting up cells using config constructor (with RNG) "
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' "
786 const auto cell_params =
_cfg[
"cell_params"];
798 cont.shrink_to_fit();
799 _log->info(
"Populated cell container with {:d} cells.",
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."
815 _log->info(
"Setting up cells using config constructor ...");
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' "
833 if (
_cfg[
"neighborhood"]) {
834 _log->debug(
"Setting up neighborhood from config entry ...");
840 _log->debug(
"No neighborhood configuration given; using empty.");
A cell is a slightly specialized state container.
Definition: cell.hh:40
Manages a physical space, its grid discretization, and cells on that grid.
Definition: cell_manager.hh:41
Config setup_cfg(const Model &model, const Config &custom_cfg) const
Set up the cell manager configuration member.
Definition: cell_manager.hh:657
MultiIndex midx_of(const std::shared_ptr< Cell > &cell) const
Returns the multi-index of the given cell.
Definition: cell_manager.hh:244
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.
Definition: cell_manager.hh:388
typename Model::RNG RNG
Random number generator type.
Definition: cell_manager.hh:71
const CellContainer< Cell > & cells() const
Return const reference to the managed CA cells.
Definition: cell_manager.hh:219
const NBMode & nb_mode() const
Return the currently selected neighborhood mode.
Definition: cell_manager.hh:443
typename GridType::MultiIndex MultiIndex
Type of multi-index like arrays.
Definition: cell_manager.hh:68
const std::shared_ptr< Cell > & cell_at(const SpaceVec &pos) const
Return the cell covering the given point in physical space.
Definition: cell_manager.hh:302
typename Model::Config Config
Configuration node type.
Definition: cell_manager.hh:74
CellContainer< Cell > setup_cells() const
Set up cells container via config or default constructor.
Definition: cell_manager.hh:752
typename std::function< CellState(const std::shared_ptr< Cell > &)> RuleFunc
The type of a rule function acting on cells of this cell manager.
Definition: cell_manager.hh:84
CellContainer< Cell > select_cells(Args &&... args) const
Select cells using the Utopia::select_entities interface.
Definition: cell_manager.hh:342
const Config _cfg
Cell manager configuration node.
Definition: cell_manager.hh:101
static constexpr DimType dim
Dimensionality of the space this cell manager is to discretize.
Definition: cell_manager.hh:59
std::vector< CellContainer< Cell > > _cell_neighbors
Storage container for pre-calculated (!) cell neighbors.
Definition: cell_manager.hh:116
SpaceVec barycenter_of(const Cell &cell) const
Returns the barycenter of the given cell.
Definition: cell_manager.hh:249
typename std::function< void(const std::shared_ptr< Cell > &)> VoidRuleFunc
The type of a void rule function acting on cells of this cell manager.
Definition: cell_manager.hh:92
void select_neighborhood(const Config &nb_cfg)
Select the neighborhood and all parameters fully from a config node.
Definition: cell_manager.hh:486
MultiIndex midx_of(const Cell &cell) const
Returns the multi-index of the given cell.
Definition: cell_manager.hh:236
auto nb_size() const
Return the (maximum) size of the currently selected neighborhood.
Definition: cell_manager.hh:450
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
CellManager(const Model &model, const Config &custom_cfg={})
Construct a cell manager.
Definition: cell_manager.hh:141
const std::shared_ptr< GridType > & grid() const
Return const reference to the grid.
Definition: cell_manager.hh:214
CellContainer< Cell > neighbors_of(const Cell &cell) const
Retrieve the given cell's neighbors.
Definition: cell_manager.hh:458
NBFuncCell _nb_compute_each_time_empty
Compute the neighbors for the given cell using the grid.
Definition: cell_manager.hh:638
NBFuncCell _nb_from_cache
Return the pre-computed neighbors of the given cell.
Definition: cell_manager.hh:626
SpaceVecType< dim > SpaceVec
Type of vectors that represent a physical quantity.
Definition: cell_manager.hh:65
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_compute_each_time
Compute the neighbors for the given cell using the grid.
Definition: cell_manager.hh:631
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
std::shared_ptr< GridType > setup_grid() const
Set up the grid discretization.
Definition: cell_manager.hh:680
const std::shared_ptr< Space > _space
The physical space the cells are to reside in.
Definition: cell_manager.hh:107
const Config & cfg() const
Return the configuration used for building this cell manager.
Definition: cell_manager.hh:199
SpaceVec extent_of(const Cell &cell) const
Returns the physical extent of the given cell.
Definition: cell_manager.hh:259
SpaceVec barycenter_of(const std::shared_ptr< Cell > &cell) const
Returns the barycenter of the given cell.
Definition: cell_manager.hh:254
bool _empty_nb_warning_emitted
Whether a warning about an empty neighbourhood was already emitted.
Definition: cell_manager.hh:125
SpaceVec extent_of(const std::shared_ptr< Cell > &cell) const
Returns the physical extent of the given cell.
Definition: cell_manager.hh:264
Utopia::Cell< CellTraits > Cell
Type of the managed cells.
Definition: cell_manager.hh:47
typename Model::Space Space
The space type this cell manager maps to.
Definition: cell_manager.hh:56
CellManager(const Model &model, const CellState initial_state, const Config &custom_cfg={})
Construct a cell manager explicitly passing an initial cell state.
Definition: cell_manager.hh:170
std::vector< SpaceVec > vertices_of(const std::shared_ptr< Cell > &cell) const
Returns a container of vertices of the given cell.
Definition: cell_manager.hh:284
void compute_cell_neighbors()
Compute (and store) all cells' neighbors.
Definition: cell_manager.hh:582
const std::shared_ptr< RNG > & rng() const
Return a reference to the shared random number generator.
Definition: cell_manager.hh:204
CellContainer< Cell > select_cells(const Config &sel_cfg) const
Select entities according to parameters specified in a configuration.
Definition: cell_manager.hh:356
CellContainer< Cell > boundary_cells(const std::string &select="all") const
Retrieve a container of cells that are at a specified boundary.
Definition: cell_manager.hh:323
std::function< CellContainer< Cell >(const Cell &)> NBFuncCell
Neighborhood function used in public interface (with cell as argument)
Definition: cell_manager.hh:77
void select_neighborhood(const NBMode &nb_mode, const bool compute_and_store=true, const Config &nb_params={})
Set the neighborhood mode.
Definition: cell_manager.hh:535
const std::shared_ptr< GridType > _grid
The grid that discretely maps cells into space.
Definition: cell_manager.hh:110
const auto & log() const
Definition: cell_manager.hh:194
const std::shared_ptr< Space > & space() const
Return pointer to the space, for convenience.
Definition: cell_manager.hh:209
CellContainer< Cell > setup_cells(const CellState &initial_state) const
Set up the cells container using an explicitly passed initial state.
Definition: cell_manager.hh:720
typename CellTraits::State CellState
Type of the cell state.
Definition: cell_manager.hh:53
const std::shared_ptr< RNG > _rng
The model's random number generator, used e.g. for cell construction.
Definition: cell_manager.hh:104
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.
Definition: cell_manager.hh:511
const CellContainer< Cell > & entities() const
Return const reference to the entities managed by this manager: cells.
Definition: cell_manager.hh:224
std::vector< SpaceVec > vertices_of(const Cell &cell) const
Returns a container of vertices of the given cell.
Definition: cell_manager.hh:276
CellContainer< Cell > neighbors_of(const std::shared_ptr< Cell > &cell) const
Retrieve the given cell's neighbors.
Definition: cell_manager.hh:466
const IndexType & id() const
Return const reference to entity ID.
Definition: entity.hh:134
The base class for all grid discretizations used by the CellManager.
Definition: base.hh:99
MultiIndexType< dim > MultiIndex
The type of multi-index like arrays, e.g. the grid shape.
Definition: base.hh:111
A grid discretization using hexagonal cells.
Definition: hexagonal.hh:50
For access to a dict-like structure with a bad key.
Definition: exceptions.hh:67
Base class interface for Models using the CRT Pattern.
Definition: model.hh:112
std::shared_ptr< spdlog::logger > get_logger() const
Return a pointer to the logger of this model.
Definition: model.hh:485
typename ModelTypes::Space Space
Data type of the space this model resides in.
Definition: model.hh:131
std::string get_name() const
Return the name of this model instance.
Definition: model.hh:417
Config get_cfg() const
Return the config node of this model.
Definition: model.hh:412
std::shared_ptr< RNG > get_rng() const
Return a pointer to the shared RNG.
Definition: model.hh:480
typename ModelTypes::Config Config
Data type that holds the configuration.
Definition: model.hh:116
typename ModelTypes::RNG RNG
Data type of the shared RNG.
Definition: model.hh:128
const std::shared_ptr< Space > & get_space() const
Return the space this model resides in.
Definition: model.hh:388
A grid discretization using square cells.
Definition: square.hh:31
A grid discretization using triangular cells.
Definition: triangular.hh:16
NBMode
Possible neighborhood types; availability depends on choice of grid.
Definition: base.hh:52
const std::map< std::string, NBMode > nb_mode_map
A map from strings to neighborhood enum values.
Definition: base.hh:67
std::string nb_mode_to_string(const NBMode &nb_mode)
Given an NBMode enum value, return the corresponding string key.
Definition: base.hh:78
@ empty
Every entity is utterly alone in the world.
std::string to_string(const Config &node)
Given a config node, returns a string representation of it.
Definition: cfg_utils.hh:110
SelectionMode
Possible selection modes; availability depends on choice of manager.
Definition: select.hh:72
Container select_entities(const Manager &mngr, const DataIO::Config &sel_cfg)
Select entities according to parameters specified in a configuration.
Definition: select.hh:200
@ manual
User chooses update type when calling apply_rule()
arma::Col< double >::fixed< dim > SpaceVecType
Type for vector-like data that is associated with a physical space.
Definition: types.hh:61
std::vector< IndexType > IndexContainer
Type for container of indices.
Definition: types.hh:43
unsigned short DimType
Type for dimensions, i.e. very small unsigned integers.
Definition: types.hh:34
EntityContainer< CellType > CellContainer
Type of the variably sized container for cells.
Definition: types.hh:26
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
static constexpr Update mode
Whether the entitys should be synchronously updated.
Definition: entity.hh:54
StateType State
Type of the entitys' state container.
Definition: entity.hh:51