Agent Spawning

Last updated on 29th April 2024

This section deals with the spawning of individual agents from within other agents during the model run. For creating groups of agents with specific connections between them read the section on topologies.

During the execution of an action, an agent can spawn a new agent. When spawning an new agent, a SpawnedVertex is returned, which is a reference that can be used for setting up links or sending messages to the new agent.

Spawning a new agent

    SpawnedVertex spawnedAgent = agent.spawn(NewAgent.class);

This method can only be called from within an action see Actions and Sequences. This example shows what this looks like from inside an action. The rest of the examples will not include the action, and assume all code is running from inside an action.

Spawning a new agent inside an action

class Cell extends Agent<GlobalState> {
    public Action<Cell> spawnNewAgent() {
      return Action.create(
        Cell.class,
        agent -> {
          SpawnedVertex spawnedAgent = agent.spawn(NewAgent.class));
        }
      );
    }
  }

Remember to register spawned agents

When spawning agents be careful to register them. This is especially important if you are spawning agent types that were not part of the topology at setup. If you fail to do so, an exception will be thrown at the point the agent is spawned.

When spawning agents, the dataInjector Consumer can be used to set up the agent with initial values. The dataInjector can also be used to create links from the agent.

Spawning a new agent with a data injector

    //Create an agent with a link back to the agent that created it.  
    SpawnedVertex spawnedAgent = agent.spawn(NewAgent.class, agent -> agent.addLink(agent.getID(), MyLink.class));

When an agent spawns a new agent, it can also create a link to this spawned agent.

Linking to a newly spawned agent

    SpawnedVertex spawnedAgent = agent.spawn(NewAgent.class);
    agent.addLink(spawnedAgent, MyLink.class);

This link can be treated like regular links, except that you will not be able to get Link#getTo() for this link until the next timestep.

You will however be able to do treat it like your other links if you want to send a message along this link.

Sending a message along a link to a spawned agent

    SpawnedVertex spawnedAgent = agent.spawn(NewAgent.class);
    agent.addLink(spawnedAgent, MyLink.class);
    agent.getLinks(MyLink.class).send(MyMessage.class);

This will create a new agent create a link to the new agent, and send MyMessage to the agent to be processed in the next timestep.

Messages can also be sent directly to a spawned agent.

Sending a message to a spawned agent

    SpawnedVertex spawnedAgent = agent.spawn(NewAgent.class);
    agent.send(MyMessage.class).to(spawnedAgent);