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
      ...
end

mutable struct Rescuer <: Abstract Agent
    ...
end

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},
        OpenStreetMapSpace(OSM.TEST_MAP),
        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)
    end
    return model
end

#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)
        end
    end
    return ids
end

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