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

The agent manager manages the agents living in a model. More...

#include <agent_manager.hh>

Public Types

using Self = AgentManager< AgentTraits, Model >
 The type of this AgentManager.
 
using Space = typename Model::Space
 The type of the space.
 
using Agent = Utopia::Agent< AgentTraits, Space >
 The type of the managed agents.
 
using Entity = Agent
 Alias for entity type; part of the shared interface of entity managers.
 
using AgentState = typename AgentTraits::State
 The type of the agent state.
 
using SpaceVec = SpaceVecType< dim >
 The type of the vectors that represent physical quantities.
 
using MoveFunc = std::function< void(Agent &, const SpaceVec &)>
 The type of the move function type.
 
using PosFunc = std::function< SpaceVec(const SpaceVec &)>
 The type of the function that prepares the position of a new agent.
 
using RuleFunc = std::function< AgentState(const std::shared_ptr< Agent > &)>
 The type of a rule function acting on agents of this agent manager.
 
using VoidRuleFunc = std::function< void(const std::shared_ptr< Agent > &)>
 The type of a void rule function acting on agents of this agent manager.
 
using RNG = typename Model::RNG
 The random number generator type.
 

Public Member Functions

 AgentManager (const Model &model, const DataIO::Config &custom_cfg={})
 Construct an agent manager.
 
 AgentManager (const Model &model, const AgentState initial_state, const DataIO::Config &custom_cfg={})
 Construct an agent manager, using the same initial state for all agents.
 
const autolog () const
 
const DataIO::Configcfg () const
 Return the configuration used for building this AgentManager.
 
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 AgentContainer< Agent > & agents () const
 Return const reference to the managed agents.
 
const AgentContainer< Agent > & entities () const
 Return const reference to the entities managed by this manager: agents.
 
IndexType id_counter () const
 Return the ID counter.
 
void move_to (const std::shared_ptr< Agent > &agent, const SpaceVec &pos) const
 Move an agent to a new position in the space.
 
void move_to (Agent &agent, const SpaceVec &pos) const
 Move an agent to a new position in the space.
 
void move_by (const std::shared_ptr< Agent > &agent, const SpaceVec &move_vec) const
 Move an agent relative to its current position.
 
void move_by (Agent &agent, const SpaceVec &move_vec) const
 Move an agent relative to its current position.
 
const std::shared_ptr< Agent > & add_agent (const AgentState &state, const SpaceVec &pos)
 Create an agent and associate it with this AgentManager.
 
const std::shared_ptr< Agent > & add_agent (const SpaceVec &pos, const Config &custom_cfg={})
 add_agent overload for auto-constructed agent states
 
const std::shared_ptr< Agent > & add_agent (const Config &custom_cfg={})
 add_agent overload for auto constructed states and random position
 
void remove_agent (const std::shared_ptr< Agent > &agent)
 Removes the given agent from the agent manager.
 
template<typename UnaryPredicate >
void erase_agent_if (UnaryPredicate &&condition)
 Remove agents if the given condition is met.
 
void update_agents ()
 Update the agents.
 
template<SelectionMode mode, class... Args>
AgentContainer< Agentselect_agents (Args &&... args)
 Select agents using the Utopia::select_entities interface.
 
AgentContainer< Agentselect_agents (const Config &sel_cfg)
 Select entities according to parameters specified in a configuration.
 
SpaceVec displacement (const std::shared_ptr< Agent > &a, const std::shared_ptr< Agent > &b) const
 Returns the (shortest) displacement vector between two agents.
 
template<class NormType = std::size_t>
double distance (const std::shared_ptr< Agent > &a, const std::shared_ptr< Agent > &b, const NormType p=2) const
 Returns the (shortest) distance between two agents.
 
AgentContainer< Agentneighbors_of (const std::shared_ptr< Agent > &agent, const double radius) const
 Returns a container of all agents within a certain radius.
 

Static Public Attributes

static constexpr DimType dim = Space::dim
 The dimensionality of the space.
 

Private Member Functions

SpaceVec random_pos () const
 Returns a valid (uniformly) random position in space.
 
Config setup_cfg (const Model &model, const Config &custom_cfg)
 Set up the agent manager configuration member.
 
SpaceVec initial_agent_pos ()
 Setup helper used to determine a single agent's initial position.
 
void setup_agents (const AgentState &initial_state)
 Set up the manager's agent container with initial states.
 
void setup_agents ()
 Set up agents container via config or default constructor.
 
MoveFunc setup_move_to_func () const
 Depending on periodicity, return the function to move agents in space.
 
PosFunc setup_prepare_pos_func () const
 

Private Attributes

IndexType _id_counter
 Counts the number of agents created with this manager, used for new IDs.
 
const std::shared_ptr< spdlog::logger > _log
 The logger (same as the model this manager resides in)
 
const DataIO::Config _cfg
 Agent manager configuration node.
 
const std::shared_ptr< RNG_rng
 The model's random number generator.
 
const std::shared_ptr< Space_space
 The physical space the agents are to reside in.
 
AgentContainer< Agent_agents
 Storage container for agents.
 
MoveFunc _move_to_func
 Function that will be used for moving agents, called by move_* methods.
 
PosFunc _prepare_pos
 Function that will be used to prepare positions for adding an agent.
 

Detailed Description

template<class AgentTraits, class Model>
class Utopia::AgentManager< AgentTraits, Model >

The agent manager manages the agents living in a model.

The agent manager holds a container with all agents that live in a model space. It provides dynamic functions such as to move models within a space and ensures that the agents move correctly and are never allowed to leave the allowed space. Further, all agents get an ID that is unique among all existing agents (also with respect to multiple agent managers).

Template Parameters
AgentTraitsSpecialized Utopia::AgentTraits describing the kind of agents this manager should manage
ModelThe model this AgentManager resides in

Member Typedef Documentation

◆ Agent

The type of the managed agents.

◆ AgentState

The type of the agent state.

◆ Entity

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

◆ MoveFunc

template<class AgentTraits , class Model >
using Utopia::AgentManager< AgentTraits, Model >::MoveFunc = std::function<void(Agent&, const SpaceVec&)>

The type of the move function type.

◆ PosFunc

The type of the function that prepares the position of a new agent.

◆ RNG

The random number generator type.

◆ RuleFunc

template<class AgentTraits , class Model >
using Utopia::AgentManager< AgentTraits, Model >::RuleFunc = std::function<AgentState(const std::shared_ptr<Agent>&)>

The type of a rule function acting on agents of this agent manager.

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

◆ Self

The type of this AgentManager.

◆ Space

The type of the space.

◆ SpaceVec

The type of the vectors that represent physical quantities.

◆ VoidRuleFunc

template<class AgentTraits , class Model >
using Utopia::AgentManager< AgentTraits, Model >::VoidRuleFunc = std::function<void(const std::shared_ptr<Agent>&)>

The type of a void rule function acting on agents of this agent manager.

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

Constructor & Destructor Documentation

◆ AgentManager() [1/2]

template<class AgentTraits , class Model >
Utopia::AgentManager< AgentTraits, Model >::AgentManager ( const Model model,
const DataIO::Config custom_cfg = {} 
)
inline

Construct an agent manager.

With the model available, the AgentManager 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 and num_agents parameters such that the way the initial state of the agents is determined can be controlled via the configuration.

Parameters
modelThe model this AgentManager belongs to
custom_cfgA custom config node to use to use for grid and agent setup. If not given, the model's configuration is used to extract the required entries.
121 {})
122 :
123 _id_counter(0),
124 _log(model.get_logger()),
126 _rng(model.get_rng()),
127 _space(model.get_space()),
128 _agents(),
131 {
132 setup_agents();
133 _log->info("AgentManager is all set up.");
134 }
void setup_agents()
Set up agents container via config or default constructor.
Definition agent_manager.hh:559
MoveFunc _move_to_func
Function that will be used for moving agents, called by move_* methods.
Definition agent_manager.hh:97
const std::shared_ptr< RNG > _rng
The model's random number generator.
Definition agent_manager.hh:88
IndexType _id_counter
Counts the number of agents created with this manager, used for new IDs.
Definition agent_manager.hh:79
AgentContainer< Agent > _agents
Storage container for agents.
Definition agent_manager.hh:94
PosFunc _prepare_pos
Function that will be used to prepare positions for adding an agent.
Definition agent_manager.hh:100
PosFunc setup_prepare_pos_func() const
Definition agent_manager.hh:679
const std::shared_ptr< spdlog::logger > _log
The logger (same as the model this manager resides in)
Definition agent_manager.hh:82
const DataIO::Config _cfg
Agent manager configuration node.
Definition agent_manager.hh:85
const std::shared_ptr< Space > _space
The physical space the agents are to reside in.
Definition agent_manager.hh:91
MoveFunc setup_move_to_func() const
Depending on periodicity, return the function to move agents in space.
Definition agent_manager.hh:647
Config setup_cfg(const Model &model, const Config &custom_cfg)
Set up the agent manager configuration member.
Definition agent_manager.hh:466
Container select_entities(const Manager &mngr, const DataIO::Config &sel_cfg)
Select entities according to parameters specified in a configuration.
Definition select.hh:213

◆ AgentManager() [2/2]

template<class AgentTraits , class Model >
Utopia::AgentManager< AgentTraits, Model >::AgentManager ( const Model model,
const AgentState  initial_state,
const DataIO::Config custom_cfg = {} 
)
inline

Construct an agent manager, using the same initial state for all agents.

Parameters
modelThe model this AgentManager belongs to
initial_stateThe initial state of all agents
custom_cfgA custom config node to use to use for grid and agent setup. If not given, the model's configuration is used to extract the required entries.
147 {})
148 :
149 _id_counter(0),
150 _log(model.get_logger()),
152 _rng(model.get_rng()),
153 _space(model.get_space()),
154 _agents(),
157 {
159 _log->info("AgentManager is all set up.");
160 }

Member Function Documentation

◆ add_agent() [1/3]

template<class AgentTraits , class Model >
const std::shared_ptr< Agent > & Utopia::AgentManager< AgentTraits, Model >::add_agent ( const AgentState state,
const SpaceVec pos 
)
inline

Create an agent and associate it with this AgentManager.

Adds an agent with the specified state to the managed container of agents. It is checked whether the given position is valid; if space is periodic, any position outside the space is mapped back into the space.

Parameters
stateThe state of the agent that is to be added
posThe position of the agent that is to be added
238 {
239 _log->trace("Creating agent with ID {:d} ...", _id_counter);
240 _agents.emplace_back(
241 std::make_shared<Agent>(_id_counter, state, _prepare_pos(pos))
242 );
243 ++_id_counter;
244
245 return _agents.back();
246 }

◆ add_agent() [2/3]

template<class AgentTraits , class Model >
const std::shared_ptr< Agent > & Utopia::AgentManager< AgentTraits, Model >::add_agent ( const Config custom_cfg = {})
inline

add_agent overload for auto constructed states and random position

Add an agent with a random position and an auto-constructed AgentState depending on the setup: Either default constructed if the flag was set in the AgentTraits or config-constructed with or without use of the RNG.

303 {}) {
305 }
const std::shared_ptr< Agent > & add_agent(const AgentState &state, const SpaceVec &pos)
Create an agent and associate it with this AgentManager.
Definition agent_manager.hh:236
SpaceVec random_pos() const
Returns a valid (uniformly) random position in space.
Definition agent_manager.hh:451

◆ add_agent() [3/3]

template<class AgentTraits , class Model >
const std::shared_ptr< Agent > & Utopia::AgentManager< AgentTraits, Model >::add_agent ( const SpaceVec pos,
const Config custom_cfg = {} 
)
inline

add_agent overload for auto-constructed agent states

Adds an agent with a specified position and an auto-constructed AgentState depending on the setup, either default-constructed if the flag was set in the AgentTraits or config-constructed with or without use of the RNG.

Parameters
posThe position of the newly created agent
custom_cfgA custom configuration. If not given, will use the configuration given at initialization.
259 {})
260 {
261 // Check if flag for default constructor was set
263 if (custom_cfg.size()) {
264 throw std::runtime_error("custom_cfg was passed but "
265 "AgentTraits specified use of default constructor!");
266 }
267
268 return add_agent(AgentState(), pos);
269 }
270 else {
271 // Determine whether to use the given custom configuration or the
272 // one passed at construction of AgentManager
274
275 if (custom_cfg.size()) {
276 cfg = custom_cfg;
277 }
278 else {
279 cfg = _cfg["agent_params"];
280 }
281
282 // Distinguish the two config-constructible states
283 if constexpr (std::is_constructible<AgentState,
284 const DataIO::Config&,
285 const std::shared_ptr<RNG>&
286 >())
287 {
288 return add_agent(AgentState(cfg, _rng), pos);
289 }
290 else {
291 // Should be config-constructible
292 return add_agent(AgentState(cfg), pos);
293 }
294 }
295
296 }
typename AgentTraits::State AgentState
The type of the agent state.
Definition agent_manager.hh:46
const DataIO::Config & cfg() const
Return the configuration used for building this AgentManager.
Definition agent_manager.hh:169
YAML::Node Config
Type of a variadic dictionary-like data structure used throughout Utopia.
Definition types.hh:71
static constexpr bool use_default_state_constructor
Whether to use the default constructor for constructing a entity state.
Definition entity.hh:57

◆ agents()

template<class AgentTraits , class Model >
const AgentContainer< Agent > & Utopia::AgentManager< AgentTraits, Model >::agents ( ) const
inline

Return const reference to the managed agents.

184 {
185 return _agents;
186 }

◆ cfg()

Return the configuration used for building this AgentManager.

169 {
170 return _cfg;
171 }

◆ displacement()

template<class AgentTraits , class Model >
SpaceVec Utopia::AgentManager< AgentTraits, Model >::displacement ( const std::shared_ptr< Agent > &  a,
const std::shared_ptr< Agent > &  b 
) const
inline

Returns the (shortest) displacement vector between two agents.

The returned vector points from agent a to agent b.

In periodic space, this will also check across boundaries to return the shortest vector.

402 {
403 return this->_space->displacement(a->position(), b->position());
404 }

◆ distance()

template<class AgentTraits , class Model >
template<class NormType = std::size_t>
double Utopia::AgentManager< AgentTraits, Model >::distance ( const std::shared_ptr< Agent > &  a,
const std::shared_ptr< Agent > &  b,
const NormType  p = 2 
) const
inline

Returns the (shortest) distance between two agents.

By default, uses the 2-norm.

413 {
414 return this->_space->distance(a->position(), b->position(), p);
415 }

◆ entities()

template<class AgentTraits , class Model >
const AgentContainer< Agent > & Utopia::AgentManager< AgentTraits, Model >::entities ( ) const
inline

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

189 {
190 return agents();
191 }
const AgentContainer< Agent > & agents() const
Return const reference to the managed agents.
Definition agent_manager.hh:184

◆ erase_agent_if()

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::erase_agent_if ( UnaryPredicate &&  condition)
inline

Remove agents if the given condition is met.

Uses the erase-remove idiom

Template Parameters
UnaryPredicatetype of the UnaryPredicate
Parameters
conditionThe condition under which the agent is to be removed. This should be a callable that takes the agent shared pointer as argument and returns bool.
332 {
333 _agents.erase(
334 std::remove_if(_agents.begin(), _agents.end(), condition),
335 _agents.cend()
336 );
337 }
@ condition
Select if a condition is fulfilled.

◆ id_counter()

template<class AgentTraits , class Model >
IndexType Utopia::AgentManager< AgentTraits, Model >::id_counter ( ) const
inline

Return the ID counter.

194 {
195 return _id_counter;
196 }

◆ initial_agent_pos()

template<class AgentTraits , class Model >
SpaceVec Utopia::AgentManager< AgentTraits, Model >::initial_agent_pos ( )
inlineprivate

Setup helper used to determine a single agent's initial position.

490 {
491 // By default, use a random initial position
492 std::string initial_pos_mode = "random";
493
494 // If given, extract the initial_position mode from the configuration
495 if (_cfg["initial_position"]) {
496 initial_pos_mode = get_as<std::string>("initial_position", _cfg);
497 }
498
499 // Return the agent position depending on the mode
500 if (initial_pos_mode == "random") {
501 return random_pos();
502 }
503 else {
504 throw std::invalid_argument("AgentManager got an invalid "
505 "configuration entry for 'initial_position': '"
506 + initial_pos_mode + "'. Valid options are: 'random'");
507 }
508 }

◆ log()

template<class AgentTraits , class Model >
const auto & Utopia::AgentManager< AgentTraits, Model >::log ( ) const
inline

– Getters ---------------------------------------------------------— Return the logger of this AgentManager

164 {
165 return _log;
166 }

◆ move_by() [1/2]

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::move_by ( Agent agent,
const SpaceVec move_vec 
) const
inline

Move an agent relative to its current position.

223 {
224 _move_to_func(agent, agent.position() + move_vec);
225 }

◆ move_by() [2/2]

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::move_by ( const std::shared_ptr< Agent > &  agent,
const SpaceVec move_vec 
) const
inline

Move an agent relative to its current position.

216 {
217 _move_to_func(*agent, agent->position() + move_vec);
218 }

◆ move_to() [1/2]

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::move_to ( Agent agent,
const SpaceVec pos 
) const
inline

Move an agent to a new position in the space.

209 {
211 }

◆ move_to() [2/2]

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::move_to ( const std::shared_ptr< Agent > &  agent,
const SpaceVec pos 
) const
inline

Move an agent to a new position in the space.

202 {
204 }

◆ neighbors_of()

template<class AgentTraits , class Model >
AgentContainer< Agent > Utopia::AgentManager< AgentTraits, Model >::neighbors_of ( const std::shared_ptr< Agent > &  agent,
const double  radius 
) const
inline

Returns a container of all agents within a certain radius.

This does not include the agent itself

Warning
Neighbors are found simply by iterating over all available agents, thus scaling linearly with the number of agents for each lookup (or: quadratically if using this on all agents).
Todo:
This should be parallelized or a lookup-grid should be used to constrain the number of possible neighbors to a smaller number
Parameters
agentThe agent whose neighborhood is to be constructed
radiusThe radius within which agents other than agent are considered to be part of the neighborhood
436 {
438 for (const auto& a : agents()) {
439 if (distance(a, agent) <= radius and a != agent) {
440 nbs.push_back(a);
441 }
442 }
443 return nbs;
444 }
double distance(const std::shared_ptr< Agent > &a, const std::shared_ptr< Agent > &b, const NormType p=2) const
Returns the (shortest) distance between two agents.
Definition agent_manager.hh:410

◆ random_pos()

template<class AgentTraits , class Model >
SpaceVec Utopia::AgentManager< AgentTraits, Model >::random_pos ( ) const
inlineprivate

Returns a valid (uniformly) random position in space.

451 {
452 // Create a space vector with random relative positions [0, 1), and
453 // calculate the absolute position by multiplying element-wise with the
454 // extent of the space
455 std::uniform_real_distribution<double> dist(0., 1.);
456 return ( this->_space->extent
457 % SpaceVec().imbue([this,&dist](){return dist(*this->_rng);}));
458 }
SpaceVecType< dim > SpaceVec
The type of the vectors that represent physical quantities.
Definition agent_manager.hh:52

◆ remove_agent()

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::remove_agent ( const std::shared_ptr< Agent > &  agent)
inline

Removes the given agent from the agent manager.

309 {
310 // Find the position in the agents container that belongs to the agent
311 const auto it = std::find(_agents.cbegin(), _agents.cend(), agent);
312
313 if (it == _agents.cend()) {
314 throw std::invalid_argument("The given agent is not handled by "
315 "this manager!");
316 };
317
318 _log->trace("Removing agent with ID {:d} ...", agent->id());
319 _agents.erase(it);
320 }

◆ rng()

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

Return a reference to the shared random number generator.

174 {
175 return _rng;
176 }

◆ select_agents() [1/2]

template<class AgentTraits , class Model >
template<SelectionMode mode, class... Args>
AgentContainer< Agent > Utopia::AgentManager< AgentTraits, Model >::select_agents ( Args &&...  args)
inline

Select agents using the Utopia::select_entities interface.

Returns a container of agents 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

374 {
375 return select_entities<mode>(*this, std::forward<Args>(args)...);
376 }

◆ select_agents() [2/2]

template<class AgentTraits , class Model >
AgentContainer< Agent > Utopia::AgentManager< AgentTraits, Model >::select_agents ( const Config sel_cfg)
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.
388 {
389 return select_entities(*this, sel_cfg);
390 }

◆ setup_agents() [1/2]

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::setup_agents ( )
inlineprivate

Set up agents container via config or default constructor.

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

Otherwise, the AgentState needs to be constructible via a const DataIO::Config& argument, which gets passed the config entry agent_params from the AgentManager's configuration.

If a constructor with the signature (const DataIO::Config&, const std::shared_ptr<RNG>&) is supported, that constructor is called instead.

Note
If the constructor for the agent state has an RNG available it is called anew for each agent; otherwise, an initial state is constructed once and used for all agents.
559 {
560 // Distinguish depending on constructor.
561 // Is the default constructor to be used?
563 static_assert(std::is_default_constructible<AgentState>(),
564 "AgentTraits were configured to use the default constructor "
565 "to create agent states, but the AgentState is not "
566 "default-constructible! Either implement such a constructor, "
567 "unset the flag in the AgentTraits, or pass an explicit "
568 "initial agent state to the AgentManager.");
569
570 _log->info("Setting up agents using default constructor ...");
571
572 // Create the initial state (same for all agents)
574 }
575
576 // Is there a constructor available that allows passing the RNG?
577 else if constexpr (std::is_constructible<AgentState,
578 const DataIO::Config&,
579 const std::shared_ptr<RNG>&
580 >())
581 {
582 _log->info("Setting up agents using config constructor (with RNG) "
583 "...");
584
585 // Extract the configuration parameter
586 if (not _cfg["agent_params"]) {
587 throw std::invalid_argument("AgentManager is missing the "
588 "configuration entry 'agent_params' to set up the agents' "
589 "initial states!");
590 }
591 const auto agent_params = _cfg["agent_params"];
592
593 if (not _cfg["initial_num_agents"]){
594 throw std::invalid_argument("AgentManager is missing the "
595 "configuration entry 'initial_num_agents' to set up the "
596 "agents!"
597 );
598 }
599 const auto initial_num_agents =
600 get_as<IndexType>("initial_num_agents", _cfg);
601
602 // Populate the container, creating the agent state anew each time
603 for (IndexType i=0; i<initial_num_agents; i++) {
606 }
607
608 // Done. Shrink it.
609 _agents.shrink_to_fit();
610 _log->info("Populated agent container with {:d} agents.",
611 _agents.size());
612 }
613
614 // As default, require a Config constructor
615 else {
616 static_assert(std::is_constructible<AgentState,
617 const DataIO::Config&>(),
618 "AgentManager::AgentState needs to be constructible using "
619 "const DataIO::Config& as only argument. Either implement "
620 "such a constructor, pass an explicit initial agent state to "
621 "the AgentManager, or set the AgentTraits such that a default "
622 "constructor is to be used.");
623
624 _log->info("Setting up agents using config constructor ...");
625
626 // Extract the configuration parameter
627 if (not _cfg["agent_params"]) {
628 throw std::invalid_argument("AgentManager is missing the "
629 "configuration entry 'agent_params' to set up the agents' "
630 "initial states!");
631 }
632
633 // Create the initial state (same for all agents)
634 return setup_agents(AgentState(_cfg["agent_params"]));
635 }
636 // This point is never reached.
637 }
SpaceVec initial_agent_pos()
Setup helper used to determine a single agent's initial position.
Definition agent_manager.hh:490
std::size_t IndexType
Type for indices, i.e. values used for container indexing, agent IDs, ...
Definition types.hh:40

◆ setup_agents() [2/2]

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::setup_agents ( const AgentState initial_state)
inlineprivate

Set up the manager's agent container with initial states.

Creates a container with agents that get an initial state and are set up with a random position.

Parameters
initial_stateThe initial state of the agents
num_agentsThe number of agents
519 {
520 // Extract parameters from the configuration
521 if (not _cfg["initial_num_agents"]) {
522 throw std::invalid_argument("AgentManager is missing the "
523 "configuration entry 'initial_num_agents' that specifies the "
524 "number of agents to set up!");
525 }
526 const auto num_agents = get_as<IndexType>("initial_num_agents", _cfg);
527
528 // Construct all the agents with incremented IDs, the initial state
529 // and a random position
530 for (IndexType i=0; i<num_agents; ++i){
532 }
533
534 // Done. Shrink it.
535 _agents.shrink_to_fit();
536 _log->info("Populated agent container with {:d} agents.",
537 _agents.size());
538 }

◆ setup_cfg()

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

Set up the agent manager configuration member.

Determines whether to use a custom configuration or the one provided by the model this AgentManager belongs to

466 {
467 Config cfg;
468
469 if (custom_cfg.size() > 0) {
470 _log->debug("Using custom config for agent manager setup ...");
471 cfg = custom_cfg;
472 }
473 else {
474 _log->debug("Using '{}' model's configuration for agent manager "
475 "setup ... ", model.get_name());
476
477 if (not model.get_cfg()["agent_manager"]) {
478 throw std::invalid_argument("Missing config entry "
479 "'agent_manager' in model configuration! Either specify "
480 "that key or pass a custom configuration node to the "
481 "AgentManager constructor.");
482 }
483 cfg = model.get_cfg()["agent_manager"];
484 }
485 return cfg;
486 }
DataIO::Config Config
Type of a variadic dictionary-like data structure used throughout Utopia.
Definition types.hh:80

◆ setup_move_to_func()

template<class AgentTraits , class Model >
MoveFunc Utopia::AgentManager< AgentTraits, Model >::setup_move_to_func ( ) const
inlineprivate

Depending on periodicity, return the function to move agents in space.

The function that is used to move an agent to a new position in space depends on whether the space is periodic or not. In the case of a periodic space the position is automatically mapped into space again across the borders. For a nonperiodic space a position outside of the borders will throw an error.

647 {
648 // Need to distinguish by periodicity of the space the agents live in
649 if (_space->periodic) {
650 // Can simply use the space's mapping function
651 return [this](Agent& agent, const SpaceVec& pos){
652 agent.set_pos(this->_space->map_into_space(pos));
653 };
654 }
655 else {
656 // For nonperiodic space, need to make sure the position is valid
657 return [this](Agent& agent, const SpaceVec& pos){
658 if (not this->_space->contains(pos)) {
659 throw OutOfSpace(pos, this->_space,
660 "Could not move agent!");
661 }
662
663 // Set the new agent position
664 agent.set_pos(pos);
665 };
666 }
667 }
Utopia::Agent< AgentTraits, Space > Agent
The type of the managed agents.
Definition agent_manager.hh:40

◆ setup_prepare_pos_func()

template<class AgentTraits , class Model >
PosFunc Utopia::AgentManager< AgentTraits, Model >::setup_prepare_pos_func ( ) const
inlineprivate

Depending on periodicity, return the function to prepare positions of agents before they are added The function that is used to prepare a position before an agent is added (if passed explicitly) depends on whether the space is periodic or not. In the case of a periodic space the position is automatically mapped into space again across the borders. For a nonperiodic space a position outside of the borders will throw an error.

679 {
680 // If periodic, map the position back into space
681 if (_space->periodic) {
682 return
683 [this](const SpaceVec& pos){
684 return this->_space->map_into_space(pos);
685 };
686 }
687 // If non-periodic, check wether the position is valid
688 else {
689 return
690 [this](const SpaceVec& pos) {
691 if (not _space->contains(pos)) {
692 throw OutOfSpace(pos, _space,
693 "Given position is out of space!");
694 }
695 return pos;
696 };
697 }
698 }

◆ space()

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

Return pointer to the space, for convenience.

179 {
180 return _space;
181 }

◆ update_agents()

template<class AgentTraits , class Model >
void Utopia::AgentManager< AgentTraits, Model >::update_agents ( )
inline

Update the agents.

This method is used in the case of synchronous update. It updates the state and position from the agent's state and position cache variables.

Note
In the case of asynchronous agent update this function will throw an error during compilation. There is no need to update these agent traits because there is no cached trait.
349 {
350 // Assert that the agents update synchronously
351 static_assert(AgentTraits::mode == Update::sync,
352 "The update_agents method only makes sense to call when agents "
353 "are set to be updated synchronously, which is not the case! "
354 "Either adapt the AgentTraits to that update mode or remove the "
355 "call to the update_agents method.");
356
357 // Go through all agents and update them
358 for (const auto& agent : _agents){
359 agent->update();
360 }
361 }
@ sync
Synchronous update.
static constexpr Update mode
Whether the entitys should be synchronously updated.
Definition entity.hh:54

Member Data Documentation

◆ _agents

Storage container for agents.

◆ _cfg

Agent manager configuration node.

◆ _id_counter

Counts the number of agents created with this manager, used for new IDs.

◆ _log

template<class AgentTraits , class Model >
const std::shared_ptr<spdlog::logger> Utopia::AgentManager< AgentTraits, Model >::_log
private

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

◆ _move_to_func

template<class AgentTraits , class Model >
MoveFunc Utopia::AgentManager< AgentTraits, Model >::_move_to_func
private

Function that will be used for moving agents, called by move_* methods.

◆ _prepare_pos

template<class AgentTraits , class Model >
PosFunc Utopia::AgentManager< AgentTraits, Model >::_prepare_pos
private

Function that will be used to prepare positions for adding an agent.

◆ _rng

template<class AgentTraits , class Model >
const std::shared_ptr<RNG> Utopia::AgentManager< AgentTraits, Model >::_rng
private

The model's random number generator.

◆ _space

template<class AgentTraits , class Model >
const std::shared_ptr<Space> Utopia::AgentManager< AgentTraits, Model >::_space
private

The physical space the agents are to reside in.

◆ dim

template<class AgentTraits , class Model >
constexpr DimType Utopia::AgentManager< AgentTraits, Model >::dim = Space::dim
staticconstexpr

The dimensionality of the space.


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