Schedule agents by type

Hi, I am wondering whether there is a way to get a list of agents by their type?

For example if there are two types of agents

mutable struct Casualty <: AbstractAgent

mutable struct Rescuer <: Abstract Agent

I am able to get keyset of all agents in a model provided Schedulers.fastest is used through the following syntax, ids = model.scheduler(model). However if I were to use Schedulers.by_type instead, I am wondering how would I go about getting a keyset pertaining to one type of agent (note for the latter model.scheduler(model) ends up with a Method error.

function main2()
    model = AgentBasedModel(
        Union{Casualty, Rescuer},
        scheduler = Schedulers.by_type,

    for id = 1:5
        pos = random_position(model)
        init_pos = (775, 775, 0.0)
        casualty = Casualty(id, pos, rand([1,2,3]), true, false,false, false, false, false, false)
        rescuer = rescuer = Rescuer(id + 5, init_pos, "inactive", (0, 0, 0.) ,Array{Casualty}([]))
        add_agent_pos!(casualty, model)
        add_agent_pos!(rescuer, model)
    return model

#get a keyset of a specific agent ?

ids = model.scheduler(model)
ERROR: MethodError: no method matching by_type(::AgentBasedModel{Agents.OSM.OpenStreetMapSpace, Union{Casualty, Rescuer}, typeof(Agents.Schedulers.by_type), Nothing, Random.TaskLocalRNG})

Schedulers.by_type works differently than how you use it here. See here. It’s for activating agents in certain order determined by their type.

To do what you want to do, you need to construct an iterable (e.g. a vector) of all the agent ids for agents of a given type. Something like

function by_type(T, model)
    ids = Int[]
    for id in allids(model)
        if model[id] isa T 
            push!(ids, id)
    return ids

should work, I suppose? I don’t have a mixed agent model at hand right now, so I can’t test it. Worked just fine for a model with a single agent type.

1 Like