AnyLogic gives you the ability to dynamically create and destroy agents living in a population. To enable dynamic creation or destruction, in the agent properties, the Population of agents option should be selected. The Initial number of agents field in the population properties is used to specify the initial number of agents that will be created when the container object is created and can be 0 if you do not want to have any agents of this type at that time.
Assume you have declared a population people of agents of type Person within the Main agent. Then AnyLogic automatically generates two functions (at the Main level) for adding and removing agents to that population during the model execution:
- Person add_people() — this function creates a new agent of type Person and adds it into the population (and returns it so you can do additional setup)
- void remove_people( Person personToRemove ) — this function removes the given agent from the population and destroys it.
To create or destroy an agent from another agent of the same population or from itself, access the Main agent first. For example, if a person gives birth to another person, you should write within the “parent” person:
main.add_people();
Another frequently used pattern: an object wishes to destroy itself:
main.remove_people( this );
You may take a look at the given simple model. It demonstrates how to create agents dynamically (in this model they are generated using an event).
Demo model: Event Generating New AgentsYou can dynamically change the population of an existing agent during the model simulation using the goToPopulation() function of the agent. The new population must contain agents of the same (or compatible) agent type.
goToPopulation(AgentList newPopulation) — Moves the agent to a new population. Agent will leave its current environment (if it has belonged to any) and join environment of the new population (if it lives in an environment).
newPopulation — the new population to move to. If newPopulation is null then the agent will go into the default population of the top-level agent of the model and will leave its environment (if it has lived in any).
-
How can we improve this article?
-