Utopia 2
Framework for studying models of complex & adaptive systems.
Loading...
Searching...
No Matches
Public Types | Public Member Functions | Private Member Functions | Private Attributes | List of all members
Utopia::Models::ForestFire::ForestFire Class Reference

The ForestFire model. More...

#include <ForestFire.hh>

Inheritance diagram for Utopia::Models::ForestFire::ForestFire:
Inheritance graph
[legend]
Collaboration diagram for Utopia::Models::ForestFire::ForestFire:
Collaboration graph
[legend]

Public Types

using Base = Model< ForestFire, ModelTypes >
 The base model type.
 
using DataSet = typename Base::DataSet
 Data type for a dataset.
 
using CellManager = Utopia::CellManager< CellTraits, ForestFire >
 The type of the cell manager.
 
using Cell = typename CellManager::Cell
 The type of a cell.
 
using RuleFunc = typename CellManager::RuleFunc
 Rule function type, extracted from CellManager.
 
- Public Types inherited from Utopia::Model< ForestFire, ModelTypes >
using Config = typename ModelTypes::Config
 Data type that holds the configuration.
 
using DataManager = DataIO::Default::DefaultDataManager< ForestFire >
 The data manager to use, specialized with the derived model.
 
using DataGroup = typename ModelTypes::DataGroup
 Data type that is used for storing datasets.
 
using DataSet = typename ModelTypes::DataSet
 Data type that is used for storing data.
 
using RNG = typename ModelTypes::RNG
 Data type of the shared RNG.
 
using Space = typename ModelTypes::Space
 Data type of the space this model resides in.
 
using Time = typename ModelTypes::Time
 Data type for the model time.
 
using Monitor = typename ModelTypes::Monitor
 Data type for the monitor.
 
using MonitorManager = typename ModelTypes::MonitorManager
 Data type for the monitor manager.
 
using Level = typename ModelTypes::Level
 Data type for the hierarchical level.
 

Public Member Functions

template<class ParentModel >
 ForestFire (const std::string &name, ParentModel &parent_model, const DataIO::Config &custom_cfg={})
 Construct the ForestFire model.
 
void perform_step ()
 Perform step.
 
void monitor ()
 Provide monitoring information to the frontend: tree_density
 
void write_data ()
 Write data.
 
- Public Member Functions inherited from Utopia::Model< ForestFire, ModelTypes >
 Model (const std::string &name, const ParentModel &parent_model, const Config &custom_cfg={}, std::tuple< WriterArgs... > w_args={}, const DataIO::Default::DefaultDecidermap< ForestFire > &w_deciders=DataIO::Default::default_deciders< ForestFire >, const DataIO::Default::DefaultTriggermap< ForestFire > &w_triggers=DataIO::Default::default_triggers< ForestFire >)
 Constructs a Model instance.
 
const std::shared_ptr< Space > & get_space () const
 Return the space this model resides in.
 
Time get_time () const
 Return the current time of this model.
 
Time get_time_max () const
 Return the maximum time possible for this model.
 
Config get_cfg () const
 Return the config node of this model.
 
std::string get_name () const
 Return the name of this model instance.
 
std::string get_full_name () const
 Return the full name of this model within the model hierarchy.
 
std::shared_ptr< DataGroupget_hdfgrp () const
 Return a pointer to the HDF group this model stores data in.
 
Time get_write_start () const
 Return the parameter that controls when write_data is called first.
 
Time get_write_every () const
 Return the parameter that controls how often write_data is called.
 
DataManager get_datamanager () const
 return the datamanager
 
hsize_t get_remaining_num_writes () const
 Return the number of remaining write_data calls this model will make.
 
std::shared_ptr< RNGget_rng () const
 Return a pointer to the shared RNG.
 
std::shared_ptr< spdlog::logger > get_logger () const
 Return a pointer to the logger of this model.
 
Monitor get_monitor () const
 Return the monitor of this model.
 
std::shared_ptr< MonitorManagerget_monitor_manager () const
 Get the monitor manager of the root model.
 
Level get_level () const
 Return the hierarchical level within the model hierarchy.
 
virtual void prolog ()
 A function that is called before starting model iteration.
 
virtual void epilog ()
 A function that is called after the last iteration of a model.
 
void iterate ()
 Iterate one (time) step of this model.
 
void run ()
 Run the model from the current time to the maximum time.
 
std::shared_ptr< DataSetcreate_dset (const std::string name, const std::shared_ptr< DataGroup > &hdfgrp, std::vector< hsize_t > add_write_shape, const std::size_t compression_level=1, const std::vector< hsize_t > chunksize={})
 Create a new dataset within the given group.
 
std::shared_ptr< DataSetcreate_dset (const std::string name, const std::vector< hsize_t > add_write_shape, const std::size_t compression_level=1, const std::vector< hsize_t > chunksize={})
 Create a new dataset within the model's base data group.
 
std::shared_ptr< DataSetcreate_cm_dset (const std::string name, const CellManager &cm, const std::size_t compression_level=1, const std::vector< hsize_t > chunksize={})
 Create a dataset storing data from a CellManager.
 
std::shared_ptr< DataSetcreate_am_dset (const std::string name, const AgentManager &am, const std::size_t compression_level=1, const std::vector< hsize_t > chunksize={})
 Create a dataset storing data from a AgentManager.
 

Private Member Functions

double calculate_tree_density () const
 Calculate and return the density of tree cells.
 
unsigned int identify_clusters ()
 Identifies clusters in the cells and labels them with corresponding IDs.
 

Private Attributes

CellManager _cm
 The cell manager for the forest fire model.
 
const Param _param
 Model parameters.
 
std::uniform_real_distribution< double_prob_distr
 A [0,1]-range uniform distribution used for evaluating probabilities.
 
unsigned int _cluster_id_cnt
 The incremental cluster tag caching variable.
 
std::vector< std::shared_ptr< CellManager::Cell > > _cluster_members
 A temporary container for use in cluster identification.
 
const bool _write_only_tree_density
 Whether to only write the tree density.
 
const std::shared_ptr< DataSet_dset_kind
 The dataset that stores the kind for each cell, e.g. Kind::tree.
 
const std::shared_ptr< DataSet_dset_age
 2D dataset (tree age and time) of cells
 
const std::shared_ptr< DataSet_dset_cluster_id
 The dataset that stores the cluster id.
 
const std::shared_ptr< DataSet_dset_tree_density
 The dataset that stores the mean density.
 
RuleFunc _update
 Update rule, called every step.
 
RuleFunc _burn_cluster
 Rule to burn a cluster of trees around the given cell.
 
RuleFunc _identify_cluster
 Get the identity of each cluster of trees.
 

Additional Inherited Members

- Protected Member Functions inherited from Utopia::Model< ForestFire, ModelTypes >
void __perform_step ()
 Perform the computation of a step.
 
void __monitor ()
 Monitor information in the terminal.
 
void __write_data ()
 Write data; calls the implementation's write_data method.
 
void __write_initial_state ()
 Write the initial state.
 
void increment_time (const Time dt=1)
 Increment time.
 
void __prolog ()
 The default prolog of a model.
 
void __epilog ()
 The default epilog of a model.
 
ForestFire & impl ()
 cast to the derived class
 
const ForestFire & impl () const
 const cast to the derived interface
 
- Protected Attributes inherited from Utopia::Model< ForestFire, ModelTypes >
const std::string _name
 Name of the model instance.
 
const std::string _full_name
 The full name within the model hierarchy.
 
const Level _level
 The level within the model hierarchy.
 
const Config _cfg
 Config node belonging to this model instance.
 
const std::shared_ptr< RNG_rng
 The RNG shared between models.
 
const std::shared_ptr< spdlog::logger > _log
 The (model) logger.
 
std::shared_ptr< Space_space
 The space this model resides in.
 
Time _time
 Model-internal current time stamp.
 
const Time _time_max
 Model-internal maximum time stamp.
 
const std::shared_ptr< DataGroup_hdfgrp
 The HDF group this model instance should write its data to.
 
const Time _write_start
 First time at which write_data is called.
 
const Time _write_every
 How often to call write_data from iterate.
 
Monitor _monitor
 The monitor.
 
DataManager _datamanager
 Manager object for handling data output; see DataManager.
 
- Static Protected Attributes inherited from Utopia::Model< ForestFire, ModelTypes >
static constexpr WriteMode _write_mode
 Which data-writing mode the base model should use.
 

Detailed Description

The ForestFire model.

The ForestFire model simulates the development of a forest under influence of fires. Trees grow randomly and lightning strikes lead to a whole cluster instantaneously burning down. This is the so-called two state model.

Member Typedef Documentation

◆ Base

The base model type.

◆ Cell

The type of a cell.

◆ CellManager

The type of the cell manager.

◆ DataSet

Data type for a dataset.

◆ RuleFunc

Rule function type, extracted from CellManager.

Constructor & Destructor Documentation

◆ ForestFire()

template<class ParentModel >
Utopia::Models::ForestFire::ForestFire::ForestFire ( const std::string &  name,
ParentModel parent_model,
const DataIO::Config custom_cfg = {} 
)
inline

Construct the ForestFire model.

Parameters
nameName of this model instance; is used to extract the configuration from the parent model and set up a HDFGroup for this instance
parent_modelThe parent model this model instance resides in
custom_cfgA custom configuration to use instead of the one extracted from the parent model using the instance name
208 {}
209 )
210 :
211 // Initialize first via base model
213
214 // Initialize the cell manager, binding it to this model
215 _cm(*this),
216
217 // Carry over parameters
218 _param(this->_cfg),
219
220 // Initialize remaining members
221 _prob_distr(0., 1.),
224 _write_only_tree_density(get_as<bool>("write_only_tree_density",
225 this->_cfg)),
226
227 // Create datasets using the helper functions for CellManager-data
230 _dset_cluster_id{this->create_cm_dset("cluster_id", _cm)},
231 _dset_tree_density{this->create_dset("tree_density", {})}
232 {
233 // Cells are already set up in the CellManager.
234 // Take care of the heterogeneities now:
235
236 // Stones
237 if (_cfg["stones"] and get_as<bool>("enabled", _cfg["stones"])) {
238 this->_log->info("Setting cells to be stones ...");
239
240 // Get the container
241 auto to_turn_to_stone = _cm.select_cells(_cfg["stones"]);
242
243 // Apply a rule to all cells of that container: turn to stone
245 [](const auto& cell){
246 auto& state = cell->state;
247 state.kind = Kind::stone;
248 return state;
249 },
251 );
252
253 this->_log->info("Set {} cells to be stones using selection mode "
254 "'{}'.", to_turn_to_stone.size(),
255 get_as<std::string>("mode", _cfg["stones"]));
256 }
257
258 // Ignite some cells permanently: fire sources
259 if ( _cfg["ignite_permanently"]
260 and get_as<bool>("enabled", _cfg["ignite_permanently"]))
261 {
262 this->_log->info("Setting cells to be permanently ignited ...");
263 auto to_be_ignited = _cm.select_cells(_cfg["ignite_permanently"]);
264
266 [](const auto& cell){
267 auto& state = cell->state;
268 state.kind = Kind::source;
269 return state;
270 },
272 );
273
274 this->_log->info("Set {} cells to be permanently ignited using "
275 "selection mode '{}'.", to_be_ignited.size(),
276 get_as<std::string>("mode", _cfg["ignite_permanently"]));
277 }
278
279 this->_log->debug("{} model fully set up.", this->_name);
280 }
CellContainer< Cell > select_cells(Args &&... args) const
Select cells using the Utopia::select_entities interface.
Definition cell_manager.hh:342
std::shared_ptr< DataSet > create_cm_dset(const std::string name, const CellManager &cm, const std::size_t compression_level=1, const std::vector< hsize_t > chunksize={})
Create a dataset storing data from a CellManager.
Definition model.hh:849
const Config _cfg
Config node belonging to this model instance.
Definition model.hh:158
const std::string _name
Name of the model instance.
Definition model.hh:149
const std::shared_ptr< spdlog::logger > _log
The (model) logger.
Definition model.hh:164
std::shared_ptr< DataSet > create_dset(const std::string name, const std::shared_ptr< DataGroup > &hdfgrp, std::vector< hsize_t > add_write_shape, const std::size_t compression_level=1, const std::vector< hsize_t > chunksize={})
Create a new dataset within the given group.
Definition model.hh:752
CellManager _cm
The cell manager for the forest fire model.
Definition ForestFire.hh:162
Model< ForestFire, ModelTypes > Base
The base model type.
Definition ForestFire.hh:141
std::uniform_real_distribution< double > _prob_distr
A [0,1]-range uniform distribution used for evaluating probabilities.
Definition ForestFire.hh:168
const std::shared_ptr< DataSet > _dset_age
2D dataset (tree age and time) of cells
Definition ForestFire.hh:184
unsigned int _cluster_id_cnt
The incremental cluster tag caching variable.
Definition ForestFire.hh:171
std::vector< std::shared_ptr< CellManager::Cell > > _cluster_members
A temporary container for use in cluster identification.
Definition ForestFire.hh:174
const std::shared_ptr< DataSet > _dset_tree_density
The dataset that stores the mean density.
Definition ForestFire.hh:190
const std::shared_ptr< DataSet > _dset_kind
The dataset that stores the kind for each cell, e.g. Kind::tree.
Definition ForestFire.hh:181
const bool _write_only_tree_density
Whether to only write the tree density.
Definition ForestFire.hh:178
const Param _param
Model parameters.
Definition ForestFire.hh:165
const std::shared_ptr< DataSet > _dset_cluster_id
The dataset that stores the cluster id.
Definition ForestFire.hh:187
ReturnType get_as(const std::string &key, const DataIO::Config &node)
This function is a wrapper around the yaml-cpp YAML::Node::as function.
Definition cfg_utils.hh:158
Container select_entities(const Manager &mngr, const DataIO::Config &sel_cfg)
Select entities according to parameters specified in a configuration.
Definition select.hh:213

Member Function Documentation

◆ calculate_tree_density()

double Utopia::Models::ForestFire::ForestFire::calculate_tree_density ( ) const
inlineprivate

Calculate and return the density of tree cells.

288 {
289 // NOTE If execution policies are implemented, this could be easily
290 // made parallel by replacing std::accumulate with std::reduce
291 // and adding std::execution::par from the header
292 // <execution> as first argument.
293 return
294 std::accumulate(_cm.cells().begin(), _cm.cells().end(),
295 0,
296 [&](std::size_t sum, const std::shared_ptr<Cell>& cell) {
297 return sum + (cell->state.kind == Kind::tree);
298 }
299 )
300 / static_cast<double>(_cm.cells().size());
301 }
const CellContainer< Cell > & cells() const
Return const reference to the managed CA cells.
Definition cell_manager.hh:219

◆ identify_clusters()

unsigned int Utopia::Models::ForestFire::ForestFire::identify_clusters ( )
inlineprivate

Identifies clusters in the cells and labels them with corresponding IDs.

This function updates the cluster ID of each cell. This only applies to cells that are trees; all others keep ID 0.

Returns
Number of clusters identified
309 {
310 this->_log->debug("Identifying clusters...");
311
312 // Reset counter for cluster IDs, then call the identification function
313 _cluster_id_cnt = 0;
314
317 );
318
319 this->_log->debug("Identified {} clusters.", _cluster_id_cnt);
320
321 return _cluster_id_cnt;
322 }
RuleFunc _identify_cluster
Get the identity of each cluster of trees.
Definition ForestFire.hh:436

◆ monitor()

void Utopia::Models::ForestFire::ForestFire::monitor ( )
inline

Provide monitoring information to the frontend: tree_density

487 {
488 this->_monitor.set_entry("tree_density", calculate_tree_density());
489 }
Monitor _monitor
The monitor.
Definition model.hh:188
double calculate_tree_density() const
Calculate and return the density of tree cells.
Definition ForestFire.hh:288

◆ perform_step()

void Utopia::Models::ForestFire::ForestFire::perform_step ( )
inline

Perform step.

479 {
480 // Apply update rule on all cells, asynchronously and shuffled
482 _update, _cm.cells(), *this->_rng
483 );
484 }
RuleFunc _update
Update rule, called every step.
Definition ForestFire.hh:341

◆ write_data()

void Utopia::Models::ForestFire::ForestFire::write_data ( )
inline

Write data.

492 {
493 // Calculate and write the tree density
495
497 // Done here.
498 return;
499 }
500
501 // Store all cells' kind
502 _dset_kind->write(_cm.cells().begin(), _cm.cells().end(),
503 [](const auto& cell) {
504 return static_cast<char>(cell->state.kind);
505 });
506
507 // ... and age
508 _dset_age->write(_cm.cells().begin(), _cm.cells().end(),
509 [](const auto& cell) {
510 return cell->state.age;
511 });
512
513 // Identify the clusters (only needed when actually writing)
515 _dset_cluster_id->write(_cm.cells().begin(), _cm.cells().end(),
516 [](const auto& cell) {
517 return cell->state.cluster_id;
518 });
519 }
unsigned int identify_clusters()
Identifies clusters in the cells and labels them with corresponding IDs.
Definition ForestFire.hh:309

Member Data Documentation

◆ _burn_cluster

RuleFunc Utopia::Models::ForestFire::ForestFire::_burn_cluster
private

Rule to burn a cluster of trees around the given cell.

Note
This function is never actually called via apply_rule, but only from the update method. It relies on an asynchronous cell update.
387 {
388 // A tree cell should burn, i.e.: transition to empty.
389 if (cell->state.kind == Kind::tree) {
390 cell->state.kind = Kind::empty;
391 }
392 // The only other possibility would be a fire source: remains alight!
393
394 // Use existing cluster member container, clear it, add current cell
396 cluster.clear();
397 cluster.push_back(cell);
398
399 // Recursively go over all cluster members
400 for (unsigned int i = 0; i < cluster.size(); ++i) {
401 const auto& cluster_member = cluster[i];
402
403 // Iterate over all potential cluster members
404 for (const auto& c : this->_cm.neighbors_of(cluster_member)) {
405 // If it is a tree, it will burn ...
406 if (c->state.kind == Kind::tree) {
407 // ... unless there is p_immunity > 0 ...
408 if (this->_param.p_immunity > 0.) {
409 // ... where there is a chance not to burn:
410 if ( this->_prob_distr(*this->_rng)
411 < _param.p_immunity) {
412 continue;
413 }
414 }
415
416 // Bad luck. Burn.
417 c->state.kind = Kind::empty;
418 c->state.age = 0;
419 cluster.push_back(c);
420 // This extends the outer for-loop
421 }
422 }
423 }
424
425 // Return the current cell's adjusted state.
426 return cell->state;
427 };
const std::shared_ptr< RNG > _rng
The RNG shared between models.
Definition model.hh:161
const double p_immunity
The probability (per neighbor) to be immune to a spreading fire.
Definition ForestFire.hh:97

◆ _cluster_id_cnt

unsigned int Utopia::Models::ForestFire::ForestFire::_cluster_id_cnt
private

The incremental cluster tag caching variable.

◆ _cluster_members

std::vector<std::shared_ptr<CellManager::Cell> > Utopia::Models::ForestFire::ForestFire::_cluster_members
private

A temporary container for use in cluster identification.

◆ _cm

CellManager Utopia::Models::ForestFire::ForestFire::_cm
private

The cell manager for the forest fire model.

◆ _dset_age

const std::shared_ptr<DataSet> Utopia::Models::ForestFire::ForestFire::_dset_age
private

2D dataset (tree age and time) of cells

◆ _dset_cluster_id

const std::shared_ptr<DataSet> Utopia::Models::ForestFire::ForestFire::_dset_cluster_id
private

The dataset that stores the cluster id.

◆ _dset_kind

const std::shared_ptr<DataSet> Utopia::Models::ForestFire::ForestFire::_dset_kind
private

The dataset that stores the kind for each cell, e.g. Kind::tree.

◆ _dset_tree_density

const std::shared_ptr<DataSet> Utopia::Models::ForestFire::ForestFire::_dset_tree_density
private

The dataset that stores the mean density.

◆ _identify_cluster

RuleFunc Utopia::Models::ForestFire::ForestFire::_identify_cluster
private

Get the identity of each cluster of trees.

436 {
437 // Only need to continue if a tree and not already labelled
438 if ( cell->state.cluster_id != 0
439 or cell->state.kind != Kind::tree)
440 {
441 return cell->state;
442 }
443 // else: is an unlabelled tree; need to label it.
444
445 // Increment the cluster ID counter and label the given cell
447 cell->state.cluster_id = _cluster_id_cnt;
448
449 // Use existing cluster member container, clear it, add current cell
451 cluster.clear();
452 cluster.push_back(cell);
453
454 // Perform the percolation
455 for (unsigned int i = 0; i < cluster.size(); ++i) {
456 // Iterate over all potential cluster members c, i.e. all
457 // neighbors of cell cluster[i] that is already in the cluster
458 for (const auto& c : this->_cm.neighbors_of(cluster[i])) {
459 // If it is a tree that is not yet in the cluster, add it.
460 if ( c->state.cluster_id == 0
461 and c->state.kind == Kind::tree)
462 {
463 c->state.cluster_id = _cluster_id_cnt;
464 cluster.push_back(c);
465 // This extends the outer for-loop...
466 }
467 }
468 }
469
470 return cell->state;
471 };

◆ _param

const Param Utopia::Models::ForestFire::ForestFire::_param
private

Model parameters.

◆ _prob_distr

std::uniform_real_distribution<double> Utopia::Models::ForestFire::ForestFire::_prob_distr
private

A [0,1]-range uniform distribution used for evaluating probabilities.

◆ _update

RuleFunc Utopia::Models::ForestFire::ForestFire::_update
private

Update rule, called every step.

The possible transitions are the following:

- empty -> tree (with p_growth)
- tree -> burning (with p_lightning)

A burning tree directly invokes the burning of the whole cluster of connected trees ("two-state FFM"). After that, all burned cells are in the empty state again.

Additionally, some trees are constantly ignited and will always lead to the burning of the adjacent cluster. Other cells ("stones") do not take part in interactions at all.

Note
This rule relies on an asynchronous cell update.
341 {
342 // Get the current state of the cell and reset the cluster tag
343 auto& state = cell->state;
344 state.cluster_id = 0;
345
346 // Empty cells can grow a tree
347 if (state.kind == Kind::empty) {
348 if (this->_prob_distr(*this->_rng) < _param.p_growth) {
349 state.kind = Kind::tree;
350 }
351 }
352
353 // Trees can be hit by lightning or continue living
354 else if (state.kind == Kind::tree) {
355 // Can be hit by lightning
356 if (this->_prob_distr(*this->_rng) < _param.p_lightning) {
357 state = _burn_cluster(cell);
358 }
359 else {
360 // Lives. Increase its age
361 state.age++;
362 }
363 }
364
365 // Permanently ignited cells always burn the cluster
366 else if (state.kind == Kind::source) {
367 state = _burn_cluster(cell);
368 }
369
370 // Stones don't do anything
371 else if (state.kind == Kind::stone) {
372 // Not doing anything, like the good stone I am ...
373 }
374
375 else {
376 // Should never occur!
377 throw std::invalid_argument("Invalid cell state!");
378 }
379
380 return state;
381 };
RuleFunc _burn_cluster
Rule to burn a cluster of trees around the given cell.
Definition ForestFire.hh:387
const double p_lightning
Frequency of lightning occurring per cell.
Definition ForestFire.hh:94
const double p_growth
Rate of growth per cell.
Definition ForestFire.hh:91

◆ _write_only_tree_density

const bool Utopia::Models::ForestFire::ForestFire::_write_only_tree_density
private

Whether to only write the tree density.


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