Agents.jl: A performant and feature-full agent based modelling software of minimal code complexity
AAgents.jl: A performant and feature-fullagent based modelling software ofminimal code complexity
SAGE
George Datseris , Ali R. Vahdati and Timothy C. DuBois Abstract
Agent based modelling is a simulation method in which autonomous agents react to their environment, given apredefined set of rules. It is an integral method for modelling and simulating complex systems, such as socio-economicproblems. Since agent based models are not described by simple and concise mathematical equations, code thatgenerates them is typically complicated, large, and slow. Here we present Agents.jl, a Julia-based software that providesan ABM analysis platform with minimal code complexity. We compare our software with some of the most popular ABMpackages in other programming languages. We find that Agents.jl is not only the most performant, but also the leastcomplicated software, providing the same (and sometimes more) features as the competitors with less input requiredfrom the user. Agents.jl also integrates excellently with the entire Julia ecosystem, including interactive applications,differential equations, parameter optimization, and more. This removes any “extensions library” requirement fromAgents.jl, which is paramount in many other tools.
Keywords
Agent based modelling, ABM, software, framework, Julia, NetLogo, Mesa, MASON, complex systems
Introduction
Many processes in biology, ecology, sociology, andeconomics are characterized by interactions between theirconstituent parts (1; 2; 3; 4; 5; 6; 7; 8; 9). The large numberof interactions leads to numerous possible states within eachsystem. Such systems, with many interacting componentsare complex: where a single component cannot generallydetermine system behavior. Each component may have anegligible effect in isolation, but a significant effect wheninteracting with other components.To model and analyze complex systems, bottom-upapproaches such as agent-based simulations are common,and sometimes the only feasible approach. Agent-basedmodels (ABMs) consist of autonomous agents or individualsthat behave according to a set of predefined rules. The rulesspecify how agents interact with one another, as well as withtheir environment.ABMs differ from other analytical models, such asdifferential equations. Analytical models use variables thatcharacterize the whole system, they are top-down. ABMs usevariables that describe the components of a system, ratherthan the behavior of the whole system. A modeler choosesABM variables based on an understanding of the system,but not to fit some expectation of outcome. The outcomeemerges (10) from all these lower-level interactions, whichare often nonlinear and cannot be captured by aggregatingthem. By incorporating spatial and temporal heterogeneity,each agent may only interact with a local neighborhood.Such heterogeneity allows for more realistic models that canshow behaviors not captured in top-down approaches (11).Despite being widely used, efficient and reproducibleABMs are not common. Many studies use ABMs written from scratch, which increases the probability of bugs in code,and makes model validation and verification difficult.An agent-based modeling frameworks help define a gen-eral structure for ABMs. The structure makes it easier formodel developers to define models, explore parameters, andcollect data. As well as enabling the target audience tobetter understand, compare, reproduce, and modify models(Figure 1). This is especially important at present, sinceincreasingly complex models are being developed in collabo-ration, where each party focuses on a single component of themodel. A well-defined and simple framework fosters mutualunderstanding between collaborators. ABMs can be com-putationally heavy programs, and it is important to exploitavailable computing resources. An agent-based simulationframework makes it easier to use all computing resourcesthrough distributed computing. Such a framework separatesthe tasks of defining a model from running it, collecting andmerging model outputs, as well as analysis of results.We developed an agent-based simulation framework:Agents.jl (12), that fulfilled many of the mentioned tasks.Various agent-based simulation frameworks exists in differ-ent programming languages (13). Notable examples includeSwarm (14), NetLogo (15), MASON (16), Repast (17) andMesa (18) (for a comprehensive review, see (19)). Theseframeworks differ in their capabilities, scope, learning curve, Max Planck Institute for Meteorology, Germany Department of Anthropology, University of Zurich, Zurich, Switzerland Stockholm Resilience Centre, Stockholm University, Stockholm,Sweden
Corresponding author:
George DatserisEmail: [email protected]
Prepared using sagej.cls [Version: 2017/01/17 v1.20] a r X i v : . [ c s . M A ] J a n Journal Title XX(X)
ABM
Visualize
Scatter plotInteractive app
Analyze
Julia ecosystem tools:DataFrames.jl,DataVoyager.jl, etc . Collect Data
What: agent & modeldata, aggregated orfiltered aggregate
When: specified times,programmatic times
Space
GraphGridContinuous
Agentstruct(s) Agent & modelsteppingfunctions Ecosystem Integration
DifferentialEquations.jlBlackBoxOptim.jl...
Run
For 'n' steps, or acondition is metWith replicatesIn parallel...
Utilities
Add agentsMove agentsKill agentsFind neighbors...
JuliaEcosystemAgents.jlAPIUserInput
Schedule
FastestRandomBy property...User-defined
Figure 1.
Flow chart representation of the Agents.jl framework. amount of code needed to develop a model, speed of exe-cution, as well as data collection and visualization features.Our framework is written using the Julia language. Thisprogramming language choice brings advantages over otherframeworks: quick and intuitive model development, fastmodel execution, and easy integration with many analyticaltools in the Julia ecosystem (removing the need for pluginsor extensions).Here we discuss Agents.jl v4.0 with many more featuresand improvements over the initial release (20). Specifically,it supports three additional space types (continuous space,directed graphs and OpenStreetMap), better visualizationfunctions, more flexible data collection, simpler sourcecode, automatic parameter exploration, as well as interactivemodel execution & visualization. We show the advantagesof Agents.jl through a detailed comparison with threeother commonly used frameworks: Mesa, NetLogo andMASON (Table 1 and comparison section). We alsodemonstrate its integration with other Julia packages tocreate interactive applications, include differential equationsin ABMs, optimize model parameters and create novel spacetypes.
Simulations with Agents.jl
The design of Agents.jl separates a simulation into simplecomponents, following the philosophy of giving as muchfreedom to the user as possible, whilst also minimisingthe usage complexity. Each of these components integrateswith each other through the help of the Agents.jl API, asillustrated in Figure 1. In this section we will describe thedesign of Agents.jl, by going through a typical workflow ofan Agents.jl simulation, referencing all aspects of Figure 1.Our goal here is not to highlight the full list of features ofAgents.jl (for this please see the comparison section and theonline documentation), but instead to highlight the simplicityof using Agents.jl.We will use the Schelling segregation model as an example(a fully detailed version of this model is available in ourdocumentation, the example herein is provided solely to outline the basic principles of Agents.jl). Below we will beincluding code snippets that implement the Schelling modelin Agents.jl. These code snippets are typically stored in asingle script, but could also be inputted interactively intoa Julia console or separated into multiple files. All codesnippets are based on standard, generic Julia functions, asAgents.jl can be used like any other Julia package. This is incontrast to requiring you to code in a specific environment(NetLogo), defaulting to using a dedicated “server” (Mesa)or distributing model files in a binary format (MASON). Thismakes models from Agents.jl easier to share and reproduce,but also easier to integrate with the Julia ecosystem andtherefore easier to learn.
Model creation
In Agents.jl, an agent based model is represented by a bundlecalled
AgentBasedModel , that contains all currently aliveagents, the space they reside in, and other model-levelparameters. To create such an
AgentBasedModel , theuser must provide:1. the type of agents the model will contain (but not theagents themselves)2. the properties of the space they can occupy3. the order the agents will activate (optional)4. model-level parameters (optional)The agent type is defined via a Julia mutable struct , whichin principle is a container of arbitrary data (in the case of amixed-agent models, one struct for each agent type needsto be provided). Such a struct must always have a field id and pos (for position). For our Schelling model, the structlooks like: mutable struct Schelling <: AbstractAgentid::Intpos::Dims{ }mood::Boolgroup::Int end Notice that the fields of such a struct (besides the mandatoryfields id, pos ) can be any possible data structuresupported by the Julia language. Their value can be alteredat any point during the simulation. Rather than writingthis out manually, Agents.jl also provides an @agent macro that simplifies this process. Next, the user creates aspace structure which can be populated by agents. Agents.jlprovides three spaces: grid, graph, and continuous. A gridspace (for example) is initialized by dims = ( , )space = GridSpace (dims; periodic = false ) All spaces have their appropriate set of configuration options.The final setup step is to choose model-level parametersand agent activation order. In Agents.jl, agents activatesequentially, according to a dynamically determined order(arbitrary user-defined function which can include arbitraryevents at arbitrary times). In this example the activation orderdoes not matter and we use the default (random) activation.After creating a model-parameter container, we instantiatethe
AgentBasedModel with
Prepared using sagej.cls atseris, Vahdati and DuBois properties = Dict(:min_to_be_happy => )schelling = ABM (Schelling, space;properties = properties) (where
ABM is an alias of
AgentBasedModel ). In the Juliaconsole, the output of the above command would be:
AgentBasedModel with 0 agents of typeSchellingspace: GridSpace with size (10, 10),metric=chebyshev and periodic=falsescheduler: fastestproperties: Dict(:min_to_be_happy => 3)
One can populate the model immediately now, by takingadvantage of the API of Agents.jl, and functions like add_agent! or fill_space! , but we skip this step herefor conciseness.Before actually running a simulation, the user must alsodefine the dynamics of the model. This is done by providingtwo functions (which of course themselves can be composedby simpler parts). First, an agent-stepping function whichdecides what happens when each agent is activated, andsecond, a model-step function which is called either before orafter every scheduled agent has performed their operations,and acts on the model as a whole (all agents are stillaccessible by the model if needed). Both functions areoptional, depending on the simulation’s requirements. Theuser creates these two functions by taking advantage of theAPI of Agents.jl. For example, the Schelling model has therules that1. Agents belong to one of two groups (0 or 1).2. If an agent is in a location with at least three neighborsof the same group, then it is happy.3. If an agent is unhappy, it keeps moving to newlocations until it is happy.This can be implemented with the function shown inListing 1. This function uses several functions from the APIof Agents.jl. Specifically:• model.x returns the model-level property called x ( agent.x behaves in the same manner).• nearby_positions(agent, model) returnsids of all positions near agent .• nearby_agents(agent, model) returns a listof agents nearby.• move_agent_single!(agent, model) moves the agent to a random, but empty location (ifpossible).In a similar manner, one defines a model step function. Afull list of functions available from the API is described inour documentation. Simulation run, data collection
Once the aforementioned structures and functions have beendefined, the model can be evolved for one step by simplydoing step! (model, agent_step!) which internally takes care of scheduling agents, activatingthem one by one, and applying the given rules to them. Thefull form of step! is step! (model, agent_step!, model_step!, n) where n is either an integer (step for n steps), or anarbitrary Julia function n(model, s) with s the currentstep number. In this case, evolution goes on until n returns true . Model evolution is in a sense interactive (since Juliais an interactive language, and all data structures involvedin Agents.jl are mutable). Thus, after stepping the model,the contained agents and/or model parameters have changedvalues according to model rules.Data collection in Agents.jl is also as simple and as generalas constructing a model. This is accomplished via a twostep process. First, the user decides which data should becollected, which can be any combination of:1. Agent properties2. Aggregated agent properties3. Aggregated agent properties, conditional on a user-defined filter4. Model propertiesThis is done by providing vectors of appropriate entries fordata collection. For example, if the user wanted to collectdata for the property mood and position of the agents, theywould define adata = [:mood, :pos] It is also possible to collect arbitrary data from an agent byproviding a function, e.g. f (a::Schelling) = a.pos[ ]-a.pos[ ]adata = [:mood, f] This process works identically for model parameters.As noted above, it is also possible to aggregate agentdata during data collection. For example, while get-ting the ‘mood‘ of each individual agent as data issometimes desired, other scenarios may only requirean aggregated result. We can achieve this by modify-ing the adata vector above, so that its entries are (:value, aggregation_function) instead of just :value . For example, using
Statistics ` mean ` right (a::Schelling) = a.pos[ ] > adata = [(:mood, sum),(f, mean),(:mood, sum, right)] would sum the mood property (and thus in our examplecount how many agents are happy), provide the average valueof the f function, and finally the number of agents that arehappy, provided they are in the right side of the space.Once the user has defined adata (and mdata for modelparameters), they can simply call Prepared using sagej.cls
Journal Title XX(X) function agent_step! (agent, model)agent.mood == true && return nearby_positions (agent, model)count_neighbors_same_group = for neighbor in nearby_agents (agent, model) if agent.group == neighbor.groupcount_neighbors_same_group += if count_neighbors_same_group >= minhappyagent.mood = trueelsemove_agent_single! (agent, model) endend Listing 1: Agent stepping function for the Schelling model. run! (model, agent_step!, model_step!, n;adata = adata)
The run! function evolves the model in the same manner as step! , but collects data in addition. It provides the results inthe form of a
DataFrame : the most common Julia tabulardata format. An example output of the executable version ofthe Schelling model (from our documentation) is | step | sum_mood | maximum_x || Int64 | Int64 | Int64 ||-------|----------|-----------|| 0 | 0 | 20 || 1 | 219 | 20 || 2 | 278 | 20 || 3 | 299 | 20 || 4 | 312 | 20 || 5 | 313 | 20 |
Visualization
Visualization follows the same principles as data collection.The user provides a few simple functions which decide howan agent should be represented. These user-defined functionsare then given to the main plotting function abm_plot thatis provided by InteractiveDynamics.jl (a package providingvisualization and interactive applications for the packages ofthe JuliaDynamics organization).Using the current Schelling example, we can define twofunctions for the color and shape of the agents as follows using
InteractiveDynamics, GLMakie groupcolor (a) =ifelse(a.group == , :blue, :orange) groupmarker (a) =ifelse(a.group == , :circle, :rect)fig, _ abm_plot (model; ac = groupcolor, Figure 2.
An example plot of an implementation of theSchelling segregation model in Agents.jl. am = groupmarker, as = )fig the keywords ac, am, as decide the agent color, markertype and size respectively. The output of the above codeblock (for the documentation version of the Schelling model)is an image like Figure 2. Interactive applications
By adding only a couple of lines of code to the existingsimple interface for data collection and plotting within
Prepared using sagej.cls atseris, Vahdati and DuBois Figure 3.
An interactive application of an agent based model. Controls on the bottom left are created automatically and tune thesimulation speed. Red vertical lines in the timeseries of the collected data denote when the “reset” button was pressed. Here it waspressed after the slider of the parameter “minimum to be happy” was changed from 3 to 6, and then to 8.
Agents.jl, we can immediately explore an ABM in aninteractive application that looks like Figure 3.Provided that the user has already created an ABM and hasdefined the necessary stepping functions, launching such anapplication is trivial. The data-collection flags adata and mdata are re-used to make the timeseries plot in the rightside of the window. The arguments ac, am, as of thefunction abm_plot are re-used as-is. Lastly, the user canchoose some model-level parameters to vary interactivelyduring the simulation, by providing a dictionary that mapsparameter names to value ranges. All in all, the only extralines of code the user has to write can be expressed as (wecontinue with the Schelling example used throughout thearticle) using
InteractiveDynamics, GLMakieparange = Dict(:min_to_be_happy => : )alabels = ["happy", "avg. x"]fig, adf, mdf = abm_data_exploration (model, agent_step!, dummystep, parange;ac=groupcolor, am=groupmarker, as= ,adata, alabels) The only new thing the user had to define was the parange and alabels variables, where the latter only affects theshown labels of the timeseries. This is in striking contrastto the user-defined input necessary by competing ABMsoftware, e.g. Mesa (Python) where several pages of code arenecessary to reach the same level of interactive application.
Framework Comparison
ABMs have had a long history, with many tools whichenabled their construction along the way. In Table 1 we compare Agents.jl with three current and popularframeworks: Mesa, Netlogo and MASON, to assesswhere Agents.jl excels and also may need some futureimprovement. This assessment is quantitative where it canbe, although many aspects of the comparison are qualitativeby nature. We categorise our results first by having eitherPoor/None (red color), Basic (yellow color), or Goodfunctionality (green color). If there is a clear category winner,this is labelled as Current Best (blue color).Our major goal in this paper is to highlight that Agents.jl isa framework that is simple and easy-to-use (something hardto showcase in a comparison table, but already illustratedin the “Simulations with Agents.jl” section). Regardless,even though Agents.jl is a new-comer ABM software(development started Dec. 2018 (20)), it becomes clearfrom Table 1 that we already match the main functionalityof decades-old competitors (all of which are under activedevelopment), most of the time exceeding it, with only afew aspects being available in the competitors and not inAgents.lj (e.g. GIS integration).Worth noting is our design of space types, which allowsfundamentally new spaces to be created with relatively loweffort. Specifically, a new space can be created by defininga new Julia struct and extending only 5 methods (i.e.defining 5 functions). The resulting space then integrateswith all of the Agents.jl API as any other space would. Forexample, the entire implementation of our graph space isonly 75 lines of code. We showcase the new OpenStreetMapspace in the Ecosystem interaction section below as a morecomplex example.There are two API categories listed in the table that shownew features that only Agents.jl provides.• Agent sampling: the ability to select randomisedsubsets of the model population based on certainproperties. Useful in biological applications.
Prepared using sagej.cls
Journal Title XX(X)
Table 1.
A comparison of four ABM frameworks: ease of use, available functionality and performance. Colours representimplementation quality. Red: poor/none, Yellow: basic, Green: good, Blue: clear class leader.
Agents.jl 4.0 Mesa 0.8.7 Netlogo 6.1.1 Mason 20.0Core
Core design decisions and aspects that cannot be changed or implemented by users
ContinuousSpace
Yes Yes Yes Yes
OpenStreetMapSpace
Yes No No No
Graph Space
Yes, and mutable Only undirectional Link Agents(not a Space) Networks (not aSpace)
Grid Space
Yes Yes (+Hexagonal) Yes Yes (+Hexagonal,Triangular)
Dimensionality
Any 2D 2D & 3D (separateapplications) 2D & 3D(complicated installfor 3D)
Licensepermissiveness
MIT Apache v2.0 GPL v2 Academic FreeLicense
Mixed-agentmodels
Type Unions Yes Breed Separate Class
Simulationtermination
After ‘n’ steps oruser-provided booleancondition of modelstate Explicitly written userloop Manually by pressinga button on theinterface, stopcommand in code When Schedule isempty, or userprovided customfinish function
Parameter types
Anything Anything Float64, ListsHashtables andAssoc. Arrays in theTable extension Anything
Ease ofInstallation
One-click for Julia,one command forpackage One-click for Python,one command forpackage One-click JRE installRun jar file One-click JRE, installlibraries, complexJava3D installRun jar file
Modeling andAnalysis in thesame language
Yes, Julia v1.5+ Yes, Python v3+ No Yes, Java butdesigned to workwithin the console orGUI of the applet
Languageecosystemintegration
By Design. Examples:black boxoptimization,differential equations Any of Python’sanalytical tools can beused Complex. Must createplugins or use ControlAPI Warned against (e.g.Random), providescustom types in placeof Java primitives
Documentationquality
Short, with tutorials,15+ executableexamples, APIlistings & integrationexamples. Short, has a tutorialbut no hosted runexamples online Extensive, split overwebsite and GitHubwiki. Difficult tosearch. Extensive, over 350pages in pdf and adeveloper dump ofclass properties. Hardto navigate.
Data collection
Any chosen parameter/ property or functionmapped over them.Aggregating andfiltered aggregatefunctions Any chosen parameter/ property.Aggregatingfunctions. Noconditional options boolean, number,string and lists ofthese types. Inspectors track &chart any parameter /property. Entiremodel saved to diskvia checkpointing, nocustom export
Modelcomplexity (19) Simple Moderate Simple High
Prepared using sagej.cls atseris, Vahdati and DuBois Agents.jl Mesa Netlogo MasonAPI, Utilities
How users interface with the framework, overview of convenience functions
Finding nearestneighbors
Same API for allspaces, custom ranges Covers all spaces Covers graphs,cardinal directionsand city blocks ongrids and continuousspace Cardinal, city block,Von Neumann andradial types. No 3Dsearch in continuousspace
Adding agents tospace specified position,random, randomempty, fill Specified position,random empty specified position specified position
Agent creationfrom values
Yes No Yes No
Moving agents
Unified API for allspace types. Unified API for allspace types. specify position, onlyTurtle Agents move specify position,move with mouse inGUI
Killing agents
Individual, all,specified by function. Individual, all. individual, all,specified by function individual, all
Random numberdistributions
Any Any Normal, Poisson,Exponential, Gamma Uniform, GaussianCan use COLT librarybut not recommended
Agent sampleand replacement
Yes No No No
GIS data
No No GIS Extension GeoMason Extension
Parameterscanning paramscan batch runner Behaviour Space ParameterSweep
New space typesAPI
Yes No No No
Advanced APIfor continuousspace
Yes No No No
Data collectionlow-level API
Yes No Yes Yes, but onlyexportable viacheck-pointing
Scheduling
As added, byproperty, by type,filtered, random,custom function As added, random,staged custom function custom function
Visualizationprimitives forprovided spaces
Yes Yes Yes Yes
Complexity ofvisualization
Single function with 3helper functions (5LOC) Complex API, manyLOC Simple, functionbased. Extend agentproperties and plot Complex API, manyLOC
GUI forsimulation setup
No User implemented Yes User implementedNumeric Performance features, benchmarks where possible and lines of code (LOC) for implementations
Maximummemory capacity
Hardware limits Hardware limits 1 GBManually expandedby increasing JVMheap 1 GBManually expandedby increasing JVMheap
Flocking(continuous)implementation
Wolf-Sheep-Grass (grid)implementation
Forest Fire (grid)implementation
Schelling (grid)implementation
Prepared using sagej.cls
Journal Title XX(X) • Advanced continuous space API: due to the timeof publication, COVID-19 social distancing modelshave been very important. Agents.jl provides such anexample in the documentation, with methods suchas interacting_pairs (sets of nearby agentswith many possible methods of finding these sets)and elastic_collision! to resolve interactionsbetween agents on crossing paths who may not wantto closely interact.In addition, many categories we have scored Agents.jl inblue (class leader). One example reason for this can be seenin the Battle Royale example in our documentation. Here weshow an N-dimensional space, with a 2D spatial grid andthe higher order dimensions representing agent categories.While agent categories can be represented as standardagent properties, using additional “spatial” dimensions forthem instead allows finding nearest neighbors along thesedimensions, which would become cumbersome to do via theproperty approach.Analysing performance between the frameworks wasdifficult, since each system implements example modelsin their own unique manner. This highlights the lack ofstandardised bench-marking models, perhaps stemming fromthe lack of communication between the ABM communities.Since the Wolf-Sheep-Grass model requires frameworksto utilise most of the common machinery (multiple agenttypes, adding, deleting and moving agents, etc.), wewould appreciate if the MASON community (and ABMcommunities as a whole) could provide an implementationof this model for future comparisons. From the analysis wepresent here, Agents.jl is a clear winner in performance, mostof the time by an order of magnitude. Since typical ABMsimulations can cover hours of run time, even a 2x speed upis a large gain.
Ecosystem interaction examples
In this section we want to showcase how easily Agents.jlinteracts with the rest of the Julia ecosystem. This is possiblefor two reasons: first, the minimal design of Agents.jl, as wellas the support it provides for low-level interfaces. Second,the design of the core of the Julia language itself, whichallows straightforward inter-package communication. Noticethat the examples we showcase here have fully detaileddocumentation online, explaining precisely how they work.Our goal here is to highlight how easy it is for Agents.jlto “communicate” with other Julia packages, removing anyneed for a plugin or extension ecosystem and thus makingthe user experience smoother.
ODEs with DifferentialEquations.jl
Coupling a set of differential equations (DE) to an ABM hashistorically led to a complex set of validation and sensitivitytests (21), which stem from discretizing a DE in somemanner (predominantly via the forward Euler method) toconform with the step function of the ABM framework. Thetests outlined in Martin et al. (21) concerning sensitivitycan be handled automatically by integrating Agents.jl withDifferentialEquations.jl (22). To demonstrate this, our documentation (under the“Ecosystem Integration” section) describes a small fisherymodel where fish stocks are managed on a yearly basis. Anumber of fishers, with differing competence at catching fish,work in a common catchment. This is managed by someagency that makes sure the catchment is not over-fished. Thefish population in the catchment is modelled via a logisticfunction d s d t = s (cid:16) − s (cid:17) − h, (1)where s is the fish stock with some maximum carry capacity( here) and a harvest rate h .The status-quo method to implement such a hybriddynamical system-agent based model is to discretize thisequation to s t +1 = s t + s t (1 − s t / − h (2)with a timestep of normalised unit initially. To validatethis result, it would be important to undertake a step sizeanalysis as a bare minimum, and to be thorough, use ascheme such as the one outlined in Martin et al. (21).Thankfully, the issues caused by discretization do not needto exist within an Agents.jl model, as we can couple ourmodel with a continuous implementation of the DE fromDifferentialEquations.jl. Figure 4.
Comparative result of a continuous DE solution(
Tsit5 ) and a non-optimal Eulerian discretisation. This errorcomes about due to oversimplification of a continuous functioninto a discrete solution, which occurs frequently in publishedABM examples.
We can see in Figure 4 that a forward Euler method withno step size optimisation performed (or further sensitivitychecks as discussed above) will yield an average discrepancyof 30 fish. Integration with DifferentialEquations.jl hasprovided us with a stable, valid solution—with an addedbonus of efficiency. Since the chosen solver (in this case
Tsit5 ) required less allocations and computations to obtainthe result, we achieved a 6x speedup for this model.
Agents on Maps
With our new space type API, building ABMs on novelspaces is no-longer a months-long development process. An
Prepared using sagej.cls atseris, Vahdati and DuBois Figure 5.
Agents following planned routes on a map,interacting with passers-by. Black markers: agents, greenmarkers: zombies!
OpenStreetMapSpace has been introduced in Agents.jl4.0, which is a continuous space that constrains agents ontoroads and streets of any provided real-world map obtainedfrom Open Street Map. We leverage the OpenStretMapX.jlpackage and build methods specific to agent navigation andneighbor searching, which culminates in incredibly simple,yet powerful map based models.Our Zombie Outbreak example (see documentationonline) explains how a simple agent constructor: @agent Zombie OSMAgent begin infected::Bool end coupled with 8 lines of movement dynamics can depict a cityin chaos after a zombie infection (Figure 5).
Parameter optimization
Describing the logic of an ABM is usually not complicated,even when ABMs have a large number of heterogeneousagents (23). However, exploring the effect of modelparameters has the possibility to become infeasible. ABMsare often computationally more expensive than analyticalmodels, and brute force algorithms do not suit parameterexploration since the size of the parameter space of asimple model with 10 parameters and 10 possible valuesper parameter is . Even if each simulation takes onlyone second, exploring the entire parameter space wouldtake more than 300 years. Additionally, each parametersetting needs to be run multiple times and an average taken,since ABMs are stochastic. Machine learning algorithmshandle the large parameter space by differentiation. ABMs,however, are not (universally) differentiable.We must resort to optimization strategies for non-differentiable functions. One such strategy is evolutionaryalgorithms (24). They are inspired from how livingorganisms evolve in a constantly changing environment andwith large parameter spaces, similar to how ABMs oftenneed to explore large parameter spaces. The Agents.jl documentation demonstrates how anepidemiological model can be optimized with evolutionaryalgorithms using the BlackBoxOptim.jl package. Weoptimize a number of parameters of a SIR * model explicitlyaccounting for multiple cities/regions. Specifically we tunetransmission rates, death rate, migration rate, infection anddetection times, and reinfection probability to minimize thenumber of infections. We note that to optimize the ABM,the simulation code does not need to be changed. All weneed is a cost function that takes model parameters as input,runs the model one or more times, and returns one ormore numbers as the objectives that need to be minimized(here, the number of infected individuals and the negativeof the number of individuals). With our initial values,94% of the population gets the infection. The optimizationfinds that reducing the transmission rate is enough forreducing death rate and infections to 0.3% and 0.04%of the population, respectively. That is despite increasingthe reinfection probability, migration rate, and death rate.Accessibility of optimization tools in the Julia ecosystem andtheir easy integration with Agents.jl makes ABM analysismuch easier. Conclusions and Future Work
We have presented an overview of the capabilitiesof Agents.jl, showing the simplicity and power ofthis framework compared to long-established frameworks(NetLogo, Meson), as well as contemporaries (Mesa). Fromour perspective, the biggest take-away of this paper is thatAgents.jl is a framework that is simple to use, requiringsmall amount of written code from the user and overall easyto learn. Despite this, our comparison shows that Agents.jlalways exceeds other frameworks in performance, and oftenalso in capability. An added bonus is how simple it is fora user to incorporate other parts of the already large, andconstantly evolving, Julia ecosystem into their model. Withthis, we hope to motivate more users to try out Agents.jl,which will enable them to extend the frontier of possibilitiesin the world of ABMs, due to faster prototyping and fastercode execution.Several possible future directions already exist forAgents.jl, some planned by the developers while somerequested by users. A useful new feature would be crowddynamics and obstacle avoidance, as well as a new typeof grid space based on hexagonal grids, rather than theexisting rectangular. Adding even more examples (currently18 online and constantly increasing), is always useful, andthe near future focus will be highlighting more 3D models.Integrations into the greater Julia ecosystem are useful tohighlight as well, with current ideas targeting automatic errorpropagation and Bayesian inference for decision makingamong others. Given that Agents.jl is an open sourceproject, we welcome new users to add to the wish-listof functionalities by opening a new issue in our GitHubrepository, or even better to contribute new features via a pullrequest. ∗ SIR stands for Susceptible-Infected-Recovered and is a simple model forinfection dynamics commonly used in ABMs.
Prepared using sagej.cls Journal Title XX(X)
Acknowledgements
We acknowledge all users of Agents.jl that contributed in the formof reporting bugs, suggesting new features, and even contributingcode directly via pull requests.
Funding
T.C.D. acknowledges funding from the EU project LimnoScenES(2017–2018 Belmont Forum and BiodivERsA joint call under theBiodivScen ERA-Net COFUND with funding from the SwedishResearch Council FORMAS).
Author Contribution Statement
G.D. provided direction to the team, refactored and optimisedmuch of the current codebase, oversaw critical design decisionsregarding the representation of spaces and plotting, and served aslead developer from v2.0 until v4.0. A.R.D. is the original author ofAgents.jl and has been continuously active in development since.T.C.D. is the current lead developer of Agents.jl, has been activein development since version v2.0, implementing and optimisinga large portion of the framework and contributing several newfeatures and examples.A.R.D. drafted the introduction section, G.D. drafted the usagesection and the outline of the comparison table. Mesa comparisonswere compiled by A.R.D., all other frameworks by T.C.D.Benchmarks were run and listed by T.C.D. A.R.D. and T.C.D. wrotethe Ecosystem Integration. All authors contributed to draft revisionsand editing.
References [1] V. Grimm and S. F. Railsback, “Agent-Based Models inEcology: Patterns and Alternative Theories of AdaptiveBehaviour,” in
Agent-Based Computational Modelling (F. C.Billari, T. Fent, A. Prskawetz, and J. Scheffran, eds.), pp. 139–152, Heidelberg: Physica-Verlag, 2006.[2] I. Politopoulos, “Review and analysis of agent-based modelsin biology,”
University of Liverpool.—2007 , no. September,pp. 1–14, 2007.[3] J. D. Farmer and D. Foley, “The economy needs agent-basedmodelling,”
Nature , vol. 460, pp. 685–686, Aug. 2009.[4] S. Heckbert, T. Baynes, and A. Reeson, “Agent-basedmodeling in ecological economics: Agent-based modeling inecological economics,”
Annals of the New York Academy ofSciences , vol. 1185, pp. 39–53, Jan. 2010.[5] A. J. McLane, C. Semeniuk, G. J. McDermid, and D. J.Marceau, “The role of agent-based models in wildlife ecologyand management,”
Ecological Modelling , vol. 222, pp. 1544–1556, Apr. 2011.[6] T. Lekvam, B. Gamb¨ack, and L. Bungum, “Agent-basedmodeling of language evolution,” in
Proceedings of the 5thWorkshop on Cognitive Aspects of Computational LanguageLearning (CogACLL) , (Gothenburg, Sweden), pp. 49–54,Association for Computational Linguistics, 2014.[7] J. Schulze, B. M¨uller, J. Groeneveld, and V. Grimm,“Agent-Based Modelling of Social-Ecological Systems:Achievements, Challenges, and a Way Forward,”
Journal ofArtificial Societies and Social Simulation , vol. 20, no. 2, p. 8,2017.[8] S¸ . Bora and S. Emek, “Agent-Based Modeling andSimulation of Biological Systems,” in
Modeling and Computer Simulation (D. Cvetkovi´c, ed.), IntechOpen, Apr.2019.[9] M. Lippe, M. Bithell, N. Gotts, D. Natalini, P. Barbrook-Johnson, C. Giupponi, M. Hallier, G. J. Hofstede, C. Le Page,R. B. Matthews, M. Schl¨uter, P. Smith, A. Teglio, andK. Thellmann, “Using agent-based modelling to simulatesocial-ecological systems across scales,”
GeoInformatica ,vol. 23, pp. 269–298, Apr. 2019.[10] J. O. Dada and P. Mendes, “Multi-scale modelling andsimulation in systems biology,”
Integrative Biology , vol. 3,no. 2, p. 86, 2011.[11] S. F. Railsback,
Agent-Based and Individual-Based Modeling:A Practical Introduction . Princeton, NJ: Princeton UniversityPress, 2nd edition ed., 2019.[12] G. Datseris, A. Vahdati, and T. DuBois,“Agents.jl online repository and documentation:https://github.com/juliadynamics/agents.jl.”[13] S. F. Railsback, S. L. Lytinen, and S. K. Jackson, “Agent-based Simulation Platforms: Review and DevelopmentRecommendations,”
SIMULATION , vol. 82, pp. 609–623,Sept. 2006.[14] H. Iba,
Agent-Based Modeling and Simulation with Swarm .Chapman and Hall/CRC, zeroth ed., June 2013.[15] L. Wilensky, “Netlogo.” Center for Connected Learning andComputer-Based Modeling, Northwestern University, 1999.[16] S. Luke, C. Cioffi-Revilla, L. Panait, K. Sullivan, andG. Balan, “MASON: A Multiagent Simulation Environment,”
SIMULATION , vol. 81, pp. 517–527, July 2005.[17] M. J. North, N. T. Collier, J. Ozik, E. R. Tatara, C. M. Macal,M. Bragen, and P. Sydelko, “Complex adaptive systemsmodeling with Repast Simphony,”
Complex Adaptive SystemsModeling , vol. 1, p. 3, Dec. 2013.[18] D. Masad and J. Kazil, “Mesa: An Agent-Based ModelingFramework,” in
Python in Science Conference , (Austin,Texas), pp. 51–58, 2015.[19] S. Abar, G. K. Theodoropoulos, P. Lemarinier, and G. M.O’Hare, “Agent Based Modelling and Simulation tools:A review of the state-of-art software,”
Computer ScienceReview , vol. 24, pp. 13–33, May 2017.[20] A. Vahdati, “Agents.jl: Agent-based modeling framework inJulia,”
Journal of Open Source Software , vol. 4, p. 1611, Oct.2019.[21] R. Martin and M. Schl¨uter, “Combining system dynamicsand agent-based modeling to analyze social-ecologicalinteractions—an example from modeling restoration of ashallow lake,”
Frontiers in Environmental Science , vol. 3, Oct.2015.[22] C. Rackauckas and Q. Nie, “Differentialequations. jl–aperformant and feature-rich ecosystem for solving differentialequations in julia,”
Journal of Open Research Software , vol. 5,no. 1, 2017.[23] T. Terano, H. Deguchi, and K. Takadama, eds.,
Meeting theChallenge of Social Problems via Agent-Based Simulation .Springer Japan, 2003.[24] P. A. Vikhar, “Evolutionary algorithms: A critical review andits future prospects,” in , pp. 261–265, IEEE, 2016.